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.

260929 lines
7.7MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-7 by Raw Material Software ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the
  7. GNU General Public License, as published by the Free Software Foundation;
  8. either version 2 of the License, or (at your option) any later version.
  9. JUCE is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with JUCE; if not, visit www.gnu.org/licenses or write to the
  15. Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  16. Boston, MA 02111-1307 USA
  17. ------------------------------------------------------------------------------
  18. If you'd like to release a closed-source product which uses JUCE, commercial
  19. licenses are also available: visit www.rawmaterialsoftware.com/juce for
  20. more information.
  21. ==============================================================================
  22. */
  23. /*
  24. This monolithic file contains the entire Juce source tree!
  25. To build an app which uses Juce, all you need to do is to add this
  26. file to your project, and include juce.h in your own cpp files.
  27. */
  28. //==============================================================================
  29. #ifdef _WIN32
  30. /********* Start of inlined file: win32_headers.h *********/
  31. #ifndef __WIN32_HEADERS_JUCEHEADER__
  32. #define __WIN32_HEADERS_JUCEHEADER__
  33. #ifndef STRICT
  34. #define STRICT 1
  35. #endif
  36. #define WIN32_LEAN_AND_MEAN
  37. // don't want to get told about microsoft's mistakes..
  38. #ifdef _MSC_VER
  39. #pragma warning (push)
  40. #pragma warning (disable : 4100 4201)
  41. #endif
  42. // use Platform SDK as win2000 unless this is disabled
  43. #ifndef DISABLE_TRANSPARENT_WINDOWS
  44. #define _WIN32_WINNT 0x0500
  45. #endif
  46. #define _UNICODE 1
  47. #define UNICODE 1
  48. #include <windows.h>
  49. #include <commdlg.h>
  50. #include <shellapi.h>
  51. #include <mmsystem.h>
  52. #include <vfw.h>
  53. #include <tchar.h>
  54. #undef PACKED
  55. #ifdef _MSC_VER
  56. #pragma warning (pop)
  57. #endif
  58. #endif // __WIN32_HEADERS_JUCEHEADER__
  59. /********* End of inlined file: win32_headers.h *********/
  60. #include <winsock2.h>
  61. #include <mapi.h>
  62. #include <ctime>
  63. #if JUCE_QUICKTIME
  64. #include <Movies.h>
  65. #include <QTML.h>
  66. #include <QuickTimeComponents.h>
  67. #include <MediaHandlers.h>
  68. #include <ImageCodec.h>
  69. #undef TARGET_OS_MAC // quicktime sets these, but they confuse some of the 3rd party libs
  70. #undef MACOS
  71. #endif
  72. #elif defined (LINUX)
  73. #else
  74. #include <Carbon/Carbon.h>
  75. #include <CoreAudio/HostTime.h>
  76. #define __Point__
  77. #include <IOKit/IOKitLib.h>
  78. #include <IOKit/graphics/IOGraphicsTypes.h>
  79. #include <IOKit/network/IOEthernetInterface.h>
  80. #include <IOKit/network/IONetworkInterface.h>
  81. #include <IOKit/network/IOEthernetController.h>
  82. #include <IOKit/IOCFPlugIn.h>
  83. #include <IOKit/hid/IOHIDLib.h>
  84. #include <IOKit/hid/IOHIDKeys.h>
  85. #include <sys/filedesc.h>
  86. #include <sys/time.h>
  87. #include <sys/proc.h>
  88. #include <Kernel/libkern/OSTypes.h>
  89. #endif
  90. //==============================================================================
  91. #define DONT_SET_USING_JUCE_NAMESPACE 1
  92. #include "juce_amalgamated.h"
  93. #define NO_DUMMY_DECL
  94. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  95. #pragma warning (disable: 4309 4305)
  96. #endif
  97. //==============================================================================
  98. /********* Start of inlined file: juce_FileLogger.cpp *********/
  99. BEGIN_JUCE_NAMESPACE
  100. FileLogger::FileLogger (const File& logFile_,
  101. const String& welcomeMessage,
  102. const int maxInitialFileSizeBytes)
  103. : logFile (logFile_)
  104. {
  105. if (maxInitialFileSizeBytes >= 0)
  106. trimFileSize (maxInitialFileSizeBytes);
  107. if (! logFile_.exists())
  108. {
  109. // do this so that the parent directories get created..
  110. logFile_.create();
  111. }
  112. logStream = logFile_.createOutputStream (256);
  113. jassert (logStream != 0);
  114. String welcome;
  115. welcome << "\r\n**********************************************************\r\n"
  116. << welcomeMessage
  117. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  118. << "\r\n";
  119. logMessage (welcome);
  120. }
  121. FileLogger::~FileLogger()
  122. {
  123. deleteAndZero (logStream);
  124. }
  125. void FileLogger::logMessage (const String& message)
  126. {
  127. if (logStream != 0)
  128. {
  129. Logger::outputDebugString (message);
  130. const ScopedLock sl (logLock);
  131. (*logStream) << message << T("\r\n");
  132. logStream->flush();
  133. }
  134. }
  135. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  136. {
  137. if (maxFileSizeBytes <= 0)
  138. {
  139. logFile.deleteFile();
  140. }
  141. else
  142. {
  143. const int64 fileSize = logFile.getSize();
  144. if (fileSize > maxFileSizeBytes)
  145. {
  146. FileInputStream* const in = logFile.createInputStream();
  147. jassert (in != 0);
  148. if (in != 0)
  149. {
  150. in->setPosition (fileSize - maxFileSizeBytes);
  151. String content;
  152. {
  153. MemoryBlock contentToSave;
  154. contentToSave.setSize (maxFileSizeBytes + 4);
  155. contentToSave.fillWith (0);
  156. in->read (contentToSave.getData(), maxFileSizeBytes);
  157. delete in;
  158. content = contentToSave.toString();
  159. }
  160. int newStart = 0;
  161. while (newStart < fileSize
  162. && content[newStart] != '\n'
  163. && content[newStart] != '\r')
  164. ++newStart;
  165. logFile.deleteFile();
  166. logFile.appendText (content.substring (newStart), false, false);
  167. }
  168. }
  169. }
  170. }
  171. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  172. const String& logFileName,
  173. const String& welcomeMessage,
  174. const int maxInitialFileSizeBytes)
  175. {
  176. #if JUCE_MAC
  177. File logFile ("~/Library/Logs");
  178. logFile = logFile.getChildFile (logFileName);
  179. #else
  180. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  181. if (logFile.isDirectory())
  182. {
  183. logFile = logFile.getChildFile (logFileSubDirectoryName)
  184. .getChildFile (logFileName);
  185. }
  186. #endif
  187. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  188. }
  189. END_JUCE_NAMESPACE
  190. /********* End of inlined file: juce_FileLogger.cpp *********/
  191. /********* Start of inlined file: juce_Logger.cpp *********/
  192. BEGIN_JUCE_NAMESPACE
  193. Logger::Logger()
  194. {
  195. }
  196. Logger::~Logger()
  197. {
  198. }
  199. static Logger* currentLogger = 0;
  200. void Logger::setCurrentLogger (Logger* const newLogger,
  201. const bool deleteOldLogger)
  202. {
  203. Logger* const oldLogger = currentLogger;
  204. currentLogger = newLogger;
  205. if (deleteOldLogger && (oldLogger != 0))
  206. delete oldLogger;
  207. }
  208. void Logger::writeToLog (const String& message)
  209. {
  210. if (currentLogger != 0)
  211. currentLogger->logMessage (message);
  212. else
  213. outputDebugString (message);
  214. }
  215. #if JUCE_LOG_ASSERTIONS
  216. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  217. {
  218. String m ("JUCE Assertion failure in ");
  219. m << filename << ", line " << lineNum;
  220. Logger::writeToLog (m);
  221. }
  222. #endif
  223. END_JUCE_NAMESPACE
  224. /********* End of inlined file: juce_Logger.cpp *********/
  225. /********* Start of inlined file: juce_Random.cpp *********/
  226. BEGIN_JUCE_NAMESPACE
  227. Random::Random (const int64 seedValue) throw()
  228. : seed (seedValue)
  229. {
  230. }
  231. Random::~Random() throw()
  232. {
  233. }
  234. void Random::setSeed (const int64 newSeed) throw()
  235. {
  236. seed = newSeed;
  237. }
  238. int Random::nextInt() throw()
  239. {
  240. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  241. return (int) (seed >> 16);
  242. }
  243. int Random::nextInt (const int maxValue) throw()
  244. {
  245. jassert (maxValue > 0);
  246. return (nextInt() & 0x7fffffff) % maxValue;
  247. }
  248. int64 Random::nextInt64() throw()
  249. {
  250. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  251. }
  252. bool Random::nextBool() throw()
  253. {
  254. return (nextInt() & 0x80000000) != 0;
  255. }
  256. float Random::nextFloat() throw()
  257. {
  258. return ((uint32) nextInt()) / (float) 0xffffffff;
  259. }
  260. double Random::nextDouble() throw()
  261. {
  262. return ((uint32) nextInt()) / (double) 0xffffffff;
  263. }
  264. static Random sysRand (1);
  265. Random& Random::getSystemRandom() throw()
  266. {
  267. return sysRand;
  268. }
  269. END_JUCE_NAMESPACE
  270. /********* End of inlined file: juce_Random.cpp *********/
  271. /********* Start of inlined file: juce_RelativeTime.cpp *********/
  272. BEGIN_JUCE_NAMESPACE
  273. RelativeTime::RelativeTime (const double seconds_) throw()
  274. : seconds (seconds_)
  275. {
  276. }
  277. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  278. : seconds (other.seconds)
  279. {
  280. }
  281. RelativeTime::~RelativeTime() throw()
  282. {
  283. }
  284. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  285. {
  286. return RelativeTime (milliseconds * 0.001);
  287. }
  288. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  289. {
  290. return RelativeTime (milliseconds * 0.001);
  291. }
  292. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  293. {
  294. return RelativeTime (numberOfMinutes * 60.0);
  295. }
  296. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  297. {
  298. return RelativeTime (numberOfHours * (60.0 * 60.0));
  299. }
  300. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  301. {
  302. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  303. }
  304. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  305. {
  306. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  307. }
  308. int64 RelativeTime::inMilliseconds() const throw()
  309. {
  310. return (int64)(seconds * 1000.0);
  311. }
  312. double RelativeTime::inMinutes() const throw()
  313. {
  314. return seconds / 60.0;
  315. }
  316. double RelativeTime::inHours() const throw()
  317. {
  318. return seconds / (60.0 * 60.0);
  319. }
  320. double RelativeTime::inDays() const throw()
  321. {
  322. return seconds / (60.0 * 60.0 * 24.0);
  323. }
  324. double RelativeTime::inWeeks() const throw()
  325. {
  326. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  327. }
  328. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  329. {
  330. if (seconds < 0.001 && seconds > -0.001)
  331. return returnValueForZeroTime;
  332. String result;
  333. if (seconds < 0)
  334. result = T("-");
  335. int fieldsShown = 0;
  336. int n = abs ((int) inWeeks());
  337. if (n > 0)
  338. {
  339. result << n << ((n == 1) ? TRANS(" week ")
  340. : TRANS(" weeks "));
  341. ++fieldsShown;
  342. }
  343. n = abs ((int) inDays()) % 7;
  344. if (n > 0)
  345. {
  346. result << n << ((n == 1) ? TRANS(" day ")
  347. : TRANS(" days "));
  348. ++fieldsShown;
  349. }
  350. if (fieldsShown < 2)
  351. {
  352. n = abs ((int) inHours()) % 24;
  353. if (n > 0)
  354. {
  355. result << n << ((n == 1) ? TRANS(" hr ")
  356. : TRANS(" hrs "));
  357. ++fieldsShown;
  358. }
  359. if (fieldsShown < 2)
  360. {
  361. n = abs ((int) inMinutes()) % 60;
  362. if (n > 0)
  363. {
  364. result << n << ((n == 1) ? TRANS(" min ")
  365. : TRANS(" mins "));
  366. ++fieldsShown;
  367. }
  368. if (fieldsShown < 2)
  369. {
  370. n = abs ((int) inSeconds()) % 60;
  371. if (n > 0)
  372. {
  373. result << n << ((n == 1) ? TRANS(" sec ")
  374. : TRANS(" secs "));
  375. ++fieldsShown;
  376. }
  377. if (fieldsShown < 1)
  378. {
  379. n = abs ((int) inMilliseconds()) % 1000;
  380. if (n > 0)
  381. {
  382. result << n << TRANS(" ms");
  383. ++fieldsShown;
  384. }
  385. }
  386. }
  387. }
  388. }
  389. return result.trimEnd();
  390. }
  391. const RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  392. {
  393. seconds = other.seconds;
  394. return *this;
  395. }
  396. bool RelativeTime::operator== (const RelativeTime& other) const throw()
  397. {
  398. return seconds == other.seconds;
  399. }
  400. bool RelativeTime::operator!= (const RelativeTime& other) const throw()
  401. {
  402. return seconds != other.seconds;
  403. }
  404. bool RelativeTime::operator> (const RelativeTime& other) const throw()
  405. {
  406. return seconds > other.seconds;
  407. }
  408. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  409. {
  410. return seconds < other.seconds;
  411. }
  412. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  413. {
  414. return seconds >= other.seconds;
  415. }
  416. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  417. {
  418. return seconds <= other.seconds;
  419. }
  420. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  421. {
  422. return RelativeTime (seconds + timeToAdd.seconds);
  423. }
  424. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  425. {
  426. return RelativeTime (seconds - timeToSubtract.seconds);
  427. }
  428. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  429. {
  430. return RelativeTime (seconds + secondsToAdd);
  431. }
  432. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  433. {
  434. return RelativeTime (seconds - secondsToSubtract);
  435. }
  436. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  437. {
  438. seconds += timeToAdd.seconds;
  439. return *this;
  440. }
  441. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  442. {
  443. seconds -= timeToSubtract.seconds;
  444. return *this;
  445. }
  446. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  447. {
  448. seconds += secondsToAdd;
  449. return *this;
  450. }
  451. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  452. {
  453. seconds -= secondsToSubtract;
  454. return *this;
  455. }
  456. END_JUCE_NAMESPACE
  457. /********* End of inlined file: juce_RelativeTime.cpp *********/
  458. /********* Start of inlined file: juce_SystemStats.cpp *********/
  459. BEGIN_JUCE_NAMESPACE
  460. void juce_initialiseStrings();
  461. const String SystemStats::getJUCEVersion() throw()
  462. {
  463. return "JUCE v" + String (JUCE_MAJOR_VERSION) + "." + String (JUCE_MINOR_VERSION);
  464. }
  465. static bool juceInitialisedNonGUI = false;
  466. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  467. {
  468. if (! juceInitialisedNonGUI)
  469. {
  470. #ifdef JUCE_DEBUG
  471. // Some simple test code to keep an eye on things and make sure these functions
  472. // work ok on all platforms. Let me know if any of these assertions fail!
  473. int n = 1;
  474. atomicIncrement (n);
  475. jassert (atomicIncrementAndReturn (n) == 3);
  476. atomicDecrement (n);
  477. jassert (atomicDecrementAndReturn (n) == 1);
  478. jassert (swapByteOrder ((uint32) 0x11223344) == 0x44332211);
  479. // quick test to make sure the run-time lib doesn't crash on freeing a null-pointer.
  480. SystemStats* nullPointer = 0;
  481. juce_free (nullPointer);
  482. delete[] nullPointer;
  483. delete nullPointer;
  484. #endif
  485. // Now the real initialisation..
  486. juceInitialisedNonGUI = true;
  487. DBG (SystemStats::getJUCEVersion());
  488. juce_initialiseStrings();
  489. SystemStats::initialiseStats();
  490. Random::getSystemRandom().setSeed (Time::currentTimeMillis());
  491. }
  492. }
  493. #if JUCE_WIN32
  494. // This is imported from the sockets code..
  495. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  496. extern juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib;
  497. #endif
  498. #if JUCE_DEBUG
  499. extern void juce_CheckForDanglingStreams();
  500. #endif
  501. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  502. {
  503. if (juceInitialisedNonGUI)
  504. {
  505. #if JUCE_WIN32
  506. // need to shut down sockets if they were used..
  507. if (juce_CloseWin32SocketLib != 0)
  508. (*juce_CloseWin32SocketLib)();
  509. #endif
  510. LocalisedStrings::setCurrentMappings (0);
  511. Thread::stopAllThreads (3000);
  512. #if JUCE_DEBUG
  513. juce_CheckForDanglingStreams();
  514. #endif
  515. juceInitialisedNonGUI = false;
  516. }
  517. }
  518. #ifdef JUCE_DLL
  519. void* juce_Malloc (const int size)
  520. {
  521. return malloc (size);
  522. }
  523. void* juce_Calloc (const int size)
  524. {
  525. return calloc (1, size);
  526. }
  527. void* juce_Realloc (void* const block, const int size)
  528. {
  529. return realloc (block, size);
  530. }
  531. void juce_Free (void* const block)
  532. {
  533. free (block);
  534. }
  535. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  536. void* juce_DebugMalloc (const int size, const char* file, const int line)
  537. {
  538. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  539. }
  540. void* juce_DebugCalloc (const int size, const char* file, const int line)
  541. {
  542. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  543. }
  544. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  545. {
  546. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  547. }
  548. void juce_DebugFree (void* const block)
  549. {
  550. _free_dbg (block, _NORMAL_BLOCK);
  551. }
  552. #endif
  553. #endif
  554. END_JUCE_NAMESPACE
  555. /********* End of inlined file: juce_SystemStats.cpp *********/
  556. /********* Start of inlined file: juce_Time.cpp *********/
  557. #ifdef _MSC_VER
  558. #pragma warning (disable: 4514)
  559. #pragma warning (push)
  560. #endif
  561. #ifndef JUCE_WIN32
  562. #include <sys/time.h>
  563. #else
  564. #include <ctime>
  565. #endif
  566. #include <sys/timeb.h>
  567. BEGIN_JUCE_NAMESPACE
  568. #ifdef _MSC_VER
  569. #pragma warning (pop)
  570. #ifdef _INC_TIME_INL
  571. #define USE_NEW_SECURE_TIME_FNS
  572. #endif
  573. #endif
  574. static void millisToLocal (const int64 millis, struct tm& result) throw()
  575. {
  576. const int64 seconds = millis / 1000;
  577. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  578. {
  579. // use extended maths for dates beyond 1970 to 2037..
  580. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  581. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  582. const int days = (int) (jdm / literal64bit (86400));
  583. const int a = 32044 + days;
  584. const int b = (4 * a + 3) / 146097;
  585. const int c = a - (b * 146097) / 4;
  586. const int d = (4 * c + 3) / 1461;
  587. const int e = c - (d * 1461) / 4;
  588. const int m = (5 * e + 2) / 153;
  589. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  590. result.tm_mon = m + 2 - 12 * (m / 10);
  591. result.tm_year = b * 100 + d - 6700 + (m / 10);
  592. result.tm_wday = (days + 1) % 7;
  593. result.tm_yday = -1;
  594. int t = (int) (jdm % literal64bit (86400));
  595. result.tm_hour = t / 3600;
  596. t %= 3600;
  597. result.tm_min = t / 60;
  598. result.tm_sec = t % 60;
  599. result.tm_isdst = -1;
  600. }
  601. else
  602. {
  603. time_t now = (time_t) (seconds);
  604. #if JUCE_WIN32
  605. #ifdef USE_NEW_SECURE_TIME_FNS
  606. if (now >= 0 && now <= 0x793406fff)
  607. localtime_s (&result, &now);
  608. else
  609. zeromem (&result, sizeof (result));
  610. #else
  611. result = *localtime (&now);
  612. #endif
  613. #else
  614. // more thread-safe
  615. localtime_r (&now, &result);
  616. #endif
  617. }
  618. }
  619. Time::Time() throw()
  620. : millisSinceEpoch (0)
  621. {
  622. }
  623. Time::Time (const Time& other) throw()
  624. : millisSinceEpoch (other.millisSinceEpoch)
  625. {
  626. }
  627. Time::Time (const int64 ms) throw()
  628. : millisSinceEpoch (ms)
  629. {
  630. }
  631. Time::Time (const int year,
  632. const int month,
  633. const int day,
  634. const int hours,
  635. const int minutes,
  636. const int seconds,
  637. const int milliseconds,
  638. const bool useLocalTime) throw()
  639. {
  640. jassert (year > 100); // year must be a 4-digit version
  641. if (year < 1971 || year >= 2038 || ! useLocalTime)
  642. {
  643. // use extended maths for dates beyond 1970 to 2037..
  644. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  645. : 0;
  646. const int a = (13 - month) / 12;
  647. const int y = year + 4800 - a;
  648. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  649. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  650. - 32045;
  651. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  652. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  653. + milliseconds;
  654. }
  655. else
  656. {
  657. struct tm t;
  658. t.tm_year = year - 1900;
  659. t.tm_mon = month;
  660. t.tm_mday = day;
  661. t.tm_hour = hours;
  662. t.tm_min = minutes;
  663. t.tm_sec = seconds;
  664. t.tm_isdst = -1;
  665. millisSinceEpoch = 1000 * (int64) mktime (&t);
  666. if (millisSinceEpoch < 0)
  667. millisSinceEpoch = 0;
  668. else
  669. millisSinceEpoch += milliseconds;
  670. }
  671. }
  672. Time::~Time() throw()
  673. {
  674. }
  675. const Time& Time::operator= (const Time& other) throw()
  676. {
  677. millisSinceEpoch = other.millisSinceEpoch;
  678. return *this;
  679. }
  680. int64 Time::currentTimeMillis() throw()
  681. {
  682. static uint32 lastCounterResult = 0xffffffff;
  683. static int64 correction = 0;
  684. const uint32 now = getMillisecondCounter();
  685. // check the counter hasn't wrapped (also triggered the first time this function is called)
  686. if (now < lastCounterResult)
  687. {
  688. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  689. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  690. {
  691. // get the time once using normal library calls, and store the difference needed to
  692. // turn the millisecond counter into a real time.
  693. #if JUCE_WIN32
  694. struct _timeb t;
  695. #ifdef USE_NEW_SECURE_TIME_FNS
  696. _ftime_s (&t);
  697. #else
  698. _ftime (&t);
  699. #endif
  700. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  701. #else
  702. struct timeval tv;
  703. struct timezone tz;
  704. gettimeofday (&tv, &tz);
  705. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  706. #endif
  707. }
  708. }
  709. lastCounterResult = now;
  710. return correction + now;
  711. }
  712. uint32 juce_millisecondsSinceStartup() throw();
  713. static uint32 lastMSCounterValue = 0;
  714. uint32 Time::getMillisecondCounter() throw()
  715. {
  716. const uint32 now = juce_millisecondsSinceStartup();
  717. if (now < lastMSCounterValue)
  718. {
  719. // in multi-threaded apps this might be called concurrently, so
  720. // make sure that our last counter value only increases and doesn't
  721. // go backwards..
  722. if (now < lastMSCounterValue - 1000)
  723. lastMSCounterValue = now;
  724. }
  725. else
  726. {
  727. lastMSCounterValue = now;
  728. }
  729. return now;
  730. }
  731. uint32 Time::getApproximateMillisecondCounter() throw()
  732. {
  733. jassert (lastMSCounterValue != 0);
  734. return lastMSCounterValue;
  735. }
  736. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  737. {
  738. for (;;)
  739. {
  740. const uint32 now = getMillisecondCounter();
  741. if (now >= targetTime)
  742. break;
  743. const int toWait = targetTime - now;
  744. if (toWait > 2)
  745. {
  746. Thread::sleep (jmin (20, toWait >> 1));
  747. }
  748. else
  749. {
  750. // xxx should consider using mutex_pause on the mac as it apparently
  751. // makes it seem less like a spinlock and avoids lowering the thread pri.
  752. for (int i = 10; --i >= 0;)
  753. Thread::yield();
  754. }
  755. }
  756. }
  757. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  758. {
  759. return ticks / (double) getHighResolutionTicksPerSecond();
  760. }
  761. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  762. {
  763. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  764. }
  765. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  766. {
  767. return Time (currentTimeMillis());
  768. }
  769. const String Time::toString (const bool includeDate,
  770. const bool includeTime,
  771. const bool includeSeconds,
  772. const bool use24HourClock) const throw()
  773. {
  774. String result;
  775. if (includeDate)
  776. {
  777. result << getDayOfMonth() << ' '
  778. << getMonthName (true) << ' '
  779. << getYear();
  780. if (includeTime)
  781. result << ' ';
  782. }
  783. if (includeTime)
  784. {
  785. if (includeSeconds)
  786. {
  787. result += String::formatted (T("%d:%02d:%02d "),
  788. (use24HourClock) ? getHours()
  789. : getHoursInAmPmFormat(),
  790. getMinutes(),
  791. getSeconds());
  792. }
  793. else
  794. {
  795. result += String::formatted (T("%d.%02d"),
  796. (use24HourClock) ? getHours()
  797. : getHoursInAmPmFormat(),
  798. getMinutes());
  799. }
  800. if (! use24HourClock)
  801. result << (isAfternoon() ? "pm" : "am");
  802. }
  803. return result.trimEnd();
  804. }
  805. const String Time::formatted (const tchar* const format) const throw()
  806. {
  807. tchar buffer[80];
  808. struct tm t;
  809. millisToLocal (millisSinceEpoch, t);
  810. if (CharacterFunctions::ftime (buffer, 79, format, &t) <= 0)
  811. {
  812. int bufferSize = 128;
  813. for (;;)
  814. {
  815. MemoryBlock mb (bufferSize * sizeof (tchar));
  816. tchar* const b = (tchar*) mb.getData();
  817. if (CharacterFunctions::ftime (b, bufferSize, format, &t) > 0)
  818. return String (b);
  819. bufferSize += 128;
  820. }
  821. }
  822. return String (buffer);
  823. }
  824. int Time::getYear() const throw()
  825. {
  826. struct tm t;
  827. millisToLocal (millisSinceEpoch, t);
  828. return t.tm_year + 1900;
  829. }
  830. int Time::getMonth() const throw()
  831. {
  832. struct tm t;
  833. millisToLocal (millisSinceEpoch, t);
  834. return t.tm_mon;
  835. }
  836. int Time::getDayOfMonth() const throw()
  837. {
  838. struct tm t;
  839. millisToLocal (millisSinceEpoch, t);
  840. return t.tm_mday;
  841. }
  842. int Time::getDayOfWeek() const throw()
  843. {
  844. struct tm t;
  845. millisToLocal (millisSinceEpoch, t);
  846. return t.tm_wday;
  847. }
  848. int Time::getHours() const throw()
  849. {
  850. struct tm t;
  851. millisToLocal (millisSinceEpoch, t);
  852. return t.tm_hour;
  853. }
  854. int Time::getHoursInAmPmFormat() const throw()
  855. {
  856. const int hours = getHours();
  857. if (hours == 0)
  858. return 12;
  859. else if (hours <= 12)
  860. return hours;
  861. else
  862. return hours - 12;
  863. }
  864. bool Time::isAfternoon() const throw()
  865. {
  866. return getHours() >= 12;
  867. }
  868. static int extendedModulo (const int64 value, const int modulo) throw()
  869. {
  870. return (int) (value >= 0 ? (value % modulo)
  871. : (value - ((value / modulo) + 1) * modulo));
  872. }
  873. int Time::getMinutes() const throw()
  874. {
  875. return extendedModulo (millisSinceEpoch / 60000, 60);
  876. }
  877. int Time::getSeconds() const throw()
  878. {
  879. return extendedModulo (millisSinceEpoch / 1000, 60);
  880. }
  881. int Time::getMilliseconds() const throw()
  882. {
  883. return extendedModulo (millisSinceEpoch, 1000);
  884. }
  885. bool Time::isDaylightSavingTime() const throw()
  886. {
  887. struct tm t;
  888. millisToLocal (millisSinceEpoch, t);
  889. return t.tm_isdst != 0;
  890. }
  891. const String Time::getTimeZone() const throw()
  892. {
  893. String zone[2];
  894. #if JUCE_WIN32
  895. _tzset();
  896. #ifdef USE_NEW_SECURE_TIME_FNS
  897. {
  898. char name [128];
  899. size_t length;
  900. for (int i = 0; i < 2; ++i)
  901. {
  902. zeromem (name, sizeof (name));
  903. _get_tzname (&length, name, 127, i);
  904. zone[i] = name;
  905. }
  906. }
  907. #else
  908. const char** const zonePtr = (const char**) _tzname;
  909. zone[0] = zonePtr[0];
  910. zone[1] = zonePtr[1];
  911. #endif
  912. #else
  913. tzset();
  914. const char** const zonePtr = (const char**) tzname;
  915. zone[0] = zonePtr[0];
  916. zone[1] = zonePtr[1];
  917. #endif
  918. if (isDaylightSavingTime())
  919. {
  920. zone[0] = zone[1];
  921. if (zone[0].length() > 3
  922. && zone[0].containsIgnoreCase (T("daylight"))
  923. && zone[0].contains (T("GMT")))
  924. zone[0] = "BST";
  925. }
  926. return zone[0].substring (0, 3);
  927. }
  928. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  929. {
  930. return getMonthName (getMonth(), threeLetterVersion);
  931. }
  932. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  933. {
  934. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  935. }
  936. const String Time::getMonthName (int monthNumber,
  937. const bool threeLetterVersion) throw()
  938. {
  939. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  940. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  941. monthNumber %= 12;
  942. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  943. : longMonthNames [monthNumber]);
  944. }
  945. const String Time::getWeekdayName (int day,
  946. const bool threeLetterVersion) throw()
  947. {
  948. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  949. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  950. day %= 7;
  951. return TRANS (threeLetterVersion ? shortDayNames [day]
  952. : longDayNames [day]);
  953. }
  954. END_JUCE_NAMESPACE
  955. /********* End of inlined file: juce_Time.cpp *********/
  956. /********* Start of inlined file: juce_BitArray.cpp *********/
  957. BEGIN_JUCE_NAMESPACE
  958. BitArray::BitArray() throw()
  959. : numValues (4),
  960. highestBit (-1),
  961. negative (false)
  962. {
  963. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  964. }
  965. BitArray::BitArray (const int value) throw()
  966. : numValues (4),
  967. highestBit (31),
  968. negative (value < 0)
  969. {
  970. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  971. values[0] = abs (value);
  972. highestBit = getHighestBit();
  973. }
  974. BitArray::BitArray (int64 value) throw()
  975. : numValues (4),
  976. highestBit (63),
  977. negative (value < 0)
  978. {
  979. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  980. if (value < 0)
  981. value = -value;
  982. values[0] = (unsigned int) value;
  983. values[1] = (unsigned int) (value >> 32);
  984. highestBit = getHighestBit();
  985. }
  986. BitArray::BitArray (const unsigned int value) throw()
  987. : numValues (4),
  988. highestBit (31),
  989. negative (false)
  990. {
  991. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  992. values[0] = value;
  993. highestBit = getHighestBit();
  994. }
  995. BitArray::BitArray (const BitArray& other) throw()
  996. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  997. highestBit (other.getHighestBit()),
  998. negative (other.negative)
  999. {
  1000. const int bytes = sizeof (unsigned int) * (numValues + 1);
  1001. values = (unsigned int*) juce_malloc (bytes);
  1002. memcpy (values, other.values, bytes);
  1003. }
  1004. BitArray::~BitArray() throw()
  1005. {
  1006. juce_free (values);
  1007. }
  1008. const BitArray& BitArray::operator= (const BitArray& other) throw()
  1009. {
  1010. if (this != &other)
  1011. {
  1012. juce_free (values);
  1013. highestBit = other.getHighestBit();
  1014. numValues = jmax (4, (highestBit >> 5) + 1);
  1015. negative = other.negative;
  1016. const int memSize = sizeof (unsigned int) * (numValues + 1);
  1017. values = (unsigned int*)juce_malloc (memSize);
  1018. memcpy (values, other.values, memSize);
  1019. }
  1020. return *this;
  1021. }
  1022. // result == 0 = the same
  1023. // result < 0 = this number is smaller
  1024. // result > 0 = this number is bigger
  1025. int BitArray::compare (const BitArray& other) const throw()
  1026. {
  1027. if (isNegative() == other.isNegative())
  1028. {
  1029. const int absComp = compareAbsolute (other);
  1030. return isNegative() ? -absComp : absComp;
  1031. }
  1032. else
  1033. {
  1034. return isNegative() ? -1 : 1;
  1035. }
  1036. }
  1037. int BitArray::compareAbsolute (const BitArray& other) const throw()
  1038. {
  1039. const int h1 = getHighestBit();
  1040. const int h2 = other.getHighestBit();
  1041. if (h1 > h2)
  1042. return 1;
  1043. else if (h1 < h2)
  1044. return -1;
  1045. for (int i = (h1 >> 5) + 1; --i >= 0;)
  1046. if (values[i] != other.values[i])
  1047. return (values[i] > other.values[i]) ? 1 : -1;
  1048. return 0;
  1049. }
  1050. bool BitArray::operator== (const BitArray& other) const throw()
  1051. {
  1052. return compare (other) == 0;
  1053. }
  1054. bool BitArray::operator!= (const BitArray& other) const throw()
  1055. {
  1056. return compare (other) != 0;
  1057. }
  1058. bool BitArray::operator[] (const int bit) const throw()
  1059. {
  1060. return bit >= 0 && bit <= highestBit
  1061. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  1062. }
  1063. bool BitArray::isEmpty() const throw()
  1064. {
  1065. return getHighestBit() < 0;
  1066. }
  1067. void BitArray::clear() throw()
  1068. {
  1069. if (numValues > 16)
  1070. {
  1071. juce_free (values);
  1072. numValues = 4;
  1073. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1074. }
  1075. else
  1076. {
  1077. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  1078. }
  1079. highestBit = -1;
  1080. negative = false;
  1081. }
  1082. void BitArray::setBit (const int bit) throw()
  1083. {
  1084. if (bit >= 0)
  1085. {
  1086. if (bit > highestBit)
  1087. {
  1088. ensureSize (bit >> 5);
  1089. highestBit = bit;
  1090. }
  1091. values [bit >> 5] |= (1 << (bit & 31));
  1092. }
  1093. }
  1094. void BitArray::setBit (const int bit,
  1095. const bool shouldBeSet) throw()
  1096. {
  1097. if (shouldBeSet)
  1098. setBit (bit);
  1099. else
  1100. clearBit (bit);
  1101. }
  1102. void BitArray::clearBit (const int bit) throw()
  1103. {
  1104. if (bit >= 0 && bit <= highestBit)
  1105. values [bit >> 5] &= ~(1 << (bit & 31));
  1106. }
  1107. void BitArray::setRange (int startBit,
  1108. int numBits,
  1109. const bool shouldBeSet) throw()
  1110. {
  1111. while (--numBits >= 0)
  1112. setBit (startBit++, shouldBeSet);
  1113. }
  1114. void BitArray::insertBit (const int bit,
  1115. const bool shouldBeSet) throw()
  1116. {
  1117. if (bit >= 0)
  1118. shiftBits (1, bit);
  1119. setBit (bit, shouldBeSet);
  1120. }
  1121. void BitArray::andWith (const BitArray& other) throw()
  1122. {
  1123. // this operation will only work with the absolute values
  1124. jassert (isNegative() == other.isNegative());
  1125. int n = numValues;
  1126. while (n > other.numValues)
  1127. values[--n] = 0;
  1128. while (--n >= 0)
  1129. values[n] &= other.values[n];
  1130. if (other.highestBit < highestBit)
  1131. highestBit = other.highestBit;
  1132. highestBit = getHighestBit();
  1133. }
  1134. void BitArray::orWith (const BitArray& other) throw()
  1135. {
  1136. if (other.highestBit < 0)
  1137. return;
  1138. // this operation will only work with the absolute values
  1139. jassert (isNegative() == other.isNegative());
  1140. ensureSize (other.highestBit >> 5);
  1141. int n = (other.highestBit >> 5) + 1;
  1142. while (--n >= 0)
  1143. values[n] |= other.values[n];
  1144. if (other.highestBit > highestBit)
  1145. highestBit = other.highestBit;
  1146. highestBit = getHighestBit();
  1147. }
  1148. void BitArray::xorWith (const BitArray& other) throw()
  1149. {
  1150. if (other.highestBit < 0)
  1151. return;
  1152. // this operation will only work with the absolute values
  1153. jassert (isNegative() == other.isNegative());
  1154. ensureSize (other.highestBit >> 5);
  1155. int n = (other.highestBit >> 5) + 1;
  1156. while (--n >= 0)
  1157. values[n] ^= other.values[n];
  1158. if (other.highestBit > highestBit)
  1159. highestBit = other.highestBit;
  1160. highestBit = getHighestBit();
  1161. }
  1162. void BitArray::add (const BitArray& other) throw()
  1163. {
  1164. if (other.isNegative())
  1165. {
  1166. BitArray o (other);
  1167. o.negate();
  1168. subtract (o);
  1169. return;
  1170. }
  1171. if (isNegative())
  1172. {
  1173. if (compareAbsolute (other) < 0)
  1174. {
  1175. BitArray temp (*this);
  1176. temp.negate();
  1177. *this = other;
  1178. subtract (temp);
  1179. }
  1180. else
  1181. {
  1182. negate();
  1183. subtract (other);
  1184. negate();
  1185. }
  1186. return;
  1187. }
  1188. if (other.highestBit > highestBit)
  1189. highestBit = other.highestBit;
  1190. ++highestBit;
  1191. const int numInts = (highestBit >> 5) + 1;
  1192. ensureSize (numInts);
  1193. int64 remainder = 0;
  1194. for (int i = 0; i <= numInts; ++i)
  1195. {
  1196. if (i < numValues)
  1197. remainder += values[i];
  1198. if (i < other.numValues)
  1199. remainder += other.values[i];
  1200. values[i] = (unsigned int) remainder;
  1201. remainder >>= 32;
  1202. }
  1203. jassert (remainder == 0);
  1204. highestBit = getHighestBit();
  1205. }
  1206. void BitArray::subtract (const BitArray& other) throw()
  1207. {
  1208. if (other.isNegative())
  1209. {
  1210. BitArray o (other);
  1211. o.negate();
  1212. add (o);
  1213. return;
  1214. }
  1215. if (! isNegative())
  1216. {
  1217. if (compareAbsolute (other) < 0)
  1218. {
  1219. BitArray temp (*this);
  1220. *this = other;
  1221. subtract (temp);
  1222. negate();
  1223. return;
  1224. }
  1225. }
  1226. else
  1227. {
  1228. negate();
  1229. add (other);
  1230. negate();
  1231. return;
  1232. }
  1233. const int numInts = (highestBit >> 5) + 1;
  1234. const int maxOtherInts = (other.highestBit >> 5) + 1;
  1235. int64 amountToSubtract = 0;
  1236. for (int i = 0; i <= numInts; ++i)
  1237. {
  1238. if (i <= maxOtherInts)
  1239. amountToSubtract += (int64)other.values[i];
  1240. if (values[i] >= amountToSubtract)
  1241. {
  1242. values[i] = (unsigned int) (values[i] - amountToSubtract);
  1243. amountToSubtract = 0;
  1244. }
  1245. else
  1246. {
  1247. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  1248. values[i] = (unsigned int) n;
  1249. amountToSubtract = 1;
  1250. }
  1251. }
  1252. }
  1253. void BitArray::multiplyBy (const BitArray& other) throw()
  1254. {
  1255. BitArray total;
  1256. highestBit = getHighestBit();
  1257. const bool wasNegative = isNegative();
  1258. setNegative (false);
  1259. for (int i = 0; i <= highestBit; ++i)
  1260. {
  1261. if (operator[](i))
  1262. {
  1263. BitArray n (other);
  1264. n.setNegative (false);
  1265. n.shiftBits (i);
  1266. total.add (n);
  1267. }
  1268. }
  1269. *this = total;
  1270. negative = wasNegative ^ other.isNegative();
  1271. }
  1272. void BitArray::divideBy (const BitArray& divisor, BitArray& remainder) throw()
  1273. {
  1274. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  1275. const int divHB = divisor.getHighestBit();
  1276. const int ourHB = getHighestBit();
  1277. if (divHB < 0 || ourHB < 0)
  1278. {
  1279. // division by zero
  1280. remainder.clear();
  1281. clear();
  1282. }
  1283. else
  1284. {
  1285. remainder = *this;
  1286. remainder.setNegative (false);
  1287. const bool wasNegative = isNegative();
  1288. clear();
  1289. BitArray temp (divisor);
  1290. temp.setNegative (false);
  1291. int leftShift = ourHB - divHB;
  1292. temp.shiftBits (leftShift);
  1293. while (leftShift >= 0)
  1294. {
  1295. if (remainder.compareAbsolute (temp) >= 0)
  1296. {
  1297. remainder.subtract (temp);
  1298. setBit (leftShift);
  1299. }
  1300. if (--leftShift >= 0)
  1301. temp.shiftBits (-1);
  1302. }
  1303. negative = wasNegative ^ divisor.isNegative();
  1304. remainder.setNegative (wasNegative);
  1305. }
  1306. }
  1307. void BitArray::modulo (const BitArray& divisor) throw()
  1308. {
  1309. BitArray remainder;
  1310. divideBy (divisor, remainder);
  1311. *this = remainder;
  1312. }
  1313. static const BitArray simpleGCD (BitArray* m, BitArray* n) throw()
  1314. {
  1315. while (! m->isEmpty())
  1316. {
  1317. if (n->compareAbsolute (*m) > 0)
  1318. swapVariables (m, n);
  1319. m->subtract (*n);
  1320. }
  1321. return *n;
  1322. }
  1323. const BitArray BitArray::findGreatestCommonDivisor (BitArray n) const throw()
  1324. {
  1325. BitArray m (*this);
  1326. while (! n.isEmpty())
  1327. {
  1328. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  1329. return simpleGCD (&m, &n);
  1330. BitArray temp1 (m), temp2;
  1331. temp1.divideBy (n, temp2);
  1332. m = n;
  1333. n = temp2;
  1334. }
  1335. return m;
  1336. }
  1337. void BitArray::exponentModulo (const BitArray& exponent,
  1338. const BitArray& modulus) throw()
  1339. {
  1340. BitArray exp (exponent);
  1341. exp.modulo (modulus);
  1342. BitArray value (*this);
  1343. value.modulo (modulus);
  1344. clear();
  1345. setBit (0);
  1346. while (! exp.isEmpty())
  1347. {
  1348. if (exp [0])
  1349. {
  1350. multiplyBy (value);
  1351. this->modulo (modulus);
  1352. }
  1353. value.multiplyBy (value);
  1354. value.modulo (modulus);
  1355. exp.shiftBits (-1);
  1356. }
  1357. }
  1358. void BitArray::inverseModulo (const BitArray& modulus) throw()
  1359. {
  1360. const BitArray one (1);
  1361. if (modulus == one || modulus.isNegative())
  1362. {
  1363. clear();
  1364. return;
  1365. }
  1366. if (isNegative() || compareAbsolute (modulus) >= 0)
  1367. this->modulo (modulus);
  1368. if (*this == one)
  1369. return;
  1370. if (! (*this)[0])
  1371. {
  1372. // not invertible
  1373. clear();
  1374. return;
  1375. }
  1376. BitArray a1 (modulus);
  1377. BitArray a2 (*this);
  1378. BitArray b1 (modulus);
  1379. BitArray b2 (1);
  1380. while (a2 != one)
  1381. {
  1382. BitArray temp1, temp2, multiplier (a1);
  1383. multiplier.divideBy (a2, temp1);
  1384. temp1 = a2;
  1385. temp1.multiplyBy (multiplier);
  1386. temp2 = a1;
  1387. temp2.subtract (temp1);
  1388. a1 = a2;
  1389. a2 = temp2;
  1390. temp1 = b2;
  1391. temp1.multiplyBy (multiplier);
  1392. temp2 = b1;
  1393. temp2.subtract (temp1);
  1394. b1 = b2;
  1395. b2 = temp2;
  1396. }
  1397. while (b2.isNegative())
  1398. b2.add (modulus);
  1399. b2.modulo (modulus);
  1400. *this = b2;
  1401. }
  1402. void BitArray::shiftBits (int bits, const int startBit) throw()
  1403. {
  1404. if (highestBit < 0)
  1405. return;
  1406. if (startBit > 0)
  1407. {
  1408. if (bits < 0)
  1409. {
  1410. // right shift
  1411. for (int i = startBit; i <= highestBit; ++i)
  1412. setBit (i, operator[] (i - bits));
  1413. highestBit = getHighestBit();
  1414. }
  1415. else if (bits > 0)
  1416. {
  1417. // left shift
  1418. for (int i = highestBit + 1; --i >= startBit;)
  1419. setBit (i + bits, operator[] (i));
  1420. while (--bits >= 0)
  1421. clearBit (bits + startBit);
  1422. }
  1423. }
  1424. else
  1425. {
  1426. if (bits < 0)
  1427. {
  1428. // right shift
  1429. bits = -bits;
  1430. if (bits > highestBit)
  1431. {
  1432. clear();
  1433. }
  1434. else
  1435. {
  1436. const int wordsToMove = bits >> 5;
  1437. int top = 1 + (highestBit >> 5) - wordsToMove;
  1438. highestBit -= bits;
  1439. if (wordsToMove > 0)
  1440. {
  1441. int i;
  1442. for (i = 0; i < top; ++i)
  1443. values [i] = values [i + wordsToMove];
  1444. for (i = 0; i < wordsToMove; ++i)
  1445. values [top + i] = 0;
  1446. bits &= 31;
  1447. }
  1448. if (bits != 0)
  1449. {
  1450. const int invBits = 32 - bits;
  1451. --top;
  1452. for (int i = 0; i < top; ++i)
  1453. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  1454. values[top] = (values[top] >> bits);
  1455. }
  1456. highestBit = getHighestBit();
  1457. }
  1458. }
  1459. else if (bits > 0)
  1460. {
  1461. // left shift
  1462. ensureSize (((highestBit + bits) >> 5) + 1);
  1463. const int wordsToMove = bits >> 5;
  1464. int top = 1 + (highestBit >> 5);
  1465. highestBit += bits;
  1466. if (wordsToMove > 0)
  1467. {
  1468. int i;
  1469. for (i = top; --i >= 0;)
  1470. values [i + wordsToMove] = values [i];
  1471. for (i = 0; i < wordsToMove; ++i)
  1472. values [i] = 0;
  1473. bits &= 31;
  1474. }
  1475. if (bits != 0)
  1476. {
  1477. const int invBits = 32 - bits;
  1478. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  1479. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  1480. values [wordsToMove] = values [wordsToMove] << bits;
  1481. }
  1482. highestBit = getHighestBit();
  1483. }
  1484. }
  1485. }
  1486. int BitArray::getBitRangeAsInt (const int startBit, int numBits) const throw()
  1487. {
  1488. if (numBits > 32)
  1489. {
  1490. jassertfalse
  1491. numBits = 32;
  1492. }
  1493. if (startBit == 0)
  1494. {
  1495. if (numBits < 32)
  1496. return values[0] & ((1 << numBits) - 1);
  1497. return values[0];
  1498. }
  1499. int n = 0;
  1500. for (int i = numBits; --i >= 0;)
  1501. {
  1502. n <<= 1;
  1503. if (operator[] (startBit + i))
  1504. n |= 1;
  1505. }
  1506. return n;
  1507. }
  1508. void BitArray::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet) throw()
  1509. {
  1510. if (numBits > 32)
  1511. {
  1512. jassertfalse
  1513. numBits = 32;
  1514. }
  1515. for (int i = 0; i < numBits; ++i)
  1516. {
  1517. setBit (startBit + i, (valueToSet & 1) != 0);
  1518. valueToSet >>= 1;
  1519. }
  1520. }
  1521. void BitArray::fillBitsRandomly (int startBit, int numBits) throw()
  1522. {
  1523. highestBit = jmax (highestBit, startBit + numBits);
  1524. ensureSize (((startBit + numBits) >> 5) + 1);
  1525. while ((startBit & 31) != 0 && numBits > 0)
  1526. {
  1527. setBit (startBit++, Random::getSystemRandom().nextBool());
  1528. --numBits;
  1529. }
  1530. while (numBits >= 32)
  1531. {
  1532. values [startBit >> 5] = (unsigned int) Random::getSystemRandom().nextInt();
  1533. startBit += 32;
  1534. numBits -= 32;
  1535. }
  1536. while (--numBits >= 0)
  1537. {
  1538. setBit (startBit + numBits, Random::getSystemRandom().nextBool());
  1539. }
  1540. highestBit = getHighestBit();
  1541. }
  1542. void BitArray::createRandomNumber (const BitArray& maximumValue) throw()
  1543. {
  1544. clear();
  1545. do
  1546. {
  1547. fillBitsRandomly (0, maximumValue.getHighestBit() + 1);
  1548. }
  1549. while (compare (maximumValue) >= 0);
  1550. }
  1551. bool BitArray::isNegative() const throw()
  1552. {
  1553. return negative && ! isEmpty();
  1554. }
  1555. void BitArray::setNegative (const bool neg) throw()
  1556. {
  1557. negative = neg;
  1558. }
  1559. void BitArray::negate() throw()
  1560. {
  1561. negative = (! negative) && ! isEmpty();
  1562. }
  1563. int BitArray::countNumberOfSetBits() const throw()
  1564. {
  1565. int total = 0;
  1566. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  1567. {
  1568. unsigned int n = values[i];
  1569. if (n == 0xffffffff)
  1570. {
  1571. total += 32;
  1572. }
  1573. else
  1574. {
  1575. while (n != 0)
  1576. {
  1577. total += (n & 1);
  1578. n >>= 1;
  1579. }
  1580. }
  1581. }
  1582. return total;
  1583. }
  1584. int BitArray::getHighestBit() const throw()
  1585. {
  1586. for (int i = highestBit + 1; --i >= 0;)
  1587. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  1588. return i;
  1589. return -1;
  1590. }
  1591. int BitArray::findNextSetBit (int i) const throw()
  1592. {
  1593. for (; i <= highestBit; ++i)
  1594. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  1595. return i;
  1596. return -1;
  1597. }
  1598. int BitArray::findNextClearBit (int i) const throw()
  1599. {
  1600. for (; i <= highestBit; ++i)
  1601. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  1602. break;
  1603. return i;
  1604. }
  1605. void BitArray::ensureSize (const int numVals) throw()
  1606. {
  1607. if (numVals + 2 >= numValues)
  1608. {
  1609. int oldSize = numValues;
  1610. numValues = ((numVals + 2) * 3) / 2;
  1611. values = (unsigned int*) juce_realloc (values, sizeof (unsigned int) * numValues + 4);
  1612. while (oldSize < numValues)
  1613. values [oldSize++] = 0;
  1614. }
  1615. }
  1616. const String BitArray::toString (const int base) const throw()
  1617. {
  1618. String s;
  1619. BitArray v (*this);
  1620. if (base == 2 || base == 8 || base == 16)
  1621. {
  1622. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  1623. static const tchar* const hexDigits = T("0123456789abcdef");
  1624. for (;;)
  1625. {
  1626. const int remainder = v.getBitRangeAsInt (0, bits);
  1627. v.shiftBits (-bits);
  1628. if (remainder == 0 && v.isEmpty())
  1629. break;
  1630. s = String::charToString (hexDigits [remainder]) + s;
  1631. }
  1632. }
  1633. else if (base == 10)
  1634. {
  1635. const BitArray ten (10);
  1636. BitArray remainder;
  1637. for (;;)
  1638. {
  1639. v.divideBy (ten, remainder);
  1640. if (remainder.isEmpty() && v.isEmpty())
  1641. break;
  1642. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  1643. }
  1644. }
  1645. else
  1646. {
  1647. jassertfalse // can't do the specified base
  1648. return String::empty;
  1649. }
  1650. if (s.isEmpty())
  1651. return T("0");
  1652. return isNegative() ? T("-") + s : s;
  1653. }
  1654. void BitArray::parseString (const String& text,
  1655. const int base) throw()
  1656. {
  1657. clear();
  1658. const tchar* t = (const tchar*) text;
  1659. if (base == 2 || base == 8 || base == 16)
  1660. {
  1661. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  1662. for (;;)
  1663. {
  1664. const tchar c = *t++;
  1665. const int digit = CharacterFunctions::getHexDigitValue (c);
  1666. if (((unsigned int) digit) < (unsigned int) base)
  1667. {
  1668. shiftBits (bits);
  1669. add (digit);
  1670. }
  1671. else if (c == 0)
  1672. {
  1673. break;
  1674. }
  1675. }
  1676. }
  1677. else if (base == 10)
  1678. {
  1679. const BitArray ten ((unsigned int) 10);
  1680. for (;;)
  1681. {
  1682. const tchar c = *t++;
  1683. if (c >= T('0') && c <= T('9'))
  1684. {
  1685. multiplyBy (ten);
  1686. add ((int) (c - T('0')));
  1687. }
  1688. else if (c == 0)
  1689. {
  1690. break;
  1691. }
  1692. }
  1693. }
  1694. setNegative (text.trimStart().startsWithChar (T('-')));
  1695. }
  1696. const MemoryBlock BitArray::toMemoryBlock() const throw()
  1697. {
  1698. const int numBytes = (getHighestBit() + 7) >> 3;
  1699. MemoryBlock mb (numBytes);
  1700. for (int i = 0; i < numBytes; ++i)
  1701. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  1702. return mb;
  1703. }
  1704. void BitArray::loadFromMemoryBlock (const MemoryBlock& data) throw()
  1705. {
  1706. clear();
  1707. for (int i = data.getSize(); --i >= 0;)
  1708. this->setBitRangeAsInt (i << 3, 8, data [i]);
  1709. }
  1710. END_JUCE_NAMESPACE
  1711. /********* End of inlined file: juce_BitArray.cpp *********/
  1712. /********* Start of inlined file: juce_MemoryBlock.cpp *********/
  1713. BEGIN_JUCE_NAMESPACE
  1714. MemoryBlock::MemoryBlock() throw()
  1715. : data (0),
  1716. size (0)
  1717. {
  1718. }
  1719. MemoryBlock::MemoryBlock (const int initialSize,
  1720. const bool initialiseToZero) throw()
  1721. {
  1722. if (initialSize > 0)
  1723. {
  1724. size = initialSize;
  1725. if (initialiseToZero)
  1726. data = (char*) juce_calloc (initialSize);
  1727. else
  1728. data = (char*) juce_malloc (initialSize);
  1729. }
  1730. else
  1731. {
  1732. data = 0;
  1733. size = 0;
  1734. }
  1735. }
  1736. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  1737. : data (0),
  1738. size (other.size)
  1739. {
  1740. if (size > 0)
  1741. {
  1742. jassert (other.data != 0);
  1743. data = (char*) juce_malloc (size);
  1744. memcpy (data, other.data, size);
  1745. }
  1746. }
  1747. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  1748. const int sizeInBytes) throw()
  1749. : data (0),
  1750. size (jmax (0, sizeInBytes))
  1751. {
  1752. jassert (sizeInBytes >= 0);
  1753. if (size > 0)
  1754. {
  1755. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  1756. data = (char*) juce_malloc (size);
  1757. if (dataToInitialiseFrom != 0)
  1758. memcpy (data, dataToInitialiseFrom, size);
  1759. }
  1760. }
  1761. MemoryBlock::~MemoryBlock() throw()
  1762. {
  1763. jassert (size >= 0); // should never happen
  1764. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  1765. juce_free (data);
  1766. }
  1767. const MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  1768. {
  1769. if (this != &other)
  1770. {
  1771. setSize (other.size, false);
  1772. memcpy (data, other.data, size);
  1773. }
  1774. return *this;
  1775. }
  1776. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  1777. {
  1778. return (size == other.size)
  1779. && (memcmp (data, other.data, size) == 0);
  1780. }
  1781. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  1782. {
  1783. return ! operator== (other);
  1784. }
  1785. // this will resize the block to this size
  1786. void MemoryBlock::setSize (const int newSize,
  1787. const bool initialiseToZero) throw()
  1788. {
  1789. if (size != newSize)
  1790. {
  1791. if (newSize <= 0)
  1792. {
  1793. juce_free (data);
  1794. data = 0;
  1795. size = 0;
  1796. }
  1797. else
  1798. {
  1799. if (data != 0)
  1800. {
  1801. data = (char*) juce_realloc (data, newSize);
  1802. if (initialiseToZero && (newSize > size))
  1803. zeromem (data + size, newSize - size);
  1804. }
  1805. else
  1806. {
  1807. if (initialiseToZero)
  1808. data = (char*) juce_calloc (newSize);
  1809. else
  1810. data = (char*) juce_malloc (newSize);
  1811. }
  1812. size = newSize;
  1813. }
  1814. }
  1815. }
  1816. void MemoryBlock::ensureSize (const int minimumSize,
  1817. const bool initialiseToZero) throw()
  1818. {
  1819. if (size < minimumSize)
  1820. setSize (minimumSize, initialiseToZero);
  1821. }
  1822. void MemoryBlock::fillWith (const uint8 value) throw()
  1823. {
  1824. memset (data, (int) value, size);
  1825. }
  1826. void MemoryBlock::append (const void* const srcData,
  1827. const int numBytes) throw()
  1828. {
  1829. if (numBytes > 0)
  1830. {
  1831. const int oldSize = size;
  1832. setSize (size + numBytes);
  1833. memcpy (data + oldSize, srcData, numBytes);
  1834. }
  1835. }
  1836. void MemoryBlock::copyFrom (const void* const src, int offset, int num) throw()
  1837. {
  1838. const char* d = (const char*) src;
  1839. if (offset < 0)
  1840. {
  1841. d -= offset;
  1842. num -= offset;
  1843. offset = 0;
  1844. }
  1845. if (offset + num > size)
  1846. num = size - offset;
  1847. if (num > 0)
  1848. memcpy (data + offset, d, num);
  1849. }
  1850. void MemoryBlock::copyTo (void* const dst, int offset, int num) const throw()
  1851. {
  1852. char* d = (char*) dst;
  1853. if (offset < 0)
  1854. {
  1855. zeromem (d, -offset);
  1856. d -= offset;
  1857. num += offset;
  1858. offset = 0;
  1859. }
  1860. if (offset + num > size)
  1861. {
  1862. const int newNum = size - offset;
  1863. zeromem (d + newNum, num - newNum);
  1864. num = newNum;
  1865. }
  1866. if (num > 0)
  1867. memcpy (d, data + offset, num);
  1868. }
  1869. void MemoryBlock::removeSection (int startByte, int numBytesToRemove) throw()
  1870. {
  1871. if (startByte < 0)
  1872. {
  1873. numBytesToRemove += startByte;
  1874. startByte = 0;
  1875. }
  1876. if (startByte + numBytesToRemove >= size)
  1877. {
  1878. setSize (startByte);
  1879. }
  1880. else if (numBytesToRemove > 0)
  1881. {
  1882. memmove (data + startByte,
  1883. data + startByte + numBytesToRemove,
  1884. size - (startByte + numBytesToRemove));
  1885. setSize (size - numBytesToRemove);
  1886. }
  1887. }
  1888. const String MemoryBlock::toString() const throw()
  1889. {
  1890. return String (data, size);
  1891. }
  1892. int MemoryBlock::getBitRange (const int bitRangeStart, int numBits) const throw()
  1893. {
  1894. int res = 0;
  1895. int byte = bitRangeStart >> 3;
  1896. int offsetInByte = bitRangeStart & 7;
  1897. int bitsSoFar = 0;
  1898. while (numBits > 0 && byte < size)
  1899. {
  1900. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  1901. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  1902. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  1903. bitsSoFar += bitsThisTime;
  1904. numBits -= bitsThisTime;
  1905. ++byte;
  1906. offsetInByte = 0;
  1907. }
  1908. return res;
  1909. }
  1910. void MemoryBlock::setBitRange (const int bitRangeStart, int numBits, int bitsToSet) throw()
  1911. {
  1912. int byte = bitRangeStart >> 3;
  1913. int offsetInByte = bitRangeStart & 7;
  1914. unsigned int mask = ~((((unsigned int)0xffffffff) << (32 - numBits)) >> (32 - numBits));
  1915. while (numBits > 0 && byte < size)
  1916. {
  1917. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  1918. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int)0xffffffff) >> offsetInByte) << offsetInByte);
  1919. const unsigned int tempBits = bitsToSet << offsetInByte;
  1920. data[byte] = (char)((data[byte] & tempMask) | tempBits);
  1921. ++byte;
  1922. numBits -= bitsThisTime;
  1923. bitsToSet >>= bitsThisTime;
  1924. mask >>= bitsThisTime;
  1925. offsetInByte = 0;
  1926. }
  1927. }
  1928. void MemoryBlock::loadFromHexString (const String& hex) throw()
  1929. {
  1930. ensureSize (hex.length() >> 1);
  1931. char* dest = data;
  1932. int i = 0;
  1933. for (;;)
  1934. {
  1935. int byte = 0;
  1936. for (int loop = 2; --loop >= 0;)
  1937. {
  1938. byte <<= 4;
  1939. for (;;)
  1940. {
  1941. const tchar c = hex [i++];
  1942. if (c >= T('0') && c <= T('9'))
  1943. {
  1944. byte |= c - T('0');
  1945. break;
  1946. }
  1947. else if (c >= T('a') && c <= T('z'))
  1948. {
  1949. byte |= c - (T('a') - 10);
  1950. break;
  1951. }
  1952. else if (c >= T('A') && c <= T('Z'))
  1953. {
  1954. byte |= c - (T('A') - 10);
  1955. break;
  1956. }
  1957. else if (c == 0)
  1958. {
  1959. setSize ((int) (dest - data));
  1960. return;
  1961. }
  1962. }
  1963. }
  1964. *dest++ = (char) byte;
  1965. }
  1966. }
  1967. static const char* const encodingTable
  1968. = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  1969. const String MemoryBlock::toBase64Encoding() const throw()
  1970. {
  1971. const int numChars = ((size << 3) + 5) / 6;
  1972. String destString (size); // store the length, followed by a '.', and then the data.
  1973. const int initialLen = destString.length();
  1974. destString.preallocateStorage (initialLen + 2 + numChars);
  1975. tchar* d = const_cast <tchar*> (((const tchar*) destString) + initialLen);
  1976. *d++ = T('.');
  1977. for (int i = 0; i < numChars; ++i)
  1978. *d++ = encodingTable [getBitRange (i * 6, 6)];
  1979. *d++ = 0;
  1980. return destString;
  1981. }
  1982. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  1983. {
  1984. const int startPos = s.indexOfChar (T('.')) + 1;
  1985. if (startPos <= 0)
  1986. return false;
  1987. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  1988. setSize (numBytesNeeded, true);
  1989. const int numChars = s.length() - startPos;
  1990. const tchar* const srcChars = ((const tchar*) s) + startPos;
  1991. for (int i = 0; i < numChars; ++i)
  1992. {
  1993. const char c = (char) srcChars[i];
  1994. for (int j = 0; j < 64; ++j)
  1995. {
  1996. if (encodingTable[j] == c)
  1997. {
  1998. setBitRange (i * 6, 6, j);
  1999. break;
  2000. }
  2001. }
  2002. }
  2003. return true;
  2004. }
  2005. END_JUCE_NAMESPACE
  2006. /********* End of inlined file: juce_MemoryBlock.cpp *********/
  2007. /********* Start of inlined file: juce_PropertySet.cpp *********/
  2008. BEGIN_JUCE_NAMESPACE
  2009. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  2010. : properties (ignoreCaseOfKeyNames),
  2011. fallbackProperties (0),
  2012. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  2013. {
  2014. }
  2015. PropertySet::PropertySet (const PropertySet& other) throw()
  2016. : properties (other.properties),
  2017. fallbackProperties (other.fallbackProperties),
  2018. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  2019. {
  2020. }
  2021. const PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  2022. {
  2023. properties = other.properties;
  2024. fallbackProperties = other.fallbackProperties;
  2025. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  2026. propertyChanged();
  2027. return *this;
  2028. }
  2029. PropertySet::~PropertySet()
  2030. {
  2031. }
  2032. void PropertySet::clear()
  2033. {
  2034. const ScopedLock sl (lock);
  2035. if (properties.size() > 0)
  2036. {
  2037. properties.clear();
  2038. propertyChanged();
  2039. }
  2040. }
  2041. const String PropertySet::getValue (const String& keyName,
  2042. const String& defaultValue) const throw()
  2043. {
  2044. const ScopedLock sl (lock);
  2045. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2046. if (index >= 0)
  2047. return properties.getAllValues() [index];
  2048. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  2049. : defaultValue;
  2050. }
  2051. int PropertySet::getIntValue (const String& keyName,
  2052. const int defaultValue) const throw()
  2053. {
  2054. const ScopedLock sl (lock);
  2055. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2056. if (index >= 0)
  2057. return properties.getAllValues() [index].getIntValue();
  2058. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  2059. : defaultValue;
  2060. }
  2061. double PropertySet::getDoubleValue (const String& keyName,
  2062. const double defaultValue) const throw()
  2063. {
  2064. const ScopedLock sl (lock);
  2065. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2066. if (index >= 0)
  2067. return properties.getAllValues()[index].getDoubleValue();
  2068. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  2069. : defaultValue;
  2070. }
  2071. bool PropertySet::getBoolValue (const String& keyName,
  2072. const bool defaultValue) const throw()
  2073. {
  2074. const ScopedLock sl (lock);
  2075. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2076. if (index >= 0)
  2077. return properties.getAllValues() [index].getIntValue() != 0;
  2078. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  2079. : defaultValue;
  2080. }
  2081. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  2082. {
  2083. XmlDocument doc (getValue (keyName));
  2084. return doc.getDocumentElement();
  2085. }
  2086. void PropertySet::setValue (const String& keyName,
  2087. const String& value) throw()
  2088. {
  2089. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  2090. if (keyName.isNotEmpty())
  2091. {
  2092. const ScopedLock sl (lock);
  2093. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2094. if (index < 0 || properties.getAllValues() [index] != value)
  2095. {
  2096. properties.set (keyName, value);
  2097. propertyChanged();
  2098. }
  2099. }
  2100. }
  2101. void PropertySet::removeValue (const String& keyName) throw()
  2102. {
  2103. if (keyName.isNotEmpty())
  2104. {
  2105. const ScopedLock sl (lock);
  2106. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2107. if (index >= 0)
  2108. {
  2109. properties.remove (keyName);
  2110. propertyChanged();
  2111. }
  2112. }
  2113. }
  2114. void PropertySet::setValue (const String& keyName, const tchar* const value) throw()
  2115. {
  2116. setValue (keyName, String (value));
  2117. }
  2118. void PropertySet::setValue (const String& keyName, const int value) throw()
  2119. {
  2120. setValue (keyName, String (value));
  2121. }
  2122. void PropertySet::setValue (const String& keyName, const double value) throw()
  2123. {
  2124. setValue (keyName, String (value));
  2125. }
  2126. void PropertySet::setValue (const String& keyName, const bool value) throw()
  2127. {
  2128. setValue (keyName, String ((value) ? T("1") : T("0")));
  2129. }
  2130. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  2131. {
  2132. setValue (keyName, (xml == 0) ? String::empty
  2133. : xml->createDocument (String::empty, true));
  2134. }
  2135. bool PropertySet::containsKey (const String& keyName) const throw()
  2136. {
  2137. const ScopedLock sl (lock);
  2138. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  2139. }
  2140. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  2141. {
  2142. const ScopedLock sl (lock);
  2143. fallbackProperties = fallbackProperties_;
  2144. }
  2145. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  2146. {
  2147. const ScopedLock sl (lock);
  2148. XmlElement* const xml = new XmlElement (nodeName);
  2149. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  2150. {
  2151. XmlElement* const e = new XmlElement (T("VALUE"));
  2152. e->setAttribute (T("name"), properties.getAllKeys()[i]);
  2153. e->setAttribute (T("val"), properties.getAllValues()[i]);
  2154. xml->addChildElement (e);
  2155. }
  2156. return xml;
  2157. }
  2158. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  2159. {
  2160. const ScopedLock sl (lock);
  2161. clear();
  2162. forEachXmlChildElementWithTagName (xml, e, T("VALUE"))
  2163. {
  2164. if (e->hasAttribute (T("name"))
  2165. && e->hasAttribute (T("val")))
  2166. {
  2167. properties.set (e->getStringAttribute (T("name")),
  2168. e->getStringAttribute (T("val")));
  2169. }
  2170. }
  2171. if (properties.size() > 0)
  2172. propertyChanged();
  2173. }
  2174. void PropertySet::propertyChanged()
  2175. {
  2176. }
  2177. END_JUCE_NAMESPACE
  2178. /********* End of inlined file: juce_PropertySet.cpp *********/
  2179. /********* Start of inlined file: juce_BlowFish.cpp *********/
  2180. BEGIN_JUCE_NAMESPACE
  2181. static const uint32 initialPValues [18] =
  2182. {
  2183. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
  2184. 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  2185. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
  2186. 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  2187. 0x9216d5d9, 0x8979fb1b
  2188. };
  2189. static const uint32 initialSValues [4 * 256] =
  2190. {
  2191. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
  2192. 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  2193. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
  2194. 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  2195. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
  2196. 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  2197. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
  2198. 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  2199. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
  2200. 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  2201. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
  2202. 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  2203. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
  2204. 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  2205. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
  2206. 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  2207. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
  2208. 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  2209. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
  2210. 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  2211. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
  2212. 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  2213. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
  2214. 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  2215. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
  2216. 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  2217. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
  2218. 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  2219. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
  2220. 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  2221. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
  2222. 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  2223. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
  2224. 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  2225. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
  2226. 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  2227. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
  2228. 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  2229. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
  2230. 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  2231. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
  2232. 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  2233. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
  2234. 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  2235. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
  2236. 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  2237. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
  2238. 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  2239. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
  2240. 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  2241. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
  2242. 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  2243. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
  2244. 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  2245. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
  2246. 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  2247. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
  2248. 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  2249. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
  2250. 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  2251. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
  2252. 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  2253. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
  2254. 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  2255. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
  2256. 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  2257. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
  2258. 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  2259. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
  2260. 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  2261. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
  2262. 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  2263. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
  2264. 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  2265. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
  2266. 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  2267. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
  2268. 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  2269. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
  2270. 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  2271. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
  2272. 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  2273. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
  2274. 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  2275. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
  2276. 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  2277. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
  2278. 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  2279. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
  2280. 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  2281. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
  2282. 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  2283. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
  2284. 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  2285. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
  2286. 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  2287. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
  2288. 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  2289. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
  2290. 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  2291. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
  2292. 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  2293. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
  2294. 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  2295. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
  2296. 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  2297. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
  2298. 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  2299. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
  2300. 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  2301. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
  2302. 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  2303. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
  2304. 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  2305. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
  2306. 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  2307. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
  2308. 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  2309. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
  2310. 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  2311. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
  2312. 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  2313. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
  2314. 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  2315. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
  2316. 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  2317. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
  2318. 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  2319. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
  2320. 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  2321. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
  2322. 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  2323. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
  2324. 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  2325. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
  2326. 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  2327. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
  2328. 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  2329. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
  2330. 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  2331. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
  2332. 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  2333. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
  2334. 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  2335. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
  2336. 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  2337. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
  2338. 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  2339. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
  2340. 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  2341. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
  2342. 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  2343. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
  2344. 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  2345. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
  2346. 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  2347. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
  2348. 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  2349. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
  2350. 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  2351. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
  2352. 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  2353. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
  2354. 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  2355. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
  2356. 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  2357. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
  2358. 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  2359. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
  2360. 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  2361. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
  2362. 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  2363. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
  2364. 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  2365. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
  2366. 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  2367. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
  2368. 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  2369. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
  2370. 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  2371. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
  2372. 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  2373. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
  2374. 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  2375. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
  2376. 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  2377. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
  2378. 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  2379. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
  2380. 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  2381. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
  2382. 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  2383. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
  2384. 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  2385. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
  2386. 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  2387. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
  2388. 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  2389. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
  2390. 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  2391. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
  2392. 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  2393. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
  2394. 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  2395. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
  2396. 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  2397. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
  2398. 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  2399. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
  2400. 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  2401. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
  2402. 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  2403. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
  2404. 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  2405. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
  2406. 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  2407. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
  2408. 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  2409. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
  2410. 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  2411. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
  2412. 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  2413. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
  2414. 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  2415. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
  2416. 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  2417. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
  2418. 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  2419. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
  2420. 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  2421. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
  2422. 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  2423. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
  2424. 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  2425. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
  2426. 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  2427. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
  2428. 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  2429. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
  2430. 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  2431. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
  2432. 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  2433. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
  2434. 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  2435. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
  2436. 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  2437. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
  2438. 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  2439. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
  2440. 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  2441. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
  2442. 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  2443. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
  2444. 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  2445. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
  2446. 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  2447. };
  2448. BlowFish::BlowFish (const uint8* keyData, int keyBytes)
  2449. {
  2450. memcpy (p, initialPValues, sizeof (p));
  2451. int i, j;
  2452. for (i = 4; --i >= 0;)
  2453. {
  2454. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  2455. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  2456. }
  2457. j = 0;
  2458. for (i = 0; i < 18; ++i)
  2459. {
  2460. uint32 d = 0;
  2461. for (int k = 0; k < 4; ++k)
  2462. {
  2463. d = (d << 8) | keyData[j];
  2464. if (++j >= keyBytes)
  2465. j = 0;
  2466. }
  2467. p[i] = initialPValues[i] ^ d;
  2468. }
  2469. uint32 l = 0, r = 0;
  2470. for (i = 0; i < 18; i += 2)
  2471. {
  2472. encrypt (l, r);
  2473. p[i] = l;
  2474. p[i + 1] = r;
  2475. }
  2476. for (i = 0; i < 4; ++i)
  2477. {
  2478. for (j = 0; j < 256; j += 2)
  2479. {
  2480. encrypt (l, r);
  2481. s[i][j] = l;
  2482. s[i][j + 1] = r;
  2483. }
  2484. }
  2485. }
  2486. BlowFish::BlowFish (const BlowFish& other)
  2487. {
  2488. for (int i = 4; --i >= 0;)
  2489. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  2490. operator= (other);
  2491. }
  2492. const BlowFish& BlowFish::operator= (const BlowFish& other)
  2493. {
  2494. memcpy (p, other.p, sizeof (p));
  2495. for (int i = 4; --i >= 0;)
  2496. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  2497. return *this;
  2498. }
  2499. BlowFish::~BlowFish()
  2500. {
  2501. for (int i = 4; --i >= 0;)
  2502. juce_free (s[i]);
  2503. }
  2504. uint32 BlowFish::F (uint32 x) const
  2505. {
  2506. uint16 a, b, c, d;
  2507. uint32 y;
  2508. d = (uint16) (x & 0xff);
  2509. x >>= 8;
  2510. c = (uint16) (x & 0xff);
  2511. x >>= 8;
  2512. b = (uint16) (x & 0xff);
  2513. x >>= 8;
  2514. a = (uint16) (x & 0xff);
  2515. y = s[0][a] + s[1][b];
  2516. y = y ^ s[2][c];
  2517. y = y + s[3][d];
  2518. return y;
  2519. }
  2520. void BlowFish::encrypt (uint32& data1,
  2521. uint32& data2) const
  2522. {
  2523. uint32 l = data1;
  2524. uint32 r = data2;
  2525. for (int i = 0; i < 16; ++i)
  2526. {
  2527. l = l ^ p[i];
  2528. r = F (l) ^ r;
  2529. const uint32 temp = l;
  2530. l = r;
  2531. r = temp;
  2532. }
  2533. const uint32 temp = l;
  2534. l = r;
  2535. r = temp;
  2536. r = r ^ p[16];
  2537. l = l ^ p[17];
  2538. data1 = l;
  2539. data2 = r;
  2540. }
  2541. void BlowFish::decrypt (uint32& data1,
  2542. uint32& data2) const
  2543. {
  2544. uint32 l = data1;
  2545. uint32 r = data2;
  2546. for (int i = 17; i > 1; --i)
  2547. {
  2548. l =l ^ p[i];
  2549. r = F (l) ^ r;
  2550. const uint32 temp = l;
  2551. l = r;
  2552. r = temp;
  2553. }
  2554. const uint32 temp = l;
  2555. l = r;
  2556. r = temp;
  2557. r = r ^ p[1];
  2558. l = l ^ p[0];
  2559. data1 = l;
  2560. data2 = r;
  2561. }
  2562. END_JUCE_NAMESPACE
  2563. /********* End of inlined file: juce_BlowFish.cpp *********/
  2564. /********* Start of inlined file: juce_MD5.cpp *********/
  2565. BEGIN_JUCE_NAMESPACE
  2566. MD5::MD5()
  2567. {
  2568. zeromem (result, sizeof (result));
  2569. }
  2570. MD5::MD5 (const MD5& other)
  2571. {
  2572. memcpy (result, other.result, sizeof (result));
  2573. }
  2574. const MD5& MD5::operator= (const MD5& other)
  2575. {
  2576. memcpy (result, other.result, sizeof (result));
  2577. return *this;
  2578. }
  2579. MD5::MD5 (const MemoryBlock& data)
  2580. {
  2581. ProcessContext context;
  2582. context.processBlock ((const uint8*) data.getData(), data.getSize());
  2583. context.finish (result);
  2584. }
  2585. MD5::MD5 (const char* data, const int numBytes)
  2586. {
  2587. ProcessContext context;
  2588. context.processBlock ((const uint8*) data, numBytes);
  2589. context.finish (result);
  2590. }
  2591. MD5::MD5 (const String& text)
  2592. {
  2593. ProcessContext context;
  2594. const int len = text.length();
  2595. const juce_wchar* const t = text;
  2596. for (int i = 0; i < len; ++i)
  2597. {
  2598. // force the string into integer-sized unicode characters, to try to make it
  2599. // get the same results on all platforms + compilers.
  2600. uint32 unicodeChar = (uint32) t[i];
  2601. swapIfBigEndian (unicodeChar);
  2602. context.processBlock ((const uint8*) &unicodeChar,
  2603. sizeof (unicodeChar));
  2604. }
  2605. context.finish (result);
  2606. }
  2607. void MD5::processStream (InputStream& input, int numBytesToRead)
  2608. {
  2609. ProcessContext context;
  2610. if (numBytesToRead < 0)
  2611. numBytesToRead = INT_MAX;
  2612. while (numBytesToRead > 0)
  2613. {
  2614. char tempBuffer [512];
  2615. const int bytesRead = input.read (tempBuffer, jmin (numBytesToRead, sizeof (tempBuffer)));
  2616. if (bytesRead <= 0)
  2617. break;
  2618. numBytesToRead -= bytesRead;
  2619. context.processBlock ((const uint8*) tempBuffer, bytesRead);
  2620. }
  2621. context.finish (result);
  2622. }
  2623. MD5::MD5 (InputStream& input, int numBytesToRead)
  2624. {
  2625. processStream (input, numBytesToRead);
  2626. }
  2627. MD5::MD5 (const File& file)
  2628. {
  2629. FileInputStream* const fin = file.createInputStream();
  2630. if (fin != 0)
  2631. {
  2632. processStream (*fin, -1);
  2633. delete fin;
  2634. }
  2635. else
  2636. {
  2637. zeromem (result, sizeof (result));
  2638. }
  2639. }
  2640. MD5::~MD5()
  2641. {
  2642. }
  2643. MD5::ProcessContext::ProcessContext()
  2644. {
  2645. state[0] = 0x67452301;
  2646. state[1] = 0xefcdab89;
  2647. state[2] = 0x98badcfe;
  2648. state[3] = 0x10325476;
  2649. count[0] = 0;
  2650. count[1] = 0;
  2651. }
  2652. void MD5::ProcessContext::processBlock (const uint8* const data, int dataSize)
  2653. {
  2654. int bufferPos = ((count[0] >> 3) & 0x3F);
  2655. count[0] += (dataSize << 3);
  2656. if (count[0] < ((uint32) dataSize << 3))
  2657. count[1]++;
  2658. count[1] += (dataSize >> 29);
  2659. const int spaceLeft = 64 - bufferPos;
  2660. int i = 0;
  2661. if (dataSize >= spaceLeft)
  2662. {
  2663. memcpy (buffer + bufferPos, data, spaceLeft);
  2664. transform (buffer);
  2665. i = spaceLeft;
  2666. while (i < dataSize - 63)
  2667. {
  2668. transform (data + i);
  2669. i += 64;
  2670. }
  2671. bufferPos = 0;
  2672. }
  2673. memcpy (buffer + bufferPos, data + i, dataSize - i);
  2674. }
  2675. static void encode (uint8* const output,
  2676. const uint32* const input,
  2677. const int numBytes)
  2678. {
  2679. uint32* const o = (uint32*) output;
  2680. for (int i = 0; i < (numBytes >> 2); ++i)
  2681. o[i] = swapIfBigEndian (input [i]);
  2682. }
  2683. static void decode (uint32* const output,
  2684. const uint8* const input,
  2685. const int numBytes)
  2686. {
  2687. for (int i = 0; i < (numBytes >> 2); ++i)
  2688. output[i] = littleEndianInt ((const char*) input + (i << 2));
  2689. }
  2690. void MD5::ProcessContext::finish (uint8* const result)
  2691. {
  2692. unsigned char encodedLength[8];
  2693. encode (encodedLength, count, 8);
  2694. // Pad out to 56 mod 64.
  2695. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  2696. const int paddingLength = (index < 56) ? (56 - index)
  2697. : (120 - index);
  2698. uint8 paddingBuffer [64];
  2699. zeromem (paddingBuffer, paddingLength);
  2700. paddingBuffer [0] = 0x80;
  2701. processBlock (paddingBuffer, paddingLength);
  2702. processBlock (encodedLength, 8);
  2703. encode (result, state, 16);
  2704. zeromem (buffer, sizeof (buffer));
  2705. }
  2706. #define S11 7
  2707. #define S12 12
  2708. #define S13 17
  2709. #define S14 22
  2710. #define S21 5
  2711. #define S22 9
  2712. #define S23 14
  2713. #define S24 20
  2714. #define S31 4
  2715. #define S32 11
  2716. #define S33 16
  2717. #define S34 23
  2718. #define S41 6
  2719. #define S42 10
  2720. #define S43 15
  2721. #define S44 21
  2722. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) { return (x & y) | (~x & z); }
  2723. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) { return (x & z) | (y & ~z); }
  2724. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) { return x ^ y ^ z; }
  2725. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) { return y ^ (x | ~z); }
  2726. static inline uint32 rotateLeft (const uint32 x, const uint32 n) { return (x << n) | (x >> (32 - n)); }
  2727. static inline void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  2728. {
  2729. a += F (b, c, d) + x + ac;
  2730. a = rotateLeft (a, s) + b;
  2731. }
  2732. static inline void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  2733. {
  2734. a += G (b, c, d) + x + ac;
  2735. a = rotateLeft (a, s) + b;
  2736. }
  2737. static inline void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  2738. {
  2739. a += H (b, c, d) + x + ac;
  2740. a = rotateLeft (a, s) + b;
  2741. }
  2742. static inline void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  2743. {
  2744. a += I (b, c, d) + x + ac;
  2745. a = rotateLeft (a, s) + b;
  2746. }
  2747. void MD5::ProcessContext::transform (const uint8* const buffer)
  2748. {
  2749. uint32 a = state[0];
  2750. uint32 b = state[1];
  2751. uint32 c = state[2];
  2752. uint32 d = state[3];
  2753. uint32 x[16];
  2754. decode (x, buffer, 64);
  2755. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
  2756. FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
  2757. FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
  2758. FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
  2759. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
  2760. FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
  2761. FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
  2762. FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
  2763. FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
  2764. FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
  2765. FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
  2766. FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
  2767. FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
  2768. FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
  2769. FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
  2770. FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
  2771. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
  2772. GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
  2773. GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
  2774. GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
  2775. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
  2776. GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
  2777. GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
  2778. GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
  2779. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
  2780. GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
  2781. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
  2782. GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
  2783. GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
  2784. GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
  2785. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
  2786. GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
  2787. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
  2788. HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
  2789. HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
  2790. HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
  2791. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
  2792. HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
  2793. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
  2794. HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
  2795. HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
  2796. HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
  2797. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
  2798. HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
  2799. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
  2800. HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
  2801. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
  2802. HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
  2803. II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
  2804. II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
  2805. II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
  2806. II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
  2807. II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
  2808. II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
  2809. II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
  2810. II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
  2811. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
  2812. II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
  2813. II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
  2814. II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
  2815. II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
  2816. II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
  2817. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
  2818. II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
  2819. state[0] += a;
  2820. state[1] += b;
  2821. state[2] += c;
  2822. state[3] += d;
  2823. zeromem (x, sizeof (x));
  2824. }
  2825. const MemoryBlock MD5::getRawChecksumData() const
  2826. {
  2827. return MemoryBlock (result, 16);
  2828. }
  2829. const String MD5::toHexString() const
  2830. {
  2831. return String::toHexString (result, 16, 0);
  2832. }
  2833. bool MD5::operator== (const MD5& other) const
  2834. {
  2835. return memcmp (result, other.result, 16) == 0;
  2836. }
  2837. bool MD5::operator!= (const MD5& other) const
  2838. {
  2839. return ! operator== (other);
  2840. }
  2841. END_JUCE_NAMESPACE
  2842. /********* End of inlined file: juce_MD5.cpp *********/
  2843. /********* Start of inlined file: juce_Primes.cpp *********/
  2844. BEGIN_JUCE_NAMESPACE
  2845. static void createSmallSieve (const int numBits, BitArray& result) throw()
  2846. {
  2847. result.setBit (numBits);
  2848. result.clearBit (numBits); // to enlarge the array
  2849. result.setBit (0);
  2850. int n = 2;
  2851. do
  2852. {
  2853. for (int i = n + n; i < numBits; i += n)
  2854. result.setBit (i);
  2855. n = result.findNextClearBit (n + 1);
  2856. }
  2857. while (n <= (numBits >> 1));
  2858. }
  2859. static void bigSieve (const BitArray& base,
  2860. const int numBits,
  2861. BitArray& result,
  2862. const BitArray& smallSieve,
  2863. const int smallSieveSize) throw()
  2864. {
  2865. jassert (! base[0]); // must be even!
  2866. result.setBit (numBits);
  2867. result.clearBit (numBits); // to enlarge the array
  2868. int index = smallSieve.findNextClearBit (0);
  2869. do
  2870. {
  2871. const int prime = (index << 1) + 1;
  2872. BitArray r (base);
  2873. BitArray remainder;
  2874. r.divideBy (prime, remainder);
  2875. int i = prime - remainder.getBitRangeAsInt (0, 32);
  2876. if (r.isEmpty())
  2877. i += prime;
  2878. if ((i & 1) == 0)
  2879. i += prime;
  2880. i = (i - 1) >> 1;
  2881. while (i < numBits)
  2882. {
  2883. result.setBit (i);
  2884. i += prime;
  2885. }
  2886. index = smallSieve.findNextClearBit (index + 1);
  2887. }
  2888. while (index < smallSieveSize);
  2889. }
  2890. static bool findCandidate (const BitArray& base,
  2891. const BitArray& sieve,
  2892. const int numBits,
  2893. BitArray& result,
  2894. const int certainty) throw()
  2895. {
  2896. for (int i = 0; i < numBits; ++i)
  2897. {
  2898. if (! sieve[i])
  2899. {
  2900. result = base;
  2901. result.add (BitArray ((unsigned int) ((i << 1) + 1)));
  2902. if (Primes::isProbablyPrime (result, certainty))
  2903. return true;
  2904. }
  2905. }
  2906. return false;
  2907. }
  2908. const BitArray Primes::createProbablePrime (const int bitLength,
  2909. const int certainty) throw()
  2910. {
  2911. BitArray smallSieve;
  2912. const int smallSieveSize = 15000;
  2913. createSmallSieve (smallSieveSize, smallSieve);
  2914. BitArray p;
  2915. p.fillBitsRandomly (0, bitLength);
  2916. p.setBit (bitLength - 1);
  2917. p.clearBit (0);
  2918. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  2919. while (p.getHighestBit() < bitLength)
  2920. {
  2921. p.add (2 * searchLen);
  2922. BitArray sieve;
  2923. bigSieve (p, searchLen, sieve,
  2924. smallSieve, smallSieveSize);
  2925. BitArray candidate;
  2926. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  2927. return candidate;
  2928. }
  2929. jassertfalse
  2930. return BitArray();
  2931. }
  2932. static bool passesMillerRabin (const BitArray& n, int iterations) throw()
  2933. {
  2934. const BitArray one (1);
  2935. const BitArray two (2);
  2936. BitArray nMinusOne (n);
  2937. nMinusOne.subtract (one);
  2938. BitArray d (nMinusOne);
  2939. const int s = d.findNextSetBit (0);
  2940. d.shiftBits (-s);
  2941. BitArray smallPrimes;
  2942. int numBitsInSmallPrimes = 0;
  2943. for (;;)
  2944. {
  2945. numBitsInSmallPrimes += 256;
  2946. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  2947. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  2948. if (numPrimesFound > iterations + 1)
  2949. break;
  2950. }
  2951. int smallPrime = 2;
  2952. while (--iterations >= 0)
  2953. {
  2954. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  2955. BitArray r (smallPrime);
  2956. //r.createRandomNumber (nMinusOne);
  2957. r.exponentModulo (d, n);
  2958. if (! (r == one || r == nMinusOne))
  2959. {
  2960. for (int j = 0; j < s; ++j)
  2961. {
  2962. r.exponentModulo (two, n);
  2963. if (r == nMinusOne)
  2964. break;
  2965. }
  2966. if (r != nMinusOne)
  2967. return false;
  2968. }
  2969. }
  2970. return true;
  2971. }
  2972. bool Primes::isProbablyPrime (const BitArray& number,
  2973. const int certainty) throw()
  2974. {
  2975. if (! number[0])
  2976. return false;
  2977. if (number.getHighestBit() <= 10)
  2978. {
  2979. const int num = number.getBitRangeAsInt (0, 10);
  2980. for (int i = num / 2; --i > 1;)
  2981. if (num % i == 0)
  2982. return false;
  2983. return true;
  2984. }
  2985. else
  2986. {
  2987. const BitArray screen (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23);
  2988. if (number.findGreatestCommonDivisor (screen) != BitArray (1))
  2989. return false;
  2990. return passesMillerRabin (number, certainty);
  2991. }
  2992. }
  2993. END_JUCE_NAMESPACE
  2994. /********* End of inlined file: juce_Primes.cpp *********/
  2995. /********* Start of inlined file: juce_RSAKey.cpp *********/
  2996. BEGIN_JUCE_NAMESPACE
  2997. RSAKey::RSAKey() throw()
  2998. {
  2999. }
  3000. RSAKey::RSAKey (const String& s) throw()
  3001. {
  3002. if (s.containsChar (T(',')))
  3003. {
  3004. part1.parseString (s.upToFirstOccurrenceOf (T(","), false, false), 16);
  3005. part2.parseString (s.fromFirstOccurrenceOf (T(","), false, false), 16);
  3006. }
  3007. else
  3008. {
  3009. // the string needs to be two hex numbers, comma-separated..
  3010. jassertfalse;
  3011. }
  3012. }
  3013. RSAKey::~RSAKey() throw()
  3014. {
  3015. }
  3016. const String RSAKey::toString() const throw()
  3017. {
  3018. return part1.toString (16) + T(",") + part2.toString (16);
  3019. }
  3020. bool RSAKey::applyToValue (BitArray& value) const throw()
  3021. {
  3022. if (part1.isEmpty() || part2.isEmpty()
  3023. || value.compare (0) <= 0)
  3024. {
  3025. jassertfalse // using an uninitialised key
  3026. value.clear();
  3027. return false;
  3028. }
  3029. BitArray result;
  3030. while (! value.isEmpty())
  3031. {
  3032. result.multiplyBy (part2);
  3033. BitArray remainder;
  3034. value.divideBy (part2, remainder);
  3035. remainder.exponentModulo (part1, part2);
  3036. result.add (remainder);
  3037. }
  3038. value = result;
  3039. return true;
  3040. }
  3041. static const BitArray findBestCommonDivisor (const BitArray& p,
  3042. const BitArray& q) throw()
  3043. {
  3044. const BitArray one (1);
  3045. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  3046. // are fast to divide + multiply
  3047. for (int i = 2; i <= 65536; i *= 2)
  3048. {
  3049. const BitArray e (1 + i);
  3050. if (e.findGreatestCommonDivisor (p) == one
  3051. && e.findGreatestCommonDivisor (q) == one)
  3052. {
  3053. return e;
  3054. }
  3055. }
  3056. BitArray e (4);
  3057. while (! (e.findGreatestCommonDivisor (p) == one
  3058. && e.findGreatestCommonDivisor (q) == one))
  3059. {
  3060. e.add (one);
  3061. }
  3062. return e;
  3063. }
  3064. void RSAKey::createKeyPair (RSAKey& publicKey,
  3065. RSAKey& privateKey,
  3066. const int numBits) throw()
  3067. {
  3068. jassert (numBits > 16); // not much point using less than this..
  3069. BitArray p (Primes::createProbablePrime (numBits / 2, 30));
  3070. BitArray q (Primes::createProbablePrime (numBits - numBits / 2, 30));
  3071. BitArray n (p);
  3072. n.multiplyBy (q); // n = pq
  3073. const BitArray one (1);
  3074. p.subtract (one);
  3075. q.subtract (one);
  3076. BitArray m (p);
  3077. m.multiplyBy (q); // m = (p - 1)(q - 1)
  3078. const BitArray e (findBestCommonDivisor (p, q));
  3079. BitArray d (e);
  3080. d.inverseModulo (m);
  3081. publicKey.part1 = e;
  3082. publicKey.part2 = n;
  3083. privateKey.part1 = d;
  3084. privateKey.part2 = n;
  3085. }
  3086. END_JUCE_NAMESPACE
  3087. /********* End of inlined file: juce_RSAKey.cpp *********/
  3088. /********* Start of inlined file: juce_InputStream.cpp *********/
  3089. BEGIN_JUCE_NAMESPACE
  3090. char InputStream::readByte()
  3091. {
  3092. char temp = 0;
  3093. read (&temp, 1);
  3094. return temp;
  3095. }
  3096. bool InputStream::readBool()
  3097. {
  3098. return readByte() != 0;
  3099. }
  3100. short InputStream::readShort()
  3101. {
  3102. char temp [2];
  3103. if (read (temp, 2) == 2)
  3104. return (short) littleEndianShort (temp);
  3105. else
  3106. return 0;
  3107. }
  3108. short InputStream::readShortBigEndian()
  3109. {
  3110. char temp [2];
  3111. if (read (temp, 2) == 2)
  3112. return (short) bigEndianShort (temp);
  3113. else
  3114. return 0;
  3115. }
  3116. int InputStream::readInt()
  3117. {
  3118. char temp [4];
  3119. if (read (temp, 4) == 4)
  3120. return (int) littleEndianInt (temp);
  3121. else
  3122. return 0;
  3123. }
  3124. int InputStream::readIntBigEndian()
  3125. {
  3126. char temp [4];
  3127. if (read (temp, 4) == 4)
  3128. return (int) bigEndianInt (temp);
  3129. else
  3130. return 0;
  3131. }
  3132. int InputStream::readCompressedInt()
  3133. {
  3134. int num = 0;
  3135. if (! isExhausted())
  3136. {
  3137. unsigned char numBytes = readByte();
  3138. const bool negative = (numBytes & 0x80) != 0;
  3139. numBytes &= 0x7f;
  3140. if (numBytes <= 4)
  3141. {
  3142. if (read (&num, numBytes) != numBytes)
  3143. return 0;
  3144. if (negative)
  3145. num = -num;
  3146. }
  3147. }
  3148. return num;
  3149. }
  3150. int64 InputStream::readInt64()
  3151. {
  3152. char temp [8];
  3153. if (read (temp, 8) == 8)
  3154. return (int64) swapIfBigEndian (*(uint64*)temp);
  3155. else
  3156. return 0;
  3157. }
  3158. int64 InputStream::readInt64BigEndian()
  3159. {
  3160. char temp [8];
  3161. if (read (temp, 8) == 8)
  3162. return (int64) swapIfLittleEndian (*(uint64*)temp);
  3163. else
  3164. return 0;
  3165. }
  3166. float InputStream::readFloat()
  3167. {
  3168. union { int asInt; float asFloat; } n;
  3169. n.asInt = readInt();
  3170. return n.asFloat;
  3171. }
  3172. float InputStream::readFloatBigEndian()
  3173. {
  3174. union { int asInt; float asFloat; } n;
  3175. n.asInt = readIntBigEndian();
  3176. return n.asFloat;
  3177. }
  3178. double InputStream::readDouble()
  3179. {
  3180. union { int64 asInt; double asDouble; } n;
  3181. n.asInt = readInt64();
  3182. return n.asDouble;
  3183. }
  3184. double InputStream::readDoubleBigEndian()
  3185. {
  3186. union { int64 asInt; double asDouble; } n;
  3187. n.asInt = readInt64BigEndian();
  3188. return n.asDouble;
  3189. }
  3190. const String InputStream::readString()
  3191. {
  3192. const int tempBufferSize = 256;
  3193. uint8 temp [tempBufferSize];
  3194. int i = 0;
  3195. while ((temp [i++] = readByte()) != 0)
  3196. {
  3197. if (i == tempBufferSize)
  3198. {
  3199. // too big for our quick buffer, so read it in blocks..
  3200. String result (String::fromUTF8 (temp, i));
  3201. i = 0;
  3202. for (;;)
  3203. {
  3204. if ((temp [i++] = readByte()) == 0)
  3205. {
  3206. result += String::fromUTF8 (temp, i - 1);
  3207. break;
  3208. }
  3209. else if (i == tempBufferSize)
  3210. {
  3211. result += String::fromUTF8 (temp, i);
  3212. i = 0;
  3213. }
  3214. }
  3215. return result;
  3216. }
  3217. }
  3218. return String::fromUTF8 (temp, i - 1);
  3219. }
  3220. const String InputStream::readNextLine()
  3221. {
  3222. String s;
  3223. const int maxChars = 256;
  3224. tchar buffer [maxChars];
  3225. int charsInBuffer = 0;
  3226. while (! isExhausted())
  3227. {
  3228. const uint8 c = readByte();
  3229. const int64 lastPos = getPosition();
  3230. if (c == '\n')
  3231. {
  3232. break;
  3233. }
  3234. else if (c == '\r')
  3235. {
  3236. if (readByte() != '\n')
  3237. setPosition (lastPos);
  3238. break;
  3239. }
  3240. buffer [charsInBuffer++] = c;
  3241. if (charsInBuffer == maxChars)
  3242. {
  3243. s.append (buffer, maxChars);
  3244. charsInBuffer = 0;
  3245. }
  3246. }
  3247. if (charsInBuffer > 0)
  3248. s.append (buffer, charsInBuffer);
  3249. return s;
  3250. }
  3251. int InputStream::readIntoMemoryBlock (MemoryBlock& block,
  3252. int numBytes)
  3253. {
  3254. const int64 totalLength = getTotalLength();
  3255. if (totalLength >= 0)
  3256. {
  3257. const int totalBytesRemaining = (int) jmin ((int64) 0x7fffffff,
  3258. totalLength - getPosition());
  3259. if (numBytes < 0)
  3260. numBytes = totalBytesRemaining;
  3261. else if (numBytes > 0)
  3262. numBytes = jmin (numBytes, totalBytesRemaining);
  3263. else
  3264. return 0;
  3265. }
  3266. const int originalBlockSize = block.getSize();
  3267. int totalBytesRead = 0;
  3268. if (numBytes > 0)
  3269. {
  3270. // know how many bytes we want, so we can resize the block first..
  3271. block.setSize (originalBlockSize + numBytes, false);
  3272. totalBytesRead = read (((char*) block.getData()) + originalBlockSize, numBytes);
  3273. }
  3274. else
  3275. {
  3276. // read until end of stram..
  3277. const int chunkSize = 32768;
  3278. for (;;)
  3279. {
  3280. block.ensureSize (originalBlockSize + totalBytesRead + chunkSize, false);
  3281. const int bytesJustIn = read (((char*) block.getData())
  3282. + originalBlockSize
  3283. + totalBytesRead,
  3284. chunkSize);
  3285. if (bytesJustIn == 0)
  3286. break;
  3287. totalBytesRead += bytesJustIn;
  3288. }
  3289. }
  3290. // trim off any excess left at the end
  3291. block.setSize (originalBlockSize + totalBytesRead, false);
  3292. return totalBytesRead;
  3293. }
  3294. const String InputStream::readEntireStreamAsString()
  3295. {
  3296. MemoryBlock mb;
  3297. const int size = readIntoMemoryBlock (mb);
  3298. return String::createStringFromData ((const char*) mb.getData(), size);
  3299. }
  3300. void InputStream::skipNextBytes (int64 numBytesToSkip)
  3301. {
  3302. if (numBytesToSkip > 0)
  3303. {
  3304. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  3305. MemoryBlock temp (skipBufferSize);
  3306. while ((numBytesToSkip > 0) && ! isExhausted())
  3307. {
  3308. numBytesToSkip -= read (temp.getData(), (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  3309. }
  3310. }
  3311. }
  3312. END_JUCE_NAMESPACE
  3313. /********* End of inlined file: juce_InputStream.cpp *********/
  3314. /********* Start of inlined file: juce_OutputStream.cpp *********/
  3315. BEGIN_JUCE_NAMESPACE
  3316. #if JUCE_DEBUG
  3317. static CriticalSection activeStreamLock;
  3318. static VoidArray activeStreams;
  3319. void juce_CheckForDanglingStreams()
  3320. {
  3321. /*
  3322. It's always a bad idea to leak any object, but if you're leaking output
  3323. streams, then there's a good chance that you're failing to flush a file
  3324. to disk properly, which could result in corrupted data and other similar
  3325. nastiness..
  3326. */
  3327. jassert (activeStreams.size() == 0);
  3328. };
  3329. #endif
  3330. OutputStream::OutputStream() throw()
  3331. {
  3332. #if JUCE_DEBUG
  3333. activeStreamLock.enter();
  3334. activeStreams.add (this);
  3335. activeStreamLock.exit();
  3336. #endif
  3337. }
  3338. OutputStream::~OutputStream()
  3339. {
  3340. #if JUCE_DEBUG
  3341. activeStreamLock.enter();
  3342. activeStreams.removeValue (this);
  3343. activeStreamLock.exit();
  3344. #endif
  3345. }
  3346. void OutputStream::writeBool (bool b)
  3347. {
  3348. writeByte ((b) ? (char) 1
  3349. : (char) 0);
  3350. }
  3351. void OutputStream::writeByte (char byte)
  3352. {
  3353. write (&byte, 1);
  3354. }
  3355. void OutputStream::writeShort (short value)
  3356. {
  3357. const unsigned short v = swapIfBigEndian ((unsigned short) value);
  3358. write (&v, 2);
  3359. }
  3360. void OutputStream::writeShortBigEndian (short value)
  3361. {
  3362. const unsigned short v = swapIfLittleEndian ((unsigned short) value);
  3363. write (&v, 2);
  3364. }
  3365. void OutputStream::writeInt (int value)
  3366. {
  3367. const unsigned int v = swapIfBigEndian ((unsigned int) value);
  3368. write (&v, 4);
  3369. }
  3370. void OutputStream::writeIntBigEndian (int value)
  3371. {
  3372. const unsigned int v = swapIfLittleEndian ((unsigned int) value);
  3373. write (&v, 4);
  3374. }
  3375. void OutputStream::writeCompressedInt (int value)
  3376. {
  3377. unsigned int un = (value < 0) ? (unsigned int) -value
  3378. : (unsigned int) value;
  3379. unsigned int tn = un;
  3380. int numSigBytes = 0;
  3381. do
  3382. {
  3383. tn >>= 8;
  3384. numSigBytes++;
  3385. } while (tn & 0xff);
  3386. if (value < 0)
  3387. numSigBytes |= 0x80;
  3388. writeByte ((char) numSigBytes);
  3389. write (&un, numSigBytes);
  3390. }
  3391. void OutputStream::writeInt64 (int64 value)
  3392. {
  3393. const uint64 v = swapIfBigEndian ((uint64) value);
  3394. write (&v, 8);
  3395. }
  3396. void OutputStream::writeInt64BigEndian (int64 value)
  3397. {
  3398. const uint64 v = swapIfLittleEndian ((uint64) value);
  3399. write (&v, 8);
  3400. }
  3401. void OutputStream::writeFloat (float value)
  3402. {
  3403. union { int asInt; float asFloat; } n;
  3404. n.asFloat = value;
  3405. writeInt (n.asInt);
  3406. }
  3407. void OutputStream::writeFloatBigEndian (float value)
  3408. {
  3409. union { int asInt; float asFloat; } n;
  3410. n.asFloat = value;
  3411. writeIntBigEndian (n.asInt);
  3412. }
  3413. void OutputStream::writeDouble (double value)
  3414. {
  3415. union { int64 asInt; double asDouble; } n;
  3416. n.asDouble = value;
  3417. writeInt64 (n.asInt);
  3418. }
  3419. void OutputStream::writeDoubleBigEndian (double value)
  3420. {
  3421. union { int64 asInt; double asDouble; } n;
  3422. n.asDouble = value;
  3423. writeInt64BigEndian (n.asInt);
  3424. }
  3425. void OutputStream::writeString (const String& text)
  3426. {
  3427. const int numBytes = text.copyToUTF8 (0);
  3428. uint8* const temp = (uint8*) juce_malloc (numBytes);
  3429. text.copyToUTF8 (temp);
  3430. write (temp, numBytes); // (numBytes includes the terminating null).
  3431. juce_free (temp);
  3432. }
  3433. void OutputStream::printf (const char* pf, ...)
  3434. {
  3435. unsigned int bufSize = 256;
  3436. char* buf = (char*) juce_malloc (bufSize);
  3437. for (;;)
  3438. {
  3439. va_list list;
  3440. va_start (list, pf);
  3441. const int num = CharacterFunctions::vprintf (buf, bufSize, pf, list);
  3442. va_end (list);
  3443. if (num > 0)
  3444. {
  3445. write (buf, num);
  3446. break;
  3447. }
  3448. else if (num == 0)
  3449. {
  3450. break;
  3451. }
  3452. juce_free (buf);
  3453. bufSize += 256;
  3454. buf = (char*) juce_malloc (bufSize);
  3455. }
  3456. juce_free (buf);
  3457. }
  3458. OutputStream& OutputStream::operator<< (const int number)
  3459. {
  3460. const String s (number);
  3461. write ((const char*) s, s.length());
  3462. return *this;
  3463. }
  3464. OutputStream& OutputStream::operator<< (const double number)
  3465. {
  3466. const String s (number);
  3467. write ((const char*) s, s.length());
  3468. return *this;
  3469. }
  3470. OutputStream& OutputStream::operator<< (const char character)
  3471. {
  3472. writeByte (character);
  3473. return *this;
  3474. }
  3475. OutputStream& OutputStream::operator<< (const char* const text)
  3476. {
  3477. write (text, (int) strlen (text));
  3478. return *this;
  3479. }
  3480. OutputStream& OutputStream::operator<< (const juce_wchar* const text)
  3481. {
  3482. const String s (text);
  3483. write ((const char*) s, s.length());
  3484. return *this;
  3485. }
  3486. OutputStream& OutputStream::operator<< (const String& text)
  3487. {
  3488. write ((const char*) text,
  3489. text.length());
  3490. return *this;
  3491. }
  3492. void OutputStream::writeText (const String& text,
  3493. const bool asUnicode,
  3494. const bool writeUnicodeHeaderBytes)
  3495. {
  3496. if (asUnicode)
  3497. {
  3498. if (writeUnicodeHeaderBytes)
  3499. write ("\x0ff\x0fe", 2);
  3500. const juce_wchar* src = (const juce_wchar*) text;
  3501. bool lastCharWasReturn = false;
  3502. while (*src != 0)
  3503. {
  3504. if (*src == L'\n' && ! lastCharWasReturn)
  3505. writeShort ((short) L'\r');
  3506. lastCharWasReturn = (*src == L'\r');
  3507. writeShort ((short) *src++);
  3508. }
  3509. }
  3510. else
  3511. {
  3512. const char* src = (const char*) text;
  3513. const char* t = src;
  3514. for (;;)
  3515. {
  3516. if (*t == '\n')
  3517. {
  3518. if (t > src)
  3519. write (src, (int) (t - src));
  3520. write ("\r\n", 2);
  3521. src = t + 1;
  3522. }
  3523. else if (*t == '\r')
  3524. {
  3525. if (t[1] == '\n')
  3526. ++t;
  3527. }
  3528. else if (*t == 0)
  3529. {
  3530. if (t > src)
  3531. write (src, (int) (t - src));
  3532. break;
  3533. }
  3534. ++t;
  3535. }
  3536. }
  3537. }
  3538. int OutputStream::writeFromInputStream (InputStream& source,
  3539. int numBytesToWrite)
  3540. {
  3541. if (numBytesToWrite < 0)
  3542. numBytesToWrite = 0x7fffffff;
  3543. int numWritten = 0;
  3544. while (numBytesToWrite > 0 && ! source.isExhausted())
  3545. {
  3546. char buffer [8192];
  3547. const int num = source.read (buffer, jmin (numBytesToWrite, sizeof (buffer)));
  3548. if (num == 0)
  3549. break;
  3550. write (buffer, num);
  3551. numBytesToWrite -= num;
  3552. numWritten += num;
  3553. }
  3554. return numWritten;
  3555. }
  3556. END_JUCE_NAMESPACE
  3557. /********* End of inlined file: juce_OutputStream.cpp *********/
  3558. /********* Start of inlined file: juce_DirectoryIterator.cpp *********/
  3559. BEGIN_JUCE_NAMESPACE
  3560. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  3561. bool* isDirectory, bool* isHidden, int64* fileSize,
  3562. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  3563. bool juce_findFileNext (void* handle, String& resultFile,
  3564. bool* isDirectory, bool* isHidden, int64* fileSize,
  3565. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  3566. void juce_findFileClose (void* handle) throw();
  3567. DirectoryIterator::DirectoryIterator (const File& directory,
  3568. bool isRecursive,
  3569. const String& wc,
  3570. const int whatToLookFor_) throw()
  3571. : wildCard (wc),
  3572. index (-1),
  3573. whatToLookFor (whatToLookFor_),
  3574. subIterator (0)
  3575. {
  3576. // you have to specify the type of files you're looking for!
  3577. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  3578. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  3579. String path (directory.getFullPathName());
  3580. if (! path.endsWithChar (File::separator))
  3581. path += File::separator;
  3582. String filename;
  3583. bool isDirectory, isHidden;
  3584. void* const handle = juce_findFileStart (path,
  3585. isRecursive ? T("*") : wc,
  3586. filename, &isDirectory, &isHidden, 0, 0, 0, 0);
  3587. if (handle != 0)
  3588. {
  3589. do
  3590. {
  3591. if (! filename.containsOnly (T(".")))
  3592. {
  3593. bool addToList = false;
  3594. if (isDirectory)
  3595. {
  3596. if (isRecursive
  3597. && ((whatToLookFor_ & File::ignoreHiddenFiles) == 0
  3598. || ! isHidden))
  3599. {
  3600. dirsFound.add (new File (path + filename, 0));
  3601. }
  3602. addToList = (whatToLookFor_ & File::findDirectories) != 0;
  3603. }
  3604. else
  3605. {
  3606. addToList = (whatToLookFor_ & File::findFiles) != 0;
  3607. }
  3608. // if it's recursive, we're not relying on the OS iterator
  3609. // to do the wildcard match, so do it now..
  3610. if (isRecursive && addToList)
  3611. addToList = filename.matchesWildcard (wc, true);
  3612. if (addToList && (whatToLookFor_ & File::ignoreHiddenFiles) != 0)
  3613. addToList = ! isHidden;
  3614. if (addToList)
  3615. filesFound.add (new File (path + filename, 0));
  3616. }
  3617. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  3618. juce_findFileClose (handle);
  3619. }
  3620. }
  3621. DirectoryIterator::~DirectoryIterator() throw()
  3622. {
  3623. if (subIterator != 0)
  3624. delete subIterator;
  3625. }
  3626. bool DirectoryIterator::next() throw()
  3627. {
  3628. if (subIterator != 0)
  3629. {
  3630. if (subIterator->next())
  3631. return true;
  3632. deleteAndZero (subIterator);
  3633. }
  3634. if (index >= filesFound.size() + dirsFound.size() - 1)
  3635. return false;
  3636. ++index;
  3637. if (index >= filesFound.size())
  3638. {
  3639. subIterator = new DirectoryIterator (*(dirsFound [index - filesFound.size()]),
  3640. true, wildCard, whatToLookFor);
  3641. return next();
  3642. }
  3643. return true;
  3644. }
  3645. const File DirectoryIterator::getFile() const throw()
  3646. {
  3647. if (subIterator != 0)
  3648. return subIterator->getFile();
  3649. const File* const f = filesFound [index];
  3650. return (f != 0) ? *f
  3651. : File::nonexistent;
  3652. }
  3653. float DirectoryIterator::getEstimatedProgress() const throw()
  3654. {
  3655. if (filesFound.size() + dirsFound.size() == 0)
  3656. {
  3657. return 0.0f;
  3658. }
  3659. else
  3660. {
  3661. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  3662. : (float) index;
  3663. return detailedIndex / (filesFound.size() + dirsFound.size());
  3664. }
  3665. }
  3666. END_JUCE_NAMESPACE
  3667. /********* End of inlined file: juce_DirectoryIterator.cpp *********/
  3668. /********* Start of inlined file: juce_File.cpp *********/
  3669. #ifdef _MSC_VER
  3670. #pragma warning (disable: 4514)
  3671. #pragma warning (push)
  3672. #endif
  3673. #ifndef JUCE_WIN32
  3674. #include <pwd.h>
  3675. #endif
  3676. BEGIN_JUCE_NAMESPACE
  3677. #ifdef _MSC_VER
  3678. #pragma warning (pop)
  3679. #endif
  3680. void* juce_fileOpen (const String& path, bool forWriting) throw();
  3681. void juce_fileClose (void* handle) throw();
  3682. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  3683. int64 juce_fileGetPosition (void* handle) throw();
  3684. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  3685. void juce_fileFlush (void* handle) throw();
  3686. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw();
  3687. bool juce_isDirectory (const String& fileName) throw();
  3688. int64 juce_getFileSize (const String& fileName) throw();
  3689. bool juce_canWriteToFile (const String& fileName) throw();
  3690. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw();
  3691. void juce_getFileTimes (const String& fileName, int64& modificationTime, int64& accessTime, int64& creationTime) throw();
  3692. bool juce_setFileTimes (const String& fileName, int64 modificationTime, int64 accessTime, int64 creationTime) throw();
  3693. bool juce_deleteFile (const String& fileName) throw();
  3694. bool juce_copyFile (const String& source, const String& dest) throw();
  3695. bool juce_moveFile (const String& source, const String& dest) throw();
  3696. // this must also create all paths involved in the directory.
  3697. void juce_createDirectory (const String& fileName) throw();
  3698. bool juce_launchFile (const String& fileName, const String& parameters) throw();
  3699. const StringArray juce_getFileSystemRoots() throw();
  3700. const String juce_getVolumeLabel (const String& filenameOnVolume, int& volumeSerialNumber) throw();
  3701. // starts a directory search operation with a wildcard, returning a handle for
  3702. // use in calls to juce_findFileNext.
  3703. // juce_firstResultFile gets the name of the file (not the whole pathname) and
  3704. // the other pointers, if non-null, are set based on the properties of the file.
  3705. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  3706. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  3707. Time* creationTime, bool* isReadOnly) throw();
  3708. // returns false when no more files are found
  3709. bool juce_findFileNext (void* handle, String& resultFile,
  3710. bool* isDirectory, bool* isHidden, int64* fileSize,
  3711. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  3712. void juce_findFileClose (void* handle) throw();
  3713. static const String parseAbsolutePath (String path) throw()
  3714. {
  3715. if (path.isEmpty())
  3716. return String::empty;
  3717. #if JUCE_WIN32
  3718. // Windows..
  3719. path = path.replaceCharacter (T('/'), T('\\')).unquoted();
  3720. if (path.startsWithChar (File::separator))
  3721. {
  3722. if (path[1] != File::separator)
  3723. {
  3724. jassertfalse // using a filename that starts with a slash is a bit dodgy on
  3725. // Windows, because it needs a drive letter, which in this case
  3726. // we'll take from the CWD.. but this is a bit of an assumption that
  3727. // could be wrong..
  3728. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  3729. }
  3730. }
  3731. else if (path.indexOfChar (T(':')) < 0)
  3732. {
  3733. if (path.isEmpty())
  3734. return String::empty;
  3735. jassertfalse // using a partial filename is a bad way to initialise a file, because
  3736. // we don't know what directory to put it in.
  3737. // Here we'll assume it's in the CWD, but this might not be what was
  3738. // intended..
  3739. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  3740. }
  3741. #else
  3742. // Mac or Linux..
  3743. path = path.replaceCharacter (T('\\'), T('/')).unquoted();
  3744. if (path.startsWithChar (T('~')))
  3745. {
  3746. const char* homeDir = 0;
  3747. if (path[1] == File::separator || path[1] == 0)
  3748. {
  3749. // expand a name of the form "~/abc"
  3750. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  3751. + path.substring (1);
  3752. }
  3753. else
  3754. {
  3755. // expand a name of type "~dave/abc"
  3756. const String userName (path.substring (1)
  3757. .upToFirstOccurrenceOf (T("/"), false, false));
  3758. struct passwd* const pw = getpwnam (userName);
  3759. if (pw != 0)
  3760. {
  3761. String home (homeDir);
  3762. if (home.endsWithChar (File::separator))
  3763. home [home.length() - 1] = 0;
  3764. path = String (pw->pw_dir)
  3765. + path.substring (userName.length());
  3766. }
  3767. }
  3768. }
  3769. else if (! path.startsWithChar (File::separator))
  3770. {
  3771. while (path.startsWith (T("./")))
  3772. path = path.substring (2);
  3773. if (path.isEmpty())
  3774. return String::empty;
  3775. jassertfalse // using a partial filename is a bad way to initialise a file, because
  3776. // we don't know what directory to put it in.
  3777. // Here we'll assume it's in the CWD, but this might not be what was
  3778. // intended..
  3779. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  3780. }
  3781. #endif
  3782. int len = path.length();
  3783. while (--len > 0 && path [len] == File::separator)
  3784. path [len] = 0;
  3785. return path;
  3786. }
  3787. const File File::nonexistent;
  3788. File::File (const String& fullPathName) throw()
  3789. : fullPath (parseAbsolutePath (fullPathName))
  3790. {
  3791. }
  3792. File::File (const String& path, int) throw()
  3793. : fullPath (path)
  3794. {
  3795. }
  3796. File::File (const File& other) throw()
  3797. : fullPath (other.fullPath)
  3798. {
  3799. }
  3800. const File& File::operator= (const String& newPath) throw()
  3801. {
  3802. fullPath = parseAbsolutePath (newPath);
  3803. return *this;
  3804. }
  3805. const File& File::operator= (const File& other) throw()
  3806. {
  3807. fullPath = other.fullPath;
  3808. return *this;
  3809. }
  3810. #if JUCE_LINUX
  3811. #define NAMES_ARE_CASE_SENSITIVE 1
  3812. #endif
  3813. bool File::areFileNamesCaseSensitive()
  3814. {
  3815. #if NAMES_ARE_CASE_SENSITIVE
  3816. return true;
  3817. #else
  3818. return false;
  3819. #endif
  3820. }
  3821. bool File::operator== (const File& other) const throw()
  3822. {
  3823. // case-insensitive on Windows, but not on linux.
  3824. #if NAMES_ARE_CASE_SENSITIVE
  3825. return fullPath == other.fullPath;
  3826. #else
  3827. return fullPath.equalsIgnoreCase (other.fullPath);
  3828. #endif
  3829. }
  3830. bool File::operator!= (const File& other) const throw()
  3831. {
  3832. return ! operator== (other);
  3833. }
  3834. bool File::exists() const throw()
  3835. {
  3836. return juce_fileExists (fullPath, false);
  3837. }
  3838. bool File::existsAsFile() const throw()
  3839. {
  3840. return juce_fileExists (fullPath, true);
  3841. }
  3842. bool File::isDirectory() const throw()
  3843. {
  3844. return juce_isDirectory (fullPath);
  3845. }
  3846. bool File::hasWriteAccess() const throw()
  3847. {
  3848. if (exists())
  3849. return juce_canWriteToFile (fullPath);
  3850. #ifndef JUCE_WIN32
  3851. else if ((! isDirectory()) && fullPath.containsChar (separator))
  3852. return getParentDirectory().hasWriteAccess();
  3853. else
  3854. return false;
  3855. #else
  3856. // on windows, it seems that even read-only directories can still be written into,
  3857. // so checking the parent directory's permissions would return the wrong result..
  3858. else
  3859. return true;
  3860. #endif
  3861. }
  3862. bool File::setReadOnly (const bool shouldBeReadOnly,
  3863. const bool applyRecursively) const throw()
  3864. {
  3865. bool worked = true;
  3866. if (applyRecursively && isDirectory())
  3867. {
  3868. OwnedArray <File> subFiles;
  3869. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  3870. for (int i = subFiles.size(); --i >= 0;)
  3871. worked = subFiles[i]->setReadOnly (shouldBeReadOnly, true) && worked;
  3872. }
  3873. return juce_setFileReadOnly (fullPath, shouldBeReadOnly) && worked;
  3874. }
  3875. bool File::deleteFile() const throw()
  3876. {
  3877. return (! exists())
  3878. || juce_deleteFile (fullPath);
  3879. }
  3880. bool File::deleteRecursively() const throw()
  3881. {
  3882. bool worked = true;
  3883. if (isDirectory())
  3884. {
  3885. OwnedArray<File> subFiles;
  3886. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  3887. for (int i = subFiles.size(); --i >= 0;)
  3888. worked = subFiles[i]->deleteRecursively() && worked;
  3889. }
  3890. return deleteFile() && worked;
  3891. }
  3892. bool File::moveFileTo (const File& newFile) const throw()
  3893. {
  3894. if (newFile.fullPath == fullPath)
  3895. return true;
  3896. #if ! NAMES_ARE_CASE_SENSITIVE
  3897. if (*this != newFile)
  3898. #endif
  3899. if (! newFile.deleteFile())
  3900. return false;
  3901. return juce_moveFile (fullPath, newFile.fullPath);
  3902. }
  3903. bool File::copyFileTo (const File& newFile) const throw()
  3904. {
  3905. if (*this == newFile)
  3906. return true;
  3907. if (! newFile.deleteFile())
  3908. return false;
  3909. return juce_copyFile (fullPath, newFile.fullPath);
  3910. }
  3911. bool File::copyDirectoryTo (const File& newDirectory) const throw()
  3912. {
  3913. if (isDirectory() && newDirectory.createDirectory())
  3914. {
  3915. OwnedArray<File> subFiles;
  3916. findChildFiles (subFiles, File::findFiles, false);
  3917. int i;
  3918. for (i = 0; i < subFiles.size(); ++i)
  3919. if (! subFiles[i]->copyFileTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  3920. return false;
  3921. subFiles.clear();
  3922. findChildFiles (subFiles, File::findDirectories, false);
  3923. for (i = 0; i < subFiles.size(); ++i)
  3924. if (! subFiles[i]->copyDirectoryTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  3925. return false;
  3926. return true;
  3927. }
  3928. return false;
  3929. }
  3930. const String File::getPathUpToLastSlash() const throw()
  3931. {
  3932. const int lastSlash = fullPath.lastIndexOfChar (separator);
  3933. if (lastSlash > 0)
  3934. return fullPath.substring (0, lastSlash);
  3935. else if (lastSlash == 0)
  3936. return separatorString;
  3937. else
  3938. return fullPath;
  3939. }
  3940. const File File::getParentDirectory() const throw()
  3941. {
  3942. return File (getPathUpToLastSlash());
  3943. }
  3944. const String File::getFileName() const throw()
  3945. {
  3946. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  3947. }
  3948. int File::hashCode() const throw()
  3949. {
  3950. return fullPath.hashCode();
  3951. }
  3952. int64 File::hashCode64() const throw()
  3953. {
  3954. return fullPath.hashCode64();
  3955. }
  3956. const String File::getFileNameWithoutExtension() const throw()
  3957. {
  3958. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  3959. const int lastDot = fullPath.lastIndexOfChar (T('.'));
  3960. if (lastDot > lastSlash)
  3961. return fullPath.substring (lastSlash, lastDot);
  3962. else
  3963. return fullPath.substring (lastSlash);
  3964. }
  3965. bool File::isAChildOf (const File& potentialParent) const throw()
  3966. {
  3967. const String ourPath (getPathUpToLastSlash());
  3968. #if NAMES_ARE_CASE_SENSITIVE
  3969. if (potentialParent.fullPath == ourPath)
  3970. #else
  3971. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  3972. #endif
  3973. {
  3974. return true;
  3975. }
  3976. else if (potentialParent.fullPath.length() >= ourPath.length())
  3977. {
  3978. return false;
  3979. }
  3980. else
  3981. {
  3982. return getParentDirectory().isAChildOf (potentialParent);
  3983. }
  3984. }
  3985. bool File::isAbsolutePath (const String& path) throw()
  3986. {
  3987. return path.startsWithChar (T('/')) || path.startsWithChar (T('\\'))
  3988. #if JUCE_WIN32
  3989. || (path.isNotEmpty() && ((const String&) path)[1] == T(':'));
  3990. #else
  3991. || path.startsWithChar (T('~'));
  3992. #endif
  3993. }
  3994. const File File::getChildFile (String relativePath) const throw()
  3995. {
  3996. if (isAbsolutePath (relativePath))
  3997. {
  3998. // the path is really absolute..
  3999. return File (relativePath);
  4000. }
  4001. else
  4002. {
  4003. // it's relative, so remove any ../ or ./ bits at the start.
  4004. String path (fullPath);
  4005. if (relativePath[0] == T('.'))
  4006. {
  4007. #if JUCE_WIN32
  4008. relativePath = relativePath.replaceCharacter (T('/'), T('\\')).trimStart();
  4009. #else
  4010. relativePath = relativePath.replaceCharacter (T('\\'), T('/')).trimStart();
  4011. #endif
  4012. while (relativePath[0] == T('.'))
  4013. {
  4014. if (relativePath[1] == T('.'))
  4015. {
  4016. if (relativePath [2] == 0 || relativePath[2] == separator)
  4017. {
  4018. const int lastSlash = path.lastIndexOfChar (separator);
  4019. if (lastSlash > 0)
  4020. path = path.substring (0, lastSlash);
  4021. relativePath = relativePath.substring (3);
  4022. }
  4023. else
  4024. {
  4025. break;
  4026. }
  4027. }
  4028. else if (relativePath[1] == separator)
  4029. {
  4030. relativePath = relativePath.substring (2);
  4031. }
  4032. else
  4033. {
  4034. break;
  4035. }
  4036. }
  4037. }
  4038. if (! path.endsWithChar (separator))
  4039. path += separator;
  4040. return File (path + relativePath);
  4041. }
  4042. }
  4043. const File File::getSiblingFile (const String& fileName) const throw()
  4044. {
  4045. return getParentDirectory().getChildFile (fileName);
  4046. }
  4047. int64 File::getSize() const throw()
  4048. {
  4049. return juce_getFileSize (fullPath);
  4050. }
  4051. const String File::descriptionOfSizeInBytes (const int64 bytes)
  4052. {
  4053. if (bytes == 1)
  4054. {
  4055. return "1 byte";
  4056. }
  4057. else if (bytes < 1024)
  4058. {
  4059. return String ((int) bytes) + " bytes";
  4060. }
  4061. else if (bytes < 1024 * 1024)
  4062. {
  4063. return String (bytes / 1024.0, 1) + " KB";
  4064. }
  4065. else if (bytes < 1024 * 1024 * 1024)
  4066. {
  4067. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  4068. }
  4069. else
  4070. {
  4071. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  4072. }
  4073. }
  4074. bool File::create() const throw()
  4075. {
  4076. if (! exists())
  4077. {
  4078. const File parentDir (getParentDirectory());
  4079. if (parentDir == *this || ! parentDir.createDirectory())
  4080. return false;
  4081. void* const fh = juce_fileOpen (fullPath, true);
  4082. if (fh == 0)
  4083. return false;
  4084. juce_fileClose (fh);
  4085. }
  4086. return true;
  4087. }
  4088. bool File::createDirectory() const throw()
  4089. {
  4090. if (! isDirectory())
  4091. {
  4092. const File parentDir (getParentDirectory());
  4093. if (parentDir == *this || ! parentDir.createDirectory())
  4094. return false;
  4095. String dir (fullPath);
  4096. while (dir.endsWithChar (separator))
  4097. dir [dir.length() - 1] = 0;
  4098. juce_createDirectory (dir);
  4099. return isDirectory();
  4100. }
  4101. return true;
  4102. }
  4103. const Time File::getCreationTime() const throw()
  4104. {
  4105. int64 m, a, c;
  4106. juce_getFileTimes (fullPath, m, a, c);
  4107. return Time (c);
  4108. }
  4109. bool File::setCreationTime (const Time& t) const throw()
  4110. {
  4111. return juce_setFileTimes (fullPath, 0, 0, t.toMilliseconds());
  4112. }
  4113. const Time File::getLastModificationTime() const throw()
  4114. {
  4115. int64 m, a, c;
  4116. juce_getFileTimes (fullPath, m, a, c);
  4117. return Time (m);
  4118. }
  4119. bool File::setLastModificationTime (const Time& t) const throw()
  4120. {
  4121. return juce_setFileTimes (fullPath, t.toMilliseconds(), 0, 0);
  4122. }
  4123. const Time File::getLastAccessTime() const throw()
  4124. {
  4125. int64 m, a, c;
  4126. juce_getFileTimes (fullPath, m, a, c);
  4127. return Time (a);
  4128. }
  4129. bool File::setLastAccessTime (const Time& t) const throw()
  4130. {
  4131. return juce_setFileTimes (fullPath, 0, t.toMilliseconds(), 0);
  4132. }
  4133. bool File::loadFileAsData (MemoryBlock& destBlock) const throw()
  4134. {
  4135. if (! existsAsFile())
  4136. return false;
  4137. FileInputStream in (*this);
  4138. return getSize() == in.readIntoMemoryBlock (destBlock);
  4139. }
  4140. const String File::loadFileAsString() const throw()
  4141. {
  4142. if (! existsAsFile())
  4143. return String::empty;
  4144. FileInputStream in (*this);
  4145. return in.readEntireStreamAsString();
  4146. }
  4147. static inline bool fileTypeMatches (const int whatToLookFor,
  4148. const bool isDir,
  4149. const bool isHidden)
  4150. {
  4151. return (whatToLookFor & (isDir ? File::findDirectories
  4152. : File::findFiles)) != 0
  4153. && ((! isHidden)
  4154. || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  4155. }
  4156. int File::findChildFiles (OwnedArray<File>& results,
  4157. const int whatToLookFor,
  4158. const bool searchRecursively,
  4159. const String& wildCardPattern) const throw()
  4160. {
  4161. // you have to specify the type of files you're looking for!
  4162. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  4163. int total = 0;
  4164. // find child files or directories in this directory first..
  4165. if (isDirectory())
  4166. {
  4167. String path (fullPath);
  4168. if (! path.endsWithChar (separator))
  4169. path += separator;
  4170. String filename;
  4171. bool isDirectory, isHidden;
  4172. void* const handle = juce_findFileStart (path,
  4173. wildCardPattern,
  4174. filename,
  4175. &isDirectory, &isHidden,
  4176. 0, 0, 0, 0);
  4177. if (handle != 0)
  4178. {
  4179. do
  4180. {
  4181. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  4182. && ! filename.containsOnly (T(".")))
  4183. {
  4184. results.add (new File (path + filename, 0));
  4185. ++total;
  4186. }
  4187. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  4188. juce_findFileClose (handle);
  4189. }
  4190. }
  4191. else
  4192. {
  4193. // trying to search for files inside a non-directory?
  4194. //jassertfalse
  4195. }
  4196. // and recurse down if required.
  4197. if (searchRecursively)
  4198. {
  4199. OwnedArray <File> subDirectories;
  4200. findChildFiles (subDirectories, File::findDirectories, false);
  4201. for (int i = 0; i < subDirectories.size(); ++i)
  4202. {
  4203. total += subDirectories.getUnchecked(i)
  4204. ->findChildFiles (results,
  4205. whatToLookFor,
  4206. true,
  4207. wildCardPattern);
  4208. }
  4209. }
  4210. return total;
  4211. }
  4212. int File::getNumberOfChildFiles (const int whatToLookFor,
  4213. const String& wildCardPattern) const throw()
  4214. {
  4215. // you have to specify the type of files you're looking for!
  4216. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  4217. int count = 0;
  4218. if (isDirectory())
  4219. {
  4220. String filename;
  4221. bool isDirectory, isHidden;
  4222. void* const handle = juce_findFileStart (fullPath,
  4223. wildCardPattern,
  4224. filename,
  4225. &isDirectory, &isHidden,
  4226. 0, 0, 0, 0);
  4227. if (handle != 0)
  4228. {
  4229. do
  4230. {
  4231. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  4232. && ! filename.containsOnly (T(".")))
  4233. {
  4234. ++count;
  4235. }
  4236. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  4237. juce_findFileClose (handle);
  4238. }
  4239. }
  4240. else
  4241. {
  4242. // trying to search for files inside a non-directory?
  4243. jassertfalse
  4244. }
  4245. return count;
  4246. }
  4247. const File File::getNonexistentChildFile (const String& prefix_,
  4248. const String& suffix,
  4249. bool putNumbersInBrackets) const throw()
  4250. {
  4251. File f (getChildFile (prefix_ + suffix));
  4252. if (f.exists())
  4253. {
  4254. int num = 2;
  4255. String prefix (prefix_);
  4256. // remove any bracketed numbers that may already be on the end..
  4257. if (prefix.trim().endsWithChar (T(')')))
  4258. {
  4259. putNumbersInBrackets = true;
  4260. const int openBracks = prefix.lastIndexOfChar (T('('));
  4261. const int closeBracks = prefix.lastIndexOfChar (T(')'));
  4262. if (openBracks > 0
  4263. && closeBracks > openBracks
  4264. && prefix.substring (openBracks + 1, closeBracks).containsOnly (T("0123456789")))
  4265. {
  4266. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  4267. prefix = prefix.substring (0, openBracks);
  4268. }
  4269. }
  4270. // also use brackets if it ends in a digit.
  4271. putNumbersInBrackets = putNumbersInBrackets
  4272. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  4273. do
  4274. {
  4275. if (putNumbersInBrackets)
  4276. f = getChildFile (prefix + T('(') + String (num++) + T(')') + suffix);
  4277. else
  4278. f = getChildFile (prefix + String (num++) + suffix);
  4279. } while (f.exists());
  4280. }
  4281. return f;
  4282. }
  4283. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const throw()
  4284. {
  4285. if (exists())
  4286. {
  4287. return getParentDirectory()
  4288. .getNonexistentChildFile (getFileNameWithoutExtension(),
  4289. getFileExtension(),
  4290. putNumbersInBrackets);
  4291. }
  4292. else
  4293. {
  4294. return *this;
  4295. }
  4296. }
  4297. const String File::getFileExtension() const throw()
  4298. {
  4299. String ext;
  4300. if (! isDirectory())
  4301. {
  4302. const int indexOfDot = fullPath.lastIndexOfChar (T('.'));
  4303. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  4304. ext = fullPath.substring (indexOfDot);
  4305. }
  4306. return ext;
  4307. }
  4308. bool File::hasFileExtension (const String& possibleSuffix) const throw()
  4309. {
  4310. if (possibleSuffix.isEmpty())
  4311. return fullPath.lastIndexOfChar (T('.')) <= fullPath.lastIndexOfChar (separator);
  4312. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  4313. {
  4314. if (possibleSuffix.startsWithChar (T('.')))
  4315. return true;
  4316. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  4317. if (dotPos >= 0)
  4318. return fullPath [dotPos] == T('.');
  4319. }
  4320. return false;
  4321. }
  4322. const File File::withFileExtension (const String& newExtension) const throw()
  4323. {
  4324. if (fullPath.isEmpty())
  4325. return File::nonexistent;
  4326. String filePart (getFileName());
  4327. int i = filePart.lastIndexOfChar (T('.'));
  4328. if (i < 0)
  4329. i = filePart.length();
  4330. String newExt (newExtension);
  4331. if (newExt.isNotEmpty() && ! newExt.startsWithChar (T('.')))
  4332. newExt = T(".") + newExt;
  4333. return getSiblingFile (filePart.substring (0, i) + newExt);
  4334. }
  4335. bool File::startAsProcess (const String& parameters) const throw()
  4336. {
  4337. return exists()
  4338. && juce_launchFile (fullPath, parameters);
  4339. }
  4340. FileInputStream* File::createInputStream() const throw()
  4341. {
  4342. if (existsAsFile())
  4343. return new FileInputStream (*this);
  4344. else
  4345. return 0;
  4346. }
  4347. FileOutputStream* File::createOutputStream (const int bufferSize) const throw()
  4348. {
  4349. FileOutputStream* const out = new FileOutputStream (*this, bufferSize);
  4350. if (out->failedToOpen())
  4351. {
  4352. delete out;
  4353. return 0;
  4354. }
  4355. else
  4356. {
  4357. return out;
  4358. }
  4359. }
  4360. bool File::appendData (const void* const dataToAppend,
  4361. const int numberOfBytes) const throw()
  4362. {
  4363. if (numberOfBytes > 0)
  4364. {
  4365. FileOutputStream* const out = createOutputStream();
  4366. if (out == 0)
  4367. return false;
  4368. out->write (dataToAppend, numberOfBytes);
  4369. delete out;
  4370. }
  4371. return true;
  4372. }
  4373. bool File::replaceWithData (const void* const dataToWrite,
  4374. const int numberOfBytes) const throw()
  4375. {
  4376. jassert (numberOfBytes >= 0); // a negative number of bytes??
  4377. if (numberOfBytes <= 0)
  4378. return deleteFile();
  4379. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  4380. if (tempFile.appendData (dataToWrite, numberOfBytes)
  4381. && tempFile.moveFileTo (*this))
  4382. {
  4383. return true;
  4384. }
  4385. tempFile.deleteFile();
  4386. return false;
  4387. }
  4388. bool File::appendText (const String& text,
  4389. const bool asUnicode,
  4390. const bool writeUnicodeHeaderBytes) const throw()
  4391. {
  4392. FileOutputStream* const out = createOutputStream();
  4393. if (out != 0)
  4394. {
  4395. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  4396. delete out;
  4397. return true;
  4398. }
  4399. return false;
  4400. }
  4401. bool File::printf (const tchar* pf, ...) const throw()
  4402. {
  4403. va_list list;
  4404. va_start (list, pf);
  4405. String text;
  4406. text.vprintf (pf, list);
  4407. return appendData ((const char*) text, text.length());
  4408. }
  4409. bool File::replaceWithText (const String& textToWrite,
  4410. const bool asUnicode,
  4411. const bool writeUnicodeHeaderBytes) const throw()
  4412. {
  4413. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  4414. if (tempFile.appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes)
  4415. && tempFile.moveFileTo (*this))
  4416. {
  4417. return true;
  4418. }
  4419. tempFile.deleteFile();
  4420. return false;
  4421. }
  4422. const String File::createLegalPathName (const String& original) throw()
  4423. {
  4424. String s (original);
  4425. String start;
  4426. if (s[1] == T(':'))
  4427. {
  4428. start = s.substring (0, 2);
  4429. s = s.substring (2);
  4430. }
  4431. return start + s.removeCharacters (T("\"#@,;:<>*^|?"))
  4432. .substring (0, 1024);
  4433. }
  4434. const String File::createLegalFileName (const String& original) throw()
  4435. {
  4436. String s (original.removeCharacters (T("\"#@,;:<>*^|?\\/")));
  4437. const int maxLength = 128; // only the length of the filename, not the whole path
  4438. const int len = s.length();
  4439. if (len > maxLength)
  4440. {
  4441. const int lastDot = s.lastIndexOfChar (T('.'));
  4442. if (lastDot > jmax (0, len - 12))
  4443. {
  4444. s = s.substring (0, maxLength - (len - lastDot))
  4445. + s.substring (lastDot);
  4446. }
  4447. else
  4448. {
  4449. s = s.substring (0, maxLength);
  4450. }
  4451. }
  4452. return s;
  4453. }
  4454. const String File::getRelativePathFrom (const File& dir) const throw()
  4455. {
  4456. String thisPath (fullPath);
  4457. {
  4458. int len = thisPath.length();
  4459. while (--len >= 0 && thisPath [len] == File::separator)
  4460. thisPath [len] = 0;
  4461. }
  4462. String dirPath ((dir.existsAsFile()) ? dir.getParentDirectory().getFullPathName()
  4463. : dir.fullPath);
  4464. if (! dirPath.endsWithChar (separator))
  4465. dirPath += separator;
  4466. const int len = jmin (thisPath.length(), dirPath.length());
  4467. int commonBitLength = 0;
  4468. for (int i = 0; i < len; ++i)
  4469. {
  4470. #if NAMES_ARE_CASE_SENSITIVE
  4471. if (thisPath[i] != dirPath[i])
  4472. #else
  4473. if (CharacterFunctions::toLowerCase (thisPath[i])
  4474. != CharacterFunctions::toLowerCase (dirPath[i]))
  4475. #endif
  4476. {
  4477. break;
  4478. }
  4479. ++commonBitLength;
  4480. }
  4481. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  4482. --commonBitLength;
  4483. // if the only common bit is the root, then just return the full path..
  4484. #if JUCE_WIN32
  4485. if (commonBitLength <= 0
  4486. || (commonBitLength == 1 && thisPath [1] == File::separator)
  4487. || (commonBitLength <= 3 && thisPath [1] == T(':')))
  4488. #else
  4489. if (commonBitLength <= 0
  4490. || (commonBitLength == 1 && thisPath [1] == File::separator))
  4491. #endif
  4492. return fullPath;
  4493. thisPath = thisPath.substring (commonBitLength);
  4494. dirPath = dirPath.substring (commonBitLength);
  4495. while (dirPath.isNotEmpty())
  4496. {
  4497. #if JUCE_WIN32
  4498. thisPath = T("..\\") + thisPath;
  4499. #else
  4500. thisPath = T("../") + thisPath;
  4501. #endif
  4502. const int sep = dirPath.indexOfChar (separator);
  4503. if (sep >= 0)
  4504. dirPath = dirPath.substring (sep + 1);
  4505. else
  4506. dirPath = String::empty;
  4507. }
  4508. return thisPath;
  4509. }
  4510. void File::findFileSystemRoots (OwnedArray<File>& destArray) throw()
  4511. {
  4512. const StringArray roots (juce_getFileSystemRoots());
  4513. for (int i = 0; i < roots.size(); ++i)
  4514. destArray.add (new File (roots[i]));
  4515. }
  4516. const String File::getVolumeLabel() const throw()
  4517. {
  4518. int serialNum;
  4519. return juce_getVolumeLabel (fullPath, serialNum);
  4520. }
  4521. int File::getVolumeSerialNumber() const throw()
  4522. {
  4523. int serialNum;
  4524. juce_getVolumeLabel (fullPath, serialNum);
  4525. return serialNum;
  4526. }
  4527. const File File::createTempFile (const String& fileNameEnding) throw()
  4528. {
  4529. String tempName (T("temp"));
  4530. static int tempNum = 0;
  4531. tempName << tempNum++ << fileNameEnding;
  4532. const File tempFile (getSpecialLocation (tempDirectory)
  4533. .getChildFile (tempName));
  4534. if (tempFile.exists())
  4535. return createTempFile (fileNameEnding);
  4536. else
  4537. return tempFile;
  4538. }
  4539. END_JUCE_NAMESPACE
  4540. /********* End of inlined file: juce_File.cpp *********/
  4541. /********* Start of inlined file: juce_FileInputStream.cpp *********/
  4542. BEGIN_JUCE_NAMESPACE
  4543. void* juce_fileOpen (const String& path, bool forWriting) throw();
  4544. void juce_fileClose (void* handle) throw();
  4545. int juce_fileRead (void* handle, void* buffer, int size) throw();
  4546. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  4547. FileInputStream::FileInputStream (const File& f)
  4548. : file (f),
  4549. currentPosition (0),
  4550. needToSeek (true)
  4551. {
  4552. totalSize = f.getSize();
  4553. fileHandle = juce_fileOpen (f.getFullPathName(), false);
  4554. }
  4555. FileInputStream::~FileInputStream()
  4556. {
  4557. juce_fileClose (fileHandle);
  4558. }
  4559. int64 FileInputStream::getTotalLength()
  4560. {
  4561. return totalSize;
  4562. }
  4563. int FileInputStream::read (void* buffer, int bytesToRead)
  4564. {
  4565. int num = 0;
  4566. if (needToSeek)
  4567. {
  4568. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  4569. return 0;
  4570. needToSeek = false;
  4571. }
  4572. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  4573. currentPosition += num;
  4574. return num;
  4575. }
  4576. bool FileInputStream::isExhausted()
  4577. {
  4578. return currentPosition >= totalSize;
  4579. }
  4580. int64 FileInputStream::getPosition()
  4581. {
  4582. return currentPosition;
  4583. }
  4584. bool FileInputStream::setPosition (int64 pos)
  4585. {
  4586. pos = jlimit ((int64) 0, totalSize, pos);
  4587. needToSeek |= (currentPosition != pos);
  4588. currentPosition = pos;
  4589. return true;
  4590. }
  4591. END_JUCE_NAMESPACE
  4592. /********* End of inlined file: juce_FileInputStream.cpp *********/
  4593. /********* Start of inlined file: juce_FileOutputStream.cpp *********/
  4594. BEGIN_JUCE_NAMESPACE
  4595. void* juce_fileOpen (const String& path, bool forWriting) throw();
  4596. void juce_fileClose (void* handle) throw();
  4597. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  4598. void juce_fileFlush (void* handle) throw();
  4599. int64 juce_fileGetPosition (void* handle) throw();
  4600. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  4601. FileOutputStream::FileOutputStream (const File& f,
  4602. const int bufferSize_)
  4603. : file (f),
  4604. bufferSize (bufferSize_),
  4605. bytesInBuffer (0)
  4606. {
  4607. fileHandle = juce_fileOpen (f.getFullPathName(), true);
  4608. if (fileHandle != 0)
  4609. {
  4610. currentPosition = juce_fileGetPosition (fileHandle);
  4611. if (currentPosition < 0)
  4612. {
  4613. jassertfalse
  4614. juce_fileClose (fileHandle);
  4615. fileHandle = 0;
  4616. }
  4617. }
  4618. buffer = (char*) juce_malloc (jmax (bufferSize_, 16));
  4619. }
  4620. FileOutputStream::~FileOutputStream()
  4621. {
  4622. flush();
  4623. juce_fileClose (fileHandle);
  4624. juce_free (buffer);
  4625. }
  4626. int64 FileOutputStream::getPosition()
  4627. {
  4628. return currentPosition;
  4629. }
  4630. bool FileOutputStream::setPosition (int64 newPosition)
  4631. {
  4632. if (newPosition != currentPosition)
  4633. {
  4634. flush();
  4635. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  4636. }
  4637. return newPosition == currentPosition;
  4638. }
  4639. void FileOutputStream::flush()
  4640. {
  4641. if (bytesInBuffer > 0)
  4642. {
  4643. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  4644. bytesInBuffer = 0;
  4645. }
  4646. juce_fileFlush (fileHandle);
  4647. }
  4648. bool FileOutputStream::write (const void* const src, const int numBytes)
  4649. {
  4650. if (bytesInBuffer + numBytes < bufferSize)
  4651. {
  4652. memcpy (buffer + bytesInBuffer, src, numBytes);
  4653. bytesInBuffer += numBytes;
  4654. currentPosition += numBytes;
  4655. }
  4656. else
  4657. {
  4658. if (bytesInBuffer > 0)
  4659. {
  4660. // flush the reservoir
  4661. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  4662. bytesInBuffer = 0;
  4663. if (! wroteOk)
  4664. return false;
  4665. }
  4666. if (numBytes < bufferSize)
  4667. {
  4668. memcpy (buffer + bytesInBuffer, src, numBytes);
  4669. bytesInBuffer += numBytes;
  4670. currentPosition += numBytes;
  4671. }
  4672. else
  4673. {
  4674. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  4675. currentPosition += bytesWritten;
  4676. return bytesWritten == numBytes;
  4677. }
  4678. }
  4679. return true;
  4680. }
  4681. END_JUCE_NAMESPACE
  4682. /********* End of inlined file: juce_FileOutputStream.cpp *********/
  4683. /********* Start of inlined file: juce_FileSearchPath.cpp *********/
  4684. BEGIN_JUCE_NAMESPACE
  4685. FileSearchPath::FileSearchPath()
  4686. {
  4687. }
  4688. FileSearchPath::FileSearchPath (const String& path)
  4689. {
  4690. init (path);
  4691. }
  4692. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  4693. : directories (other.directories)
  4694. {
  4695. }
  4696. FileSearchPath::~FileSearchPath()
  4697. {
  4698. }
  4699. const FileSearchPath& FileSearchPath::operator= (const String& path)
  4700. {
  4701. init (path);
  4702. return *this;
  4703. }
  4704. void FileSearchPath::init (const String& path)
  4705. {
  4706. directories.clear();
  4707. directories.addTokens (path, T(";"), T("\""));
  4708. directories.trim();
  4709. directories.removeEmptyStrings();
  4710. for (int i = directories.size(); --i >= 0;)
  4711. directories.set (i, directories[i].unquoted());
  4712. }
  4713. int FileSearchPath::getNumPaths() const
  4714. {
  4715. return directories.size();
  4716. }
  4717. const File FileSearchPath::operator[] (const int index) const
  4718. {
  4719. return File (directories [index]);
  4720. }
  4721. const String FileSearchPath::toString() const
  4722. {
  4723. StringArray directories2 (directories);
  4724. for (int i = directories2.size(); --i >= 0;)
  4725. if (directories2[i].containsChar (T(';')))
  4726. directories2.set (i, directories2[i].quoted());
  4727. return directories2.joinIntoString (T(";"));
  4728. }
  4729. void FileSearchPath::add (const File& dir, const int insertIndex)
  4730. {
  4731. directories.insert (insertIndex, dir.getFullPathName());
  4732. }
  4733. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  4734. {
  4735. for (int i = 0; i < directories.size(); ++i)
  4736. if (File (directories[i]) == dir)
  4737. return;
  4738. add (dir);
  4739. }
  4740. void FileSearchPath::remove (const int index)
  4741. {
  4742. directories.remove (index);
  4743. }
  4744. void FileSearchPath::addPath (const FileSearchPath& other)
  4745. {
  4746. for (int i = 0; i < other.getNumPaths(); ++i)
  4747. addIfNotAlreadyThere (other[i]);
  4748. }
  4749. void FileSearchPath::removeRedundantPaths()
  4750. {
  4751. for (int i = directories.size(); --i >= 0;)
  4752. {
  4753. const File d1 (directories[i]);
  4754. for (int j = directories.size(); --j >= 0;)
  4755. {
  4756. const File d2 (directories[j]);
  4757. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  4758. {
  4759. directories.remove (i);
  4760. break;
  4761. }
  4762. }
  4763. }
  4764. }
  4765. void FileSearchPath::removeNonExistentPaths()
  4766. {
  4767. for (int i = directories.size(); --i >= 0;)
  4768. if (! File (directories[i]).isDirectory())
  4769. directories.remove (i);
  4770. }
  4771. int FileSearchPath::findChildFiles (OwnedArray<File>& results,
  4772. const int whatToLookFor,
  4773. const bool searchRecursively,
  4774. const String& wildCardPattern) const
  4775. {
  4776. int total = 0;
  4777. for (int i = 0; i < directories.size(); ++i)
  4778. total += operator[] (i).findChildFiles (results,
  4779. whatToLookFor,
  4780. searchRecursively,
  4781. wildCardPattern);
  4782. return total;
  4783. }
  4784. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  4785. const bool checkRecursively) const
  4786. {
  4787. for (int i = directories.size(); --i >= 0;)
  4788. {
  4789. const File d (directories[i]);
  4790. if (checkRecursively)
  4791. {
  4792. if (fileToCheck.isAChildOf (d))
  4793. return true;
  4794. }
  4795. else
  4796. {
  4797. if (fileToCheck.getParentDirectory() == d)
  4798. return true;
  4799. }
  4800. }
  4801. return false;
  4802. }
  4803. END_JUCE_NAMESPACE
  4804. /********* End of inlined file: juce_FileSearchPath.cpp *********/
  4805. /********* Start of inlined file: juce_NamedPipe.cpp *********/
  4806. BEGIN_JUCE_NAMESPACE
  4807. NamedPipe::NamedPipe()
  4808. : internal (0)
  4809. {
  4810. }
  4811. NamedPipe::~NamedPipe()
  4812. {
  4813. close();
  4814. }
  4815. bool NamedPipe::openExisting (const String& pipeName)
  4816. {
  4817. currentPipeName = pipeName;
  4818. return openInternal (pipeName, false);
  4819. }
  4820. bool NamedPipe::createNewPipe (const String& pipeName)
  4821. {
  4822. currentPipeName = pipeName;
  4823. return openInternal (pipeName, true);
  4824. }
  4825. bool NamedPipe::isOpen() const throw()
  4826. {
  4827. return internal != 0;
  4828. }
  4829. const String NamedPipe::getName() const throw()
  4830. {
  4831. return currentPipeName;
  4832. }
  4833. // other methods for this class are implemented in the platform-specific files
  4834. END_JUCE_NAMESPACE
  4835. /********* End of inlined file: juce_NamedPipe.cpp *********/
  4836. /********* Start of inlined file: juce_Socket.cpp *********/
  4837. #ifdef _WIN32
  4838. #include <winsock2.h>
  4839. #ifdef _MSC_VER
  4840. #pragma warning (disable : 4127 4389 4018)
  4841. #endif
  4842. #else
  4843. #ifndef LINUX
  4844. #include <Carbon/Carbon.h>
  4845. #endif
  4846. #include <sys/types.h>
  4847. #include <netdb.h>
  4848. #include <sys/socket.h>
  4849. #include <arpa/inet.h>
  4850. #include <sys/errno.h>
  4851. #include <netinet/tcp.h>
  4852. #include <netinet/in.h>
  4853. #include <fcntl.h>
  4854. #include <unistd.h>
  4855. #endif
  4856. BEGIN_JUCE_NAMESPACE
  4857. #if JUCE_WIN32
  4858. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  4859. juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  4860. static void initWin32Sockets()
  4861. {
  4862. static CriticalSection lock;
  4863. const ScopedLock sl (lock);
  4864. if (juce_CloseWin32SocketLib == 0)
  4865. {
  4866. WSADATA wsaData;
  4867. const WORD wVersionRequested = MAKEWORD (1, 1);
  4868. WSAStartup (wVersionRequested, &wsaData);
  4869. juce_CloseWin32SocketLib = &WSACleanup;
  4870. }
  4871. }
  4872. #endif
  4873. static bool resetSocketOptions (const int handle, const bool isDatagram) throw()
  4874. {
  4875. if (handle <= 0)
  4876. return false;
  4877. const int sndBufSize = 65536;
  4878. const int rcvBufSize = 65536;
  4879. const int one = 1;
  4880. return setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (int)) == 0
  4881. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (int)) == 0
  4882. && (isDatagram || (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (int)) == 0));
  4883. }
  4884. static bool bindSocketToPort (const int handle, const int port) throw()
  4885. {
  4886. if (handle == 0 || port <= 0)
  4887. return false;
  4888. struct sockaddr_in servTmpAddr;
  4889. zerostruct (servTmpAddr);
  4890. servTmpAddr.sin_family = PF_INET;
  4891. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  4892. servTmpAddr.sin_port = htons ((uint16) port);
  4893. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  4894. }
  4895. static int readSocket (const int handle,
  4896. void* const destBuffer, const int maxBytesToRead,
  4897. bool volatile& connected) throw()
  4898. {
  4899. int bytesRead = 0;
  4900. while (bytesRead < maxBytesToRead)
  4901. {
  4902. int bytesThisTime;
  4903. #if JUCE_WIN32
  4904. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  4905. #else
  4906. while ((bytesThisTime = ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  4907. && errno == EINTR
  4908. && connected)
  4909. {
  4910. }
  4911. #endif
  4912. if (bytesThisTime <= 0 || ! connected)
  4913. {
  4914. if (bytesRead == 0)
  4915. bytesRead = -1;
  4916. break;
  4917. }
  4918. bytesRead += bytesThisTime;
  4919. }
  4920. return bytesRead;
  4921. }
  4922. static int waitForReadiness (const int handle, const bool forReading,
  4923. const int timeoutMsecs) throw()
  4924. {
  4925. struct timeval timeout;
  4926. struct timeval* timeoutp;
  4927. if (timeoutMsecs >= 0)
  4928. {
  4929. timeout.tv_sec = timeoutMsecs / 1000;
  4930. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  4931. timeoutp = &timeout;
  4932. }
  4933. else
  4934. {
  4935. timeoutp = 0;
  4936. }
  4937. fd_set rset, wset;
  4938. FD_ZERO (&rset);
  4939. FD_SET (handle, &rset);
  4940. FD_ZERO (&wset);
  4941. FD_SET (handle, &wset);
  4942. fd_set* const prset = forReading ? &rset : 0;
  4943. fd_set* const pwset = forReading ? 0 : &wset;
  4944. #if JUCE_WIN32
  4945. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  4946. return -1;
  4947. #else
  4948. {
  4949. int result;
  4950. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  4951. && errno == EINTR)
  4952. {
  4953. }
  4954. if (result < 0)
  4955. return -1;
  4956. }
  4957. #endif
  4958. {
  4959. int opt;
  4960. #if defined (JUCE_LINUX) || (defined (JUCE_MAC) && ! MACOS_10_2_OR_EARLIER)
  4961. socklen_t len = sizeof (opt);
  4962. #else
  4963. int len = sizeof (opt);
  4964. #endif
  4965. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  4966. || opt != 0)
  4967. return -1;
  4968. }
  4969. if ((forReading && FD_ISSET (handle, &rset))
  4970. || ((! forReading) && FD_ISSET (handle, &wset)))
  4971. return 1;
  4972. return 0;
  4973. }
  4974. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  4975. {
  4976. #if JUCE_WIN32
  4977. u_long nonBlocking = shouldBlock ? 0 : 1;
  4978. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  4979. return false;
  4980. #else
  4981. int socketFlags = fcntl (handle, F_GETFL, 0);
  4982. if (socketFlags == -1)
  4983. return false;
  4984. if (shouldBlock)
  4985. socketFlags &= ~O_NONBLOCK;
  4986. else
  4987. socketFlags |= O_NONBLOCK;
  4988. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  4989. return false;
  4990. #endif
  4991. return true;
  4992. }
  4993. static bool connectSocket (int volatile& handle,
  4994. const bool isDatagram,
  4995. void** serverAddress,
  4996. const String& hostName,
  4997. const int portNumber,
  4998. const int timeOutMillisecs) throw()
  4999. {
  5000. struct hostent* const hostEnt = gethostbyname (hostName);
  5001. if (hostEnt == 0)
  5002. return false;
  5003. struct in_addr targetAddress;
  5004. memcpy (&targetAddress.s_addr,
  5005. *(hostEnt->h_addr_list),
  5006. sizeof (targetAddress.s_addr));
  5007. struct sockaddr_in servTmpAddr;
  5008. zerostruct (servTmpAddr);
  5009. servTmpAddr.sin_family = PF_INET;
  5010. servTmpAddr.sin_addr = targetAddress;
  5011. servTmpAddr.sin_port = htons ((uint16) portNumber);
  5012. if (handle < 0)
  5013. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  5014. if (handle < 0)
  5015. return false;
  5016. if (isDatagram)
  5017. {
  5018. *serverAddress = new struct sockaddr_in();
  5019. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  5020. return true;
  5021. }
  5022. setSocketBlockingState (handle, false);
  5023. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  5024. if (result < 0)
  5025. {
  5026. #if JUCE_WIN32
  5027. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  5028. #else
  5029. if (errno == EINPROGRESS)
  5030. #endif
  5031. {
  5032. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  5033. {
  5034. setSocketBlockingState (handle, true);
  5035. return false;
  5036. }
  5037. }
  5038. }
  5039. setSocketBlockingState (handle, true);
  5040. resetSocketOptions (handle, false);
  5041. return true;
  5042. }
  5043. StreamingSocket::StreamingSocket()
  5044. : portNumber (0),
  5045. handle (-1),
  5046. connected (false),
  5047. isListener (false)
  5048. {
  5049. #if JUCE_WIN32
  5050. initWin32Sockets();
  5051. #endif
  5052. }
  5053. StreamingSocket::StreamingSocket (const String& hostName_,
  5054. const int portNumber_,
  5055. const int handle_)
  5056. : hostName (hostName_),
  5057. portNumber (portNumber_),
  5058. handle (handle_),
  5059. connected (true),
  5060. isListener (false)
  5061. {
  5062. #if JUCE_WIN32
  5063. initWin32Sockets();
  5064. #endif
  5065. resetSocketOptions (handle_, false);
  5066. }
  5067. StreamingSocket::~StreamingSocket()
  5068. {
  5069. close();
  5070. }
  5071. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead)
  5072. {
  5073. return (connected && ! isListener) ? readSocket (handle, destBuffer, maxBytesToRead, connected)
  5074. : -1;
  5075. }
  5076. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  5077. {
  5078. if (isListener || ! connected)
  5079. return -1;
  5080. #if JUCE_WIN32
  5081. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  5082. #else
  5083. int result;
  5084. while ((result = ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  5085. && errno == EINTR)
  5086. {
  5087. }
  5088. return result;
  5089. #endif
  5090. }
  5091. int StreamingSocket::waitUntilReady (const bool readyForReading,
  5092. const int timeoutMsecs) const
  5093. {
  5094. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  5095. : -1;
  5096. }
  5097. bool StreamingSocket::bindToPort (const int port)
  5098. {
  5099. return bindSocketToPort (handle, port);
  5100. }
  5101. bool StreamingSocket::connect (const String& remoteHostName,
  5102. const int remotePortNumber,
  5103. const int timeOutMillisecs)
  5104. {
  5105. if (isListener)
  5106. {
  5107. jassertfalse // a listener socket can't connect to another one!
  5108. return false;
  5109. }
  5110. if (connected)
  5111. close();
  5112. hostName = remoteHostName;
  5113. portNumber = remotePortNumber;
  5114. isListener = false;
  5115. connected = connectSocket (handle, false, 0, remoteHostName,
  5116. remotePortNumber, timeOutMillisecs);
  5117. if (! (connected && resetSocketOptions (handle, false)))
  5118. {
  5119. close();
  5120. return false;
  5121. }
  5122. return true;
  5123. }
  5124. void StreamingSocket::close()
  5125. {
  5126. #if JUCE_WIN32
  5127. closesocket (handle);
  5128. connected = false;
  5129. #else
  5130. if (connected)
  5131. {
  5132. connected = false;
  5133. if (isListener)
  5134. {
  5135. // need to do this to interrupt the accept() function..
  5136. StreamingSocket temp;
  5137. temp.connect ("localhost", portNumber, 1000);
  5138. }
  5139. }
  5140. ::close (handle);
  5141. #endif
  5142. hostName = String::empty;
  5143. portNumber = 0;
  5144. handle = -1;
  5145. isListener = false;
  5146. }
  5147. bool StreamingSocket::createListener (const int newPortNumber)
  5148. {
  5149. if (connected)
  5150. close();
  5151. hostName = "listener";
  5152. portNumber = newPortNumber;
  5153. isListener = true;
  5154. struct sockaddr_in servTmpAddr;
  5155. zerostruct (servTmpAddr);
  5156. servTmpAddr.sin_family = PF_INET;
  5157. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  5158. servTmpAddr.sin_port = htons ((uint16) portNumber);
  5159. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  5160. if (handle < 0)
  5161. return false;
  5162. const int reuse = 1;
  5163. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  5164. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  5165. || listen (handle, SOMAXCONN) < 0)
  5166. {
  5167. close();
  5168. return false;
  5169. }
  5170. connected = true;
  5171. return true;
  5172. }
  5173. StreamingSocket* StreamingSocket::waitForNextConnection() const
  5174. {
  5175. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  5176. // prepare this socket as a listener.
  5177. if (connected && isListener)
  5178. {
  5179. struct sockaddr address;
  5180. #if defined (JUCE_LINUX) || (defined (JUCE_MAC) && ! MACOS_10_2_OR_EARLIER)
  5181. socklen_t len = sizeof (sockaddr);
  5182. #else
  5183. int len = sizeof (sockaddr);
  5184. #endif
  5185. const int newSocket = (int) accept (handle, &address, &len);
  5186. if (newSocket >= 0 && connected)
  5187. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  5188. portNumber, newSocket);
  5189. }
  5190. return 0;
  5191. }
  5192. bool StreamingSocket::isLocal() const throw()
  5193. {
  5194. return hostName == T("127.0.0.1");
  5195. }
  5196. DatagramSocket::DatagramSocket (const int localPortNumber)
  5197. : portNumber (0),
  5198. handle (-1),
  5199. connected (false),
  5200. serverAddress (0)
  5201. {
  5202. #if JUCE_WIN32
  5203. initWin32Sockets();
  5204. #endif
  5205. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  5206. bindToPort (localPortNumber);
  5207. }
  5208. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  5209. const int handle_, const int localPortNumber)
  5210. : hostName (hostName_),
  5211. portNumber (portNumber_),
  5212. handle (handle_),
  5213. connected (true),
  5214. serverAddress (0)
  5215. {
  5216. #if JUCE_WIN32
  5217. initWin32Sockets();
  5218. #endif
  5219. resetSocketOptions (handle_, true);
  5220. bindToPort (localPortNumber);
  5221. }
  5222. DatagramSocket::~DatagramSocket()
  5223. {
  5224. close();
  5225. delete ((struct sockaddr_in*) serverAddress);
  5226. serverAddress = 0;
  5227. }
  5228. void DatagramSocket::close()
  5229. {
  5230. #if JUCE_WIN32
  5231. closesocket (handle);
  5232. connected = false;
  5233. #else
  5234. connected = false;
  5235. ::close (handle);
  5236. #endif
  5237. hostName = String::empty;
  5238. portNumber = 0;
  5239. handle = -1;
  5240. }
  5241. bool DatagramSocket::bindToPort (const int port)
  5242. {
  5243. return bindSocketToPort (handle, port);
  5244. }
  5245. bool DatagramSocket::connect (const String& remoteHostName,
  5246. const int remotePortNumber,
  5247. const int timeOutMillisecs)
  5248. {
  5249. if (connected)
  5250. close();
  5251. hostName = remoteHostName;
  5252. portNumber = remotePortNumber;
  5253. connected = connectSocket (handle, true, &serverAddress,
  5254. remoteHostName, remotePortNumber,
  5255. timeOutMillisecs);
  5256. if (! (connected && resetSocketOptions (handle, true)))
  5257. {
  5258. close();
  5259. return false;
  5260. }
  5261. return true;
  5262. }
  5263. DatagramSocket* DatagramSocket::waitForNextConnection() const
  5264. {
  5265. struct sockaddr address;
  5266. #if defined (JUCE_LINUX) || (defined (JUCE_MAC) && ! MACOS_10_2_OR_EARLIER)
  5267. socklen_t len = sizeof (sockaddr);
  5268. #else
  5269. int len = sizeof (sockaddr);
  5270. #endif
  5271. while (waitUntilReady (true, -1) == 1)
  5272. {
  5273. char buf[1];
  5274. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  5275. {
  5276. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  5277. ntohs (((struct sockaddr_in*) &address)->sin_port),
  5278. -1, -1);
  5279. }
  5280. }
  5281. return 0;
  5282. }
  5283. int DatagramSocket::waitUntilReady (const bool readyForReading,
  5284. const int timeoutMsecs) const
  5285. {
  5286. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  5287. : -1;
  5288. }
  5289. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead)
  5290. {
  5291. return connected ? readSocket (handle, destBuffer, maxBytesToRead, connected)
  5292. : -1;
  5293. }
  5294. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  5295. {
  5296. // You need to call connect() first to set the server address..
  5297. jassert (serverAddress != 0 && connected);
  5298. return connected ? sendto (handle, (const char*) sourceBuffer,
  5299. numBytesToWrite, 0,
  5300. (const struct sockaddr*) serverAddress,
  5301. sizeof (struct sockaddr_in))
  5302. : -1;
  5303. }
  5304. bool DatagramSocket::isLocal() const throw()
  5305. {
  5306. return hostName == T("127.0.0.1");
  5307. }
  5308. END_JUCE_NAMESPACE
  5309. /********* End of inlined file: juce_Socket.cpp *********/
  5310. /********* Start of inlined file: juce_URL.cpp *********/
  5311. BEGIN_JUCE_NAMESPACE
  5312. URL::URL() throw()
  5313. {
  5314. }
  5315. URL::URL (const String& url_)
  5316. : url (url_)
  5317. {
  5318. int i = url.indexOfChar (T('?'));
  5319. if (i >= 0)
  5320. {
  5321. do
  5322. {
  5323. const int nextAmp = url.indexOfChar (i + 1, T('&'));
  5324. const int equalsPos = url.indexOfChar (i + 1, T('='));
  5325. if (equalsPos > i + 1)
  5326. {
  5327. if (nextAmp < 0)
  5328. {
  5329. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  5330. removeEscapeChars (url.substring (equalsPos + 1)));
  5331. }
  5332. else if (nextAmp > 0 && equalsPos < nextAmp)
  5333. {
  5334. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  5335. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  5336. }
  5337. }
  5338. i = nextAmp;
  5339. }
  5340. while (i >= 0);
  5341. url = url.upToFirstOccurrenceOf (T("?"), false, false);
  5342. }
  5343. }
  5344. URL::URL (const URL& other)
  5345. : url (other.url),
  5346. parameters (other.parameters),
  5347. filesToUpload (other.filesToUpload),
  5348. mimeTypes (other.mimeTypes)
  5349. {
  5350. }
  5351. const URL& URL::operator= (const URL& other)
  5352. {
  5353. url = other.url;
  5354. parameters = other.parameters;
  5355. filesToUpload = other.filesToUpload;
  5356. mimeTypes = other.mimeTypes;
  5357. return *this;
  5358. }
  5359. URL::~URL() throw()
  5360. {
  5361. }
  5362. static const String getMangledParameters (const StringPairArray& parameters)
  5363. {
  5364. String p;
  5365. for (int i = 0; i < parameters.size(); ++i)
  5366. {
  5367. if (i > 0)
  5368. p += T("&");
  5369. p << URL::addEscapeChars (parameters.getAllKeys() [i])
  5370. << T("=")
  5371. << URL::addEscapeChars (parameters.getAllValues() [i]);
  5372. }
  5373. return p;
  5374. }
  5375. const String URL::toString (const bool includeGetParameters) const
  5376. {
  5377. if (includeGetParameters && parameters.size() > 0)
  5378. return url + T("?") + getMangledParameters (parameters);
  5379. else
  5380. return url;
  5381. }
  5382. bool URL::isWellFormed() const
  5383. {
  5384. //xxx TODO
  5385. return url.isNotEmpty();
  5386. }
  5387. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  5388. {
  5389. return (possibleURL.containsChar (T('.'))
  5390. && (! possibleURL.containsChar (T('@')))
  5391. && (! possibleURL.endsWithChar (T('.')))
  5392. && (possibleURL.startsWithIgnoreCase (T("www."))
  5393. || possibleURL.startsWithIgnoreCase (T("http:"))
  5394. || possibleURL.startsWithIgnoreCase (T("ftp:"))
  5395. || possibleURL.endsWithIgnoreCase (T(".com"))
  5396. || possibleURL.endsWithIgnoreCase (T(".net"))
  5397. || possibleURL.endsWithIgnoreCase (T(".org"))
  5398. || possibleURL.endsWithIgnoreCase (T(".co.uk")))
  5399. || possibleURL.startsWithIgnoreCase (T("file:")));
  5400. }
  5401. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  5402. {
  5403. const int atSign = possibleEmailAddress.indexOfChar (T('@'));
  5404. return atSign > 0
  5405. && possibleEmailAddress.lastIndexOfChar (T('.')) > (atSign + 1)
  5406. && (! possibleEmailAddress.endsWithChar (T('.')));
  5407. }
  5408. void* juce_openInternetFile (const String& url,
  5409. const String& headers,
  5410. const MemoryBlock& optionalPostData,
  5411. const bool isPost,
  5412. URL::OpenStreamProgressCallback* callback,
  5413. void* callbackContext,
  5414. int timeOutMs);
  5415. void juce_closeInternetFile (void* handle);
  5416. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  5417. int juce_seekInInternetFile (void* handle, int newPosition);
  5418. class WebInputStream : public InputStream
  5419. {
  5420. public:
  5421. WebInputStream (const URL& url,
  5422. const bool isPost_,
  5423. URL::OpenStreamProgressCallback* const progressCallback_,
  5424. void* const progressCallbackContext_,
  5425. const String& extraHeaders,
  5426. int timeOutMs_)
  5427. : position (0),
  5428. finished (false),
  5429. isPost (isPost_),
  5430. progressCallback (progressCallback_),
  5431. progressCallbackContext (progressCallbackContext_),
  5432. timeOutMs (timeOutMs_)
  5433. {
  5434. server = url.toString (! isPost);
  5435. if (isPost_)
  5436. createHeadersAndPostData (url);
  5437. headers += extraHeaders;
  5438. if (! headers.endsWithChar (T('\n')))
  5439. headers << "\r\n";
  5440. handle = juce_openInternetFile (server, headers, postData, isPost,
  5441. progressCallback_, progressCallbackContext_,
  5442. timeOutMs);
  5443. }
  5444. ~WebInputStream()
  5445. {
  5446. juce_closeInternetFile (handle);
  5447. }
  5448. bool isError() const throw()
  5449. {
  5450. return handle == 0;
  5451. }
  5452. int64 getTotalLength()
  5453. {
  5454. return -1;
  5455. }
  5456. bool isExhausted()
  5457. {
  5458. return finished;
  5459. }
  5460. int read (void* dest, int bytes)
  5461. {
  5462. if (finished || isError())
  5463. {
  5464. return 0;
  5465. }
  5466. else
  5467. {
  5468. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  5469. position += bytesRead;
  5470. if (bytesRead == 0)
  5471. finished = true;
  5472. return bytesRead;
  5473. }
  5474. }
  5475. int64 getPosition()
  5476. {
  5477. return position;
  5478. }
  5479. bool setPosition (int64 wantedPos)
  5480. {
  5481. if (wantedPos != position)
  5482. {
  5483. finished = false;
  5484. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  5485. if (actualPos == wantedPos)
  5486. {
  5487. position = wantedPos;
  5488. }
  5489. else
  5490. {
  5491. if (wantedPos < position)
  5492. {
  5493. juce_closeInternetFile (handle);
  5494. position = 0;
  5495. finished = false;
  5496. handle = juce_openInternetFile (server, headers, postData, isPost,
  5497. progressCallback, progressCallbackContext,
  5498. timeOutMs);
  5499. }
  5500. skipNextBytes (wantedPos - position);
  5501. }
  5502. }
  5503. return true;
  5504. }
  5505. juce_UseDebuggingNewOperator
  5506. private:
  5507. String server, headers;
  5508. MemoryBlock postData;
  5509. int64 position;
  5510. bool finished;
  5511. const bool isPost;
  5512. void* handle;
  5513. URL::OpenStreamProgressCallback* const progressCallback;
  5514. void* const progressCallbackContext;
  5515. const int timeOutMs;
  5516. void createHeadersAndPostData (const URL& url)
  5517. {
  5518. if (url.getFilesToUpload().size() > 0)
  5519. {
  5520. // need to upload some files, so do it as multi-part...
  5521. String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  5522. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  5523. appendUTF8ToPostData ("--" + boundary);
  5524. int i;
  5525. for (i = 0; i < url.getParameters().size(); ++i)
  5526. {
  5527. String s;
  5528. s << "\r\nContent-Disposition: form-data; name=\""
  5529. << url.getParameters().getAllKeys() [i]
  5530. << "\"\r\n\r\n"
  5531. << url.getParameters().getAllValues() [i]
  5532. << "\r\n--"
  5533. << boundary;
  5534. appendUTF8ToPostData (s);
  5535. }
  5536. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  5537. {
  5538. const File f (url.getFilesToUpload().getAllValues() [i]);
  5539. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  5540. String s;
  5541. s << "\r\nContent-Disposition: form-data; name=\""
  5542. << paramName
  5543. << "\"; filename=\""
  5544. << f.getFileName()
  5545. << "\"\r\n";
  5546. const String mimeType (url.getMimeTypesOfUploadFiles()
  5547. .getValue (paramName, String::empty));
  5548. if (mimeType.isNotEmpty())
  5549. s << "Content-Type: " << mimeType << "\r\n";
  5550. s << "Content-Transfer-Encoding: binary\r\n\r\n";
  5551. appendUTF8ToPostData (s);
  5552. f.loadFileAsData (postData);
  5553. s = "\r\n--" + boundary;
  5554. appendUTF8ToPostData (s);
  5555. }
  5556. appendUTF8ToPostData ("--\r\n");
  5557. }
  5558. else
  5559. {
  5560. // just a short text attachment, so use simple url encoding..
  5561. const String params (getMangledParameters (url.getParameters()));
  5562. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  5563. + String ((int) strlen (params.toUTF8()))
  5564. + "\r\n";
  5565. appendUTF8ToPostData (params);
  5566. }
  5567. }
  5568. void appendUTF8ToPostData (const String& text) throw()
  5569. {
  5570. postData.append (text.toUTF8(),
  5571. (int) strlen (text.toUTF8()));
  5572. }
  5573. WebInputStream (const WebInputStream&);
  5574. const WebInputStream& operator= (const WebInputStream&);
  5575. };
  5576. InputStream* URL::createInputStream (const bool usePostCommand,
  5577. OpenStreamProgressCallback* const progressCallback,
  5578. void* const progressCallbackContext,
  5579. const String& extraHeaders,
  5580. const int timeOutMs) const
  5581. {
  5582. WebInputStream* wi = new WebInputStream (*this, usePostCommand,
  5583. progressCallback, progressCallbackContext,
  5584. extraHeaders,
  5585. timeOutMs);
  5586. if (wi->isError())
  5587. {
  5588. delete wi;
  5589. wi = 0;
  5590. }
  5591. return wi;
  5592. }
  5593. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  5594. const bool usePostCommand) const
  5595. {
  5596. InputStream* const in = createInputStream (usePostCommand);
  5597. if (in != 0)
  5598. {
  5599. in->readIntoMemoryBlock (destData, -1);
  5600. delete in;
  5601. return true;
  5602. }
  5603. return false;
  5604. }
  5605. const String URL::readEntireTextStream (const bool usePostCommand) const
  5606. {
  5607. String result;
  5608. InputStream* const in = createInputStream (usePostCommand);
  5609. if (in != 0)
  5610. {
  5611. result = in->readEntireStreamAsString();
  5612. delete in;
  5613. }
  5614. return result;
  5615. }
  5616. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  5617. {
  5618. XmlDocument doc (readEntireTextStream (usePostCommand));
  5619. return doc.getDocumentElement();
  5620. }
  5621. const URL URL::withParameter (const String& parameterName,
  5622. const String& parameterValue) const
  5623. {
  5624. URL u (*this);
  5625. u.parameters.set (parameterName, parameterValue);
  5626. return u;
  5627. }
  5628. const URL URL::withFileToUpload (const String& parameterName,
  5629. const File& fileToUpload,
  5630. const String& mimeType) const
  5631. {
  5632. URL u (*this);
  5633. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  5634. u.mimeTypes.set (parameterName, mimeType);
  5635. return u;
  5636. }
  5637. const StringPairArray& URL::getParameters() const throw()
  5638. {
  5639. return parameters;
  5640. }
  5641. const StringPairArray& URL::getFilesToUpload() const throw()
  5642. {
  5643. return filesToUpload;
  5644. }
  5645. const StringPairArray& URL::getMimeTypesOfUploadFiles() const throw()
  5646. {
  5647. return mimeTypes;
  5648. }
  5649. const String URL::removeEscapeChars (const String& s)
  5650. {
  5651. const int len = s.length();
  5652. uint8* const resultUTF8 = (uint8*) juce_calloc (len * 4);
  5653. uint8* r = resultUTF8;
  5654. for (int i = 0; i < len; ++i)
  5655. {
  5656. char c = (char) s[i];
  5657. if (c == 0)
  5658. break;
  5659. if (c == '+')
  5660. {
  5661. c = ' ';
  5662. }
  5663. else if (c == '%')
  5664. {
  5665. c = (char) s.substring (i + 1, i + 3).getHexValue32();
  5666. i += 2;
  5667. }
  5668. *r++ = c;
  5669. }
  5670. const String stringResult (String::fromUTF8 (resultUTF8));
  5671. juce_free (resultUTF8);
  5672. return stringResult;
  5673. }
  5674. const String URL::addEscapeChars (const String& s)
  5675. {
  5676. String result;
  5677. result.preallocateStorage (s.length() + 8);
  5678. const char* utf8 = s.toUTF8();
  5679. while (*utf8 != 0)
  5680. {
  5681. const char c = *utf8++;
  5682. if (c == ' ')
  5683. {
  5684. result += T('+');
  5685. }
  5686. else if (CharacterFunctions::isLetterOrDigit (c)
  5687. || CharacterFunctions::indexOfChar ("_-$.*!'(),", c, false) >= 0)
  5688. {
  5689. result << c;
  5690. }
  5691. else
  5692. {
  5693. const int v = (int) (uint8) c;
  5694. if (v < 0x10)
  5695. result << T("%0");
  5696. else
  5697. result << T('%');
  5698. result << String::toHexString (v);
  5699. }
  5700. }
  5701. return result;
  5702. }
  5703. extern bool juce_launchFile (const String& fileName,
  5704. const String& parameters) throw();
  5705. bool URL::launchInDefaultBrowser() const
  5706. {
  5707. String u (toString (true));
  5708. if (u.contains (T("@")) && ! u.contains (T(":")))
  5709. u = "mailto:" + u;
  5710. return juce_launchFile (u, String::empty);
  5711. }
  5712. END_JUCE_NAMESPACE
  5713. /********* End of inlined file: juce_URL.cpp *********/
  5714. /********* Start of inlined file: juce_BufferedInputStream.cpp *********/
  5715. BEGIN_JUCE_NAMESPACE
  5716. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  5717. const int bufferSize_,
  5718. const bool deleteSourceWhenDestroyed_) throw()
  5719. : source (source_),
  5720. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  5721. bufferSize (jmax (256, bufferSize_)),
  5722. position (source_->getPosition()),
  5723. lastReadPos (0),
  5724. bufferOverlap (128)
  5725. {
  5726. const int sourceSize = (int) source_->getTotalLength();
  5727. if (sourceSize >= 0)
  5728. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  5729. bufferStart = position;
  5730. buffer = (char*) juce_malloc (bufferSize);
  5731. }
  5732. BufferedInputStream::~BufferedInputStream() throw()
  5733. {
  5734. if (deleteSourceWhenDestroyed)
  5735. delete source;
  5736. juce_free (buffer);
  5737. }
  5738. int64 BufferedInputStream::getTotalLength()
  5739. {
  5740. return source->getTotalLength();
  5741. }
  5742. int64 BufferedInputStream::getPosition()
  5743. {
  5744. return position;
  5745. }
  5746. bool BufferedInputStream::setPosition (int64 newPosition)
  5747. {
  5748. position = jmax ((int64) 0, newPosition);
  5749. return true;
  5750. }
  5751. bool BufferedInputStream::isExhausted()
  5752. {
  5753. return (position >= lastReadPos)
  5754. && source->isExhausted();
  5755. }
  5756. void BufferedInputStream::ensureBuffered()
  5757. {
  5758. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  5759. if (position < bufferStart || position >= bufferEndOverlap)
  5760. {
  5761. int bytesRead;
  5762. if (position < lastReadPos
  5763. && position >= bufferEndOverlap
  5764. && position >= bufferStart)
  5765. {
  5766. const int bytesToKeep = (int) (lastReadPos - position);
  5767. memmove (buffer, buffer + position - bufferStart, bytesToKeep);
  5768. bufferStart = position;
  5769. bytesRead = source->read (buffer + bytesToKeep,
  5770. bufferSize - bytesToKeep);
  5771. lastReadPos += bytesRead;
  5772. bytesRead += bytesToKeep;
  5773. }
  5774. else
  5775. {
  5776. bufferStart = position;
  5777. source->setPosition (bufferStart);
  5778. bytesRead = source->read (buffer, bufferSize);
  5779. lastReadPos = bufferStart + bytesRead;
  5780. }
  5781. while (bytesRead < bufferSize)
  5782. buffer [bytesRead++] = 0;
  5783. }
  5784. }
  5785. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  5786. {
  5787. if (position >= bufferStart
  5788. && position + maxBytesToRead <= lastReadPos)
  5789. {
  5790. memcpy (destBuffer, buffer + (position - bufferStart), maxBytesToRead);
  5791. position += maxBytesToRead;
  5792. return maxBytesToRead;
  5793. }
  5794. else
  5795. {
  5796. if (position < bufferStart || position >= lastReadPos)
  5797. ensureBuffered();
  5798. int bytesRead = 0;
  5799. while (maxBytesToRead > 0)
  5800. {
  5801. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  5802. if (bytesAvailable > 0)
  5803. {
  5804. memcpy (destBuffer, buffer + (position - bufferStart), bytesAvailable);
  5805. maxBytesToRead -= bytesAvailable;
  5806. bytesRead += bytesAvailable;
  5807. position += bytesAvailable;
  5808. destBuffer = (void*) (((char*) destBuffer) + bytesAvailable);
  5809. }
  5810. ensureBuffered();
  5811. if (isExhausted())
  5812. break;
  5813. }
  5814. return bytesRead;
  5815. }
  5816. }
  5817. const String BufferedInputStream::readString()
  5818. {
  5819. if (position >= bufferStart
  5820. && position < lastReadPos)
  5821. {
  5822. const int maxChars = (int) (lastReadPos - position);
  5823. const char* const src = buffer + (position - bufferStart);
  5824. for (int i = 0; i < maxChars; ++i)
  5825. {
  5826. if (src[i] == 0)
  5827. {
  5828. position += i + 1;
  5829. return String::fromUTF8 ((const uint8*) src, i);
  5830. }
  5831. }
  5832. }
  5833. return InputStream::readString();
  5834. }
  5835. END_JUCE_NAMESPACE
  5836. /********* End of inlined file: juce_BufferedInputStream.cpp *********/
  5837. /********* Start of inlined file: juce_FileInputSource.cpp *********/
  5838. BEGIN_JUCE_NAMESPACE
  5839. FileInputSource::FileInputSource (const File& file_) throw()
  5840. : file (file_)
  5841. {
  5842. }
  5843. FileInputSource::~FileInputSource()
  5844. {
  5845. }
  5846. InputStream* FileInputSource::createInputStream()
  5847. {
  5848. return file.createInputStream();
  5849. }
  5850. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  5851. {
  5852. return file.getSiblingFile (relatedItemPath).createInputStream();
  5853. }
  5854. int64 FileInputSource::hashCode() const
  5855. {
  5856. return file.hashCode();
  5857. }
  5858. END_JUCE_NAMESPACE
  5859. /********* End of inlined file: juce_FileInputSource.cpp *********/
  5860. /********* Start of inlined file: juce_MemoryInputStream.cpp *********/
  5861. BEGIN_JUCE_NAMESPACE
  5862. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  5863. const int sourceDataSize,
  5864. const bool keepInternalCopy) throw()
  5865. : data ((const char*) sourceData),
  5866. dataSize (sourceDataSize),
  5867. position (0)
  5868. {
  5869. if (keepInternalCopy)
  5870. {
  5871. internalCopy.append (data, sourceDataSize);
  5872. data = (const char*) internalCopy.getData();
  5873. }
  5874. }
  5875. MemoryInputStream::~MemoryInputStream() throw()
  5876. {
  5877. }
  5878. int64 MemoryInputStream::getTotalLength()
  5879. {
  5880. return dataSize;
  5881. }
  5882. int MemoryInputStream::read (void* buffer, int howMany)
  5883. {
  5884. const int num = jmin (howMany, dataSize - position);
  5885. memcpy (buffer, data + position, num);
  5886. position += num;
  5887. return num;
  5888. }
  5889. bool MemoryInputStream::isExhausted()
  5890. {
  5891. return (position >= dataSize);
  5892. }
  5893. bool MemoryInputStream::setPosition (int64 pos)
  5894. {
  5895. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  5896. return true;
  5897. }
  5898. int64 MemoryInputStream::getPosition()
  5899. {
  5900. return position;
  5901. }
  5902. END_JUCE_NAMESPACE
  5903. /********* End of inlined file: juce_MemoryInputStream.cpp *********/
  5904. /********* Start of inlined file: juce_MemoryOutputStream.cpp *********/
  5905. BEGIN_JUCE_NAMESPACE
  5906. MemoryOutputStream::MemoryOutputStream (const int initialSize,
  5907. const int blockSizeToIncreaseBy,
  5908. MemoryBlock* const memoryBlockToWriteTo) throw()
  5909. : data (memoryBlockToWriteTo),
  5910. position (0),
  5911. size (0),
  5912. blockSize (jmax (16, blockSizeToIncreaseBy)),
  5913. ownsMemoryBlock (memoryBlockToWriteTo == 0)
  5914. {
  5915. if (memoryBlockToWriteTo == 0)
  5916. data = new MemoryBlock (initialSize);
  5917. else
  5918. memoryBlockToWriteTo->setSize (initialSize, false);
  5919. }
  5920. MemoryOutputStream::~MemoryOutputStream() throw()
  5921. {
  5922. if (ownsMemoryBlock)
  5923. delete data;
  5924. else
  5925. flush();
  5926. }
  5927. void MemoryOutputStream::flush()
  5928. {
  5929. if (! ownsMemoryBlock)
  5930. data->setSize (size, false);
  5931. }
  5932. void MemoryOutputStream::reset() throw()
  5933. {
  5934. position = 0;
  5935. size = 0;
  5936. }
  5937. bool MemoryOutputStream::write (const void* buffer, int howMany)
  5938. {
  5939. int storageNeeded = position + howMany + 1;
  5940. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  5941. data->ensureSize (storageNeeded);
  5942. data->copyFrom (buffer, position, howMany);
  5943. position += howMany;
  5944. size = jmax (size, position);
  5945. return true;
  5946. }
  5947. const char* MemoryOutputStream::getData() throw()
  5948. {
  5949. if (data->getSize() > size)
  5950. ((char*) data->getData()) [size] = 0;
  5951. return (const char*) data->getData();
  5952. }
  5953. int MemoryOutputStream::getDataSize() const throw()
  5954. {
  5955. return size;
  5956. }
  5957. int64 MemoryOutputStream::getPosition()
  5958. {
  5959. return position;
  5960. }
  5961. bool MemoryOutputStream::setPosition (int64 newPosition)
  5962. {
  5963. if (newPosition <= size)
  5964. {
  5965. // ok to seek backwards
  5966. position = jlimit (0, size, (int) newPosition);
  5967. return true;
  5968. }
  5969. else
  5970. {
  5971. // trying to make it bigger isn't a good thing to do..
  5972. return false;
  5973. }
  5974. }
  5975. END_JUCE_NAMESPACE
  5976. /********* End of inlined file: juce_MemoryOutputStream.cpp *********/
  5977. /********* Start of inlined file: juce_SubregionStream.cpp *********/
  5978. BEGIN_JUCE_NAMESPACE
  5979. SubregionStream::SubregionStream (InputStream* const sourceStream,
  5980. const int64 startPositionInSourceStream_,
  5981. const int64 lengthOfSourceStream_,
  5982. const bool deleteSourceWhenDestroyed_) throw()
  5983. : source (sourceStream),
  5984. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  5985. startPositionInSourceStream (startPositionInSourceStream_),
  5986. lengthOfSourceStream (lengthOfSourceStream_)
  5987. {
  5988. setPosition (0);
  5989. }
  5990. SubregionStream::~SubregionStream() throw()
  5991. {
  5992. if (deleteSourceWhenDestroyed)
  5993. delete source;
  5994. }
  5995. int64 SubregionStream::getTotalLength()
  5996. {
  5997. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  5998. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  5999. : srcLen;
  6000. }
  6001. int64 SubregionStream::getPosition()
  6002. {
  6003. return source->getPosition() - startPositionInSourceStream;
  6004. }
  6005. bool SubregionStream::setPosition (int64 newPosition)
  6006. {
  6007. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  6008. }
  6009. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  6010. {
  6011. if (lengthOfSourceStream < 0)
  6012. {
  6013. return source->read (destBuffer, maxBytesToRead);
  6014. }
  6015. else
  6016. {
  6017. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  6018. if (maxBytesToRead <= 0)
  6019. return 0;
  6020. return source->read (destBuffer, maxBytesToRead);
  6021. }
  6022. }
  6023. bool SubregionStream::isExhausted()
  6024. {
  6025. if (lengthOfSourceStream >= 0)
  6026. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  6027. else
  6028. return source->isExhausted();
  6029. }
  6030. END_JUCE_NAMESPACE
  6031. /********* End of inlined file: juce_SubregionStream.cpp *********/
  6032. /********* Start of inlined file: juce_PerformanceCounter.cpp *********/
  6033. BEGIN_JUCE_NAMESPACE
  6034. PerformanceCounter::PerformanceCounter (const String& name_,
  6035. int runsPerPrintout,
  6036. const File& loggingFile)
  6037. : name (name_),
  6038. numRuns (0),
  6039. runsPerPrint (runsPerPrintout),
  6040. totalTime (0),
  6041. outputFile (loggingFile)
  6042. {
  6043. if (outputFile != File::nonexistent)
  6044. {
  6045. String s ("**** Counter for \"");
  6046. s << name_ << "\" started at: "
  6047. << Time::getCurrentTime().toString (true, true)
  6048. << "\r\n";
  6049. outputFile.appendText (s, false, false);
  6050. }
  6051. }
  6052. PerformanceCounter::~PerformanceCounter()
  6053. {
  6054. printStatistics();
  6055. }
  6056. void PerformanceCounter::start()
  6057. {
  6058. started = Time::getHighResolutionTicks();
  6059. }
  6060. void PerformanceCounter::stop()
  6061. {
  6062. const int64 now = Time::getHighResolutionTicks();
  6063. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  6064. if (++numRuns == runsPerPrint)
  6065. printStatistics();
  6066. }
  6067. void PerformanceCounter::printStatistics()
  6068. {
  6069. if (numRuns > 0)
  6070. {
  6071. String s ("Performance count for \"");
  6072. s << name << "\" - average over " << numRuns << " run(s) = ";
  6073. const int micros = (int) (totalTime * (1000.0 / numRuns));
  6074. if (micros > 10000)
  6075. s << (micros/1000) << " millisecs";
  6076. else
  6077. s << micros << " microsecs";
  6078. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  6079. Logger::outputDebugString (s);
  6080. s << "\r\n";
  6081. if (outputFile != File::nonexistent)
  6082. outputFile.appendText (s, false, false);
  6083. numRuns = 0;
  6084. totalTime = 0;
  6085. }
  6086. }
  6087. END_JUCE_NAMESPACE
  6088. /********* End of inlined file: juce_PerformanceCounter.cpp *********/
  6089. /********* Start of inlined file: juce_Uuid.cpp *********/
  6090. BEGIN_JUCE_NAMESPACE
  6091. Uuid::Uuid()
  6092. {
  6093. // do some serious mixing up of our MAC addresses and different types of time info,
  6094. // plus a couple of passes of pseudo-random numbers over the whole thing.
  6095. SystemStats::getMACAddresses (value.asInt64, 2);
  6096. int i;
  6097. for (i = 16; --i >= 0;)
  6098. {
  6099. Random r (Time::getHighResolutionTicks()
  6100. + Random::getSystemRandom().nextInt()
  6101. + value.asInt [i & 3]);
  6102. value.asBytes[i] ^= (uint8) r.nextInt();
  6103. }
  6104. value.asInt64 [0] ^= Time::getHighResolutionTicks();
  6105. value.asInt64 [1] ^= Time::currentTimeMillis();
  6106. for (i = 4; --i >= 0;)
  6107. {
  6108. Random r (Time::getHighResolutionTicks() ^ value.asInt[i]);
  6109. value.asInt[i] ^= r.nextInt();
  6110. }
  6111. }
  6112. Uuid::~Uuid() throw()
  6113. {
  6114. }
  6115. Uuid::Uuid (const Uuid& other)
  6116. : value (other.value)
  6117. {
  6118. }
  6119. Uuid& Uuid::operator= (const Uuid& other)
  6120. {
  6121. if (this != &other)
  6122. value = other.value;
  6123. return *this;
  6124. }
  6125. bool Uuid::operator== (const Uuid& other) const
  6126. {
  6127. return memcmp (value.asBytes, other.value.asBytes, 16) == 0;
  6128. }
  6129. bool Uuid::operator!= (const Uuid& other) const
  6130. {
  6131. return ! operator== (other);
  6132. }
  6133. bool Uuid::isNull() const throw()
  6134. {
  6135. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  6136. }
  6137. const String Uuid::toString() const
  6138. {
  6139. return String::toHexString (value.asBytes, 16, 0);
  6140. }
  6141. Uuid::Uuid (const String& uuidString)
  6142. {
  6143. operator= (uuidString);
  6144. }
  6145. Uuid& Uuid::operator= (const String& uuidString)
  6146. {
  6147. int destIndex = 0;
  6148. int i = 0;
  6149. for (;;)
  6150. {
  6151. int byte = 0;
  6152. for (int loop = 2; --loop >= 0;)
  6153. {
  6154. byte <<= 4;
  6155. for (;;)
  6156. {
  6157. const tchar c = uuidString [i++];
  6158. if (c >= T('0') && c <= T('9'))
  6159. {
  6160. byte |= c - T('0');
  6161. break;
  6162. }
  6163. else if (c >= T('a') && c <= T('z'))
  6164. {
  6165. byte |= c - (T('a') - 10);
  6166. break;
  6167. }
  6168. else if (c >= T('A') && c <= T('Z'))
  6169. {
  6170. byte |= c - (T('A') - 10);
  6171. break;
  6172. }
  6173. else if (c == 0)
  6174. {
  6175. while (destIndex < 16)
  6176. value.asBytes [destIndex++] = 0;
  6177. return *this;
  6178. }
  6179. }
  6180. }
  6181. value.asBytes [destIndex++] = (uint8) byte;
  6182. }
  6183. }
  6184. Uuid::Uuid (const uint8* const rawData)
  6185. {
  6186. operator= (rawData);
  6187. }
  6188. Uuid& Uuid::operator= (const uint8* const rawData)
  6189. {
  6190. if (rawData != 0)
  6191. memcpy (value.asBytes, rawData, 16);
  6192. else
  6193. zeromem (value.asBytes, 16);
  6194. return *this;
  6195. }
  6196. END_JUCE_NAMESPACE
  6197. /********* End of inlined file: juce_Uuid.cpp *********/
  6198. /********* Start of inlined file: juce_ZipFile.cpp *********/
  6199. BEGIN_JUCE_NAMESPACE
  6200. struct ZipEntryInfo
  6201. {
  6202. ZipFile::ZipEntry entry;
  6203. int streamOffset;
  6204. int compressedSize;
  6205. bool compressed;
  6206. };
  6207. class ZipInputStream : public InputStream
  6208. {
  6209. public:
  6210. ZipInputStream (ZipFile& file_,
  6211. ZipEntryInfo& zei) throw()
  6212. : file (file_),
  6213. zipEntryInfo (zei),
  6214. pos (0),
  6215. headerSize (0),
  6216. inputStream (0)
  6217. {
  6218. inputStream = file_.inputStream;
  6219. if (file_.inputSource != 0)
  6220. {
  6221. inputStream = file.inputSource->createInputStream();
  6222. }
  6223. else
  6224. {
  6225. #ifdef JUCE_DEBUG
  6226. file_.numOpenStreams++;
  6227. #endif
  6228. }
  6229. char buffer [30];
  6230. if (inputStream != 0
  6231. && inputStream->setPosition (zei.streamOffset)
  6232. && inputStream->read (buffer, 30) == 30
  6233. && littleEndianInt (buffer) == 0x04034b50)
  6234. {
  6235. headerSize = 30 + littleEndianShort (buffer + 26)
  6236. + littleEndianShort (buffer + 28);
  6237. }
  6238. }
  6239. ~ZipInputStream() throw()
  6240. {
  6241. #ifdef JUCE_DEBUG
  6242. if (inputStream != 0 && inputStream == file.inputStream)
  6243. file.numOpenStreams--;
  6244. #endif
  6245. if (inputStream != file.inputStream)
  6246. delete inputStream;
  6247. }
  6248. int64 getTotalLength() throw()
  6249. {
  6250. return zipEntryInfo.compressedSize;
  6251. }
  6252. int read (void* buffer, int howMany) throw()
  6253. {
  6254. if (headerSize <= 0)
  6255. return 0;
  6256. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  6257. if (inputStream == 0)
  6258. return 0;
  6259. int num;
  6260. if (inputStream == file.inputStream)
  6261. {
  6262. const ScopedLock sl (file.lock);
  6263. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  6264. num = inputStream->read (buffer, howMany);
  6265. }
  6266. else
  6267. {
  6268. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  6269. num = inputStream->read (buffer, howMany);
  6270. }
  6271. pos += num;
  6272. return num;
  6273. }
  6274. bool isExhausted() throw()
  6275. {
  6276. return pos >= zipEntryInfo.compressedSize;
  6277. }
  6278. int64 getPosition() throw()
  6279. {
  6280. return pos;
  6281. }
  6282. bool setPosition (int64 newPos) throw()
  6283. {
  6284. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  6285. return true;
  6286. }
  6287. private:
  6288. ZipFile& file;
  6289. ZipEntryInfo zipEntryInfo;
  6290. int64 pos;
  6291. int headerSize;
  6292. InputStream* inputStream;
  6293. ZipInputStream (const ZipInputStream&);
  6294. const ZipInputStream& operator= (const ZipInputStream&);
  6295. };
  6296. ZipFile::ZipFile (InputStream* const source_,
  6297. const bool deleteStreamWhenDestroyed_) throw()
  6298. : inputStream (source_),
  6299. inputSource (0),
  6300. deleteStreamWhenDestroyed (deleteStreamWhenDestroyed_)
  6301. #ifdef JUCE_DEBUG
  6302. , numOpenStreams (0)
  6303. #endif
  6304. {
  6305. init();
  6306. }
  6307. ZipFile::ZipFile (const File& file)
  6308. : inputStream (0),
  6309. deleteStreamWhenDestroyed (false)
  6310. #ifdef JUCE_DEBUG
  6311. , numOpenStreams (0)
  6312. #endif
  6313. {
  6314. inputSource = new FileInputSource (file);
  6315. init();
  6316. }
  6317. ZipFile::ZipFile (InputSource* const inputSource_)
  6318. : inputStream (0),
  6319. inputSource (inputSource_),
  6320. deleteStreamWhenDestroyed (false)
  6321. #ifdef JUCE_DEBUG
  6322. , numOpenStreams (0)
  6323. #endif
  6324. {
  6325. init();
  6326. }
  6327. ZipFile::~ZipFile() throw()
  6328. {
  6329. for (int i = entries.size(); --i >= 0;)
  6330. {
  6331. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [i];
  6332. delete zei;
  6333. }
  6334. if (deleteStreamWhenDestroyed)
  6335. delete inputStream;
  6336. delete inputSource;
  6337. #ifdef JUCE_DEBUG
  6338. // If you hit this assertion, it means you've created a stream to read
  6339. // one of the items in the zipfile, but you've forgotten to delete that
  6340. // stream object before deleting the file.. Streams can't be kept open
  6341. // after the file is deleted because they need to share the input
  6342. // stream that the file uses to read itself.
  6343. jassert (numOpenStreams == 0);
  6344. #endif
  6345. }
  6346. int ZipFile::getNumEntries() const throw()
  6347. {
  6348. return entries.size();
  6349. }
  6350. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  6351. {
  6352. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [index];
  6353. return (zei != 0) ? &(zei->entry)
  6354. : 0;
  6355. }
  6356. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  6357. {
  6358. for (int i = 0; i < entries.size(); ++i)
  6359. if (((ZipEntryInfo*) entries.getUnchecked (i))->entry.filename == fileName)
  6360. return i;
  6361. return -1;
  6362. }
  6363. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  6364. {
  6365. return getEntry (getIndexOfFileName (fileName));
  6366. }
  6367. InputStream* ZipFile::createStreamForEntry (const int index)
  6368. {
  6369. ZipEntryInfo* const zei = (ZipEntryInfo*) entries[index];
  6370. InputStream* stream = 0;
  6371. if (zei != 0)
  6372. {
  6373. stream = new ZipInputStream (*this, *zei);
  6374. if (zei->compressed)
  6375. {
  6376. stream = new GZIPDecompressorInputStream (stream, true, true,
  6377. zei->entry.uncompressedSize);
  6378. // (much faster to unzip in big blocks using a buffer..)
  6379. stream = new BufferedInputStream (stream, 32768, true);
  6380. }
  6381. }
  6382. return stream;
  6383. }
  6384. class ZipFilenameComparator
  6385. {
  6386. public:
  6387. static int compareElements (const void* const first, const void* const second) throw()
  6388. {
  6389. return ((const ZipEntryInfo*) first)->entry.filename
  6390. .compare (((const ZipEntryInfo*) second)->entry.filename);
  6391. }
  6392. };
  6393. void ZipFile::sortEntriesByFilename()
  6394. {
  6395. ZipFilenameComparator sorter;
  6396. entries.sort (sorter);
  6397. }
  6398. void ZipFile::init()
  6399. {
  6400. InputStream* in = inputStream;
  6401. bool deleteInput = false;
  6402. if (inputSource != 0)
  6403. {
  6404. deleteInput = true;
  6405. in = inputSource->createInputStream();
  6406. }
  6407. if (in != 0)
  6408. {
  6409. numEntries = 0;
  6410. int pos = findEndOfZipEntryTable (in);
  6411. if (pos >= 0 && pos < in->getTotalLength())
  6412. {
  6413. const int size = (int) (in->getTotalLength() - pos);
  6414. in->setPosition (pos);
  6415. MemoryBlock headerData;
  6416. if (in->readIntoMemoryBlock (headerData, size) == size)
  6417. {
  6418. pos = 0;
  6419. for (int i = 0; i < numEntries; ++i)
  6420. {
  6421. if (pos + 46 > size)
  6422. break;
  6423. const char* const buffer = ((const char*) headerData.getData()) + pos;
  6424. const int fileNameLen = littleEndianShort (buffer + 28);
  6425. if (pos + 46 + fileNameLen > size)
  6426. break;
  6427. ZipEntryInfo* const zei = new ZipEntryInfo();
  6428. zei->entry.filename = String (buffer + 46, fileNameLen);
  6429. const int time = littleEndianShort (buffer + 12);
  6430. const int date = littleEndianShort (buffer + 14);
  6431. const int year = 1980 + (date >> 9);
  6432. const int month = ((date >> 5) & 15) - 1;
  6433. const int day = date & 31;
  6434. const int hours = time >> 11;
  6435. const int minutes = (time >> 5) & 63;
  6436. const int seconds = (time & 31) << 1;
  6437. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  6438. zei->compressed = littleEndianShort (buffer + 10) != 0;
  6439. zei->compressedSize = littleEndianInt (buffer + 20);
  6440. zei->entry.uncompressedSize = littleEndianInt (buffer + 24);
  6441. zei->streamOffset = littleEndianInt (buffer + 42);
  6442. entries.add (zei);
  6443. pos += 46 + fileNameLen
  6444. + littleEndianShort (buffer + 30)
  6445. + littleEndianShort (buffer + 32);
  6446. }
  6447. }
  6448. }
  6449. if (deleteInput)
  6450. delete in;
  6451. }
  6452. }
  6453. int ZipFile::findEndOfZipEntryTable (InputStream* input)
  6454. {
  6455. BufferedInputStream in (input, 8192, false);
  6456. in.setPosition (in.getTotalLength());
  6457. int64 pos = in.getPosition();
  6458. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  6459. char buffer [32];
  6460. zeromem (buffer, sizeof (buffer));
  6461. while (pos > lowestPos)
  6462. {
  6463. in.setPosition (pos - 22);
  6464. pos = in.getPosition();
  6465. memcpy (buffer + 22, buffer, 4);
  6466. if (in.read (buffer, 22) != 22)
  6467. return 0;
  6468. for (int i = 0; i < 22; ++i)
  6469. {
  6470. if (littleEndianInt (buffer + i) == 0x06054b50)
  6471. {
  6472. in.setPosition (pos + i);
  6473. in.read (buffer, 22);
  6474. numEntries = littleEndianShort (buffer + 10);
  6475. return littleEndianInt (buffer + 16);
  6476. }
  6477. }
  6478. }
  6479. return 0;
  6480. }
  6481. void ZipFile::uncompressTo (const File& targetDirectory,
  6482. const bool shouldOverwriteFiles)
  6483. {
  6484. for (int i = 0; i < entries.size(); ++i)
  6485. {
  6486. const ZipEntryInfo& zei = *(ZipEntryInfo*) entries[i];
  6487. const File targetFile (targetDirectory.getChildFile (zei.entry.filename));
  6488. if (zei.entry.filename.endsWithChar (T('/')))
  6489. {
  6490. targetFile.createDirectory(); // (entry is a directory, not a file)
  6491. }
  6492. else
  6493. {
  6494. InputStream* const in = createStreamForEntry (i);
  6495. if (in != 0)
  6496. {
  6497. if (shouldOverwriteFiles)
  6498. targetFile.deleteFile();
  6499. if ((! targetFile.exists())
  6500. && targetFile.getParentDirectory().createDirectory())
  6501. {
  6502. FileOutputStream* const out = targetFile.createOutputStream();
  6503. if (out != 0)
  6504. {
  6505. out->writeFromInputStream (*in, -1);
  6506. delete out;
  6507. targetFile.setCreationTime (zei.entry.fileTime);
  6508. targetFile.setLastModificationTime (zei.entry.fileTime);
  6509. targetFile.setLastAccessTime (zei.entry.fileTime);
  6510. }
  6511. }
  6512. delete in;
  6513. }
  6514. }
  6515. }
  6516. }
  6517. END_JUCE_NAMESPACE
  6518. /********* End of inlined file: juce_ZipFile.cpp *********/
  6519. /********* Start of inlined file: juce_CharacterFunctions.cpp *********/
  6520. #ifdef _MSC_VER
  6521. #pragma warning (disable: 4514 4996)
  6522. #pragma warning (push)
  6523. #endif
  6524. #include <cwctype>
  6525. #include <cctype>
  6526. #include <ctime>
  6527. #ifdef _MSC_VER
  6528. #pragma warning (pop)
  6529. #endif
  6530. BEGIN_JUCE_NAMESPACE
  6531. int CharacterFunctions::length (const char* const s) throw()
  6532. {
  6533. return (int) strlen (s);
  6534. }
  6535. int CharacterFunctions::length (const juce_wchar* const s) throw()
  6536. {
  6537. #if MACOS_10_2_OR_EARLIER
  6538. int n = 0;
  6539. while (s[n] != 0)
  6540. ++n;
  6541. return n;
  6542. #else
  6543. return (int) wcslen (s);
  6544. #endif
  6545. }
  6546. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  6547. {
  6548. strncpy (dest, src, maxChars);
  6549. }
  6550. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  6551. {
  6552. #if MACOS_10_2_OR_EARLIER
  6553. while (--maxChars >= 0 && *src != 0)
  6554. *dest++ = *src++;
  6555. *dest = 0;
  6556. #else
  6557. wcsncpy (dest, src, maxChars);
  6558. #endif
  6559. }
  6560. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  6561. {
  6562. mbstowcs (dest, src, maxChars);
  6563. }
  6564. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  6565. {
  6566. wcstombs (dest, src, maxChars);
  6567. }
  6568. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  6569. {
  6570. return (int) wcstombs (0, src, 0);
  6571. }
  6572. void CharacterFunctions::append (char* dest, const char* src) throw()
  6573. {
  6574. strcat (dest, src);
  6575. }
  6576. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  6577. {
  6578. #if MACOS_10_2_OR_EARLIER
  6579. while (*dest != 0)
  6580. ++dest;
  6581. while (*src != 0)
  6582. *dest++ = *src++;
  6583. *dest = 0;
  6584. #else
  6585. wcscat (dest, src);
  6586. #endif
  6587. }
  6588. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  6589. {
  6590. return strcmp (s1, s2);
  6591. }
  6592. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  6593. {
  6594. jassert (s1 != 0 && s2 != 0);
  6595. #if MACOS_10_2_OR_EARLIER
  6596. for (;;)
  6597. {
  6598. if (*s1 != *s2)
  6599. {
  6600. const int diff = *s1 - *s2;
  6601. if (diff != 0)
  6602. return diff < 0 ? -1 : 1;
  6603. }
  6604. else if (*s1 == 0)
  6605. break;
  6606. ++s1;
  6607. ++s2;
  6608. }
  6609. return 0;
  6610. #else
  6611. return wcscmp (s1, s2);
  6612. #endif
  6613. }
  6614. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  6615. {
  6616. jassert (s1 != 0 && s2 != 0);
  6617. return strncmp (s1, s2, maxChars);
  6618. }
  6619. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  6620. {
  6621. jassert (s1 != 0 && s2 != 0);
  6622. #if MACOS_10_2_OR_EARLIER
  6623. while (--maxChars >= 0)
  6624. {
  6625. if (*s1 != *s2)
  6626. return (*s1 < *s2) ? -1 : 1;
  6627. else if (*s1 == 0)
  6628. break;
  6629. ++s1;
  6630. ++s2;
  6631. }
  6632. return 0;
  6633. #else
  6634. return wcsncmp (s1, s2, maxChars);
  6635. #endif
  6636. }
  6637. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  6638. {
  6639. jassert (s1 != 0 && s2 != 0);
  6640. #if JUCE_WIN32
  6641. return stricmp (s1, s2);
  6642. #else
  6643. return strcasecmp (s1, s2);
  6644. #endif
  6645. }
  6646. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  6647. {
  6648. jassert (s1 != 0 && s2 != 0);
  6649. #if JUCE_WIN32
  6650. return _wcsicmp (s1, s2);
  6651. #else
  6652. for (;;)
  6653. {
  6654. if (*s1 != *s2)
  6655. {
  6656. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  6657. if (diff != 0)
  6658. return diff < 0 ? -1 : 1;
  6659. }
  6660. else if (*s1 == 0)
  6661. break;
  6662. ++s1;
  6663. ++s2;
  6664. }
  6665. return 0;
  6666. #endif
  6667. }
  6668. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  6669. {
  6670. jassert (s1 != 0 && s2 != 0);
  6671. #if JUCE_WIN32
  6672. return strnicmp (s1, s2, maxChars);
  6673. #else
  6674. return strncasecmp (s1, s2, maxChars);
  6675. #endif
  6676. }
  6677. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  6678. {
  6679. jassert (s1 != 0 && s2 != 0);
  6680. #if JUCE_WIN32
  6681. return _wcsnicmp (s1, s2, maxChars);
  6682. #else
  6683. while (--maxChars >= 0)
  6684. {
  6685. if (*s1 != *s2)
  6686. {
  6687. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  6688. if (diff != 0)
  6689. return diff < 0 ? -1 : 1;
  6690. }
  6691. else if (*s1 == 0)
  6692. break;
  6693. ++s1;
  6694. ++s2;
  6695. }
  6696. return 0;
  6697. #endif
  6698. }
  6699. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  6700. {
  6701. return strstr (haystack, needle);
  6702. }
  6703. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  6704. {
  6705. #if MACOS_10_2_OR_EARLIER
  6706. while (*haystack != 0)
  6707. {
  6708. const juce_wchar* s1 = haystack;
  6709. const juce_wchar* s2 = needle;
  6710. for (;;)
  6711. {
  6712. if (*s2 == 0)
  6713. return haystack;
  6714. if (*s1 != *s2 || *s2 == 0)
  6715. break;
  6716. ++s1;
  6717. ++s2;
  6718. }
  6719. ++haystack;
  6720. }
  6721. return 0;
  6722. #else
  6723. return wcsstr (haystack, needle);
  6724. #endif
  6725. }
  6726. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  6727. {
  6728. if (haystack != 0)
  6729. {
  6730. int i = 0;
  6731. if (ignoreCase)
  6732. {
  6733. const char n1 = toLowerCase (needle);
  6734. const char n2 = toUpperCase (needle);
  6735. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  6736. {
  6737. while (haystack[i] != 0)
  6738. {
  6739. if (haystack[i] == n1 || haystack[i] == n2)
  6740. return i;
  6741. ++i;
  6742. }
  6743. return -1;
  6744. }
  6745. jassert (n1 == needle);
  6746. }
  6747. while (haystack[i] != 0)
  6748. {
  6749. if (haystack[i] == needle)
  6750. return i;
  6751. ++i;
  6752. }
  6753. }
  6754. return -1;
  6755. }
  6756. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  6757. {
  6758. if (haystack != 0)
  6759. {
  6760. int i = 0;
  6761. if (ignoreCase)
  6762. {
  6763. const juce_wchar n1 = toLowerCase (needle);
  6764. const juce_wchar n2 = toUpperCase (needle);
  6765. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  6766. {
  6767. while (haystack[i] != 0)
  6768. {
  6769. if (haystack[i] == n1 || haystack[i] == n2)
  6770. return i;
  6771. ++i;
  6772. }
  6773. return -1;
  6774. }
  6775. jassert (n1 == needle);
  6776. }
  6777. while (haystack[i] != 0)
  6778. {
  6779. if (haystack[i] == needle)
  6780. return i;
  6781. ++i;
  6782. }
  6783. }
  6784. return -1;
  6785. }
  6786. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  6787. {
  6788. jassert (haystack != 0);
  6789. int i = 0;
  6790. while (haystack[i] != 0)
  6791. {
  6792. if (haystack[i] == needle)
  6793. return i;
  6794. ++i;
  6795. }
  6796. return -1;
  6797. }
  6798. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  6799. {
  6800. jassert (haystack != 0);
  6801. int i = 0;
  6802. while (haystack[i] != 0)
  6803. {
  6804. if (haystack[i] == needle)
  6805. return i;
  6806. ++i;
  6807. }
  6808. return -1;
  6809. }
  6810. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  6811. {
  6812. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  6813. }
  6814. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  6815. {
  6816. if (allowedChars == 0)
  6817. return 0;
  6818. int i = 0;
  6819. for (;;)
  6820. {
  6821. if (indexOfCharFast (allowedChars, text[i]) < 0)
  6822. break;
  6823. ++i;
  6824. }
  6825. return i;
  6826. }
  6827. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  6828. {
  6829. return (int) strftime (dest, maxChars, format, tm);
  6830. }
  6831. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  6832. {
  6833. #if MACOS_10_2_OR_EARLIER
  6834. const String formatTemp (format);
  6835. size_t num = strftime ((char*) dest, maxChars, (const char*) formatTemp, tm);
  6836. String temp ((char*) dest);
  6837. temp.copyToBuffer (dest, num);
  6838. dest [num] = 0;
  6839. return (int) num;
  6840. #else
  6841. return (int) wcsftime (dest, maxChars, format, tm);
  6842. #endif
  6843. }
  6844. int CharacterFunctions::getIntValue (const char* const s) throw()
  6845. {
  6846. return atoi (s);
  6847. }
  6848. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  6849. {
  6850. #if JUCE_WIN32
  6851. return _wtoi (s);
  6852. #else
  6853. int v = 0;
  6854. while (isWhitespace (*s))
  6855. ++s;
  6856. const bool isNeg = *s == T('-');
  6857. if (isNeg)
  6858. ++s;
  6859. for (;;)
  6860. {
  6861. const wchar_t c = *s++;
  6862. if (c >= T('0') && c <= T('9'))
  6863. v = v * 10 + (int) (c - T('0'));
  6864. else
  6865. break;
  6866. }
  6867. return isNeg ? -v : v;
  6868. #endif
  6869. }
  6870. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  6871. {
  6872. #if JUCE_LINUX
  6873. return atoll (s);
  6874. #elif defined (JUCE_WIN32)
  6875. return _atoi64 (s);
  6876. #else
  6877. int64 v = 0;
  6878. while (isWhitespace (*s))
  6879. ++s;
  6880. const bool isNeg = *s == T('-');
  6881. if (isNeg)
  6882. ++s;
  6883. for (;;)
  6884. {
  6885. const char c = *s++;
  6886. if (c >= '0' && c <= '9')
  6887. v = v * 10 + (int64) (c - '0');
  6888. else
  6889. break;
  6890. }
  6891. return isNeg ? -v : v;
  6892. #endif
  6893. }
  6894. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  6895. {
  6896. #if JUCE_WIN32
  6897. return _wtoi64 (s);
  6898. #else
  6899. int64 v = 0;
  6900. while (isWhitespace (*s))
  6901. ++s;
  6902. const bool isNeg = *s == T('-');
  6903. if (isNeg)
  6904. ++s;
  6905. for (;;)
  6906. {
  6907. const juce_wchar c = *s++;
  6908. if (c >= T('0') && c <= T('9'))
  6909. v = v * 10 + (int64) (c - T('0'));
  6910. else
  6911. break;
  6912. }
  6913. return isNeg ? -v : v;
  6914. #endif
  6915. }
  6916. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  6917. {
  6918. return atof (s);
  6919. }
  6920. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  6921. {
  6922. #if MACOS_10_2_OR_EARLIER
  6923. String temp (s);
  6924. return atof ((const char*) temp);
  6925. #else
  6926. wchar_t* endChar;
  6927. return wcstod (s, &endChar);
  6928. #endif
  6929. }
  6930. char CharacterFunctions::toUpperCase (const char character) throw()
  6931. {
  6932. return (char) toupper (character);
  6933. }
  6934. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  6935. {
  6936. #if MACOS_10_2_OR_EARLIER
  6937. return toupper ((char) character);
  6938. #else
  6939. return towupper (character);
  6940. #endif
  6941. }
  6942. void CharacterFunctions::toUpperCase (char* s) throw()
  6943. {
  6944. #if JUCE_WIN32
  6945. strupr (s);
  6946. #else
  6947. while (*s != 0)
  6948. {
  6949. *s = toUpperCase (*s);
  6950. ++s;
  6951. }
  6952. #endif
  6953. }
  6954. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  6955. {
  6956. #if JUCE_WIN32
  6957. _wcsupr (s);
  6958. #else
  6959. while (*s != 0)
  6960. {
  6961. *s = toUpperCase (*s);
  6962. ++s;
  6963. }
  6964. #endif
  6965. }
  6966. bool CharacterFunctions::isUpperCase (const char character) throw()
  6967. {
  6968. return isupper (character) != 0;
  6969. }
  6970. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  6971. {
  6972. #if JUCE_WIN32
  6973. return iswupper (character) != 0;
  6974. #else
  6975. return toLowerCase (character) != character;
  6976. #endif
  6977. }
  6978. char CharacterFunctions::toLowerCase (const char character) throw()
  6979. {
  6980. return (char) tolower (character);
  6981. }
  6982. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  6983. {
  6984. #if MACOS_10_2_OR_EARLIER
  6985. return tolower ((char) character);
  6986. #else
  6987. return towlower (character);
  6988. #endif
  6989. }
  6990. void CharacterFunctions::toLowerCase (char* s) throw()
  6991. {
  6992. #if JUCE_WIN32
  6993. strlwr (s);
  6994. #else
  6995. while (*s != 0)
  6996. {
  6997. *s = toLowerCase (*s);
  6998. ++s;
  6999. }
  7000. #endif
  7001. }
  7002. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  7003. {
  7004. #if JUCE_WIN32
  7005. _wcslwr (s);
  7006. #else
  7007. while (*s != 0)
  7008. {
  7009. *s = toLowerCase (*s);
  7010. ++s;
  7011. }
  7012. #endif
  7013. }
  7014. bool CharacterFunctions::isLowerCase (const char character) throw()
  7015. {
  7016. return islower (character) != 0;
  7017. }
  7018. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  7019. {
  7020. #if JUCE_WIN32
  7021. return iswlower (character) != 0;
  7022. #else
  7023. return toUpperCase (character) != character;
  7024. #endif
  7025. }
  7026. bool CharacterFunctions::isWhitespace (const char character) throw()
  7027. {
  7028. return character == T(' ') || (character <= 13 && character >= 9);
  7029. }
  7030. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  7031. {
  7032. #if MACOS_10_2_OR_EARLIER
  7033. return isWhitespace ((char) character);
  7034. #else
  7035. return iswspace (character) != 0;
  7036. #endif
  7037. }
  7038. bool CharacterFunctions::isDigit (const char character) throw()
  7039. {
  7040. return (character >= '0' && character <= '9');
  7041. }
  7042. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  7043. {
  7044. #if MACOS_10_2_OR_EARLIER
  7045. return isdigit ((char) character) != 0;
  7046. #else
  7047. return iswdigit (character) != 0;
  7048. #endif
  7049. }
  7050. bool CharacterFunctions::isLetter (const char character) throw()
  7051. {
  7052. return (character >= 'a' && character <= 'z')
  7053. || (character >= 'A' && character <= 'Z');
  7054. }
  7055. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  7056. {
  7057. #if MACOS_10_2_OR_EARLIER
  7058. return isLetter ((char) character);
  7059. #else
  7060. return iswalpha (character) != 0;
  7061. #endif
  7062. }
  7063. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  7064. {
  7065. return (character >= 'a' && character <= 'z')
  7066. || (character >= 'A' && character <= 'Z')
  7067. || (character >= '0' && character <= '9');
  7068. }
  7069. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  7070. {
  7071. #if MACOS_10_2_OR_EARLIER
  7072. return isLetterOrDigit ((char) character);
  7073. #else
  7074. return iswalnum (character) != 0;
  7075. #endif
  7076. }
  7077. int CharacterFunctions::getHexDigitValue (const tchar digit) throw()
  7078. {
  7079. if (digit >= T('0') && digit <= T('9'))
  7080. return digit - T('0');
  7081. else if (digit >= T('a') && digit <= T('f'))
  7082. return digit - (T('a') - 10);
  7083. else if (digit >= T('A') && digit <= T('F'))
  7084. return digit - (T('A') - 10);
  7085. return -1;
  7086. }
  7087. int CharacterFunctions::printf (char* const dest, const int maxLength, const char* const format, ...) throw()
  7088. {
  7089. va_list list;
  7090. va_start (list, format);
  7091. return vprintf (dest, maxLength, format, list);
  7092. }
  7093. int CharacterFunctions::printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw()
  7094. {
  7095. va_list list;
  7096. va_start (list, format);
  7097. return vprintf (dest, maxLength, format, list);
  7098. }
  7099. int CharacterFunctions::vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw()
  7100. {
  7101. #if JUCE_WIN32
  7102. return (int) _vsnprintf (dest, maxLength, format, args);
  7103. #else
  7104. return (int) vsnprintf (dest, maxLength, format, args);
  7105. #endif
  7106. }
  7107. int CharacterFunctions::vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw()
  7108. {
  7109. #if MACOS_10_3_OR_EARLIER
  7110. const String formatTemp (format);
  7111. size_t num = vprintf ((char*) dest, maxLength, formatTemp, args);
  7112. String temp ((char*) dest);
  7113. temp.copyToBuffer (dest, num);
  7114. dest [num] = 0;
  7115. return (int) num;
  7116. #elif defined (JUCE_WIN32)
  7117. return (int) _vsnwprintf (dest, maxLength, format, args);
  7118. #else
  7119. return (int) vswprintf (dest, maxLength, format, args);
  7120. #endif
  7121. }
  7122. END_JUCE_NAMESPACE
  7123. /********* End of inlined file: juce_CharacterFunctions.cpp *********/
  7124. /********* Start of inlined file: juce_LocalisedStrings.cpp *********/
  7125. BEGIN_JUCE_NAMESPACE
  7126. LocalisedStrings::LocalisedStrings (const String& fileContents) throw()
  7127. {
  7128. loadFromText (fileContents);
  7129. }
  7130. LocalisedStrings::LocalisedStrings (const File& fileToLoad) throw()
  7131. {
  7132. loadFromText (fileToLoad.loadFileAsString());
  7133. }
  7134. LocalisedStrings::~LocalisedStrings() throw()
  7135. {
  7136. }
  7137. const String LocalisedStrings::translate (const String& text) const throw()
  7138. {
  7139. return translations.getValue (text, text);
  7140. }
  7141. static int findCloseQuote (const String& text, int startPos) throw()
  7142. {
  7143. tchar lastChar = 0;
  7144. for (;;)
  7145. {
  7146. const tchar c = text [startPos];
  7147. if (c == 0 || (c == T('"') && lastChar != T('\\')))
  7148. break;
  7149. lastChar = c;
  7150. ++startPos;
  7151. }
  7152. return startPos;
  7153. }
  7154. static const String unescapeString (const String& s) throw()
  7155. {
  7156. return s.replace (T("\\\""), T("\""))
  7157. .replace (T("\\\'"), T("\'"))
  7158. .replace (T("\\t"), T("\t"))
  7159. .replace (T("\\r"), T("\r"))
  7160. .replace (T("\\n"), T("\n"));
  7161. }
  7162. void LocalisedStrings::loadFromText (const String& fileContents) throw()
  7163. {
  7164. StringArray lines;
  7165. lines.addLines (fileContents);
  7166. for (int i = 0; i < lines.size(); ++i)
  7167. {
  7168. String line (lines[i].trim());
  7169. if (line.startsWithChar (T('"')))
  7170. {
  7171. int closeQuote = findCloseQuote (line, 1);
  7172. const String originalText (unescapeString (line.substring (1, closeQuote)));
  7173. if (originalText.isNotEmpty())
  7174. {
  7175. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  7176. closeQuote = findCloseQuote (line, openingQuote + 1);
  7177. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  7178. if (newText.isNotEmpty())
  7179. translations.set (originalText, newText);
  7180. }
  7181. }
  7182. else if (line.startsWithIgnoreCase (T("language:")))
  7183. {
  7184. languageName = line.substring (9).trim();
  7185. }
  7186. else if (line.startsWithIgnoreCase (T("countries:")))
  7187. {
  7188. countryCodes.addTokens (line.substring (10).trim(), true);
  7189. countryCodes.trim();
  7190. countryCodes.removeEmptyStrings();
  7191. }
  7192. }
  7193. }
  7194. static CriticalSection currentMappingsLock;
  7195. static LocalisedStrings* currentMappings = 0;
  7196. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations) throw()
  7197. {
  7198. const ScopedLock sl (currentMappingsLock);
  7199. delete currentMappings;
  7200. currentMappings = newTranslations;
  7201. }
  7202. LocalisedStrings* LocalisedStrings::getCurrentMappings() throw()
  7203. {
  7204. return currentMappings;
  7205. }
  7206. const String LocalisedStrings::translateWithCurrentMappings (const String& text) throw()
  7207. {
  7208. const ScopedLock sl (currentMappingsLock);
  7209. if (currentMappings != 0)
  7210. return currentMappings->translate (text);
  7211. return text;
  7212. }
  7213. const String LocalisedStrings::translateWithCurrentMappings (const char* text) throw()
  7214. {
  7215. return translateWithCurrentMappings (String (text));
  7216. }
  7217. END_JUCE_NAMESPACE
  7218. /********* End of inlined file: juce_LocalisedStrings.cpp *********/
  7219. /********* Start of inlined file: juce_String.cpp *********/
  7220. #ifdef _MSC_VER
  7221. #pragma warning (disable: 4514)
  7222. #pragma warning (push)
  7223. #endif
  7224. #include <locale>
  7225. #if JUCE_MSVC
  7226. #include <float.h>
  7227. #endif
  7228. BEGIN_JUCE_NAMESPACE
  7229. #ifdef _MSC_VER
  7230. #pragma warning (pop)
  7231. #endif
  7232. static const char* const emptyCharString = "\0\0\0\0JUCE";
  7233. static const int safeEmptyStringRefCount = 0x3fffffff;
  7234. String::InternalRefCountedStringHolder String::emptyString = { safeEmptyStringRefCount, 0, { 0 } };
  7235. static tchar decimalPoint = T('.');
  7236. void juce_initialiseStrings()
  7237. {
  7238. decimalPoint = String::fromUTF8 ((const uint8*) localeconv()->decimal_point) [0];
  7239. }
  7240. void String::deleteInternal() throw()
  7241. {
  7242. if (atomicDecrementAndReturn (text->refCount) == 0)
  7243. juce_free (text);
  7244. }
  7245. void String::createInternal (const int numChars) throw()
  7246. {
  7247. jassert (numChars > 0);
  7248. text = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7249. + numChars * sizeof (tchar));
  7250. text->refCount = 1;
  7251. text->allocatedNumChars = numChars;
  7252. text->text[0] = 0;
  7253. }
  7254. void String::createInternal (const tchar* const t, const tchar* const textEnd) throw()
  7255. {
  7256. jassert (*(textEnd - 1) == 0); // must have a null terminator
  7257. const int numChars = (int) (textEnd - t);
  7258. createInternal (numChars - 1);
  7259. memcpy (text->text, t, numChars * sizeof (tchar));
  7260. }
  7261. void String::appendInternal (const tchar* const newText,
  7262. const int numExtraChars) throw()
  7263. {
  7264. if (numExtraChars > 0)
  7265. {
  7266. const int oldLen = CharacterFunctions::length (text->text);
  7267. const int newTotalLen = oldLen + numExtraChars;
  7268. if (text->refCount > 1)
  7269. {
  7270. // it's in use by other strings as well, so we need to make a private copy before messing with it..
  7271. InternalRefCountedStringHolder* const newTextHolder
  7272. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7273. + newTotalLen * sizeof (tchar));
  7274. newTextHolder->refCount = 1;
  7275. newTextHolder->allocatedNumChars = newTotalLen;
  7276. memcpy (newTextHolder->text, text->text, oldLen * sizeof (tchar));
  7277. memcpy (newTextHolder->text + oldLen, newText, numExtraChars * sizeof (tchar));
  7278. InternalRefCountedStringHolder* const old = text;
  7279. text = newTextHolder;
  7280. if (atomicDecrementAndReturn (old->refCount) == 0)
  7281. juce_free (old);
  7282. }
  7283. else
  7284. {
  7285. // no other strings using it, so just expand it if needed..
  7286. if (newTotalLen > text->allocatedNumChars)
  7287. {
  7288. text = (InternalRefCountedStringHolder*)
  7289. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7290. + newTotalLen * sizeof (tchar));
  7291. text->allocatedNumChars = newTotalLen;
  7292. }
  7293. memcpy (text->text + oldLen, newText, numExtraChars * sizeof (tchar));
  7294. }
  7295. text->text [newTotalLen] = 0;
  7296. }
  7297. }
  7298. void String::dupeInternalIfMultiplyReferenced() throw()
  7299. {
  7300. if (text->refCount > 1)
  7301. {
  7302. InternalRefCountedStringHolder* const old = text;
  7303. const int len = old->allocatedNumChars;
  7304. InternalRefCountedStringHolder* const newTextHolder
  7305. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7306. + len * sizeof (tchar));
  7307. newTextHolder->refCount = 1;
  7308. newTextHolder->allocatedNumChars = len;
  7309. memcpy (newTextHolder->text, old->text, (len + 1) * sizeof (tchar));
  7310. text = newTextHolder;
  7311. if (atomicDecrementAndReturn (old->refCount) == 0)
  7312. juce_free (old);
  7313. }
  7314. }
  7315. const String String::empty;
  7316. String::String() throw()
  7317. : text (&emptyString)
  7318. {
  7319. }
  7320. String::String (const String& other) throw()
  7321. : text (other.text)
  7322. {
  7323. atomicIncrement (text->refCount);
  7324. }
  7325. String::String (const int numChars,
  7326. const int /*dummyVariable*/) throw()
  7327. {
  7328. createInternal (numChars);
  7329. }
  7330. String::String (const char* const t) throw()
  7331. {
  7332. if (t != 0 && *t != 0)
  7333. {
  7334. const int len = CharacterFunctions::length (t);
  7335. createInternal (len);
  7336. #if JUCE_STRINGS_ARE_UNICODE
  7337. CharacterFunctions::copy (text->text, t, len + 1);
  7338. #else
  7339. memcpy (text->text, t, len + 1);
  7340. #endif
  7341. }
  7342. else
  7343. {
  7344. text = &emptyString;
  7345. emptyString.refCount = safeEmptyStringRefCount;
  7346. }
  7347. }
  7348. String::String (const juce_wchar* const t) throw()
  7349. {
  7350. if (t != 0 && *t != 0)
  7351. {
  7352. #if JUCE_STRINGS_ARE_UNICODE
  7353. const int len = CharacterFunctions::length (t);
  7354. createInternal (len);
  7355. memcpy (text->text, t, (len + 1) * sizeof (tchar));
  7356. #else
  7357. const int len = CharacterFunctions::bytesRequiredForCopy (t);
  7358. createInternal (len);
  7359. CharacterFunctions::copy (text->text, t, len + 1);
  7360. #endif
  7361. }
  7362. else
  7363. {
  7364. text = &emptyString;
  7365. emptyString.refCount = safeEmptyStringRefCount;
  7366. }
  7367. }
  7368. String::String (const char* const t,
  7369. const int maxChars) throw()
  7370. {
  7371. int i;
  7372. for (i = 0; i < maxChars; ++i)
  7373. if (t[i] == 0)
  7374. break;
  7375. if (i > 0)
  7376. {
  7377. createInternal (i);
  7378. #if JUCE_STRINGS_ARE_UNICODE
  7379. CharacterFunctions::copy (text->text, t, i);
  7380. #else
  7381. memcpy (text->text, t, i);
  7382. #endif
  7383. text->text [i] = 0;
  7384. }
  7385. else
  7386. {
  7387. text = &emptyString;
  7388. emptyString.refCount = safeEmptyStringRefCount;
  7389. }
  7390. }
  7391. String::String (const juce_wchar* const t,
  7392. const int maxChars) throw()
  7393. {
  7394. int i;
  7395. for (i = 0; i < maxChars; ++i)
  7396. if (t[i] == 0)
  7397. break;
  7398. if (i > 0)
  7399. {
  7400. createInternal (i);
  7401. #if JUCE_STRINGS_ARE_UNICODE
  7402. memcpy (text->text, t, i * sizeof (tchar));
  7403. #else
  7404. CharacterFunctions::copy (text->text, t, i);
  7405. #endif
  7406. text->text [i] = 0;
  7407. }
  7408. else
  7409. {
  7410. text = &emptyString;
  7411. emptyString.refCount = safeEmptyStringRefCount;
  7412. }
  7413. }
  7414. const String String::charToString (const tchar character) throw()
  7415. {
  7416. tchar temp[2];
  7417. temp[0] = character;
  7418. temp[1] = 0;
  7419. return String (temp);
  7420. }
  7421. // pass in a pointer to the END of a buffer..
  7422. static tchar* int64ToCharString (tchar* t, const int64 n) throw()
  7423. {
  7424. *--t = 0;
  7425. int64 v = (n >= 0) ? n : -n;
  7426. do
  7427. {
  7428. *--t = (tchar) (T('0') + (int) (v % 10));
  7429. v /= 10;
  7430. } while (v > 0);
  7431. if (n < 0)
  7432. *--t = T('-');
  7433. return t;
  7434. }
  7435. static tchar* intToCharString (tchar* t, const int n) throw()
  7436. {
  7437. if (n == (int) 0x80000000) // (would cause an overflow)
  7438. return int64ToCharString (t, n);
  7439. *--t = 0;
  7440. int v = abs (n);
  7441. do
  7442. {
  7443. *--t = (tchar) (T('0') + (v % 10));
  7444. v /= 10;
  7445. } while (v > 0);
  7446. if (n < 0)
  7447. *--t = T('-');
  7448. return t;
  7449. }
  7450. static tchar* uintToCharString (tchar* t, unsigned int v) throw()
  7451. {
  7452. *--t = 0;
  7453. do
  7454. {
  7455. *--t = (tchar) (T('0') + (v % 10));
  7456. v /= 10;
  7457. } while (v > 0);
  7458. return t;
  7459. }
  7460. String::String (const int number) throw()
  7461. {
  7462. tchar buffer [16];
  7463. tchar* const end = buffer + 16;
  7464. createInternal (intToCharString (end, number), end);
  7465. }
  7466. String::String (const unsigned int number) throw()
  7467. {
  7468. tchar buffer [16];
  7469. tchar* const end = buffer + 16;
  7470. createInternal (uintToCharString (end, number), end);
  7471. }
  7472. String::String (const short number) throw()
  7473. {
  7474. tchar buffer [16];
  7475. tchar* const end = buffer + 16;
  7476. createInternal (intToCharString (end, (int) number), end);
  7477. }
  7478. String::String (const unsigned short number) throw()
  7479. {
  7480. tchar buffer [16];
  7481. tchar* const end = buffer + 16;
  7482. createInternal (uintToCharString (end, (unsigned int) number), end);
  7483. }
  7484. String::String (const int64 number) throw()
  7485. {
  7486. tchar buffer [32];
  7487. tchar* const end = buffer + 32;
  7488. createInternal (int64ToCharString (end, number), end);
  7489. }
  7490. String::String (const uint64 number) throw()
  7491. {
  7492. tchar buffer [32];
  7493. tchar* const end = buffer + 32;
  7494. tchar* t = end;
  7495. *--t = 0;
  7496. int64 v = number;
  7497. do
  7498. {
  7499. *--t = (tchar) (T('0') + (int) (v % 10));
  7500. v /= 10;
  7501. } while (v > 0);
  7502. createInternal (t, end);
  7503. }
  7504. // a double-to-string routine that actually uses the number of dec. places you asked for
  7505. // without resorting to exponent notation if the number's too big or small (which is what printf does).
  7506. void String::doubleToStringWithDecPlaces (double n, int numDecPlaces) throw()
  7507. {
  7508. const int bufSize = 80;
  7509. tchar buffer [bufSize];
  7510. int len;
  7511. tchar* t;
  7512. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  7513. {
  7514. int64 v = (int64) (pow (10.0, numDecPlaces) * fabs (n) + 0.5);
  7515. t = buffer + bufSize;
  7516. *--t = (tchar) 0;
  7517. while (numDecPlaces >= 0 || v > 0)
  7518. {
  7519. if (numDecPlaces == 0)
  7520. *--t = decimalPoint;
  7521. *--t = (tchar) (T('0') + (v % 10));
  7522. v /= 10;
  7523. --numDecPlaces;
  7524. }
  7525. if (n < 0)
  7526. *--t = T('-');
  7527. len = (int) ((buffer + bufSize) - t);
  7528. }
  7529. else
  7530. {
  7531. len = CharacterFunctions::printf (buffer, bufSize, T("%.9g"), n) + 1;
  7532. t = buffer;
  7533. }
  7534. if (len > 1)
  7535. {
  7536. jassert (len < numElementsInArray (buffer));
  7537. createInternal (len - 1);
  7538. memcpy (text->text, t, len * sizeof (tchar));
  7539. }
  7540. else
  7541. {
  7542. jassert (*t == 0);
  7543. text = &emptyString;
  7544. emptyString.refCount = safeEmptyStringRefCount;
  7545. }
  7546. }
  7547. String::String (const float number,
  7548. const int numberOfDecimalPlaces) throw()
  7549. {
  7550. doubleToStringWithDecPlaces ((double) number,
  7551. numberOfDecimalPlaces);
  7552. }
  7553. String::String (const double number,
  7554. const int numberOfDecimalPlaces) throw()
  7555. {
  7556. doubleToStringWithDecPlaces (number,
  7557. numberOfDecimalPlaces);
  7558. }
  7559. String::~String() throw()
  7560. {
  7561. if (atomicDecrementAndReturn (text->refCount) == 0)
  7562. juce_free (text);
  7563. }
  7564. void String::preallocateStorage (const int numChars) throw()
  7565. {
  7566. if (numChars > text->allocatedNumChars)
  7567. {
  7568. dupeInternalIfMultiplyReferenced();
  7569. text = (InternalRefCountedStringHolder*) juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7570. + numChars * sizeof (tchar));
  7571. text->allocatedNumChars = numChars;
  7572. }
  7573. }
  7574. #if JUCE_STRINGS_ARE_UNICODE
  7575. String::operator const char*() const throw()
  7576. {
  7577. if (isEmpty())
  7578. {
  7579. return (const char*) emptyCharString;
  7580. }
  7581. else
  7582. {
  7583. String* const mutableThis = const_cast <String*> (this);
  7584. mutableThis->dupeInternalIfMultiplyReferenced();
  7585. int len = CharacterFunctions::bytesRequiredForCopy (text->text) + 1;
  7586. mutableThis->text = (InternalRefCountedStringHolder*)
  7587. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7588. + (len * sizeof (juce_wchar) + len));
  7589. char* otherCopy = (char*) (text->text + len);
  7590. --len;
  7591. CharacterFunctions::copy (otherCopy, text->text, len);
  7592. otherCopy [len] = 0;
  7593. return otherCopy;
  7594. }
  7595. }
  7596. #else
  7597. String::operator const juce_wchar*() const throw()
  7598. {
  7599. if (isEmpty())
  7600. {
  7601. return (const juce_wchar*) emptyCharString;
  7602. }
  7603. else
  7604. {
  7605. String* const mutableThis = const_cast <String*> (this);
  7606. mutableThis->dupeInternalIfMultiplyReferenced();
  7607. int len = CharacterFunctions::length (text->text) + 1;
  7608. mutableThis->text = (InternalRefCountedStringHolder*)
  7609. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7610. + (len * sizeof (juce_wchar) + len));
  7611. juce_wchar* otherCopy = (juce_wchar*) (text->text + len);
  7612. --len;
  7613. CharacterFunctions::copy (otherCopy, text->text, len);
  7614. otherCopy [len] = 0;
  7615. return otherCopy;
  7616. }
  7617. }
  7618. #endif
  7619. void String::copyToBuffer (char* const destBuffer,
  7620. const int bufferSizeBytes) const throw()
  7621. {
  7622. #if JUCE_STRINGS_ARE_UNICODE
  7623. const int len = jmin (bufferSizeBytes, CharacterFunctions::bytesRequiredForCopy (text->text));
  7624. CharacterFunctions::copy (destBuffer, text->text, len);
  7625. #else
  7626. const int len = jmin (bufferSizeBytes, length());
  7627. memcpy (destBuffer, text->text, len * sizeof (tchar));
  7628. #endif
  7629. destBuffer [len] = 0;
  7630. }
  7631. void String::copyToBuffer (juce_wchar* const destBuffer,
  7632. const int maxCharsToCopy) const throw()
  7633. {
  7634. const int len = jmin (maxCharsToCopy, length());
  7635. #if JUCE_STRINGS_ARE_UNICODE
  7636. memcpy (destBuffer, text->text, len * sizeof (juce_wchar));
  7637. #else
  7638. CharacterFunctions::copy (destBuffer, text->text, len);
  7639. #endif
  7640. destBuffer [len] = 0;
  7641. }
  7642. int String::length() const throw()
  7643. {
  7644. return CharacterFunctions::length (text->text);
  7645. }
  7646. int String::hashCode() const throw()
  7647. {
  7648. const tchar* t = text->text;
  7649. int result = 0;
  7650. while (*t != (tchar) 0)
  7651. result = 31 * result + *t++;
  7652. return result;
  7653. }
  7654. int64 String::hashCode64() const throw()
  7655. {
  7656. const tchar* t = text->text;
  7657. int64 result = 0;
  7658. while (*t != (tchar) 0)
  7659. result = 101 * result + *t++;
  7660. return result;
  7661. }
  7662. const String& String::operator= (const tchar* const otherText) throw()
  7663. {
  7664. if (otherText != 0 && *otherText != 0)
  7665. {
  7666. const int otherLen = CharacterFunctions::length (otherText);
  7667. if (otherLen > 0)
  7668. {
  7669. // avoid resizing the memory block if the string is
  7670. // shrinking..
  7671. if (text->refCount > 1
  7672. || otherLen > text->allocatedNumChars
  7673. || otherLen <= (text->allocatedNumChars >> 1))
  7674. {
  7675. deleteInternal();
  7676. createInternal (otherLen);
  7677. }
  7678. memcpy (text->text, otherText, (otherLen + 1) * sizeof (tchar));
  7679. return *this;
  7680. }
  7681. }
  7682. deleteInternal();
  7683. text = &emptyString;
  7684. emptyString.refCount = safeEmptyStringRefCount;
  7685. return *this;
  7686. }
  7687. const String& String::operator= (const String& other) throw()
  7688. {
  7689. if (this != &other)
  7690. {
  7691. atomicIncrement (other.text->refCount);
  7692. if (atomicDecrementAndReturn (text->refCount) == 0)
  7693. juce_free (text);
  7694. text = other.text;
  7695. }
  7696. return *this;
  7697. }
  7698. bool String::operator== (const String& other) const throw()
  7699. {
  7700. return text == other.text
  7701. || CharacterFunctions::compare (text->text, other.text->text) == 0;
  7702. }
  7703. bool String::operator== (const tchar* const t) const throw()
  7704. {
  7705. return t != 0 ? CharacterFunctions::compare (text->text, t) == 0
  7706. : isEmpty();
  7707. }
  7708. bool String::equalsIgnoreCase (const tchar* t) const throw()
  7709. {
  7710. return t != 0 ? CharacterFunctions::compareIgnoreCase (text->text, t) == 0
  7711. : isEmpty();
  7712. }
  7713. bool String::equalsIgnoreCase (const String& other) const throw()
  7714. {
  7715. return text == other.text
  7716. || CharacterFunctions::compareIgnoreCase (text->text, other.text->text) == 0;
  7717. }
  7718. bool String::operator!= (const String& other) const throw()
  7719. {
  7720. return text != other.text
  7721. && CharacterFunctions::compare (text->text, other.text->text) != 0;
  7722. }
  7723. bool String::operator!= (const tchar* const t) const throw()
  7724. {
  7725. return t != 0 ? (CharacterFunctions::compare (text->text, t) != 0)
  7726. : isNotEmpty();
  7727. }
  7728. bool String::operator> (const String& other) const throw()
  7729. {
  7730. return compare (other) > 0;
  7731. }
  7732. bool String::operator< (const tchar* const other) const throw()
  7733. {
  7734. return compare (other) < 0;
  7735. }
  7736. bool String::operator>= (const String& other) const throw()
  7737. {
  7738. return compare (other) >= 0;
  7739. }
  7740. bool String::operator<= (const tchar* const other) const throw()
  7741. {
  7742. return compare (other) <= 0;
  7743. }
  7744. int String::compare (const tchar* const other) const throw()
  7745. {
  7746. return other != 0 ? CharacterFunctions::compare (text->text, other)
  7747. : isEmpty();
  7748. }
  7749. int String::compareIgnoreCase (const tchar* const other) const throw()
  7750. {
  7751. return other != 0 ? CharacterFunctions::compareIgnoreCase (text->text, other)
  7752. : isEmpty();
  7753. }
  7754. int String::compareLexicographically (const tchar* other) const throw()
  7755. {
  7756. if (other == 0)
  7757. return isEmpty();
  7758. const tchar* s1 = text->text;
  7759. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  7760. ++s1;
  7761. while (*other != 0 && ! CharacterFunctions::isLetterOrDigit (*other))
  7762. ++other;
  7763. return CharacterFunctions::compareIgnoreCase (s1, other);
  7764. }
  7765. const String String::operator+ (const String& other) const throw()
  7766. {
  7767. if (*(other.text->text) == 0)
  7768. return *this;
  7769. if (isEmpty())
  7770. return other;
  7771. const int len = CharacterFunctions::length (text->text);
  7772. const int otherLen = CharacterFunctions::length (other.text->text);
  7773. String result (len + otherLen, (int) 0);
  7774. memcpy (result.text->text, text->text, len * sizeof (tchar));
  7775. memcpy (result.text->text + len, other.text->text, otherLen * sizeof (tchar));
  7776. result.text->text [len + otherLen] = 0;
  7777. return result;
  7778. }
  7779. const String String::operator+ (const tchar* const textToAppend) const throw()
  7780. {
  7781. if (textToAppend == 0 || *textToAppend == 0)
  7782. return *this;
  7783. const int len = CharacterFunctions::length (text->text);
  7784. const int otherLen = CharacterFunctions::length (textToAppend);
  7785. String result (len + otherLen, (int) 0);
  7786. memcpy (result.text->text, text->text, len * sizeof (tchar));
  7787. memcpy (result.text->text + len, textToAppend, otherLen * sizeof (tchar));
  7788. result.text->text [len + otherLen] = 0;
  7789. return result;
  7790. }
  7791. const String String::operator+ (const tchar characterToAppend) const throw()
  7792. {
  7793. if (characterToAppend == 0)
  7794. return *this;
  7795. const int len = CharacterFunctions::length (text->text);
  7796. String result ((int) (len + 1), (int) 0);
  7797. memcpy (result.text->text, text->text, len * sizeof (tchar));
  7798. result.text->text[len] = characterToAppend;
  7799. result.text->text[len + 1] = 0;
  7800. return result;
  7801. }
  7802. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  7803. const String& string2) throw()
  7804. {
  7805. String s (string1);
  7806. s += string2;
  7807. return s;
  7808. }
  7809. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  7810. const String& string2) throw()
  7811. {
  7812. String s (string1);
  7813. s += string2;
  7814. return s;
  7815. }
  7816. const String& String::operator+= (const tchar* const t) throw()
  7817. {
  7818. if (t != 0)
  7819. appendInternal (t, CharacterFunctions::length (t));
  7820. return *this;
  7821. }
  7822. const String& String::operator+= (const String& other) throw()
  7823. {
  7824. if (isEmpty())
  7825. operator= (other);
  7826. else
  7827. appendInternal (other.text->text,
  7828. CharacterFunctions::length (other.text->text));
  7829. return *this;
  7830. }
  7831. const String& String::operator+= (const char ch) throw()
  7832. {
  7833. char asString[2];
  7834. asString[0] = ch;
  7835. asString[1] = 0;
  7836. #if JUCE_STRINGS_ARE_UNICODE
  7837. operator+= (String (asString));
  7838. #else
  7839. appendInternal (asString, 1);
  7840. #endif
  7841. return *this;
  7842. }
  7843. const String& String::operator+= (const juce_wchar ch) throw()
  7844. {
  7845. juce_wchar asString[2];
  7846. asString[0] = ch;
  7847. asString[1] = 0;
  7848. #if JUCE_STRINGS_ARE_UNICODE
  7849. appendInternal (asString, 1);
  7850. #else
  7851. operator+= (String (asString));
  7852. #endif
  7853. return *this;
  7854. }
  7855. void String::append (const tchar* const other,
  7856. const int howMany) throw()
  7857. {
  7858. if (howMany > 0)
  7859. {
  7860. int i;
  7861. for (i = 0; i < howMany; ++i)
  7862. if (other[i] == 0)
  7863. break;
  7864. appendInternal (other, i);
  7865. }
  7866. }
  7867. String& String::operator<< (const int number) throw()
  7868. {
  7869. tchar buffer [64];
  7870. tchar* const end = buffer + 64;
  7871. const tchar* const t = intToCharString (end, number);
  7872. appendInternal (t, (int) (end - t) - 1);
  7873. return *this;
  7874. }
  7875. String& String::operator<< (const unsigned int number) throw()
  7876. {
  7877. tchar buffer [64];
  7878. tchar* const end = buffer + 64;
  7879. const tchar* const t = uintToCharString (end, number);
  7880. appendInternal (t, (int) (end - t) - 1);
  7881. return *this;
  7882. }
  7883. String& String::operator<< (const short number) throw()
  7884. {
  7885. tchar buffer [64];
  7886. tchar* const end = buffer + 64;
  7887. const tchar* const t = intToCharString (end, (int) number);
  7888. appendInternal (t, (int) (end - t) - 1);
  7889. return *this;
  7890. }
  7891. String& String::operator<< (const double number) throw()
  7892. {
  7893. operator+= (String (number));
  7894. return *this;
  7895. }
  7896. String& String::operator<< (const float number) throw()
  7897. {
  7898. operator+= (String (number));
  7899. return *this;
  7900. }
  7901. String& String::operator<< (const char character) throw()
  7902. {
  7903. operator+= (character);
  7904. return *this;
  7905. }
  7906. String& String::operator<< (const juce_wchar character) throw()
  7907. {
  7908. operator+= (character);
  7909. return *this;
  7910. }
  7911. String& String::operator<< (const char* const t) throw()
  7912. {
  7913. #if JUCE_STRINGS_ARE_UNICODE
  7914. operator+= (String (t));
  7915. #else
  7916. operator+= (t);
  7917. #endif
  7918. return *this;
  7919. }
  7920. String& String::operator<< (const juce_wchar* const t) throw()
  7921. {
  7922. #if JUCE_STRINGS_ARE_UNICODE
  7923. operator+= (t);
  7924. #else
  7925. operator+= (String (t));
  7926. #endif
  7927. return *this;
  7928. }
  7929. String& String::operator<< (const String& t) throw()
  7930. {
  7931. operator+= (t);
  7932. return *this;
  7933. }
  7934. int String::indexOfChar (const tchar character) const throw()
  7935. {
  7936. const tchar* t = text->text;
  7937. for (;;)
  7938. {
  7939. if (*t == character)
  7940. return (int) (t - text->text);
  7941. if (*t++ == 0)
  7942. return -1;
  7943. }
  7944. }
  7945. int String::lastIndexOfChar (const tchar character) const throw()
  7946. {
  7947. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  7948. if (text->text[i] == character)
  7949. return i;
  7950. return -1;
  7951. }
  7952. int String::indexOf (const tchar* const t) const throw()
  7953. {
  7954. const tchar* const r = CharacterFunctions::find (text->text, t);
  7955. return (r == 0) ? -1
  7956. : (int) (r - text->text);
  7957. }
  7958. int String::indexOfChar (const int startIndex,
  7959. const tchar character) const throw()
  7960. {
  7961. if (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text))
  7962. return -1;
  7963. const tchar* t = text->text + jmax (0, startIndex);
  7964. for (;;)
  7965. {
  7966. if (*t == character)
  7967. return (int) (t - text->text);
  7968. if (*t++ == 0)
  7969. return -1;
  7970. }
  7971. }
  7972. int String::indexOfAnyOf (const tchar* const charactersToLookFor,
  7973. const int startIndex,
  7974. const bool ignoreCase) const throw()
  7975. {
  7976. if (charactersToLookFor == 0
  7977. || (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text)))
  7978. return -1;
  7979. const tchar* t = text->text + jmax (0, startIndex);
  7980. while (*t != 0)
  7981. {
  7982. if (CharacterFunctions::indexOfChar (charactersToLookFor, *t, ignoreCase) >= 0)
  7983. return (int) (t - text->text);
  7984. ++t;
  7985. }
  7986. return -1;
  7987. }
  7988. int String::indexOf (const int startIndex,
  7989. const tchar* const other) const throw()
  7990. {
  7991. if (other == 0 || startIndex >= CharacterFunctions::length (text->text))
  7992. return -1;
  7993. const tchar* const found = CharacterFunctions::find (text->text + jmax (0, startIndex),
  7994. other);
  7995. return (found == 0) ? -1
  7996. : (int) (found - text->text);
  7997. }
  7998. int String::indexOfIgnoreCase (const tchar* const other) const throw()
  7999. {
  8000. if (other != 0 && *other != 0)
  8001. {
  8002. const int len = CharacterFunctions::length (other);
  8003. const int end = CharacterFunctions::length (text->text) - len;
  8004. for (int i = 0; i <= end; ++i)
  8005. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  8006. return i;
  8007. }
  8008. return -1;
  8009. }
  8010. int String::indexOfIgnoreCase (const int startIndex,
  8011. const tchar* const other) const throw()
  8012. {
  8013. if (other != 0 && *other != 0)
  8014. {
  8015. const int len = CharacterFunctions::length (other);
  8016. const int end = length() - len;
  8017. for (int i = jmax (0, startIndex); i <= end; ++i)
  8018. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  8019. return i;
  8020. }
  8021. return -1;
  8022. }
  8023. int String::lastIndexOf (const tchar* const other) const throw()
  8024. {
  8025. if (other != 0 && *other != 0)
  8026. {
  8027. const int len = CharacterFunctions::length (other);
  8028. int i = length() - len;
  8029. if (i >= 0)
  8030. {
  8031. const tchar* n = text->text + i;
  8032. while (i >= 0)
  8033. {
  8034. if (CharacterFunctions::compare (n--, other, len) == 0)
  8035. return i;
  8036. --i;
  8037. }
  8038. }
  8039. }
  8040. return -1;
  8041. }
  8042. int String::lastIndexOfIgnoreCase (const tchar* const other) const throw()
  8043. {
  8044. if (other != 0 && *other != 0)
  8045. {
  8046. const int len = CharacterFunctions::length (other);
  8047. int i = length() - len;
  8048. if (i >= 0)
  8049. {
  8050. const tchar* n = text->text + i;
  8051. while (i >= 0)
  8052. {
  8053. if (CharacterFunctions::compareIgnoreCase (n--, other, len) == 0)
  8054. return i;
  8055. --i;
  8056. }
  8057. }
  8058. }
  8059. return -1;
  8060. }
  8061. int String::lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  8062. const bool ignoreCase) const throw()
  8063. {
  8064. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  8065. if (CharacterFunctions::indexOfChar (charactersToLookFor, text->text [i], ignoreCase) >= 0)
  8066. return i;
  8067. return -1;
  8068. }
  8069. bool String::contains (const tchar* const other) const throw()
  8070. {
  8071. return indexOf (other) >= 0;
  8072. }
  8073. bool String::containsChar (const tchar character) const throw()
  8074. {
  8075. return indexOfChar (character) >= 0;
  8076. }
  8077. bool String::containsIgnoreCase (const tchar* const t) const throw()
  8078. {
  8079. return indexOfIgnoreCase (t) >= 0;
  8080. }
  8081. int String::indexOfWholeWord (const tchar* const word) const throw()
  8082. {
  8083. if (word != 0 && *word != 0)
  8084. {
  8085. const int wordLen = CharacterFunctions::length (word);
  8086. const int end = length() - wordLen;
  8087. const tchar* t = text->text;
  8088. for (int i = 0; i <= end; ++i)
  8089. {
  8090. if (CharacterFunctions::compare (t, word, wordLen) == 0
  8091. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  8092. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  8093. {
  8094. return i;
  8095. }
  8096. ++t;
  8097. }
  8098. }
  8099. return -1;
  8100. }
  8101. int String::indexOfWholeWordIgnoreCase (const tchar* const word) const throw()
  8102. {
  8103. if (word != 0 && *word != 0)
  8104. {
  8105. const int wordLen = CharacterFunctions::length (word);
  8106. const int end = length() - wordLen;
  8107. const tchar* t = text->text;
  8108. for (int i = 0; i <= end; ++i)
  8109. {
  8110. if (CharacterFunctions::compareIgnoreCase (t, word, wordLen) == 0
  8111. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  8112. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  8113. {
  8114. return i;
  8115. }
  8116. ++t;
  8117. }
  8118. }
  8119. return -1;
  8120. }
  8121. bool String::containsWholeWord (const tchar* const wordToLookFor) const throw()
  8122. {
  8123. return indexOfWholeWord (wordToLookFor) >= 0;
  8124. }
  8125. bool String::containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw()
  8126. {
  8127. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  8128. }
  8129. static int indexOfMatch (const tchar* const wildcard,
  8130. const tchar* const test,
  8131. const bool ignoreCase) throw()
  8132. {
  8133. int start = 0;
  8134. while (test [start] != 0)
  8135. {
  8136. int i = 0;
  8137. for (;;)
  8138. {
  8139. const tchar wc = wildcard [i];
  8140. const tchar c = test [i + start];
  8141. if (wc == c
  8142. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  8143. || (wc == T('?') && c != 0))
  8144. {
  8145. if (wc == 0)
  8146. return start;
  8147. ++i;
  8148. }
  8149. else
  8150. {
  8151. if (wc == T('*') && (wildcard [i + 1] == 0
  8152. || indexOfMatch (wildcard + i + 1,
  8153. test + start + i,
  8154. ignoreCase) >= 0))
  8155. {
  8156. return start;
  8157. }
  8158. break;
  8159. }
  8160. }
  8161. ++start;
  8162. }
  8163. return -1;
  8164. }
  8165. bool String::matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw()
  8166. {
  8167. int i = 0;
  8168. for (;;)
  8169. {
  8170. const tchar wc = wildcard [i];
  8171. const tchar c = text->text [i];
  8172. if (wc == c
  8173. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  8174. || (wc == T('?') && c != 0))
  8175. {
  8176. if (wc == 0)
  8177. return true;
  8178. ++i;
  8179. }
  8180. else
  8181. {
  8182. return wc == T('*') && (wildcard [i + 1] == 0
  8183. || indexOfMatch (wildcard + i + 1,
  8184. text->text + i,
  8185. ignoreCase) >= 0);
  8186. }
  8187. }
  8188. }
  8189. void String::printf (const tchar* const pf, ...) throw()
  8190. {
  8191. va_list list;
  8192. va_start (list, pf);
  8193. vprintf (pf, list);
  8194. }
  8195. const String String::formatted (const tchar* const pf, ...) throw()
  8196. {
  8197. va_list list;
  8198. va_start (list, pf);
  8199. String result;
  8200. result.vprintf (pf, list);
  8201. return result;
  8202. }
  8203. void String::vprintf (const tchar* const pf, va_list& args) throw()
  8204. {
  8205. tchar stackBuf [256];
  8206. unsigned int bufSize = 256;
  8207. tchar* buf = stackBuf;
  8208. deleteInternal();
  8209. do
  8210. {
  8211. #if JUCE_LINUX && JUCE_64BIT
  8212. va_list tempArgs;
  8213. va_copy (tempArgs, args);
  8214. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, tempArgs);
  8215. va_end (tempArgs);
  8216. #else
  8217. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, args);
  8218. #endif
  8219. if (num > 0)
  8220. {
  8221. createInternal (num);
  8222. memcpy (text->text, buf, (num + 1) * sizeof (tchar));
  8223. break;
  8224. }
  8225. else if (num == 0)
  8226. {
  8227. text = &emptyString;
  8228. emptyString.refCount = safeEmptyStringRefCount;
  8229. break;
  8230. }
  8231. if (buf != stackBuf)
  8232. juce_free (buf);
  8233. bufSize += 256;
  8234. buf = (tchar*) juce_malloc (bufSize * sizeof (tchar));
  8235. }
  8236. while (bufSize < 65536); // this is a sanity check to avoid situations where vprintf repeatedly
  8237. // returns -1 because of an error rather than because it needs more space.
  8238. if (buf != stackBuf)
  8239. juce_free (buf);
  8240. }
  8241. const String String::repeatedString (const tchar* const stringToRepeat,
  8242. int numberOfTimesToRepeat) throw()
  8243. {
  8244. const int len = CharacterFunctions::length (stringToRepeat);
  8245. String result ((int) (len * numberOfTimesToRepeat + 1), (int) 0);
  8246. tchar* n = result.text->text;
  8247. n[0] = 0;
  8248. while (--numberOfTimesToRepeat >= 0)
  8249. {
  8250. CharacterFunctions::append (n, stringToRepeat);
  8251. n += len;
  8252. }
  8253. return result;
  8254. }
  8255. const String String::replaceSection (int index,
  8256. int numCharsToReplace,
  8257. const tchar* const stringToInsert) const throw()
  8258. {
  8259. if (index < 0)
  8260. {
  8261. // a negative index to replace from?
  8262. jassertfalse
  8263. index = 0;
  8264. }
  8265. if (numCharsToReplace < 0)
  8266. {
  8267. // replacing a negative number of characters?
  8268. numCharsToReplace = 0;
  8269. jassertfalse;
  8270. }
  8271. const int len = length();
  8272. if (index + numCharsToReplace > len)
  8273. {
  8274. if (index > len)
  8275. {
  8276. // replacing beyond the end of the string?
  8277. index = len;
  8278. jassertfalse
  8279. }
  8280. numCharsToReplace = len - index;
  8281. }
  8282. const int newStringLen = (stringToInsert != 0) ? CharacterFunctions::length (stringToInsert) : 0;
  8283. const int newTotalLen = len + newStringLen - numCharsToReplace;
  8284. String result (newTotalLen, (int) 0);
  8285. memcpy (result.text->text,
  8286. text->text,
  8287. index * sizeof (tchar));
  8288. if (newStringLen > 0)
  8289. memcpy (result.text->text + index,
  8290. stringToInsert,
  8291. newStringLen * sizeof (tchar));
  8292. const int endStringLen = newTotalLen - (index + newStringLen);
  8293. if (endStringLen > 0)
  8294. memcpy (result.text->text + (index + newStringLen),
  8295. text->text + (index + numCharsToReplace),
  8296. endStringLen * sizeof (tchar));
  8297. result.text->text [newTotalLen] = 0;
  8298. return result;
  8299. }
  8300. const String String::replace (const tchar* const stringToReplace,
  8301. const tchar* const stringToInsert,
  8302. const bool ignoreCase) const throw()
  8303. {
  8304. const int stringToReplaceLen = CharacterFunctions::length (stringToReplace);
  8305. const int stringToInsertLen = CharacterFunctions::length (stringToInsert);
  8306. int i = 0;
  8307. String result (*this);
  8308. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  8309. : result.indexOf (i, stringToReplace))) >= 0)
  8310. {
  8311. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  8312. i += stringToInsertLen;
  8313. }
  8314. return result;
  8315. }
  8316. const String String::replaceCharacter (const tchar charToReplace,
  8317. const tchar charToInsert) const throw()
  8318. {
  8319. const int index = indexOfChar (charToReplace);
  8320. if (index < 0)
  8321. return *this;
  8322. String result (*this);
  8323. result.dupeInternalIfMultiplyReferenced();
  8324. tchar* t = result.text->text + index;
  8325. while (*t != 0)
  8326. {
  8327. if (*t == charToReplace)
  8328. *t = charToInsert;
  8329. ++t;
  8330. }
  8331. return result;
  8332. }
  8333. const String String::replaceCharacters (const String& charactersToReplace,
  8334. const tchar* const charactersToInsertInstead) const throw()
  8335. {
  8336. String result (*this);
  8337. result.dupeInternalIfMultiplyReferenced();
  8338. tchar* t = result.text->text;
  8339. const int len2 = CharacterFunctions::length (charactersToInsertInstead);
  8340. // the two strings passed in are supposed to be the same length!
  8341. jassert (len2 == charactersToReplace.length());
  8342. while (*t != 0)
  8343. {
  8344. const int index = charactersToReplace.indexOfChar (*t);
  8345. if (((unsigned int) index) < (unsigned int) len2)
  8346. *t = charactersToInsertInstead [index];
  8347. ++t;
  8348. }
  8349. return result;
  8350. }
  8351. bool String::startsWith (const tchar* const other) const throw()
  8352. {
  8353. return other != 0
  8354. && CharacterFunctions::compare (text->text, other, CharacterFunctions::length (other)) == 0;
  8355. }
  8356. bool String::startsWithIgnoreCase (const tchar* const other) const throw()
  8357. {
  8358. return other != 0
  8359. && CharacterFunctions::compareIgnoreCase (text->text, other, CharacterFunctions::length (other)) == 0;
  8360. }
  8361. bool String::startsWithChar (const tchar character) const throw()
  8362. {
  8363. return text->text[0] == character;
  8364. }
  8365. bool String::endsWithChar (const tchar character) const throw()
  8366. {
  8367. return text->text[0] != 0
  8368. && text->text [length() - 1] == character;
  8369. }
  8370. bool String::endsWith (const tchar* const other) const throw()
  8371. {
  8372. if (other == 0)
  8373. return false;
  8374. const int thisLen = length();
  8375. const int otherLen = CharacterFunctions::length (other);
  8376. return thisLen >= otherLen
  8377. && CharacterFunctions::compare (text->text + thisLen - otherLen, other) == 0;
  8378. }
  8379. bool String::endsWithIgnoreCase (const tchar* const other) const throw()
  8380. {
  8381. if (other == 0)
  8382. return false;
  8383. const int thisLen = length();
  8384. const int otherLen = CharacterFunctions::length (other);
  8385. return thisLen >= otherLen
  8386. && CharacterFunctions::compareIgnoreCase (text->text + thisLen - otherLen, other) == 0;
  8387. }
  8388. const String String::toUpperCase() const throw()
  8389. {
  8390. String result (*this);
  8391. result.dupeInternalIfMultiplyReferenced();
  8392. CharacterFunctions::toUpperCase (result.text->text);
  8393. return result;
  8394. }
  8395. const String String::toLowerCase() const throw()
  8396. {
  8397. String result (*this);
  8398. result.dupeInternalIfMultiplyReferenced();
  8399. CharacterFunctions::toLowerCase (result.text->text);
  8400. return result;
  8401. }
  8402. tchar& String::operator[] (const int index) throw()
  8403. {
  8404. jassert (((unsigned int) index) <= (unsigned int) length());
  8405. dupeInternalIfMultiplyReferenced();
  8406. return text->text [index];
  8407. }
  8408. tchar String::getLastCharacter() const throw()
  8409. {
  8410. return (isEmpty()) ? ((tchar) 0)
  8411. : text->text [CharacterFunctions::length (text->text) - 1];
  8412. }
  8413. const String String::substring (int start, int end) const throw()
  8414. {
  8415. if (start < 0)
  8416. start = 0;
  8417. else if (end <= start)
  8418. return empty;
  8419. int len = 0;
  8420. const tchar* const t = text->text;
  8421. while (len <= end && t [len] != 0)
  8422. ++len;
  8423. if (end >= len)
  8424. {
  8425. if (start == 0)
  8426. return *this;
  8427. end = len;
  8428. }
  8429. return String (text->text + start,
  8430. end - start);
  8431. }
  8432. const String String::substring (const int start) const throw()
  8433. {
  8434. if (start <= 0)
  8435. return *this;
  8436. const int len = CharacterFunctions::length (text->text);
  8437. if (start >= len)
  8438. return empty;
  8439. else
  8440. return String (text->text + start,
  8441. len - start);
  8442. }
  8443. const String String::dropLastCharacters (const int numberToDrop) const throw()
  8444. {
  8445. return String (text->text,
  8446. jmax (0, CharacterFunctions::length (text->text) - numberToDrop));
  8447. }
  8448. const String String::fromFirstOccurrenceOf (const tchar* const sub,
  8449. const bool includeSubString,
  8450. const bool ignoreCase) const throw()
  8451. {
  8452. const int i = ignoreCase ? indexOf (sub)
  8453. : indexOfIgnoreCase (sub);
  8454. if (i < 0)
  8455. return empty;
  8456. else
  8457. return substring ((includeSubString) ? i : i + CharacterFunctions::length (sub));
  8458. }
  8459. const String String::fromLastOccurrenceOf (const tchar* const sub,
  8460. const bool includeSubString,
  8461. const bool ignoreCase) const throw()
  8462. {
  8463. const int i = ignoreCase ? lastIndexOf (sub)
  8464. : lastIndexOfIgnoreCase (sub);
  8465. if (i < 0)
  8466. return *this;
  8467. else
  8468. return substring ((includeSubString) ? i : i + CharacterFunctions::length (sub));
  8469. }
  8470. const String String::upToFirstOccurrenceOf (const tchar* const sub,
  8471. const bool includeSubString,
  8472. const bool ignoreCase) const throw()
  8473. {
  8474. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  8475. : indexOf (sub);
  8476. if (i < 0)
  8477. return *this;
  8478. else
  8479. return substring (0, (includeSubString) ? i + CharacterFunctions::length (sub) : i);
  8480. }
  8481. const String String::upToLastOccurrenceOf (const tchar* const sub,
  8482. const bool includeSubString,
  8483. const bool ignoreCase) const throw()
  8484. {
  8485. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  8486. : lastIndexOf (sub);
  8487. if (i < 0)
  8488. return *this;
  8489. return substring (0, (includeSubString) ? i + CharacterFunctions::length (sub) : i);
  8490. }
  8491. bool String::isQuotedString() const throw()
  8492. {
  8493. const String trimmed (trimStart());
  8494. return trimmed[0] == T('"')
  8495. || trimmed[0] == T('\'');
  8496. }
  8497. const String String::unquoted() const throw()
  8498. {
  8499. String s (*this);
  8500. if (s[0] == T('"') || s[0] == T('\''))
  8501. s = s.substring (1);
  8502. const int lastCharIndex = s.length() - 1;
  8503. if (lastCharIndex >= 0
  8504. && (s [lastCharIndex] == T('"') || s[lastCharIndex] == T('\'')))
  8505. s [lastCharIndex] = 0;
  8506. return s;
  8507. }
  8508. const String String::quoted (const tchar quoteCharacter) const throw()
  8509. {
  8510. if (isEmpty())
  8511. return charToString (quoteCharacter) + quoteCharacter;
  8512. String t (*this);
  8513. if (! t.startsWithChar (quoteCharacter))
  8514. t = charToString (quoteCharacter) + t;
  8515. if (! t.endsWithChar (quoteCharacter))
  8516. t += quoteCharacter;
  8517. return t;
  8518. }
  8519. const String String::trim() const throw()
  8520. {
  8521. if (isEmpty())
  8522. return empty;
  8523. int start = 0;
  8524. while (CharacterFunctions::isWhitespace (text->text [start]))
  8525. ++start;
  8526. const int len = CharacterFunctions::length (text->text);
  8527. int end = len - 1;
  8528. while ((end >= start) && CharacterFunctions::isWhitespace (text->text [end]))
  8529. --end;
  8530. ++end;
  8531. if (end <= start)
  8532. return empty;
  8533. else if (start > 0 || end < len)
  8534. return String (text->text + start, end - start);
  8535. else
  8536. return *this;
  8537. }
  8538. const String String::trimStart() const throw()
  8539. {
  8540. if (isEmpty())
  8541. return empty;
  8542. const tchar* t = text->text;
  8543. while (CharacterFunctions::isWhitespace (*t))
  8544. ++t;
  8545. if (t == text->text)
  8546. return *this;
  8547. else
  8548. return String (t);
  8549. }
  8550. const String String::trimEnd() const throw()
  8551. {
  8552. if (isEmpty())
  8553. return empty;
  8554. const tchar* endT = text->text + (CharacterFunctions::length (text->text) - 1);
  8555. while ((endT >= text->text) && CharacterFunctions::isWhitespace (*endT))
  8556. --endT;
  8557. return String (text->text, (int) (++endT - text->text));
  8558. }
  8559. const String String::retainCharacters (const tchar* const charactersToRetain) const throw()
  8560. {
  8561. jassert (charactersToRetain != 0);
  8562. if (isEmpty())
  8563. return empty;
  8564. String result (text->allocatedNumChars, (int) 0);
  8565. tchar* dst = result.text->text;
  8566. const tchar* src = text->text;
  8567. while (*src != 0)
  8568. {
  8569. if (CharacterFunctions::indexOfCharFast (charactersToRetain, *src) >= 0)
  8570. *dst++ = *src;
  8571. ++src;
  8572. }
  8573. *dst = 0;
  8574. return result;
  8575. }
  8576. const String String::removeCharacters (const tchar* const charactersToRemove) const throw()
  8577. {
  8578. jassert (charactersToRemove != 0);
  8579. if (isEmpty())
  8580. return empty;
  8581. String result (text->allocatedNumChars, (int) 0);
  8582. tchar* dst = result.text->text;
  8583. const tchar* src = text->text;
  8584. while (*src != 0)
  8585. {
  8586. if (CharacterFunctions::indexOfCharFast (charactersToRemove, *src) < 0)
  8587. *dst++ = *src;
  8588. ++src;
  8589. }
  8590. *dst = 0;
  8591. return result;
  8592. }
  8593. const String String::initialSectionContainingOnly (const tchar* const permittedCharacters) const throw()
  8594. {
  8595. return substring (0, CharacterFunctions::getIntialSectionContainingOnly (text->text, permittedCharacters));
  8596. }
  8597. const String String::initialSectionNotContaining (const tchar* const charactersToStopAt) const throw()
  8598. {
  8599. jassert (charactersToStopAt != 0);
  8600. const tchar* const t = text->text;
  8601. int i = 0;
  8602. while (t[i] != 0)
  8603. {
  8604. if (CharacterFunctions::indexOfCharFast (charactersToStopAt, t[i]) >= 0)
  8605. return String (text->text, i);
  8606. ++i;
  8607. }
  8608. return empty;
  8609. }
  8610. bool String::containsOnly (const tchar* const chars) const throw()
  8611. {
  8612. jassert (chars != 0);
  8613. const tchar* t = text->text;
  8614. while (*t != 0)
  8615. if (CharacterFunctions::indexOfCharFast (chars, *t++) < 0)
  8616. return false;
  8617. return true;
  8618. }
  8619. bool String::containsAnyOf (const tchar* const chars) const throw()
  8620. {
  8621. jassert (chars != 0);
  8622. const tchar* t = text->text;
  8623. while (*t != 0)
  8624. if (CharacterFunctions::indexOfCharFast (chars, *t++) >= 0)
  8625. return true;
  8626. return false;
  8627. }
  8628. int String::getIntValue() const throw()
  8629. {
  8630. return CharacterFunctions::getIntValue (text->text);
  8631. }
  8632. int String::getTrailingIntValue() const throw()
  8633. {
  8634. int n = 0;
  8635. int mult = 1;
  8636. const tchar* t = text->text + length();
  8637. while (--t >= text->text)
  8638. {
  8639. const tchar c = *t;
  8640. if (! CharacterFunctions::isDigit (c))
  8641. {
  8642. if (c == T('-'))
  8643. n = -n;
  8644. break;
  8645. }
  8646. n += mult * (c - T('0'));
  8647. mult *= 10;
  8648. }
  8649. return n;
  8650. }
  8651. int64 String::getLargeIntValue() const throw()
  8652. {
  8653. return CharacterFunctions::getInt64Value (text->text);
  8654. }
  8655. float String::getFloatValue() const throw()
  8656. {
  8657. return (float) CharacterFunctions::getDoubleValue (text->text);
  8658. }
  8659. double String::getDoubleValue() const throw()
  8660. {
  8661. return CharacterFunctions::getDoubleValue (text->text);
  8662. }
  8663. static const tchar* const hexDigits = T("0123456789abcdef");
  8664. const String String::toHexString (const int number) throw()
  8665. {
  8666. tchar buffer[32];
  8667. tchar* const end = buffer + 32;
  8668. tchar* t = end;
  8669. *--t = 0;
  8670. unsigned int v = (unsigned int) number;
  8671. do
  8672. {
  8673. *--t = hexDigits [v & 15];
  8674. v >>= 4;
  8675. } while (v != 0);
  8676. return String (t, (int) (((char*) end) - (char*) t) - 1);
  8677. }
  8678. const String String::toHexString (const int64 number) throw()
  8679. {
  8680. tchar buffer[32];
  8681. tchar* const end = buffer + 32;
  8682. tchar* t = end;
  8683. *--t = 0;
  8684. uint64 v = (uint64) number;
  8685. do
  8686. {
  8687. *--t = hexDigits [(int) (v & 15)];
  8688. v >>= 4;
  8689. } while (v != 0);
  8690. return String (t, (int) (((char*) end) - (char*) t));
  8691. }
  8692. const String String::toHexString (const short number) throw()
  8693. {
  8694. return toHexString ((int) (unsigned short) number);
  8695. }
  8696. const String String::toHexString (const unsigned char* data,
  8697. const int size,
  8698. const int groupSize) throw()
  8699. {
  8700. if (size <= 0)
  8701. return empty;
  8702. int numChars = (size * 2) + 2;
  8703. if (groupSize > 0)
  8704. numChars += size / groupSize;
  8705. String s (numChars, (int) 0);
  8706. tchar* d = s.text->text;
  8707. for (int i = 0; i < size; ++i)
  8708. {
  8709. *d++ = hexDigits [(*data) >> 4];
  8710. *d++ = hexDigits [(*data) & 0xf];
  8711. ++data;
  8712. if (groupSize > 0 && (i % groupSize) == 0)
  8713. *d++ = T(' ');
  8714. }
  8715. if (groupSize > 0)
  8716. --d;
  8717. *d = 0;
  8718. return s;
  8719. }
  8720. int String::getHexValue32() const throw()
  8721. {
  8722. int result = 0;
  8723. const tchar* c = text->text;
  8724. for (;;)
  8725. {
  8726. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  8727. if (hexValue >= 0)
  8728. result = (result << 4) | hexValue;
  8729. else if (*c == 0)
  8730. break;
  8731. ++c;
  8732. }
  8733. return result;
  8734. }
  8735. int64 String::getHexValue64() const throw()
  8736. {
  8737. int64 result = 0;
  8738. const tchar* c = text->text;
  8739. for (;;)
  8740. {
  8741. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  8742. if (hexValue >= 0)
  8743. result = (result << 4) | hexValue;
  8744. else if (*c == 0)
  8745. break;
  8746. ++c;
  8747. }
  8748. return result;
  8749. }
  8750. const String String::createStringFromData (const void* const data_,
  8751. const int size) throw()
  8752. {
  8753. const char* const data = (const char*) data_;
  8754. if (size <= 0 || data == 0)
  8755. {
  8756. return empty;
  8757. }
  8758. else if (size < 2)
  8759. {
  8760. return charToString (data[0]);
  8761. }
  8762. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  8763. || (data[0] == (char)-1 && data[1] == (char)-2))
  8764. {
  8765. // assume it's 16-bit unicode
  8766. const bool bigEndian = (data[0] == (char)-2);
  8767. const int numChars = size / 2 - 1;
  8768. String result;
  8769. result.preallocateStorage (numChars + 2);
  8770. const uint16* const src = (const uint16*) (data + 2);
  8771. tchar* const dst = const_cast <tchar*> ((const tchar*) result);
  8772. if (bigEndian)
  8773. {
  8774. for (int i = 0; i < numChars; ++i)
  8775. dst[i] = (tchar) swapIfLittleEndian (src[i]);
  8776. }
  8777. else
  8778. {
  8779. for (int i = 0; i < numChars; ++i)
  8780. dst[i] = (tchar) swapIfBigEndian (src[i]);
  8781. }
  8782. dst [numChars] = 0;
  8783. return result;
  8784. }
  8785. else
  8786. {
  8787. #if JUCE_STRINGS_ARE_UNICODE && JUCE_LINUX
  8788. // (workaround for strange behaviour of mbstowcs)
  8789. int i;
  8790. for (i = 0; i < size; ++i)
  8791. if (data[i] == 0)
  8792. break;
  8793. String result;
  8794. result.preallocateStorage (i + 1);
  8795. tchar* const dst = const_cast <tchar*> ((const tchar*) result);
  8796. for (int j = 0; j < i; ++j)
  8797. dst[j] = (juce_wchar) (unsigned char) data[j];
  8798. dst[i] = 0;
  8799. return result;
  8800. #else
  8801. return String (data, size);
  8802. #endif
  8803. }
  8804. }
  8805. const char* String::toUTF8() const throw()
  8806. {
  8807. if (isEmpty())
  8808. {
  8809. return (const char*) emptyCharString;
  8810. }
  8811. else
  8812. {
  8813. String* const mutableThis = const_cast <String*> (this);
  8814. mutableThis->dupeInternalIfMultiplyReferenced();
  8815. const int currentLen = CharacterFunctions::length (text->text) + 1;
  8816. const int utf8BytesNeeded = copyToUTF8 (0);
  8817. mutableThis->text = (InternalRefCountedStringHolder*)
  8818. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8819. + (currentLen * sizeof (juce_wchar) + utf8BytesNeeded));
  8820. char* const otherCopy = (char*) (text->text + currentLen);
  8821. copyToUTF8 ((uint8*) otherCopy);
  8822. return otherCopy;
  8823. }
  8824. }
  8825. int String::copyToUTF8 (uint8* const buffer) const throw()
  8826. {
  8827. #if JUCE_STRINGS_ARE_UNICODE
  8828. int num = 0, index = 0;
  8829. for (;;)
  8830. {
  8831. const uint32 c = (uint32) text->text [index++];
  8832. if (c >= 0x80)
  8833. {
  8834. int numExtraBytes = 1;
  8835. if (c >= 0x800)
  8836. {
  8837. ++numExtraBytes;
  8838. if (c >= 0x10000)
  8839. {
  8840. ++numExtraBytes;
  8841. if (c >= 0x200000)
  8842. {
  8843. ++numExtraBytes;
  8844. if (c >= 0x4000000)
  8845. ++numExtraBytes;
  8846. }
  8847. }
  8848. }
  8849. if (buffer != 0)
  8850. {
  8851. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  8852. while (--numExtraBytes >= 0)
  8853. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  8854. }
  8855. else
  8856. {
  8857. num += numExtraBytes + 1;
  8858. }
  8859. }
  8860. else
  8861. {
  8862. if (buffer != 0)
  8863. buffer [num] = (uint8) c;
  8864. ++num;
  8865. }
  8866. if (c == 0)
  8867. break;
  8868. }
  8869. return num;
  8870. #else
  8871. const int numBytes = length() + 1;
  8872. if (buffer != 0)
  8873. copyToBuffer ((char*) buffer, numBytes);
  8874. return numBytes;
  8875. #endif
  8876. }
  8877. const String String::fromUTF8 (const uint8* const buffer, int bufferSizeBytes) throw()
  8878. {
  8879. if (buffer == 0)
  8880. return empty;
  8881. if (bufferSizeBytes < 0)
  8882. bufferSizeBytes = INT_MAX;
  8883. int numBytes;
  8884. for (numBytes = 0; numBytes < bufferSizeBytes; ++numBytes)
  8885. if (buffer [numBytes] == 0)
  8886. break;
  8887. String result (numBytes + 1, 0);
  8888. tchar* dest = result.text->text;
  8889. int i = 0;
  8890. while (i < numBytes)
  8891. {
  8892. const uint8 c = buffer [i++];
  8893. if ((c & 0x80) != 0)
  8894. {
  8895. int mask = 0x7f;
  8896. int bit = 0x40;
  8897. int numExtraValues = 0;
  8898. while (bit != 0 && (c & bit) != 0)
  8899. {
  8900. bit >>= 1;
  8901. mask >>= 1;
  8902. ++numExtraValues;
  8903. }
  8904. int n = (c & mask);
  8905. while (--numExtraValues >= 0 && i < bufferSizeBytes)
  8906. {
  8907. const uint8 c = buffer[i];
  8908. if ((c & 0xc0) != 0x80)
  8909. break;
  8910. n <<= 6;
  8911. n |= (c & 0x3f);
  8912. ++i;
  8913. }
  8914. *dest++ = (tchar) n;
  8915. }
  8916. else
  8917. {
  8918. *dest++ = (tchar) c;
  8919. }
  8920. }
  8921. *dest = 0;
  8922. return result;
  8923. }
  8924. END_JUCE_NAMESPACE
  8925. /********* End of inlined file: juce_String.cpp *********/
  8926. /********* Start of inlined file: juce_StringArray.cpp *********/
  8927. BEGIN_JUCE_NAMESPACE
  8928. StringArray::StringArray() throw()
  8929. {
  8930. }
  8931. StringArray::StringArray (const StringArray& other) throw()
  8932. {
  8933. addArray (other);
  8934. }
  8935. StringArray::StringArray (const juce_wchar** const strings,
  8936. const int numberOfStrings) throw()
  8937. {
  8938. for (int i = 0; i < numberOfStrings; ++i)
  8939. add (strings [i]);
  8940. }
  8941. StringArray::StringArray (const char** const strings,
  8942. const int numberOfStrings) throw()
  8943. {
  8944. for (int i = 0; i < numberOfStrings; ++i)
  8945. add (strings [i]);
  8946. }
  8947. StringArray::StringArray (const juce_wchar** const strings) throw()
  8948. {
  8949. int i = 0;
  8950. while (strings[i] != 0)
  8951. add (strings [i++]);
  8952. }
  8953. StringArray::StringArray (const char** const strings) throw()
  8954. {
  8955. int i = 0;
  8956. while (strings[i] != 0)
  8957. add (strings [i++]);
  8958. }
  8959. const StringArray& StringArray::operator= (const StringArray& other) throw()
  8960. {
  8961. if (this != &other)
  8962. {
  8963. clear();
  8964. addArray (other);
  8965. }
  8966. return *this;
  8967. }
  8968. StringArray::~StringArray() throw()
  8969. {
  8970. clear();
  8971. }
  8972. bool StringArray::operator== (const StringArray& other) const throw()
  8973. {
  8974. if (other.size() != size())
  8975. return false;
  8976. for (int i = size(); --i >= 0;)
  8977. {
  8978. if (*(String*) other.strings.getUnchecked(i)
  8979. != *(String*) strings.getUnchecked(i))
  8980. {
  8981. return false;
  8982. }
  8983. }
  8984. return true;
  8985. }
  8986. bool StringArray::operator!= (const StringArray& other) const throw()
  8987. {
  8988. return ! operator== (other);
  8989. }
  8990. void StringArray::clear() throw()
  8991. {
  8992. for (int i = size(); --i >= 0;)
  8993. {
  8994. String* const s = (String*) strings.getUnchecked(i);
  8995. delete s;
  8996. }
  8997. strings.clear();
  8998. }
  8999. const String& StringArray::operator[] (const int index) const throw()
  9000. {
  9001. if (((unsigned int) index) < (unsigned int) strings.size())
  9002. return *(const String*) (strings.getUnchecked (index));
  9003. return String::empty;
  9004. }
  9005. void StringArray::add (const String& newString) throw()
  9006. {
  9007. strings.add (new String (newString));
  9008. }
  9009. void StringArray::insert (const int index,
  9010. const String& newString) throw()
  9011. {
  9012. strings.insert (index, new String (newString));
  9013. }
  9014. void StringArray::addIfNotAlreadyThere (const String& newString,
  9015. const bool ignoreCase) throw()
  9016. {
  9017. if (! contains (newString, ignoreCase))
  9018. add (newString);
  9019. }
  9020. void StringArray::addArray (const StringArray& otherArray,
  9021. int startIndex,
  9022. int numElementsToAdd) throw()
  9023. {
  9024. if (startIndex < 0)
  9025. {
  9026. jassertfalse
  9027. startIndex = 0;
  9028. }
  9029. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  9030. numElementsToAdd = otherArray.size() - startIndex;
  9031. while (--numElementsToAdd >= 0)
  9032. strings.add (new String (*(const String*) otherArray.strings.getUnchecked (startIndex++)));
  9033. }
  9034. void StringArray::set (const int index,
  9035. const String& newString) throw()
  9036. {
  9037. String* const s = (String*) strings [index];
  9038. if (s != 0)
  9039. {
  9040. *s = newString;
  9041. }
  9042. else if (index >= 0)
  9043. {
  9044. add (newString);
  9045. }
  9046. }
  9047. bool StringArray::contains (const String& stringToLookFor,
  9048. const bool ignoreCase) const throw()
  9049. {
  9050. if (ignoreCase)
  9051. {
  9052. for (int i = size(); --i >= 0;)
  9053. if (stringToLookFor.equalsIgnoreCase (*(const String*)(strings.getUnchecked(i))))
  9054. return true;
  9055. }
  9056. else
  9057. {
  9058. for (int i = size(); --i >= 0;)
  9059. if (stringToLookFor == *(const String*)(strings.getUnchecked(i)))
  9060. return true;
  9061. }
  9062. return false;
  9063. }
  9064. int StringArray::indexOf (const String& stringToLookFor,
  9065. const bool ignoreCase,
  9066. int i) const throw()
  9067. {
  9068. if (i < 0)
  9069. i = 0;
  9070. const int numElements = size();
  9071. if (ignoreCase)
  9072. {
  9073. while (i < numElements)
  9074. {
  9075. if (stringToLookFor.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  9076. return i;
  9077. ++i;
  9078. }
  9079. }
  9080. else
  9081. {
  9082. while (i < numElements)
  9083. {
  9084. if (stringToLookFor == *(const String*) strings.getUnchecked (i))
  9085. return i;
  9086. ++i;
  9087. }
  9088. }
  9089. return -1;
  9090. }
  9091. void StringArray::remove (const int index) throw()
  9092. {
  9093. String* const s = (String*) strings [index];
  9094. if (s != 0)
  9095. {
  9096. strings.remove (index);
  9097. delete s;
  9098. }
  9099. }
  9100. void StringArray::removeString (const String& stringToRemove,
  9101. const bool ignoreCase) throw()
  9102. {
  9103. if (ignoreCase)
  9104. {
  9105. for (int i = size(); --i >= 0;)
  9106. if (stringToRemove.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  9107. remove (i);
  9108. }
  9109. else
  9110. {
  9111. for (int i = size(); --i >= 0;)
  9112. if (stringToRemove == *(const String*) strings.getUnchecked (i))
  9113. remove (i);
  9114. }
  9115. }
  9116. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings) throw()
  9117. {
  9118. if (removeWhitespaceStrings)
  9119. {
  9120. for (int i = size(); --i >= 0;)
  9121. if (((const String*) strings.getUnchecked(i))->trim().isEmpty())
  9122. remove (i);
  9123. }
  9124. else
  9125. {
  9126. for (int i = size(); --i >= 0;)
  9127. if (((const String*) strings.getUnchecked(i))->isEmpty())
  9128. remove (i);
  9129. }
  9130. }
  9131. void StringArray::trim() throw()
  9132. {
  9133. for (int i = size(); --i >= 0;)
  9134. {
  9135. String& s = *(String*) strings.getUnchecked(i);
  9136. s = s.trim();
  9137. }
  9138. }
  9139. class InternalStringArrayComparator
  9140. {
  9141. public:
  9142. static int compareElements (void* const first, void* const second) throw()
  9143. {
  9144. return ((const String*) first)->compare (*(const String*) second);
  9145. }
  9146. };
  9147. class InsensitiveInternalStringArrayComparator
  9148. {
  9149. public:
  9150. static int compareElements (void* const first, void* const second) throw()
  9151. {
  9152. return ((const String*) first)->compareIgnoreCase (*(const String*) second);
  9153. }
  9154. };
  9155. void StringArray::sort (const bool ignoreCase) throw()
  9156. {
  9157. if (ignoreCase)
  9158. {
  9159. InsensitiveInternalStringArrayComparator comp;
  9160. strings.sort (comp);
  9161. }
  9162. else
  9163. {
  9164. InternalStringArrayComparator comp;
  9165. strings.sort (comp);
  9166. }
  9167. }
  9168. void StringArray::move (const int currentIndex, int newIndex) throw()
  9169. {
  9170. strings.move (currentIndex, newIndex);
  9171. }
  9172. const String StringArray::joinIntoString (const String& separator,
  9173. int start,
  9174. int numberToJoin) const throw()
  9175. {
  9176. const int last = (numberToJoin < 0) ? size()
  9177. : jmin (size(), start + numberToJoin);
  9178. if (start < 0)
  9179. start = 0;
  9180. if (start >= last)
  9181. return String::empty;
  9182. if (start == last - 1)
  9183. return *(const String*) strings.getUnchecked (start);
  9184. const int separatorLen = separator.length();
  9185. int charsNeeded = separatorLen * (last - start - 1);
  9186. for (int i = start; i < last; ++i)
  9187. charsNeeded += ((const String*) strings.getUnchecked(i))->length();
  9188. String result;
  9189. result.preallocateStorage (charsNeeded);
  9190. tchar* dest = (tchar*) (const tchar*) result;
  9191. while (start < last)
  9192. {
  9193. const String& s = *(const String*) strings.getUnchecked (start);
  9194. const int len = s.length();
  9195. if (len > 0)
  9196. {
  9197. s.copyToBuffer (dest, len);
  9198. dest += len;
  9199. }
  9200. if (++start < last && separatorLen > 0)
  9201. {
  9202. separator.copyToBuffer (dest, separatorLen);
  9203. dest += separatorLen;
  9204. }
  9205. }
  9206. *dest = 0;
  9207. return result;
  9208. }
  9209. int StringArray::addTokens (const tchar* const text,
  9210. const bool preserveQuotedStrings) throw()
  9211. {
  9212. return addTokens (text,
  9213. T(" \n\r\t"),
  9214. preserveQuotedStrings ? T("\"") : 0);
  9215. }
  9216. int StringArray::addTokens (const tchar* const text,
  9217. const tchar* breakCharacters,
  9218. const tchar* quoteCharacters) throw()
  9219. {
  9220. int num = 0;
  9221. if (text != 0 && *text != 0)
  9222. {
  9223. if (breakCharacters == 0)
  9224. breakCharacters = T("");
  9225. if (quoteCharacters == 0)
  9226. quoteCharacters = T("");
  9227. bool insideQuotes = false;
  9228. tchar currentQuoteChar = 0;
  9229. int i = 0;
  9230. int tokenStart = 0;
  9231. for (;;)
  9232. {
  9233. const tchar c = text[i];
  9234. bool isBreak = (c == 0);
  9235. if (! (insideQuotes || isBreak))
  9236. {
  9237. const tchar* b = breakCharacters;
  9238. while (*b != 0)
  9239. {
  9240. if (*b++ == c)
  9241. {
  9242. isBreak = true;
  9243. break;
  9244. }
  9245. }
  9246. }
  9247. if (! isBreak)
  9248. {
  9249. bool isQuote = false;
  9250. const tchar* q = quoteCharacters;
  9251. while (*q != 0)
  9252. {
  9253. if (*q++ == c)
  9254. {
  9255. isQuote = true;
  9256. break;
  9257. }
  9258. }
  9259. if (isQuote)
  9260. {
  9261. if (insideQuotes)
  9262. {
  9263. // only break out of quotes-mode if we find a matching quote to the
  9264. // one that we opened with..
  9265. if (currentQuoteChar == c)
  9266. insideQuotes = false;
  9267. }
  9268. else
  9269. {
  9270. insideQuotes = true;
  9271. currentQuoteChar = c;
  9272. }
  9273. }
  9274. }
  9275. else
  9276. {
  9277. add (String (text + tokenStart, i - tokenStart));
  9278. ++num;
  9279. tokenStart = i + 1;
  9280. }
  9281. if (c == 0)
  9282. break;
  9283. ++i;
  9284. }
  9285. }
  9286. return num;
  9287. }
  9288. int StringArray::addLines (const tchar* text) throw()
  9289. {
  9290. int numLines = 0;
  9291. if (text != 0)
  9292. {
  9293. while (*text != 0)
  9294. {
  9295. const tchar* const startOfLine = text;
  9296. while (*text != 0)
  9297. {
  9298. if (*text == T('\r'))
  9299. {
  9300. ++text;
  9301. if (*text == T('\n'))
  9302. ++text;
  9303. break;
  9304. }
  9305. if (*text == T('\n'))
  9306. {
  9307. ++text;
  9308. break;
  9309. }
  9310. ++text;
  9311. }
  9312. const tchar* endOfLine = text;
  9313. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  9314. --endOfLine;
  9315. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  9316. --endOfLine;
  9317. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  9318. ++numLines;
  9319. }
  9320. }
  9321. return numLines;
  9322. }
  9323. void StringArray::removeDuplicates (const bool ignoreCase) throw()
  9324. {
  9325. for (int i = 0; i < size() - 1; ++i)
  9326. {
  9327. const String& s = *(String*) strings.getUnchecked(i);
  9328. int nextIndex = i + 1;
  9329. for (;;)
  9330. {
  9331. nextIndex = indexOf (s, ignoreCase, nextIndex);
  9332. if (nextIndex < 0)
  9333. break;
  9334. remove (nextIndex);
  9335. }
  9336. }
  9337. }
  9338. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  9339. const bool appendNumberToFirstInstance,
  9340. const tchar* const preNumberString,
  9341. const tchar* const postNumberString) throw()
  9342. {
  9343. for (int i = 0; i < size() - 1; ++i)
  9344. {
  9345. String& s = *(String*) strings.getUnchecked(i);
  9346. int nextIndex = indexOf (s, ignoreCase, i + 1);
  9347. if (nextIndex >= 0)
  9348. {
  9349. const String original (s);
  9350. int number = 0;
  9351. if (appendNumberToFirstInstance)
  9352. s = original + preNumberString + String (++number) + postNumberString;
  9353. else
  9354. ++number;
  9355. while (nextIndex >= 0)
  9356. {
  9357. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  9358. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  9359. }
  9360. }
  9361. }
  9362. }
  9363. void StringArray::minimiseStorageOverheads() throw()
  9364. {
  9365. strings.minimiseStorageOverheads();
  9366. }
  9367. END_JUCE_NAMESPACE
  9368. /********* End of inlined file: juce_StringArray.cpp *********/
  9369. /********* Start of inlined file: juce_StringPairArray.cpp *********/
  9370. BEGIN_JUCE_NAMESPACE
  9371. StringPairArray::StringPairArray (const bool ignoreCase_) throw()
  9372. : ignoreCase (ignoreCase_)
  9373. {
  9374. }
  9375. StringPairArray::StringPairArray (const StringPairArray& other) throw()
  9376. : keys (other.keys),
  9377. values (other.values),
  9378. ignoreCase (other.ignoreCase)
  9379. {
  9380. }
  9381. StringPairArray::~StringPairArray() throw()
  9382. {
  9383. }
  9384. const StringPairArray& StringPairArray::operator= (const StringPairArray& other) throw()
  9385. {
  9386. keys = other.keys;
  9387. values = other.values;
  9388. return *this;
  9389. }
  9390. bool StringPairArray::operator== (const StringPairArray& other) const throw()
  9391. {
  9392. for (int i = keys.size(); --i >= 0;)
  9393. if (other [keys[i]] != values[i])
  9394. return false;
  9395. return true;
  9396. }
  9397. bool StringPairArray::operator!= (const StringPairArray& other) const throw()
  9398. {
  9399. return ! operator== (other);
  9400. }
  9401. const String& StringPairArray::operator[] (const String& key) const throw()
  9402. {
  9403. return values [keys.indexOf (key, ignoreCase)];
  9404. }
  9405. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  9406. {
  9407. const int i = keys.indexOf (key, ignoreCase);
  9408. if (i >= 0)
  9409. return values[i];
  9410. return defaultReturnValue;
  9411. }
  9412. void StringPairArray::set (const String& key,
  9413. const String& value) throw()
  9414. {
  9415. const int i = keys.indexOf (key, ignoreCase);
  9416. if (i >= 0)
  9417. {
  9418. values.set (i, value);
  9419. }
  9420. else
  9421. {
  9422. keys.add (key);
  9423. values.add (value);
  9424. }
  9425. }
  9426. void StringPairArray::addArray (const StringPairArray& other)
  9427. {
  9428. for (int i = 0; i < other.size(); ++i)
  9429. set (other.keys[i], other.values[i]);
  9430. }
  9431. void StringPairArray::clear() throw()
  9432. {
  9433. keys.clear();
  9434. values.clear();
  9435. }
  9436. void StringPairArray::remove (const String& key) throw()
  9437. {
  9438. remove (keys.indexOf (key, ignoreCase));
  9439. }
  9440. void StringPairArray::remove (const int index) throw()
  9441. {
  9442. keys.remove (index);
  9443. values.remove (index);
  9444. }
  9445. void StringPairArray::minimiseStorageOverheads() throw()
  9446. {
  9447. keys.minimiseStorageOverheads();
  9448. values.minimiseStorageOverheads();
  9449. }
  9450. END_JUCE_NAMESPACE
  9451. /********* End of inlined file: juce_StringPairArray.cpp *********/
  9452. /********* Start of inlined file: juce_XmlDocument.cpp *********/
  9453. BEGIN_JUCE_NAMESPACE
  9454. static bool isXmlIdentifierChar_Slow (const tchar c) throw()
  9455. {
  9456. return CharacterFunctions::isLetterOrDigit (c)
  9457. || c == T('_')
  9458. || c == T('-')
  9459. || c == T(':')
  9460. || c == T('.');
  9461. }
  9462. #define isXmlIdentifierChar(c) \
  9463. ((c > 0 && c <= 127) ? identifierLookupTable [(int) c] : isXmlIdentifierChar_Slow (c))
  9464. XmlDocument::XmlDocument (const String& documentText) throw()
  9465. : originalText (documentText),
  9466. inputSource (0)
  9467. {
  9468. }
  9469. XmlDocument::XmlDocument (const File& file)
  9470. {
  9471. inputSource = new FileInputSource (file);
  9472. }
  9473. XmlDocument::~XmlDocument() throw()
  9474. {
  9475. delete inputSource;
  9476. }
  9477. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  9478. {
  9479. if (inputSource != newSource)
  9480. {
  9481. delete inputSource;
  9482. inputSource = newSource;
  9483. }
  9484. }
  9485. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  9486. {
  9487. String textToParse (originalText);
  9488. if (textToParse.isEmpty() && inputSource != 0)
  9489. {
  9490. InputStream* const in = inputSource->createInputStream();
  9491. if (in != 0)
  9492. {
  9493. MemoryBlock data;
  9494. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  9495. delete in;
  9496. if (data.getSize() >= 2
  9497. && ((data[0] == (char)-2 && data[1] == (char)-1)
  9498. || (data[0] == (char)-1 && data[1] == (char)-2)))
  9499. {
  9500. textToParse = String::createStringFromData ((const char*) data.getData(), data.getSize());
  9501. }
  9502. else
  9503. {
  9504. textToParse = String::fromUTF8 ((const uint8*) data.getData(), data.getSize());
  9505. }
  9506. if (! onlyReadOuterDocumentElement)
  9507. originalText = textToParse;
  9508. }
  9509. }
  9510. input = textToParse;
  9511. lastError = String::empty;
  9512. errorOccurred = false;
  9513. outOfData = false;
  9514. needToLoadDTD = true;
  9515. for (int i = 0; i < 128; ++i)
  9516. identifierLookupTable[i] = isXmlIdentifierChar_Slow ((tchar) i);
  9517. if (textToParse.isEmpty())
  9518. {
  9519. lastError = "not enough input";
  9520. }
  9521. else
  9522. {
  9523. skipHeader();
  9524. if (input != 0)
  9525. {
  9526. XmlElement* const result = readNextElement (! onlyReadOuterDocumentElement);
  9527. if (errorOccurred)
  9528. delete result;
  9529. else
  9530. return result;
  9531. }
  9532. else
  9533. {
  9534. lastError = "incorrect xml header";
  9535. }
  9536. }
  9537. return 0;
  9538. }
  9539. const String& XmlDocument::getLastParseError() const throw()
  9540. {
  9541. return lastError;
  9542. }
  9543. void XmlDocument::setLastError (const String& desc, const bool carryOn) throw()
  9544. {
  9545. lastError = desc;
  9546. errorOccurred = ! carryOn;
  9547. }
  9548. const String XmlDocument::getFileContents (const String& filename) const
  9549. {
  9550. String result;
  9551. if (inputSource != 0)
  9552. {
  9553. InputStream* const in = inputSource->createInputStreamFor (filename.trim().unquoted());
  9554. if (in != 0)
  9555. {
  9556. result = in->readEntireStreamAsString();
  9557. delete in;
  9558. }
  9559. }
  9560. return result;
  9561. }
  9562. tchar XmlDocument::readNextChar() throw()
  9563. {
  9564. if (*input != 0)
  9565. {
  9566. return *input++;
  9567. }
  9568. else
  9569. {
  9570. outOfData = true;
  9571. return 0;
  9572. }
  9573. }
  9574. int XmlDocument::findNextTokenLength() throw()
  9575. {
  9576. int len = 0;
  9577. tchar c = *input;
  9578. while (isXmlIdentifierChar (c))
  9579. c = input [++len];
  9580. return len;
  9581. }
  9582. void XmlDocument::skipHeader() throw()
  9583. {
  9584. const tchar* const found = CharacterFunctions::find (input, T("<?xml"));
  9585. if (found != 0)
  9586. {
  9587. input = found;
  9588. input = CharacterFunctions::find (input, T("?>"));
  9589. if (input == 0)
  9590. return;
  9591. input += 2;
  9592. }
  9593. skipNextWhiteSpace();
  9594. const tchar* docType = CharacterFunctions::find (input, T("<!DOCTYPE"));
  9595. if (docType == 0)
  9596. return;
  9597. input = docType + 9;
  9598. int n = 1;
  9599. while (n > 0)
  9600. {
  9601. const tchar c = readNextChar();
  9602. if (outOfData)
  9603. return;
  9604. if (c == T('<'))
  9605. ++n;
  9606. else if (c == T('>'))
  9607. --n;
  9608. }
  9609. docType += 9;
  9610. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  9611. }
  9612. void XmlDocument::skipNextWhiteSpace() throw()
  9613. {
  9614. for (;;)
  9615. {
  9616. tchar c = *input;
  9617. while (CharacterFunctions::isWhitespace (c))
  9618. c = *++input;
  9619. if (c == 0)
  9620. {
  9621. outOfData = true;
  9622. break;
  9623. }
  9624. else if (c == T('<'))
  9625. {
  9626. if (input[1] == T('!')
  9627. && input[2] == T('-')
  9628. && input[3] == T('-'))
  9629. {
  9630. const tchar* const closeComment = CharacterFunctions::find (input, T("-->"));
  9631. if (closeComment == 0)
  9632. {
  9633. outOfData = true;
  9634. break;
  9635. }
  9636. input = closeComment + 3;
  9637. continue;
  9638. }
  9639. else if (input[1] == T('?'))
  9640. {
  9641. const tchar* const closeBracket = CharacterFunctions::find (input, T("?>"));
  9642. if (closeBracket == 0)
  9643. {
  9644. outOfData = true;
  9645. break;
  9646. }
  9647. input = closeBracket + 2;
  9648. continue;
  9649. }
  9650. }
  9651. break;
  9652. }
  9653. }
  9654. void XmlDocument::readQuotedString (String& result) throw()
  9655. {
  9656. const tchar quote = readNextChar();
  9657. while (! outOfData)
  9658. {
  9659. const tchar character = readNextChar();
  9660. if (character == quote)
  9661. break;
  9662. if (character == T('&'))
  9663. {
  9664. --input;
  9665. readEntity (result);
  9666. }
  9667. else
  9668. {
  9669. --input;
  9670. const tchar* const start = input;
  9671. for (;;)
  9672. {
  9673. const tchar character = *input;
  9674. if (character == quote)
  9675. {
  9676. result.append (start, (int) (input - start));
  9677. ++input;
  9678. return;
  9679. }
  9680. else if (character == T('&'))
  9681. {
  9682. result.append (start, (int) (input - start));
  9683. break;
  9684. }
  9685. else if (character == 0)
  9686. {
  9687. outOfData = true;
  9688. setLastError ("unmatched quotes", false);
  9689. break;
  9690. }
  9691. ++input;
  9692. }
  9693. }
  9694. }
  9695. }
  9696. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements) throw()
  9697. {
  9698. XmlElement* node = 0;
  9699. skipNextWhiteSpace();
  9700. if (outOfData)
  9701. return 0;
  9702. input = CharacterFunctions::find (input, T("<"));
  9703. if (input != 0)
  9704. {
  9705. ++input;
  9706. int tagLen = findNextTokenLength();
  9707. if (tagLen == 0)
  9708. {
  9709. // no tag name - but allow for a gap after the '<' before giving an error
  9710. skipNextWhiteSpace();
  9711. tagLen = findNextTokenLength();
  9712. if (tagLen == 0)
  9713. {
  9714. setLastError ("tag name missing", false);
  9715. return node;
  9716. }
  9717. }
  9718. node = new XmlElement (input, tagLen);
  9719. input += tagLen;
  9720. XmlElement::XmlAttributeNode* lastAttribute = 0;
  9721. // look for attributes
  9722. for (;;)
  9723. {
  9724. skipNextWhiteSpace();
  9725. const tchar c = *input;
  9726. // empty tag..
  9727. if (c == T('/') && input[1] == T('>'))
  9728. {
  9729. input += 2;
  9730. break;
  9731. }
  9732. // parse the guts of the element..
  9733. if (c == T('>'))
  9734. {
  9735. ++input;
  9736. skipNextWhiteSpace();
  9737. if (alsoParseSubElements)
  9738. readChildElements (node);
  9739. break;
  9740. }
  9741. // get an attribute..
  9742. if (isXmlIdentifierChar (c))
  9743. {
  9744. const int attNameLen = findNextTokenLength();
  9745. if (attNameLen > 0)
  9746. {
  9747. const tchar* attNameStart = input;
  9748. input += attNameLen;
  9749. skipNextWhiteSpace();
  9750. if (readNextChar() == T('='))
  9751. {
  9752. skipNextWhiteSpace();
  9753. const tchar c = *input;
  9754. if (c == T('"') || c == T('\''))
  9755. {
  9756. XmlElement::XmlAttributeNode* const newAtt
  9757. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  9758. String::empty);
  9759. readQuotedString (newAtt->value);
  9760. if (lastAttribute == 0)
  9761. node->attributes = newAtt;
  9762. else
  9763. lastAttribute->next = newAtt;
  9764. lastAttribute = newAtt;
  9765. continue;
  9766. }
  9767. }
  9768. }
  9769. }
  9770. else
  9771. {
  9772. if (! outOfData)
  9773. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  9774. }
  9775. break;
  9776. }
  9777. }
  9778. return node;
  9779. }
  9780. void XmlDocument::readChildElements (XmlElement* parent) throw()
  9781. {
  9782. XmlElement* lastChildNode = 0;
  9783. for (;;)
  9784. {
  9785. skipNextWhiteSpace();
  9786. if (outOfData)
  9787. {
  9788. setLastError ("unmatched tags", false);
  9789. break;
  9790. }
  9791. if (*input == T('<'))
  9792. {
  9793. if (input[1] == T('/'))
  9794. {
  9795. // our close tag..
  9796. input = CharacterFunctions::find (input, T(">"));
  9797. ++input;
  9798. break;
  9799. }
  9800. else if (input[1] == T('!')
  9801. && input[2] == T('[')
  9802. && input[3] == T('C')
  9803. && input[4] == T('D')
  9804. && input[5] == T('A')
  9805. && input[6] == T('T')
  9806. && input[7] == T('A')
  9807. && input[8] == T('['))
  9808. {
  9809. input += 9;
  9810. const tchar* const inputStart = input;
  9811. int len = 0;
  9812. for (;;)
  9813. {
  9814. if (*input == 0)
  9815. {
  9816. setLastError ("unterminated CDATA section", false);
  9817. outOfData = true;
  9818. break;
  9819. }
  9820. else if (input[0] == T(']')
  9821. && input[1] == T(']')
  9822. && input[2] == T('>'))
  9823. {
  9824. input += 3;
  9825. break;
  9826. }
  9827. ++input;
  9828. ++len;
  9829. }
  9830. XmlElement* const e = new XmlElement ((int) 0);
  9831. e->setText (String (inputStart, len));
  9832. if (lastChildNode != 0)
  9833. lastChildNode->nextElement = e;
  9834. else
  9835. parent->addChildElement (e);
  9836. lastChildNode = e;
  9837. }
  9838. else
  9839. {
  9840. // this is some other element, so parse and add it..
  9841. XmlElement* const n = readNextElement (true);
  9842. if (n != 0)
  9843. {
  9844. if (lastChildNode == 0)
  9845. parent->addChildElement (n);
  9846. else
  9847. lastChildNode->nextElement = n;
  9848. lastChildNode = n;
  9849. }
  9850. else
  9851. {
  9852. return;
  9853. }
  9854. }
  9855. }
  9856. else
  9857. {
  9858. // read character block..
  9859. XmlElement* const e = new XmlElement ((int)0);
  9860. if (lastChildNode != 0)
  9861. lastChildNode->nextElement = e;
  9862. else
  9863. parent->addChildElement (e);
  9864. lastChildNode = e;
  9865. String textElementContent;
  9866. for (;;)
  9867. {
  9868. const tchar c = *input;
  9869. if (c == T('<'))
  9870. break;
  9871. if (c == 0)
  9872. {
  9873. setLastError ("unmatched tags", false);
  9874. outOfData = true;
  9875. return;
  9876. }
  9877. if (c == T('&'))
  9878. {
  9879. String entity;
  9880. readEntity (entity);
  9881. if (entity.startsWithChar (T('<')) && entity [1] != 0)
  9882. {
  9883. const tchar* const oldInput = input;
  9884. const bool oldOutOfData = outOfData;
  9885. input = (const tchar*) entity;
  9886. outOfData = false;
  9887. for (;;)
  9888. {
  9889. XmlElement* const n = readNextElement (true);
  9890. if (n == 0)
  9891. break;
  9892. if (lastChildNode == 0)
  9893. parent->addChildElement (n);
  9894. else
  9895. lastChildNode->nextElement = n;
  9896. lastChildNode = n;
  9897. }
  9898. input = oldInput;
  9899. outOfData = oldOutOfData;
  9900. }
  9901. else
  9902. {
  9903. textElementContent += entity;
  9904. }
  9905. }
  9906. else
  9907. {
  9908. const tchar* start = input;
  9909. int len = 0;
  9910. for (;;)
  9911. {
  9912. const tchar c = *input;
  9913. if (c == T('<') || c == T('&'))
  9914. {
  9915. break;
  9916. }
  9917. else if (c == 0)
  9918. {
  9919. setLastError ("unmatched tags", false);
  9920. outOfData = true;
  9921. return;
  9922. }
  9923. ++input;
  9924. ++len;
  9925. }
  9926. textElementContent.append (start, len);
  9927. }
  9928. }
  9929. textElementContent = textElementContent.trim();
  9930. if (textElementContent.isNotEmpty())
  9931. e->setText (textElementContent);
  9932. }
  9933. }
  9934. }
  9935. void XmlDocument::readEntity (String& result) throw()
  9936. {
  9937. // skip over the ampersand
  9938. ++input;
  9939. if (CharacterFunctions::compareIgnoreCase (input, T("amp;"), 4) == 0)
  9940. {
  9941. input += 4;
  9942. result += T("&");
  9943. }
  9944. else if (CharacterFunctions::compareIgnoreCase (input, T("quot;"), 5) == 0)
  9945. {
  9946. input += 5;
  9947. result += T("\"");
  9948. }
  9949. else if (CharacterFunctions::compareIgnoreCase (input, T("apos;"), 5) == 0)
  9950. {
  9951. input += 5;
  9952. result += T("\'");
  9953. }
  9954. else if (CharacterFunctions::compareIgnoreCase (input, T("lt;"), 3) == 0)
  9955. {
  9956. input += 3;
  9957. result += T("<");
  9958. }
  9959. else if (CharacterFunctions::compareIgnoreCase (input, T("gt;"), 3) == 0)
  9960. {
  9961. input += 3;
  9962. result += T(">");
  9963. }
  9964. else if (*input == T('#'))
  9965. {
  9966. int charCode = 0;
  9967. ++input;
  9968. if (*input == T('x') || *input == T('X'))
  9969. {
  9970. ++input;
  9971. int numChars = 0;
  9972. while (input[0] != T(';'))
  9973. {
  9974. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  9975. if (hexValue < 0 || ++numChars > 8)
  9976. {
  9977. setLastError ("illegal escape sequence", true);
  9978. break;
  9979. }
  9980. charCode = (charCode << 4) | hexValue;
  9981. ++input;
  9982. }
  9983. ++input;
  9984. }
  9985. else if (input[0] >= T('0') && input[0] <= T('9'))
  9986. {
  9987. int numChars = 0;
  9988. while (input[0] != T(';'))
  9989. {
  9990. if (++numChars > 12)
  9991. {
  9992. setLastError ("illegal escape sequence", true);
  9993. break;
  9994. }
  9995. charCode = charCode * 10 + (input[0] - T('0'));
  9996. ++input;
  9997. }
  9998. ++input;
  9999. }
  10000. else
  10001. {
  10002. setLastError ("illegal escape sequence", true);
  10003. result += T("&");
  10004. return;
  10005. }
  10006. result << (tchar) charCode;
  10007. }
  10008. else
  10009. {
  10010. const tchar* const entityNameStart = input;
  10011. const tchar* const closingSemiColon = CharacterFunctions::find (input, T(";"));
  10012. if (closingSemiColon == 0)
  10013. {
  10014. outOfData = true;
  10015. result += T("&");
  10016. }
  10017. else
  10018. {
  10019. input = closingSemiColon + 1;
  10020. result += expandExternalEntity (String (entityNameStart,
  10021. (int) (closingSemiColon - entityNameStart)));
  10022. }
  10023. }
  10024. }
  10025. const String XmlDocument::expandEntity (const String& ent)
  10026. {
  10027. if (ent.equalsIgnoreCase (T("amp")))
  10028. {
  10029. return T("&");
  10030. }
  10031. else if (ent.equalsIgnoreCase (T("quot")))
  10032. {
  10033. return T("\"");
  10034. }
  10035. else if (ent.equalsIgnoreCase (T("apos")))
  10036. {
  10037. return T("\'");
  10038. }
  10039. else if (ent.equalsIgnoreCase (T("lt")))
  10040. {
  10041. return T("<");
  10042. }
  10043. else if (ent.equalsIgnoreCase (T("gt")))
  10044. {
  10045. return T(">");
  10046. }
  10047. else if (ent[0] == T('#'))
  10048. {
  10049. if (ent[1] == T('x') || ent[1] == T('X'))
  10050. {
  10051. return String::charToString ((tchar) ent.substring (2).getHexValue32());
  10052. }
  10053. else if (ent[1] >= T('0') && ent[1] <= T('9'))
  10054. {
  10055. return String::charToString ((tchar) ent.substring (1).getIntValue());
  10056. }
  10057. setLastError ("illegal escape sequence", false);
  10058. return T("&");
  10059. }
  10060. else
  10061. {
  10062. return expandExternalEntity (ent);
  10063. }
  10064. }
  10065. const String XmlDocument::expandExternalEntity (const String& entity)
  10066. {
  10067. if (needToLoadDTD)
  10068. {
  10069. if (dtdText.isNotEmpty())
  10070. {
  10071. while (dtdText.endsWithChar (T('>')))
  10072. dtdText = dtdText.dropLastCharacters (1);
  10073. tokenisedDTD.addTokens (dtdText, true);
  10074. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase (T("system"))
  10075. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  10076. {
  10077. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  10078. tokenisedDTD.clear();
  10079. tokenisedDTD.addTokens (getFileContents (fn), true);
  10080. }
  10081. else
  10082. {
  10083. tokenisedDTD.clear();
  10084. const int openBracket = dtdText.indexOfChar (T('['));
  10085. if (openBracket > 0)
  10086. {
  10087. const int closeBracket = dtdText.lastIndexOfChar (T(']'));
  10088. if (closeBracket > openBracket)
  10089. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  10090. closeBracket), true);
  10091. }
  10092. }
  10093. for (int i = tokenisedDTD.size(); --i >= 0;)
  10094. {
  10095. if (tokenisedDTD[i].startsWithChar (T('%'))
  10096. && tokenisedDTD[i].endsWithChar (T(';')))
  10097. {
  10098. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  10099. StringArray newToks;
  10100. newToks.addTokens (parsed, true);
  10101. tokenisedDTD.remove (i);
  10102. for (int j = newToks.size(); --j >= 0;)
  10103. tokenisedDTD.insert (i, newToks[j]);
  10104. }
  10105. }
  10106. }
  10107. needToLoadDTD = false;
  10108. }
  10109. for (int i = 0; i < tokenisedDTD.size(); ++i)
  10110. {
  10111. if (tokenisedDTD[i] == entity)
  10112. {
  10113. if (tokenisedDTD[i - 1].equalsIgnoreCase (T("<!entity")))
  10114. {
  10115. String ent (tokenisedDTD [i + 1]);
  10116. while (ent.endsWithChar (T('>')))
  10117. ent = ent.dropLastCharacters (1);
  10118. ent = ent.trim().unquoted();
  10119. // check for sub-entities..
  10120. int ampersand = ent.indexOfChar (T('&'));
  10121. while (ampersand >= 0)
  10122. {
  10123. const int semiColon = ent.indexOf (i + 1, T(";"));
  10124. if (semiColon < 0)
  10125. {
  10126. setLastError ("entity without terminating semi-colon", false);
  10127. break;
  10128. }
  10129. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  10130. ent = ent.substring (0, ampersand)
  10131. + resolved
  10132. + ent.substring (semiColon + 1);
  10133. ampersand = ent.indexOfChar (semiColon + 1, T('&'));
  10134. }
  10135. return ent;
  10136. }
  10137. }
  10138. }
  10139. setLastError ("unknown entity", true);
  10140. return entity;
  10141. }
  10142. const String XmlDocument::getParameterEntity (const String& entity)
  10143. {
  10144. for (int i = 0; i < tokenisedDTD.size(); ++i)
  10145. {
  10146. if (tokenisedDTD[i] == entity)
  10147. {
  10148. if (tokenisedDTD [i - 1] == T("%")
  10149. && tokenisedDTD [i - 2].equalsIgnoreCase (T("<!entity")))
  10150. {
  10151. String ent (tokenisedDTD [i + 1]);
  10152. while (ent.endsWithChar (T('>')))
  10153. ent = ent.dropLastCharacters (1);
  10154. if (ent.equalsIgnoreCase (T("system")))
  10155. {
  10156. String filename (tokenisedDTD [i + 2]);
  10157. while (filename.endsWithChar (T('>')))
  10158. filename = filename.dropLastCharacters (1);
  10159. return getFileContents (filename);
  10160. }
  10161. else
  10162. {
  10163. return ent.trim().unquoted();
  10164. }
  10165. }
  10166. }
  10167. }
  10168. return entity;
  10169. }
  10170. END_JUCE_NAMESPACE
  10171. /********* End of inlined file: juce_XmlDocument.cpp *********/
  10172. /********* Start of inlined file: juce_XmlElement.cpp *********/
  10173. BEGIN_JUCE_NAMESPACE
  10174. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  10175. : name (other.name),
  10176. value (other.value),
  10177. next (0)
  10178. {
  10179. }
  10180. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_,
  10181. const String& value_) throw()
  10182. : name (name_),
  10183. value (value_),
  10184. next (0)
  10185. {
  10186. }
  10187. XmlElement::XmlElement (const String& tagName_) throw()
  10188. : tagName (tagName_),
  10189. firstChildElement (0),
  10190. nextElement (0),
  10191. attributes (0)
  10192. {
  10193. // the tag name mustn't be empty, or it'll look like a text element!
  10194. jassert (tagName_.trim().isNotEmpty())
  10195. }
  10196. XmlElement::XmlElement (int /*dummy*/) throw()
  10197. : firstChildElement (0),
  10198. nextElement (0),
  10199. attributes (0)
  10200. {
  10201. }
  10202. XmlElement::XmlElement (const tchar* const tagName_,
  10203. const int nameLen) throw()
  10204. : tagName (tagName_, nameLen),
  10205. firstChildElement (0),
  10206. nextElement (0),
  10207. attributes (0)
  10208. {
  10209. }
  10210. XmlElement::XmlElement (const XmlElement& other) throw()
  10211. : tagName (other.tagName),
  10212. firstChildElement (0),
  10213. nextElement (0),
  10214. attributes (0)
  10215. {
  10216. copyChildrenAndAttributesFrom (other);
  10217. }
  10218. const XmlElement& XmlElement::operator= (const XmlElement& other) throw()
  10219. {
  10220. if (this != &other)
  10221. {
  10222. removeAllAttributes();
  10223. deleteAllChildElements();
  10224. tagName = other.tagName;
  10225. copyChildrenAndAttributesFrom (other);
  10226. }
  10227. return *this;
  10228. }
  10229. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other) throw()
  10230. {
  10231. XmlElement* child = other.firstChildElement;
  10232. XmlElement* lastChild = 0;
  10233. while (child != 0)
  10234. {
  10235. XmlElement* const copiedChild = new XmlElement (*child);
  10236. if (lastChild != 0)
  10237. lastChild->nextElement = copiedChild;
  10238. else
  10239. firstChildElement = copiedChild;
  10240. lastChild = copiedChild;
  10241. child = child->nextElement;
  10242. }
  10243. const XmlAttributeNode* att = other.attributes;
  10244. XmlAttributeNode* lastAtt = 0;
  10245. while (att != 0)
  10246. {
  10247. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  10248. if (lastAtt != 0)
  10249. lastAtt->next = newAtt;
  10250. else
  10251. attributes = newAtt;
  10252. lastAtt = newAtt;
  10253. att = att->next;
  10254. }
  10255. }
  10256. XmlElement::~XmlElement() throw()
  10257. {
  10258. XmlElement* child = firstChildElement;
  10259. while (child != 0)
  10260. {
  10261. XmlElement* const nextChild = child->nextElement;
  10262. delete child;
  10263. child = nextChild;
  10264. }
  10265. XmlAttributeNode* att = attributes;
  10266. while (att != 0)
  10267. {
  10268. XmlAttributeNode* const nextAtt = att->next;
  10269. delete att;
  10270. att = nextAtt;
  10271. }
  10272. }
  10273. static bool isLegalXmlChar (const juce_wchar character)
  10274. {
  10275. if ((character >= 'a' && character <= 'z')
  10276. || (character >= 'A' && character <= 'Z')
  10277. || (character >= '0' && character <= '9'))
  10278. return true;
  10279. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}";
  10280. do
  10281. {
  10282. if (((juce_wchar) (uint8) *t) == character)
  10283. return true;
  10284. }
  10285. while (*++t != 0);
  10286. return false;
  10287. }
  10288. static void escapeIllegalXmlChars (OutputStream& outputStream,
  10289. const String& text,
  10290. const bool changeNewLines) throw()
  10291. {
  10292. const juce_wchar* t = (const juce_wchar*) text;
  10293. for (;;)
  10294. {
  10295. const juce_wchar character = *t++;
  10296. if (character == 0)
  10297. {
  10298. break;
  10299. }
  10300. else if (isLegalXmlChar (character))
  10301. {
  10302. outputStream.writeByte ((char) character);
  10303. }
  10304. else
  10305. {
  10306. switch (character)
  10307. {
  10308. case '&':
  10309. outputStream.write ("&amp;", 5);
  10310. break;
  10311. case '"':
  10312. outputStream.write ("&quot;", 6);
  10313. break;
  10314. case '>':
  10315. outputStream.write ("&gt;", 4);
  10316. break;
  10317. case '<':
  10318. outputStream.write ("&lt;", 4);
  10319. break;
  10320. case '\n':
  10321. if (changeNewLines)
  10322. outputStream.write ("&#10;", 5);
  10323. else
  10324. outputStream.writeByte ((char) character);
  10325. break;
  10326. case '\r':
  10327. if (changeNewLines)
  10328. outputStream.write ("&#13;", 5);
  10329. else
  10330. outputStream.writeByte ((char) character);
  10331. break;
  10332. default:
  10333. {
  10334. String encoded (T("&#"));
  10335. encoded << String ((int) (unsigned int) character).trim()
  10336. << T(';');
  10337. outputStream.write ((const char*) encoded, encoded.length());
  10338. }
  10339. }
  10340. }
  10341. }
  10342. }
  10343. static void writeSpaces (OutputStream& out, int numSpaces) throw()
  10344. {
  10345. if (numSpaces > 0)
  10346. {
  10347. const char* const blanks = " ";
  10348. const int blankSize = (int) sizeof (blanks) - 1;
  10349. while (numSpaces > blankSize)
  10350. {
  10351. out.write (blanks, blankSize);
  10352. numSpaces -= blankSize;
  10353. }
  10354. out.write (blanks, numSpaces);
  10355. }
  10356. }
  10357. void XmlElement::writeElementAsText (OutputStream& outputStream,
  10358. const int indentationLevel) const throw()
  10359. {
  10360. writeSpaces (outputStream, indentationLevel);
  10361. if (! isTextElement())
  10362. {
  10363. outputStream.writeByte ('<');
  10364. const int nameLen = tagName.length();
  10365. outputStream.write ((const char*) tagName, nameLen);
  10366. const int attIndent = indentationLevel + nameLen + 1;
  10367. int lineLen = 0;
  10368. const XmlAttributeNode* att = attributes;
  10369. while (att != 0)
  10370. {
  10371. if (lineLen > 60 && indentationLevel >= 0)
  10372. {
  10373. outputStream.write ("\r\n", 2);
  10374. writeSpaces (outputStream, attIndent);
  10375. lineLen = 0;
  10376. }
  10377. const int attNameLen = att->name.length();
  10378. outputStream.writeByte (' ');
  10379. outputStream.write ((const char*) (att->name), attNameLen);
  10380. outputStream.write ("=\"", 2);
  10381. escapeIllegalXmlChars (outputStream, att->value, true);
  10382. outputStream.writeByte ('"');
  10383. lineLen += 4 + attNameLen + att->value.length();
  10384. att = att->next;
  10385. }
  10386. if (firstChildElement != 0)
  10387. {
  10388. XmlElement* child = firstChildElement;
  10389. if (child->nextElement == 0 && child->isTextElement())
  10390. {
  10391. outputStream.writeByte ('>');
  10392. escapeIllegalXmlChars (outputStream, child->getText(), false);
  10393. }
  10394. else
  10395. {
  10396. if (indentationLevel >= 0)
  10397. outputStream.write (">\r\n", 3);
  10398. else
  10399. outputStream.writeByte ('>');
  10400. bool lastWasTextNode = false;
  10401. while (child != 0)
  10402. {
  10403. if (child->isTextElement())
  10404. {
  10405. if ((! lastWasTextNode) && (indentationLevel >= 0))
  10406. writeSpaces (outputStream, indentationLevel + 2);
  10407. escapeIllegalXmlChars (outputStream, child->getText(), false);
  10408. lastWasTextNode = true;
  10409. }
  10410. else
  10411. {
  10412. if (indentationLevel >= 0)
  10413. {
  10414. if (lastWasTextNode)
  10415. outputStream.write ("\r\n", 2);
  10416. child->writeElementAsText (outputStream, indentationLevel + 2);
  10417. }
  10418. else
  10419. {
  10420. child->writeElementAsText (outputStream, indentationLevel);
  10421. }
  10422. lastWasTextNode = false;
  10423. }
  10424. child = child->nextElement;
  10425. }
  10426. if (indentationLevel >= 0)
  10427. {
  10428. if (lastWasTextNode)
  10429. outputStream.write ("\r\n", 2);
  10430. writeSpaces (outputStream, indentationLevel);
  10431. }
  10432. }
  10433. outputStream.write ("</", 2);
  10434. outputStream.write ((const char*) tagName, nameLen);
  10435. if (indentationLevel >= 0)
  10436. outputStream.write (">\r\n", 3);
  10437. else
  10438. outputStream.writeByte ('>');
  10439. }
  10440. else
  10441. {
  10442. if (indentationLevel >= 0)
  10443. outputStream.write ("/>\r\n", 4);
  10444. else
  10445. outputStream.write ("/>", 2);
  10446. }
  10447. }
  10448. else
  10449. {
  10450. if (indentationLevel >= 0)
  10451. writeSpaces (outputStream, indentationLevel + 2);
  10452. escapeIllegalXmlChars (outputStream, getText(), false);
  10453. }
  10454. }
  10455. const String XmlElement::createDocument (const String& dtd,
  10456. const bool allOnOneLine,
  10457. const bool includeXmlHeader,
  10458. const tchar* const encoding) const throw()
  10459. {
  10460. String doc;
  10461. doc.preallocateStorage (1024);
  10462. if (includeXmlHeader)
  10463. {
  10464. doc << "<?xml version=\"1.0\" encoding=\""
  10465. << encoding;
  10466. if (allOnOneLine)
  10467. doc += "\"?> ";
  10468. else
  10469. doc += "\"?>\n\n";
  10470. }
  10471. if (dtd.isNotEmpty())
  10472. {
  10473. if (allOnOneLine)
  10474. doc << dtd << " ";
  10475. else
  10476. doc << dtd << "\r\n";
  10477. }
  10478. MemoryOutputStream mem (2048, 4096);
  10479. writeElementAsText (mem, allOnOneLine ? -1 : 0);
  10480. return doc + String (mem.getData(),
  10481. mem.getDataSize());
  10482. }
  10483. bool XmlElement::writeToFile (const File& f,
  10484. const String& dtd,
  10485. const tchar* const encoding) const throw()
  10486. {
  10487. if (f.hasWriteAccess())
  10488. {
  10489. const File tempFile (f.getNonexistentSibling());
  10490. FileOutputStream* const out = tempFile.createOutputStream();
  10491. if (out != 0)
  10492. {
  10493. *out << "<?xml version=\"1.0\" encoding=\"" << encoding << "\"?>\r\n\r\n"
  10494. << dtd << "\r\n";
  10495. writeElementAsText (*out, 0);
  10496. delete out;
  10497. if (tempFile.moveFileTo (f))
  10498. return true;
  10499. tempFile.deleteFile();
  10500. }
  10501. }
  10502. return false;
  10503. }
  10504. bool XmlElement::hasTagName (const tchar* const tagNameWanted) const throw()
  10505. {
  10506. #ifdef JUCE_DEBUG
  10507. // if debugging, check that the case is actually the same, because
  10508. // valid xml is case-sensitive, and although this lets it pass, it's
  10509. // better not to..
  10510. if (tagName.equalsIgnoreCase (tagNameWanted))
  10511. {
  10512. jassert (tagName == tagNameWanted);
  10513. return true;
  10514. }
  10515. else
  10516. {
  10517. return false;
  10518. }
  10519. #else
  10520. return tagName.equalsIgnoreCase (tagNameWanted);
  10521. #endif
  10522. }
  10523. XmlElement* XmlElement::getNextElementWithTagName (const tchar* const requiredTagName) const
  10524. {
  10525. XmlElement* e = nextElement;
  10526. while (e != 0 && ! e->hasTagName (requiredTagName))
  10527. e = e->nextElement;
  10528. return e;
  10529. }
  10530. int XmlElement::getNumAttributes() const throw()
  10531. {
  10532. const XmlAttributeNode* att = attributes;
  10533. int count = 0;
  10534. while (att != 0)
  10535. {
  10536. att = att->next;
  10537. ++count;
  10538. }
  10539. return count;
  10540. }
  10541. const String& XmlElement::getAttributeName (const int index) const throw()
  10542. {
  10543. const XmlAttributeNode* att = attributes;
  10544. int count = 0;
  10545. while (att != 0)
  10546. {
  10547. if (count == index)
  10548. return att->name;
  10549. att = att->next;
  10550. ++count;
  10551. }
  10552. return String::empty;
  10553. }
  10554. const String& XmlElement::getAttributeValue (const int index) const throw()
  10555. {
  10556. const XmlAttributeNode* att = attributes;
  10557. int count = 0;
  10558. while (att != 0)
  10559. {
  10560. if (count == index)
  10561. return att->value;
  10562. att = att->next;
  10563. ++count;
  10564. }
  10565. return String::empty;
  10566. }
  10567. bool XmlElement::hasAttribute (const tchar* const attributeName) const throw()
  10568. {
  10569. const XmlAttributeNode* att = attributes;
  10570. while (att != 0)
  10571. {
  10572. if (att->name.equalsIgnoreCase (attributeName))
  10573. return true;
  10574. att = att->next;
  10575. }
  10576. return false;
  10577. }
  10578. const String XmlElement::getStringAttribute (const tchar* const attributeName,
  10579. const tchar* const defaultReturnValue) const throw()
  10580. {
  10581. const XmlAttributeNode* att = attributes;
  10582. while (att != 0)
  10583. {
  10584. if (att->name.equalsIgnoreCase (attributeName))
  10585. return att->value;
  10586. att = att->next;
  10587. }
  10588. return defaultReturnValue;
  10589. }
  10590. int XmlElement::getIntAttribute (const tchar* const attributeName,
  10591. const int defaultReturnValue) const throw()
  10592. {
  10593. const XmlAttributeNode* att = attributes;
  10594. while (att != 0)
  10595. {
  10596. if (att->name.equalsIgnoreCase (attributeName))
  10597. return att->value.getIntValue();
  10598. att = att->next;
  10599. }
  10600. return defaultReturnValue;
  10601. }
  10602. double XmlElement::getDoubleAttribute (const tchar* const attributeName,
  10603. const double defaultReturnValue) const throw()
  10604. {
  10605. const XmlAttributeNode* att = attributes;
  10606. while (att != 0)
  10607. {
  10608. if (att->name.equalsIgnoreCase (attributeName))
  10609. return att->value.getDoubleValue();
  10610. att = att->next;
  10611. }
  10612. return defaultReturnValue;
  10613. }
  10614. bool XmlElement::getBoolAttribute (const tchar* const attributeName,
  10615. const bool defaultReturnValue) const throw()
  10616. {
  10617. const XmlAttributeNode* att = attributes;
  10618. while (att != 0)
  10619. {
  10620. if (att->name.equalsIgnoreCase (attributeName))
  10621. {
  10622. tchar firstChar = att->value[0];
  10623. if (CharacterFunctions::isWhitespace (firstChar))
  10624. firstChar = att->value.trimStart() [0];
  10625. return firstChar == T('1')
  10626. || firstChar == T('t')
  10627. || firstChar == T('y')
  10628. || firstChar == T('T')
  10629. || firstChar == T('Y');
  10630. }
  10631. att = att->next;
  10632. }
  10633. return defaultReturnValue;
  10634. }
  10635. bool XmlElement::compareAttribute (const tchar* const attributeName,
  10636. const tchar* const stringToCompareAgainst,
  10637. const bool ignoreCase) const throw()
  10638. {
  10639. const XmlAttributeNode* att = attributes;
  10640. while (att != 0)
  10641. {
  10642. if (att->name.equalsIgnoreCase (attributeName))
  10643. {
  10644. if (ignoreCase)
  10645. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  10646. else
  10647. return att->value == stringToCompareAgainst;
  10648. }
  10649. att = att->next;
  10650. }
  10651. return false;
  10652. }
  10653. void XmlElement::setAttribute (const tchar* const attributeName,
  10654. const String& value) throw()
  10655. {
  10656. #ifdef JUCE_DEBUG
  10657. // check the identifier being passed in is legal..
  10658. const tchar* t = attributeName;
  10659. while (*t != 0)
  10660. {
  10661. jassert (CharacterFunctions::isLetterOrDigit (*t)
  10662. || *t == T('_')
  10663. || *t == T('-')
  10664. || *t == T(':'));
  10665. ++t;
  10666. }
  10667. #endif
  10668. if (attributes == 0)
  10669. {
  10670. attributes = new XmlAttributeNode (attributeName, value);
  10671. }
  10672. else
  10673. {
  10674. XmlAttributeNode* att = attributes;
  10675. for (;;)
  10676. {
  10677. if (att->name.equalsIgnoreCase (attributeName))
  10678. {
  10679. att->value = value;
  10680. break;
  10681. }
  10682. else if (att->next == 0)
  10683. {
  10684. att->next = new XmlAttributeNode (attributeName, value);
  10685. break;
  10686. }
  10687. att = att->next;
  10688. }
  10689. }
  10690. }
  10691. void XmlElement::setAttribute (const tchar* const attributeName,
  10692. const tchar* const text) throw()
  10693. {
  10694. setAttribute (attributeName, String (text));
  10695. }
  10696. void XmlElement::setAttribute (const tchar* const attributeName,
  10697. const int number) throw()
  10698. {
  10699. setAttribute (attributeName, String (number));
  10700. }
  10701. void XmlElement::setAttribute (const tchar* const attributeName,
  10702. const double number) throw()
  10703. {
  10704. tchar buffer [40];
  10705. CharacterFunctions::printf (buffer, numElementsInArray (buffer), T("%.9g"), number);
  10706. setAttribute (attributeName, buffer);
  10707. }
  10708. void XmlElement::removeAttribute (const tchar* const attributeName) throw()
  10709. {
  10710. XmlAttributeNode* att = attributes;
  10711. XmlAttributeNode* lastAtt = 0;
  10712. while (att != 0)
  10713. {
  10714. if (att->name.equalsIgnoreCase (attributeName))
  10715. {
  10716. if (lastAtt == 0)
  10717. attributes = att->next;
  10718. else
  10719. lastAtt->next = att->next;
  10720. delete att;
  10721. break;
  10722. }
  10723. lastAtt = att;
  10724. att = att->next;
  10725. }
  10726. }
  10727. void XmlElement::removeAllAttributes() throw()
  10728. {
  10729. while (attributes != 0)
  10730. {
  10731. XmlAttributeNode* const nextAtt = attributes->next;
  10732. delete attributes;
  10733. attributes = nextAtt;
  10734. }
  10735. }
  10736. int XmlElement::getNumChildElements() const throw()
  10737. {
  10738. int count = 0;
  10739. const XmlElement* child = firstChildElement;
  10740. while (child != 0)
  10741. {
  10742. ++count;
  10743. child = child->nextElement;
  10744. }
  10745. return count;
  10746. }
  10747. XmlElement* XmlElement::getChildElement (const int index) const throw()
  10748. {
  10749. int count = 0;
  10750. XmlElement* child = firstChildElement;
  10751. while (child != 0 && count < index)
  10752. {
  10753. child = child->nextElement;
  10754. ++count;
  10755. }
  10756. return child;
  10757. }
  10758. XmlElement* XmlElement::getChildByName (const tchar* const childName) const throw()
  10759. {
  10760. XmlElement* child = firstChildElement;
  10761. while (child != 0)
  10762. {
  10763. if (child->hasTagName (childName))
  10764. break;
  10765. child = child->nextElement;
  10766. }
  10767. return child;
  10768. }
  10769. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  10770. {
  10771. if (newNode != 0)
  10772. {
  10773. if (firstChildElement == 0)
  10774. {
  10775. firstChildElement = newNode;
  10776. }
  10777. else
  10778. {
  10779. XmlElement* child = firstChildElement;
  10780. while (child->nextElement != 0)
  10781. child = child->nextElement;
  10782. child->nextElement = newNode;
  10783. // if this is non-zero, then something's probably
  10784. // gone wrong..
  10785. jassert (newNode->nextElement == 0);
  10786. }
  10787. }
  10788. }
  10789. void XmlElement::insertChildElement (XmlElement* const newNode,
  10790. int indexToInsertAt) throw()
  10791. {
  10792. if (newNode != 0)
  10793. {
  10794. removeChildElement (newNode, false);
  10795. if (indexToInsertAt == 0)
  10796. {
  10797. newNode->nextElement = firstChildElement;
  10798. firstChildElement = newNode;
  10799. }
  10800. else
  10801. {
  10802. if (firstChildElement == 0)
  10803. {
  10804. firstChildElement = newNode;
  10805. }
  10806. else
  10807. {
  10808. if (indexToInsertAt < 0)
  10809. indexToInsertAt = INT_MAX;
  10810. XmlElement* child = firstChildElement;
  10811. while (child->nextElement != 0 && --indexToInsertAt > 0)
  10812. child = child->nextElement;
  10813. newNode->nextElement = child->nextElement;
  10814. child->nextElement = newNode;
  10815. }
  10816. }
  10817. }
  10818. }
  10819. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  10820. XmlElement* const newNode) throw()
  10821. {
  10822. if (newNode != 0)
  10823. {
  10824. XmlElement* child = firstChildElement;
  10825. XmlElement* previousNode = 0;
  10826. while (child != 0)
  10827. {
  10828. if (child == currentChildElement)
  10829. {
  10830. if (child != newNode)
  10831. {
  10832. if (previousNode == 0)
  10833. firstChildElement = newNode;
  10834. else
  10835. previousNode->nextElement = newNode;
  10836. newNode->nextElement = child->nextElement;
  10837. delete child;
  10838. }
  10839. return true;
  10840. }
  10841. previousNode = child;
  10842. child = child->nextElement;
  10843. }
  10844. }
  10845. return false;
  10846. }
  10847. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  10848. const bool shouldDeleteTheChild) throw()
  10849. {
  10850. if (childToRemove != 0)
  10851. {
  10852. if (firstChildElement == childToRemove)
  10853. {
  10854. firstChildElement = childToRemove->nextElement;
  10855. childToRemove->nextElement = 0;
  10856. }
  10857. else
  10858. {
  10859. XmlElement* child = firstChildElement;
  10860. XmlElement* last = 0;
  10861. while (child != 0)
  10862. {
  10863. if (child == childToRemove)
  10864. {
  10865. if (last == 0)
  10866. firstChildElement = child->nextElement;
  10867. else
  10868. last->nextElement = child->nextElement;
  10869. childToRemove->nextElement = 0;
  10870. break;
  10871. }
  10872. last = child;
  10873. child = child->nextElement;
  10874. }
  10875. }
  10876. if (shouldDeleteTheChild)
  10877. delete childToRemove;
  10878. }
  10879. }
  10880. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  10881. const bool ignoreOrderOfAttributes) const throw()
  10882. {
  10883. if (this != other)
  10884. {
  10885. if (other == 0 || tagName != other->tagName)
  10886. {
  10887. return false;
  10888. }
  10889. if (ignoreOrderOfAttributes)
  10890. {
  10891. int totalAtts = 0;
  10892. const XmlAttributeNode* att = attributes;
  10893. while (att != 0)
  10894. {
  10895. if (! other->compareAttribute (att->name, att->value))
  10896. return false;
  10897. att = att->next;
  10898. ++totalAtts;
  10899. }
  10900. if (totalAtts != other->getNumAttributes())
  10901. return false;
  10902. }
  10903. else
  10904. {
  10905. const XmlAttributeNode* thisAtt = attributes;
  10906. const XmlAttributeNode* otherAtt = other->attributes;
  10907. for (;;)
  10908. {
  10909. if (thisAtt == 0 || otherAtt == 0)
  10910. {
  10911. if (thisAtt == otherAtt) // both 0, so it's a match
  10912. break;
  10913. return false;
  10914. }
  10915. if (thisAtt->name != otherAtt->name
  10916. || thisAtt->value != otherAtt->value)
  10917. {
  10918. return false;
  10919. }
  10920. thisAtt = thisAtt->next;
  10921. otherAtt = otherAtt->next;
  10922. }
  10923. }
  10924. const XmlElement* thisChild = firstChildElement;
  10925. const XmlElement* otherChild = other->firstChildElement;
  10926. for (;;)
  10927. {
  10928. if (thisChild == 0 || otherChild == 0)
  10929. {
  10930. if (thisChild == otherChild) // both 0, so it's a match
  10931. break;
  10932. return false;
  10933. }
  10934. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  10935. return false;
  10936. thisChild = thisChild->nextElement;
  10937. otherChild = otherChild->nextElement;
  10938. }
  10939. }
  10940. return true;
  10941. }
  10942. void XmlElement::deleteAllChildElements() throw()
  10943. {
  10944. while (firstChildElement != 0)
  10945. {
  10946. XmlElement* const nextChild = firstChildElement->nextElement;
  10947. delete firstChildElement;
  10948. firstChildElement = nextChild;
  10949. }
  10950. }
  10951. void XmlElement::deleteAllChildElementsWithTagName (const tchar* const name) throw()
  10952. {
  10953. XmlElement* child = firstChildElement;
  10954. while (child != 0)
  10955. {
  10956. if (child->hasTagName (name))
  10957. {
  10958. XmlElement* const nextChild = child->nextElement;
  10959. removeChildElement (child, true);
  10960. child = nextChild;
  10961. }
  10962. else
  10963. {
  10964. child = child->nextElement;
  10965. }
  10966. }
  10967. }
  10968. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  10969. {
  10970. const XmlElement* child = firstChildElement;
  10971. while (child != 0)
  10972. {
  10973. if (child == possibleChild)
  10974. return true;
  10975. child = child->nextElement;
  10976. }
  10977. return false;
  10978. }
  10979. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  10980. {
  10981. if (this == elementToLookFor || elementToLookFor == 0)
  10982. return 0;
  10983. XmlElement* child = firstChildElement;
  10984. while (child != 0)
  10985. {
  10986. if (elementToLookFor == child)
  10987. return this;
  10988. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  10989. if (found != 0)
  10990. return found;
  10991. child = child->nextElement;
  10992. }
  10993. return 0;
  10994. }
  10995. XmlElement** XmlElement::getChildElementsAsArray (const int num) const throw()
  10996. {
  10997. XmlElement** const elems = new XmlElement* [num];
  10998. XmlElement* e = firstChildElement;
  10999. int i = 0;
  11000. while (e != 0)
  11001. {
  11002. elems [i++] = e;
  11003. e = e->nextElement;
  11004. }
  11005. return elems;
  11006. }
  11007. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  11008. {
  11009. XmlElement* e = firstChildElement = elems[0];
  11010. for (int i = 1; i < num; ++i)
  11011. {
  11012. e->nextElement = elems[i];
  11013. e = e->nextElement;
  11014. }
  11015. e->nextElement = 0;
  11016. }
  11017. bool XmlElement::isTextElement() const throw()
  11018. {
  11019. return tagName.isEmpty();
  11020. }
  11021. static const tchar* const juce_xmltextContentAttributeName = T("text");
  11022. const String XmlElement::getText() const throw()
  11023. {
  11024. jassert (isTextElement()); // you're trying to get the text from an element that
  11025. // isn't actually a text element.. If this contains text sub-nodes, you
  11026. // can use getAllSubText instead to
  11027. return getStringAttribute (juce_xmltextContentAttributeName);
  11028. }
  11029. void XmlElement::setText (const String& newText) throw()
  11030. {
  11031. if (isTextElement())
  11032. {
  11033. setAttribute (juce_xmltextContentAttributeName, newText);
  11034. }
  11035. else
  11036. {
  11037. jassertfalse // you can only change the text in a text element, not a normal one.
  11038. }
  11039. }
  11040. const String XmlElement::getAllSubText() const throw()
  11041. {
  11042. String result;
  11043. const XmlElement* child = firstChildElement;
  11044. while (child != 0)
  11045. {
  11046. if (child->isTextElement())
  11047. result += child->getText();
  11048. child = child->nextElement;
  11049. }
  11050. return result;
  11051. }
  11052. const String XmlElement::getChildElementAllSubText (const tchar* const childTagName,
  11053. const String& defaultReturnValue) const throw()
  11054. {
  11055. const XmlElement* const child = getChildByName (childTagName);
  11056. if (child != 0)
  11057. return child->getAllSubText();
  11058. return defaultReturnValue;
  11059. }
  11060. XmlElement* XmlElement::createTextElement (const String& text) throw()
  11061. {
  11062. XmlElement* const e = new XmlElement ((int) 0);
  11063. e->setAttribute (juce_xmltextContentAttributeName, text);
  11064. return e;
  11065. }
  11066. void XmlElement::addTextElement (const String& text) throw()
  11067. {
  11068. addChildElement (createTextElement (text));
  11069. }
  11070. void XmlElement::deleteAllTextElements() throw()
  11071. {
  11072. XmlElement* child = firstChildElement;
  11073. while (child != 0)
  11074. {
  11075. XmlElement* const next = child->nextElement;
  11076. if (child->isTextElement())
  11077. removeChildElement (child, true);
  11078. child = next;
  11079. }
  11080. }
  11081. END_JUCE_NAMESPACE
  11082. /********* End of inlined file: juce_XmlElement.cpp *********/
  11083. /********* Start of inlined file: juce_InterProcessLock.cpp *********/
  11084. BEGIN_JUCE_NAMESPACE
  11085. // (implemented in the platform-specific code files)
  11086. END_JUCE_NAMESPACE
  11087. /********* End of inlined file: juce_InterProcessLock.cpp *********/
  11088. /********* Start of inlined file: juce_ReadWriteLock.cpp *********/
  11089. BEGIN_JUCE_NAMESPACE
  11090. ReadWriteLock::ReadWriteLock() throw()
  11091. : numWaitingWriters (0),
  11092. numWriters (0),
  11093. writerThreadId (0)
  11094. {
  11095. }
  11096. ReadWriteLock::~ReadWriteLock() throw()
  11097. {
  11098. jassert (readerThreads.size() == 0);
  11099. jassert (numWriters == 0);
  11100. }
  11101. void ReadWriteLock::enterRead() const throw()
  11102. {
  11103. const int threadId = Thread::getCurrentThreadId();
  11104. const ScopedLock sl (accessLock);
  11105. for (;;)
  11106. {
  11107. jassert (readerThreads.size() % 2 == 0);
  11108. int i;
  11109. for (i = 0; i < readerThreads.size(); i += 2)
  11110. if (readerThreads.getUnchecked(i) == threadId)
  11111. break;
  11112. if (i < readerThreads.size()
  11113. || numWriters + numWaitingWriters == 0
  11114. || (threadId == writerThreadId && numWriters > 0))
  11115. {
  11116. if (i < readerThreads.size())
  11117. {
  11118. readerThreads.set (i + 1, readerThreads.getUnchecked (i + 1) + 1);
  11119. }
  11120. else
  11121. {
  11122. readerThreads.add (threadId);
  11123. readerThreads.add (1);
  11124. }
  11125. return;
  11126. }
  11127. const ScopedUnlock ul (accessLock);
  11128. waitEvent.wait (100);
  11129. }
  11130. }
  11131. void ReadWriteLock::exitRead() const throw()
  11132. {
  11133. const int threadId = Thread::getCurrentThreadId();
  11134. const ScopedLock sl (accessLock);
  11135. for (int i = 0; i < readerThreads.size(); i += 2)
  11136. {
  11137. if (readerThreads.getUnchecked(i) == threadId)
  11138. {
  11139. const int newCount = readerThreads.getUnchecked (i + 1) - 1;
  11140. if (newCount == 0)
  11141. {
  11142. readerThreads.removeRange (i, 2);
  11143. waitEvent.signal();
  11144. }
  11145. else
  11146. {
  11147. readerThreads.set (i + 1, newCount);
  11148. }
  11149. return;
  11150. }
  11151. }
  11152. jassertfalse // unlocking a lock that wasn't locked..
  11153. }
  11154. void ReadWriteLock::enterWrite() const throw()
  11155. {
  11156. const int threadId = Thread::getCurrentThreadId();
  11157. const ScopedLock sl (accessLock);
  11158. for (;;)
  11159. {
  11160. if (readerThreads.size() + numWriters == 0
  11161. || threadId == writerThreadId
  11162. || (readerThreads.size() == 2
  11163. && readerThreads.getUnchecked(0) == threadId))
  11164. {
  11165. writerThreadId = threadId;
  11166. ++numWriters;
  11167. break;
  11168. }
  11169. ++numWaitingWriters;
  11170. accessLock.exit();
  11171. waitEvent.wait (100);
  11172. accessLock.enter();
  11173. --numWaitingWriters;
  11174. }
  11175. }
  11176. bool ReadWriteLock::tryEnterWrite() const throw()
  11177. {
  11178. const int threadId = Thread::getCurrentThreadId();
  11179. const ScopedLock sl (accessLock);
  11180. if (readerThreads.size() + numWriters == 0
  11181. || threadId == writerThreadId
  11182. || (readerThreads.size() == 2
  11183. && readerThreads.getUnchecked(0) == threadId))
  11184. {
  11185. writerThreadId = threadId;
  11186. ++numWriters;
  11187. return true;
  11188. }
  11189. return false;
  11190. }
  11191. void ReadWriteLock::exitWrite() const throw()
  11192. {
  11193. const ScopedLock sl (accessLock);
  11194. // check this thread actually had the lock..
  11195. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  11196. if (--numWriters == 0)
  11197. {
  11198. writerThreadId = 0;
  11199. waitEvent.signal();
  11200. }
  11201. }
  11202. END_JUCE_NAMESPACE
  11203. /********* End of inlined file: juce_ReadWriteLock.cpp *********/
  11204. /********* Start of inlined file: juce_Thread.cpp *********/
  11205. BEGIN_JUCE_NAMESPACE
  11206. // these functions are implemented in the platform-specific code.
  11207. void* juce_createThread (void* userData) throw();
  11208. void juce_killThread (void* handle) throw();
  11209. void juce_setThreadPriority (void* handle, int priority) throw();
  11210. void juce_setCurrentThreadName (const String& name) throw();
  11211. #if JUCE_WIN32
  11212. void juce_CloseThreadHandle (void* handle) throw();
  11213. #endif
  11214. static VoidArray runningThreads (4);
  11215. static CriticalSection runningThreadsLock;
  11216. void Thread::threadEntryPoint (Thread* const thread) throw()
  11217. {
  11218. runningThreadsLock.enter();
  11219. runningThreads.add (thread);
  11220. runningThreadsLock.exit();
  11221. JUCE_TRY
  11222. {
  11223. thread->threadId_ = Thread::getCurrentThreadId();
  11224. if (thread->threadName_.isNotEmpty())
  11225. juce_setCurrentThreadName (thread->threadName_);
  11226. if (thread->startSuspensionEvent_.wait (10000))
  11227. {
  11228. if (thread->affinityMask_ != 0)
  11229. setCurrentThreadAffinityMask (thread->affinityMask_);
  11230. thread->run();
  11231. }
  11232. }
  11233. JUCE_CATCH_ALL_ASSERT
  11234. runningThreadsLock.enter();
  11235. jassert (runningThreads.contains (thread));
  11236. runningThreads.removeValue (thread);
  11237. runningThreadsLock.exit();
  11238. #if JUCE_WIN32
  11239. juce_CloseThreadHandle (thread->threadHandle_);
  11240. #endif
  11241. thread->threadHandle_ = 0;
  11242. thread->threadId_ = 0;
  11243. }
  11244. // used to wrap the incoming call from the platform-specific code
  11245. void JUCE_API juce_threadEntryPoint (void* userData)
  11246. {
  11247. Thread::threadEntryPoint ((Thread*) userData);
  11248. }
  11249. Thread::Thread (const String& threadName)
  11250. : threadName_ (threadName),
  11251. threadHandle_ (0),
  11252. threadPriority_ (5),
  11253. threadId_ (0),
  11254. affinityMask_ (0),
  11255. threadShouldExit_ (false)
  11256. {
  11257. }
  11258. Thread::~Thread()
  11259. {
  11260. stopThread (100);
  11261. }
  11262. void Thread::startThread() throw()
  11263. {
  11264. const ScopedLock sl (startStopLock);
  11265. threadShouldExit_ = false;
  11266. if (threadHandle_ == 0)
  11267. {
  11268. threadHandle_ = juce_createThread ((void*) this);
  11269. juce_setThreadPriority (threadHandle_, threadPriority_);
  11270. startSuspensionEvent_.signal();
  11271. }
  11272. }
  11273. void Thread::startThread (const int priority) throw()
  11274. {
  11275. const ScopedLock sl (startStopLock);
  11276. if (threadHandle_ == 0)
  11277. {
  11278. threadPriority_ = priority;
  11279. startThread();
  11280. }
  11281. else
  11282. {
  11283. setPriority (priority);
  11284. }
  11285. }
  11286. bool Thread::isThreadRunning() const throw()
  11287. {
  11288. return threadHandle_ != 0;
  11289. }
  11290. void Thread::signalThreadShouldExit() throw()
  11291. {
  11292. threadShouldExit_ = true;
  11293. }
  11294. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const throw()
  11295. {
  11296. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  11297. jassert (getThreadId() != getCurrentThreadId());
  11298. const int sleepMsPerIteration = 5;
  11299. int count = timeOutMilliseconds / sleepMsPerIteration;
  11300. while (isThreadRunning())
  11301. {
  11302. if (timeOutMilliseconds > 0 && --count < 0)
  11303. return false;
  11304. sleep (sleepMsPerIteration);
  11305. }
  11306. return true;
  11307. }
  11308. void Thread::stopThread (const int timeOutMilliseconds) throw()
  11309. {
  11310. // agh! You can't stop the thread that's calling this method! How on earth
  11311. // would that work??
  11312. jassert (getCurrentThreadId() != getThreadId());
  11313. const ScopedLock sl (startStopLock);
  11314. if (isThreadRunning())
  11315. {
  11316. signalThreadShouldExit();
  11317. notify();
  11318. if (timeOutMilliseconds != 0)
  11319. waitForThreadToExit (timeOutMilliseconds);
  11320. if (isThreadRunning())
  11321. {
  11322. // very bad karma if this point is reached, as
  11323. // there are bound to be locks and events left in
  11324. // silly states when a thread is killed by force..
  11325. jassertfalse
  11326. Logger::writeToLog ("!! killing thread by force !!");
  11327. juce_killThread (threadHandle_);
  11328. threadHandle_ = 0;
  11329. threadId_ = 0;
  11330. const ScopedLock sl (runningThreadsLock);
  11331. runningThreads.removeValue (this);
  11332. }
  11333. }
  11334. }
  11335. void Thread::setPriority (const int priority) throw()
  11336. {
  11337. const ScopedLock sl (startStopLock);
  11338. threadPriority_ = priority;
  11339. juce_setThreadPriority (threadHandle_, priority);
  11340. }
  11341. void Thread::setCurrentThreadPriority (const int priority) throw()
  11342. {
  11343. juce_setThreadPriority (0, priority);
  11344. }
  11345. void Thread::setAffinityMask (const uint32 affinityMask) throw()
  11346. {
  11347. affinityMask_ = affinityMask;
  11348. }
  11349. int Thread::getThreadId() const throw()
  11350. {
  11351. return threadId_;
  11352. }
  11353. bool Thread::wait (const int timeOutMilliseconds) const throw()
  11354. {
  11355. return defaultEvent_.wait (timeOutMilliseconds);
  11356. }
  11357. void Thread::notify() const throw()
  11358. {
  11359. defaultEvent_.signal();
  11360. }
  11361. int Thread::getNumRunningThreads() throw()
  11362. {
  11363. return runningThreads.size();
  11364. }
  11365. Thread* Thread::getCurrentThread() throw()
  11366. {
  11367. const int thisId = getCurrentThreadId();
  11368. Thread* result = 0;
  11369. runningThreadsLock.enter();
  11370. for (int i = runningThreads.size(); --i >= 0;)
  11371. {
  11372. Thread* const t = (Thread*) (runningThreads.getUnchecked(i));
  11373. if (t->threadId_ == thisId)
  11374. {
  11375. result = t;
  11376. break;
  11377. }
  11378. }
  11379. runningThreadsLock.exit();
  11380. return result;
  11381. }
  11382. void Thread::stopAllThreads (const int timeOutMilliseconds) throw()
  11383. {
  11384. runningThreadsLock.enter();
  11385. for (int i = runningThreads.size(); --i >= 0;)
  11386. ((Thread*) runningThreads.getUnchecked(i))->signalThreadShouldExit();
  11387. runningThreadsLock.exit();
  11388. for (;;)
  11389. {
  11390. runningThreadsLock.enter();
  11391. Thread* const t = (Thread*) runningThreads[0];
  11392. runningThreadsLock.exit();
  11393. if (t == 0)
  11394. break;
  11395. t->stopThread (timeOutMilliseconds);
  11396. }
  11397. }
  11398. END_JUCE_NAMESPACE
  11399. /********* End of inlined file: juce_Thread.cpp *********/
  11400. /********* Start of inlined file: juce_ThreadPool.cpp *********/
  11401. BEGIN_JUCE_NAMESPACE
  11402. ThreadPoolJob::ThreadPoolJob (const String& name)
  11403. : jobName (name),
  11404. pool (0),
  11405. shouldStop (false),
  11406. isActive (false),
  11407. shouldBeDeleted (false)
  11408. {
  11409. }
  11410. ThreadPoolJob::~ThreadPoolJob()
  11411. {
  11412. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  11413. // to remove it first!
  11414. jassert (pool == 0 || ! pool->contains (this));
  11415. }
  11416. const String ThreadPoolJob::getJobName() const
  11417. {
  11418. return jobName;
  11419. }
  11420. void ThreadPoolJob::setJobName (const String& newName)
  11421. {
  11422. jobName = newName;
  11423. }
  11424. void ThreadPoolJob::signalJobShouldExit()
  11425. {
  11426. shouldStop = true;
  11427. }
  11428. class ThreadPoolThread : public Thread
  11429. {
  11430. ThreadPool& pool;
  11431. bool volatile busy;
  11432. ThreadPoolThread (const ThreadPoolThread&);
  11433. const ThreadPoolThread& operator= (const ThreadPoolThread&);
  11434. public:
  11435. ThreadPoolThread (ThreadPool& pool_)
  11436. : Thread (T("Pool")),
  11437. pool (pool_),
  11438. busy (false)
  11439. {
  11440. }
  11441. ~ThreadPoolThread()
  11442. {
  11443. }
  11444. void run()
  11445. {
  11446. while (! threadShouldExit())
  11447. {
  11448. if (! pool.runNextJob())
  11449. wait (500);
  11450. }
  11451. }
  11452. };
  11453. ThreadPool::ThreadPool (const int numThreads_,
  11454. const bool startThreadsOnlyWhenNeeded,
  11455. const int stopThreadsWhenNotUsedTimeoutMs)
  11456. : numThreads (jmax (1, numThreads_)),
  11457. threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  11458. priority (5)
  11459. {
  11460. jassert (numThreads_ > 0); // not much point having one of these with no threads in it.
  11461. threads = (Thread**) juce_calloc (sizeof (Thread*) * numThreads);
  11462. for (int i = numThreads; --i >= 0;)
  11463. {
  11464. threads[i] = new ThreadPoolThread (*this);
  11465. if (! startThreadsOnlyWhenNeeded)
  11466. threads[i]->startThread();
  11467. }
  11468. }
  11469. ThreadPool::~ThreadPool()
  11470. {
  11471. removeAllJobs (true, 4000);
  11472. int i;
  11473. for (i = numThreads; --i >= 0;)
  11474. threads[i]->signalThreadShouldExit();
  11475. for (i = numThreads; --i >= 0;)
  11476. {
  11477. threads[i]->stopThread (500);
  11478. delete threads[i];
  11479. }
  11480. juce_free (threads);
  11481. }
  11482. void ThreadPool::addJob (ThreadPoolJob* const job)
  11483. {
  11484. jassert (job->pool == 0);
  11485. if (job->pool == 0)
  11486. {
  11487. job->pool = this;
  11488. job->shouldStop = false;
  11489. job->isActive = false;
  11490. lock.enter();
  11491. jobs.add (job);
  11492. int numRunning = 0;
  11493. int i;
  11494. for (i = numThreads; --i >= 0;)
  11495. if (threads[i]->isThreadRunning() && ! threads[i]->threadShouldExit())
  11496. ++numRunning;
  11497. if (numRunning < numThreads)
  11498. {
  11499. bool startedOne = false;
  11500. int n = 1000;
  11501. while (--n >= 0 && ! startedOne)
  11502. {
  11503. for (int i = numThreads; --i >= 0;)
  11504. {
  11505. if (! threads[i]->isThreadRunning())
  11506. {
  11507. threads[i]->startThread();
  11508. startedOne = true;
  11509. }
  11510. }
  11511. if (! startedOne)
  11512. Thread::sleep (5);
  11513. }
  11514. }
  11515. lock.exit();
  11516. for (i = numThreads; --i >= 0;)
  11517. threads[i]->notify();
  11518. }
  11519. }
  11520. int ThreadPool::getNumJobs() const throw()
  11521. {
  11522. return jobs.size();
  11523. }
  11524. ThreadPoolJob* ThreadPool::getJob (const int index) const
  11525. {
  11526. const ScopedLock sl (lock);
  11527. return (ThreadPoolJob*) jobs [index];
  11528. }
  11529. bool ThreadPool::contains (const ThreadPoolJob* const job) const throw()
  11530. {
  11531. const ScopedLock sl (lock);
  11532. return jobs.contains ((void*) job);
  11533. }
  11534. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  11535. {
  11536. const ScopedLock sl (lock);
  11537. return jobs.contains ((void*) job) && job->isActive;
  11538. }
  11539. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  11540. const int timeOutMs) const
  11541. {
  11542. if (job != 0)
  11543. {
  11544. const uint32 start = Time::getMillisecondCounter();
  11545. while (contains (job))
  11546. {
  11547. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  11548. return false;
  11549. Thread::sleep (2);
  11550. }
  11551. }
  11552. return true;
  11553. }
  11554. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  11555. const bool interruptIfRunning,
  11556. const int timeOutMs)
  11557. {
  11558. if (job != 0)
  11559. {
  11560. lock.enter();
  11561. if (jobs.contains (job))
  11562. {
  11563. if (job->isActive)
  11564. {
  11565. if (interruptIfRunning)
  11566. job->signalJobShouldExit();
  11567. lock.exit();
  11568. return waitForJobToFinish (job, timeOutMs);
  11569. }
  11570. else
  11571. {
  11572. jobs.removeValue (job);
  11573. }
  11574. }
  11575. lock.exit();
  11576. }
  11577. return true;
  11578. }
  11579. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  11580. const int timeOutMs)
  11581. {
  11582. lock.enter();
  11583. for (int i = jobs.size(); --i >= 0;)
  11584. {
  11585. ThreadPoolJob* const job = (ThreadPoolJob*) jobs.getUnchecked(i);
  11586. if (job->isActive)
  11587. {
  11588. if (interruptRunningJobs)
  11589. job->signalJobShouldExit();
  11590. }
  11591. else
  11592. {
  11593. jobs.remove (i);
  11594. }
  11595. }
  11596. lock.exit();
  11597. const uint32 start = Time::getMillisecondCounter();
  11598. while (jobs.size() > 0)
  11599. {
  11600. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  11601. return false;
  11602. Thread::sleep (2);
  11603. }
  11604. return true;
  11605. }
  11606. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  11607. {
  11608. StringArray s;
  11609. const ScopedLock sl (lock);
  11610. for (int i = 0; i < jobs.size(); ++i)
  11611. {
  11612. const ThreadPoolJob* const job = (const ThreadPoolJob*) jobs.getUnchecked(i);
  11613. if (job->isActive || ! onlyReturnActiveJobs)
  11614. s.add (job->getJobName());
  11615. }
  11616. return s;
  11617. }
  11618. void ThreadPool::setThreadPriorities (const int newPriority)
  11619. {
  11620. if (priority != newPriority)
  11621. {
  11622. priority = newPriority;
  11623. for (int i = numThreads; --i >= 0;)
  11624. threads[i]->setPriority (newPriority);
  11625. }
  11626. }
  11627. bool ThreadPool::runNextJob()
  11628. {
  11629. lock.enter();
  11630. ThreadPoolJob* job = 0;
  11631. for (int i = 0; i < jobs.size(); ++i)
  11632. {
  11633. job = (ThreadPoolJob*) jobs [i];
  11634. if (job != 0 && ! (job->isActive || job->shouldStop))
  11635. break;
  11636. job = 0;
  11637. }
  11638. if (job != 0)
  11639. {
  11640. job->isActive = true;
  11641. lock.exit();
  11642. JUCE_TRY
  11643. {
  11644. ThreadPoolJob::JobStatus result = job->runJob();
  11645. lastJobEndTime = Time::getApproximateMillisecondCounter();
  11646. const ScopedLock sl (lock);
  11647. if (jobs.contains (job))
  11648. {
  11649. job->isActive = false;
  11650. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  11651. {
  11652. job->pool = 0;
  11653. job->shouldStop = true;
  11654. jobs.removeValue (job);
  11655. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  11656. delete job;
  11657. }
  11658. else
  11659. {
  11660. // move the job to the end of the queue if it wants another go
  11661. jobs.move (jobs.indexOf (job), -1);
  11662. }
  11663. }
  11664. }
  11665. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  11666. catch (...)
  11667. {
  11668. lock.enter();
  11669. jobs.removeValue (job);
  11670. lock.exit();
  11671. }
  11672. #endif
  11673. }
  11674. else
  11675. {
  11676. lock.exit();
  11677. if (threadStopTimeout > 0
  11678. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  11679. {
  11680. lock.enter();
  11681. if (jobs.size() == 0)
  11682. {
  11683. for (int i = numThreads; --i >= 0;)
  11684. threads[i]->signalThreadShouldExit();
  11685. }
  11686. lock.exit();
  11687. }
  11688. else
  11689. {
  11690. return false;
  11691. }
  11692. }
  11693. return true;
  11694. }
  11695. END_JUCE_NAMESPACE
  11696. /********* End of inlined file: juce_ThreadPool.cpp *********/
  11697. /********* Start of inlined file: juce_TimeSliceThread.cpp *********/
  11698. BEGIN_JUCE_NAMESPACE
  11699. TimeSliceThread::TimeSliceThread (const String& threadName)
  11700. : Thread (threadName),
  11701. index (0),
  11702. clientBeingCalled (0),
  11703. clientsChanged (false)
  11704. {
  11705. }
  11706. TimeSliceThread::~TimeSliceThread()
  11707. {
  11708. stopThread (2000);
  11709. }
  11710. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  11711. {
  11712. const ScopedLock sl (listLock);
  11713. clients.addIfNotAlreadyThere (client);
  11714. clientsChanged = true;
  11715. notify();
  11716. }
  11717. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  11718. {
  11719. const ScopedLock sl1 (listLock);
  11720. clientsChanged = true;
  11721. // if there's a chance we're in the middle of calling this client, we need to
  11722. // also lock the outer lock..
  11723. if (clientBeingCalled == client)
  11724. {
  11725. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  11726. const ScopedLock sl1 (callbackLock);
  11727. const ScopedLock sl2 (listLock);
  11728. clients.removeValue (client);
  11729. }
  11730. else
  11731. {
  11732. clients.removeValue (client);
  11733. }
  11734. }
  11735. int TimeSliceThread::getNumClients() const throw()
  11736. {
  11737. return clients.size();
  11738. }
  11739. TimeSliceClient* TimeSliceThread::getClient (const int index) const throw()
  11740. {
  11741. const ScopedLock sl (listLock);
  11742. return clients [index];
  11743. }
  11744. void TimeSliceThread::run()
  11745. {
  11746. int numCallsSinceBusy = 0;
  11747. while (! threadShouldExit())
  11748. {
  11749. int timeToWait = 500;
  11750. {
  11751. const ScopedLock sl (callbackLock);
  11752. {
  11753. const ScopedLock sl (listLock);
  11754. if (clients.size() > 0)
  11755. {
  11756. index = (index + 1) % clients.size();
  11757. clientBeingCalled = clients [index];
  11758. }
  11759. else
  11760. {
  11761. index = 0;
  11762. clientBeingCalled = 0;
  11763. }
  11764. if (clientsChanged)
  11765. {
  11766. clientsChanged = false;
  11767. numCallsSinceBusy = 0;
  11768. }
  11769. }
  11770. if (clientBeingCalled != 0)
  11771. {
  11772. if (clientBeingCalled->useTimeSlice())
  11773. numCallsSinceBusy = 0;
  11774. else
  11775. ++numCallsSinceBusy;
  11776. if (numCallsSinceBusy >= clients.size())
  11777. timeToWait = 500;
  11778. else if (index == 0)
  11779. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  11780. else
  11781. timeToWait = 0;
  11782. }
  11783. }
  11784. if (timeToWait > 0)
  11785. wait (timeToWait);
  11786. }
  11787. }
  11788. END_JUCE_NAMESPACE
  11789. /********* End of inlined file: juce_TimeSliceThread.cpp *********/
  11790. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  11791. /********* Start of inlined file: juce_Application.cpp *********/
  11792. #if JUCE_MSVC
  11793. #pragma warning (push)
  11794. #pragma warning (disable: 4245 4514 4100)
  11795. #include <crtdbg.h>
  11796. #pragma warning (pop)
  11797. #endif
  11798. BEGIN_JUCE_NAMESPACE
  11799. void juce_setCurrentExecutableFileName (const String& filename) throw();
  11800. void juce_setCurrentThreadName (const String& name) throw();
  11801. static JUCEApplication* appInstance = 0;
  11802. JUCEApplication::JUCEApplication()
  11803. : appReturnValue (0),
  11804. stillInitialising (true)
  11805. {
  11806. }
  11807. JUCEApplication::~JUCEApplication()
  11808. {
  11809. }
  11810. JUCEApplication* JUCEApplication::getInstance() throw()
  11811. {
  11812. return appInstance;
  11813. }
  11814. bool JUCEApplication::isInitialising() const throw()
  11815. {
  11816. return stillInitialising;
  11817. }
  11818. const String JUCEApplication::getApplicationVersion()
  11819. {
  11820. return String::empty;
  11821. }
  11822. bool JUCEApplication::moreThanOneInstanceAllowed()
  11823. {
  11824. return true;
  11825. }
  11826. void JUCEApplication::anotherInstanceStarted (const String&)
  11827. {
  11828. }
  11829. void JUCEApplication::systemRequestedQuit()
  11830. {
  11831. quit();
  11832. }
  11833. void JUCEApplication::quit (const bool useMaximumForce)
  11834. {
  11835. MessageManager::getInstance()->postQuitMessage (useMaximumForce);
  11836. }
  11837. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  11838. {
  11839. appReturnValue = newReturnValue;
  11840. }
  11841. void JUCEApplication::unhandledException (const std::exception*,
  11842. const String&,
  11843. const int)
  11844. {
  11845. jassertfalse
  11846. }
  11847. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  11848. const char* const sourceFile,
  11849. const int lineNumber)
  11850. {
  11851. if (appInstance != 0)
  11852. appInstance->unhandledException (e, sourceFile, lineNumber);
  11853. }
  11854. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  11855. {
  11856. return 0;
  11857. }
  11858. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  11859. {
  11860. commands.add (StandardApplicationCommandIDs::quit);
  11861. }
  11862. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  11863. {
  11864. if (commandID == StandardApplicationCommandIDs::quit)
  11865. {
  11866. result.setInfo ("Quit",
  11867. "Quits the application",
  11868. "Application",
  11869. 0);
  11870. result.defaultKeypresses.add (KeyPress (T('q'), ModifierKeys::commandModifier, 0));
  11871. }
  11872. }
  11873. bool JUCEApplication::perform (const InvocationInfo& info)
  11874. {
  11875. if (info.commandID == StandardApplicationCommandIDs::quit)
  11876. {
  11877. systemRequestedQuit();
  11878. return true;
  11879. }
  11880. return false;
  11881. }
  11882. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  11883. {
  11884. jassert (appInstance == 0);
  11885. appInstance = app;
  11886. bool useForce = true;
  11887. initialiseJuce_GUI();
  11888. InterProcessLock* appLock = 0;
  11889. if (! app->moreThanOneInstanceAllowed())
  11890. {
  11891. appLock = new InterProcessLock ("juceAppLock_" + app->getApplicationName());
  11892. if (! appLock->enter(0))
  11893. {
  11894. MessageManager::broadcastMessage (app->getApplicationName() + "/" + commandLine);
  11895. delete appInstance;
  11896. appInstance = 0;
  11897. commandLine = String::empty;
  11898. DBG ("Another instance is running - quitting...");
  11899. return 0;
  11900. }
  11901. }
  11902. JUCE_TRY
  11903. {
  11904. juce_setCurrentThreadName ("Juce Message Thread");
  11905. // let the app do its setting-up..
  11906. app->initialise (commandLine.trim());
  11907. commandLine = String::empty;
  11908. // register for broadcast new app messages
  11909. MessageManager::getInstance()->registerBroadcastListener (app);
  11910. app->stillInitialising = false;
  11911. // now loop until a quit message is received..
  11912. useForce = MessageManager::getInstance()->runDispatchLoop();
  11913. MessageManager::getInstance()->deregisterBroadcastListener (app);
  11914. if (appLock != 0)
  11915. {
  11916. appLock->exit();
  11917. delete appLock;
  11918. }
  11919. }
  11920. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  11921. catch (const std::exception& e)
  11922. {
  11923. app->unhandledException (&e, __FILE__, __LINE__);
  11924. }
  11925. catch (...)
  11926. {
  11927. app->unhandledException (0, __FILE__, __LINE__);
  11928. }
  11929. #endif
  11930. return shutdownAppAndClearUp (useForce);
  11931. }
  11932. int JUCEApplication::shutdownAppAndClearUp (const bool useMaximumForce)
  11933. {
  11934. jassert (appInstance != 0);
  11935. JUCEApplication* const app = appInstance;
  11936. int returnValue = 0;
  11937. static bool reentrancyCheck = false;
  11938. if (! reentrancyCheck)
  11939. {
  11940. reentrancyCheck = true;
  11941. JUCE_TRY
  11942. {
  11943. // give the app a chance to clean up..
  11944. app->shutdown();
  11945. }
  11946. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  11947. catch (const std::exception& e)
  11948. {
  11949. app->unhandledException (&e, __FILE__, __LINE__);
  11950. }
  11951. catch (...)
  11952. {
  11953. app->unhandledException (0, __FILE__, __LINE__);
  11954. }
  11955. #endif
  11956. JUCE_TRY
  11957. {
  11958. shutdownJuce_GUI();
  11959. returnValue = app->getApplicationReturnValue();
  11960. appInstance = 0;
  11961. delete app;
  11962. }
  11963. JUCE_CATCH_ALL_ASSERT
  11964. if (useMaximumForce)
  11965. {
  11966. Process::terminate();
  11967. }
  11968. reentrancyCheck = false;
  11969. }
  11970. return returnValue;
  11971. }
  11972. int JUCEApplication::main (int argc, char* argv[],
  11973. JUCEApplication* const newApp)
  11974. {
  11975. juce_setCurrentExecutableFileName (String::fromUTF8 ((const uint8*) argv[0]));
  11976. String cmd;
  11977. for (int i = 1; i < argc; ++i)
  11978. cmd << String::fromUTF8 ((const uint8*) argv[i]) << T(' ');
  11979. return JUCEApplication::main (cmd, newApp);
  11980. }
  11981. void JUCEApplication::actionListenerCallback (const String& message)
  11982. {
  11983. if (message.startsWith (getApplicationName() + "/"))
  11984. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  11985. }
  11986. static bool juceInitialisedGUI = false;
  11987. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  11988. {
  11989. if (! juceInitialisedGUI)
  11990. {
  11991. juceInitialisedGUI = true;
  11992. initialiseJuce_NonGUI();
  11993. MessageManager::getInstance();
  11994. Font::initialiseDefaultFontNames();
  11995. LookAndFeel::setDefaultLookAndFeel (0);
  11996. #if JUCE_WIN32 && JUCE_DEBUG
  11997. // This section is just for catching people who mess up their project settings and
  11998. // turn RTTI off..
  11999. try
  12000. {
  12001. TextButton tb (String::empty);
  12002. Component* c = &tb;
  12003. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  12004. c = dynamic_cast <Button*> (c);
  12005. }
  12006. catch (...)
  12007. {
  12008. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  12009. // got as far as this catch statement, then why haven't you got exception catching
  12010. // turned on in the debugger???
  12011. jassertfalse
  12012. }
  12013. #endif
  12014. }
  12015. }
  12016. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  12017. {
  12018. if (juceInitialisedGUI)
  12019. {
  12020. DeletedAtShutdown::deleteAll();
  12021. LookAndFeel::clearDefaultLookAndFeel();
  12022. shutdownJuce_NonGUI();
  12023. juceInitialisedGUI = false;
  12024. }
  12025. }
  12026. END_JUCE_NAMESPACE
  12027. /********* End of inlined file: juce_Application.cpp *********/
  12028. /********* Start of inlined file: juce_ApplicationCommandInfo.cpp *********/
  12029. BEGIN_JUCE_NAMESPACE
  12030. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  12031. : commandID (commandID_),
  12032. flags (0)
  12033. {
  12034. }
  12035. void ApplicationCommandInfo::setInfo (const String& shortName_,
  12036. const String& description_,
  12037. const String& categoryName_,
  12038. const int flags_) throw()
  12039. {
  12040. shortName = shortName_;
  12041. description = description_;
  12042. categoryName = categoryName_;
  12043. flags = flags_;
  12044. }
  12045. void ApplicationCommandInfo::setActive (const bool b) throw()
  12046. {
  12047. if (b)
  12048. flags &= ~isDisabled;
  12049. else
  12050. flags |= isDisabled;
  12051. }
  12052. void ApplicationCommandInfo::setTicked (const bool b) throw()
  12053. {
  12054. if (b)
  12055. flags |= isTicked;
  12056. else
  12057. flags &= ~isTicked;
  12058. }
  12059. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  12060. {
  12061. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  12062. }
  12063. END_JUCE_NAMESPACE
  12064. /********* End of inlined file: juce_ApplicationCommandInfo.cpp *********/
  12065. /********* Start of inlined file: juce_ApplicationCommandManager.cpp *********/
  12066. BEGIN_JUCE_NAMESPACE
  12067. ApplicationCommandManager::ApplicationCommandManager()
  12068. : listeners (8),
  12069. firstTarget (0)
  12070. {
  12071. keyMappings = new KeyPressMappingSet (this);
  12072. Desktop::getInstance().addFocusChangeListener (this);
  12073. }
  12074. ApplicationCommandManager::~ApplicationCommandManager()
  12075. {
  12076. Desktop::getInstance().removeFocusChangeListener (this);
  12077. deleteAndZero (keyMappings);
  12078. }
  12079. void ApplicationCommandManager::clearCommands()
  12080. {
  12081. commands.clear();
  12082. keyMappings->clearAllKeyPresses();
  12083. triggerAsyncUpdate();
  12084. }
  12085. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  12086. {
  12087. // zero isn't a valid command ID!
  12088. jassert (newCommand.commandID != 0);
  12089. // the name isn't optional!
  12090. jassert (newCommand.shortName.isNotEmpty());
  12091. if (getCommandForID (newCommand.commandID) == 0)
  12092. {
  12093. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  12094. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  12095. commands.add (newInfo);
  12096. keyMappings->resetToDefaultMapping (newCommand.commandID);
  12097. triggerAsyncUpdate();
  12098. }
  12099. else
  12100. {
  12101. // trying to re-register the same command with different parameters?
  12102. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  12103. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  12104. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  12105. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  12106. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  12107. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  12108. }
  12109. }
  12110. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  12111. {
  12112. if (target != 0)
  12113. {
  12114. Array <CommandID> commandIDs;
  12115. target->getAllCommands (commandIDs);
  12116. for (int i = 0; i < commandIDs.size(); ++i)
  12117. {
  12118. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  12119. target->getCommandInfo (info.commandID, info);
  12120. registerCommand (info);
  12121. }
  12122. }
  12123. }
  12124. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  12125. {
  12126. for (int i = commands.size(); --i >= 0;)
  12127. {
  12128. if (commands.getUnchecked (i)->commandID == commandID)
  12129. {
  12130. commands.remove (i);
  12131. triggerAsyncUpdate();
  12132. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  12133. for (int j = keys.size(); --j >= 0;)
  12134. keyMappings->removeKeyPress (keys.getReference (j));
  12135. }
  12136. }
  12137. }
  12138. void ApplicationCommandManager::commandStatusChanged()
  12139. {
  12140. triggerAsyncUpdate();
  12141. }
  12142. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  12143. {
  12144. for (int i = commands.size(); --i >= 0;)
  12145. if (commands.getUnchecked(i)->commandID == commandID)
  12146. return commands.getUnchecked(i);
  12147. return 0;
  12148. }
  12149. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  12150. {
  12151. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  12152. return (ci != 0) ? ci->shortName : String::empty;
  12153. }
  12154. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  12155. {
  12156. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  12157. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  12158. : String::empty;
  12159. }
  12160. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  12161. {
  12162. StringArray s;
  12163. for (int i = 0; i < commands.size(); ++i)
  12164. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  12165. return s;
  12166. }
  12167. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  12168. {
  12169. Array <CommandID> results (4);
  12170. for (int i = 0; i < commands.size(); ++i)
  12171. if (commands.getUnchecked(i)->categoryName == categoryName)
  12172. results.add (commands.getUnchecked(i)->commandID);
  12173. return results;
  12174. }
  12175. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  12176. {
  12177. ApplicationCommandTarget::InvocationInfo info (commandID);
  12178. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  12179. return invoke (info, asynchronously);
  12180. }
  12181. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  12182. {
  12183. // This call isn't thread-safe for use from a non-UI thread without locking the message
  12184. // manager first..
  12185. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  12186. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  12187. if (target == 0)
  12188. return false;
  12189. ApplicationCommandInfo commandInfo (0);
  12190. target->getCommandInfo (info_.commandID, commandInfo);
  12191. ApplicationCommandTarget::InvocationInfo info (info_);
  12192. info.commandFlags = commandInfo.flags;
  12193. sendListenerInvokeCallback (info);
  12194. const bool ok = target->invoke (info, asynchronously);
  12195. commandStatusChanged();
  12196. return ok;
  12197. }
  12198. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  12199. {
  12200. return firstTarget != 0 ? firstTarget
  12201. : findDefaultComponentTarget();
  12202. }
  12203. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  12204. {
  12205. firstTarget = newTarget;
  12206. }
  12207. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  12208. ApplicationCommandInfo& upToDateInfo)
  12209. {
  12210. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  12211. if (target == 0)
  12212. target = JUCEApplication::getInstance();
  12213. if (target != 0)
  12214. target = target->getTargetForCommand (commandID);
  12215. if (target != 0)
  12216. target->getCommandInfo (commandID, upToDateInfo);
  12217. return target;
  12218. }
  12219. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  12220. {
  12221. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  12222. if (target == 0 && c != 0)
  12223. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  12224. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  12225. return target;
  12226. }
  12227. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  12228. {
  12229. Component* c = Component::getCurrentlyFocusedComponent();
  12230. if (c == 0)
  12231. {
  12232. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  12233. if (activeWindow != 0)
  12234. {
  12235. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  12236. if (c == 0)
  12237. c = activeWindow;
  12238. }
  12239. }
  12240. if (c == 0)
  12241. {
  12242. // getting a bit desperate now - try all desktop comps..
  12243. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  12244. {
  12245. ApplicationCommandTarget* const target
  12246. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  12247. ->getPeer()->getLastFocusedSubcomponent());
  12248. if (target != 0)
  12249. return target;
  12250. }
  12251. }
  12252. if (c != 0)
  12253. {
  12254. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  12255. // if we're focused on a ResizableWindow, chances are that it's the content
  12256. // component that really should get the event. And if not, the event will
  12257. // still be passed up to the top level window anyway, so let's send it to the
  12258. // content comp.
  12259. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  12260. c = resizableWindow->getContentComponent();
  12261. ApplicationCommandTarget* const target = findTargetForComponent (c);
  12262. if (target != 0)
  12263. return target;
  12264. }
  12265. return JUCEApplication::getInstance();
  12266. }
  12267. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  12268. {
  12269. jassert (listener != 0);
  12270. if (listener != 0)
  12271. listeners.add (listener);
  12272. }
  12273. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  12274. {
  12275. listeners.removeValue (listener);
  12276. }
  12277. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const
  12278. {
  12279. for (int i = listeners.size(); --i >= 0;)
  12280. {
  12281. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandInvoked (info);
  12282. i = jmin (i, listeners.size());
  12283. }
  12284. }
  12285. void ApplicationCommandManager::handleAsyncUpdate()
  12286. {
  12287. for (int i = listeners.size(); --i >= 0;)
  12288. {
  12289. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandListChanged();
  12290. i = jmin (i, listeners.size());
  12291. }
  12292. }
  12293. void ApplicationCommandManager::globalFocusChanged (Component*)
  12294. {
  12295. commandStatusChanged();
  12296. }
  12297. END_JUCE_NAMESPACE
  12298. /********* End of inlined file: juce_ApplicationCommandManager.cpp *********/
  12299. /********* Start of inlined file: juce_ApplicationCommandTarget.cpp *********/
  12300. BEGIN_JUCE_NAMESPACE
  12301. ApplicationCommandTarget::ApplicationCommandTarget()
  12302. : messageInvoker (0)
  12303. {
  12304. }
  12305. ApplicationCommandTarget::~ApplicationCommandTarget()
  12306. {
  12307. deleteAndZero (messageInvoker);
  12308. }
  12309. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  12310. {
  12311. if (isCommandActive (info.commandID))
  12312. {
  12313. if (async)
  12314. {
  12315. if (messageInvoker == 0)
  12316. messageInvoker = new CommandTargetMessageInvoker (this);
  12317. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  12318. return true;
  12319. }
  12320. else
  12321. {
  12322. const bool success = perform (info);
  12323. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  12324. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  12325. // returns the command's info.
  12326. return success;
  12327. }
  12328. }
  12329. return false;
  12330. }
  12331. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  12332. {
  12333. Component* c = dynamic_cast <Component*> (this);
  12334. if (c != 0)
  12335. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  12336. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  12337. return 0;
  12338. }
  12339. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  12340. {
  12341. ApplicationCommandTarget* target = this;
  12342. int depth = 0;
  12343. while (target != 0)
  12344. {
  12345. Array <CommandID> commandIDs;
  12346. target->getAllCommands (commandIDs);
  12347. if (commandIDs.contains (commandID))
  12348. return target;
  12349. target = target->getNextCommandTarget();
  12350. ++depth;
  12351. jassert (depth < 100); // could be a recursive command chain??
  12352. jassert (target != this); // definitely a recursive command chain!
  12353. if (depth > 100 || target == this)
  12354. break;
  12355. }
  12356. if (target == 0)
  12357. {
  12358. target = JUCEApplication::getInstance();
  12359. if (target != 0)
  12360. {
  12361. Array <CommandID> commandIDs;
  12362. target->getAllCommands (commandIDs);
  12363. if (commandIDs.contains (commandID))
  12364. return target;
  12365. }
  12366. }
  12367. return 0;
  12368. }
  12369. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  12370. {
  12371. ApplicationCommandInfo info (commandID);
  12372. info.flags = ApplicationCommandInfo::isDisabled;
  12373. getCommandInfo (commandID, info);
  12374. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  12375. }
  12376. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  12377. {
  12378. ApplicationCommandTarget* target = this;
  12379. int depth = 0;
  12380. while (target != 0)
  12381. {
  12382. if (target->tryToInvoke (info, async))
  12383. return true;
  12384. target = target->getNextCommandTarget();
  12385. ++depth;
  12386. jassert (depth < 100); // could be a recursive command chain??
  12387. jassert (target != this); // definitely a recursive command chain!
  12388. if (depth > 100 || target == this)
  12389. break;
  12390. }
  12391. if (target == 0)
  12392. {
  12393. target = JUCEApplication::getInstance();
  12394. if (target != 0)
  12395. return target->tryToInvoke (info, async);
  12396. }
  12397. return false;
  12398. }
  12399. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  12400. {
  12401. ApplicationCommandTarget::InvocationInfo info (commandID);
  12402. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  12403. return invoke (info, asynchronously);
  12404. }
  12405. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  12406. : commandID (commandID_),
  12407. commandFlags (0),
  12408. invocationMethod (direct),
  12409. originatingComponent (0),
  12410. isKeyDown (false),
  12411. millisecsSinceKeyPressed (0)
  12412. {
  12413. }
  12414. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  12415. : owner (owner_)
  12416. {
  12417. }
  12418. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  12419. {
  12420. }
  12421. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  12422. {
  12423. InvocationInfo* const info = (InvocationInfo*) message.pointerParameter;
  12424. owner->tryToInvoke (*info, false);
  12425. delete info;
  12426. }
  12427. END_JUCE_NAMESPACE
  12428. /********* End of inlined file: juce_ApplicationCommandTarget.cpp *********/
  12429. /********* Start of inlined file: juce_ApplicationProperties.cpp *********/
  12430. BEGIN_JUCE_NAMESPACE
  12431. juce_ImplementSingleton (ApplicationProperties)
  12432. ApplicationProperties::ApplicationProperties() throw()
  12433. : userProps (0),
  12434. commonProps (0),
  12435. msBeforeSaving (3000),
  12436. options (PropertiesFile::storeAsBinary),
  12437. commonSettingsAreReadOnly (0)
  12438. {
  12439. }
  12440. ApplicationProperties::~ApplicationProperties()
  12441. {
  12442. closeFiles();
  12443. clearSingletonInstance();
  12444. }
  12445. void ApplicationProperties::setStorageParameters (const String& applicationName,
  12446. const String& fileNameSuffix,
  12447. const String& folderName_,
  12448. const int millisecondsBeforeSaving,
  12449. const int propertiesFileOptions) throw()
  12450. {
  12451. appName = applicationName;
  12452. fileSuffix = fileNameSuffix;
  12453. folderName = folderName_;
  12454. msBeforeSaving = millisecondsBeforeSaving;
  12455. options = propertiesFileOptions;
  12456. }
  12457. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  12458. const bool testCommonSettings,
  12459. const bool showWarningDialogOnFailure)
  12460. {
  12461. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  12462. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  12463. if (! (userOk && commonOk))
  12464. {
  12465. if (showWarningDialogOnFailure)
  12466. {
  12467. String filenames;
  12468. if (userProps != 0 && ! userOk)
  12469. filenames << '\n' << userProps->getFile().getFullPathName();
  12470. if (commonProps != 0 && ! commonOk)
  12471. filenames << '\n' << commonProps->getFile().getFullPathName();
  12472. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  12473. appName + TRANS(" - Unable to save settings"),
  12474. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  12475. + appName + TRANS(" needs to be able to write to the following files:\n")
  12476. + filenames
  12477. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  12478. }
  12479. return false;
  12480. }
  12481. return true;
  12482. }
  12483. void ApplicationProperties::openFiles() throw()
  12484. {
  12485. // You need to call setStorageParameters() before trying to get hold of the
  12486. // properties!
  12487. jassert (appName.isNotEmpty());
  12488. if (appName.isNotEmpty())
  12489. {
  12490. if (userProps == 0)
  12491. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  12492. false, msBeforeSaving, options);
  12493. if (commonProps == 0)
  12494. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  12495. true, msBeforeSaving, options);
  12496. userProps->setFallbackPropertySet (commonProps);
  12497. }
  12498. }
  12499. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  12500. {
  12501. if (userProps == 0)
  12502. openFiles();
  12503. return userProps;
  12504. }
  12505. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  12506. {
  12507. if (commonProps == 0)
  12508. openFiles();
  12509. if (returnUserPropsIfReadOnly)
  12510. {
  12511. if (commonSettingsAreReadOnly == 0)
  12512. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  12513. if (commonSettingsAreReadOnly > 0)
  12514. return userProps;
  12515. }
  12516. return commonProps;
  12517. }
  12518. bool ApplicationProperties::saveIfNeeded()
  12519. {
  12520. return (userProps == 0 || userProps->saveIfNeeded())
  12521. && (commonProps == 0 || commonProps->saveIfNeeded());
  12522. }
  12523. void ApplicationProperties::closeFiles()
  12524. {
  12525. deleteAndZero (userProps);
  12526. deleteAndZero (commonProps);
  12527. }
  12528. END_JUCE_NAMESPACE
  12529. /********* End of inlined file: juce_ApplicationProperties.cpp *********/
  12530. /********* Start of inlined file: juce_DeletedAtShutdown.cpp *********/
  12531. BEGIN_JUCE_NAMESPACE
  12532. static VoidArray objectsToDelete (16);
  12533. static CriticalSection lock;
  12534. DeletedAtShutdown::DeletedAtShutdown() throw()
  12535. {
  12536. const ScopedLock sl (lock);
  12537. objectsToDelete.add (this);
  12538. }
  12539. DeletedAtShutdown::~DeletedAtShutdown()
  12540. {
  12541. const ScopedLock sl (lock);
  12542. objectsToDelete.removeValue (this);
  12543. }
  12544. void DeletedAtShutdown::deleteAll()
  12545. {
  12546. // make a local copy of the array, so it can't get into a loop if something
  12547. // creates another DeletedAtShutdown object during its destructor.
  12548. lock.enter();
  12549. const VoidArray localCopy (objectsToDelete);
  12550. lock.exit();
  12551. for (int i = localCopy.size(); --i >= 0;)
  12552. {
  12553. JUCE_TRY
  12554. {
  12555. DeletedAtShutdown* const deletee = (DeletedAtShutdown*) localCopy.getUnchecked(i);
  12556. // double-check that it's not already been deleted during another object's destructor.
  12557. lock.enter();
  12558. const bool okToDelete = objectsToDelete.contains (deletee);
  12559. lock.exit();
  12560. if (okToDelete)
  12561. delete deletee;
  12562. }
  12563. JUCE_CATCH_EXCEPTION
  12564. }
  12565. // if no objects got re-created during shutdown, this should have been emptied by their
  12566. // destructors
  12567. jassert (objectsToDelete.size() == 0);
  12568. objectsToDelete.clear(); // just to make sure the array doesn't have any memory still allocated
  12569. }
  12570. END_JUCE_NAMESPACE
  12571. /********* End of inlined file: juce_DeletedAtShutdown.cpp *********/
  12572. /********* Start of inlined file: juce_PropertiesFile.cpp *********/
  12573. BEGIN_JUCE_NAMESPACE
  12574. static const int propFileMagicNumber = ((int) littleEndianInt ("PROP"));
  12575. static const int propFileMagicNumberCompressed = ((int) littleEndianInt ("CPRP"));
  12576. static const tchar* const propertyFileXmlTag = T("PROPERTIES");
  12577. static const tchar* const propertyTagName = T("VALUE");
  12578. PropertiesFile::PropertiesFile (const File& f,
  12579. const int millisecondsBeforeSaving,
  12580. const int options_) throw()
  12581. : PropertySet (ignoreCaseOfKeyNames),
  12582. file (f),
  12583. timerInterval (millisecondsBeforeSaving),
  12584. options (options_),
  12585. needsWriting (false)
  12586. {
  12587. // You need to correctly specify just one storage format for the file
  12588. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  12589. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  12590. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  12591. InputStream* fileStream = f.createInputStream();
  12592. if (fileStream != 0)
  12593. {
  12594. int magicNumber = fileStream->readInt();
  12595. if (magicNumber == propFileMagicNumberCompressed)
  12596. {
  12597. fileStream = new SubregionStream (fileStream, 4, -1, true);
  12598. fileStream = new GZIPDecompressorInputStream (fileStream, true);
  12599. magicNumber = propFileMagicNumber;
  12600. }
  12601. if (magicNumber == propFileMagicNumber)
  12602. {
  12603. BufferedInputStream in (fileStream, 2048, true);
  12604. int numValues = in.readInt();
  12605. while (--numValues >= 0 && ! in.isExhausted())
  12606. {
  12607. const String key (in.readString());
  12608. const String value (in.readString());
  12609. jassert (key.isNotEmpty());
  12610. if (key.isNotEmpty())
  12611. getAllProperties().set (key, value);
  12612. }
  12613. }
  12614. else
  12615. {
  12616. // Not a binary props file - let's see if it's XML..
  12617. delete fileStream;
  12618. XmlDocument parser (f);
  12619. XmlElement* doc = parser.getDocumentElement (true);
  12620. if (doc != 0 && doc->hasTagName (propertyFileXmlTag))
  12621. {
  12622. delete doc;
  12623. doc = parser.getDocumentElement();
  12624. if (doc != 0)
  12625. {
  12626. forEachXmlChildElementWithTagName (*doc, e, propertyTagName)
  12627. {
  12628. const String name (e->getStringAttribute (T("name")));
  12629. if (name.isNotEmpty())
  12630. {
  12631. getAllProperties().set (name,
  12632. e->getFirstChildElement() != 0
  12633. ? e->getFirstChildElement()->createDocument (String::empty, true)
  12634. : e->getStringAttribute (T("val")));
  12635. }
  12636. }
  12637. }
  12638. else
  12639. {
  12640. // must be a pretty broken XML file we're trying to parse here!
  12641. jassertfalse
  12642. }
  12643. delete doc;
  12644. }
  12645. }
  12646. }
  12647. }
  12648. PropertiesFile::~PropertiesFile()
  12649. {
  12650. saveIfNeeded();
  12651. }
  12652. bool PropertiesFile::saveIfNeeded()
  12653. {
  12654. const ScopedLock sl (getLock());
  12655. return (! needsWriting) || save();
  12656. }
  12657. bool PropertiesFile::needsToBeSaved() const throw()
  12658. {
  12659. const ScopedLock sl (getLock());
  12660. return needsWriting;
  12661. }
  12662. bool PropertiesFile::save()
  12663. {
  12664. const ScopedLock sl (getLock());
  12665. stopTimer();
  12666. if (file == File::nonexistent
  12667. || file.isDirectory()
  12668. || ! file.getParentDirectory().createDirectory())
  12669. return false;
  12670. if ((options & storeAsXML) != 0)
  12671. {
  12672. XmlElement* const doc = new XmlElement (propertyFileXmlTag);
  12673. for (int i = 0; i < getAllProperties().size(); ++i)
  12674. {
  12675. XmlElement* const e = new XmlElement (propertyTagName);
  12676. e->setAttribute (T("name"), getAllProperties().getAllKeys() [i]);
  12677. // if the value seems to contain xml, store it as such..
  12678. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  12679. XmlElement* const childElement = xmlContent.getDocumentElement();
  12680. if (childElement != 0)
  12681. e->addChildElement (childElement);
  12682. else
  12683. e->setAttribute (T("val"), getAllProperties().getAllValues() [i]);
  12684. doc->addChildElement (e);
  12685. }
  12686. const bool ok = doc->writeToFile (file, String::empty);
  12687. delete doc;
  12688. return ok;
  12689. }
  12690. else
  12691. {
  12692. const File tempFile (file.getNonexistentSibling (false));
  12693. OutputStream* out = tempFile.createOutputStream();
  12694. if (out != 0)
  12695. {
  12696. if ((options & storeAsCompressedBinary) != 0)
  12697. {
  12698. out->writeInt (propFileMagicNumberCompressed);
  12699. out->flush();
  12700. out = new GZIPCompressorOutputStream (out, 9, true);
  12701. }
  12702. else
  12703. {
  12704. // have you set up the storage option flags correctly?
  12705. jassert ((options & storeAsBinary) != 0);
  12706. out->writeInt (propFileMagicNumber);
  12707. }
  12708. const int numProperties = getAllProperties().size();
  12709. out->writeInt (numProperties);
  12710. for (int i = 0; i < numProperties; ++i)
  12711. {
  12712. out->writeString (getAllProperties().getAllKeys() [i]);
  12713. out->writeString (getAllProperties().getAllValues() [i]);
  12714. }
  12715. out->flush();
  12716. delete out;
  12717. if (tempFile.moveFileTo (file))
  12718. {
  12719. needsWriting = false;
  12720. return true;
  12721. }
  12722. tempFile.deleteFile();
  12723. }
  12724. }
  12725. return false;
  12726. }
  12727. void PropertiesFile::timerCallback()
  12728. {
  12729. saveIfNeeded();
  12730. }
  12731. void PropertiesFile::propertyChanged()
  12732. {
  12733. sendChangeMessage (this);
  12734. needsWriting = true;
  12735. if (timerInterval > 0)
  12736. startTimer (timerInterval);
  12737. else if (timerInterval == 0)
  12738. saveIfNeeded();
  12739. }
  12740. const File PropertiesFile::getFile() const throw()
  12741. {
  12742. return file;
  12743. }
  12744. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  12745. const String& fileNameSuffix,
  12746. const String& folderName,
  12747. const bool commonToAllUsers)
  12748. {
  12749. // mustn't have illegal characters in this name..
  12750. jassert (applicationName == File::createLegalFileName (applicationName));
  12751. #if JUCE_MAC
  12752. File dir (commonToAllUsers ? "/Library/Preferences"
  12753. : "~/Library/Preferences");
  12754. if (folderName.isNotEmpty())
  12755. dir = dir.getChildFile (folderName);
  12756. #endif
  12757. #ifdef JUCE_LINUX
  12758. const File dir ((commonToAllUsers ? T("/var/") : T("~/"))
  12759. + (folderName.isNotEmpty() ? folderName
  12760. : (T(".") + applicationName)));
  12761. #endif
  12762. #if JUCE_WIN32
  12763. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  12764. : File::userApplicationDataDirectory));
  12765. if (dir == File::nonexistent)
  12766. return File::nonexistent;
  12767. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  12768. : applicationName);
  12769. #endif
  12770. return dir.getChildFile (applicationName)
  12771. .withFileExtension (fileNameSuffix);
  12772. }
  12773. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  12774. const String& fileNameSuffix,
  12775. const String& folderName,
  12776. const bool commonToAllUsers,
  12777. const int millisecondsBeforeSaving,
  12778. const int propertiesFileOptions)
  12779. {
  12780. const File file (getDefaultAppSettingsFile (applicationName,
  12781. fileNameSuffix,
  12782. folderName,
  12783. commonToAllUsers));
  12784. jassert (file != File::nonexistent);
  12785. if (file == File::nonexistent)
  12786. return 0;
  12787. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions);
  12788. }
  12789. END_JUCE_NAMESPACE
  12790. /********* End of inlined file: juce_PropertiesFile.cpp *********/
  12791. /********* Start of inlined file: juce_AiffAudioFormat.cpp *********/
  12792. BEGIN_JUCE_NAMESPACE
  12793. #undef chunkName
  12794. #define chunkName(a) (int)littleEndianInt(a)
  12795. #define aiffFormatName TRANS("AIFF file")
  12796. static const tchar* const aiffExtensions[] = { T(".aiff"), T(".aif"), 0 };
  12797. class AiffAudioFormatReader : public AudioFormatReader
  12798. {
  12799. public:
  12800. int bytesPerFrame;
  12801. int64 dataChunkStart;
  12802. bool littleEndian;
  12803. AiffAudioFormatReader (InputStream* in)
  12804. : AudioFormatReader (in, aiffFormatName)
  12805. {
  12806. if (input->readInt() == chunkName ("FORM"))
  12807. {
  12808. const int len = input->readIntBigEndian();
  12809. const int64 end = input->getPosition() + len;
  12810. const int nextType = input->readInt();
  12811. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  12812. {
  12813. bool hasGotVer = false;
  12814. bool hasGotData = false;
  12815. bool hasGotType = false;
  12816. while (input->getPosition() < end)
  12817. {
  12818. const int type = input->readInt();
  12819. const uint32 length = (uint32) input->readIntBigEndian();
  12820. const int64 chunkEnd = input->getPosition() + length;
  12821. if (type == chunkName ("FVER"))
  12822. {
  12823. hasGotVer = true;
  12824. const int ver = input->readIntBigEndian();
  12825. if (ver != 0 && ver != (int)0xa2805140)
  12826. break;
  12827. }
  12828. else if (type == chunkName ("COMM"))
  12829. {
  12830. hasGotType = true;
  12831. numChannels = (unsigned int)input->readShortBigEndian();
  12832. lengthInSamples = input->readIntBigEndian();
  12833. bitsPerSample = input->readShortBigEndian();
  12834. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  12835. unsigned char sampleRateBytes[10];
  12836. input->read (sampleRateBytes, 10);
  12837. const int byte0 = sampleRateBytes[0];
  12838. if ((byte0 & 0x80) != 0
  12839. || byte0 <= 0x3F || byte0 > 0x40
  12840. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  12841. break;
  12842. unsigned int sampRate = bigEndianInt ((char*) sampleRateBytes + 2);
  12843. sampRate >>= (16414 - bigEndianShort ((char*) sampleRateBytes));
  12844. sampleRate = (int)sampRate;
  12845. if (length <= 18)
  12846. {
  12847. // some types don't have a chunk large enough to include a compression
  12848. // type, so assume it's just big-endian pcm
  12849. littleEndian = false;
  12850. }
  12851. else
  12852. {
  12853. const int compType = input->readInt();
  12854. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  12855. {
  12856. littleEndian = false;
  12857. }
  12858. else if (compType == chunkName ("sowt"))
  12859. {
  12860. littleEndian = true;
  12861. }
  12862. else
  12863. {
  12864. sampleRate = 0;
  12865. break;
  12866. }
  12867. }
  12868. }
  12869. else if (type == chunkName ("SSND"))
  12870. {
  12871. hasGotData = true;
  12872. const int offset = input->readIntBigEndian();
  12873. dataChunkStart = input->getPosition() + 4 + offset;
  12874. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  12875. }
  12876. else if ((hasGotVer && hasGotData && hasGotType)
  12877. || chunkEnd < input->getPosition()
  12878. || input->isExhausted())
  12879. {
  12880. break;
  12881. }
  12882. input->setPosition (chunkEnd);
  12883. }
  12884. }
  12885. }
  12886. }
  12887. ~AiffAudioFormatReader()
  12888. {
  12889. }
  12890. bool read (int** destSamples,
  12891. int64 startSampleInFile,
  12892. int numSamples)
  12893. {
  12894. int64 start = startSampleInFile;
  12895. int startOffsetInDestBuffer = 0;
  12896. if (startSampleInFile < 0)
  12897. {
  12898. const int silence = (int) jmin (-startSampleInFile, (int64) numSamples);
  12899. int** destChan = destSamples;
  12900. for (int i = 2; --i >= 0;)
  12901. {
  12902. if (*destChan != 0)
  12903. {
  12904. zeromem (*destChan, sizeof (int) * silence);
  12905. ++destChan;
  12906. }
  12907. }
  12908. startOffsetInDestBuffer += silence;
  12909. numSamples -= silence;
  12910. start = 0;
  12911. }
  12912. int numToDo = jlimit (0, numSamples, (int) (lengthInSamples - start));
  12913. if (numToDo > 0)
  12914. {
  12915. input->setPosition (dataChunkStart + start * bytesPerFrame);
  12916. int num = numToDo;
  12917. int* left = destSamples[0];
  12918. if (left != 0)
  12919. left += startOffsetInDestBuffer;
  12920. int* right = destSamples[1];
  12921. if (right != 0)
  12922. right += startOffsetInDestBuffer;
  12923. // (keep this a multiple of 3)
  12924. const int tempBufSize = 1440 * 4;
  12925. char tempBuffer [tempBufSize];
  12926. while (num > 0)
  12927. {
  12928. const int numThisTime = jmin (tempBufSize / bytesPerFrame, num);
  12929. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  12930. if (bytesRead < numThisTime * bytesPerFrame)
  12931. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  12932. if (bitsPerSample == 16)
  12933. {
  12934. if (littleEndian)
  12935. {
  12936. const short* src = (const short*) tempBuffer;
  12937. if (numChannels > 1)
  12938. {
  12939. if (left == 0)
  12940. {
  12941. for (int i = numThisTime; --i >= 0;)
  12942. {
  12943. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12944. ++src;
  12945. }
  12946. }
  12947. else if (right == 0)
  12948. {
  12949. for (int i = numThisTime; --i >= 0;)
  12950. {
  12951. ++src;
  12952. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12953. }
  12954. }
  12955. else
  12956. {
  12957. for (int i = numThisTime; --i >= 0;)
  12958. {
  12959. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12960. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12961. }
  12962. }
  12963. }
  12964. else
  12965. {
  12966. for (int i = numThisTime; --i >= 0;)
  12967. {
  12968. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12969. }
  12970. }
  12971. }
  12972. else
  12973. {
  12974. const char* src = (const char*) tempBuffer;
  12975. if (numChannels > 1)
  12976. {
  12977. if (left == 0)
  12978. {
  12979. for (int i = numThisTime; --i >= 0;)
  12980. {
  12981. *right++ = bigEndianShort (src) << 16;
  12982. src += 4;
  12983. }
  12984. }
  12985. else if (right == 0)
  12986. {
  12987. for (int i = numThisTime; --i >= 0;)
  12988. {
  12989. src += 2;
  12990. *left++ = bigEndianShort (src) << 16;
  12991. src += 2;
  12992. }
  12993. }
  12994. else
  12995. {
  12996. for (int i = numThisTime; --i >= 0;)
  12997. {
  12998. *left++ = bigEndianShort (src) << 16;
  12999. src += 2;
  13000. *right++ = bigEndianShort (src) << 16;
  13001. src += 2;
  13002. }
  13003. }
  13004. }
  13005. else
  13006. {
  13007. for (int i = numThisTime; --i >= 0;)
  13008. {
  13009. *left++ = bigEndianShort (src) << 16;
  13010. src += 2;
  13011. }
  13012. }
  13013. }
  13014. }
  13015. else if (bitsPerSample == 24)
  13016. {
  13017. const char* src = (const char*)tempBuffer;
  13018. if (littleEndian)
  13019. {
  13020. if (numChannels > 1)
  13021. {
  13022. if (left == 0)
  13023. {
  13024. for (int i = numThisTime; --i >= 0;)
  13025. {
  13026. *right++ = littleEndian24Bit (src) << 8;
  13027. src += 6;
  13028. }
  13029. }
  13030. else if (right == 0)
  13031. {
  13032. for (int i = numThisTime; --i >= 0;)
  13033. {
  13034. src += 3;
  13035. *left++ = littleEndian24Bit (src) << 8;
  13036. src += 3;
  13037. }
  13038. }
  13039. else
  13040. {
  13041. for (int i = numThisTime; --i >= 0;)
  13042. {
  13043. *left++ = littleEndian24Bit (src) << 8;
  13044. src += 3;
  13045. *right++ = littleEndian24Bit (src) << 8;
  13046. src += 3;
  13047. }
  13048. }
  13049. }
  13050. else
  13051. {
  13052. for (int i = numThisTime; --i >= 0;)
  13053. {
  13054. *left++ = littleEndian24Bit (src) << 8;
  13055. src += 3;
  13056. }
  13057. }
  13058. }
  13059. else
  13060. {
  13061. if (numChannels > 1)
  13062. {
  13063. if (left == 0)
  13064. {
  13065. for (int i = numThisTime; --i >= 0;)
  13066. {
  13067. *right++ = bigEndian24Bit (src) << 8;
  13068. src += 6;
  13069. }
  13070. }
  13071. else if (right == 0)
  13072. {
  13073. for (int i = numThisTime; --i >= 0;)
  13074. {
  13075. src += 3;
  13076. *left++ = bigEndian24Bit (src) << 8;
  13077. src += 3;
  13078. }
  13079. }
  13080. else
  13081. {
  13082. for (int i = numThisTime; --i >= 0;)
  13083. {
  13084. *left++ = bigEndian24Bit (src) << 8;
  13085. src += 3;
  13086. *right++ = bigEndian24Bit (src) << 8;
  13087. src += 3;
  13088. }
  13089. }
  13090. }
  13091. else
  13092. {
  13093. for (int i = numThisTime; --i >= 0;)
  13094. {
  13095. *left++ = bigEndian24Bit (src) << 8;
  13096. src += 3;
  13097. }
  13098. }
  13099. }
  13100. }
  13101. else if (bitsPerSample == 32)
  13102. {
  13103. const unsigned int* src = (const unsigned int*) tempBuffer;
  13104. unsigned int* l = (unsigned int*) left;
  13105. unsigned int* r = (unsigned int*) right;
  13106. if (littleEndian)
  13107. {
  13108. if (numChannels > 1)
  13109. {
  13110. if (l == 0)
  13111. {
  13112. for (int i = numThisTime; --i >= 0;)
  13113. {
  13114. ++src;
  13115. *r++ = swapIfBigEndian (*src++);
  13116. }
  13117. }
  13118. else if (r == 0)
  13119. {
  13120. for (int i = numThisTime; --i >= 0;)
  13121. {
  13122. *l++ = swapIfBigEndian (*src++);
  13123. ++src;
  13124. }
  13125. }
  13126. else
  13127. {
  13128. for (int i = numThisTime; --i >= 0;)
  13129. {
  13130. *l++ = swapIfBigEndian (*src++);
  13131. *r++ = swapIfBigEndian (*src++);
  13132. }
  13133. }
  13134. }
  13135. else
  13136. {
  13137. for (int i = numThisTime; --i >= 0;)
  13138. {
  13139. *l++ = swapIfBigEndian (*src++);
  13140. }
  13141. }
  13142. }
  13143. else
  13144. {
  13145. if (numChannels > 1)
  13146. {
  13147. if (l == 0)
  13148. {
  13149. for (int i = numThisTime; --i >= 0;)
  13150. {
  13151. ++src;
  13152. *r++ = swapIfLittleEndian (*src++);
  13153. }
  13154. }
  13155. else if (r == 0)
  13156. {
  13157. for (int i = numThisTime; --i >= 0;)
  13158. {
  13159. *l++ = swapIfLittleEndian (*src++);
  13160. ++src;
  13161. }
  13162. }
  13163. else
  13164. {
  13165. for (int i = numThisTime; --i >= 0;)
  13166. {
  13167. *l++ = swapIfLittleEndian (*src++);
  13168. *r++ = swapIfLittleEndian (*src++);
  13169. }
  13170. }
  13171. }
  13172. else
  13173. {
  13174. for (int i = numThisTime; --i >= 0;)
  13175. {
  13176. *l++ = swapIfLittleEndian (*src++);
  13177. }
  13178. }
  13179. }
  13180. left = (int*) l;
  13181. right = (int*) r;
  13182. }
  13183. else if (bitsPerSample == 8)
  13184. {
  13185. const char* src = (const char*) tempBuffer;
  13186. if (numChannels > 1)
  13187. {
  13188. if (left == 0)
  13189. {
  13190. for (int i = numThisTime; --i >= 0;)
  13191. {
  13192. *right++ = ((int) *src++) << 24;
  13193. ++src;
  13194. }
  13195. }
  13196. else if (right == 0)
  13197. {
  13198. for (int i = numThisTime; --i >= 0;)
  13199. {
  13200. ++src;
  13201. *left++ = ((int) *src++) << 24;
  13202. }
  13203. }
  13204. else
  13205. {
  13206. for (int i = numThisTime; --i >= 0;)
  13207. {
  13208. *left++ = ((int) *src++) << 24;
  13209. *right++ = ((int) *src++) << 24;
  13210. }
  13211. }
  13212. }
  13213. else
  13214. {
  13215. for (int i = numThisTime; --i >= 0;)
  13216. {
  13217. *left++ = ((int) *src++) << 24;
  13218. }
  13219. }
  13220. }
  13221. num -= numThisTime;
  13222. }
  13223. }
  13224. if (numToDo < numSamples)
  13225. {
  13226. int** destChan = destSamples;
  13227. while (*destChan != 0)
  13228. {
  13229. zeromem ((*destChan) + (startOffsetInDestBuffer + numToDo),
  13230. sizeof (int) * (numSamples - numToDo));
  13231. ++destChan;
  13232. }
  13233. }
  13234. return true;
  13235. }
  13236. juce_UseDebuggingNewOperator
  13237. private:
  13238. AiffAudioFormatReader (const AiffAudioFormatReader&);
  13239. const AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  13240. };
  13241. class AiffAudioFormatWriter : public AudioFormatWriter
  13242. {
  13243. MemoryBlock tempBlock;
  13244. uint32 lengthInSamples, bytesWritten;
  13245. int64 headerPosition;
  13246. bool writeFailed;
  13247. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  13248. const AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  13249. void writeHeader()
  13250. {
  13251. const bool couldSeekOk = output->setPosition (headerPosition);
  13252. (void) couldSeekOk;
  13253. // if this fails, you've given it an output stream that can't seek! It needs
  13254. // to be able to seek back to write the header
  13255. jassert (couldSeekOk);
  13256. const int headerLen = 54;
  13257. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  13258. audioBytes += (audioBytes & 1);
  13259. output->writeInt (chunkName ("FORM"));
  13260. output->writeIntBigEndian (headerLen + audioBytes - 8);
  13261. output->writeInt (chunkName ("AIFF"));
  13262. output->writeInt (chunkName ("COMM"));
  13263. output->writeIntBigEndian (18);
  13264. output->writeShortBigEndian ((short) numChannels);
  13265. output->writeIntBigEndian (lengthInSamples);
  13266. output->writeShortBigEndian ((short) bitsPerSample);
  13267. uint8 sampleRateBytes[10];
  13268. zeromem (sampleRateBytes, 10);
  13269. if (sampleRate <= 1)
  13270. {
  13271. sampleRateBytes[0] = 0x3f;
  13272. sampleRateBytes[1] = 0xff;
  13273. sampleRateBytes[2] = 0x80;
  13274. }
  13275. else
  13276. {
  13277. int mask = 0x40000000;
  13278. sampleRateBytes[0] = 0x40;
  13279. if (sampleRate >= mask)
  13280. {
  13281. jassertfalse
  13282. sampleRateBytes[1] = 0x1d;
  13283. }
  13284. else
  13285. {
  13286. int n = (int) sampleRate;
  13287. int i;
  13288. for (i = 0; i <= 32 ; ++i)
  13289. {
  13290. if ((n & mask) != 0)
  13291. break;
  13292. mask >>= 1;
  13293. }
  13294. n = n << (i + 1);
  13295. sampleRateBytes[1] = (uint8) (29 - i);
  13296. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  13297. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  13298. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  13299. sampleRateBytes[5] = (uint8) (n & 0xff);
  13300. }
  13301. }
  13302. output->write (sampleRateBytes, 10);
  13303. output->writeInt (chunkName ("SSND"));
  13304. output->writeIntBigEndian (audioBytes + 8);
  13305. output->writeInt (0);
  13306. output->writeInt (0);
  13307. jassert (output->getPosition() == headerLen);
  13308. }
  13309. public:
  13310. AiffAudioFormatWriter (OutputStream* out,
  13311. const double sampleRate,
  13312. const unsigned int chans,
  13313. const int bits)
  13314. : AudioFormatWriter (out,
  13315. aiffFormatName,
  13316. sampleRate,
  13317. chans,
  13318. bits),
  13319. lengthInSamples (0),
  13320. bytesWritten (0),
  13321. writeFailed (false)
  13322. {
  13323. headerPosition = out->getPosition();
  13324. writeHeader();
  13325. }
  13326. ~AiffAudioFormatWriter()
  13327. {
  13328. if ((bytesWritten & 1) != 0)
  13329. output->writeByte (0);
  13330. writeHeader();
  13331. }
  13332. bool write (const int** data, int numSamples)
  13333. {
  13334. if (writeFailed)
  13335. return false;
  13336. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  13337. tempBlock.ensureSize (bytes, false);
  13338. char* buffer = (char*) tempBlock.getData();
  13339. const int* left = data[0];
  13340. const int* right = data[1];
  13341. if (right == 0)
  13342. right = left;
  13343. if (bitsPerSample == 16)
  13344. {
  13345. short* b = (short*) buffer;
  13346. if (numChannels > 1)
  13347. {
  13348. for (int i = numSamples; --i >= 0;)
  13349. {
  13350. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  13351. *b++ = (short) swapIfLittleEndian ((unsigned short) (*right++ >> 16));
  13352. }
  13353. }
  13354. else
  13355. {
  13356. for (int i = numSamples; --i >= 0;)
  13357. {
  13358. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  13359. }
  13360. }
  13361. }
  13362. else if (bitsPerSample == 24)
  13363. {
  13364. char* b = (char*) buffer;
  13365. if (numChannels > 1)
  13366. {
  13367. for (int i = numSamples; --i >= 0;)
  13368. {
  13369. bigEndian24BitToChars (*left++ >> 8, b);
  13370. b += 3;
  13371. bigEndian24BitToChars (*right++ >> 8, b);
  13372. b += 3;
  13373. }
  13374. }
  13375. else
  13376. {
  13377. for (int i = numSamples; --i >= 0;)
  13378. {
  13379. bigEndian24BitToChars (*left++ >> 8, b);
  13380. b += 3;
  13381. }
  13382. }
  13383. }
  13384. else if (bitsPerSample == 32)
  13385. {
  13386. unsigned int* b = (unsigned int*) buffer;
  13387. if (numChannels > 1)
  13388. {
  13389. for (int i = numSamples; --i >= 0;)
  13390. {
  13391. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  13392. *b++ = swapIfLittleEndian ((unsigned int) *right++);
  13393. }
  13394. }
  13395. else
  13396. {
  13397. for (int i = numSamples; --i >= 0;)
  13398. {
  13399. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  13400. }
  13401. }
  13402. }
  13403. else if (bitsPerSample == 8)
  13404. {
  13405. char* b = (char*)buffer;
  13406. if (numChannels > 1)
  13407. {
  13408. for (int i = numSamples; --i >= 0;)
  13409. {
  13410. *b++ = (char) (*left++ >> 24);
  13411. *b++ = (char) (*right++ >> 24);
  13412. }
  13413. }
  13414. else
  13415. {
  13416. for (int i = numSamples; --i >= 0;)
  13417. {
  13418. *b++ = (char) (*left++ >> 24);
  13419. }
  13420. }
  13421. }
  13422. if (bytesWritten + bytes >= (uint32) 0xfff00000
  13423. || ! output->write (buffer, bytes))
  13424. {
  13425. // failed to write to disk, so let's try writing the header.
  13426. // If it's just run out of disk space, then if it does manage
  13427. // to write the header, we'll still have a useable file..
  13428. writeHeader();
  13429. writeFailed = true;
  13430. return false;
  13431. }
  13432. else
  13433. {
  13434. bytesWritten += bytes;
  13435. lengthInSamples += numSamples;
  13436. return true;
  13437. }
  13438. }
  13439. juce_UseDebuggingNewOperator
  13440. };
  13441. AiffAudioFormat::AiffAudioFormat()
  13442. : AudioFormat (aiffFormatName, (const tchar**) aiffExtensions)
  13443. {
  13444. }
  13445. AiffAudioFormat::~AiffAudioFormat()
  13446. {
  13447. }
  13448. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  13449. {
  13450. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  13451. return Array <int> (rates);
  13452. }
  13453. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  13454. {
  13455. const int depths[] = { 8, 16, 24, 0 };
  13456. return Array <int> (depths);
  13457. }
  13458. bool AiffAudioFormat::canDoStereo()
  13459. {
  13460. return true;
  13461. }
  13462. bool AiffAudioFormat::canDoMono()
  13463. {
  13464. return true;
  13465. }
  13466. #if JUCE_MAC
  13467. bool AiffAudioFormat::canHandleFile (const File& f)
  13468. {
  13469. if (AudioFormat::canHandleFile (f))
  13470. return true;
  13471. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  13472. return type == 'AIFF' || type == 'AIFC'
  13473. || type == 'aiff' || type == 'aifc';
  13474. }
  13475. #endif
  13476. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  13477. const bool deleteStreamIfOpeningFails)
  13478. {
  13479. AiffAudioFormatReader* w = new AiffAudioFormatReader (sourceStream);
  13480. if (w->sampleRate == 0)
  13481. {
  13482. if (! deleteStreamIfOpeningFails)
  13483. w->input = 0;
  13484. deleteAndZero (w);
  13485. }
  13486. return w;
  13487. }
  13488. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  13489. double sampleRate,
  13490. unsigned int chans,
  13491. int bitsPerSample,
  13492. const StringPairArray& /*metadataValues*/,
  13493. int /*qualityOptionIndex*/)
  13494. {
  13495. if (getPossibleBitDepths().contains (bitsPerSample))
  13496. {
  13497. return new AiffAudioFormatWriter (out,
  13498. sampleRate,
  13499. chans,
  13500. bitsPerSample);
  13501. }
  13502. return 0;
  13503. }
  13504. END_JUCE_NAMESPACE
  13505. /********* End of inlined file: juce_AiffAudioFormat.cpp *********/
  13506. /********* Start of inlined file: juce_AudioCDReader.cpp *********/
  13507. BEGIN_JUCE_NAMESPACE
  13508. #if JUCE_MAC
  13509. // Mac version doesn't need any native code because it's all done with files..
  13510. // Windows + Linux versions are in the platform-dependent code sections.
  13511. static void findCDs (OwnedArray<File>& cds)
  13512. {
  13513. File volumes ("/Volumes");
  13514. volumes.findChildFiles (cds, File::findDirectories, false);
  13515. for (int i = cds.size(); --i >= 0;)
  13516. if (! cds[i]->getChildFile (".TOC.plist").exists())
  13517. cds.remove (i);
  13518. }
  13519. const StringArray AudioCDReader::getAvailableCDNames()
  13520. {
  13521. OwnedArray<File> cds;
  13522. findCDs (cds);
  13523. StringArray names;
  13524. for (int i = 0; i < cds.size(); ++i)
  13525. names.add (cds[i]->getFileName());
  13526. return names;
  13527. }
  13528. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  13529. {
  13530. OwnedArray<File> cds;
  13531. findCDs (cds);
  13532. if (cds[index] != 0)
  13533. return new AudioCDReader (*cds[index]);
  13534. else
  13535. return 0;
  13536. }
  13537. AudioCDReader::AudioCDReader (const File& volume)
  13538. : AudioFormatReader (0, "CD Audio"),
  13539. volumeDir (volume),
  13540. currentReaderTrack (-1),
  13541. reader (0)
  13542. {
  13543. sampleRate = 44100.0;
  13544. bitsPerSample = 16;
  13545. numChannels = 2;
  13546. usesFloatingPointData = false;
  13547. refreshTrackLengths();
  13548. }
  13549. AudioCDReader::~AudioCDReader()
  13550. {
  13551. if (reader != 0)
  13552. delete reader;
  13553. }
  13554. static int getTrackNumber (const File& file)
  13555. {
  13556. return file.getFileName()
  13557. .initialSectionContainingOnly (T("0123456789"))
  13558. .getIntValue();
  13559. }
  13560. int AudioCDReader::compareElements (const File* const first, const File* const second) throw()
  13561. {
  13562. const int firstTrack = getTrackNumber (*first);
  13563. const int secondTrack = getTrackNumber (*second);
  13564. jassert (firstTrack > 0 && secondTrack > 0);
  13565. return firstTrack - secondTrack;
  13566. }
  13567. void AudioCDReader::refreshTrackLengths()
  13568. {
  13569. tracks.clear();
  13570. trackStartSamples.clear();
  13571. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, T("*.aiff"));
  13572. tracks.sort (*this);
  13573. AiffAudioFormat format;
  13574. int sample = 0;
  13575. for (int i = 0; i < tracks.size(); ++i)
  13576. {
  13577. trackStartSamples.add (sample);
  13578. FileInputStream* const in = tracks[i]->createInputStream();
  13579. if (in != 0)
  13580. {
  13581. AudioFormatReader* const r = format.createReaderFor (in, true);
  13582. if (r != 0)
  13583. {
  13584. sample += r->lengthInSamples;
  13585. delete r;
  13586. }
  13587. }
  13588. }
  13589. trackStartSamples.add (sample);
  13590. lengthInSamples = sample;
  13591. }
  13592. bool AudioCDReader::read (int** destSamples,
  13593. int64 startSampleInFile,
  13594. int numSamples)
  13595. {
  13596. while (numSamples > 0)
  13597. {
  13598. int track = -1;
  13599. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  13600. {
  13601. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  13602. {
  13603. track = i;
  13604. break;
  13605. }
  13606. }
  13607. if (track < 0)
  13608. return false;
  13609. if (track != currentReaderTrack)
  13610. {
  13611. deleteAndZero (reader);
  13612. if (tracks [track] != 0)
  13613. {
  13614. FileInputStream* const in = tracks [track]->createInputStream();
  13615. if (in != 0)
  13616. {
  13617. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  13618. AiffAudioFormat format;
  13619. reader = format.createReaderFor (bin, true);
  13620. if (reader == 0)
  13621. currentReaderTrack = -1;
  13622. else
  13623. currentReaderTrack = track;
  13624. }
  13625. }
  13626. }
  13627. if (reader == 0)
  13628. return false;
  13629. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  13630. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  13631. reader->read (destSamples, startPos, numAvailable);
  13632. numSamples -= numAvailable;
  13633. startSampleInFile += numAvailable;
  13634. }
  13635. return true;
  13636. }
  13637. bool AudioCDReader::isCDStillPresent() const
  13638. {
  13639. return volumeDir.exists();
  13640. }
  13641. int AudioCDReader::getNumTracks() const
  13642. {
  13643. return tracks.size();
  13644. }
  13645. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  13646. {
  13647. return trackStartSamples [trackNum];
  13648. }
  13649. bool AudioCDReader::isTrackAudio (int trackNum) const
  13650. {
  13651. return tracks [trackNum] != 0;
  13652. }
  13653. void AudioCDReader::enableIndexScanning (bool b)
  13654. {
  13655. // any way to do this on a Mac??
  13656. }
  13657. int AudioCDReader::getLastIndex() const
  13658. {
  13659. return 0;
  13660. }
  13661. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  13662. {
  13663. return Array <int>();
  13664. }
  13665. int AudioCDReader::getCDDBId()
  13666. {
  13667. return 0; //xxx
  13668. }
  13669. #endif
  13670. END_JUCE_NAMESPACE
  13671. /********* End of inlined file: juce_AudioCDReader.cpp *********/
  13672. /********* Start of inlined file: juce_AudioFormat.cpp *********/
  13673. BEGIN_JUCE_NAMESPACE
  13674. AudioFormatReader::AudioFormatReader (InputStream* const in,
  13675. const String& formatName_)
  13676. : sampleRate (0),
  13677. bitsPerSample (0),
  13678. lengthInSamples (0),
  13679. numChannels (0),
  13680. usesFloatingPointData (false),
  13681. input (in),
  13682. formatName (formatName_)
  13683. {
  13684. }
  13685. AudioFormatReader::~AudioFormatReader()
  13686. {
  13687. delete input;
  13688. }
  13689. static void findMaxMin (const float* src, const int num,
  13690. float& maxVal, float& minVal)
  13691. {
  13692. float mn = src[0];
  13693. float mx = mn;
  13694. for (int i = 1; i < num; ++i)
  13695. {
  13696. const float s = src[i];
  13697. if (s > mx)
  13698. mx = s;
  13699. if (s < mn)
  13700. mn = s;
  13701. }
  13702. maxVal = mx;
  13703. minVal = mn;
  13704. }
  13705. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  13706. int64 numSamples,
  13707. float& lowestLeft, float& highestLeft,
  13708. float& lowestRight, float& highestRight)
  13709. {
  13710. if (numSamples <= 0)
  13711. {
  13712. lowestLeft = 0;
  13713. lowestRight = 0;
  13714. highestLeft = 0;
  13715. highestRight = 0;
  13716. return;
  13717. }
  13718. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  13719. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  13720. int* tempBuffer[3];
  13721. tempBuffer[0] = (int*) tempSpace.getData();
  13722. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  13723. tempBuffer[2] = 0;
  13724. if (usesFloatingPointData)
  13725. {
  13726. float lmin = 1.0e6;
  13727. float lmax = -lmin;
  13728. float rmin = lmin;
  13729. float rmax = lmax;
  13730. while (numSamples > 0)
  13731. {
  13732. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  13733. read ((int**) tempBuffer, startSampleInFile, numToDo);
  13734. numSamples -= numToDo;
  13735. float bufmin, bufmax;
  13736. findMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  13737. lmin = jmin (lmin, bufmin);
  13738. lmax = jmax (lmax, bufmax);
  13739. if (numChannels > 1)
  13740. {
  13741. findMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  13742. rmin = jmin (rmin, bufmin);
  13743. rmax = jmax (rmax, bufmax);
  13744. }
  13745. }
  13746. if (numChannels <= 1)
  13747. {
  13748. rmax = lmax;
  13749. rmin = lmin;
  13750. }
  13751. lowestLeft = lmin;
  13752. highestLeft = lmax;
  13753. lowestRight = rmin;
  13754. highestRight = rmax;
  13755. }
  13756. else
  13757. {
  13758. int lmax = INT_MIN;
  13759. int lmin = INT_MAX;
  13760. int rmax = INT_MIN;
  13761. int rmin = INT_MAX;
  13762. while (numSamples > 0)
  13763. {
  13764. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  13765. read ((int**) tempBuffer, startSampleInFile, numToDo);
  13766. numSamples -= numToDo;
  13767. for (int j = numChannels; --j >= 0;)
  13768. {
  13769. int bufMax = INT_MIN;
  13770. int bufMin = INT_MAX;
  13771. const int* const b = tempBuffer[j];
  13772. for (int i = 0; i < numToDo; ++i)
  13773. {
  13774. const int samp = b[i];
  13775. if (samp < bufMin)
  13776. bufMin = samp;
  13777. if (samp > bufMax)
  13778. bufMax = samp;
  13779. }
  13780. if (j == 0)
  13781. {
  13782. lmax = jmax (lmax, bufMax);
  13783. lmin = jmin (lmin, bufMin);
  13784. }
  13785. else
  13786. {
  13787. rmax = jmax (rmax, bufMax);
  13788. rmin = jmin (rmin, bufMin);
  13789. }
  13790. }
  13791. }
  13792. if (numChannels <= 1)
  13793. {
  13794. rmax = lmax;
  13795. rmin = lmin;
  13796. }
  13797. lowestLeft = lmin / (float)INT_MAX;
  13798. highestLeft = lmax / (float)INT_MAX;
  13799. lowestRight = rmin / (float)INT_MAX;
  13800. highestRight = rmax / (float)INT_MAX;
  13801. }
  13802. }
  13803. int64 AudioFormatReader::searchForLevel (int64 startSample,
  13804. int64 numSamplesToSearch,
  13805. const double magnitudeRangeMinimum,
  13806. const double magnitudeRangeMaximum,
  13807. const int minimumConsecutiveSamples)
  13808. {
  13809. if (numSamplesToSearch == 0)
  13810. return -1;
  13811. const int bufferSize = 4096;
  13812. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  13813. int* tempBuffer[3];
  13814. tempBuffer[0] = (int*) tempSpace.getData();
  13815. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  13816. tempBuffer[2] = 0;
  13817. int consecutive = 0;
  13818. int64 firstMatchPos = -1;
  13819. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  13820. const double doubleMin = jlimit (0.0, (double) INT_MAX, magnitudeRangeMinimum * INT_MAX);
  13821. const double doubleMax = jlimit (doubleMin, (double) INT_MAX, magnitudeRangeMaximum * INT_MAX);
  13822. const int intMagnitudeRangeMinimum = roundDoubleToInt (doubleMin);
  13823. const int intMagnitudeRangeMaximum = roundDoubleToInt (doubleMax);
  13824. while (numSamplesToSearch != 0)
  13825. {
  13826. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  13827. int64 bufferStart = startSample;
  13828. if (numSamplesToSearch < 0)
  13829. bufferStart -= numThisTime;
  13830. if (bufferStart >= (int) lengthInSamples)
  13831. break;
  13832. read ((int**) tempBuffer, bufferStart, numThisTime);
  13833. int num = numThisTime;
  13834. while (--num >= 0)
  13835. {
  13836. if (numSamplesToSearch < 0)
  13837. --startSample;
  13838. bool matches = false;
  13839. const int index = (int) (startSample - bufferStart);
  13840. if (usesFloatingPointData)
  13841. {
  13842. const float sample1 = fabsf (((float*) tempBuffer[0]) [index]);
  13843. if (sample1 >= magnitudeRangeMinimum
  13844. && sample1 <= magnitudeRangeMaximum)
  13845. {
  13846. matches = true;
  13847. }
  13848. else if (numChannels > 1)
  13849. {
  13850. const float sample2 = fabsf (((float*) tempBuffer[1]) [index]);
  13851. matches = (sample2 >= magnitudeRangeMinimum
  13852. && sample2 <= magnitudeRangeMaximum);
  13853. }
  13854. }
  13855. else
  13856. {
  13857. const int sample1 = abs (tempBuffer[0] [index]);
  13858. if (sample1 >= intMagnitudeRangeMinimum
  13859. && sample1 <= intMagnitudeRangeMaximum)
  13860. {
  13861. matches = true;
  13862. }
  13863. else if (numChannels > 1)
  13864. {
  13865. const int sample2 = abs (tempBuffer[1][index]);
  13866. matches = (sample2 >= intMagnitudeRangeMinimum
  13867. && sample2 <= intMagnitudeRangeMaximum);
  13868. }
  13869. }
  13870. if (matches)
  13871. {
  13872. if (firstMatchPos < 0)
  13873. firstMatchPos = startSample;
  13874. if (++consecutive >= minimumConsecutiveSamples)
  13875. {
  13876. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  13877. return -1;
  13878. return firstMatchPos;
  13879. }
  13880. }
  13881. else
  13882. {
  13883. consecutive = 0;
  13884. firstMatchPos = -1;
  13885. }
  13886. if (numSamplesToSearch > 0)
  13887. ++startSample;
  13888. }
  13889. if (numSamplesToSearch > 0)
  13890. numSamplesToSearch -= numThisTime;
  13891. else
  13892. numSamplesToSearch += numThisTime;
  13893. }
  13894. return -1;
  13895. }
  13896. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  13897. const String& formatName_,
  13898. const double rate,
  13899. const unsigned int numChannels_,
  13900. const unsigned int bitsPerSample_)
  13901. : sampleRate (rate),
  13902. numChannels (numChannels_),
  13903. bitsPerSample (bitsPerSample_),
  13904. usesFloatingPointData (false),
  13905. output (out),
  13906. formatName (formatName_)
  13907. {
  13908. }
  13909. AudioFormatWriter::~AudioFormatWriter()
  13910. {
  13911. delete output;
  13912. }
  13913. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  13914. int64 startSample,
  13915. int numSamplesToRead)
  13916. {
  13917. const int bufferSize = 16384;
  13918. const int maxChans = 128;
  13919. AudioSampleBuffer tempBuffer (reader.numChannels, bufferSize);
  13920. int* buffers [maxChans];
  13921. for (int i = maxChans; --i >= 0;)
  13922. buffers[i] = 0;
  13923. while (numSamplesToRead > 0)
  13924. {
  13925. const int numToDo = jmin (numSamplesToRead, bufferSize);
  13926. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  13927. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  13928. if (! reader.read (buffers, startSample, numToDo))
  13929. return false;
  13930. if (reader.usesFloatingPointData != isFloatingPoint())
  13931. {
  13932. int** bufferChan = buffers;
  13933. while (*bufferChan != 0)
  13934. {
  13935. int* b = *bufferChan++;
  13936. if (isFloatingPoint())
  13937. {
  13938. // int -> float
  13939. const double factor = 1.0 / INT_MAX;
  13940. for (int i = 0; i < numToDo; ++i)
  13941. ((float*)b)[i] = (float) (factor * b[i]);
  13942. }
  13943. else
  13944. {
  13945. // float -> int
  13946. for (int i = 0; i < numToDo; ++i)
  13947. {
  13948. const double samp = *(const float*) b;
  13949. if (samp <= -1.0)
  13950. *b++ = INT_MIN;
  13951. else if (samp >= 1.0)
  13952. *b++ = INT_MAX;
  13953. else
  13954. *b++ = roundDoubleToInt (INT_MAX * samp);
  13955. }
  13956. }
  13957. }
  13958. }
  13959. if (! write ((const int**) buffers, numToDo))
  13960. return false;
  13961. numSamplesToRead -= numToDo;
  13962. startSample += numToDo;
  13963. }
  13964. return true;
  13965. }
  13966. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  13967. int numSamplesToRead,
  13968. const int samplesPerBlock)
  13969. {
  13970. const int maxChans = 128;
  13971. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  13972. int* buffers [maxChans];
  13973. while (numSamplesToRead > 0)
  13974. {
  13975. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  13976. AudioSourceChannelInfo info;
  13977. info.buffer = &tempBuffer;
  13978. info.startSample = 0;
  13979. info.numSamples = numToDo;
  13980. info.clearActiveBufferRegion();
  13981. source.getNextAudioBlock (info);
  13982. int i;
  13983. for (i = maxChans; --i >= 0;)
  13984. buffers[i] = 0;
  13985. for (i = tempBuffer.getNumChannels(); --i >= 0;)
  13986. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  13987. if (! isFloatingPoint())
  13988. {
  13989. int** bufferChan = buffers;
  13990. while (*bufferChan != 0)
  13991. {
  13992. int* b = *bufferChan++;
  13993. // float -> int
  13994. for (int j = numToDo; --j >= 0;)
  13995. {
  13996. const double samp = *(const float*) b;
  13997. if (samp <= -1.0)
  13998. *b++ = INT_MIN;
  13999. else if (samp >= 1.0)
  14000. *b++ = INT_MAX;
  14001. else
  14002. *b++ = roundDoubleToInt (INT_MAX * samp);
  14003. }
  14004. }
  14005. }
  14006. if (! write ((const int**) buffers, numToDo))
  14007. return false;
  14008. numSamplesToRead -= numToDo;
  14009. }
  14010. return true;
  14011. }
  14012. AudioFormat::AudioFormat (const String& name,
  14013. const tchar** const extensions)
  14014. : formatName (name),
  14015. fileExtensions (extensions)
  14016. {
  14017. }
  14018. AudioFormat::~AudioFormat()
  14019. {
  14020. }
  14021. const String& AudioFormat::getFormatName() const
  14022. {
  14023. return formatName;
  14024. }
  14025. const StringArray& AudioFormat::getFileExtensions() const
  14026. {
  14027. return fileExtensions;
  14028. }
  14029. bool AudioFormat::canHandleFile (const File& f)
  14030. {
  14031. for (int i = 0; i < fileExtensions.size(); ++i)
  14032. if (f.hasFileExtension (fileExtensions[i]))
  14033. return true;
  14034. return false;
  14035. }
  14036. bool AudioFormat::isCompressed()
  14037. {
  14038. return false;
  14039. }
  14040. const StringArray AudioFormat::getQualityOptions()
  14041. {
  14042. return StringArray();
  14043. }
  14044. END_JUCE_NAMESPACE
  14045. /********* End of inlined file: juce_AudioFormat.cpp *********/
  14046. /********* Start of inlined file: juce_AudioFormatManager.cpp *********/
  14047. BEGIN_JUCE_NAMESPACE
  14048. AudioFormatManager::AudioFormatManager()
  14049. : knownFormats (4),
  14050. defaultFormatIndex (0)
  14051. {
  14052. }
  14053. AudioFormatManager::~AudioFormatManager()
  14054. {
  14055. clearFormats();
  14056. clearSingletonInstance();
  14057. }
  14058. juce_ImplementSingleton (AudioFormatManager);
  14059. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  14060. const bool makeThisTheDefaultFormat)
  14061. {
  14062. jassert (newFormat != 0);
  14063. if (newFormat != 0)
  14064. {
  14065. #ifdef JUCE_DEBUG
  14066. for (int i = getNumKnownFormats(); --i >= 0;)
  14067. {
  14068. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  14069. {
  14070. jassertfalse // trying to add the same format twice!
  14071. }
  14072. }
  14073. #endif
  14074. if (makeThisTheDefaultFormat)
  14075. defaultFormatIndex = knownFormats.size();
  14076. knownFormats.add (newFormat);
  14077. }
  14078. }
  14079. void AudioFormatManager::registerBasicFormats()
  14080. {
  14081. #if JUCE_MAC
  14082. registerFormat (new AiffAudioFormat(), true);
  14083. registerFormat (new WavAudioFormat(), false);
  14084. #else
  14085. registerFormat (new WavAudioFormat(), true);
  14086. registerFormat (new AiffAudioFormat(), false);
  14087. #endif
  14088. #if JUCE_USE_FLAC
  14089. registerFormat (new FlacAudioFormat(), false);
  14090. #endif
  14091. #if JUCE_USE_OGGVORBIS
  14092. registerFormat (new OggVorbisAudioFormat(), false);
  14093. #endif
  14094. }
  14095. void AudioFormatManager::clearFormats()
  14096. {
  14097. for (int i = getNumKnownFormats(); --i >= 0;)
  14098. {
  14099. AudioFormat* const af = getKnownFormat(i);
  14100. delete af;
  14101. }
  14102. knownFormats.clear();
  14103. defaultFormatIndex = 0;
  14104. }
  14105. int AudioFormatManager::getNumKnownFormats() const
  14106. {
  14107. return knownFormats.size();
  14108. }
  14109. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  14110. {
  14111. return (AudioFormat*) knownFormats [index];
  14112. }
  14113. AudioFormat* AudioFormatManager::getDefaultFormat() const
  14114. {
  14115. return getKnownFormat (defaultFormatIndex);
  14116. }
  14117. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  14118. {
  14119. String e (fileExtension);
  14120. if (! e.startsWithChar (T('.')))
  14121. e = T(".") + e;
  14122. for (int i = 0; i < getNumKnownFormats(); ++i)
  14123. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  14124. return getKnownFormat(i);
  14125. return 0;
  14126. }
  14127. const String AudioFormatManager::getWildcardForAllFormats() const
  14128. {
  14129. StringArray allExtensions;
  14130. int i;
  14131. for (i = 0; i < getNumKnownFormats(); ++i)
  14132. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  14133. allExtensions.trim();
  14134. allExtensions.removeEmptyStrings();
  14135. String s;
  14136. for (i = 0; i < allExtensions.size(); ++i)
  14137. {
  14138. s << T('*');
  14139. if (! allExtensions[i].startsWithChar (T('.')))
  14140. s << T('.');
  14141. s << allExtensions[i];
  14142. if (i < allExtensions.size() - 1)
  14143. s << T(';');
  14144. }
  14145. return s;
  14146. }
  14147. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  14148. {
  14149. // you need to actually register some formats before the manager can
  14150. // use them to open a file!
  14151. jassert (knownFormats.size() > 0);
  14152. for (int i = 0; i < getNumKnownFormats(); ++i)
  14153. {
  14154. AudioFormat* const af = getKnownFormat(i);
  14155. if (af->canHandleFile (file))
  14156. {
  14157. InputStream* const in = file.createInputStream();
  14158. if (in != 0)
  14159. {
  14160. AudioFormatReader* const r = af->createReaderFor (in, true);
  14161. if (r != 0)
  14162. return r;
  14163. }
  14164. }
  14165. }
  14166. return 0;
  14167. }
  14168. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* in)
  14169. {
  14170. // you need to actually register some formats before the manager can
  14171. // use them to open a file!
  14172. jassert (knownFormats.size() > 0);
  14173. if (in != 0)
  14174. {
  14175. const int64 originalStreamPos = in->getPosition();
  14176. for (int i = 0; i < getNumKnownFormats(); ++i)
  14177. {
  14178. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  14179. if (r != 0)
  14180. return r;
  14181. in->setPosition (originalStreamPos);
  14182. // the stream that is passed-in must be capable of being repositioned so
  14183. // that all the formats can have a go at opening it.
  14184. jassert (in->getPosition() == originalStreamPos);
  14185. }
  14186. delete in;
  14187. }
  14188. return 0;
  14189. }
  14190. END_JUCE_NAMESPACE
  14191. /********* End of inlined file: juce_AudioFormatManager.cpp *********/
  14192. /********* Start of inlined file: juce_AudioSubsectionReader.cpp *********/
  14193. BEGIN_JUCE_NAMESPACE
  14194. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  14195. const int64 startSample_,
  14196. const int64 length_,
  14197. const bool deleteSourceWhenDeleted_)
  14198. : AudioFormatReader (0, source_->getFormatName()),
  14199. source (source_),
  14200. startSample (startSample_),
  14201. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  14202. {
  14203. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  14204. sampleRate = source->sampleRate;
  14205. bitsPerSample = source->bitsPerSample;
  14206. lengthInSamples = length;
  14207. numChannels = source->numChannels;
  14208. usesFloatingPointData = source->usesFloatingPointData;
  14209. }
  14210. AudioSubsectionReader::~AudioSubsectionReader()
  14211. {
  14212. if (deleteSourceWhenDeleted)
  14213. delete source;
  14214. }
  14215. bool AudioSubsectionReader::read (int** destSamples,
  14216. int64 startSampleInFile,
  14217. int numSamples)
  14218. {
  14219. if (startSampleInFile < 0 || startSampleInFile + numSamples > length)
  14220. {
  14221. int** d = destSamples;
  14222. while (*d != 0)
  14223. {
  14224. zeromem (*d, sizeof (int) * numSamples);
  14225. ++d;
  14226. }
  14227. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  14228. numSamples = jmax (0, jmin (numSamples, (int) (length - startSampleInFile)));
  14229. }
  14230. return source->read (destSamples,
  14231. startSampleInFile + startSample,
  14232. numSamples);
  14233. }
  14234. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  14235. int64 numSamples,
  14236. float& lowestLeft,
  14237. float& highestLeft,
  14238. float& lowestRight,
  14239. float& highestRight)
  14240. {
  14241. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  14242. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  14243. source->readMaxLevels (startSampleInFile + startSample,
  14244. numSamples,
  14245. lowestLeft,
  14246. highestLeft,
  14247. lowestRight,
  14248. highestRight);
  14249. }
  14250. END_JUCE_NAMESPACE
  14251. /********* End of inlined file: juce_AudioSubsectionReader.cpp *********/
  14252. /********* Start of inlined file: juce_AudioThumbnail.cpp *********/
  14253. BEGIN_JUCE_NAMESPACE
  14254. const int timeBeforeDeletingReader = 2000;
  14255. struct AudioThumbnailDataFormat
  14256. {
  14257. char thumbnailMagic[4];
  14258. int samplesPerThumbSample;
  14259. int64 totalSamples; // source samples
  14260. int64 numFinishedSamples; // source samples
  14261. int numThumbnailSamples;
  14262. int numChannels;
  14263. int sampleRate;
  14264. char future[16];
  14265. char data[1];
  14266. };
  14267. #if JUCE_BIG_ENDIAN
  14268. static void swap (int& n) { n = (int) swapByteOrder ((uint32) n); }
  14269. static void swap (int64& n) { n = (int64) swapByteOrder ((uint64) n); }
  14270. #endif
  14271. static void swapEndiannessIfNeeded (AudioThumbnailDataFormat* const d)
  14272. {
  14273. (void) d;
  14274. #if JUCE_BIG_ENDIAN
  14275. swap (d->samplesPerThumbSample);
  14276. swap (d->totalSamples);
  14277. swap (d->numFinishedSamples);
  14278. swap (d->numThumbnailSamples);
  14279. swap (d->numChannels);
  14280. swap (d->sampleRate);
  14281. #endif
  14282. }
  14283. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  14284. AudioFormatManager& formatManagerToUse_,
  14285. AudioThumbnailCache& cacheToUse)
  14286. : formatManagerToUse (formatManagerToUse_),
  14287. cache (cacheToUse),
  14288. source (0),
  14289. reader (0),
  14290. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  14291. {
  14292. clear();
  14293. }
  14294. AudioThumbnail::~AudioThumbnail()
  14295. {
  14296. cache.removeThumbnail (this);
  14297. const ScopedLock sl (readerLock);
  14298. deleteAndZero (reader);
  14299. delete source;
  14300. }
  14301. void AudioThumbnail::setSource (InputSource* const newSource)
  14302. {
  14303. cache.removeThumbnail (this);
  14304. timerCallback(); // stops the timer and deletes the reader
  14305. delete source;
  14306. source = newSource;
  14307. clear();
  14308. if (! (cache.loadThumb (*this, newSource->hashCode())
  14309. && isFullyLoaded()))
  14310. {
  14311. {
  14312. const ScopedLock sl (readerLock);
  14313. reader = createReader();
  14314. }
  14315. if (reader != 0)
  14316. {
  14317. initialiseFromAudioFile (*reader);
  14318. cache.addThumbnail (this);
  14319. }
  14320. }
  14321. sendChangeMessage (this);
  14322. }
  14323. bool AudioThumbnail::useTimeSlice()
  14324. {
  14325. const ScopedLock sl (readerLock);
  14326. if (isFullyLoaded())
  14327. {
  14328. if (reader != 0)
  14329. startTimer (timeBeforeDeletingReader);
  14330. cache.removeThumbnail (this);
  14331. return false;
  14332. }
  14333. if (reader == 0)
  14334. reader = createReader();
  14335. if (reader != 0)
  14336. {
  14337. readNextBlockFromAudioFile (*reader);
  14338. stopTimer();
  14339. sendChangeMessage (this);
  14340. const bool justFinished = isFullyLoaded();
  14341. if (justFinished)
  14342. cache.storeThumb (*this, source->hashCode());
  14343. return ! justFinished;
  14344. }
  14345. return false;
  14346. }
  14347. AudioFormatReader* AudioThumbnail::createReader() const
  14348. {
  14349. if (source != 0)
  14350. {
  14351. InputStream* const audioFileStream = source->createInputStream();
  14352. if (audioFileStream != 0)
  14353. return formatManagerToUse.createReaderFor (audioFileStream);
  14354. }
  14355. return 0;
  14356. }
  14357. void AudioThumbnail::timerCallback()
  14358. {
  14359. stopTimer();
  14360. const ScopedLock sl (readerLock);
  14361. deleteAndZero (reader);
  14362. }
  14363. void AudioThumbnail::clear()
  14364. {
  14365. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  14366. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14367. d->thumbnailMagic[0] = 'j';
  14368. d->thumbnailMagic[1] = 'a';
  14369. d->thumbnailMagic[2] = 't';
  14370. d->thumbnailMagic[3] = 'm';
  14371. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  14372. d->totalSamples = 0;
  14373. d->numFinishedSamples = 0;
  14374. d->numThumbnailSamples = 0;
  14375. d->numChannels = 0;
  14376. d->sampleRate = 0;
  14377. numSamplesCached = 0;
  14378. cacheNeedsRefilling = true;
  14379. }
  14380. void AudioThumbnail::loadFrom (InputStream& input)
  14381. {
  14382. data.setSize (0);
  14383. input.readIntoMemoryBlock (data);
  14384. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14385. swapEndiannessIfNeeded (d);
  14386. if (! (d->thumbnailMagic[0] == 'j'
  14387. && d->thumbnailMagic[1] == 'a'
  14388. && d->thumbnailMagic[2] == 't'
  14389. && d->thumbnailMagic[3] == 'm'))
  14390. {
  14391. clear();
  14392. }
  14393. numSamplesCached = 0;
  14394. cacheNeedsRefilling = true;
  14395. }
  14396. void AudioThumbnail::saveTo (OutputStream& output) const
  14397. {
  14398. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14399. swapEndiannessIfNeeded (d);
  14400. output.write (data.getData(), data.getSize());
  14401. swapEndiannessIfNeeded (d);
  14402. }
  14403. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& reader)
  14404. {
  14405. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  14406. d->totalSamples = reader.lengthInSamples;
  14407. d->numChannels = jmin (2, reader.numChannels);
  14408. d->numFinishedSamples = 0;
  14409. d->sampleRate = roundDoubleToInt (reader.sampleRate);
  14410. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  14411. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  14412. d = (AudioThumbnailDataFormat*) data.getData();
  14413. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  14414. return d->totalSamples > 0;
  14415. }
  14416. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& reader)
  14417. {
  14418. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14419. if (d->numFinishedSamples < d->totalSamples)
  14420. {
  14421. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  14422. generateSection (reader,
  14423. d->numFinishedSamples,
  14424. numToDo);
  14425. d->numFinishedSamples += numToDo;
  14426. }
  14427. cacheNeedsRefilling = true;
  14428. return (d->numFinishedSamples < d->totalSamples);
  14429. }
  14430. int AudioThumbnail::getNumChannels() const throw()
  14431. {
  14432. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14433. jassert (d != 0);
  14434. return d->numChannels;
  14435. }
  14436. double AudioThumbnail::getTotalLength() const throw()
  14437. {
  14438. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14439. jassert (d != 0);
  14440. if (d->sampleRate > 0)
  14441. return d->totalSamples / (double)d->sampleRate;
  14442. else
  14443. return 0.0;
  14444. }
  14445. void AudioThumbnail::generateSection (AudioFormatReader& reader,
  14446. int64 startSample,
  14447. int numSamples)
  14448. {
  14449. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14450. jassert (d != 0);
  14451. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  14452. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  14453. char* l = getChannelData (0);
  14454. char* r = getChannelData (1);
  14455. for (int i = firstDataPos; i < lastDataPos; ++i)
  14456. {
  14457. const int sourceStart = i * d->samplesPerThumbSample;
  14458. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  14459. float lowestLeft, highestLeft, lowestRight, highestRight;
  14460. reader.readMaxLevels (sourceStart,
  14461. sourceEnd - sourceStart,
  14462. lowestLeft,
  14463. highestLeft,
  14464. lowestRight,
  14465. highestRight);
  14466. int n = i * 2;
  14467. if (r != 0)
  14468. {
  14469. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  14470. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  14471. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  14472. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  14473. }
  14474. else
  14475. {
  14476. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  14477. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  14478. }
  14479. }
  14480. }
  14481. char* AudioThumbnail::getChannelData (int channel) const
  14482. {
  14483. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14484. jassert (d != 0);
  14485. if (channel >= 0 && channel < d->numChannels)
  14486. return d->data + (channel * 2 * d->numThumbnailSamples);
  14487. return 0;
  14488. }
  14489. bool AudioThumbnail::isFullyLoaded() const throw()
  14490. {
  14491. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14492. jassert (d != 0);
  14493. return d->numFinishedSamples >= d->totalSamples;
  14494. }
  14495. void AudioThumbnail::refillCache (const int numSamples,
  14496. double startTime,
  14497. const double timePerPixel)
  14498. {
  14499. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14500. jassert (d != 0);
  14501. if (numSamples <= 0
  14502. || timePerPixel <= 0.0
  14503. || d->sampleRate <= 0)
  14504. {
  14505. numSamplesCached = 0;
  14506. cacheNeedsRefilling = true;
  14507. return;
  14508. }
  14509. if (numSamples == numSamplesCached
  14510. && numChannelsCached == d->numChannels
  14511. && startTime == cachedStart
  14512. && timePerPixel == cachedTimePerPixel
  14513. && ! cacheNeedsRefilling)
  14514. {
  14515. return;
  14516. }
  14517. numSamplesCached = numSamples;
  14518. numChannelsCached = d->numChannels;
  14519. cachedStart = startTime;
  14520. cachedTimePerPixel = timePerPixel;
  14521. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  14522. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  14523. const ScopedLock sl (readerLock);
  14524. cacheNeedsRefilling = false;
  14525. if (needExtraDetail && reader == 0)
  14526. reader = createReader();
  14527. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  14528. {
  14529. startTimer (timeBeforeDeletingReader);
  14530. char* cacheData = (char*) cachedLevels.getData();
  14531. int sample = roundDoubleToInt (startTime * d->sampleRate);
  14532. for (int i = numSamples; --i >= 0;)
  14533. {
  14534. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * d->sampleRate);
  14535. if (sample >= 0)
  14536. {
  14537. if (sample >= reader->lengthInSamples)
  14538. break;
  14539. float lmin, lmax, rmin, rmax;
  14540. reader->readMaxLevels (sample,
  14541. jmax (1, nextSample - sample),
  14542. lmin, lmax, rmin, rmax);
  14543. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  14544. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  14545. if (numChannelsCached > 1)
  14546. {
  14547. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  14548. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  14549. }
  14550. cacheData += 2 * numChannelsCached;
  14551. }
  14552. startTime += timePerPixel;
  14553. sample = nextSample;
  14554. }
  14555. }
  14556. else
  14557. {
  14558. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  14559. {
  14560. char* const data = getChannelData (channelNum);
  14561. char* cacheData = ((char*) cachedLevels.getData()) + channelNum * 2;
  14562. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  14563. startTime = cachedStart;
  14564. int sample = roundDoubleToInt (startTime * timeToThumbSampleFactor);
  14565. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  14566. for (int i = numSamples; --i >= 0;)
  14567. {
  14568. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  14569. if (sample >= 0 && data != 0)
  14570. {
  14571. char mx = -128;
  14572. char mn = 127;
  14573. while (sample <= nextSample)
  14574. {
  14575. if (sample >= numFinished)
  14576. break;
  14577. const int n = sample << 1;
  14578. const char sampMin = data [n];
  14579. const char sampMax = data [n + 1];
  14580. if (sampMin < mn)
  14581. mn = sampMin;
  14582. if (sampMax > mx)
  14583. mx = sampMax;
  14584. ++sample;
  14585. }
  14586. if (mn <= mx)
  14587. {
  14588. cacheData[0] = mn;
  14589. cacheData[1] = mx;
  14590. }
  14591. else
  14592. {
  14593. cacheData[0] = 1;
  14594. cacheData[1] = 0;
  14595. }
  14596. }
  14597. else
  14598. {
  14599. cacheData[0] = 1;
  14600. cacheData[1] = 0;
  14601. }
  14602. cacheData += numChannelsCached * 2;
  14603. startTime += timePerPixel;
  14604. sample = nextSample;
  14605. }
  14606. }
  14607. }
  14608. }
  14609. void AudioThumbnail::drawChannel (Graphics& g,
  14610. int x, int y, int w, int h,
  14611. double startTime,
  14612. double endTime,
  14613. int channelNum,
  14614. const float verticalZoomFactor)
  14615. {
  14616. refillCache (w, startTime, (endTime - startTime) / w);
  14617. if (numSamplesCached >= w
  14618. && channelNum >= 0
  14619. && channelNum < numChannelsCached)
  14620. {
  14621. const float topY = (float) y;
  14622. const float bottomY = topY + h;
  14623. const float midY = topY + h * 0.5f;
  14624. const float vscale = verticalZoomFactor * h / 256.0f;
  14625. const Rectangle clip (g.getClipBounds());
  14626. const int skipLeft = clip.getX() - x;
  14627. w -= skipLeft;
  14628. x += skipLeft;
  14629. const char* cacheData = ((const char*) cachedLevels.getData())
  14630. + (channelNum << 1)
  14631. + skipLeft * (numChannelsCached << 1);
  14632. while (--w >= 0)
  14633. {
  14634. const char mn = cacheData[0];
  14635. const char mx = cacheData[1];
  14636. cacheData += numChannelsCached << 1;
  14637. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  14638. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  14639. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  14640. ++x;
  14641. if (x >= clip.getRight())
  14642. break;
  14643. }
  14644. }
  14645. }
  14646. END_JUCE_NAMESPACE
  14647. /********* End of inlined file: juce_AudioThumbnail.cpp *********/
  14648. /********* Start of inlined file: juce_AudioThumbnailCache.cpp *********/
  14649. BEGIN_JUCE_NAMESPACE
  14650. struct ThumbnailCacheEntry
  14651. {
  14652. int64 hash;
  14653. uint32 lastUsed;
  14654. MemoryBlock data;
  14655. juce_UseDebuggingNewOperator
  14656. };
  14657. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  14658. : TimeSliceThread (T("thumb cache")),
  14659. maxNumThumbsToStore (maxNumThumbsToStore_)
  14660. {
  14661. startThread (2);
  14662. }
  14663. AudioThumbnailCache::~AudioThumbnailCache()
  14664. {
  14665. }
  14666. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  14667. {
  14668. for (int i = thumbs.size(); --i >= 0;)
  14669. {
  14670. if (thumbs[i]->hash == hashCode)
  14671. {
  14672. MemoryInputStream in ((const char*) thumbs[i]->data.getData(),
  14673. thumbs[i]->data.getSize(),
  14674. false);
  14675. thumb.loadFrom (in);
  14676. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  14677. return true;
  14678. }
  14679. }
  14680. return false;
  14681. }
  14682. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  14683. const int64 hashCode)
  14684. {
  14685. MemoryOutputStream out;
  14686. thumb.saveTo (out);
  14687. ThumbnailCacheEntry* te = 0;
  14688. for (int i = thumbs.size(); --i >= 0;)
  14689. {
  14690. if (thumbs[i]->hash == hashCode)
  14691. {
  14692. te = thumbs[i];
  14693. break;
  14694. }
  14695. }
  14696. if (te == 0)
  14697. {
  14698. te = new ThumbnailCacheEntry();
  14699. te->hash = hashCode;
  14700. if (thumbs.size() < maxNumThumbsToStore)
  14701. {
  14702. thumbs.add (te);
  14703. }
  14704. else
  14705. {
  14706. int oldest = 0;
  14707. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  14708. int i;
  14709. for (i = thumbs.size(); --i >= 0;)
  14710. if (thumbs[i]->lastUsed < oldestTime)
  14711. oldest = i;
  14712. thumbs.set (i, te);
  14713. }
  14714. }
  14715. te->lastUsed = Time::getMillisecondCounter();
  14716. te->data.setSize (0);
  14717. te->data.append (out.getData(), out.getDataSize());
  14718. }
  14719. void AudioThumbnailCache::clear()
  14720. {
  14721. thumbs.clear();
  14722. }
  14723. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  14724. {
  14725. addTimeSliceClient (thumb);
  14726. }
  14727. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  14728. {
  14729. removeTimeSliceClient (thumb);
  14730. }
  14731. END_JUCE_NAMESPACE
  14732. /********* End of inlined file: juce_AudioThumbnailCache.cpp *********/
  14733. /********* Start of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  14734. #if JUCE_QUICKTIME
  14735. #if ! defined (_WIN32)
  14736. #include <Quicktime/Movies.h>
  14737. #include <Quicktime/QTML.h>
  14738. #include <Quicktime/QuickTimeComponents.h>
  14739. #include <Quicktime/MediaHandlers.h>
  14740. #include <Quicktime/ImageCodec.h>
  14741. #else
  14742. #ifdef _MSC_VER
  14743. #pragma warning (push)
  14744. #pragma warning (disable : 4100)
  14745. #endif
  14746. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  14747. add its header directory to your include path.
  14748. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  14749. flag in juce_Config.h
  14750. */
  14751. #include <Movies.h>
  14752. #include <QTML.h>
  14753. #include <QuickTimeComponents.h>
  14754. #include <MediaHandlers.h>
  14755. #include <ImageCodec.h>
  14756. #ifdef _MSC_VER
  14757. #pragma warning (pop)
  14758. #endif
  14759. #endif
  14760. BEGIN_JUCE_NAMESPACE
  14761. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  14762. #define quickTimeFormatName TRANS("QuickTime file")
  14763. static const tchar* const quickTimeExtensions[] = { T(".mov"), T(".mp3"), T(".mp4"), 0 };
  14764. class QTAudioReader : public AudioFormatReader
  14765. {
  14766. public:
  14767. QTAudioReader (InputStream* const input_, const int trackNum_)
  14768. : AudioFormatReader (input_, quickTimeFormatName),
  14769. ok (false),
  14770. movie (0),
  14771. trackNum (trackNum_),
  14772. extractor (0),
  14773. lastSampleRead (0),
  14774. lastThreadId (0),
  14775. dataHandle (0)
  14776. {
  14777. bufferList = (AudioBufferList*) juce_calloc (256);
  14778. #ifdef WIN32
  14779. if (InitializeQTML (0) != noErr)
  14780. return;
  14781. #elif JUCE_MAC
  14782. EnterMoviesOnThread (0);
  14783. #endif
  14784. if (EnterMovies() != noErr)
  14785. return;
  14786. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  14787. if (! opened)
  14788. return;
  14789. {
  14790. const int numTracks = GetMovieTrackCount (movie);
  14791. int trackCount = 0;
  14792. for (int i = 1; i <= numTracks; ++i)
  14793. {
  14794. track = GetMovieIndTrack (movie, i);
  14795. media = GetTrackMedia (track);
  14796. OSType mediaType;
  14797. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  14798. if (mediaType == SoundMediaType
  14799. && trackCount++ == trackNum_)
  14800. {
  14801. ok = true;
  14802. break;
  14803. }
  14804. }
  14805. }
  14806. if (! ok)
  14807. return;
  14808. ok = false;
  14809. lengthInSamples = GetMediaDecodeDuration (media);
  14810. usesFloatingPointData = false;
  14811. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  14812. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  14813. / GetMediaTimeScale (media);
  14814. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  14815. unsigned long output_layout_size;
  14816. err = MovieAudioExtractionGetPropertyInfo (extractor,
  14817. kQTPropertyClass_MovieAudioExtraction_Audio,
  14818. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  14819. 0, &output_layout_size, 0);
  14820. if (err != noErr)
  14821. return;
  14822. AudioChannelLayout* const qt_audio_channel_layout
  14823. = (AudioChannelLayout*) juce_calloc (output_layout_size);
  14824. err = MovieAudioExtractionGetProperty (extractor,
  14825. kQTPropertyClass_MovieAudioExtraction_Audio,
  14826. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  14827. output_layout_size, qt_audio_channel_layout, 0);
  14828. qt_audio_channel_layout->mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  14829. err = MovieAudioExtractionSetProperty (extractor,
  14830. kQTPropertyClass_MovieAudioExtraction_Audio,
  14831. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  14832. sizeof (qt_audio_channel_layout),
  14833. qt_audio_channel_layout);
  14834. juce_free (qt_audio_channel_layout);
  14835. err = MovieAudioExtractionGetProperty (extractor,
  14836. kQTPropertyClass_MovieAudioExtraction_Audio,
  14837. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  14838. sizeof (inputStreamDesc),
  14839. &inputStreamDesc, 0);
  14840. if (err != noErr)
  14841. return;
  14842. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  14843. | kAudioFormatFlagIsPacked
  14844. | kAudioFormatFlagsNativeEndian;
  14845. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  14846. inputStreamDesc.mChannelsPerFrame = jmin (2, inputStreamDesc.mChannelsPerFrame);
  14847. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  14848. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  14849. err = MovieAudioExtractionSetProperty (extractor,
  14850. kQTPropertyClass_MovieAudioExtraction_Audio,
  14851. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  14852. sizeof (inputStreamDesc),
  14853. &inputStreamDesc);
  14854. if (err != noErr)
  14855. return;
  14856. Boolean allChannelsDiscrete = false;
  14857. err = MovieAudioExtractionSetProperty (extractor,
  14858. kQTPropertyClass_MovieAudioExtraction_Movie,
  14859. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  14860. sizeof (allChannelsDiscrete),
  14861. &allChannelsDiscrete);
  14862. if (err != noErr)
  14863. return;
  14864. bufferList->mNumberBuffers = 1;
  14865. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  14866. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  14867. bufferList->mBuffers[0].mData = malloc (bufferList->mBuffers[0].mDataByteSize);
  14868. sampleRate = inputStreamDesc.mSampleRate;
  14869. bitsPerSample = 16;
  14870. numChannels = inputStreamDesc.mChannelsPerFrame;
  14871. detachThread();
  14872. ok = true;
  14873. }
  14874. ~QTAudioReader()
  14875. {
  14876. if (dataHandle != 0)
  14877. DisposeHandle (dataHandle);
  14878. if (extractor != 0)
  14879. {
  14880. MovieAudioExtractionEnd (extractor);
  14881. extractor = 0;
  14882. }
  14883. checkThreadIsAttached();
  14884. DisposeMovie (movie);
  14885. juce_free (bufferList->mBuffers[0].mData);
  14886. juce_free (bufferList);
  14887. #if JUCE_MAC
  14888. ExitMoviesOnThread ();
  14889. #endif
  14890. }
  14891. bool read (int** destSamples,
  14892. int64 startSample,
  14893. int numSamples)
  14894. {
  14895. checkThreadIsAttached();
  14896. int done = 0;
  14897. while (numSamples > 0)
  14898. {
  14899. if (! loadFrame ((int) startSample))
  14900. return false;
  14901. const int numToDo = jmin (numSamples, samplesPerFrame);
  14902. for (unsigned int j = 0; j < inputStreamDesc.mChannelsPerFrame; ++j)
  14903. {
  14904. if (destSamples[j] != 0)
  14905. {
  14906. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  14907. for (int i = 0; i < numToDo; ++i)
  14908. destSamples[j][done + i] = src [i << 1] << 16;
  14909. }
  14910. }
  14911. done += numToDo;
  14912. startSample += numToDo;
  14913. numSamples -= numToDo;
  14914. }
  14915. detachThread();
  14916. return true;
  14917. }
  14918. bool loadFrame (const int sampleNum)
  14919. {
  14920. if (lastSampleRead != sampleNum)
  14921. {
  14922. TimeRecord time;
  14923. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  14924. time.base = 0;
  14925. time.value.hi = 0;
  14926. time.value.lo = (UInt32) sampleNum;
  14927. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  14928. kQTPropertyClass_MovieAudioExtraction_Movie,
  14929. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  14930. sizeof (time), &time);
  14931. if (err != noErr)
  14932. return false;
  14933. }
  14934. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  14935. UInt32 outFlags = 0;
  14936. UInt32 actualNumSamples = samplesPerFrame;
  14937. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  14938. bufferList, &outFlags);
  14939. lastSampleRead = sampleNum + samplesPerFrame;
  14940. return err == noErr;
  14941. }
  14942. juce_UseDebuggingNewOperator
  14943. bool ok;
  14944. private:
  14945. Movie movie;
  14946. Media media;
  14947. Track track;
  14948. const int trackNum;
  14949. double trackUnitsPerFrame;
  14950. int samplesPerFrame;
  14951. int lastSampleRead, lastThreadId;
  14952. MovieAudioExtractionRef extractor;
  14953. AudioStreamBasicDescription inputStreamDesc;
  14954. AudioBufferList* bufferList;
  14955. Handle dataHandle;
  14956. /*OSErr readMovieStream (long offset, long size, void* dataPtr)
  14957. {
  14958. input->setPosition (offset);
  14959. input->read (dataPtr, size);
  14960. return noErr;
  14961. }
  14962. static OSErr readMovieStreamProc (long offset, long size, void* dataPtr, void* userRef)
  14963. {
  14964. return ((QTAudioReader*) userRef)->readMovieStream (offset, size, dataPtr);
  14965. }*/
  14966. void checkThreadIsAttached()
  14967. {
  14968. #if JUCE_MAC
  14969. if (Thread::getCurrentThreadId() != lastThreadId)
  14970. EnterMoviesOnThread (0);
  14971. AttachMovieToCurrentThread (movie);
  14972. #endif
  14973. }
  14974. void detachThread()
  14975. {
  14976. #if JUCE_MAC
  14977. DetachMovieFromCurrentThread (movie);
  14978. #endif
  14979. }
  14980. };
  14981. QuickTimeAudioFormat::QuickTimeAudioFormat()
  14982. : AudioFormat (quickTimeFormatName, (const tchar**) quickTimeExtensions)
  14983. {
  14984. }
  14985. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  14986. {
  14987. }
  14988. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  14989. {
  14990. return Array<int>();
  14991. }
  14992. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  14993. {
  14994. return Array<int>();
  14995. }
  14996. bool QuickTimeAudioFormat::canDoStereo()
  14997. {
  14998. return true;
  14999. }
  15000. bool QuickTimeAudioFormat::canDoMono()
  15001. {
  15002. return true;
  15003. }
  15004. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  15005. const bool deleteStreamIfOpeningFails)
  15006. {
  15007. QTAudioReader* r = new QTAudioReader (sourceStream, 0);
  15008. if (! r->ok)
  15009. {
  15010. if (! deleteStreamIfOpeningFails)
  15011. r->input = 0;
  15012. deleteAndZero (r);
  15013. }
  15014. return r;
  15015. }
  15016. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  15017. double /*sampleRateToUse*/,
  15018. unsigned int /*numberOfChannels*/,
  15019. int /*bitsPerSample*/,
  15020. const StringPairArray& /*metadataValues*/,
  15021. int /*qualityOptionIndex*/)
  15022. {
  15023. jassertfalse // not yet implemented!
  15024. return 0;
  15025. }
  15026. END_JUCE_NAMESPACE
  15027. #endif
  15028. /********* End of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  15029. /********* Start of inlined file: juce_WavAudioFormat.cpp *********/
  15030. BEGIN_JUCE_NAMESPACE
  15031. #define wavFormatName TRANS("WAV file")
  15032. static const tchar* const wavExtensions[] = { T(".wav"), T(".bwf"), 0 };
  15033. const tchar* const WavAudioFormat::bwavDescription = T("bwav description");
  15034. const tchar* const WavAudioFormat::bwavOriginator = T("bwav originator");
  15035. const tchar* const WavAudioFormat::bwavOriginatorRef = T("bwav originator ref");
  15036. const tchar* const WavAudioFormat::bwavOriginationDate = T("bwav origination date");
  15037. const tchar* const WavAudioFormat::bwavOriginationTime = T("bwav origination time");
  15038. const tchar* const WavAudioFormat::bwavTimeReference = T("bwav time reference");
  15039. const tchar* const WavAudioFormat::bwavCodingHistory = T("bwav coding history");
  15040. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  15041. const String& originator,
  15042. const String& originatorRef,
  15043. const Time& date,
  15044. const int64 timeReferenceSamples,
  15045. const String& codingHistory)
  15046. {
  15047. StringPairArray m;
  15048. m.set (bwavDescription, description);
  15049. m.set (bwavOriginator, originator);
  15050. m.set (bwavOriginatorRef, originatorRef);
  15051. m.set (bwavOriginationDate, date.formatted (T("%Y-%m-%d")));
  15052. m.set (bwavOriginationTime, date.formatted (T("%H:%M:%S")));
  15053. m.set (bwavTimeReference, String (timeReferenceSamples));
  15054. m.set (bwavCodingHistory, codingHistory);
  15055. return m;
  15056. }
  15057. #if JUCE_MSVC
  15058. #pragma pack (push, 1)
  15059. #define PACKED
  15060. #elif defined (JUCE_GCC)
  15061. #define PACKED __attribute__((packed))
  15062. #else
  15063. #define PACKED
  15064. #endif
  15065. struct BWAVChunk
  15066. {
  15067. char description [256];
  15068. char originator [32];
  15069. char originatorRef [32];
  15070. char originationDate [10];
  15071. char originationTime [8];
  15072. uint32 timeRefLow;
  15073. uint32 timeRefHigh;
  15074. uint16 version;
  15075. uint8 umid[64];
  15076. uint8 reserved[190];
  15077. char codingHistory[1];
  15078. void copyTo (StringPairArray& values) const
  15079. {
  15080. values.set (WavAudioFormat::bwavDescription, String (description, 256));
  15081. values.set (WavAudioFormat::bwavOriginator, String (originator, 32));
  15082. values.set (WavAudioFormat::bwavOriginatorRef, String (originatorRef, 32));
  15083. values.set (WavAudioFormat::bwavOriginationDate, String (originationDate, 10));
  15084. values.set (WavAudioFormat::bwavOriginationTime, String (originationTime, 8));
  15085. const uint32 timeLow = swapIfBigEndian (timeRefLow);
  15086. const uint32 timeHigh = swapIfBigEndian (timeRefHigh);
  15087. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  15088. values.set (WavAudioFormat::bwavTimeReference, String (time));
  15089. values.set (WavAudioFormat::bwavCodingHistory, String (codingHistory));
  15090. }
  15091. static MemoryBlock createFrom (const StringPairArray& values)
  15092. {
  15093. const int sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].length();
  15094. MemoryBlock data ((sizeNeeded + 3) & ~3);
  15095. data.fillWith (0);
  15096. BWAVChunk* b = (BWAVChunk*) data.getData();
  15097. // although copyToBuffer may overrun by one byte, that's ok as long as these
  15098. // operations get done in the right order
  15099. values [WavAudioFormat::bwavDescription].copyToBuffer (b->description, 256);
  15100. values [WavAudioFormat::bwavOriginator].copyToBuffer (b->originator, 32);
  15101. values [WavAudioFormat::bwavOriginatorRef].copyToBuffer (b->originatorRef, 32);
  15102. values [WavAudioFormat::bwavOriginationDate].copyToBuffer (b->originationDate, 10);
  15103. values [WavAudioFormat::bwavOriginationTime].copyToBuffer (b->originationTime, 8);
  15104. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  15105. b->timeRefLow = swapIfBigEndian ((uint32) (time & 0xffffffff));
  15106. b->timeRefHigh = swapIfBigEndian ((uint32) (time >> 32));
  15107. values [WavAudioFormat::bwavCodingHistory].copyToBuffer (b->codingHistory, 256 * 1024);
  15108. if (b->description[0] != 0
  15109. || b->originator[0] != 0
  15110. || b->originationDate[0] != 0
  15111. || b->originationTime[0] != 0
  15112. || b->codingHistory[0] != 0
  15113. || time != 0)
  15114. {
  15115. return data;
  15116. }
  15117. return MemoryBlock();
  15118. }
  15119. } PACKED;
  15120. #if JUCE_MSVC
  15121. #pragma pack (pop)
  15122. #endif
  15123. #undef PACKED
  15124. #undef chunkName
  15125. #define chunkName(a) ((int) littleEndianInt(a))
  15126. class WavAudioFormatReader : public AudioFormatReader
  15127. {
  15128. int bytesPerFrame;
  15129. int64 dataChunkStart, dataLength;
  15130. WavAudioFormatReader (const WavAudioFormatReader&);
  15131. const WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  15132. public:
  15133. WavAudioFormatReader (InputStream* const in)
  15134. : AudioFormatReader (in, wavFormatName),
  15135. dataLength (0)
  15136. {
  15137. if (input->readInt() == chunkName ("RIFF"))
  15138. {
  15139. const uint32 len = (uint32) input->readInt();
  15140. const int64 end = input->getPosition() + len;
  15141. bool hasGotType = false;
  15142. bool hasGotData = false;
  15143. if (input->readInt() == chunkName ("WAVE"))
  15144. {
  15145. while (input->getPosition() < end
  15146. && ! input->isExhausted())
  15147. {
  15148. const int chunkType = input->readInt();
  15149. uint32 length = (uint32) input->readInt();
  15150. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  15151. if (chunkType == chunkName ("fmt "))
  15152. {
  15153. // read the format chunk
  15154. const short format = input->readShort();
  15155. const short numChans = input->readShort();
  15156. sampleRate = input->readInt();
  15157. const int bytesPerSec = input->readInt();
  15158. numChannels = numChans;
  15159. bytesPerFrame = bytesPerSec / (int)sampleRate;
  15160. bitsPerSample = 8 * bytesPerFrame / numChans;
  15161. if (format == 3)
  15162. usesFloatingPointData = true;
  15163. else if (format != 1)
  15164. bytesPerFrame = 0;
  15165. hasGotType = true;
  15166. }
  15167. else if (chunkType == chunkName ("data"))
  15168. {
  15169. // get the data chunk's position
  15170. dataLength = length;
  15171. dataChunkStart = input->getPosition();
  15172. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  15173. hasGotData = true;
  15174. }
  15175. else if (chunkType == chunkName ("bext"))
  15176. {
  15177. // Broadcast-wav extension chunk..
  15178. BWAVChunk* const bwav = (BWAVChunk*) juce_calloc (jmax (length + 1, (int) sizeof (BWAVChunk)));
  15179. if (bwav != 0)
  15180. {
  15181. input->read (bwav, length);
  15182. bwav->copyTo (metadataValues);
  15183. juce_free (bwav);
  15184. }
  15185. }
  15186. else if ((hasGotType && hasGotData) || chunkEnd <= input->getPosition())
  15187. {
  15188. break;
  15189. }
  15190. input->setPosition (chunkEnd);
  15191. }
  15192. }
  15193. }
  15194. }
  15195. ~WavAudioFormatReader()
  15196. {
  15197. }
  15198. bool read (int** destSamples,
  15199. int64 startSampleInFile,
  15200. int numSamples)
  15201. {
  15202. int64 start = startSampleInFile;
  15203. int startOffsetInDestBuffer = 0;
  15204. if (startSampleInFile < 0)
  15205. {
  15206. const int silence = (int) jmin (-startSampleInFile, (int64) numSamples);
  15207. int** destChan = destSamples;
  15208. for (int i = 2; --i >= 0;)
  15209. {
  15210. if (*destChan != 0)
  15211. {
  15212. zeromem (*destChan, sizeof (int) * silence);
  15213. ++destChan;
  15214. }
  15215. }
  15216. startOffsetInDestBuffer += silence;
  15217. numSamples -= silence;
  15218. start = 0;
  15219. }
  15220. const int numToDo = (int) jlimit ((int64) 0, (int64) numSamples, lengthInSamples - start);
  15221. if (numToDo > 0)
  15222. {
  15223. input->setPosition (dataChunkStart + start * bytesPerFrame);
  15224. int num = numToDo;
  15225. int* left = destSamples[0];
  15226. if (left != 0)
  15227. left += startOffsetInDestBuffer;
  15228. int* right = destSamples[1];
  15229. if (right != 0)
  15230. right += startOffsetInDestBuffer;
  15231. // (keep this a multiple of 3)
  15232. const int tempBufSize = 1440 * 4;
  15233. char tempBuffer [tempBufSize];
  15234. while (num > 0)
  15235. {
  15236. const int numThisTime = jmin (tempBufSize / bytesPerFrame, num);
  15237. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15238. if (bytesRead < numThisTime * bytesPerFrame)
  15239. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15240. if (bitsPerSample == 16)
  15241. {
  15242. const short* src = (const short*) tempBuffer;
  15243. if (numChannels > 1)
  15244. {
  15245. if (left == 0)
  15246. {
  15247. for (int i = numThisTime; --i >= 0;)
  15248. {
  15249. ++src;
  15250. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15251. }
  15252. }
  15253. else if (right == 0)
  15254. {
  15255. for (int i = numThisTime; --i >= 0;)
  15256. {
  15257. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15258. ++src;
  15259. }
  15260. }
  15261. else
  15262. {
  15263. for (int i = numThisTime; --i >= 0;)
  15264. {
  15265. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15266. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15267. }
  15268. }
  15269. }
  15270. else
  15271. {
  15272. for (int i = numThisTime; --i >= 0;)
  15273. {
  15274. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15275. }
  15276. }
  15277. }
  15278. else if (bitsPerSample == 24)
  15279. {
  15280. const char* src = (const char*) tempBuffer;
  15281. if (numChannels > 1)
  15282. {
  15283. if (left == 0)
  15284. {
  15285. for (int i = numThisTime; --i >= 0;)
  15286. {
  15287. src += 6;
  15288. *right++ = littleEndian24Bit (src) << 8;
  15289. }
  15290. }
  15291. else if (right == 0)
  15292. {
  15293. for (int i = numThisTime; --i >= 0;)
  15294. {
  15295. *left++ = littleEndian24Bit (src) << 8;
  15296. src += 6;
  15297. }
  15298. }
  15299. else
  15300. {
  15301. for (int i = 0; i < numThisTime; ++i)
  15302. {
  15303. *left++ = littleEndian24Bit (src) << 8;
  15304. src += 3;
  15305. *right++ = littleEndian24Bit (src) << 8;
  15306. src += 3;
  15307. }
  15308. }
  15309. }
  15310. else
  15311. {
  15312. for (int i = 0; i < numThisTime; ++i)
  15313. {
  15314. *left++ = littleEndian24Bit (src) << 8;
  15315. src += 3;
  15316. }
  15317. }
  15318. }
  15319. else if (bitsPerSample == 32)
  15320. {
  15321. const unsigned int* src = (const unsigned int*) tempBuffer;
  15322. unsigned int* l = (unsigned int*) left;
  15323. unsigned int* r = (unsigned int*) right;
  15324. if (numChannels > 1)
  15325. {
  15326. if (l == 0)
  15327. {
  15328. for (int i = numThisTime; --i >= 0;)
  15329. {
  15330. ++src;
  15331. *r++ = swapIfBigEndian (*src++);
  15332. }
  15333. }
  15334. else if (r == 0)
  15335. {
  15336. for (int i = numThisTime; --i >= 0;)
  15337. {
  15338. *l++ = swapIfBigEndian (*src++);
  15339. ++src;
  15340. }
  15341. }
  15342. else
  15343. {
  15344. for (int i = numThisTime; --i >= 0;)
  15345. {
  15346. *l++ = swapIfBigEndian (*src++);
  15347. *r++ = swapIfBigEndian (*src++);
  15348. }
  15349. }
  15350. }
  15351. else
  15352. {
  15353. for (int i = numThisTime; --i >= 0;)
  15354. {
  15355. *l++ = swapIfBigEndian (*src++);
  15356. }
  15357. }
  15358. left = (int*)l;
  15359. right = (int*)r;
  15360. }
  15361. else if (bitsPerSample == 8)
  15362. {
  15363. const unsigned char* src = (const unsigned char*) tempBuffer;
  15364. if (numChannels > 1)
  15365. {
  15366. if (left == 0)
  15367. {
  15368. for (int i = numThisTime; --i >= 0;)
  15369. {
  15370. ++src;
  15371. *right++ = ((int) *src++ - 128) << 24;
  15372. }
  15373. }
  15374. else if (right == 0)
  15375. {
  15376. for (int i = numThisTime; --i >= 0;)
  15377. {
  15378. *left++ = ((int) *src++ - 128) << 24;
  15379. ++src;
  15380. }
  15381. }
  15382. else
  15383. {
  15384. for (int i = numThisTime; --i >= 0;)
  15385. {
  15386. *left++ = ((int) *src++ - 128) << 24;
  15387. *right++ = ((int) *src++ - 128) << 24;
  15388. }
  15389. }
  15390. }
  15391. else
  15392. {
  15393. for (int i = numThisTime; --i >= 0;)
  15394. {
  15395. *left++ = ((int)*src++ - 128) << 24;
  15396. }
  15397. }
  15398. }
  15399. num -= numThisTime;
  15400. }
  15401. }
  15402. if (numToDo < numSamples)
  15403. {
  15404. int** destChan = destSamples;
  15405. while (*destChan != 0)
  15406. {
  15407. zeromem ((*destChan) + (startOffsetInDestBuffer + numToDo),
  15408. sizeof (int) * (numSamples - numToDo));
  15409. ++destChan;
  15410. }
  15411. }
  15412. return true;
  15413. }
  15414. juce_UseDebuggingNewOperator
  15415. };
  15416. class WavAudioFormatWriter : public AudioFormatWriter
  15417. {
  15418. MemoryBlock tempBlock, bwavChunk;
  15419. uint32 lengthInSamples, bytesWritten;
  15420. int64 headerPosition;
  15421. bool writeFailed;
  15422. WavAudioFormatWriter (const WavAudioFormatWriter&);
  15423. const WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  15424. void writeHeader()
  15425. {
  15426. const bool seekedOk = output->setPosition (headerPosition);
  15427. (void) seekedOk;
  15428. // if this fails, you've given it an output stream that can't seek! It needs
  15429. // to be able to seek back to write the header
  15430. jassert (seekedOk);
  15431. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  15432. output->writeInt (chunkName ("RIFF"));
  15433. output->writeInt (lengthInSamples * bytesPerFrame
  15434. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36));
  15435. output->writeInt (chunkName ("WAVE"));
  15436. output->writeInt (chunkName ("fmt "));
  15437. output->writeInt (16);
  15438. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  15439. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  15440. output->writeShort ((short) numChannels);
  15441. output->writeInt ((int) sampleRate);
  15442. output->writeInt (bytesPerFrame * (int) sampleRate);
  15443. output->writeShort ((short) bytesPerFrame);
  15444. output->writeShort ((short) bitsPerSample);
  15445. if (bwavChunk.getSize() > 0)
  15446. {
  15447. output->writeInt (chunkName ("bext"));
  15448. output->writeInt (bwavChunk.getSize());
  15449. output->write (bwavChunk.getData(), bwavChunk.getSize());
  15450. }
  15451. output->writeInt (chunkName ("data"));
  15452. output->writeInt (lengthInSamples * bytesPerFrame);
  15453. usesFloatingPointData = (bitsPerSample == 32);
  15454. }
  15455. public:
  15456. WavAudioFormatWriter (OutputStream* const out,
  15457. const double sampleRate,
  15458. const unsigned int numChannels_,
  15459. const int bits,
  15460. const StringPairArray& metadataValues)
  15461. : AudioFormatWriter (out,
  15462. wavFormatName,
  15463. sampleRate,
  15464. numChannels_,
  15465. bits),
  15466. lengthInSamples (0),
  15467. bytesWritten (0),
  15468. writeFailed (false)
  15469. {
  15470. if (metadataValues.size() > 0)
  15471. bwavChunk = BWAVChunk::createFrom (metadataValues);
  15472. headerPosition = out->getPosition();
  15473. writeHeader();
  15474. }
  15475. ~WavAudioFormatWriter()
  15476. {
  15477. writeHeader();
  15478. }
  15479. bool write (const int** data, int numSamples)
  15480. {
  15481. if (writeFailed)
  15482. return false;
  15483. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15484. tempBlock.ensureSize (bytes, false);
  15485. char* buffer = (char*) tempBlock.getData();
  15486. const int* left = data[0];
  15487. const int* right = data[1];
  15488. if (right == 0)
  15489. right = left;
  15490. if (bitsPerSample == 16)
  15491. {
  15492. short* b = (short*) buffer;
  15493. if (numChannels > 1)
  15494. {
  15495. for (int i = numSamples; --i >= 0;)
  15496. {
  15497. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  15498. *b++ = (short) swapIfBigEndian ((unsigned short) (*right++ >> 16));
  15499. }
  15500. }
  15501. else
  15502. {
  15503. for (int i = numSamples; --i >= 0;)
  15504. {
  15505. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  15506. }
  15507. }
  15508. }
  15509. else if (bitsPerSample == 24)
  15510. {
  15511. char* b = (char*) buffer;
  15512. if (numChannels > 1)
  15513. {
  15514. for (int i = numSamples; --i >= 0;)
  15515. {
  15516. littleEndian24BitToChars ((*left++) >> 8, b);
  15517. b += 3;
  15518. littleEndian24BitToChars ((*right++) >> 8, b);
  15519. b += 3;
  15520. }
  15521. }
  15522. else
  15523. {
  15524. for (int i = numSamples; --i >= 0;)
  15525. {
  15526. littleEndian24BitToChars ((*left++) >> 8, b);
  15527. b += 3;
  15528. }
  15529. }
  15530. }
  15531. else if (bitsPerSample == 32)
  15532. {
  15533. unsigned int* b = (unsigned int*) buffer;
  15534. if (numChannels > 1)
  15535. {
  15536. for (int i = numSamples; --i >= 0;)
  15537. {
  15538. *b++ = swapIfBigEndian ((unsigned int) *left++);
  15539. *b++ = swapIfBigEndian ((unsigned int) *right++);
  15540. }
  15541. }
  15542. else
  15543. {
  15544. for (int i = numSamples; --i >= 0;)
  15545. {
  15546. *b++ = swapIfBigEndian ((unsigned int) *left++);
  15547. }
  15548. }
  15549. }
  15550. else if (bitsPerSample == 8)
  15551. {
  15552. unsigned char* b = (unsigned char*) buffer;
  15553. if (numChannels > 1)
  15554. {
  15555. for (int i = numSamples; --i >= 0;)
  15556. {
  15557. *b++ = (unsigned char) (128 + (*left++ >> 24));
  15558. *b++ = (unsigned char) (128 + (*right++ >> 24));
  15559. }
  15560. }
  15561. else
  15562. {
  15563. for (int i = numSamples; --i >= 0;)
  15564. {
  15565. *b++ = (unsigned char) (128 + (*left++ >> 24));
  15566. }
  15567. }
  15568. }
  15569. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15570. || ! output->write (buffer, bytes))
  15571. {
  15572. // failed to write to disk, so let's try writing the header.
  15573. // If it's just run out of disk space, then if it does manage
  15574. // to write the header, we'll still have a useable file..
  15575. writeHeader();
  15576. writeFailed = true;
  15577. return false;
  15578. }
  15579. else
  15580. {
  15581. bytesWritten += bytes;
  15582. lengthInSamples += numSamples;
  15583. return true;
  15584. }
  15585. }
  15586. juce_UseDebuggingNewOperator
  15587. };
  15588. WavAudioFormat::WavAudioFormat()
  15589. : AudioFormat (wavFormatName, (const tchar**) wavExtensions)
  15590. {
  15591. }
  15592. WavAudioFormat::~WavAudioFormat()
  15593. {
  15594. }
  15595. const Array <int> WavAudioFormat::getPossibleSampleRates()
  15596. {
  15597. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15598. return Array <int> (rates);
  15599. }
  15600. const Array <int> WavAudioFormat::getPossibleBitDepths()
  15601. {
  15602. const int depths[] = { 8, 16, 24, 32, 0 };
  15603. return Array <int> (depths);
  15604. }
  15605. bool WavAudioFormat::canDoStereo()
  15606. {
  15607. return true;
  15608. }
  15609. bool WavAudioFormat::canDoMono()
  15610. {
  15611. return true;
  15612. }
  15613. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  15614. const bool deleteStreamIfOpeningFails)
  15615. {
  15616. WavAudioFormatReader* r = new WavAudioFormatReader (sourceStream);
  15617. if (r->sampleRate == 0)
  15618. {
  15619. if (! deleteStreamIfOpeningFails)
  15620. r->input = 0;
  15621. deleteAndZero (r);
  15622. }
  15623. return r;
  15624. }
  15625. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  15626. double sampleRate,
  15627. unsigned int numChannels,
  15628. int bitsPerSample,
  15629. const StringPairArray& metadataValues,
  15630. int /*qualityOptionIndex*/)
  15631. {
  15632. if (getPossibleBitDepths().contains (bitsPerSample))
  15633. {
  15634. return new WavAudioFormatWriter (out,
  15635. sampleRate,
  15636. numChannels,
  15637. bitsPerSample,
  15638. metadataValues);
  15639. }
  15640. return 0;
  15641. }
  15642. END_JUCE_NAMESPACE
  15643. /********* End of inlined file: juce_WavAudioFormat.cpp *********/
  15644. /********* Start of inlined file: juce_AudioFormatReaderSource.cpp *********/
  15645. BEGIN_JUCE_NAMESPACE
  15646. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  15647. const bool deleteReaderWhenThisIsDeleted)
  15648. : reader (reader_),
  15649. deleteReader (deleteReaderWhenThisIsDeleted),
  15650. nextPlayPos (0),
  15651. looping (false)
  15652. {
  15653. jassert (reader != 0);
  15654. }
  15655. AudioFormatReaderSource::~AudioFormatReaderSource()
  15656. {
  15657. releaseResources();
  15658. if (deleteReader)
  15659. delete reader;
  15660. }
  15661. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  15662. {
  15663. nextPlayPos = newPosition;
  15664. }
  15665. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  15666. {
  15667. looping = shouldLoop;
  15668. }
  15669. int AudioFormatReaderSource::getNextReadPosition() const
  15670. {
  15671. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  15672. : nextPlayPos;
  15673. }
  15674. int AudioFormatReaderSource::getTotalLength() const
  15675. {
  15676. return (int) reader->lengthInSamples;
  15677. }
  15678. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  15679. double /*sampleRate*/)
  15680. {
  15681. }
  15682. void AudioFormatReaderSource::releaseResources()
  15683. {
  15684. }
  15685. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  15686. {
  15687. if (info.numSamples > 0)
  15688. {
  15689. const int start = nextPlayPos;
  15690. if (looping)
  15691. {
  15692. const int newStart = start % (int) reader->lengthInSamples;
  15693. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  15694. if (newEnd > newStart)
  15695. {
  15696. info.buffer->readFromAudioReader (reader,
  15697. info.startSample,
  15698. newEnd - newStart,
  15699. newStart,
  15700. true, true);
  15701. }
  15702. else
  15703. {
  15704. const int endSamps = (int) reader->lengthInSamples - newStart;
  15705. info.buffer->readFromAudioReader (reader,
  15706. info.startSample,
  15707. endSamps,
  15708. newStart,
  15709. true, true);
  15710. info.buffer->readFromAudioReader (reader,
  15711. info.startSample + endSamps,
  15712. newEnd,
  15713. 0,
  15714. true, true);
  15715. }
  15716. nextPlayPos = newEnd;
  15717. }
  15718. else
  15719. {
  15720. info.buffer->readFromAudioReader (reader,
  15721. info.startSample,
  15722. info.numSamples,
  15723. start,
  15724. true, true);
  15725. nextPlayPos += info.numSamples;
  15726. }
  15727. }
  15728. }
  15729. END_JUCE_NAMESPACE
  15730. /********* End of inlined file: juce_AudioFormatReaderSource.cpp *********/
  15731. /********* Start of inlined file: juce_AudioSourcePlayer.cpp *********/
  15732. BEGIN_JUCE_NAMESPACE
  15733. AudioSourcePlayer::AudioSourcePlayer()
  15734. : source (0),
  15735. sampleRate (0),
  15736. bufferSize (0),
  15737. tempBuffer (2, 8),
  15738. lastGain (1.0f),
  15739. gain (1.0f)
  15740. {
  15741. }
  15742. AudioSourcePlayer::~AudioSourcePlayer()
  15743. {
  15744. setSource (0);
  15745. }
  15746. void AudioSourcePlayer::setSource (AudioSource* newSource)
  15747. {
  15748. if (source != newSource)
  15749. {
  15750. AudioSource* const oldSource = source;
  15751. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  15752. newSource->prepareToPlay (bufferSize, sampleRate);
  15753. {
  15754. const ScopedLock sl (readLock);
  15755. source = newSource;
  15756. }
  15757. if (oldSource != 0)
  15758. oldSource->releaseResources();
  15759. }
  15760. }
  15761. void AudioSourcePlayer::setGain (const float newGain) throw()
  15762. {
  15763. gain = newGain;
  15764. }
  15765. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  15766. int totalNumInputChannels,
  15767. float** outputChannelData,
  15768. int totalNumOutputChannels,
  15769. int numSamples)
  15770. {
  15771. // these should have been prepared by audioDeviceAboutToStart()...
  15772. jassert (sampleRate > 0 && bufferSize > 0);
  15773. const ScopedLock sl (readLock);
  15774. if (source != 0)
  15775. {
  15776. AudioSourceChannelInfo info;
  15777. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  15778. // messy stuff needed to compact the channels down into an array
  15779. // of non-zero pointers..
  15780. for (i = 0; i < totalNumInputChannels; ++i)
  15781. {
  15782. if (inputChannelData[i] != 0)
  15783. {
  15784. inputChans [numInputs++] = inputChannelData[i];
  15785. if (numInputs >= numElementsInArray (inputChans))
  15786. break;
  15787. }
  15788. }
  15789. for (i = 0; i < totalNumOutputChannels; ++i)
  15790. {
  15791. if (outputChannelData[i] != 0)
  15792. {
  15793. outputChans [numOutputs++] = outputChannelData[i];
  15794. if (numOutputs >= numElementsInArray (outputChans))
  15795. break;
  15796. }
  15797. }
  15798. if (numInputs > numOutputs)
  15799. {
  15800. // if there aren't enough output channels for the number of
  15801. // inputs, we need to create some temporary extra ones (can't
  15802. // use the input data in case it gets written to)
  15803. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  15804. false, false, true);
  15805. for (i = 0; i < numOutputs; ++i)
  15806. {
  15807. channels[numActiveChans] = outputChans[i];
  15808. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  15809. ++numActiveChans;
  15810. }
  15811. for (i = numOutputs; i < numInputs; ++i)
  15812. {
  15813. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  15814. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  15815. ++numActiveChans;
  15816. }
  15817. }
  15818. else
  15819. {
  15820. for (i = 0; i < numInputs; ++i)
  15821. {
  15822. channels[numActiveChans] = outputChans[i];
  15823. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  15824. ++numActiveChans;
  15825. }
  15826. for (i = numInputs; i < numOutputs; ++i)
  15827. {
  15828. channels[numActiveChans] = outputChans[i];
  15829. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  15830. ++numActiveChans;
  15831. }
  15832. }
  15833. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  15834. info.buffer = &buffer;
  15835. info.startSample = 0;
  15836. info.numSamples = numSamples;
  15837. source->getNextAudioBlock (info);
  15838. for (i = info.buffer->getNumChannels(); --i >= 0;)
  15839. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  15840. lastGain = gain;
  15841. }
  15842. else
  15843. {
  15844. for (int i = 0; i < totalNumOutputChannels; ++i)
  15845. if (outputChannelData[i] != 0)
  15846. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  15847. }
  15848. }
  15849. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  15850. {
  15851. sampleRate = device->getCurrentSampleRate();
  15852. bufferSize = device->getCurrentBufferSizeSamples();
  15853. zeromem (channels, sizeof (channels));
  15854. if (source != 0)
  15855. source->prepareToPlay (bufferSize, sampleRate);
  15856. }
  15857. void AudioSourcePlayer::audioDeviceStopped()
  15858. {
  15859. if (source != 0)
  15860. source->releaseResources();
  15861. sampleRate = 0.0;
  15862. bufferSize = 0;
  15863. tempBuffer.setSize (2, 8);
  15864. }
  15865. END_JUCE_NAMESPACE
  15866. /********* End of inlined file: juce_AudioSourcePlayer.cpp *********/
  15867. /********* Start of inlined file: juce_AudioTransportSource.cpp *********/
  15868. BEGIN_JUCE_NAMESPACE
  15869. AudioTransportSource::AudioTransportSource()
  15870. : source (0),
  15871. resamplerSource (0),
  15872. bufferingSource (0),
  15873. positionableSource (0),
  15874. masterSource (0),
  15875. gain (1.0f),
  15876. lastGain (1.0f),
  15877. playing (false),
  15878. stopped (true),
  15879. sampleRate (44100.0),
  15880. sourceSampleRate (0.0),
  15881. blockSize (128),
  15882. readAheadBufferSize (0),
  15883. isPrepared (false),
  15884. inputStreamEOF (false)
  15885. {
  15886. }
  15887. AudioTransportSource::~AudioTransportSource()
  15888. {
  15889. setSource (0);
  15890. releaseResources();
  15891. }
  15892. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  15893. int readAheadBufferSize_,
  15894. double sourceSampleRateToCorrectFor)
  15895. {
  15896. if (source == newSource)
  15897. {
  15898. if (source == 0)
  15899. return;
  15900. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  15901. }
  15902. readAheadBufferSize = readAheadBufferSize_;
  15903. sourceSampleRate = sourceSampleRateToCorrectFor;
  15904. ResamplingAudioSource* newResamplerSource = 0;
  15905. BufferingAudioSource* newBufferingSource = 0;
  15906. PositionableAudioSource* newPositionableSource = 0;
  15907. AudioSource* newMasterSource = 0;
  15908. ResamplingAudioSource* oldResamplerSource = resamplerSource;
  15909. BufferingAudioSource* oldBufferingSource = bufferingSource;
  15910. AudioSource* oldMasterSource = masterSource;
  15911. if (newSource != 0)
  15912. {
  15913. newPositionableSource = newSource;
  15914. if (readAheadBufferSize_ > 0)
  15915. newPositionableSource = newBufferingSource
  15916. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  15917. newPositionableSource->setNextReadPosition (0);
  15918. if (sourceSampleRateToCorrectFor != 0)
  15919. newMasterSource = newResamplerSource
  15920. = new ResamplingAudioSource (newPositionableSource, false);
  15921. else
  15922. newMasterSource = newPositionableSource;
  15923. if (isPrepared)
  15924. {
  15925. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  15926. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  15927. newMasterSource->prepareToPlay (blockSize, sampleRate);
  15928. }
  15929. }
  15930. {
  15931. const ScopedLock sl (callbackLock);
  15932. source = newSource;
  15933. resamplerSource = newResamplerSource;
  15934. bufferingSource = newBufferingSource;
  15935. masterSource = newMasterSource;
  15936. positionableSource = newPositionableSource;
  15937. playing = false;
  15938. }
  15939. if (oldMasterSource != 0)
  15940. oldMasterSource->releaseResources();
  15941. if (oldResamplerSource != 0)
  15942. delete oldResamplerSource;
  15943. if (oldBufferingSource != 0)
  15944. delete oldBufferingSource;
  15945. }
  15946. void AudioTransportSource::start()
  15947. {
  15948. if ((! playing) && masterSource != 0)
  15949. {
  15950. callbackLock.enter();
  15951. playing = true;
  15952. stopped = false;
  15953. inputStreamEOF = false;
  15954. callbackLock.exit();
  15955. sendChangeMessage (this);
  15956. }
  15957. }
  15958. void AudioTransportSource::stop()
  15959. {
  15960. if (playing)
  15961. {
  15962. callbackLock.enter();
  15963. playing = false;
  15964. callbackLock.exit();
  15965. int n = 500;
  15966. while (--n >= 0 && ! stopped)
  15967. Thread::sleep (2);
  15968. sendChangeMessage (this);
  15969. }
  15970. }
  15971. void AudioTransportSource::setPosition (double newPosition)
  15972. {
  15973. if (sampleRate > 0.0)
  15974. setNextReadPosition (roundDoubleToInt (newPosition * sampleRate));
  15975. }
  15976. double AudioTransportSource::getCurrentPosition() const
  15977. {
  15978. if (sampleRate > 0.0)
  15979. return getNextReadPosition() / sampleRate;
  15980. else
  15981. return 0.0;
  15982. }
  15983. void AudioTransportSource::setNextReadPosition (int newPosition)
  15984. {
  15985. if (positionableSource != 0)
  15986. {
  15987. if (sampleRate > 0 && sourceSampleRate > 0)
  15988. newPosition = roundDoubleToInt (newPosition * sourceSampleRate / sampleRate);
  15989. positionableSource->setNextReadPosition (newPosition);
  15990. }
  15991. }
  15992. int AudioTransportSource::getNextReadPosition() const
  15993. {
  15994. if (positionableSource != 0)
  15995. {
  15996. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  15997. return roundDoubleToInt (positionableSource->getNextReadPosition() * ratio);
  15998. }
  15999. return 0;
  16000. }
  16001. int AudioTransportSource::getTotalLength() const
  16002. {
  16003. const ScopedLock sl (callbackLock);
  16004. if (positionableSource != 0)
  16005. {
  16006. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  16007. return roundDoubleToInt (positionableSource->getTotalLength() * ratio);
  16008. }
  16009. return 0;
  16010. }
  16011. bool AudioTransportSource::isLooping() const
  16012. {
  16013. const ScopedLock sl (callbackLock);
  16014. return positionableSource != 0
  16015. && positionableSource->isLooping();
  16016. }
  16017. void AudioTransportSource::setGain (const float newGain) throw()
  16018. {
  16019. gain = newGain;
  16020. }
  16021. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  16022. double sampleRate_)
  16023. {
  16024. const ScopedLock sl (callbackLock);
  16025. sampleRate = sampleRate_;
  16026. blockSize = samplesPerBlockExpected;
  16027. if (masterSource != 0)
  16028. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16029. if (resamplerSource != 0 && sourceSampleRate != 0)
  16030. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  16031. isPrepared = true;
  16032. }
  16033. void AudioTransportSource::releaseResources()
  16034. {
  16035. const ScopedLock sl (callbackLock);
  16036. if (masterSource != 0)
  16037. masterSource->releaseResources();
  16038. isPrepared = false;
  16039. }
  16040. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16041. {
  16042. const ScopedLock sl (callbackLock);
  16043. inputStreamEOF = false;
  16044. if (masterSource != 0 && ! stopped)
  16045. {
  16046. masterSource->getNextAudioBlock (info);
  16047. if (! playing)
  16048. {
  16049. // just stopped playing, so fade out the last block..
  16050. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  16051. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  16052. if (info.numSamples > 256)
  16053. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  16054. }
  16055. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  16056. && ! positionableSource->isLooping())
  16057. {
  16058. playing = false;
  16059. inputStreamEOF = true;
  16060. sendChangeMessage (this);
  16061. }
  16062. stopped = ! playing;
  16063. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  16064. {
  16065. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  16066. lastGain, gain);
  16067. }
  16068. }
  16069. else
  16070. {
  16071. info.clearActiveBufferRegion();
  16072. stopped = true;
  16073. }
  16074. lastGain = gain;
  16075. }
  16076. END_JUCE_NAMESPACE
  16077. /********* End of inlined file: juce_AudioTransportSource.cpp *********/
  16078. /********* Start of inlined file: juce_BufferingAudioSource.cpp *********/
  16079. BEGIN_JUCE_NAMESPACE
  16080. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  16081. public Thread,
  16082. private Timer
  16083. {
  16084. public:
  16085. SharedBufferingAudioSourceThread()
  16086. : Thread ("Audio Buffer"),
  16087. sources (8)
  16088. {
  16089. }
  16090. ~SharedBufferingAudioSourceThread()
  16091. {
  16092. stopThread (10000);
  16093. clearSingletonInstance();
  16094. }
  16095. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  16096. void addSource (BufferingAudioSource* source)
  16097. {
  16098. const ScopedLock sl (lock);
  16099. if (! sources.contains ((void*) source))
  16100. {
  16101. sources.add ((void*) source);
  16102. startThread();
  16103. stopTimer();
  16104. }
  16105. notify();
  16106. }
  16107. void removeSource (BufferingAudioSource* source)
  16108. {
  16109. const ScopedLock sl (lock);
  16110. sources.removeValue ((void*) source);
  16111. if (sources.size() == 0)
  16112. startTimer (5000);
  16113. }
  16114. private:
  16115. VoidArray sources;
  16116. CriticalSection lock;
  16117. void run()
  16118. {
  16119. while (! threadShouldExit())
  16120. {
  16121. bool busy = false;
  16122. for (int i = sources.size(); --i >= 0;)
  16123. {
  16124. if (threadShouldExit())
  16125. return;
  16126. const ScopedLock sl (lock);
  16127. BufferingAudioSource* const b = (BufferingAudioSource*) sources[i];
  16128. if (b != 0 && b->readNextBufferChunk())
  16129. busy = true;
  16130. }
  16131. if (! busy)
  16132. wait (500);
  16133. }
  16134. }
  16135. void timerCallback()
  16136. {
  16137. stopTimer();
  16138. if (sources.size() == 0)
  16139. deleteInstance();
  16140. }
  16141. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  16142. const SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  16143. };
  16144. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  16145. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  16146. const bool deleteSourceWhenDeleted_,
  16147. int numberOfSamplesToBuffer_)
  16148. : source (source_),
  16149. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  16150. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  16151. buffer (2, 0),
  16152. bufferValidStart (0),
  16153. bufferValidEnd (0),
  16154. nextPlayPos (0),
  16155. wasSourceLooping (false)
  16156. {
  16157. jassert (source_ != 0);
  16158. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  16159. // not using a larger buffer..
  16160. }
  16161. BufferingAudioSource::~BufferingAudioSource()
  16162. {
  16163. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16164. if (thread != 0)
  16165. thread->removeSource (this);
  16166. if (deleteSourceWhenDeleted)
  16167. delete source;
  16168. }
  16169. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  16170. {
  16171. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  16172. sampleRate = sampleRate_;
  16173. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  16174. buffer.clear();
  16175. bufferValidStart = 0;
  16176. bufferValidEnd = 0;
  16177. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  16178. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  16179. buffer.getNumSamples() / 2))
  16180. {
  16181. SharedBufferingAudioSourceThread::getInstance()->notify();
  16182. Thread::sleep (5);
  16183. }
  16184. }
  16185. void BufferingAudioSource::releaseResources()
  16186. {
  16187. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16188. if (thread != 0)
  16189. thread->removeSource (this);
  16190. buffer.setSize (2, 0);
  16191. source->releaseResources();
  16192. }
  16193. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16194. {
  16195. const ScopedLock sl (bufferStartPosLock);
  16196. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  16197. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  16198. if (validStart == validEnd)
  16199. {
  16200. // total cache miss
  16201. info.clearActiveBufferRegion();
  16202. }
  16203. else
  16204. {
  16205. if (validStart > 0)
  16206. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  16207. if (validEnd < info.numSamples)
  16208. info.buffer->clear (info.startSample + validEnd,
  16209. info.numSamples - validEnd); // partial cache miss at end
  16210. if (validStart < validEnd)
  16211. {
  16212. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  16213. {
  16214. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  16215. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  16216. if (startBufferIndex < endBufferIndex)
  16217. {
  16218. info.buffer->copyFrom (chan, info.startSample + validStart,
  16219. buffer,
  16220. chan, startBufferIndex,
  16221. validEnd - validStart);
  16222. }
  16223. else
  16224. {
  16225. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  16226. info.buffer->copyFrom (chan, info.startSample + validStart,
  16227. buffer,
  16228. chan, startBufferIndex,
  16229. initialSize);
  16230. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  16231. buffer,
  16232. chan, 0,
  16233. (validEnd - validStart) - initialSize);
  16234. }
  16235. }
  16236. }
  16237. nextPlayPos += info.numSamples;
  16238. }
  16239. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16240. if (thread != 0)
  16241. thread->notify();
  16242. }
  16243. int BufferingAudioSource::getNextReadPosition() const
  16244. {
  16245. return (source->isLooping() && nextPlayPos > 0)
  16246. ? nextPlayPos % source->getTotalLength()
  16247. : nextPlayPos;
  16248. }
  16249. void BufferingAudioSource::setNextReadPosition (int newPosition)
  16250. {
  16251. const ScopedLock sl (bufferStartPosLock);
  16252. nextPlayPos = newPosition;
  16253. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16254. if (thread != 0)
  16255. thread->notify();
  16256. }
  16257. bool BufferingAudioSource::readNextBufferChunk()
  16258. {
  16259. bufferStartPosLock.enter();
  16260. if (wasSourceLooping != isLooping())
  16261. {
  16262. wasSourceLooping = isLooping();
  16263. bufferValidStart = 0;
  16264. bufferValidEnd = 0;
  16265. }
  16266. int newBVS = jmax (0, nextPlayPos);
  16267. int newBVE = newBVS + buffer.getNumSamples() - 4;
  16268. int sectionToReadStart = 0;
  16269. int sectionToReadEnd = 0;
  16270. const int maxChunkSize = 2048;
  16271. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  16272. {
  16273. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  16274. sectionToReadStart = newBVS;
  16275. sectionToReadEnd = newBVE;
  16276. bufferValidStart = 0;
  16277. bufferValidEnd = 0;
  16278. }
  16279. else if (abs (newBVS - bufferValidStart) > 512
  16280. || abs (newBVE - bufferValidEnd) > 512)
  16281. {
  16282. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  16283. sectionToReadStart = bufferValidEnd;
  16284. sectionToReadEnd = newBVE;
  16285. bufferValidStart = newBVS;
  16286. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  16287. }
  16288. bufferStartPosLock.exit();
  16289. if (sectionToReadStart != sectionToReadEnd)
  16290. {
  16291. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  16292. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  16293. if (bufferIndexStart < bufferIndexEnd)
  16294. {
  16295. readBufferSection (sectionToReadStart,
  16296. sectionToReadEnd - sectionToReadStart,
  16297. bufferIndexStart);
  16298. }
  16299. else
  16300. {
  16301. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  16302. readBufferSection (sectionToReadStart,
  16303. initialSize,
  16304. bufferIndexStart);
  16305. readBufferSection (sectionToReadStart + initialSize,
  16306. (sectionToReadEnd - sectionToReadStart) - initialSize,
  16307. 0);
  16308. }
  16309. const ScopedLock sl2 (bufferStartPosLock);
  16310. bufferValidStart = newBVS;
  16311. bufferValidEnd = newBVE;
  16312. return true;
  16313. }
  16314. else
  16315. {
  16316. return false;
  16317. }
  16318. }
  16319. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  16320. {
  16321. if (source->getNextReadPosition() != start)
  16322. source->setNextReadPosition (start);
  16323. AudioSourceChannelInfo info;
  16324. info.buffer = &buffer;
  16325. info.startSample = bufferOffset;
  16326. info.numSamples = length;
  16327. source->getNextAudioBlock (info);
  16328. }
  16329. END_JUCE_NAMESPACE
  16330. /********* End of inlined file: juce_BufferingAudioSource.cpp *********/
  16331. /********* Start of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  16332. BEGIN_JUCE_NAMESPACE
  16333. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  16334. const bool deleteSourceWhenDeleted_)
  16335. : requiredNumberOfChannels (2),
  16336. source (source_),
  16337. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  16338. buffer (2, 16)
  16339. {
  16340. remappedInfo.buffer = &buffer;
  16341. remappedInfo.startSample = 0;
  16342. }
  16343. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  16344. {
  16345. if (deleteSourceWhenDeleted)
  16346. delete source;
  16347. }
  16348. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  16349. {
  16350. const ScopedLock sl (lock);
  16351. requiredNumberOfChannels = requiredNumberOfChannels_;
  16352. }
  16353. void ChannelRemappingAudioSource::clearAllMappings() throw()
  16354. {
  16355. const ScopedLock sl (lock);
  16356. remappedInputs.clear();
  16357. remappedOutputs.clear();
  16358. }
  16359. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  16360. {
  16361. const ScopedLock sl (lock);
  16362. while (remappedInputs.size() < destIndex)
  16363. remappedInputs.add (-1);
  16364. remappedInputs.set (destIndex, sourceIndex);
  16365. }
  16366. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  16367. {
  16368. const ScopedLock sl (lock);
  16369. while (remappedOutputs.size() < sourceIndex)
  16370. remappedOutputs.add (-1);
  16371. remappedOutputs.set (sourceIndex, destIndex);
  16372. }
  16373. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  16374. {
  16375. const ScopedLock sl (lock);
  16376. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  16377. return remappedInputs.getUnchecked (inputChannelIndex);
  16378. return -1;
  16379. }
  16380. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  16381. {
  16382. const ScopedLock sl (lock);
  16383. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  16384. return remappedOutputs .getUnchecked (outputChannelIndex);
  16385. return -1;
  16386. }
  16387. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  16388. {
  16389. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16390. }
  16391. void ChannelRemappingAudioSource::releaseResources()
  16392. {
  16393. source->releaseResources();
  16394. }
  16395. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  16396. {
  16397. const ScopedLock sl (lock);
  16398. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  16399. const int numChans = bufferToFill.buffer->getNumChannels();
  16400. int i;
  16401. for (i = 0; i < buffer.getNumChannels(); ++i)
  16402. {
  16403. const int remappedChan = getRemappedInputChannel (i);
  16404. if (remappedChan >= 0 && remappedChan < numChans)
  16405. {
  16406. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  16407. remappedChan,
  16408. bufferToFill.startSample,
  16409. bufferToFill.numSamples);
  16410. }
  16411. else
  16412. {
  16413. buffer.clear (i, 0, bufferToFill.numSamples);
  16414. }
  16415. }
  16416. remappedInfo.numSamples = bufferToFill.numSamples;
  16417. source->getNextAudioBlock (remappedInfo);
  16418. bufferToFill.clearActiveBufferRegion();
  16419. for (i = 0; i < requiredNumberOfChannels; ++i)
  16420. {
  16421. const int remappedChan = getRemappedOutputChannel (i);
  16422. if (remappedChan >= 0 && remappedChan < numChans)
  16423. {
  16424. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  16425. buffer, i, 0, bufferToFill.numSamples);
  16426. }
  16427. }
  16428. }
  16429. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  16430. {
  16431. XmlElement* e = new XmlElement (T("MAPPINGS"));
  16432. String ins, outs;
  16433. int i;
  16434. const ScopedLock sl (lock);
  16435. for (i = 0; i < remappedInputs.size(); ++i)
  16436. ins << remappedInputs.getUnchecked(i) << T(' ');
  16437. for (i = 0; i < remappedOutputs.size(); ++i)
  16438. outs << remappedOutputs.getUnchecked(i) << T(' ');
  16439. e->setAttribute (T("inputs"), ins.trimEnd());
  16440. e->setAttribute (T("outputs"), outs.trimEnd());
  16441. return e;
  16442. }
  16443. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  16444. {
  16445. if (e.hasTagName (T("MAPPINGS")))
  16446. {
  16447. const ScopedLock sl (lock);
  16448. clearAllMappings();
  16449. StringArray ins, outs;
  16450. ins.addTokens (e.getStringAttribute (T("inputs")), false);
  16451. outs.addTokens (e.getStringAttribute (T("outputs")), false);
  16452. int i;
  16453. for (i = 0; i < ins.size(); ++i)
  16454. remappedInputs.add (ins[i].getIntValue());
  16455. for (i = 0; i < outs.size(); ++i)
  16456. remappedOutputs.add (outs[i].getIntValue());
  16457. }
  16458. }
  16459. END_JUCE_NAMESPACE
  16460. /********* End of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  16461. /********* Start of inlined file: juce_IIRFilterAudioSource.cpp *********/
  16462. BEGIN_JUCE_NAMESPACE
  16463. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  16464. const bool deleteInputWhenDeleted_)
  16465. : input (inputSource),
  16466. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  16467. {
  16468. jassert (inputSource != 0);
  16469. for (int i = 2; --i >= 0;)
  16470. iirFilters.add (new IIRFilter());
  16471. }
  16472. IIRFilterAudioSource::~IIRFilterAudioSource()
  16473. {
  16474. if (deleteInputWhenDeleted)
  16475. delete input;
  16476. }
  16477. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  16478. {
  16479. for (int i = iirFilters.size(); --i >= 0;)
  16480. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  16481. }
  16482. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  16483. {
  16484. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16485. for (int i = iirFilters.size(); --i >= 0;)
  16486. iirFilters.getUnchecked(i)->reset();
  16487. }
  16488. void IIRFilterAudioSource::releaseResources()
  16489. {
  16490. input->releaseResources();
  16491. }
  16492. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  16493. {
  16494. input->getNextAudioBlock (bufferToFill);
  16495. const int numChannels = bufferToFill.buffer->getNumChannels();
  16496. while (numChannels > iirFilters.size())
  16497. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  16498. for (int i = 0; i < numChannels; ++i)
  16499. iirFilters.getUnchecked(i)
  16500. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  16501. bufferToFill.numSamples);
  16502. }
  16503. END_JUCE_NAMESPACE
  16504. /********* End of inlined file: juce_IIRFilterAudioSource.cpp *********/
  16505. /********* Start of inlined file: juce_MixerAudioSource.cpp *********/
  16506. BEGIN_JUCE_NAMESPACE
  16507. MixerAudioSource::MixerAudioSource()
  16508. : tempBuffer (2, 0),
  16509. currentSampleRate (0.0),
  16510. bufferSizeExpected (0)
  16511. {
  16512. }
  16513. MixerAudioSource::~MixerAudioSource()
  16514. {
  16515. removeAllInputs();
  16516. }
  16517. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  16518. {
  16519. if (input != 0 && ! inputs.contains (input))
  16520. {
  16521. lock.enter();
  16522. double localRate = currentSampleRate;
  16523. int localBufferSize = bufferSizeExpected;
  16524. lock.exit();
  16525. if (localRate != 0.0)
  16526. input->prepareToPlay (localBufferSize, localRate);
  16527. const ScopedLock sl (lock);
  16528. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  16529. inputs.add (input);
  16530. }
  16531. }
  16532. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  16533. {
  16534. if (input != 0)
  16535. {
  16536. lock.enter();
  16537. const int index = inputs.indexOf ((void*) input);
  16538. if (index >= 0)
  16539. {
  16540. inputsToDelete.shiftBits (index, 1);
  16541. inputs.remove (index);
  16542. }
  16543. lock.exit();
  16544. if (index >= 0)
  16545. {
  16546. input->releaseResources();
  16547. if (deleteInput)
  16548. delete input;
  16549. }
  16550. }
  16551. }
  16552. void MixerAudioSource::removeAllInputs()
  16553. {
  16554. lock.enter();
  16555. VoidArray inputsCopy (inputs);
  16556. BitArray inputsToDeleteCopy (inputsToDelete);
  16557. inputs.clear();
  16558. lock.exit();
  16559. for (int i = inputsCopy.size(); --i >= 0;)
  16560. if (inputsToDeleteCopy[i])
  16561. delete (AudioSource*) inputsCopy[i];
  16562. }
  16563. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  16564. {
  16565. tempBuffer.setSize (2, samplesPerBlockExpected);
  16566. const ScopedLock sl (lock);
  16567. currentSampleRate = sampleRate;
  16568. bufferSizeExpected = samplesPerBlockExpected;
  16569. for (int i = inputs.size(); --i >= 0;)
  16570. ((AudioSource*) inputs.getUnchecked(i))->prepareToPlay (samplesPerBlockExpected,
  16571. sampleRate);
  16572. }
  16573. void MixerAudioSource::releaseResources()
  16574. {
  16575. const ScopedLock sl (lock);
  16576. for (int i = inputs.size(); --i >= 0;)
  16577. ((AudioSource*) inputs.getUnchecked(i))->releaseResources();
  16578. tempBuffer.setSize (2, 0);
  16579. currentSampleRate = 0;
  16580. bufferSizeExpected = 0;
  16581. }
  16582. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16583. {
  16584. const ScopedLock sl (lock);
  16585. if (inputs.size() > 0)
  16586. {
  16587. ((AudioSource*) inputs.getUnchecked(0))->getNextAudioBlock (info);
  16588. if (inputs.size() > 1)
  16589. {
  16590. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  16591. info.buffer->getNumSamples());
  16592. AudioSourceChannelInfo info2;
  16593. info2.buffer = &tempBuffer;
  16594. info2.numSamples = info.numSamples;
  16595. info2.startSample = 0;
  16596. for (int i = 1; i < inputs.size(); ++i)
  16597. {
  16598. ((AudioSource*) inputs.getUnchecked(i))->getNextAudioBlock (info2);
  16599. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  16600. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  16601. }
  16602. }
  16603. }
  16604. else
  16605. {
  16606. info.clearActiveBufferRegion();
  16607. }
  16608. }
  16609. END_JUCE_NAMESPACE
  16610. /********* End of inlined file: juce_MixerAudioSource.cpp *********/
  16611. /********* Start of inlined file: juce_ResamplingAudioSource.cpp *********/
  16612. BEGIN_JUCE_NAMESPACE
  16613. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  16614. const bool deleteInputWhenDeleted_)
  16615. : input (inputSource),
  16616. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  16617. ratio (1.0),
  16618. lastRatio (1.0),
  16619. buffer (2, 0),
  16620. sampsInBuffer (0)
  16621. {
  16622. jassert (input != 0);
  16623. }
  16624. ResamplingAudioSource::~ResamplingAudioSource()
  16625. {
  16626. if (deleteInputWhenDeleted)
  16627. delete input;
  16628. }
  16629. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  16630. {
  16631. jassert (samplesInPerOutputSample > 0);
  16632. const ScopedLock sl (ratioLock);
  16633. ratio = jmax (0.0, samplesInPerOutputSample);
  16634. }
  16635. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  16636. double sampleRate)
  16637. {
  16638. const ScopedLock sl (ratioLock);
  16639. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16640. buffer.setSize (2, roundDoubleToInt (samplesPerBlockExpected * ratio) + 32);
  16641. buffer.clear();
  16642. sampsInBuffer = 0;
  16643. bufferPos = 0;
  16644. subSampleOffset = 0.0;
  16645. createLowPass (ratio);
  16646. resetFilters();
  16647. }
  16648. void ResamplingAudioSource::releaseResources()
  16649. {
  16650. input->releaseResources();
  16651. buffer.setSize (2, 0);
  16652. }
  16653. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16654. {
  16655. const ScopedLock sl (ratioLock);
  16656. if (lastRatio != ratio)
  16657. {
  16658. createLowPass (ratio);
  16659. lastRatio = ratio;
  16660. }
  16661. const int sampsNeeded = roundDoubleToInt (info.numSamples * ratio) + 2;
  16662. int bufferSize = buffer.getNumSamples();
  16663. if (bufferSize < sampsNeeded + 8)
  16664. {
  16665. bufferPos %= bufferSize;
  16666. bufferSize = sampsNeeded + 32;
  16667. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  16668. }
  16669. bufferPos %= bufferSize;
  16670. int endOfBufferPos = bufferPos + sampsInBuffer;
  16671. while (sampsNeeded > sampsInBuffer)
  16672. {
  16673. endOfBufferPos %= bufferSize;
  16674. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  16675. bufferSize - endOfBufferPos);
  16676. AudioSourceChannelInfo readInfo;
  16677. readInfo.buffer = &buffer;
  16678. readInfo.numSamples = numToDo;
  16679. readInfo.startSample = endOfBufferPos;
  16680. input->getNextAudioBlock (readInfo);
  16681. if (ratio > 1.0)
  16682. {
  16683. // for down-sampling, pre-apply the filter..
  16684. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  16685. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  16686. }
  16687. sampsInBuffer += numToDo;
  16688. endOfBufferPos += numToDo;
  16689. }
  16690. float* dl = info.buffer->getSampleData (0, info.startSample);
  16691. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  16692. const float* const bl = buffer.getSampleData (0, 0);
  16693. const float* const br = buffer.getSampleData (1, 0);
  16694. int nextPos = (bufferPos + 1) % bufferSize;
  16695. for (int m = info.numSamples; --m >= 0;)
  16696. {
  16697. const float alpha = (float) subSampleOffset;
  16698. const float invAlpha = 1.0f - alpha;
  16699. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  16700. if (dr != 0)
  16701. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  16702. subSampleOffset += ratio;
  16703. jassert (sampsInBuffer > 0);
  16704. while (subSampleOffset >= 1.0)
  16705. {
  16706. if (++bufferPos >= bufferSize)
  16707. bufferPos = 0;
  16708. --sampsInBuffer;
  16709. nextPos = (bufferPos + 1) % bufferSize;
  16710. subSampleOffset -= 1.0;
  16711. }
  16712. }
  16713. if (ratio < 1.0)
  16714. {
  16715. // for up-sampling, apply the filter after transposing..
  16716. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  16717. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  16718. }
  16719. jassert (sampsInBuffer >= 0);
  16720. }
  16721. void ResamplingAudioSource::createLowPass (const double ratio)
  16722. {
  16723. const double proportionalRate = (ratio > 1.0) ? 0.5 / ratio
  16724. : 0.5 * ratio;
  16725. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  16726. const double nSquared = n * n;
  16727. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  16728. setFilterCoefficients (c1,
  16729. c1 * 2.0f,
  16730. c1,
  16731. 1.0,
  16732. c1 * 2.0 * (1.0 - nSquared),
  16733. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  16734. }
  16735. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  16736. {
  16737. const double a = 1.0 / c4;
  16738. c1 *= a;
  16739. c2 *= a;
  16740. c3 *= a;
  16741. c5 *= a;
  16742. c6 *= a;
  16743. coefficients[0] = c1;
  16744. coefficients[1] = c2;
  16745. coefficients[2] = c3;
  16746. coefficients[3] = c4;
  16747. coefficients[4] = c5;
  16748. coefficients[5] = c6;
  16749. }
  16750. void ResamplingAudioSource::resetFilters()
  16751. {
  16752. zeromem (filterStates, sizeof (filterStates));
  16753. }
  16754. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  16755. {
  16756. while (--num >= 0)
  16757. {
  16758. const double in = *samples;
  16759. double out = coefficients[0] * in
  16760. + coefficients[1] * fs.x1
  16761. + coefficients[2] * fs.x2
  16762. - coefficients[4] * fs.y1
  16763. - coefficients[5] * fs.y2;
  16764. #if JUCE_INTEL
  16765. if (! (out < -1.0e-8 || out > 1.0e-8))
  16766. out = 0;
  16767. #endif
  16768. fs.x2 = fs.x1;
  16769. fs.x1 = in;
  16770. fs.y2 = fs.y1;
  16771. fs.y1 = out;
  16772. *samples++ = (float) out;
  16773. }
  16774. }
  16775. END_JUCE_NAMESPACE
  16776. /********* End of inlined file: juce_ResamplingAudioSource.cpp *********/
  16777. /********* Start of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  16778. BEGIN_JUCE_NAMESPACE
  16779. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  16780. : frequency (1000.0),
  16781. sampleRate (44100.0),
  16782. currentPhase (0.0),
  16783. phasePerSample (0.0),
  16784. amplitude (0.5f)
  16785. {
  16786. }
  16787. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  16788. {
  16789. }
  16790. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  16791. {
  16792. amplitude = newAmplitude;
  16793. }
  16794. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  16795. {
  16796. frequency = newFrequencyHz;
  16797. phasePerSample = 0.0;
  16798. }
  16799. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  16800. double sampleRate_)
  16801. {
  16802. currentPhase = 0.0;
  16803. phasePerSample = 0.0;
  16804. sampleRate = sampleRate_;
  16805. }
  16806. void ToneGeneratorAudioSource::releaseResources()
  16807. {
  16808. }
  16809. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16810. {
  16811. if (phasePerSample == 0.0)
  16812. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  16813. for (int i = 0; i < info.numSamples; ++i)
  16814. {
  16815. const float sample = amplitude * (float) sin (currentPhase);
  16816. currentPhase += phasePerSample;
  16817. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  16818. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  16819. }
  16820. }
  16821. END_JUCE_NAMESPACE
  16822. /********* End of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  16823. /********* Start of inlined file: juce_AudioDeviceManager.cpp *********/
  16824. BEGIN_JUCE_NAMESPACE
  16825. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  16826. : sampleRate (0),
  16827. bufferSize (0),
  16828. useDefaultInputChannels (true),
  16829. useDefaultOutputChannels (true)
  16830. {
  16831. }
  16832. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  16833. {
  16834. return outputDeviceName == other.outputDeviceName
  16835. && inputDeviceName == other.inputDeviceName
  16836. && sampleRate == other.sampleRate
  16837. && bufferSize == other.bufferSize
  16838. && inputChannels == other.inputChannels
  16839. && useDefaultInputChannels == other.useDefaultInputChannels
  16840. && outputChannels == other.outputChannels
  16841. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  16842. }
  16843. AudioDeviceManager::AudioDeviceManager()
  16844. : currentAudioDevice (0),
  16845. currentCallback (0),
  16846. numInputChansNeeded (0),
  16847. numOutputChansNeeded (2),
  16848. lastExplicitSettings (0),
  16849. listNeedsScanning (true),
  16850. useInputNames (false),
  16851. inputLevelMeasurementEnabled (false),
  16852. inputLevel (0),
  16853. testSound (0),
  16854. enabledMidiInputs (4),
  16855. midiCallbacks (4),
  16856. midiCallbackDevices (4),
  16857. defaultMidiOutput (0),
  16858. cpuUsageMs (0),
  16859. timeToCpuScale (0)
  16860. {
  16861. callbackHandler.owner = this;
  16862. }
  16863. AudioDeviceManager::~AudioDeviceManager()
  16864. {
  16865. deleteAndZero (currentAudioDevice);
  16866. deleteAndZero (defaultMidiOutput);
  16867. delete lastExplicitSettings;
  16868. delete testSound;
  16869. }
  16870. void AudioDeviceManager::createDeviceTypesIfNeeded()
  16871. {
  16872. if (availableDeviceTypes.size() == 0)
  16873. {
  16874. createAudioDeviceTypes (availableDeviceTypes);
  16875. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  16876. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  16877. if (availableDeviceTypes.size() > 0)
  16878. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  16879. }
  16880. }
  16881. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  16882. {
  16883. scanDevicesIfNeeded();
  16884. return availableDeviceTypes;
  16885. }
  16886. extern AudioIODeviceType* juce_createDefaultAudioIODeviceType();
  16887. #if JUCE_WIN32 && JUCE_ASIO
  16888. extern AudioIODeviceType* juce_createASIOAudioIODeviceType();
  16889. #endif
  16890. #if JUCE_WIN32 && JUCE_WDM_AUDIO
  16891. extern AudioIODeviceType* juce_createWDMAudioIODeviceType();
  16892. #endif
  16893. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  16894. {
  16895. AudioIODeviceType* const defaultDeviceType = juce_createDefaultAudioIODeviceType();
  16896. if (defaultDeviceType != 0)
  16897. list.add (defaultDeviceType);
  16898. #if JUCE_WIN32 && JUCE_ASIO
  16899. list.add (juce_createASIOAudioIODeviceType());
  16900. #endif
  16901. #if JUCE_WIN32 && JUCE_WDM_AUDIO
  16902. list.add (juce_createWDMAudioIODeviceType());
  16903. #endif
  16904. }
  16905. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  16906. const int numOutputChannelsNeeded,
  16907. const XmlElement* const e,
  16908. const bool selectDefaultDeviceOnFailure,
  16909. const String& preferredDefaultDeviceName)
  16910. {
  16911. scanDevicesIfNeeded();
  16912. numInputChansNeeded = numInputChannelsNeeded;
  16913. numOutputChansNeeded = numOutputChannelsNeeded;
  16914. if (e != 0 && e->hasTagName (T("DEVICESETUP")))
  16915. {
  16916. delete lastExplicitSettings;
  16917. lastExplicitSettings = new XmlElement (*e);
  16918. String error;
  16919. AudioDeviceSetup setup;
  16920. if (e->getStringAttribute (T("audioDeviceName")).isNotEmpty())
  16921. {
  16922. setup.inputDeviceName = setup.outputDeviceName
  16923. = e->getStringAttribute (T("audioDeviceName"));
  16924. }
  16925. else
  16926. {
  16927. setup.inputDeviceName = e->getStringAttribute (T("audioInputDeviceName"));
  16928. setup.outputDeviceName = e->getStringAttribute (T("audioOutputDeviceName"));
  16929. }
  16930. currentDeviceType = e->getStringAttribute (T("deviceType"));
  16931. if (currentDeviceType.isEmpty())
  16932. {
  16933. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  16934. if (type != 0)
  16935. currentDeviceType = type->getTypeName();
  16936. else if (availableDeviceTypes.size() > 0)
  16937. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  16938. }
  16939. setup.bufferSize = e->getIntAttribute (T("audioDeviceBufferSize"));
  16940. setup.sampleRate = e->getDoubleAttribute (T("audioDeviceRate"));
  16941. setup.inputChannels.parseString (e->getStringAttribute (T("audioDeviceInChans"), T("11")), 2);
  16942. setup.outputChannels.parseString (e->getStringAttribute (T("audioDeviceOutChans"), T("11")), 2);
  16943. setup.useDefaultInputChannels = ! e->hasAttribute (T("audioDeviceInChans"));
  16944. setup.useDefaultOutputChannels = ! e->hasAttribute (T("audioDeviceOutChans"));
  16945. error = setAudioDeviceSetup (setup, true);
  16946. midiInsFromXml.clear();
  16947. forEachXmlChildElementWithTagName (*e, c, T("MIDIINPUT"))
  16948. midiInsFromXml.add (c->getStringAttribute (T("name")));
  16949. const StringArray allMidiIns (MidiInput::getDevices());
  16950. for (int i = allMidiIns.size(); --i >= 0;)
  16951. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  16952. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  16953. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  16954. false, preferredDefaultDeviceName);
  16955. setDefaultMidiOutput (e->getStringAttribute (T("defaultMidiOutput")));
  16956. return error;
  16957. }
  16958. else
  16959. {
  16960. AudioDeviceSetup setup;
  16961. if (preferredDefaultDeviceName.isNotEmpty())
  16962. {
  16963. for (int j = availableDeviceTypes.size(); --j >= 0;)
  16964. {
  16965. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  16966. StringArray outs (type->getDeviceNames (false));
  16967. int i;
  16968. for (i = 0; i < outs.size(); ++i)
  16969. {
  16970. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  16971. {
  16972. setup.outputDeviceName = outs[i];
  16973. break;
  16974. }
  16975. }
  16976. StringArray ins (type->getDeviceNames (true));
  16977. for (i = 0; i < ins.size(); ++i)
  16978. {
  16979. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  16980. {
  16981. setup.inputDeviceName = ins[i];
  16982. break;
  16983. }
  16984. }
  16985. }
  16986. }
  16987. insertDefaultDeviceNames (setup);
  16988. return setAudioDeviceSetup (setup, false);
  16989. }
  16990. }
  16991. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  16992. {
  16993. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  16994. if (type != 0)
  16995. {
  16996. if (setup.outputDeviceName.isEmpty())
  16997. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  16998. if (setup.inputDeviceName.isEmpty())
  16999. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  17000. }
  17001. }
  17002. XmlElement* AudioDeviceManager::createStateXml() const
  17003. {
  17004. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  17005. }
  17006. void AudioDeviceManager::scanDevicesIfNeeded()
  17007. {
  17008. if (listNeedsScanning)
  17009. {
  17010. listNeedsScanning = false;
  17011. createDeviceTypesIfNeeded();
  17012. for (int i = availableDeviceTypes.size(); --i >= 0;)
  17013. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  17014. }
  17015. }
  17016. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  17017. {
  17018. scanDevicesIfNeeded();
  17019. for (int i = availableDeviceTypes.size(); --i >= 0;)
  17020. {
  17021. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  17022. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  17023. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  17024. {
  17025. return type;
  17026. }
  17027. }
  17028. return 0;
  17029. }
  17030. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  17031. {
  17032. setup = currentSetup;
  17033. }
  17034. void AudioDeviceManager::deleteCurrentDevice()
  17035. {
  17036. deleteAndZero (currentAudioDevice);
  17037. currentSetup.inputDeviceName = String::empty;
  17038. currentSetup.outputDeviceName = String::empty;
  17039. }
  17040. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  17041. const bool treatAsChosenDevice)
  17042. {
  17043. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  17044. {
  17045. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  17046. && currentDeviceType != type)
  17047. {
  17048. currentDeviceType = type;
  17049. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  17050. insertDefaultDeviceNames (s);
  17051. setAudioDeviceSetup (s, treatAsChosenDevice);
  17052. sendChangeMessage (this);
  17053. break;
  17054. }
  17055. }
  17056. }
  17057. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  17058. {
  17059. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  17060. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  17061. return availableDeviceTypes[i];
  17062. return availableDeviceTypes[0];
  17063. }
  17064. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  17065. const bool treatAsChosenDevice)
  17066. {
  17067. jassert (&newSetup != &currentSetup); // this will have no effect
  17068. if (newSetup == currentSetup && currentAudioDevice != 0)
  17069. return String::empty;
  17070. if (! (newSetup == currentSetup))
  17071. sendChangeMessage (this);
  17072. stopDevice();
  17073. String error;
  17074. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  17075. if (type == 0 || (newSetup.inputDeviceName.isEmpty()
  17076. && newSetup.outputDeviceName.isEmpty()))
  17077. {
  17078. deleteCurrentDevice();
  17079. if (treatAsChosenDevice)
  17080. updateXml();
  17081. return String::empty;
  17082. }
  17083. if (currentSetup.inputDeviceName != newSetup.inputDeviceName
  17084. || currentSetup.outputDeviceName != newSetup.outputDeviceName
  17085. || currentAudioDevice == 0)
  17086. {
  17087. deleteCurrentDevice();
  17088. scanDevicesIfNeeded();
  17089. if (newSetup.outputDeviceName.isNotEmpty()
  17090. && ! type->getDeviceNames (false).contains (newSetup.outputDeviceName))
  17091. {
  17092. return "No such device: " + newSetup.outputDeviceName;
  17093. }
  17094. if (newSetup.inputDeviceName.isNotEmpty()
  17095. && ! type->getDeviceNames (true).contains (newSetup.inputDeviceName))
  17096. {
  17097. return "No such device: " + newSetup.outputDeviceName;
  17098. }
  17099. currentAudioDevice = type->createDevice (newSetup.outputDeviceName,
  17100. newSetup.inputDeviceName);
  17101. if (currentAudioDevice == 0)
  17102. error = "Can't open device";
  17103. else
  17104. error = currentAudioDevice->getLastError();
  17105. if (error.isNotEmpty())
  17106. {
  17107. deleteCurrentDevice();
  17108. return error;
  17109. }
  17110. if (newSetup.useDefaultInputChannels)
  17111. {
  17112. inputChannels.clear();
  17113. inputChannels.setRange (0, numInputChansNeeded, true);
  17114. }
  17115. if (newSetup.useDefaultOutputChannels)
  17116. {
  17117. outputChannels.clear();
  17118. outputChannels.setRange (0, numOutputChansNeeded, true);
  17119. }
  17120. }
  17121. if (! newSetup.useDefaultInputChannels)
  17122. inputChannels = newSetup.inputChannels;
  17123. if (! newSetup.useDefaultOutputChannels)
  17124. outputChannels = newSetup.outputChannels;
  17125. currentSetup = newSetup;
  17126. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  17127. error = currentAudioDevice->open (inputChannels,
  17128. outputChannels,
  17129. currentSetup.sampleRate,
  17130. currentSetup.bufferSize);
  17131. if (error.isEmpty())
  17132. {
  17133. currentDeviceType = currentAudioDevice->getTypeName();
  17134. currentAudioDevice->start (&callbackHandler);
  17135. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  17136. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  17137. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  17138. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  17139. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  17140. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  17141. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  17142. if (treatAsChosenDevice)
  17143. updateXml();
  17144. }
  17145. else
  17146. {
  17147. deleteCurrentDevice();
  17148. }
  17149. return error;
  17150. }
  17151. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  17152. {
  17153. jassert (currentAudioDevice != 0);
  17154. if (rate > 0)
  17155. {
  17156. bool ok = false;
  17157. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  17158. {
  17159. const double sr = currentAudioDevice->getSampleRate (i);
  17160. if (sr == rate)
  17161. ok = true;
  17162. }
  17163. if (! ok)
  17164. rate = 0;
  17165. }
  17166. if (rate == 0)
  17167. {
  17168. double lowestAbove44 = 0.0;
  17169. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  17170. {
  17171. const double sr = currentAudioDevice->getSampleRate (i);
  17172. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  17173. lowestAbove44 = sr;
  17174. }
  17175. if (lowestAbove44 == 0.0)
  17176. rate = currentAudioDevice->getSampleRate (0);
  17177. else
  17178. rate = lowestAbove44;
  17179. }
  17180. return rate;
  17181. }
  17182. void AudioDeviceManager::stopDevice()
  17183. {
  17184. if (currentAudioDevice != 0)
  17185. currentAudioDevice->stop();
  17186. }
  17187. void AudioDeviceManager::closeAudioDevice()
  17188. {
  17189. stopDevice();
  17190. deleteAndZero (currentAudioDevice);
  17191. }
  17192. void AudioDeviceManager::restartLastAudioDevice()
  17193. {
  17194. if (currentAudioDevice == 0)
  17195. {
  17196. if (currentSetup.inputDeviceName.isEmpty()
  17197. && currentSetup.outputDeviceName.isEmpty())
  17198. {
  17199. // This method will only reload the last device that was running
  17200. // before closeAudioDevice() was called - you need to actually open
  17201. // one first, with setAudioDevice().
  17202. jassertfalse
  17203. return;
  17204. }
  17205. AudioDeviceSetup s (currentSetup);
  17206. setAudioDeviceSetup (s, false);
  17207. }
  17208. }
  17209. void AudioDeviceManager::updateXml()
  17210. {
  17211. delete lastExplicitSettings;
  17212. lastExplicitSettings = new XmlElement (T("DEVICESETUP"));
  17213. lastExplicitSettings->setAttribute (T("deviceType"), currentDeviceType);
  17214. lastExplicitSettings->setAttribute (T("audioOutputDeviceName"), currentSetup.outputDeviceName);
  17215. lastExplicitSettings->setAttribute (T("audioInputDeviceName"), currentSetup.inputDeviceName);
  17216. if (currentAudioDevice != 0)
  17217. {
  17218. lastExplicitSettings->setAttribute (T("audioDeviceRate"), currentAudioDevice->getCurrentSampleRate());
  17219. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  17220. lastExplicitSettings->setAttribute (T("audioDeviceBufferSize"), currentAudioDevice->getCurrentBufferSizeSamples());
  17221. if (! currentSetup.useDefaultInputChannels)
  17222. lastExplicitSettings->setAttribute (T("audioDeviceInChans"), currentSetup.inputChannels.toString (2));
  17223. if (! currentSetup.useDefaultOutputChannels)
  17224. lastExplicitSettings->setAttribute (T("audioDeviceOutChans"), currentSetup.outputChannels.toString (2));
  17225. }
  17226. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  17227. {
  17228. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  17229. m->setAttribute (T("name"), enabledMidiInputs[i]->getName());
  17230. lastExplicitSettings->addChildElement (m);
  17231. }
  17232. if (midiInsFromXml.size() > 0)
  17233. {
  17234. // Add any midi devices that have been enabled before, but which aren't currently
  17235. // open because the device has been disconnected.
  17236. const StringArray availableMidiDevices (MidiInput::getDevices());
  17237. for (int i = 0; i < midiInsFromXml.size(); ++i)
  17238. {
  17239. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  17240. {
  17241. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  17242. m->setAttribute (T("name"), midiInsFromXml[i]);
  17243. lastExplicitSettings->addChildElement (m);
  17244. }
  17245. }
  17246. }
  17247. if (defaultMidiOutputName.isNotEmpty())
  17248. lastExplicitSettings->setAttribute (T("defaultMidiOutput"), defaultMidiOutputName);
  17249. }
  17250. void AudioDeviceManager::setAudioCallback (AudioIODeviceCallback* newCallback)
  17251. {
  17252. if (newCallback != currentCallback)
  17253. {
  17254. AudioIODeviceCallback* lastCallback = currentCallback;
  17255. audioCallbackLock.enter();
  17256. currentCallback = 0;
  17257. audioCallbackLock.exit();
  17258. if (currentAudioDevice != 0)
  17259. {
  17260. if (lastCallback != 0)
  17261. lastCallback->audioDeviceStopped();
  17262. if (newCallback != 0)
  17263. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  17264. }
  17265. currentCallback = newCallback;
  17266. }
  17267. }
  17268. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  17269. int numInputChannels,
  17270. float** outputChannelData,
  17271. int numOutputChannels,
  17272. int numSamples)
  17273. {
  17274. const ScopedLock sl (audioCallbackLock);
  17275. if (inputLevelMeasurementEnabled)
  17276. {
  17277. for (int j = 0; j < numSamples; ++j)
  17278. {
  17279. float s = 0;
  17280. for (int i = 0; i < numInputChannels; ++i)
  17281. s += fabsf (inputChannelData[i][j]);
  17282. s /= numInputChannels;
  17283. const double decayFactor = 0.99992;
  17284. if (s > inputLevel)
  17285. inputLevel = s;
  17286. else if (inputLevel > 0.001f)
  17287. inputLevel *= decayFactor;
  17288. else
  17289. inputLevel = 0;
  17290. }
  17291. }
  17292. if (currentCallback != 0)
  17293. {
  17294. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  17295. currentCallback->audioDeviceIOCallback (inputChannelData,
  17296. numInputChannels,
  17297. outputChannelData,
  17298. numOutputChannels,
  17299. numSamples);
  17300. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  17301. const double filterAmount = 0.2;
  17302. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  17303. }
  17304. else
  17305. {
  17306. for (int i = 0; i < numOutputChannels; ++i)
  17307. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  17308. }
  17309. if (testSound != 0)
  17310. {
  17311. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  17312. const float* const src = testSound->getSampleData (0, testSoundPosition);
  17313. for (int i = 0; i < numOutputChannels; ++i)
  17314. for (int j = 0; j < numSamps; ++j)
  17315. outputChannelData [i][j] += src[j];
  17316. testSoundPosition += numSamps;
  17317. if (testSoundPosition >= testSound->getNumSamples())
  17318. {
  17319. delete testSound;
  17320. testSound = 0;
  17321. }
  17322. }
  17323. }
  17324. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  17325. {
  17326. cpuUsageMs = 0;
  17327. const double sampleRate = device->getCurrentSampleRate();
  17328. const int blockSize = device->getCurrentBufferSizeSamples();
  17329. if (sampleRate > 0.0 && blockSize > 0)
  17330. {
  17331. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  17332. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  17333. }
  17334. if (currentCallback != 0)
  17335. currentCallback->audioDeviceAboutToStart (device);
  17336. sendChangeMessage (this);
  17337. }
  17338. void AudioDeviceManager::audioDeviceStoppedInt()
  17339. {
  17340. cpuUsageMs = 0;
  17341. timeToCpuScale = 0;
  17342. sendChangeMessage (this);
  17343. if (currentCallback != 0)
  17344. currentCallback->audioDeviceStopped();
  17345. }
  17346. double AudioDeviceManager::getCpuUsage() const
  17347. {
  17348. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  17349. }
  17350. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  17351. const bool enabled)
  17352. {
  17353. if (enabled != isMidiInputEnabled (name))
  17354. {
  17355. if (enabled)
  17356. {
  17357. const int index = MidiInput::getDevices().indexOf (name);
  17358. if (index >= 0)
  17359. {
  17360. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  17361. if (min != 0)
  17362. {
  17363. enabledMidiInputs.add (min);
  17364. min->start();
  17365. }
  17366. }
  17367. }
  17368. else
  17369. {
  17370. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17371. if (enabledMidiInputs[i]->getName() == name)
  17372. enabledMidiInputs.remove (i);
  17373. }
  17374. updateXml();
  17375. sendChangeMessage (this);
  17376. }
  17377. }
  17378. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  17379. {
  17380. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17381. if (enabledMidiInputs[i]->getName() == name)
  17382. return true;
  17383. return false;
  17384. }
  17385. void AudioDeviceManager::addMidiInputCallback (const String& name,
  17386. MidiInputCallback* callback)
  17387. {
  17388. removeMidiInputCallback (name, callback);
  17389. if (name.isEmpty())
  17390. {
  17391. midiCallbacks.add (callback);
  17392. midiCallbackDevices.add (0);
  17393. }
  17394. else
  17395. {
  17396. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17397. {
  17398. if (enabledMidiInputs[i]->getName() == name)
  17399. {
  17400. const ScopedLock sl (midiCallbackLock);
  17401. midiCallbacks.add (callback);
  17402. midiCallbackDevices.add (enabledMidiInputs[i]);
  17403. break;
  17404. }
  17405. }
  17406. }
  17407. }
  17408. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  17409. MidiInputCallback* /*callback*/)
  17410. {
  17411. const ScopedLock sl (midiCallbackLock);
  17412. for (int i = midiCallbacks.size(); --i >= 0;)
  17413. {
  17414. String devName;
  17415. if (midiCallbackDevices.getUnchecked(i) != 0)
  17416. devName = midiCallbackDevices.getUnchecked(i)->getName();
  17417. if (devName == name)
  17418. {
  17419. midiCallbacks.remove (i);
  17420. midiCallbackDevices.remove (i);
  17421. }
  17422. }
  17423. }
  17424. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  17425. const MidiMessage& message)
  17426. {
  17427. if (! message.isActiveSense())
  17428. {
  17429. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  17430. const ScopedLock sl (midiCallbackLock);
  17431. for (int i = midiCallbackDevices.size(); --i >= 0;)
  17432. {
  17433. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  17434. if (md == source || (md == 0 && isDefaultSource))
  17435. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  17436. }
  17437. }
  17438. }
  17439. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  17440. {
  17441. if (defaultMidiOutputName != deviceName)
  17442. {
  17443. deleteAndZero (defaultMidiOutput);
  17444. defaultMidiOutputName = deviceName;
  17445. if (deviceName.isNotEmpty())
  17446. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  17447. updateXml();
  17448. sendChangeMessage (this);
  17449. }
  17450. }
  17451. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  17452. int numInputChannels,
  17453. float** outputChannelData,
  17454. int numOutputChannels,
  17455. int numSamples)
  17456. {
  17457. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  17458. }
  17459. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  17460. {
  17461. owner->audioDeviceAboutToStartInt (device);
  17462. }
  17463. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  17464. {
  17465. owner->audioDeviceStoppedInt();
  17466. }
  17467. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  17468. {
  17469. owner->handleIncomingMidiMessageInt (source, message);
  17470. }
  17471. void AudioDeviceManager::playTestSound()
  17472. {
  17473. audioCallbackLock.enter();
  17474. AudioSampleBuffer* oldSound = testSound;
  17475. testSound = 0;
  17476. audioCallbackLock.exit();
  17477. delete oldSound;
  17478. testSoundPosition = 0;
  17479. if (currentAudioDevice != 0)
  17480. {
  17481. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  17482. const int soundLength = (int) sampleRate;
  17483. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  17484. float* samples = newSound->getSampleData (0);
  17485. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  17486. const float amplitude = 0.5f;
  17487. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  17488. for (int i = 0; i < soundLength; ++i)
  17489. samples[i] = amplitude * (float) sin (i * phasePerSample);
  17490. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  17491. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  17492. const ScopedLock sl (audioCallbackLock);
  17493. testSound = newSound;
  17494. }
  17495. }
  17496. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  17497. {
  17498. if (inputLevelMeasurementEnabled != enableMeasurement)
  17499. {
  17500. const ScopedLock sl (audioCallbackLock);
  17501. inputLevelMeasurementEnabled = enableMeasurement;
  17502. inputLevel = 0;
  17503. }
  17504. }
  17505. double AudioDeviceManager::getCurrentInputLevel() const
  17506. {
  17507. jassert (inputLevelMeasurementEnabled); // you need to call enableInputLevelMeasurement() before using this!
  17508. return inputLevel;
  17509. }
  17510. END_JUCE_NAMESPACE
  17511. /********* End of inlined file: juce_AudioDeviceManager.cpp *********/
  17512. /********* Start of inlined file: juce_AudioIODevice.cpp *********/
  17513. BEGIN_JUCE_NAMESPACE
  17514. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  17515. : name (deviceName),
  17516. typeName (typeName_)
  17517. {
  17518. }
  17519. AudioIODevice::~AudioIODevice()
  17520. {
  17521. }
  17522. bool AudioIODevice::hasControlPanel() const
  17523. {
  17524. return false;
  17525. }
  17526. bool AudioIODevice::showControlPanel()
  17527. {
  17528. jassertfalse // this should only be called for devices which return true from
  17529. // their hasControlPanel() method.
  17530. return false;
  17531. }
  17532. END_JUCE_NAMESPACE
  17533. /********* End of inlined file: juce_AudioIODevice.cpp *********/
  17534. /********* Start of inlined file: juce_AudioIODeviceType.cpp *********/
  17535. BEGIN_JUCE_NAMESPACE
  17536. AudioIODeviceType::AudioIODeviceType (const tchar* const name)
  17537. : typeName (name)
  17538. {
  17539. }
  17540. AudioIODeviceType::~AudioIODeviceType()
  17541. {
  17542. }
  17543. END_JUCE_NAMESPACE
  17544. /********* End of inlined file: juce_AudioIODeviceType.cpp *********/
  17545. /********* Start of inlined file: juce_MidiOutput.cpp *********/
  17546. BEGIN_JUCE_NAMESPACE
  17547. MidiOutput::MidiOutput() throw()
  17548. : Thread ("midi out"),
  17549. internal (0),
  17550. firstMessage (0)
  17551. {
  17552. }
  17553. MidiOutput::PendingMessage::PendingMessage (const uint8* const data,
  17554. const int len,
  17555. const double sampleNumber) throw()
  17556. : message (data, len, sampleNumber)
  17557. {
  17558. }
  17559. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  17560. const double millisecondCounterToStartAt,
  17561. double samplesPerSecondForBuffer) throw()
  17562. {
  17563. // You've got to call startBackgroundThread() for this to actually work..
  17564. jassert (isThreadRunning());
  17565. // this needs to be a value in the future - RTFM for this method!
  17566. jassert (millisecondCounterToStartAt > 0);
  17567. samplesPerSecondForBuffer *= 0.001;
  17568. MidiBuffer::Iterator i (buffer);
  17569. const uint8* data;
  17570. int len, time;
  17571. while (i.getNextEvent (data, len, time))
  17572. {
  17573. const double eventTime = millisecondCounterToStartAt + samplesPerSecondForBuffer * time;
  17574. PendingMessage* const m
  17575. = new PendingMessage (data, len, eventTime);
  17576. const ScopedLock sl (lock);
  17577. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  17578. {
  17579. m->next = firstMessage;
  17580. firstMessage = m;
  17581. }
  17582. else
  17583. {
  17584. PendingMessage* mm = firstMessage;
  17585. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  17586. mm = mm->next;
  17587. m->next = mm->next;
  17588. mm->next = m;
  17589. }
  17590. }
  17591. notify();
  17592. }
  17593. void MidiOutput::clearAllPendingMessages() throw()
  17594. {
  17595. const ScopedLock sl (lock);
  17596. while (firstMessage != 0)
  17597. {
  17598. PendingMessage* const m = firstMessage;
  17599. firstMessage = firstMessage->next;
  17600. delete m;
  17601. }
  17602. }
  17603. void MidiOutput::startBackgroundThread() throw()
  17604. {
  17605. startThread (9);
  17606. }
  17607. void MidiOutput::stopBackgroundThread() throw()
  17608. {
  17609. stopThread (5000);
  17610. }
  17611. void MidiOutput::run()
  17612. {
  17613. while (! threadShouldExit())
  17614. {
  17615. uint32 now = Time::getMillisecondCounter();
  17616. uint32 eventTime = 0;
  17617. uint32 timeToWait = 500;
  17618. lock.enter();
  17619. PendingMessage* message = firstMessage;
  17620. if (message != 0)
  17621. {
  17622. eventTime = roundDoubleToInt (message->message.getTimeStamp());
  17623. if (eventTime > now + 20)
  17624. {
  17625. timeToWait = jmax (10, eventTime - now - 100);
  17626. message = 0;
  17627. }
  17628. else
  17629. {
  17630. firstMessage = message->next;
  17631. }
  17632. }
  17633. lock.exit();
  17634. if (message != 0)
  17635. {
  17636. if (eventTime > now)
  17637. {
  17638. Time::waitForMillisecondCounter (eventTime);
  17639. if (threadShouldExit())
  17640. break;
  17641. }
  17642. if (eventTime > now - 200)
  17643. sendMessageNow (message->message);
  17644. delete message;
  17645. }
  17646. else
  17647. {
  17648. jassert (timeToWait < 1000 * 30);
  17649. wait (timeToWait);
  17650. }
  17651. }
  17652. clearAllPendingMessages();
  17653. }
  17654. END_JUCE_NAMESPACE
  17655. /********* End of inlined file: juce_MidiOutput.cpp *********/
  17656. /********* Start of inlined file: juce_AudioDataConverters.cpp *********/
  17657. BEGIN_JUCE_NAMESPACE
  17658. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17659. {
  17660. const double maxVal = (double) 0x7fff;
  17661. char* intData = (char*) dest;
  17662. for (int i = 0; i < numSamples; ++i)
  17663. {
  17664. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17665. intData += destBytesPerSample;
  17666. }
  17667. }
  17668. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17669. {
  17670. const double maxVal = (double) 0x7fff;
  17671. char* intData = (char*) dest;
  17672. for (int i = 0; i < numSamples; ++i)
  17673. {
  17674. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17675. intData += destBytesPerSample;
  17676. }
  17677. }
  17678. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17679. {
  17680. const double maxVal = (double) 0x7fffff;
  17681. char* intData = (char*) dest;
  17682. for (int i = 0; i < numSamples; ++i)
  17683. {
  17684. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  17685. intData += destBytesPerSample;
  17686. }
  17687. }
  17688. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17689. {
  17690. const double maxVal = (double) 0x7fffff;
  17691. char* intData = (char*) dest;
  17692. for (int i = 0; i < numSamples; ++i)
  17693. {
  17694. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  17695. intData += destBytesPerSample;
  17696. }
  17697. }
  17698. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17699. {
  17700. const double maxVal = (double) 0x7fffffff;
  17701. char* intData = (char*) dest;
  17702. for (int i = 0; i < numSamples; ++i)
  17703. {
  17704. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17705. intData += destBytesPerSample;
  17706. }
  17707. }
  17708. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17709. {
  17710. const double maxVal = (double) 0x7fffffff;
  17711. char* intData = (char*) dest;
  17712. for (int i = 0; i < numSamples; ++i)
  17713. {
  17714. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17715. intData += destBytesPerSample;
  17716. }
  17717. }
  17718. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17719. {
  17720. char* d = (char*) dest;
  17721. for (int i = 0; i < numSamples; ++i)
  17722. {
  17723. *(float*)d = source[i];
  17724. #if JUCE_BIG_ENDIAN
  17725. *(uint32*)d = swapByteOrder (*(uint32*)d);
  17726. #endif
  17727. d += destBytesPerSample;
  17728. }
  17729. }
  17730. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17731. {
  17732. char* d = (char*) dest;
  17733. for (int i = 0; i < numSamples; ++i)
  17734. {
  17735. *(float*)d = source[i];
  17736. #if JUCE_LITTLE_ENDIAN
  17737. *(uint32*)d = swapByteOrder (*(uint32*)d);
  17738. #endif
  17739. d += destBytesPerSample;
  17740. }
  17741. }
  17742. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17743. {
  17744. const float scale = 1.0f / 0x7fff;
  17745. const char* intData = (const char*) source;
  17746. for (int i = 0; i < numSamples; ++i)
  17747. {
  17748. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  17749. intData += srcBytesPerSample;
  17750. }
  17751. }
  17752. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17753. {
  17754. const float scale = 1.0f / 0x7fff;
  17755. const char* intData = (const char*) source;
  17756. for (int i = 0; i < numSamples; ++i)
  17757. {
  17758. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  17759. intData += srcBytesPerSample;
  17760. }
  17761. }
  17762. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17763. {
  17764. const float scale = 1.0f / 0x7fffff;
  17765. const char* intData = (const char*) source;
  17766. for (int i = 0; i < numSamples; ++i)
  17767. {
  17768. dest[i] = scale * (short) littleEndian24Bit (intData);
  17769. intData += srcBytesPerSample;
  17770. }
  17771. }
  17772. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17773. {
  17774. const float scale = 1.0f / 0x7fffff;
  17775. const char* intData = (const char*) source;
  17776. for (int i = 0; i < numSamples; ++i)
  17777. {
  17778. dest[i] = scale * (short) bigEndian24Bit (intData);
  17779. intData += srcBytesPerSample;
  17780. }
  17781. }
  17782. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17783. {
  17784. const float scale = 1.0f / 0x7fffffff;
  17785. const char* intData = (const char*) source;
  17786. for (int i = 0; i < numSamples; ++i)
  17787. {
  17788. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  17789. intData += srcBytesPerSample;
  17790. }
  17791. }
  17792. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17793. {
  17794. const float scale = 1.0f / 0x7fffffff;
  17795. const char* intData = (const char*) source;
  17796. for (int i = 0; i < numSamples; ++i)
  17797. {
  17798. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  17799. intData += srcBytesPerSample;
  17800. }
  17801. }
  17802. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17803. {
  17804. const char* s = (const char*) source;
  17805. for (int i = 0; i < numSamples; ++i)
  17806. {
  17807. dest[i] = *(float*)s;
  17808. #if JUCE_BIG_ENDIAN
  17809. uint32* const d = (uint32*) (dest + i);
  17810. *d = swapByteOrder (*d);
  17811. #endif
  17812. s += srcBytesPerSample;
  17813. }
  17814. }
  17815. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17816. {
  17817. const char* s = (const char*) source;
  17818. for (int i = 0; i < numSamples; ++i)
  17819. {
  17820. dest[i] = *(float*)s;
  17821. #if JUCE_LITTLE_ENDIAN
  17822. uint32* const d = (uint32*) (dest + i);
  17823. *d = swapByteOrder (*d);
  17824. #endif
  17825. s += srcBytesPerSample;
  17826. }
  17827. }
  17828. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  17829. const float* const source,
  17830. void* const dest,
  17831. const int numSamples)
  17832. {
  17833. switch (destFormat)
  17834. {
  17835. case int16LE:
  17836. convertFloatToInt16LE (source, dest, numSamples);
  17837. break;
  17838. case int16BE:
  17839. convertFloatToInt16BE (source, dest, numSamples);
  17840. break;
  17841. case int24LE:
  17842. convertFloatToInt24LE (source, dest, numSamples);
  17843. break;
  17844. case int24BE:
  17845. convertFloatToInt24BE (source, dest, numSamples);
  17846. break;
  17847. case int32LE:
  17848. convertFloatToInt32LE (source, dest, numSamples);
  17849. break;
  17850. case int32BE:
  17851. convertFloatToInt32BE (source, dest, numSamples);
  17852. break;
  17853. case float32LE:
  17854. convertFloatToFloat32LE (source, dest, numSamples);
  17855. break;
  17856. case float32BE:
  17857. convertFloatToFloat32BE (source, dest, numSamples);
  17858. break;
  17859. default:
  17860. jassertfalse
  17861. break;
  17862. }
  17863. }
  17864. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  17865. const void* const source,
  17866. float* const dest,
  17867. const int numSamples)
  17868. {
  17869. switch (sourceFormat)
  17870. {
  17871. case int16LE:
  17872. convertInt16LEToFloat (source, dest, numSamples);
  17873. break;
  17874. case int16BE:
  17875. convertInt16BEToFloat (source, dest, numSamples);
  17876. break;
  17877. case int24LE:
  17878. convertInt24LEToFloat (source, dest, numSamples);
  17879. break;
  17880. case int24BE:
  17881. convertInt24BEToFloat (source, dest, numSamples);
  17882. break;
  17883. case int32LE:
  17884. convertInt32LEToFloat (source, dest, numSamples);
  17885. break;
  17886. case int32BE:
  17887. convertInt32BEToFloat (source, dest, numSamples);
  17888. break;
  17889. case float32LE:
  17890. convertFloat32LEToFloat (source, dest, numSamples);
  17891. break;
  17892. case float32BE:
  17893. convertFloat32BEToFloat (source, dest, numSamples);
  17894. break;
  17895. default:
  17896. jassertfalse
  17897. break;
  17898. }
  17899. }
  17900. void AudioDataConverters::interleaveSamples (const float** const source,
  17901. float* const dest,
  17902. const int numSamples,
  17903. const int numChannels)
  17904. {
  17905. for (int chan = 0; chan < numChannels; ++chan)
  17906. {
  17907. int i = chan;
  17908. const float* src = source [chan];
  17909. for (int j = 0; j < numSamples; ++j)
  17910. {
  17911. dest [i] = src [j];
  17912. i += numChannels;
  17913. }
  17914. }
  17915. }
  17916. void AudioDataConverters::deinterleaveSamples (const float* const source,
  17917. float** const dest,
  17918. const int numSamples,
  17919. const int numChannels)
  17920. {
  17921. for (int chan = 0; chan < numChannels; ++chan)
  17922. {
  17923. int i = chan;
  17924. float* dst = dest [chan];
  17925. for (int j = 0; j < numSamples; ++j)
  17926. {
  17927. dst [j] = source [i];
  17928. i += numChannels;
  17929. }
  17930. }
  17931. }
  17932. END_JUCE_NAMESPACE
  17933. /********* End of inlined file: juce_AudioDataConverters.cpp *********/
  17934. /********* Start of inlined file: juce_AudioSampleBuffer.cpp *********/
  17935. BEGIN_JUCE_NAMESPACE
  17936. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  17937. const int numSamples) throw()
  17938. : numChannels (numChannels_),
  17939. size (numSamples)
  17940. {
  17941. jassert (numSamples >= 0);
  17942. jassert (numChannels_ > 0 && numChannels_ <= maxNumAudioSampleBufferChannels);
  17943. allocatedBytes = numChannels * numSamples * sizeof (float) + 32;
  17944. allocatedData = (float*) juce_malloc (allocatedBytes);
  17945. float* chan = allocatedData;
  17946. for (int i = 0; i < numChannels_; ++i)
  17947. {
  17948. channels[i] = chan;
  17949. chan += numSamples;
  17950. }
  17951. channels [numChannels_] = 0;
  17952. }
  17953. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  17954. const int numChannels_,
  17955. const int numSamples) throw()
  17956. : numChannels (numChannels_),
  17957. size (numSamples),
  17958. allocatedBytes (0),
  17959. allocatedData (0)
  17960. {
  17961. jassert (((unsigned int) numChannels_) <= (unsigned int) maxNumAudioSampleBufferChannels);
  17962. for (int i = 0; i < numChannels_; ++i)
  17963. {
  17964. // you have to pass in the same number of valid pointers as numChannels
  17965. jassert (dataToReferTo[i] != 0);
  17966. channels[i] = dataToReferTo[i];
  17967. }
  17968. channels [numChannels_] = 0;
  17969. }
  17970. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  17971. const int numChannels_,
  17972. const int numSamples) throw()
  17973. {
  17974. jassert (((unsigned int) numChannels_) <= (unsigned int) maxNumAudioSampleBufferChannels);
  17975. juce_free (allocatedData);
  17976. allocatedData = 0;
  17977. allocatedBytes = 0;
  17978. numChannels = numChannels_;
  17979. size = numSamples;
  17980. for (int i = 0; i < numChannels_; ++i)
  17981. {
  17982. // you have to pass in the same number of valid pointers as numChannels
  17983. jassert (dataToReferTo[i] != 0);
  17984. channels[i] = dataToReferTo[i];
  17985. }
  17986. channels [numChannels_] = 0;
  17987. }
  17988. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  17989. : numChannels (other.numChannels),
  17990. size (other.size)
  17991. {
  17992. if (other.allocatedData != 0)
  17993. {
  17994. allocatedBytes = numChannels * size * sizeof (float) + 32;
  17995. allocatedData = (float*) juce_malloc (allocatedBytes);
  17996. memcpy (allocatedData, other.allocatedData, allocatedBytes);
  17997. float* chan = allocatedData;
  17998. for (int i = 0; i < numChannels; ++i)
  17999. {
  18000. channels[i] = chan;
  18001. chan += size;
  18002. }
  18003. channels [numChannels] = 0;
  18004. }
  18005. else
  18006. {
  18007. allocatedData = 0;
  18008. allocatedBytes = 0;
  18009. memcpy (channels, other.channels, sizeof (channels));
  18010. }
  18011. }
  18012. const AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  18013. {
  18014. if (this != &other)
  18015. {
  18016. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  18017. const int numBytes = size * sizeof (float);
  18018. for (int i = 0; i < numChannels; ++i)
  18019. memcpy (channels[i], other.channels[i], numBytes);
  18020. }
  18021. return *this;
  18022. }
  18023. AudioSampleBuffer::~AudioSampleBuffer() throw()
  18024. {
  18025. juce_free (allocatedData);
  18026. }
  18027. float* AudioSampleBuffer::getSampleData (const int channelNumber,
  18028. const int sampleOffset) const throw()
  18029. {
  18030. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  18031. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  18032. return channels [channelNumber] + sampleOffset;
  18033. }
  18034. void AudioSampleBuffer::setSize (const int newNumChannels,
  18035. const int newNumSamples,
  18036. const bool keepExistingContent,
  18037. const bool clearExtraSpace,
  18038. const bool avoidReallocating) throw()
  18039. {
  18040. jassert (newNumChannels > 0 && newNumChannels <= maxNumAudioSampleBufferChannels);
  18041. if (newNumSamples != size || newNumChannels != numChannels)
  18042. {
  18043. const int newTotalBytes = newNumChannels * newNumSamples * sizeof (float) + 32;
  18044. if (keepExistingContent)
  18045. {
  18046. float* const newData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  18047. : (float*) juce_malloc (newTotalBytes);
  18048. const int sizeToCopy = sizeof (float) * jmin (newNumSamples, size);
  18049. for (int i = jmin (newNumChannels, numChannels); --i >= 0;)
  18050. {
  18051. memcpy (newData + i * newNumSamples,
  18052. channels[i],
  18053. sizeToCopy);
  18054. }
  18055. juce_free (allocatedData);
  18056. allocatedData = newData;
  18057. allocatedBytes = newTotalBytes;
  18058. }
  18059. else
  18060. {
  18061. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  18062. {
  18063. if (clearExtraSpace)
  18064. zeromem (allocatedData, newTotalBytes);
  18065. }
  18066. else
  18067. {
  18068. juce_free (allocatedData);
  18069. allocatedData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  18070. : (float*) juce_malloc (newTotalBytes);
  18071. allocatedBytes = newTotalBytes;
  18072. }
  18073. }
  18074. size = newNumSamples;
  18075. numChannels = newNumChannels;
  18076. float* chan = allocatedData;
  18077. for (int i = 0; i < newNumChannels; ++i)
  18078. {
  18079. channels[i] = chan;
  18080. chan += size;
  18081. }
  18082. channels [newNumChannels] = 0;
  18083. }
  18084. }
  18085. void AudioSampleBuffer::clear() throw()
  18086. {
  18087. for (int i = 0; i < numChannels; ++i)
  18088. zeromem (channels[i], size * sizeof (float));
  18089. }
  18090. void AudioSampleBuffer::clear (const int startSample,
  18091. const int numSamples) throw()
  18092. {
  18093. jassert (startSample >= 0 && startSample + numSamples <= size);
  18094. for (int i = 0; i < numChannels; ++i)
  18095. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  18096. }
  18097. void AudioSampleBuffer::clear (const int channel,
  18098. const int startSample,
  18099. const int numSamples) throw()
  18100. {
  18101. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18102. jassert (startSample >= 0 && startSample + numSamples <= size);
  18103. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  18104. }
  18105. void AudioSampleBuffer::applyGain (const int channel,
  18106. const int startSample,
  18107. int numSamples,
  18108. const float gain) throw()
  18109. {
  18110. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18111. jassert (startSample >= 0 && startSample + numSamples <= size);
  18112. if (gain != 1.0f)
  18113. {
  18114. float* d = channels [channel] + startSample;
  18115. if (gain == 0.0f)
  18116. {
  18117. zeromem (d, sizeof (float) * numSamples);
  18118. }
  18119. else
  18120. {
  18121. while (--numSamples >= 0)
  18122. *d++ *= gain;
  18123. }
  18124. }
  18125. }
  18126. void AudioSampleBuffer::applyGainRamp (const int channel,
  18127. const int startSample,
  18128. int numSamples,
  18129. float startGain,
  18130. float endGain) throw()
  18131. {
  18132. if (startGain == endGain)
  18133. {
  18134. applyGain (channel, startSample, numSamples, startGain);
  18135. }
  18136. else
  18137. {
  18138. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18139. jassert (startSample >= 0 && startSample + numSamples <= size);
  18140. const float increment = (endGain - startGain) / numSamples;
  18141. float* d = channels [channel] + startSample;
  18142. while (--numSamples >= 0)
  18143. {
  18144. *d++ *= startGain;
  18145. startGain += increment;
  18146. }
  18147. }
  18148. }
  18149. void AudioSampleBuffer::applyGain (const int startSample,
  18150. const int numSamples,
  18151. const float gain) throw()
  18152. {
  18153. for (int i = 0; i < numChannels; ++i)
  18154. applyGain (i, startSample, numSamples, gain);
  18155. }
  18156. void AudioSampleBuffer::addFrom (const int destChannel,
  18157. const int destStartSample,
  18158. const AudioSampleBuffer& source,
  18159. const int sourceChannel,
  18160. const int sourceStartSample,
  18161. int numSamples,
  18162. const float gain) throw()
  18163. {
  18164. jassert (&source != this || sourceChannel != destChannel);
  18165. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18166. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18167. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  18168. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  18169. if (gain != 0.0f && numSamples > 0)
  18170. {
  18171. float* d = channels [destChannel] + destStartSample;
  18172. const float* s = source.channels [sourceChannel] + sourceStartSample;
  18173. if (gain != 1.0f)
  18174. {
  18175. while (--numSamples >= 0)
  18176. *d++ += gain * *s++;
  18177. }
  18178. else
  18179. {
  18180. while (--numSamples >= 0)
  18181. *d++ += *s++;
  18182. }
  18183. }
  18184. }
  18185. void AudioSampleBuffer::addFrom (const int destChannel,
  18186. const int destStartSample,
  18187. const float* source,
  18188. int numSamples,
  18189. const float gain) throw()
  18190. {
  18191. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18192. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18193. jassert (source != 0);
  18194. if (gain != 0.0f && numSamples > 0)
  18195. {
  18196. float* d = channels [destChannel] + destStartSample;
  18197. if (gain != 1.0f)
  18198. {
  18199. while (--numSamples >= 0)
  18200. *d++ += gain * *source++;
  18201. }
  18202. else
  18203. {
  18204. while (--numSamples >= 0)
  18205. *d++ += *source++;
  18206. }
  18207. }
  18208. }
  18209. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  18210. const int destStartSample,
  18211. const float* source,
  18212. int numSamples,
  18213. float startGain,
  18214. const float endGain) throw()
  18215. {
  18216. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18217. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18218. jassert (source != 0);
  18219. if (startGain == endGain)
  18220. {
  18221. addFrom (destChannel,
  18222. destStartSample,
  18223. source,
  18224. numSamples,
  18225. startGain);
  18226. }
  18227. else
  18228. {
  18229. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  18230. {
  18231. const float increment = (endGain - startGain) / numSamples;
  18232. float* d = channels [destChannel] + destStartSample;
  18233. while (--numSamples >= 0)
  18234. {
  18235. *d++ += startGain * *source++;
  18236. startGain += increment;
  18237. }
  18238. }
  18239. }
  18240. }
  18241. void AudioSampleBuffer::copyFrom (const int destChannel,
  18242. const int destStartSample,
  18243. const AudioSampleBuffer& source,
  18244. const int sourceChannel,
  18245. const int sourceStartSample,
  18246. int numSamples) throw()
  18247. {
  18248. jassert (&source != this || sourceChannel != destChannel);
  18249. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18250. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18251. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  18252. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  18253. if (numSamples > 0)
  18254. {
  18255. memcpy (channels [destChannel] + destStartSample,
  18256. source.channels [sourceChannel] + sourceStartSample,
  18257. sizeof (float) * numSamples);
  18258. }
  18259. }
  18260. void AudioSampleBuffer::copyFrom (const int destChannel,
  18261. const int destStartSample,
  18262. const float* source,
  18263. int numSamples) throw()
  18264. {
  18265. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18266. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18267. jassert (source != 0);
  18268. if (numSamples > 0)
  18269. {
  18270. memcpy (channels [destChannel] + destStartSample,
  18271. source,
  18272. sizeof (float) * numSamples);
  18273. }
  18274. }
  18275. void AudioSampleBuffer::findMinMax (const int channel,
  18276. const int startSample,
  18277. int numSamples,
  18278. float& minVal,
  18279. float& maxVal) const throw()
  18280. {
  18281. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18282. jassert (startSample >= 0 && startSample + numSamples <= size);
  18283. if (numSamples <= 0)
  18284. {
  18285. minVal = 0.0f;
  18286. maxVal = 0.0f;
  18287. }
  18288. else
  18289. {
  18290. const float* d = channels [channel] + startSample;
  18291. float mn = *d++;
  18292. float mx = mn;
  18293. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  18294. {
  18295. const float samp = *d++;
  18296. if (samp > mx)
  18297. mx = samp;
  18298. if (samp < mn)
  18299. mn = samp;
  18300. }
  18301. maxVal = mx;
  18302. minVal = mn;
  18303. }
  18304. }
  18305. float AudioSampleBuffer::getMagnitude (const int channel,
  18306. const int startSample,
  18307. const int numSamples) const throw()
  18308. {
  18309. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18310. jassert (startSample >= 0 && startSample + numSamples <= size);
  18311. float mn, mx;
  18312. findMinMax (channel, startSample, numSamples, mn, mx);
  18313. return jmax (mn, -mn, mx, -mx);
  18314. }
  18315. float AudioSampleBuffer::getMagnitude (const int startSample,
  18316. const int numSamples) const throw()
  18317. {
  18318. float mag = 0.0f;
  18319. for (int i = 0; i < numChannels; ++i)
  18320. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  18321. return mag;
  18322. }
  18323. float AudioSampleBuffer::getRMSLevel (const int channel,
  18324. const int startSample,
  18325. const int numSamples) const throw()
  18326. {
  18327. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18328. jassert (startSample >= 0 && startSample + numSamples <= size);
  18329. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  18330. return 0.0f;
  18331. const float* const data = channels [channel] + startSample;
  18332. double sum = 0.0;
  18333. for (int i = 0; i < numSamples; ++i)
  18334. {
  18335. const float sample = data [i];
  18336. sum += sample * sample;
  18337. }
  18338. return (float) sqrt (sum / numSamples);
  18339. }
  18340. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  18341. const int startSample,
  18342. const int numSamples,
  18343. const int readerStartSample,
  18344. const bool useLeftChan,
  18345. const bool useRightChan) throw()
  18346. {
  18347. jassert (reader != 0);
  18348. jassert (startSample >= 0 && startSample + numSamples <= size);
  18349. if (numSamples > 0)
  18350. {
  18351. int* chans[3];
  18352. if (useLeftChan == useRightChan)
  18353. {
  18354. chans[0] = (int*) getSampleData (0, startSample);
  18355. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  18356. }
  18357. else if (useLeftChan || (reader->numChannels == 1))
  18358. {
  18359. chans[0] = (int*) getSampleData (0, startSample);
  18360. chans[1] = 0;
  18361. }
  18362. else if (useRightChan)
  18363. {
  18364. chans[0] = 0;
  18365. chans[1] = (int*) getSampleData (0, startSample);
  18366. }
  18367. chans[2] = 0;
  18368. reader->read (chans, readerStartSample, numSamples);
  18369. if (! reader->usesFloatingPointData)
  18370. {
  18371. for (int j = 0; j < 2; ++j)
  18372. {
  18373. float* const d = (float*) (chans[j]);
  18374. if (d != 0)
  18375. {
  18376. const float multiplier = 1.0f / 0x7fffffff;
  18377. for (int i = 0; i < numSamples; ++i)
  18378. d[i] = *(int*)(d + i) * multiplier;
  18379. }
  18380. }
  18381. }
  18382. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  18383. {
  18384. // if this is a stereo buffer and the source was mono, dupe the first channel..
  18385. memcpy (getSampleData (1, startSample),
  18386. getSampleData (0, startSample),
  18387. sizeof (float) * numSamples);
  18388. }
  18389. }
  18390. }
  18391. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  18392. const int startSample,
  18393. const int numSamples) const throw()
  18394. {
  18395. jassert (startSample >= 0 && startSample + numSamples <= size);
  18396. if (numSamples > 0)
  18397. {
  18398. int* chans [3];
  18399. if (writer->isFloatingPoint())
  18400. {
  18401. chans[0] = (int*) getSampleData (0, startSample);
  18402. if (numChannels > 1)
  18403. chans[1] = (int*) getSampleData (1, startSample);
  18404. else
  18405. chans[1] = 0;
  18406. chans[2] = 0;
  18407. writer->write ((const int**) chans, numSamples);
  18408. }
  18409. else
  18410. {
  18411. chans[0] = (int*) juce_malloc (sizeof (int) * numSamples * 2);
  18412. if (numChannels > 1)
  18413. chans[1] = chans[0] + numSamples;
  18414. else
  18415. chans[1] = 0;
  18416. chans[2] = 0;
  18417. for (int j = 0; j < 2; ++j)
  18418. {
  18419. int* const dest = chans[j];
  18420. if (dest != 0)
  18421. {
  18422. const float* const src = channels [j] + startSample;
  18423. for (int i = 0; i < numSamples; ++i)
  18424. {
  18425. const double samp = src[i];
  18426. if (samp <= -1.0)
  18427. dest[i] = INT_MIN;
  18428. else if (samp >= 1.0)
  18429. dest[i] = INT_MAX;
  18430. else
  18431. dest[i] = roundDoubleToInt (INT_MAX * samp);
  18432. }
  18433. }
  18434. }
  18435. writer->write ((const int**) chans, numSamples);
  18436. juce_free (chans[0]);
  18437. }
  18438. }
  18439. }
  18440. END_JUCE_NAMESPACE
  18441. /********* End of inlined file: juce_AudioSampleBuffer.cpp *********/
  18442. /********* Start of inlined file: juce_IIRFilter.cpp *********/
  18443. BEGIN_JUCE_NAMESPACE
  18444. IIRFilter::IIRFilter() throw()
  18445. : active (false)
  18446. {
  18447. reset();
  18448. }
  18449. IIRFilter::IIRFilter (const IIRFilter& other) throw()
  18450. : active (other.active)
  18451. {
  18452. const ScopedLock sl (other.processLock);
  18453. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  18454. reset();
  18455. }
  18456. IIRFilter::~IIRFilter() throw()
  18457. {
  18458. }
  18459. void IIRFilter::reset() throw()
  18460. {
  18461. const ScopedLock sl (processLock);
  18462. x1 = 0;
  18463. x2 = 0;
  18464. y1 = 0;
  18465. y2 = 0;
  18466. }
  18467. void IIRFilter::processSamples (float* const samples,
  18468. const int numSamples) throw()
  18469. {
  18470. const ScopedLock sl (processLock);
  18471. if (active)
  18472. {
  18473. for (int i = 0; i < numSamples; ++i)
  18474. {
  18475. const float in = samples[i];
  18476. float out = coefficients[0] * in
  18477. + coefficients[1] * x1
  18478. + coefficients[2] * x2
  18479. - coefficients[4] * y1
  18480. - coefficients[5] * y2;
  18481. #if JUCE_INTEL
  18482. if (! (out < -1.0e-8 || out > 1.0e-8))
  18483. out = 0;
  18484. #endif
  18485. x2 = x1;
  18486. x1 = in;
  18487. y2 = y1;
  18488. y1 = out;
  18489. samples[i] = out;
  18490. }
  18491. }
  18492. }
  18493. void IIRFilter::makeLowPass (const double sampleRate,
  18494. const double frequency) throw()
  18495. {
  18496. jassert (sampleRate > 0);
  18497. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  18498. const double nSquared = n * n;
  18499. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  18500. setCoefficients (c1,
  18501. c1 * 2.0f,
  18502. c1,
  18503. 1.0,
  18504. c1 * 2.0 * (1.0 - nSquared),
  18505. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  18506. }
  18507. void IIRFilter::makeHighPass (const double sampleRate,
  18508. const double frequency) throw()
  18509. {
  18510. const double n = tan (double_Pi * frequency / sampleRate);
  18511. const double nSquared = n * n;
  18512. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  18513. setCoefficients (c1,
  18514. c1 * -2.0f,
  18515. c1,
  18516. 1.0,
  18517. c1 * 2.0 * (nSquared - 1.0),
  18518. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  18519. }
  18520. void IIRFilter::makeLowShelf (const double sampleRate,
  18521. const double cutOffFrequency,
  18522. const double Q,
  18523. const float gainFactor) throw()
  18524. {
  18525. jassert (sampleRate > 0);
  18526. jassert (Q > 0);
  18527. const double A = jmax (0.0f, gainFactor);
  18528. const double aminus1 = A - 1.0;
  18529. const double aplus1 = A + 1.0;
  18530. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  18531. const double coso = cos (omega);
  18532. const double beta = sin (omega) * sqrt (A) / Q;
  18533. const double aminus1TimesCoso = aminus1 * coso;
  18534. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  18535. A * 2.0 * (aminus1 - aplus1 * coso),
  18536. A * (aplus1 - aminus1TimesCoso - beta),
  18537. aplus1 + aminus1TimesCoso + beta,
  18538. -2.0 * (aminus1 + aplus1 * coso),
  18539. aplus1 + aminus1TimesCoso - beta);
  18540. }
  18541. void IIRFilter::makeHighShelf (const double sampleRate,
  18542. const double cutOffFrequency,
  18543. const double Q,
  18544. const float gainFactor) throw()
  18545. {
  18546. jassert (sampleRate > 0);
  18547. jassert (Q > 0);
  18548. const double A = jmax (0.0f, gainFactor);
  18549. const double aminus1 = A - 1.0;
  18550. const double aplus1 = A + 1.0;
  18551. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  18552. const double coso = cos (omega);
  18553. const double beta = sin (omega) * sqrt (A) / Q;
  18554. const double aminus1TimesCoso = aminus1 * coso;
  18555. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  18556. A * -2.0 * (aminus1 + aplus1 * coso),
  18557. A * (aplus1 + aminus1TimesCoso - beta),
  18558. aplus1 - aminus1TimesCoso + beta,
  18559. 2.0 * (aminus1 - aplus1 * coso),
  18560. aplus1 - aminus1TimesCoso - beta);
  18561. }
  18562. void IIRFilter::makeBandPass (const double sampleRate,
  18563. const double centreFrequency,
  18564. const double Q,
  18565. const float gainFactor) throw()
  18566. {
  18567. jassert (sampleRate > 0);
  18568. jassert (Q > 0);
  18569. const double A = jmax (0.0f, gainFactor);
  18570. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  18571. const double alpha = 0.5 * sin (omega) / Q;
  18572. const double c2 = -2.0 * cos (omega);
  18573. const double alphaTimesA = alpha * A;
  18574. const double alphaOverA = alpha / A;
  18575. setCoefficients (1.0 + alphaTimesA,
  18576. c2,
  18577. 1.0 - alphaTimesA,
  18578. 1.0 + alphaOverA,
  18579. c2,
  18580. 1.0 - alphaOverA);
  18581. }
  18582. void IIRFilter::makeInactive() throw()
  18583. {
  18584. const ScopedLock sl (processLock);
  18585. active = false;
  18586. }
  18587. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  18588. {
  18589. const ScopedLock sl (processLock);
  18590. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  18591. active = other.active;
  18592. }
  18593. void IIRFilter::setCoefficients (double c1,
  18594. double c2,
  18595. double c3,
  18596. double c4,
  18597. double c5,
  18598. double c6) throw()
  18599. {
  18600. const double a = 1.0 / c4;
  18601. c1 *= a;
  18602. c2 *= a;
  18603. c3 *= a;
  18604. c5 *= a;
  18605. c6 *= a;
  18606. const ScopedLock sl (processLock);
  18607. coefficients[0] = (float) c1;
  18608. coefficients[1] = (float) c2;
  18609. coefficients[2] = (float) c3;
  18610. coefficients[3] = (float) c4;
  18611. coefficients[4] = (float) c5;
  18612. coefficients[5] = (float) c6;
  18613. active = true;
  18614. }
  18615. END_JUCE_NAMESPACE
  18616. /********* End of inlined file: juce_IIRFilter.cpp *********/
  18617. /********* Start of inlined file: juce_MidiBuffer.cpp *********/
  18618. BEGIN_JUCE_NAMESPACE
  18619. MidiBuffer::MidiBuffer() throw()
  18620. : ArrayAllocationBase <uint8> (32),
  18621. bytesUsed (0)
  18622. {
  18623. }
  18624. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  18625. : ArrayAllocationBase <uint8> (32),
  18626. bytesUsed (other.bytesUsed)
  18627. {
  18628. ensureAllocatedSize (bytesUsed);
  18629. memcpy (elements, other.elements, bytesUsed);
  18630. }
  18631. const MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  18632. {
  18633. if (this != &other)
  18634. {
  18635. bytesUsed = other.bytesUsed;
  18636. ensureAllocatedSize (bytesUsed);
  18637. if (bytesUsed > 0)
  18638. memcpy (elements, other.elements, bytesUsed);
  18639. }
  18640. return *this;
  18641. }
  18642. MidiBuffer::~MidiBuffer() throw()
  18643. {
  18644. }
  18645. void MidiBuffer::clear() throw()
  18646. {
  18647. bytesUsed = 0;
  18648. }
  18649. void MidiBuffer::clear (const int startSample,
  18650. const int numSamples) throw()
  18651. {
  18652. uint8* const start = findEventAfter (elements, startSample - 1);
  18653. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  18654. if (end > start)
  18655. {
  18656. const size_t bytesToMove = (size_t) (bytesUsed - (end - elements));
  18657. if (bytesToMove > 0)
  18658. memmove (start, end, bytesToMove);
  18659. bytesUsed -= (int) (end - start);
  18660. }
  18661. }
  18662. void MidiBuffer::addEvent (const MidiMessage& m,
  18663. const int sampleNumber) throw()
  18664. {
  18665. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  18666. }
  18667. static int findActualEventLength (const uint8* const data,
  18668. const int maxBytes) throw()
  18669. {
  18670. unsigned int byte = (unsigned int) *data;
  18671. int size = 0;
  18672. if (byte == 0xf0 || byte == 0xf7)
  18673. {
  18674. const uint8* d = data + 1;
  18675. while (d < data + maxBytes)
  18676. if (*d++ == 0xf7)
  18677. break;
  18678. size = (int) (d - data);
  18679. }
  18680. else if (byte == 0xff)
  18681. {
  18682. int n;
  18683. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  18684. size = jmin (maxBytes, n + 2 + bytesLeft);
  18685. }
  18686. else if (byte >= 0x80)
  18687. {
  18688. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  18689. }
  18690. return size;
  18691. }
  18692. void MidiBuffer::addEvent (const uint8* const newData,
  18693. const int maxBytes,
  18694. const int sampleNumber) throw()
  18695. {
  18696. const int numBytes = findActualEventLength (newData, maxBytes);
  18697. if (numBytes > 0)
  18698. {
  18699. ensureAllocatedSize (bytesUsed + numBytes + 6);
  18700. uint8* d = findEventAfter (elements, sampleNumber);
  18701. const size_t bytesToMove = (size_t) (bytesUsed - (d - elements));
  18702. if (bytesToMove > 0)
  18703. memmove (d + numBytes + 6,
  18704. d,
  18705. bytesToMove);
  18706. *(int*) d = sampleNumber;
  18707. d += 4;
  18708. *(uint16*) d = (uint16) numBytes;
  18709. d += 2;
  18710. memcpy (d, newData, numBytes);
  18711. bytesUsed += numBytes + 6;
  18712. }
  18713. }
  18714. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  18715. const int startSample,
  18716. const int numSamples,
  18717. const int sampleDeltaToAdd) throw()
  18718. {
  18719. Iterator i (otherBuffer);
  18720. i.setNextSamplePosition (startSample);
  18721. const uint8* data;
  18722. int size, position;
  18723. while (i.getNextEvent (data, size, position)
  18724. && (position < startSample + numSamples || numSamples < 0))
  18725. {
  18726. addEvent (data, size, position + sampleDeltaToAdd);
  18727. }
  18728. }
  18729. bool MidiBuffer::isEmpty() const throw()
  18730. {
  18731. return bytesUsed == 0;
  18732. }
  18733. int MidiBuffer::getNumEvents() const throw()
  18734. {
  18735. int n = 0;
  18736. const uint8* d = elements;
  18737. const uint8* const end = elements + bytesUsed;
  18738. while (d < end)
  18739. {
  18740. d += 4;
  18741. d += 2 + *(const uint16*) d;
  18742. ++n;
  18743. }
  18744. return n;
  18745. }
  18746. int MidiBuffer::getFirstEventTime() const throw()
  18747. {
  18748. return (bytesUsed > 0) ? *(const int*) elements : 0;
  18749. }
  18750. int MidiBuffer::getLastEventTime() const throw()
  18751. {
  18752. if (bytesUsed == 0)
  18753. return 0;
  18754. const uint8* d = elements;
  18755. const uint8* const endData = d + bytesUsed;
  18756. for (;;)
  18757. {
  18758. const uint8* nextOne = d + 6 + * (const uint16*) (d + 4);
  18759. if (nextOne >= endData)
  18760. return *(const int*) d;
  18761. d = nextOne;
  18762. }
  18763. }
  18764. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  18765. {
  18766. const uint8* const endData = elements + bytesUsed;
  18767. while (d < endData && *(int*) d <= samplePosition)
  18768. {
  18769. d += 4;
  18770. d += 2 + *(uint16*) d;
  18771. }
  18772. return d;
  18773. }
  18774. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer) throw()
  18775. : buffer (buffer),
  18776. data (buffer.elements)
  18777. {
  18778. }
  18779. MidiBuffer::Iterator::~Iterator() throw()
  18780. {
  18781. }
  18782. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  18783. {
  18784. data = buffer.elements;
  18785. const uint8* dataEnd = buffer.elements + buffer.bytesUsed;
  18786. while (data < dataEnd && *(int*) data < samplePosition)
  18787. {
  18788. data += 4;
  18789. data += 2 + *(uint16*) data;
  18790. }
  18791. }
  18792. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData,
  18793. int& numBytes,
  18794. int& samplePosition) throw()
  18795. {
  18796. if (data >= buffer.elements + buffer.bytesUsed)
  18797. return false;
  18798. samplePosition = *(int*) data;
  18799. data += 4;
  18800. numBytes = *(uint16*) data;
  18801. data += 2;
  18802. midiData = data;
  18803. data += numBytes;
  18804. return true;
  18805. }
  18806. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result,
  18807. int& samplePosition) throw()
  18808. {
  18809. if (data >= buffer.elements + buffer.bytesUsed)
  18810. return false;
  18811. samplePosition = *(int*) data;
  18812. data += 4;
  18813. const int numBytes = *(uint16*) data;
  18814. data += 2;
  18815. result = MidiMessage (data, numBytes, samplePosition);
  18816. data += numBytes;
  18817. return true;
  18818. }
  18819. END_JUCE_NAMESPACE
  18820. /********* End of inlined file: juce_MidiBuffer.cpp *********/
  18821. /********* Start of inlined file: juce_MidiFile.cpp *********/
  18822. BEGIN_JUCE_NAMESPACE
  18823. struct TempoInfo
  18824. {
  18825. double bpm, timestamp;
  18826. };
  18827. struct TimeSigInfo
  18828. {
  18829. int numerator, denominator;
  18830. double timestamp;
  18831. };
  18832. MidiFile::MidiFile() throw()
  18833. : numTracks (0),
  18834. timeFormat ((short)(unsigned short)0xe728)
  18835. {
  18836. }
  18837. MidiFile::~MidiFile() throw()
  18838. {
  18839. clear();
  18840. }
  18841. void MidiFile::clear() throw()
  18842. {
  18843. while (numTracks > 0)
  18844. delete tracks [--numTracks];
  18845. }
  18846. int MidiFile::getNumTracks() const throw()
  18847. {
  18848. return numTracks;
  18849. }
  18850. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  18851. {
  18852. return (((unsigned int) index) < (unsigned int) numTracks) ? tracks[index] : 0;
  18853. }
  18854. void MidiFile::addTrack (const MidiMessageSequence& trackSequence) throw()
  18855. {
  18856. jassert (numTracks < numElementsInArray (tracks));
  18857. if (numTracks < numElementsInArray (tracks))
  18858. tracks [numTracks++] = new MidiMessageSequence (trackSequence);
  18859. }
  18860. short MidiFile::getTimeFormat() const throw()
  18861. {
  18862. return timeFormat;
  18863. }
  18864. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  18865. {
  18866. timeFormat = (short)ticks;
  18867. }
  18868. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  18869. const int subframeResolution) throw()
  18870. {
  18871. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  18872. }
  18873. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  18874. {
  18875. for (int i = numTracks; --i >= 0;)
  18876. {
  18877. const int numEvents = tracks[i]->getNumEvents();
  18878. for (int j = 0; j < numEvents; ++j)
  18879. {
  18880. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  18881. if (m.isTempoMetaEvent())
  18882. tempoChangeEvents.addEvent (m);
  18883. }
  18884. }
  18885. }
  18886. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  18887. {
  18888. for (int i = numTracks; --i >= 0;)
  18889. {
  18890. const int numEvents = tracks[i]->getNumEvents();
  18891. for (int j = 0; j < numEvents; ++j)
  18892. {
  18893. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  18894. if (m.isTimeSignatureMetaEvent())
  18895. timeSigEvents.addEvent (m);
  18896. }
  18897. }
  18898. }
  18899. double MidiFile::getLastTimestamp() const
  18900. {
  18901. double t = 0.0;
  18902. for (int i = numTracks; --i >= 0;)
  18903. t = jmax (t, tracks[i]->getEndTime());
  18904. return t;
  18905. }
  18906. static bool parseMidiHeader (const char* &data,
  18907. short& timeFormat,
  18908. short& fileType,
  18909. short& numberOfTracks)
  18910. {
  18911. unsigned int ch = (int) bigEndianInt (data);
  18912. data += 4;
  18913. if (ch != bigEndianInt ("MThd"))
  18914. {
  18915. bool ok = false;
  18916. if (ch == bigEndianInt ("RIFF"))
  18917. {
  18918. for (int i = 0; i < 8; ++i)
  18919. {
  18920. ch = bigEndianInt (data);
  18921. data += 4;
  18922. if (ch == bigEndianInt ("MThd"))
  18923. {
  18924. ok = true;
  18925. break;
  18926. }
  18927. }
  18928. }
  18929. if (! ok)
  18930. return false;
  18931. }
  18932. unsigned int bytesRemaining = bigEndianInt (data);
  18933. data += 4;
  18934. fileType = (short)bigEndianShort (data);
  18935. data += 2;
  18936. numberOfTracks = (short)bigEndianShort (data);
  18937. data += 2;
  18938. timeFormat = (short)bigEndianShort (data);
  18939. data += 2;
  18940. bytesRemaining -= 6;
  18941. data += bytesRemaining;
  18942. return true;
  18943. }
  18944. bool MidiFile::readFrom (InputStream& sourceStream)
  18945. {
  18946. clear();
  18947. MemoryBlock data;
  18948. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  18949. // (put a sanity-check on the file size, as midi files are generally small)
  18950. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  18951. {
  18952. int size = data.getSize();
  18953. const char* d = (char*) data.getData();
  18954. short fileType, expectedTracks;
  18955. if (size > 16 && parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  18956. {
  18957. size -= (int) (d - (char*) data.getData());
  18958. int track = 0;
  18959. while (size > 0 && track < expectedTracks)
  18960. {
  18961. const int chunkType = (int)bigEndianInt (d);
  18962. d += 4;
  18963. const int chunkSize = (int)bigEndianInt (d);
  18964. d += 4;
  18965. if (chunkSize <= 0)
  18966. break;
  18967. if (size < 0)
  18968. return false;
  18969. if (chunkType == (int)bigEndianInt ("MTrk"))
  18970. {
  18971. readNextTrack (d, chunkSize);
  18972. }
  18973. size -= chunkSize + 8;
  18974. d += chunkSize;
  18975. ++track;
  18976. }
  18977. return true;
  18978. }
  18979. }
  18980. return false;
  18981. }
  18982. // a comparator that puts all the note-offs before note-ons that have the same time
  18983. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  18984. const MidiMessageSequence::MidiEventHolder* const second) throw()
  18985. {
  18986. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  18987. if (diff == 0)
  18988. {
  18989. if (first->message.isNoteOff() && second->message.isNoteOn())
  18990. return -1;
  18991. else if (first->message.isNoteOn() && second->message.isNoteOff())
  18992. return 1;
  18993. else
  18994. return 0;
  18995. }
  18996. else
  18997. {
  18998. return (diff > 0) ? 1 : -1;
  18999. }
  19000. }
  19001. void MidiFile::readNextTrack (const char* data, int size)
  19002. {
  19003. double time = 0;
  19004. char lastStatusByte = 0;
  19005. MidiMessageSequence result;
  19006. while (size > 0)
  19007. {
  19008. int bytesUsed;
  19009. const int delay = MidiMessage::readVariableLengthVal ((const uint8*) data, bytesUsed);
  19010. data += bytesUsed;
  19011. size -= bytesUsed;
  19012. time += delay;
  19013. int messSize = 0;
  19014. const MidiMessage mm ((const uint8*) data, size, messSize, lastStatusByte, time);
  19015. if (messSize <= 0)
  19016. break;
  19017. size -= messSize;
  19018. data += messSize;
  19019. result.addEvent (mm);
  19020. const char firstByte = *(mm.getRawData());
  19021. if ((firstByte & 0xf0) != 0xf0)
  19022. lastStatusByte = firstByte;
  19023. }
  19024. // use a sort that puts all the note-offs before note-ons that have the same time
  19025. result.list.sort (*this, true);
  19026. result.updateMatchedPairs();
  19027. addTrack (result);
  19028. }
  19029. static double convertTicksToSeconds (const double time,
  19030. const MidiMessageSequence& tempoEvents,
  19031. const int timeFormat)
  19032. {
  19033. if (timeFormat > 0)
  19034. {
  19035. int numer = 4, denom = 4;
  19036. double tempoTime = 0.0, correctedTempoTime = 0.0;
  19037. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  19038. double secsPerTick = 0.5 * tickLen;
  19039. const int numEvents = tempoEvents.getNumEvents();
  19040. for (int i = 0; i < numEvents; ++i)
  19041. {
  19042. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  19043. if (time <= m.getTimeStamp())
  19044. break;
  19045. if (timeFormat > 0)
  19046. {
  19047. correctedTempoTime = correctedTempoTime
  19048. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  19049. }
  19050. else
  19051. {
  19052. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  19053. }
  19054. tempoTime = m.getTimeStamp();
  19055. if (m.isTempoMetaEvent())
  19056. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  19057. else if (m.isTimeSignatureMetaEvent())
  19058. m.getTimeSignatureInfo (numer, denom);
  19059. while (i + 1 < numEvents)
  19060. {
  19061. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  19062. if (m2.getTimeStamp() == tempoTime)
  19063. {
  19064. ++i;
  19065. if (m2.isTempoMetaEvent())
  19066. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  19067. else if (m2.isTimeSignatureMetaEvent())
  19068. m2.getTimeSignatureInfo (numer, denom);
  19069. }
  19070. else
  19071. {
  19072. break;
  19073. }
  19074. }
  19075. }
  19076. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  19077. }
  19078. else
  19079. {
  19080. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  19081. }
  19082. }
  19083. void MidiFile::convertTimestampTicksToSeconds()
  19084. {
  19085. MidiMessageSequence tempoEvents;
  19086. findAllTempoEvents (tempoEvents);
  19087. findAllTimeSigEvents (tempoEvents);
  19088. for (int i = 0; i < numTracks; ++i)
  19089. {
  19090. MidiMessageSequence& ms = *tracks[i];
  19091. for (int j = ms.getNumEvents(); --j >= 0;)
  19092. {
  19093. MidiMessage& m = ms.getEventPointer(j)->message;
  19094. m.setTimeStamp (convertTicksToSeconds (m.getTimeStamp(),
  19095. tempoEvents,
  19096. timeFormat));
  19097. }
  19098. }
  19099. }
  19100. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  19101. {
  19102. unsigned int buffer = v & 0x7F;
  19103. while ((v >>= 7) != 0)
  19104. {
  19105. buffer <<= 8;
  19106. buffer |= ((v & 0x7F) | 0x80);
  19107. }
  19108. for (;;)
  19109. {
  19110. out.writeByte ((char) buffer);
  19111. if (buffer & 0x80)
  19112. buffer >>= 8;
  19113. else
  19114. break;
  19115. }
  19116. }
  19117. bool MidiFile::writeTo (OutputStream& out)
  19118. {
  19119. out.writeIntBigEndian ((int) bigEndianInt ("MThd"));
  19120. out.writeIntBigEndian (6);
  19121. out.writeShortBigEndian (1); // type
  19122. out.writeShortBigEndian (numTracks);
  19123. out.writeShortBigEndian (timeFormat);
  19124. for (int i = 0; i < numTracks; ++i)
  19125. writeTrack (out, i);
  19126. out.flush();
  19127. return true;
  19128. }
  19129. void MidiFile::writeTrack (OutputStream& mainOut,
  19130. const int trackNum)
  19131. {
  19132. MemoryOutputStream out;
  19133. const MidiMessageSequence& ms = *tracks[trackNum];
  19134. int lastTick = 0;
  19135. char lastStatusByte = 0;
  19136. for (int i = 0; i < ms.getNumEvents(); ++i)
  19137. {
  19138. const MidiMessage& mm = ms.getEventPointer(i)->message;
  19139. const int tick = roundDoubleToInt (mm.getTimeStamp());
  19140. const int delta = jmax (0, tick - lastTick);
  19141. writeVariableLengthInt (out, delta);
  19142. lastTick = tick;
  19143. const char statusByte = *(mm.getRawData());
  19144. if ((statusByte == lastStatusByte)
  19145. && ((statusByte & 0xf0) != 0xf0)
  19146. && i > 0
  19147. && mm.getRawDataSize() > 1)
  19148. {
  19149. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  19150. }
  19151. else
  19152. {
  19153. out.write (mm.getRawData(), mm.getRawDataSize());
  19154. }
  19155. lastStatusByte = statusByte;
  19156. }
  19157. out.writeByte (0);
  19158. const MidiMessage m (MidiMessage::endOfTrack());
  19159. out.write (m.getRawData(),
  19160. m.getRawDataSize());
  19161. mainOut.writeIntBigEndian ((int)bigEndianInt ("MTrk"));
  19162. mainOut.writeIntBigEndian (out.getDataSize());
  19163. mainOut.write (out.getData(), out.getDataSize());
  19164. }
  19165. END_JUCE_NAMESPACE
  19166. /********* End of inlined file: juce_MidiFile.cpp *********/
  19167. /********* Start of inlined file: juce_MidiKeyboardState.cpp *********/
  19168. BEGIN_JUCE_NAMESPACE
  19169. MidiKeyboardState::MidiKeyboardState()
  19170. : listeners (2)
  19171. {
  19172. zeromem (noteStates, sizeof (noteStates));
  19173. }
  19174. MidiKeyboardState::~MidiKeyboardState()
  19175. {
  19176. }
  19177. void MidiKeyboardState::reset()
  19178. {
  19179. const ScopedLock sl (lock);
  19180. zeromem (noteStates, sizeof (noteStates));
  19181. eventsToAdd.clear();
  19182. }
  19183. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  19184. {
  19185. jassert (midiChannel >= 0 && midiChannel <= 16);
  19186. return ((unsigned int) n) < 128
  19187. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  19188. }
  19189. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  19190. {
  19191. return ((unsigned int) n) < 128
  19192. && (noteStates[n] & midiChannelMask) != 0;
  19193. }
  19194. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  19195. {
  19196. jassert (midiChannel >= 0 && midiChannel <= 16);
  19197. jassert (((unsigned int) midiNoteNumber) < 128);
  19198. const ScopedLock sl (lock);
  19199. if (((unsigned int) midiNoteNumber) < 128)
  19200. {
  19201. const int timeNow = (int) Time::getMillisecondCounter();
  19202. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  19203. eventsToAdd.clear (0, timeNow - 500);
  19204. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  19205. }
  19206. }
  19207. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  19208. {
  19209. if (((unsigned int) midiNoteNumber) < 128)
  19210. {
  19211. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  19212. for (int i = listeners.size(); --i >= 0;)
  19213. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  19214. ->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  19215. }
  19216. }
  19217. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  19218. {
  19219. const ScopedLock sl (lock);
  19220. if (isNoteOn (midiChannel, midiNoteNumber))
  19221. {
  19222. const int timeNow = (int) Time::getMillisecondCounter();
  19223. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  19224. eventsToAdd.clear (0, timeNow - 500);
  19225. noteOffInternal (midiChannel, midiNoteNumber);
  19226. }
  19227. }
  19228. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  19229. {
  19230. if (isNoteOn (midiChannel, midiNoteNumber))
  19231. {
  19232. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  19233. for (int i = listeners.size(); --i >= 0;)
  19234. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  19235. ->handleNoteOff (this, midiChannel, midiNoteNumber);
  19236. }
  19237. }
  19238. void MidiKeyboardState::allNotesOff (const int midiChannel)
  19239. {
  19240. const ScopedLock sl (lock);
  19241. if (midiChannel <= 0)
  19242. {
  19243. for (int i = 1; i <= 16; ++i)
  19244. allNotesOff (i);
  19245. }
  19246. else
  19247. {
  19248. for (int i = 0; i < 128; ++i)
  19249. noteOff (midiChannel, i);
  19250. }
  19251. }
  19252. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  19253. {
  19254. if (message.isNoteOn())
  19255. {
  19256. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  19257. }
  19258. else if (message.isNoteOff())
  19259. {
  19260. noteOffInternal (message.getChannel(), message.getNoteNumber());
  19261. }
  19262. else if (message.isAllNotesOff())
  19263. {
  19264. for (int i = 0; i < 128; ++i)
  19265. noteOffInternal (message.getChannel(), i);
  19266. }
  19267. }
  19268. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  19269. const int startSample,
  19270. const int numSamples,
  19271. const bool injectIndirectEvents)
  19272. {
  19273. MidiBuffer::Iterator i (buffer);
  19274. MidiMessage message (0xf4, 0.0);
  19275. int time;
  19276. const ScopedLock sl (lock);
  19277. while (i.getNextEvent (message, time))
  19278. processNextMidiEvent (message);
  19279. if (injectIndirectEvents)
  19280. {
  19281. MidiBuffer::Iterator i2 (eventsToAdd);
  19282. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  19283. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  19284. while (i2.getNextEvent (message, time))
  19285. {
  19286. const int pos = jlimit (0, numSamples - 1, roundDoubleToInt ((time - firstEventToAdd) * scaleFactor));
  19287. buffer.addEvent (message, startSample + pos);
  19288. }
  19289. }
  19290. eventsToAdd.clear();
  19291. }
  19292. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  19293. {
  19294. const ScopedLock sl (lock);
  19295. listeners.addIfNotAlreadyThere (listener);
  19296. }
  19297. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  19298. {
  19299. const ScopedLock sl (lock);
  19300. listeners.removeValue (listener);
  19301. }
  19302. END_JUCE_NAMESPACE
  19303. /********* End of inlined file: juce_MidiKeyboardState.cpp *********/
  19304. /********* Start of inlined file: juce_MidiMessage.cpp *********/
  19305. BEGIN_JUCE_NAMESPACE
  19306. int MidiMessage::readVariableLengthVal (const uint8* data,
  19307. int& numBytesUsed) throw()
  19308. {
  19309. numBytesUsed = 0;
  19310. int v = 0;
  19311. int i;
  19312. do
  19313. {
  19314. i = (int) *data++;
  19315. if (++numBytesUsed > 6)
  19316. break;
  19317. v = (v << 7) + (i & 0x7f);
  19318. } while (i & 0x80);
  19319. return v;
  19320. }
  19321. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  19322. {
  19323. // this method only works for valid starting bytes of a short midi message
  19324. jassert (firstByte >= 0x80
  19325. && firstByte != 0xff
  19326. && firstByte != 0xf0
  19327. && firstByte != 0xf7);
  19328. static const char messageLengths[] =
  19329. {
  19330. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19331. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19332. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19333. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19334. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  19335. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  19336. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19337. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  19338. };
  19339. return messageLengths [firstByte & 0x7f];
  19340. }
  19341. MidiMessage::MidiMessage (const uint8* const d,
  19342. const int dataSize,
  19343. const double t) throw()
  19344. : timeStamp (t),
  19345. message (0),
  19346. size (dataSize)
  19347. {
  19348. jassert (dataSize > 0);
  19349. if (dataSize <= 4)
  19350. data = (uint8*) &message;
  19351. else
  19352. data = (uint8*) juce_malloc (dataSize);
  19353. memcpy (data, d, dataSize);
  19354. // check that the length matches the data..
  19355. jassert (size > 3 || *d >= 0xf0 || getMessageLengthFromFirstByte (*d) == size);
  19356. }
  19357. MidiMessage::MidiMessage (const int byte1,
  19358. const double t) throw()
  19359. : timeStamp (t),
  19360. data ((uint8*) &message),
  19361. size (1)
  19362. {
  19363. data[0] = (uint8) byte1;
  19364. // check that the length matches the data..
  19365. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  19366. }
  19367. MidiMessage::MidiMessage (const int byte1,
  19368. const int byte2,
  19369. const double t) throw()
  19370. : timeStamp (t),
  19371. data ((uint8*) &message),
  19372. size (2)
  19373. {
  19374. data[0] = (uint8) byte1;
  19375. data[1] = (uint8) byte2;
  19376. // check that the length matches the data..
  19377. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  19378. }
  19379. MidiMessage::MidiMessage (const int byte1,
  19380. const int byte2,
  19381. const int byte3,
  19382. const double t) throw()
  19383. : timeStamp (t),
  19384. data ((uint8*) &message),
  19385. size (3)
  19386. {
  19387. data[0] = (uint8) byte1;
  19388. data[1] = (uint8) byte2;
  19389. data[2] = (uint8) byte3;
  19390. // check that the length matches the data..
  19391. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  19392. }
  19393. MidiMessage::MidiMessage (const MidiMessage& other) throw()
  19394. : timeStamp (other.timeStamp),
  19395. message (other.message),
  19396. size (other.size)
  19397. {
  19398. if (other.data != (uint8*) &other.message)
  19399. {
  19400. data = (uint8*) juce_malloc (size);
  19401. memcpy (data, other.data, size);
  19402. }
  19403. else
  19404. {
  19405. data = (uint8*) &message;
  19406. }
  19407. }
  19408. MidiMessage::MidiMessage (const MidiMessage& other,
  19409. const double newTimeStamp) throw()
  19410. : timeStamp (newTimeStamp),
  19411. message (other.message),
  19412. size (other.size)
  19413. {
  19414. if (other.data != (uint8*) &other.message)
  19415. {
  19416. data = (uint8*) juce_malloc (size);
  19417. memcpy (data, other.data, size);
  19418. }
  19419. else
  19420. {
  19421. data = (uint8*) &message;
  19422. }
  19423. }
  19424. MidiMessage::MidiMessage (const uint8* src,
  19425. int sz,
  19426. int& numBytesUsed,
  19427. const uint8 lastStatusByte,
  19428. double t) throw()
  19429. : timeStamp (t),
  19430. data ((uint8*) &message),
  19431. message (0)
  19432. {
  19433. unsigned int byte = (unsigned int) *src;
  19434. if (byte < 0x80)
  19435. {
  19436. byte = (unsigned int) (uint8) lastStatusByte;
  19437. numBytesUsed = -1;
  19438. }
  19439. else
  19440. {
  19441. numBytesUsed = 0;
  19442. --sz;
  19443. ++src;
  19444. }
  19445. if (byte >= 0x80)
  19446. {
  19447. if (byte == 0xf0)
  19448. {
  19449. const uint8* d = (const uint8*) src;
  19450. while (d < src + sz)
  19451. {
  19452. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  19453. {
  19454. if (*d == 0xf7) // include an 0xf7 if we hit one
  19455. ++d;
  19456. break;
  19457. }
  19458. ++d;
  19459. }
  19460. size = 1 + (int) (d - src);
  19461. data = (uint8*) juce_malloc (size);
  19462. *data = (uint8) byte;
  19463. memcpy (data + 1, src, size - 1);
  19464. }
  19465. else if (byte == 0xff)
  19466. {
  19467. int n;
  19468. const int bytesLeft = readVariableLengthVal (src + 1, n);
  19469. size = jmin (sz + 1, n + 2 + bytesLeft);
  19470. data = (uint8*) juce_malloc (size);
  19471. *data = (uint8) byte;
  19472. memcpy (data + 1, src, size - 1);
  19473. }
  19474. else
  19475. {
  19476. size = getMessageLengthFromFirstByte ((uint8) byte);
  19477. *data = (uint8) byte;
  19478. if (size > 1)
  19479. {
  19480. data[1] = src[0];
  19481. if (size > 2)
  19482. data[2] = src[1];
  19483. }
  19484. }
  19485. numBytesUsed += size;
  19486. }
  19487. else
  19488. {
  19489. message = 0;
  19490. size = 0;
  19491. }
  19492. }
  19493. const MidiMessage& MidiMessage::operator= (const MidiMessage& other) throw()
  19494. {
  19495. if (this == &other)
  19496. return *this;
  19497. timeStamp = other.timeStamp;
  19498. size = other.size;
  19499. message = other.message;
  19500. if (data != (uint8*) &message)
  19501. juce_free (data);
  19502. if (other.data != (uint8*) &other.message)
  19503. {
  19504. data = (uint8*) juce_malloc (size);
  19505. memcpy (data, other.data, size);
  19506. }
  19507. else
  19508. {
  19509. data = (uint8*) &message;
  19510. }
  19511. return *this;
  19512. }
  19513. MidiMessage::~MidiMessage() throw()
  19514. {
  19515. if (data != (uint8*) &message)
  19516. juce_free (data);
  19517. }
  19518. int MidiMessage::getChannel() const throw()
  19519. {
  19520. if ((data[0] & 0xf0) != 0xf0)
  19521. return (data[0] & 0xf) + 1;
  19522. else
  19523. return 0;
  19524. }
  19525. bool MidiMessage::isForChannel (const int channel) const throw()
  19526. {
  19527. return ((data[0] & 0xf) == channel - 1)
  19528. && ((data[0] & 0xf0) != 0xf0);
  19529. }
  19530. void MidiMessage::setChannel (const int channel) throw()
  19531. {
  19532. if ((data[0] & 0xf0) != (uint8) 0xf0)
  19533. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  19534. | (uint8)(channel - 1));
  19535. }
  19536. bool MidiMessage::isNoteOn() const throw()
  19537. {
  19538. return ((data[0] & 0xf0) == 0x90)
  19539. && (data[2] != 0);
  19540. }
  19541. bool MidiMessage::isNoteOff() const throw()
  19542. {
  19543. return ((data[0] & 0xf0) == 0x80)
  19544. || ((data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  19545. }
  19546. bool MidiMessage::isNoteOnOrOff() const throw()
  19547. {
  19548. const int d = data[0] & 0xf0;
  19549. return (d == 0x90) || (d == 0x80);
  19550. }
  19551. int MidiMessage::getNoteNumber() const throw()
  19552. {
  19553. return data[1];
  19554. }
  19555. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  19556. {
  19557. if (isNoteOnOrOff())
  19558. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  19559. }
  19560. uint8 MidiMessage::getVelocity() const throw()
  19561. {
  19562. if (isNoteOnOrOff())
  19563. return data[2];
  19564. else
  19565. return 0;
  19566. }
  19567. float MidiMessage::getFloatVelocity() const throw()
  19568. {
  19569. return getVelocity() * (1.0f / 127.0f);
  19570. }
  19571. void MidiMessage::setVelocity (const float newVelocity) throw()
  19572. {
  19573. if (isNoteOnOrOff())
  19574. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (newVelocity * 127.0f));
  19575. }
  19576. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  19577. {
  19578. if (isNoteOnOrOff())
  19579. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (scaleFactor * data[2]));
  19580. }
  19581. bool MidiMessage::isAftertouch() const throw()
  19582. {
  19583. return (data[0] & 0xf0) == 0xa0;
  19584. }
  19585. int MidiMessage::getAfterTouchValue() const throw()
  19586. {
  19587. return data[2];
  19588. }
  19589. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  19590. const int noteNum,
  19591. const int aftertouchValue) throw()
  19592. {
  19593. jassert (channel > 0 && channel <= 16);
  19594. jassert (((unsigned int) noteNum) <= 127);
  19595. jassert (((unsigned int) aftertouchValue) <= 127);
  19596. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  19597. noteNum & 0x7f,
  19598. aftertouchValue & 0x7f);
  19599. }
  19600. bool MidiMessage::isChannelPressure() const throw()
  19601. {
  19602. return (data[0] & 0xf0) == 0xd0;
  19603. }
  19604. int MidiMessage::getChannelPressureValue() const throw()
  19605. {
  19606. jassert (isChannelPressure());
  19607. return data[1];
  19608. }
  19609. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  19610. const int pressure) throw()
  19611. {
  19612. jassert (channel > 0 && channel <= 16);
  19613. jassert (((unsigned int) pressure) <= 127);
  19614. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  19615. pressure & 0x7f);
  19616. }
  19617. bool MidiMessage::isProgramChange() const throw()
  19618. {
  19619. return (data[0] & 0xf0) == 0xc0;
  19620. }
  19621. int MidiMessage::getProgramChangeNumber() const throw()
  19622. {
  19623. return data[1];
  19624. }
  19625. const MidiMessage MidiMessage::programChange (const int channel,
  19626. const int programNumber) throw()
  19627. {
  19628. jassert (channel > 0 && channel <= 16);
  19629. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  19630. programNumber & 0x7f);
  19631. }
  19632. bool MidiMessage::isPitchWheel() const throw()
  19633. {
  19634. return (data[0] & 0xf0) == 0xe0;
  19635. }
  19636. int MidiMessage::getPitchWheelValue() const throw()
  19637. {
  19638. return data[1] | (data[2] << 7);
  19639. }
  19640. const MidiMessage MidiMessage::pitchWheel (const int channel,
  19641. const int position) throw()
  19642. {
  19643. jassert (channel > 0 && channel <= 16);
  19644. jassert (((unsigned int) position) <= 0x3fff);
  19645. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  19646. position & 127,
  19647. (position >> 7) & 127);
  19648. }
  19649. bool MidiMessage::isController() const throw()
  19650. {
  19651. return (data[0] & 0xf0) == 0xb0;
  19652. }
  19653. int MidiMessage::getControllerNumber() const throw()
  19654. {
  19655. jassert (isController());
  19656. return data[1];
  19657. }
  19658. int MidiMessage::getControllerValue() const throw()
  19659. {
  19660. jassert (isController());
  19661. return data[2];
  19662. }
  19663. const MidiMessage MidiMessage::controllerEvent (const int channel,
  19664. const int controllerType,
  19665. const int value) throw()
  19666. {
  19667. // the channel must be between 1 and 16 inclusive
  19668. jassert (channel > 0 && channel <= 16);
  19669. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  19670. controllerType & 127,
  19671. value & 127);
  19672. }
  19673. const MidiMessage MidiMessage::noteOn (const int channel,
  19674. const int noteNumber,
  19675. const float velocity) throw()
  19676. {
  19677. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  19678. }
  19679. const MidiMessage MidiMessage::noteOn (const int channel,
  19680. const int noteNumber,
  19681. const uint8 velocity) throw()
  19682. {
  19683. jassert (channel > 0 && channel <= 16);
  19684. jassert (((unsigned int) noteNumber) <= 127);
  19685. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  19686. noteNumber & 127,
  19687. jlimit (0, 127, roundFloatToInt (velocity)));
  19688. }
  19689. const MidiMessage MidiMessage::noteOff (const int channel,
  19690. const int noteNumber) throw()
  19691. {
  19692. jassert (channel > 0 && channel <= 16);
  19693. jassert (((unsigned int) noteNumber) <= 127);
  19694. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  19695. }
  19696. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  19697. {
  19698. jassert (channel > 0 && channel <= 16);
  19699. return controllerEvent (channel, 123, 0);
  19700. }
  19701. bool MidiMessage::isAllNotesOff() const throw()
  19702. {
  19703. return (data[0] & 0xf0) == 0xb0
  19704. && data[1] == 123;
  19705. }
  19706. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  19707. {
  19708. return controllerEvent (channel, 120, 0);
  19709. }
  19710. bool MidiMessage::isAllSoundOff() const throw()
  19711. {
  19712. return (data[0] & 0xf0) == 0xb0
  19713. && data[1] == 120;
  19714. }
  19715. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  19716. {
  19717. return controllerEvent (channel, 121, 0);
  19718. }
  19719. const MidiMessage MidiMessage::masterVolume (const float volume) throw()
  19720. {
  19721. const int vol = jlimit (0, 0x3fff, roundFloatToInt (volume * 0x4000));
  19722. uint8 buf[8];
  19723. buf[0] = 0xf0;
  19724. buf[1] = 0x7f;
  19725. buf[2] = 0x7f;
  19726. buf[3] = 0x04;
  19727. buf[4] = 0x01;
  19728. buf[5] = (uint8) (vol & 0x7f);
  19729. buf[6] = (uint8) (vol >> 7);
  19730. buf[7] = 0xf7;
  19731. return MidiMessage (buf, 8);
  19732. }
  19733. bool MidiMessage::isSysEx() const throw()
  19734. {
  19735. return *data == 0xf0;
  19736. }
  19737. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData,
  19738. const int dataSize) throw()
  19739. {
  19740. MemoryBlock mm (dataSize + 2);
  19741. uint8* const m = (uint8*) mm.getData();
  19742. m[0] = 0xf0;
  19743. memcpy (m + 1, sysexData, dataSize);
  19744. m[dataSize + 1] = 0xf7;
  19745. return MidiMessage (m, dataSize + 2);
  19746. }
  19747. const uint8* MidiMessage::getSysExData() const throw()
  19748. {
  19749. return (isSysEx()) ? getRawData() + 1
  19750. : 0;
  19751. }
  19752. int MidiMessage::getSysExDataSize() const throw()
  19753. {
  19754. return (isSysEx()) ? size - 2
  19755. : 0;
  19756. }
  19757. bool MidiMessage::isMetaEvent() const throw()
  19758. {
  19759. return *data == 0xff;
  19760. }
  19761. bool MidiMessage::isActiveSense() const throw()
  19762. {
  19763. return *data == 0xfe;
  19764. }
  19765. int MidiMessage::getMetaEventType() const throw()
  19766. {
  19767. if (*data != 0xff)
  19768. return -1;
  19769. else
  19770. return data[1];
  19771. }
  19772. int MidiMessage::getMetaEventLength() const throw()
  19773. {
  19774. if (*data == 0xff)
  19775. {
  19776. int n;
  19777. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  19778. }
  19779. return 0;
  19780. }
  19781. const uint8* MidiMessage::getMetaEventData() const throw()
  19782. {
  19783. int n;
  19784. const uint8* d = data + 2;
  19785. readVariableLengthVal (d, n);
  19786. return d + n;
  19787. }
  19788. bool MidiMessage::isTrackMetaEvent() const throw()
  19789. {
  19790. return getMetaEventType() == 0;
  19791. }
  19792. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  19793. {
  19794. return getMetaEventType() == 47;
  19795. }
  19796. bool MidiMessage::isTextMetaEvent() const throw()
  19797. {
  19798. const int t = getMetaEventType();
  19799. return t > 0 && t < 16;
  19800. }
  19801. const String MidiMessage::getTextFromTextMetaEvent() const throw()
  19802. {
  19803. return String ((const char*) getMetaEventData(),
  19804. getMetaEventLength());
  19805. }
  19806. bool MidiMessage::isTrackNameEvent() const throw()
  19807. {
  19808. return (data[1] == 3)
  19809. && (*data == 0xff);
  19810. }
  19811. bool MidiMessage::isTempoMetaEvent() const throw()
  19812. {
  19813. return (data[1] == 81)
  19814. && (*data == 0xff);
  19815. }
  19816. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  19817. {
  19818. return (data[1] == 0x20)
  19819. && (*data == 0xff)
  19820. && (data[2] == 1);
  19821. }
  19822. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  19823. {
  19824. return data[3] + 1;
  19825. }
  19826. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  19827. {
  19828. if (! isTempoMetaEvent())
  19829. return 0.0;
  19830. const uint8* const d = getMetaEventData();
  19831. return (((unsigned int) d[0] << 16)
  19832. | ((unsigned int) d[1] << 8)
  19833. | d[2])
  19834. / 1000000.0;
  19835. }
  19836. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  19837. {
  19838. if (timeFormat > 0)
  19839. {
  19840. if (! isTempoMetaEvent())
  19841. return 0.5 / timeFormat;
  19842. return getTempoSecondsPerQuarterNote() / timeFormat;
  19843. }
  19844. else
  19845. {
  19846. const int frameCode = (-timeFormat) >> 8;
  19847. double framesPerSecond;
  19848. switch (frameCode)
  19849. {
  19850. case 24: framesPerSecond = 24.0; break;
  19851. case 25: framesPerSecond = 25.0; break;
  19852. case 29: framesPerSecond = 29.97; break;
  19853. case 30: framesPerSecond = 30.0; break;
  19854. default: framesPerSecond = 30.0; break;
  19855. }
  19856. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  19857. }
  19858. }
  19859. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  19860. {
  19861. uint8 d[8];
  19862. d[0] = 0xff;
  19863. d[1] = 81;
  19864. d[2] = 3;
  19865. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  19866. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  19867. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  19868. return MidiMessage (d, 6, 0.0);
  19869. }
  19870. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  19871. {
  19872. return (data[1] == 0x58)
  19873. && (*data == (uint8) 0xff);
  19874. }
  19875. void MidiMessage::getTimeSignatureInfo (int& numerator,
  19876. int& denominator) const throw()
  19877. {
  19878. if (isTimeSignatureMetaEvent())
  19879. {
  19880. const uint8* const d = getMetaEventData();
  19881. numerator = d[0];
  19882. denominator = 1 << d[1];
  19883. }
  19884. else
  19885. {
  19886. numerator = 4;
  19887. denominator = 4;
  19888. }
  19889. }
  19890. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator,
  19891. const int denominator) throw()
  19892. {
  19893. uint8 d[8];
  19894. d[0] = 0xff;
  19895. d[1] = 0x58;
  19896. d[2] = 0x04;
  19897. d[3] = (uint8) numerator;
  19898. int n = 1;
  19899. int powerOfTwo = 0;
  19900. while (n < denominator)
  19901. {
  19902. n <<= 1;
  19903. ++powerOfTwo;
  19904. }
  19905. d[4] = (uint8) powerOfTwo;
  19906. d[5] = 0x01;
  19907. d[6] = 96;
  19908. return MidiMessage (d, 7, 0.0);
  19909. }
  19910. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  19911. {
  19912. uint8 d[8];
  19913. d[0] = 0xff;
  19914. d[1] = 0x20;
  19915. d[2] = 0x01;
  19916. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  19917. return MidiMessage (d, 4, 0.0);
  19918. }
  19919. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  19920. {
  19921. return getMetaEventType() == 89;
  19922. }
  19923. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  19924. {
  19925. return (int) *getMetaEventData();
  19926. }
  19927. const MidiMessage MidiMessage::endOfTrack() throw()
  19928. {
  19929. return MidiMessage (0xff, 0x2f, 0, 0.0);
  19930. }
  19931. bool MidiMessage::isSongPositionPointer() const throw()
  19932. {
  19933. return *data == 0xf2;
  19934. }
  19935. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  19936. {
  19937. return data[1] | (data[2] << 7);
  19938. }
  19939. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  19940. {
  19941. return MidiMessage (0xf2,
  19942. positionInMidiBeats & 127,
  19943. (positionInMidiBeats >> 7) & 127);
  19944. }
  19945. bool MidiMessage::isMidiStart() const throw()
  19946. {
  19947. return *data == 0xfa;
  19948. }
  19949. const MidiMessage MidiMessage::midiStart() throw()
  19950. {
  19951. return MidiMessage (0xfa);
  19952. }
  19953. bool MidiMessage::isMidiContinue() const throw()
  19954. {
  19955. return *data == 0xfb;
  19956. }
  19957. const MidiMessage MidiMessage::midiContinue() throw()
  19958. {
  19959. return MidiMessage (0xfb);
  19960. }
  19961. bool MidiMessage::isMidiStop() const throw()
  19962. {
  19963. return *data == 0xfc;
  19964. }
  19965. const MidiMessage MidiMessage::midiStop() throw()
  19966. {
  19967. return MidiMessage (0xfc);
  19968. }
  19969. bool MidiMessage::isMidiClock() const throw()
  19970. {
  19971. return *data == 0xf8;
  19972. }
  19973. const MidiMessage MidiMessage::midiClock() throw()
  19974. {
  19975. return MidiMessage (0xf8);
  19976. }
  19977. bool MidiMessage::isQuarterFrame() const throw()
  19978. {
  19979. return *data == 0xf1;
  19980. }
  19981. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  19982. {
  19983. return ((int) data[1]) >> 4;
  19984. }
  19985. int MidiMessage::getQuarterFrameValue() const throw()
  19986. {
  19987. return ((int) data[1]) & 0x0f;
  19988. }
  19989. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  19990. const int value) throw()
  19991. {
  19992. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  19993. }
  19994. bool MidiMessage::isFullFrame() const throw()
  19995. {
  19996. return data[0] == 0xf0
  19997. && data[1] == 0x7f
  19998. && size >= 10
  19999. && data[3] == 0x01
  20000. && data[4] == 0x01;
  20001. }
  20002. void MidiMessage::getFullFrameParameters (int& hours,
  20003. int& minutes,
  20004. int& seconds,
  20005. int& frames,
  20006. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  20007. {
  20008. jassert (isFullFrame());
  20009. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  20010. hours = data[5] & 0x1f;
  20011. minutes = data[6];
  20012. seconds = data[7];
  20013. frames = data[8];
  20014. }
  20015. const MidiMessage MidiMessage::fullFrame (const int hours,
  20016. const int minutes,
  20017. const int seconds,
  20018. const int frames,
  20019. MidiMessage::SmpteTimecodeType timecodeType)
  20020. {
  20021. uint8 d[10];
  20022. d[0] = 0xf0;
  20023. d[1] = 0x7f;
  20024. d[2] = 0x7f;
  20025. d[3] = 0x01;
  20026. d[4] = 0x01;
  20027. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  20028. d[6] = (uint8) minutes;
  20029. d[7] = (uint8) seconds;
  20030. d[8] = (uint8) frames;
  20031. d[9] = 0xf7;
  20032. return MidiMessage (d, 10, 0.0);
  20033. }
  20034. bool MidiMessage::isMidiMachineControlMessage() const throw()
  20035. {
  20036. return data[0] == 0xf0
  20037. && data[1] == 0x7f
  20038. && data[3] == 0x06
  20039. && size > 5;
  20040. }
  20041. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  20042. {
  20043. jassert (isMidiMachineControlMessage());
  20044. return (MidiMachineControlCommand) data[4];
  20045. }
  20046. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  20047. {
  20048. uint8 d[6];
  20049. d[0] = 0xf0;
  20050. d[1] = 0x7f;
  20051. d[2] = 0x00;
  20052. d[3] = 0x06;
  20053. d[4] = (uint8) command;
  20054. d[5] = 0xf7;
  20055. return MidiMessage (d, 6, 0.0);
  20056. }
  20057. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  20058. int& minutes,
  20059. int& seconds,
  20060. int& frames) const throw()
  20061. {
  20062. if (size >= 12
  20063. && data[0] == 0xf0
  20064. && data[1] == 0x7f
  20065. && data[3] == 0x06
  20066. && data[4] == 0x44
  20067. && data[5] == 0x06
  20068. && data[6] == 0x01)
  20069. {
  20070. hours = data[7] % 24; // (that some machines send out hours > 24)
  20071. minutes = data[8];
  20072. seconds = data[9];
  20073. frames = data[10];
  20074. return true;
  20075. }
  20076. return false;
  20077. }
  20078. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  20079. int minutes,
  20080. int seconds,
  20081. int frames)
  20082. {
  20083. uint8 d[12];
  20084. d[0] = 0xf0;
  20085. d[1] = 0x7f;
  20086. d[2] = 0x00;
  20087. d[3] = 0x06;
  20088. d[4] = 0x44;
  20089. d[5] = 0x06;
  20090. d[6] = 0x01;
  20091. d[7] = (uint8) hours;
  20092. d[8] = (uint8) minutes;
  20093. d[9] = (uint8) seconds;
  20094. d[10] = (uint8) frames;
  20095. d[11] = 0xf7;
  20096. return MidiMessage (d, 12, 0.0);
  20097. }
  20098. const String MidiMessage::getMidiNoteName (int note,
  20099. bool useSharps,
  20100. bool includeOctaveNumber,
  20101. int octaveNumForMiddleC) throw()
  20102. {
  20103. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  20104. "F", "F#", "G", "G#", "A",
  20105. "A#", "B" };
  20106. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  20107. "F", "Gb", "G", "Ab", "A",
  20108. "Bb", "B" };
  20109. if (((unsigned int) note) < 128)
  20110. {
  20111. const String s ((useSharps) ? sharpNoteNames [note % 12]
  20112. : flatNoteNames [note % 12]);
  20113. if (includeOctaveNumber)
  20114. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  20115. else
  20116. return s;
  20117. }
  20118. return String::empty;
  20119. }
  20120. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  20121. {
  20122. noteNumber -= 12 * 6 + 9; // now 0 = A440
  20123. return 440.0 * pow (2.0, noteNumber / 12.0);
  20124. }
  20125. const String MidiMessage::getGMInstrumentName (int n) throw()
  20126. {
  20127. const char *names[] =
  20128. {
  20129. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  20130. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  20131. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  20132. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  20133. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  20134. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  20135. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  20136. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  20137. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  20138. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  20139. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  20140. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  20141. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  20142. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  20143. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  20144. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  20145. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  20146. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  20147. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  20148. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  20149. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  20150. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  20151. "Applause", "Gunshot"
  20152. };
  20153. return (((unsigned int) n) < 128) ? names[n]
  20154. : (const char*)0;
  20155. }
  20156. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  20157. {
  20158. const char* names[] =
  20159. {
  20160. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  20161. "Bass", "Strings", "Ensemble", "Brass",
  20162. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  20163. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  20164. };
  20165. return (((unsigned int) n) <= 15) ? names[n]
  20166. : (const char*)0;
  20167. }
  20168. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  20169. {
  20170. const char* names[] =
  20171. {
  20172. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  20173. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  20174. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  20175. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  20176. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  20177. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  20178. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  20179. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  20180. "Mute Triangle", "Open Triangle"
  20181. };
  20182. return (n >= 35 && n <= 81) ? names [n - 35]
  20183. : (const char*)0;
  20184. }
  20185. const String MidiMessage::getControllerName (int n) throw()
  20186. {
  20187. const char* names[] =
  20188. {
  20189. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  20190. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  20191. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  20192. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  20193. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  20194. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  20195. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  20196. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  20197. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  20198. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  20199. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  20200. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  20201. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  20202. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  20203. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  20204. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  20205. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  20206. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  20207. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  20208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  20209. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  20210. "Poly Operation"
  20211. };
  20212. return (((unsigned int) n) < 128) ? names[n]
  20213. : (const char*)0;
  20214. }
  20215. END_JUCE_NAMESPACE
  20216. /********* End of inlined file: juce_MidiMessage.cpp *********/
  20217. /********* Start of inlined file: juce_MidiMessageCollector.cpp *********/
  20218. BEGIN_JUCE_NAMESPACE
  20219. MidiMessageCollector::MidiMessageCollector()
  20220. : lastCallbackTime (0),
  20221. sampleRate (44100.0001)
  20222. {
  20223. }
  20224. MidiMessageCollector::~MidiMessageCollector()
  20225. {
  20226. }
  20227. void MidiMessageCollector::reset (const double sampleRate_)
  20228. {
  20229. jassert (sampleRate_ > 0);
  20230. const ScopedLock sl (midiCallbackLock);
  20231. sampleRate = sampleRate_;
  20232. incomingMessages.clear();
  20233. lastCallbackTime = Time::getMillisecondCounterHiRes();
  20234. }
  20235. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  20236. {
  20237. // you need to call reset() to set the correct sample rate before using this object
  20238. jassert (sampleRate != 44100.0001);
  20239. // the messages that come in here need to be time-stamped correctly - see MidiInput
  20240. // for details of what the number should be.
  20241. jassert (message.getTimeStamp() != 0);
  20242. const ScopedLock sl (midiCallbackLock);
  20243. const int sampleNumber
  20244. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  20245. incomingMessages.addEvent (message, sampleNumber);
  20246. // if the messages don't get used for over a second, we'd better
  20247. // get rid of any old ones to avoid the queue getting too big
  20248. if (sampleNumber > sampleRate)
  20249. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  20250. }
  20251. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  20252. const int numSamples)
  20253. {
  20254. // you need to call reset() to set the correct sample rate before using this object
  20255. jassert (sampleRate != 44100.0001);
  20256. const double timeNow = Time::getMillisecondCounterHiRes();
  20257. const double msElapsed = timeNow - lastCallbackTime;
  20258. const ScopedLock sl (midiCallbackLock);
  20259. lastCallbackTime = timeNow;
  20260. if (! incomingMessages.isEmpty())
  20261. {
  20262. int numSourceSamples = jmax (1, roundDoubleToInt (msElapsed * 0.001 * sampleRate));
  20263. int startSample = 0;
  20264. int scale = 1 << 16;
  20265. const uint8* midiData;
  20266. int numBytes, samplePosition;
  20267. MidiBuffer::Iterator iter (incomingMessages);
  20268. if (numSourceSamples > numSamples)
  20269. {
  20270. // if our list of events is longer than the buffer we're being
  20271. // asked for, scale them down to squeeze them all in..
  20272. const int maxBlockLengthToUse = numSamples << 3;
  20273. if (numSourceSamples > maxBlockLengthToUse)
  20274. {
  20275. startSample = numSourceSamples - maxBlockLengthToUse;
  20276. numSourceSamples = maxBlockLengthToUse;
  20277. iter.setNextSamplePosition (startSample);
  20278. }
  20279. scale = (numSamples << 10) / numSourceSamples;
  20280. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  20281. {
  20282. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  20283. destBuffer.addEvent (midiData, numBytes,
  20284. jlimit (0, numSamples - 1, samplePosition));
  20285. }
  20286. }
  20287. else
  20288. {
  20289. // if our event list is shorter than the number we need, put them
  20290. // towards the end of the buffer
  20291. startSample = numSamples - numSourceSamples;
  20292. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  20293. {
  20294. destBuffer.addEvent (midiData, numBytes,
  20295. jlimit (0, numSamples - 1, samplePosition + startSample));
  20296. }
  20297. }
  20298. incomingMessages.clear();
  20299. }
  20300. }
  20301. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  20302. {
  20303. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  20304. m.setTimeStamp (Time::getMillisecondCounter() * 0.001);
  20305. addMessageToQueue (m);
  20306. }
  20307. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  20308. {
  20309. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  20310. m.setTimeStamp (Time::getMillisecondCounter() * 0.001);
  20311. addMessageToQueue (m);
  20312. }
  20313. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  20314. {
  20315. addMessageToQueue (message);
  20316. }
  20317. END_JUCE_NAMESPACE
  20318. /********* End of inlined file: juce_MidiMessageCollector.cpp *********/
  20319. /********* Start of inlined file: juce_MidiMessageSequence.cpp *********/
  20320. BEGIN_JUCE_NAMESPACE
  20321. MidiMessageSequence::MidiMessageSequence()
  20322. {
  20323. }
  20324. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  20325. {
  20326. list.ensureStorageAllocated (other.list.size());
  20327. for (int i = 0; i < other.list.size(); ++i)
  20328. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  20329. }
  20330. const MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  20331. {
  20332. if (this != &other)
  20333. {
  20334. clear();
  20335. for (int i = 0; i < other.list.size(); ++i)
  20336. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  20337. }
  20338. return *this;
  20339. }
  20340. MidiMessageSequence::~MidiMessageSequence()
  20341. {
  20342. }
  20343. void MidiMessageSequence::clear()
  20344. {
  20345. list.clear();
  20346. }
  20347. int MidiMessageSequence::getNumEvents() const
  20348. {
  20349. return list.size();
  20350. }
  20351. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  20352. {
  20353. return list [index];
  20354. }
  20355. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  20356. {
  20357. const MidiEventHolder* const meh = list [index];
  20358. if (meh != 0 && meh->noteOffObject != 0)
  20359. return meh->noteOffObject->message.getTimeStamp();
  20360. else
  20361. return 0.0;
  20362. }
  20363. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  20364. {
  20365. const MidiEventHolder* const meh = list [index];
  20366. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  20367. }
  20368. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  20369. {
  20370. return list.indexOf (event);
  20371. }
  20372. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  20373. {
  20374. const int numEvents = list.size();
  20375. int i;
  20376. for (i = 0; i < numEvents; ++i)
  20377. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  20378. break;
  20379. return i;
  20380. }
  20381. double MidiMessageSequence::getStartTime() const
  20382. {
  20383. if (list.size() > 0)
  20384. return list.getUnchecked(0)->message.getTimeStamp();
  20385. else
  20386. return 0;
  20387. }
  20388. double MidiMessageSequence::getEndTime() const
  20389. {
  20390. if (list.size() > 0)
  20391. return list.getLast()->message.getTimeStamp();
  20392. else
  20393. return 0;
  20394. }
  20395. double MidiMessageSequence::getEventTime (const int index) const
  20396. {
  20397. if (((unsigned int) index) < (unsigned int) list.size())
  20398. return list.getUnchecked (index)->message.getTimeStamp();
  20399. return 0.0;
  20400. }
  20401. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  20402. double timeAdjustment)
  20403. {
  20404. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  20405. timeAdjustment += newMessage.getTimeStamp();
  20406. newOne->message.setTimeStamp (timeAdjustment);
  20407. int i;
  20408. for (i = list.size(); --i >= 0;)
  20409. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  20410. break;
  20411. list.insert (i + 1, newOne);
  20412. }
  20413. void MidiMessageSequence::deleteEvent (const int index,
  20414. const bool deleteMatchingNoteUp)
  20415. {
  20416. if (((unsigned int) index) < (unsigned int) list.size())
  20417. {
  20418. if (deleteMatchingNoteUp)
  20419. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  20420. list.remove (index);
  20421. }
  20422. }
  20423. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  20424. double timeAdjustment,
  20425. double firstAllowableTime,
  20426. double endOfAllowableDestTimes)
  20427. {
  20428. firstAllowableTime -= timeAdjustment;
  20429. endOfAllowableDestTimes -= timeAdjustment;
  20430. for (int i = 0; i < other.list.size(); ++i)
  20431. {
  20432. const MidiMessage& m = other.list.getUnchecked(i)->message;
  20433. const double t = m.getTimeStamp();
  20434. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  20435. {
  20436. MidiEventHolder* const newOne = new MidiEventHolder (m);
  20437. newOne->message.setTimeStamp (timeAdjustment + t);
  20438. list.add (newOne);
  20439. }
  20440. }
  20441. sort();
  20442. }
  20443. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  20444. const MidiMessageSequence::MidiEventHolder* const second) throw()
  20445. {
  20446. const double diff = first->message.getTimeStamp()
  20447. - second->message.getTimeStamp();
  20448. return (diff == 0) ? 0
  20449. : ((diff > 0) ? 1
  20450. : -1);
  20451. }
  20452. void MidiMessageSequence::sort()
  20453. {
  20454. list.sort (*this, true);
  20455. }
  20456. void MidiMessageSequence::updateMatchedPairs()
  20457. {
  20458. for (int i = 0; i < list.size(); ++i)
  20459. {
  20460. const MidiMessage& m1 = list.getUnchecked(i)->message;
  20461. if (m1.isNoteOn())
  20462. {
  20463. list.getUnchecked(i)->noteOffObject = 0;
  20464. const int note = m1.getNoteNumber();
  20465. const int chan = m1.getChannel();
  20466. const int len = list.size();
  20467. for (int j = i + 1; j < len; ++j)
  20468. {
  20469. const MidiMessage& m = list.getUnchecked(j)->message;
  20470. if (m.getNoteNumber() == note && m.getChannel() == chan)
  20471. {
  20472. if (m.isNoteOff())
  20473. {
  20474. list.getUnchecked(i)->noteOffObject = list[j];
  20475. break;
  20476. }
  20477. else if (m.isNoteOn())
  20478. {
  20479. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  20480. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  20481. list.getUnchecked(i)->noteOffObject = list[j];
  20482. break;
  20483. }
  20484. }
  20485. }
  20486. }
  20487. }
  20488. }
  20489. void MidiMessageSequence::addTimeToMessages (const double delta)
  20490. {
  20491. for (int i = list.size(); --i >= 0;)
  20492. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  20493. + delta);
  20494. }
  20495. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  20496. MidiMessageSequence& destSequence,
  20497. const bool alsoIncludeMetaEvents) const
  20498. {
  20499. for (int i = 0; i < list.size(); ++i)
  20500. {
  20501. const MidiMessage& mm = list.getUnchecked(i)->message;
  20502. if (mm.isForChannel (channelNumberToExtract)
  20503. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  20504. {
  20505. destSequence.addEvent (mm);
  20506. }
  20507. }
  20508. }
  20509. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  20510. {
  20511. for (int i = 0; i < list.size(); ++i)
  20512. {
  20513. const MidiMessage& mm = list.getUnchecked(i)->message;
  20514. if (mm.isSysEx())
  20515. destSequence.addEvent (mm);
  20516. }
  20517. }
  20518. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  20519. {
  20520. for (int i = list.size(); --i >= 0;)
  20521. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  20522. list.remove(i);
  20523. }
  20524. void MidiMessageSequence::deleteSysExMessages()
  20525. {
  20526. for (int i = list.size(); --i >= 0;)
  20527. if (list.getUnchecked(i)->message.isSysEx())
  20528. list.remove(i);
  20529. }
  20530. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  20531. const double time,
  20532. OwnedArray<MidiMessage>& dest)
  20533. {
  20534. bool doneProg = false;
  20535. bool donePitchWheel = false;
  20536. Array <int> doneControllers (32);
  20537. for (int i = list.size(); --i >= 0;)
  20538. {
  20539. const MidiMessage& mm = list.getUnchecked(i)->message;
  20540. if (mm.isForChannel (channelNumber)
  20541. && mm.getTimeStamp() <= time)
  20542. {
  20543. if (mm.isProgramChange())
  20544. {
  20545. if (! doneProg)
  20546. {
  20547. dest.add (new MidiMessage (mm, 0.0));
  20548. doneProg = true;
  20549. }
  20550. }
  20551. else if (mm.isController())
  20552. {
  20553. if (! doneControllers.contains (mm.getControllerNumber()))
  20554. {
  20555. dest.add (new MidiMessage (mm, 0.0));
  20556. doneControllers.add (mm.getControllerNumber());
  20557. }
  20558. }
  20559. else if (mm.isPitchWheel())
  20560. {
  20561. if (! donePitchWheel)
  20562. {
  20563. dest.add (new MidiMessage (mm, 0.0));
  20564. donePitchWheel = true;
  20565. }
  20566. }
  20567. }
  20568. }
  20569. }
  20570. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  20571. : message (message_),
  20572. noteOffObject (0)
  20573. {
  20574. }
  20575. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  20576. {
  20577. }
  20578. END_JUCE_NAMESPACE
  20579. /********* End of inlined file: juce_MidiMessageSequence.cpp *********/
  20580. /********* Start of inlined file: juce_AudioPluginFormat.cpp *********/
  20581. BEGIN_JUCE_NAMESPACE
  20582. AudioPluginFormat::AudioPluginFormat() throw()
  20583. {
  20584. }
  20585. AudioPluginFormat::~AudioPluginFormat()
  20586. {
  20587. }
  20588. END_JUCE_NAMESPACE
  20589. /********* End of inlined file: juce_AudioPluginFormat.cpp *********/
  20590. /********* Start of inlined file: juce_AudioPluginFormatManager.cpp *********/
  20591. BEGIN_JUCE_NAMESPACE
  20592. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  20593. {
  20594. }
  20595. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  20596. {
  20597. }
  20598. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  20599. void AudioPluginFormatManager::addDefaultFormats()
  20600. {
  20601. #ifdef JUCE_DEBUG
  20602. // you should only call this method once!
  20603. for (int i = formats.size(); --i >= 0;)
  20604. {
  20605. #if JUCE_PLUGINHOST_VST
  20606. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  20607. #endif
  20608. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  20609. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  20610. #endif
  20611. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  20612. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  20613. #endif
  20614. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  20615. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  20616. #endif
  20617. }
  20618. #endif
  20619. #if JUCE_PLUGINHOST_VST
  20620. formats.add (new VSTPluginFormat());
  20621. #endif
  20622. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  20623. formats.add (new AudioUnitPluginFormat());
  20624. #endif
  20625. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  20626. formats.add (new DirectXPluginFormat());
  20627. #endif
  20628. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  20629. formats.add (new LADSPAPluginFormat());
  20630. #endif
  20631. }
  20632. int AudioPluginFormatManager::getNumFormats() throw()
  20633. {
  20634. return formats.size();
  20635. }
  20636. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  20637. {
  20638. return formats [index];
  20639. }
  20640. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  20641. {
  20642. formats.add (format);
  20643. }
  20644. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  20645. String& errorMessage) const
  20646. {
  20647. AudioPluginInstance* result = 0;
  20648. for (int i = 0; i < formats.size(); ++i)
  20649. {
  20650. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  20651. if (result != 0)
  20652. break;
  20653. }
  20654. if (result == 0)
  20655. {
  20656. if (description.file != File::nonexistent && ! description.file.exists())
  20657. errorMessage = TRANS ("This plug-in file no longer exists");
  20658. else
  20659. errorMessage = TRANS ("This plug-in failed to load correctly");
  20660. }
  20661. return result;
  20662. }
  20663. END_JUCE_NAMESPACE
  20664. /********* End of inlined file: juce_AudioPluginFormatManager.cpp *********/
  20665. /********* Start of inlined file: juce_AudioPluginInstance.cpp *********/
  20666. #define JUCE_PLUGIN_HOST 1
  20667. BEGIN_JUCE_NAMESPACE
  20668. AudioPluginInstance::AudioPluginInstance()
  20669. {
  20670. }
  20671. AudioPluginInstance::~AudioPluginInstance()
  20672. {
  20673. }
  20674. END_JUCE_NAMESPACE
  20675. /********* End of inlined file: juce_AudioPluginInstance.cpp *********/
  20676. /********* Start of inlined file: juce_KnownPluginList.cpp *********/
  20677. BEGIN_JUCE_NAMESPACE
  20678. KnownPluginList::KnownPluginList()
  20679. {
  20680. }
  20681. KnownPluginList::~KnownPluginList()
  20682. {
  20683. }
  20684. void KnownPluginList::clear()
  20685. {
  20686. if (types.size() > 0)
  20687. {
  20688. types.clear();
  20689. sendChangeMessage (this);
  20690. }
  20691. }
  20692. PluginDescription* KnownPluginList::getTypeForFile (const File& file) const throw()
  20693. {
  20694. for (int i = 0; i < types.size(); ++i)
  20695. if (types.getUnchecked(i)->file == file)
  20696. return types.getUnchecked(i);
  20697. return 0;
  20698. }
  20699. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  20700. {
  20701. for (int i = 0; i < types.size(); ++i)
  20702. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  20703. return types.getUnchecked(i);
  20704. return 0;
  20705. }
  20706. bool KnownPluginList::addType (const PluginDescription& type)
  20707. {
  20708. for (int i = types.size(); --i >= 0;)
  20709. {
  20710. if (types.getUnchecked(i)->isDuplicateOf (type))
  20711. {
  20712. // strange - found a duplicate plugin with different info..
  20713. jassert (types.getUnchecked(i)->name == type.name);
  20714. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  20715. *types.getUnchecked(i) = type;
  20716. return false;
  20717. }
  20718. }
  20719. types.add (new PluginDescription (type));
  20720. sendChangeMessage (this);
  20721. return true;
  20722. }
  20723. void KnownPluginList::removeType (const int index) throw()
  20724. {
  20725. types.remove (index);
  20726. sendChangeMessage (this);
  20727. }
  20728. bool KnownPluginList::isListingUpToDate (const File& possiblePluginFile) const throw()
  20729. {
  20730. if (getTypeForFile (possiblePluginFile) == 0)
  20731. return false;
  20732. for (int i = types.size(); --i >= 0;)
  20733. {
  20734. const PluginDescription* const d = types.getUnchecked(i);
  20735. if (d->file == possiblePluginFile
  20736. && d->lastFileModTime != possiblePluginFile.getLastModificationTime())
  20737. {
  20738. return false;
  20739. }
  20740. }
  20741. return true;
  20742. }
  20743. bool KnownPluginList::scanAndAddFile (const File& possiblePluginFile,
  20744. const bool dontRescanIfAlreadyInList,
  20745. OwnedArray <PluginDescription>& typesFound)
  20746. {
  20747. bool addedOne = false;
  20748. if (dontRescanIfAlreadyInList
  20749. && getTypeForFile (possiblePluginFile) != 0)
  20750. {
  20751. bool needsRescanning = false;
  20752. for (int i = types.size(); --i >= 0;)
  20753. {
  20754. const PluginDescription* const d = types.getUnchecked(i);
  20755. if (d->file == possiblePluginFile)
  20756. {
  20757. if (d->lastFileModTime != possiblePluginFile.getLastModificationTime())
  20758. needsRescanning = true;
  20759. else
  20760. typesFound.add (new PluginDescription (*d));
  20761. }
  20762. }
  20763. if (! needsRescanning)
  20764. return false;
  20765. }
  20766. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  20767. {
  20768. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  20769. OwnedArray <PluginDescription> found;
  20770. format->findAllTypesForFile (found, possiblePluginFile);
  20771. for (int i = 0; i < found.size(); ++i)
  20772. {
  20773. PluginDescription* const desc = found.getUnchecked(i);
  20774. jassert (desc != 0);
  20775. if (addType (*desc))
  20776. addedOne = true;
  20777. typesFound.add (new PluginDescription (*desc));
  20778. }
  20779. }
  20780. return addedOne;
  20781. }
  20782. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  20783. OwnedArray <PluginDescription>& typesFound)
  20784. {
  20785. for (int i = 0; i < files.size(); ++i)
  20786. {
  20787. const File f (files [i]);
  20788. if (! scanAndAddFile (f, true, typesFound))
  20789. {
  20790. if (f.isDirectory())
  20791. {
  20792. StringArray s;
  20793. {
  20794. OwnedArray <File> subFiles;
  20795. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  20796. for (int j = 0; j < subFiles.size(); ++j)
  20797. s.add (subFiles.getUnchecked (j)->getFullPathName());
  20798. }
  20799. scanAndAddDragAndDroppedFiles (s, typesFound);
  20800. }
  20801. }
  20802. }
  20803. }
  20804. class PluginSorter
  20805. {
  20806. public:
  20807. KnownPluginList::SortMethod method;
  20808. PluginSorter() throw() {}
  20809. int compareElements (const PluginDescription* const first,
  20810. const PluginDescription* const second) const throw()
  20811. {
  20812. int diff = 0;
  20813. if (method == KnownPluginList::sortByCategory)
  20814. diff = first->category.compareLexicographically (second->category);
  20815. else if (method == KnownPluginList::sortByManufacturer)
  20816. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  20817. else if (method == KnownPluginList::sortByFileSystemLocation)
  20818. diff = first->file.getParentDirectory().getFullPathName().compare (second->file.getParentDirectory().getFullPathName());
  20819. if (diff == 0)
  20820. diff = first->name.compareLexicographically (second->name);
  20821. return diff;
  20822. }
  20823. };
  20824. void KnownPluginList::sort (const SortMethod method)
  20825. {
  20826. if (method != defaultOrder)
  20827. {
  20828. PluginSorter sorter;
  20829. sorter.method = method;
  20830. types.sort (sorter, true);
  20831. sendChangeMessage (this);
  20832. }
  20833. }
  20834. XmlElement* KnownPluginList::createXml() const
  20835. {
  20836. XmlElement* const e = new XmlElement (T("KNOWNPLUGINS"));
  20837. for (int i = 0; i < types.size(); ++i)
  20838. e->addChildElement (types.getUnchecked(i)->createXml());
  20839. return e;
  20840. }
  20841. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  20842. {
  20843. clear();
  20844. if (xml.hasTagName (T("KNOWNPLUGINS")))
  20845. {
  20846. forEachXmlChildElement (xml, e)
  20847. {
  20848. PluginDescription info;
  20849. if (info.loadFromXml (*e))
  20850. addType (info);
  20851. }
  20852. }
  20853. }
  20854. const int menuIdBase = 0x324503f4;
  20855. // This is used to turn a bunch of paths into a nested menu structure.
  20856. struct PluginFilesystemTree
  20857. {
  20858. private:
  20859. String folder;
  20860. OwnedArray <PluginFilesystemTree> subFolders;
  20861. Array <PluginDescription*> plugins;
  20862. void addPlugin (PluginDescription* const pd, const String& path)
  20863. {
  20864. if (path.isEmpty())
  20865. {
  20866. plugins.add (pd);
  20867. }
  20868. else
  20869. {
  20870. const String firstSubFolder (path.upToFirstOccurrenceOf (T("/"), false, false));
  20871. const String remainingPath (path.fromFirstOccurrenceOf (T("/"), false, false));
  20872. for (int i = subFolders.size(); --i >= 0;)
  20873. {
  20874. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  20875. {
  20876. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  20877. return;
  20878. }
  20879. }
  20880. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  20881. newFolder->folder = firstSubFolder;
  20882. subFolders.add (newFolder);
  20883. newFolder->addPlugin (pd, remainingPath);
  20884. }
  20885. }
  20886. // removes any deeply nested folders that don't contain any actual plugins
  20887. void optimise()
  20888. {
  20889. for (int i = subFolders.size(); --i >= 0;)
  20890. {
  20891. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  20892. sub->optimise();
  20893. if (sub->plugins.size() == 0)
  20894. {
  20895. for (int j = 0; j < sub->subFolders.size(); ++j)
  20896. subFolders.add (sub->subFolders.getUnchecked(j));
  20897. sub->subFolders.clear (false);
  20898. subFolders.remove (i);
  20899. }
  20900. }
  20901. }
  20902. public:
  20903. void buildTree (const Array <PluginDescription*>& allPlugins)
  20904. {
  20905. for (int i = 0; i < allPlugins.size(); ++i)
  20906. {
  20907. String path (allPlugins.getUnchecked(i)->file.getParentDirectory().getFullPathName());
  20908. if (path.substring (1, 2) == T(":"))
  20909. path = path.substring (2);
  20910. path = path.replaceCharacter (T('\\'), T('/'));
  20911. addPlugin (allPlugins.getUnchecked(i), path);
  20912. }
  20913. optimise();
  20914. }
  20915. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  20916. {
  20917. int i;
  20918. for (i = 0; i < subFolders.size(); ++i)
  20919. {
  20920. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  20921. PopupMenu subMenu;
  20922. sub->addToMenu (subMenu, allPlugins);
  20923. m.addSubMenu (sub->folder, subMenu);
  20924. }
  20925. for (i = 0; i < plugins.size(); ++i)
  20926. {
  20927. PluginDescription* const plugin = plugins.getUnchecked(i);
  20928. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  20929. plugin->name, true, false);
  20930. }
  20931. }
  20932. };
  20933. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  20934. {
  20935. Array <PluginDescription*> sorted;
  20936. {
  20937. PluginSorter sorter;
  20938. sorter.method = sortMethod;
  20939. for (int i = 0; i < types.size(); ++i)
  20940. sorted.addSorted (sorter, types.getUnchecked(i));
  20941. }
  20942. if (sortMethod == sortByCategory
  20943. || sortMethod == sortByManufacturer)
  20944. {
  20945. String lastSubMenuName;
  20946. PopupMenu sub;
  20947. for (int i = 0; i < sorted.size(); ++i)
  20948. {
  20949. const PluginDescription* const pd = sorted.getUnchecked(i);
  20950. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  20951. : pd->manufacturerName);
  20952. if (thisSubMenuName.trim().isEmpty())
  20953. thisSubMenuName = T("Other");
  20954. if (thisSubMenuName != lastSubMenuName)
  20955. {
  20956. if (sub.getNumItems() > 0)
  20957. {
  20958. menu.addSubMenu (lastSubMenuName, sub);
  20959. sub.clear();
  20960. }
  20961. lastSubMenuName = thisSubMenuName;
  20962. }
  20963. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  20964. }
  20965. if (sub.getNumItems() > 0)
  20966. menu.addSubMenu (lastSubMenuName, sub);
  20967. }
  20968. else if (sortMethod == sortByFileSystemLocation)
  20969. {
  20970. PluginFilesystemTree root;
  20971. root.buildTree (sorted);
  20972. root.addToMenu (menu, types);
  20973. }
  20974. else
  20975. {
  20976. for (int i = 0; i < sorted.size(); ++i)
  20977. {
  20978. const PluginDescription* const pd = sorted.getUnchecked(i);
  20979. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  20980. }
  20981. }
  20982. }
  20983. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  20984. {
  20985. const int i = menuResultCode - menuIdBase;
  20986. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  20987. }
  20988. END_JUCE_NAMESPACE
  20989. /********* End of inlined file: juce_KnownPluginList.cpp *********/
  20990. /********* Start of inlined file: juce_PluginDescription.cpp *********/
  20991. BEGIN_JUCE_NAMESPACE
  20992. PluginDescription::PluginDescription() throw()
  20993. : uid (0),
  20994. isInstrument (false),
  20995. numInputChannels (0),
  20996. numOutputChannels (0)
  20997. {
  20998. }
  20999. PluginDescription::~PluginDescription() throw()
  21000. {
  21001. }
  21002. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  21003. : name (other.name),
  21004. pluginFormatName (other.pluginFormatName),
  21005. category (other.category),
  21006. manufacturerName (other.manufacturerName),
  21007. version (other.version),
  21008. file (other.file),
  21009. lastFileModTime (other.lastFileModTime),
  21010. uid (other.uid),
  21011. isInstrument (other.isInstrument),
  21012. numInputChannels (other.numInputChannels),
  21013. numOutputChannels (other.numOutputChannels)
  21014. {
  21015. }
  21016. const PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  21017. {
  21018. name = other.name;
  21019. pluginFormatName = other.pluginFormatName;
  21020. category = other.category;
  21021. manufacturerName = other.manufacturerName;
  21022. version = other.version;
  21023. file = other.file;
  21024. uid = other.uid;
  21025. isInstrument = other.isInstrument;
  21026. lastFileModTime = other.lastFileModTime;
  21027. numInputChannels = other.numInputChannels;
  21028. numOutputChannels = other.numOutputChannels;
  21029. return *this;
  21030. }
  21031. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  21032. {
  21033. return file == other.file
  21034. && uid == other.uid;
  21035. }
  21036. const String PluginDescription::createIdentifierString() const throw()
  21037. {
  21038. return pluginFormatName
  21039. + T("-") + name
  21040. + T("-") + String::toHexString (file.getFileName().hashCode())
  21041. + T("-") + String::toHexString (uid);
  21042. }
  21043. XmlElement* PluginDescription::createXml() const
  21044. {
  21045. XmlElement* const e = new XmlElement (T("PLUGIN"));
  21046. e->setAttribute (T("name"), name);
  21047. e->setAttribute (T("format"), pluginFormatName);
  21048. e->setAttribute (T("category"), category);
  21049. e->setAttribute (T("manufacturer"), manufacturerName);
  21050. e->setAttribute (T("version"), version);
  21051. e->setAttribute (T("file"), file.getFullPathName());
  21052. e->setAttribute (T("uid"), String::toHexString (uid));
  21053. e->setAttribute (T("isInstrument"), isInstrument);
  21054. e->setAttribute (T("fileTime"), String::toHexString (lastFileModTime.toMilliseconds()));
  21055. e->setAttribute (T("numInputs"), numInputChannels);
  21056. e->setAttribute (T("numOutputs"), numOutputChannels);
  21057. return e;
  21058. }
  21059. bool PluginDescription::loadFromXml (const XmlElement& xml)
  21060. {
  21061. if (xml.hasTagName (T("PLUGIN")))
  21062. {
  21063. name = xml.getStringAttribute (T("name"));
  21064. pluginFormatName = xml.getStringAttribute (T("format"));
  21065. category = xml.getStringAttribute (T("category"));
  21066. manufacturerName = xml.getStringAttribute (T("manufacturer"));
  21067. version = xml.getStringAttribute (T("version"));
  21068. file = File (xml.getStringAttribute (T("file")));
  21069. uid = xml.getStringAttribute (T("uid")).getHexValue32();
  21070. isInstrument = xml.getBoolAttribute (T("isInstrument"), false);
  21071. lastFileModTime = Time (xml.getStringAttribute (T("fileTime")).getHexValue64());
  21072. numInputChannels = xml.getIntAttribute (T("numInputs"));
  21073. numOutputChannels = xml.getIntAttribute (T("numOutputs"));
  21074. return true;
  21075. }
  21076. return false;
  21077. }
  21078. END_JUCE_NAMESPACE
  21079. /********* End of inlined file: juce_PluginDescription.cpp *********/
  21080. /********* Start of inlined file: juce_PluginDirectoryScanner.cpp *********/
  21081. BEGIN_JUCE_NAMESPACE
  21082. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  21083. AudioPluginFormat& formatToLookFor,
  21084. FileSearchPath directoriesToSearch,
  21085. const bool recursive,
  21086. const File& deadMansPedalFile_)
  21087. : list (listToAddTo),
  21088. format (formatToLookFor),
  21089. deadMansPedalFile (deadMansPedalFile_),
  21090. nextIndex (0),
  21091. progress (0)
  21092. {
  21093. directoriesToSearch.removeRedundantPaths();
  21094. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  21095. recursiveFileSearch (directoriesToSearch [j], recursive);
  21096. // If any plugins have crashed recently when being loaded, move them to the
  21097. // end of the list to give the others a chance to load correctly..
  21098. const StringArray crashedPlugins (getDeadMansPedalFile());
  21099. for (int i = 0; i < crashedPlugins.size(); ++i)
  21100. {
  21101. const File f (crashedPlugins[i]);
  21102. for (int j = filesToScan.size(); --j >= 0;)
  21103. if (f == *filesToScan.getUnchecked (j))
  21104. filesToScan.move (j, -1);
  21105. }
  21106. }
  21107. void PluginDirectoryScanner::recursiveFileSearch (const File& dir, const bool recursive)
  21108. {
  21109. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  21110. // .component or .vst directories.
  21111. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  21112. while (iter.next())
  21113. {
  21114. const File f (iter.getFile());
  21115. bool isPlugin = false;
  21116. if (format.fileMightContainThisPluginType (f))
  21117. {
  21118. isPlugin = true;
  21119. filesToScan.add (new File (f));
  21120. }
  21121. if (recursive && (! isPlugin) && f.isDirectory())
  21122. recursiveFileSearch (f, true);
  21123. }
  21124. }
  21125. PluginDirectoryScanner::~PluginDirectoryScanner()
  21126. {
  21127. }
  21128. const File PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  21129. {
  21130. File* const file = filesToScan [nextIndex];
  21131. if (file != 0)
  21132. return *file;
  21133. return File::nonexistent;
  21134. }
  21135. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  21136. {
  21137. File* const file = filesToScan [nextIndex];
  21138. if (file != 0)
  21139. {
  21140. if (! list.isListingUpToDate (*file))
  21141. {
  21142. OwnedArray <PluginDescription> typesFound;
  21143. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  21144. StringArray crashedPlugins (getDeadMansPedalFile());
  21145. crashedPlugins.removeString (file->getFullPathName());
  21146. crashedPlugins.add (file->getFullPathName());
  21147. setDeadMansPedalFile (crashedPlugins);
  21148. list.scanAndAddFile (*file,
  21149. dontRescanIfAlreadyInList,
  21150. typesFound);
  21151. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  21152. crashedPlugins.removeString (file->getFullPathName());
  21153. setDeadMansPedalFile (crashedPlugins);
  21154. if (typesFound.size() == 0)
  21155. failedFiles.add (file->getFullPathName());
  21156. }
  21157. ++nextIndex;
  21158. progress = nextIndex / (float) filesToScan.size();
  21159. }
  21160. return nextIndex < filesToScan.size();
  21161. }
  21162. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  21163. {
  21164. StringArray lines;
  21165. if (deadMansPedalFile != File::nonexistent)
  21166. {
  21167. lines.addLines (deadMansPedalFile.loadFileAsString());
  21168. lines.removeEmptyStrings();
  21169. }
  21170. return lines;
  21171. }
  21172. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  21173. {
  21174. if (deadMansPedalFile != File::nonexistent)
  21175. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  21176. }
  21177. END_JUCE_NAMESPACE
  21178. /********* End of inlined file: juce_PluginDirectoryScanner.cpp *********/
  21179. /********* Start of inlined file: juce_PluginListComponent.cpp *********/
  21180. BEGIN_JUCE_NAMESPACE
  21181. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  21182. const File& deadMansPedalFile_,
  21183. PropertiesFile* const propertiesToUse_)
  21184. : list (listToEdit),
  21185. deadMansPedalFile (deadMansPedalFile_),
  21186. propertiesToUse (propertiesToUse_)
  21187. {
  21188. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  21189. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  21190. optionsButton->addButtonListener (this);
  21191. optionsButton->setTriggeredOnMouseDown (true);
  21192. setSize (400, 600);
  21193. list.addChangeListener (this);
  21194. }
  21195. PluginListComponent::~PluginListComponent()
  21196. {
  21197. list.removeChangeListener (this);
  21198. deleteAllChildren();
  21199. }
  21200. void PluginListComponent::resized()
  21201. {
  21202. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  21203. optionsButton->changeWidthToFitText (24);
  21204. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  21205. }
  21206. void PluginListComponent::changeListenerCallback (void*)
  21207. {
  21208. listBox->updateContent();
  21209. listBox->repaint();
  21210. }
  21211. int PluginListComponent::getNumRows()
  21212. {
  21213. return list.getNumTypes();
  21214. }
  21215. void PluginListComponent::paintListBoxItem (int row,
  21216. Graphics& g,
  21217. int width, int height,
  21218. bool rowIsSelected)
  21219. {
  21220. if (rowIsSelected)
  21221. g.fillAll (findColour (TextEditor::highlightColourId));
  21222. const PluginDescription* const pd = list.getType (row);
  21223. if (pd != 0)
  21224. {
  21225. GlyphArrangement ga;
  21226. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  21227. g.setColour (Colours::black);
  21228. ga.draw (g);
  21229. float x, y, r, b;
  21230. ga.getBoundingBox (0, -1, x, y, r, b, false);
  21231. String desc;
  21232. desc << pd->pluginFormatName
  21233. << (pd->isInstrument ? " instrument" : " effect")
  21234. << " - "
  21235. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  21236. << " / "
  21237. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  21238. if (pd->manufacturerName.isNotEmpty())
  21239. desc << " - " << pd->manufacturerName;
  21240. if (pd->version.isNotEmpty())
  21241. desc << " - " << pd->version;
  21242. if (pd->category.isNotEmpty())
  21243. desc << " - category: '" << pd->category << '\'';
  21244. g.setColour (Colours::grey);
  21245. ga.clear();
  21246. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, r + 10.0f, height * 0.8f, width - r - 12.0f, true);
  21247. ga.draw (g);
  21248. }
  21249. }
  21250. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  21251. {
  21252. list.removeType (lastRowSelected);
  21253. }
  21254. void PluginListComponent::buttonClicked (Button* b)
  21255. {
  21256. if (optionsButton == b)
  21257. {
  21258. PopupMenu menu;
  21259. menu.addItem (1, TRANS("Clear list"));
  21260. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  21261. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  21262. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  21263. menu.addSeparator();
  21264. menu.addItem (2, TRANS("Sort alphabetically"));
  21265. menu.addItem (3, TRANS("Sort by category"));
  21266. menu.addItem (4, TRANS("Sort by manufacturer"));
  21267. menu.addSeparator();
  21268. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  21269. {
  21270. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  21271. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  21272. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  21273. }
  21274. const int r = menu.showAt (optionsButton);
  21275. if (r == 1)
  21276. {
  21277. list.clear();
  21278. }
  21279. else if (r == 2)
  21280. {
  21281. list.sort (KnownPluginList::sortAlphabetically);
  21282. }
  21283. else if (r == 3)
  21284. {
  21285. list.sort (KnownPluginList::sortByCategory);
  21286. }
  21287. else if (r == 4)
  21288. {
  21289. list.sort (KnownPluginList::sortByManufacturer);
  21290. }
  21291. else if (r == 5)
  21292. {
  21293. const SparseSet <int> selected (listBox->getSelectedRows());
  21294. for (int i = list.getNumTypes(); --i >= 0;)
  21295. if (selected.contains (i))
  21296. list.removeType (i);
  21297. }
  21298. else if (r == 6)
  21299. {
  21300. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  21301. if (desc != 0)
  21302. desc->file.getParentDirectory().startAsProcess();
  21303. }
  21304. else if (r == 7)
  21305. {
  21306. for (int i = list.getNumTypes(); --i >= 0;)
  21307. {
  21308. if (list.getType (i)->file != File::nonexistent
  21309. && ! list.getType (i)->file.exists())
  21310. {
  21311. list.removeType (i);
  21312. }
  21313. }
  21314. }
  21315. else if (r != 0)
  21316. {
  21317. typeToScan = r - 10;
  21318. startTimer (1);
  21319. }
  21320. }
  21321. }
  21322. void PluginListComponent::timerCallback()
  21323. {
  21324. stopTimer();
  21325. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  21326. }
  21327. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  21328. {
  21329. return true;
  21330. }
  21331. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  21332. {
  21333. OwnedArray <PluginDescription> typesFound;
  21334. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  21335. }
  21336. void PluginListComponent::scanFor (AudioPluginFormat* format)
  21337. {
  21338. if (format == 0)
  21339. return;
  21340. FileSearchPath path (format->getDefaultLocationsToSearch());
  21341. if (propertiesToUse != 0)
  21342. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  21343. {
  21344. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  21345. FileSearchPathListComponent pathList;
  21346. pathList.setSize (500, 300);
  21347. pathList.setPath (path);
  21348. aw.addCustomComponent (&pathList);
  21349. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  21350. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  21351. if (aw.runModalLoop() == 0)
  21352. return;
  21353. path = pathList.getPath();
  21354. }
  21355. if (propertiesToUse != 0)
  21356. {
  21357. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  21358. propertiesToUse->saveIfNeeded();
  21359. }
  21360. double progress = 0.0;
  21361. AlertWindow aw (TRANS("Scanning for plugins..."),
  21362. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  21363. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  21364. aw.addProgressBarComponent (progress);
  21365. aw.enterModalState();
  21366. MessageManager::getInstance()->dispatchPendingMessages();
  21367. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  21368. for (;;)
  21369. {
  21370. aw.setMessage (TRANS("Testing:\n\n")
  21371. + scanner.getNextPluginFileThatWillBeScanned().getFileName());
  21372. MessageManager::getInstance()->dispatchPendingMessages (500);
  21373. if (! scanner.scanNextFile (true))
  21374. break;
  21375. if (! aw.isCurrentlyModal())
  21376. break;
  21377. progress = scanner.getProgress();
  21378. }
  21379. if (scanner.getFailedFiles().size() > 0)
  21380. {
  21381. StringArray shortNames;
  21382. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  21383. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  21384. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  21385. TRANS("Scan complete"),
  21386. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  21387. + shortNames.joinIntoString (", "));
  21388. }
  21389. }
  21390. END_JUCE_NAMESPACE
  21391. /********* End of inlined file: juce_PluginListComponent.cpp *********/
  21392. /********* Start of inlined file: juce_AudioUnitPluginFormat.cpp *********/
  21393. #if JUCE_PLUGINHOST_AU && (! (defined (LINUX) || defined (_WIN32)))
  21394. #include <Carbon/Carbon.h>
  21395. #include <AudioToolbox/AudioToolbox.h>
  21396. #include <AudioUnit/AudioUnitCarbonView.h>
  21397. BEGIN_JUCE_NAMESPACE
  21398. #if JUCE_MAC
  21399. extern void juce_callAnyTimersSynchronously();
  21400. extern bool juce_isHIViewCreatedByJuce (HIViewRef view);
  21401. extern bool juce_isWindowCreatedByJuce (WindowRef window);
  21402. #if MACOS_10_3_OR_EARLIER
  21403. #define kAudioUnitType_Generator 'augn'
  21404. #endif
  21405. // Change this to disable logging of various activities
  21406. #ifndef AU_LOGGING
  21407. #define AU_LOGGING 1
  21408. #endif
  21409. #if AU_LOGGING
  21410. #define log(a) Logger::writeToLog(a);
  21411. #else
  21412. #define log(a)
  21413. #endif
  21414. static int insideCallback = 0;
  21415. class AudioUnitPluginWindow;
  21416. class AudioUnitPluginInstance : public AudioPluginInstance
  21417. {
  21418. public:
  21419. ~AudioUnitPluginInstance();
  21420. // AudioPluginInstance methods:
  21421. void fillInPluginDescription (PluginDescription& desc) const
  21422. {
  21423. desc.name = pluginName;
  21424. desc.file = file;
  21425. desc.uid = ((int) componentDesc.componentType)
  21426. ^ ((int) componentDesc.componentSubType)
  21427. ^ ((int) componentDesc.componentManufacturer);
  21428. desc.lastFileModTime = file.getLastModificationTime();
  21429. desc.pluginFormatName = "AudioUnit";
  21430. desc.category = getCategory();
  21431. desc.manufacturerName = manufacturer;
  21432. desc.version = version;
  21433. desc.numInputChannels = getNumInputChannels();
  21434. desc.numOutputChannels = getNumOutputChannels();
  21435. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  21436. }
  21437. const String getName() const { return pluginName; }
  21438. bool acceptsMidi() const { return wantsMidiMessages; }
  21439. bool producesMidi() const { return false; }
  21440. // AudioProcessor methods:
  21441. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21442. void releaseResources();
  21443. void processBlock (AudioSampleBuffer& buffer,
  21444. MidiBuffer& midiMessages);
  21445. AudioProcessorEditor* createEditor();
  21446. const String getInputChannelName (const int index) const;
  21447. bool isInputChannelStereoPair (int index) const;
  21448. const String getOutputChannelName (const int index) const;
  21449. bool isOutputChannelStereoPair (int index) const;
  21450. int getNumParameters();
  21451. float getParameter (int index);
  21452. void setParameter (int index, float newValue);
  21453. const String getParameterName (int index);
  21454. const String getParameterText (int index);
  21455. bool isParameterAutomatable (int index) const;
  21456. int getNumPrograms();
  21457. int getCurrentProgram();
  21458. void setCurrentProgram (int index);
  21459. const String getProgramName (int index);
  21460. void changeProgramName (int index, const String& newName);
  21461. void getStateInformation (MemoryBlock& destData);
  21462. void getCurrentProgramStateInformation (MemoryBlock& destData);
  21463. void setStateInformation (const void* data, int sizeInBytes);
  21464. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  21465. juce_UseDebuggingNewOperator
  21466. private:
  21467. friend class AudioUnitPluginWindow;
  21468. friend class AudioUnitPluginFormat;
  21469. ComponentDescription componentDesc;
  21470. String pluginName, manufacturer, version;
  21471. File file;
  21472. CriticalSection lock;
  21473. bool initialised, wantsMidiMessages, wasPlaying;
  21474. AudioBufferList* outputBufferList;
  21475. AudioTimeStamp timeStamp;
  21476. AudioSampleBuffer* currentBuffer;
  21477. AudioUnit audioUnit;
  21478. Array <int> parameterIds;
  21479. bool getComponentDescFromFile (const File& file);
  21480. void initialise();
  21481. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  21482. const AudioTimeStamp* inTimeStamp,
  21483. UInt32 inBusNumber,
  21484. UInt32 inNumberFrames,
  21485. AudioBufferList* ioData) const;
  21486. static OSStatus renderGetInputCallback (void* inRefCon,
  21487. AudioUnitRenderActionFlags* ioActionFlags,
  21488. const AudioTimeStamp* inTimeStamp,
  21489. UInt32 inBusNumber,
  21490. UInt32 inNumberFrames,
  21491. AudioBufferList* ioData)
  21492. {
  21493. return ((AudioUnitPluginInstance*) inRefCon)
  21494. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  21495. }
  21496. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  21497. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  21498. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  21499. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  21500. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  21501. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  21502. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  21503. {
  21504. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  21505. }
  21506. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  21507. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  21508. Float64* outCurrentMeasureDownBeat)
  21509. {
  21510. return ((AudioUnitPluginInstance*) inHostUserData)
  21511. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  21512. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  21513. }
  21514. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  21515. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  21516. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  21517. {
  21518. return ((AudioUnitPluginInstance*) inHostUserData)
  21519. ->getTransportState (outIsPlaying, outTransportStateChanged,
  21520. outCurrentSampleInTimeLine, outIsCycling,
  21521. outCycleStartBeat, outCycleEndBeat);
  21522. }
  21523. void getNumChannels (int& numIns, int& numOuts)
  21524. {
  21525. numIns = 0;
  21526. numOuts = 0;
  21527. AUChannelInfo supportedChannels [128];
  21528. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  21529. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  21530. 0, supportedChannels, &supportedChannelsSize) == noErr
  21531. && supportedChannelsSize > 0)
  21532. {
  21533. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  21534. {
  21535. numIns = jmax (numIns, supportedChannels[i].inChannels);
  21536. numOuts = jmax (numOuts, supportedChannels[i].outChannels);
  21537. }
  21538. }
  21539. else
  21540. {
  21541. // (this really means the plugin will take any number of ins/outs as long
  21542. // as they are the same)
  21543. numIns = numOuts = 2;
  21544. }
  21545. }
  21546. const String getCategory() const;
  21547. AudioUnitPluginInstance (const File& file);
  21548. };
  21549. AudioUnitPluginInstance::AudioUnitPluginInstance (const File& file_)
  21550. : file (file_),
  21551. initialised (false),
  21552. wantsMidiMessages (false),
  21553. audioUnit (0),
  21554. outputBufferList (0),
  21555. currentBuffer (0)
  21556. {
  21557. try
  21558. {
  21559. ++insideCallback;
  21560. log (T("Opening AU: ") + file.getFullPathName());
  21561. if (getComponentDescFromFile (file))
  21562. {
  21563. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  21564. if (comp != 0)
  21565. {
  21566. audioUnit = (AudioUnit) OpenComponent (comp);
  21567. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  21568. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  21569. }
  21570. }
  21571. --insideCallback;
  21572. }
  21573. catch (...)
  21574. {
  21575. --insideCallback;
  21576. }
  21577. }
  21578. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  21579. {
  21580. {
  21581. const ScopedLock sl (lock);
  21582. jassert (insideCallback == 0);
  21583. if (audioUnit != 0)
  21584. {
  21585. AudioUnitUninitialize (audioUnit);
  21586. CloseComponent (audioUnit);
  21587. audioUnit = 0;
  21588. }
  21589. }
  21590. juce_free (outputBufferList);
  21591. }
  21592. bool AudioUnitPluginInstance::getComponentDescFromFile (const File& file)
  21593. {
  21594. zerostruct (componentDesc);
  21595. if (! file.hasFileExtension (T(".component")))
  21596. return false;
  21597. const String filename (file.getFullPathName());
  21598. const char* const utf8 = filename.toUTF8();
  21599. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  21600. strlen (utf8), file.isDirectory());
  21601. if (url != 0)
  21602. {
  21603. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  21604. CFRelease (url);
  21605. if (bundleRef != 0)
  21606. {
  21607. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  21608. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  21609. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  21610. if (pluginName.isEmpty())
  21611. pluginName = file.getFileNameWithoutExtension();
  21612. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  21613. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  21614. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  21615. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  21616. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  21617. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  21618. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  21619. UseResFile (resFileId);
  21620. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  21621. {
  21622. Handle h = Get1IndResource ('thng', i);
  21623. if (h != 0)
  21624. {
  21625. HLock (h);
  21626. const uint32* const types = (const uint32*) *h;
  21627. if (types[0] == kAudioUnitType_MusicDevice
  21628. || types[0] == kAudioUnitType_MusicEffect
  21629. || types[0] == kAudioUnitType_Effect
  21630. || types[0] == kAudioUnitType_Generator
  21631. || types[0] == kAudioUnitType_Panner)
  21632. {
  21633. componentDesc.componentType = types[0];
  21634. componentDesc.componentSubType = types[1];
  21635. componentDesc.componentManufacturer = types[2];
  21636. break;
  21637. }
  21638. HUnlock (h);
  21639. ReleaseResource (h);
  21640. }
  21641. }
  21642. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  21643. CFRelease (bundleRef);
  21644. }
  21645. }
  21646. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  21647. }
  21648. void AudioUnitPluginInstance::initialise()
  21649. {
  21650. if (initialised || audioUnit == 0)
  21651. return;
  21652. log (T("Initialising AU: ") + pluginName);
  21653. parameterIds.clear();
  21654. {
  21655. UInt32 paramListSize = 0;
  21656. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  21657. 0, 0, &paramListSize);
  21658. if (paramListSize > 0)
  21659. {
  21660. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  21661. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  21662. 0, &parameterIds.getReference(0), &paramListSize);
  21663. }
  21664. }
  21665. {
  21666. AURenderCallbackStruct info;
  21667. zerostruct (info);
  21668. info.inputProcRefCon = this;
  21669. info.inputProc = renderGetInputCallback;
  21670. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  21671. 0, &info, sizeof (info));
  21672. }
  21673. {
  21674. HostCallbackInfo info;
  21675. zerostruct (info);
  21676. info.hostUserData = this;
  21677. info.beatAndTempoProc = getBeatAndTempoCallback;
  21678. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  21679. info.transportStateProc = getTransportStateCallback;
  21680. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  21681. 0, &info, sizeof (info));
  21682. }
  21683. int numIns, numOuts;
  21684. getNumChannels (numIns, numOuts);
  21685. setPlayConfigDetails (numIns, numOuts, 0, 0);
  21686. initialised = AudioUnitInitialize (audioUnit) == noErr;
  21687. setLatencySamples (0);
  21688. }
  21689. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  21690. int samplesPerBlockExpected)
  21691. {
  21692. initialise();
  21693. if (initialised)
  21694. {
  21695. int numIns, numOuts;
  21696. getNumChannels (numIns, numOuts);
  21697. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  21698. Float64 latencySecs = 0.0;
  21699. UInt32 latencySize = sizeof (latencySecs);
  21700. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  21701. 0, &latencySecs, &latencySize);
  21702. setLatencySamples (roundDoubleToInt (latencySecs * sampleRate_));
  21703. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  21704. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  21705. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  21706. AudioStreamBasicDescription stream;
  21707. zerostruct (stream);
  21708. stream.mSampleRate = sampleRate_;
  21709. stream.mFormatID = kAudioFormatLinearPCM;
  21710. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  21711. stream.mFramesPerPacket = 1;
  21712. stream.mBytesPerPacket = 4;
  21713. stream.mBytesPerFrame = 4;
  21714. stream.mBitsPerChannel = 32;
  21715. stream.mChannelsPerFrame = numIns;
  21716. OSStatus err = AudioUnitSetProperty (audioUnit,
  21717. kAudioUnitProperty_StreamFormat,
  21718. kAudioUnitScope_Input,
  21719. 0, &stream, sizeof (stream));
  21720. stream.mChannelsPerFrame = numOuts;
  21721. err = AudioUnitSetProperty (audioUnit,
  21722. kAudioUnitProperty_StreamFormat,
  21723. kAudioUnitScope_Output,
  21724. 0, &stream, sizeof (stream));
  21725. juce_free (outputBufferList);
  21726. outputBufferList = (AudioBufferList*) juce_calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1));
  21727. outputBufferList->mNumberBuffers = numOuts;
  21728. for (int i = numOuts; --i >= 0;)
  21729. outputBufferList->mBuffers[i].mNumberChannels = 1;
  21730. zerostruct (timeStamp);
  21731. timeStamp.mSampleTime = 0;
  21732. timeStamp.mHostTime = AudioGetCurrentHostTime();
  21733. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  21734. currentBuffer = 0;
  21735. wasPlaying = false;
  21736. }
  21737. }
  21738. void AudioUnitPluginInstance::releaseResources()
  21739. {
  21740. if (initialised)
  21741. {
  21742. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  21743. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  21744. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  21745. juce_free (outputBufferList);
  21746. outputBufferList = 0;
  21747. currentBuffer = 0;
  21748. }
  21749. }
  21750. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  21751. const AudioTimeStamp* inTimeStamp,
  21752. UInt32 inBusNumber,
  21753. UInt32 inNumberFrames,
  21754. AudioBufferList* ioData) const
  21755. {
  21756. if (inBusNumber == 0
  21757. && currentBuffer != 0)
  21758. {
  21759. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  21760. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  21761. {
  21762. if (i < currentBuffer->getNumChannels())
  21763. {
  21764. memcpy (ioData->mBuffers[i].mData,
  21765. currentBuffer->getSampleData (i, 0),
  21766. sizeof (float) * inNumberFrames);
  21767. }
  21768. else
  21769. {
  21770. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  21771. }
  21772. }
  21773. }
  21774. return noErr;
  21775. }
  21776. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  21777. MidiBuffer& midiMessages)
  21778. {
  21779. const int numSamples = buffer.getNumSamples();
  21780. if (initialised)
  21781. {
  21782. AudioUnitRenderActionFlags flags = 0;
  21783. timeStamp.mHostTime = AudioGetCurrentHostTime();
  21784. for (int i = getNumOutputChannels(); --i >= 0;)
  21785. {
  21786. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  21787. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  21788. }
  21789. currentBuffer = &buffer;
  21790. if (wantsMidiMessages)
  21791. {
  21792. const uint8* midiEventData;
  21793. int midiEventSize, midiEventPosition;
  21794. MidiBuffer::Iterator i (midiMessages);
  21795. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  21796. {
  21797. if (midiEventSize <= 3)
  21798. MusicDeviceMIDIEvent (audioUnit,
  21799. midiEventData[0], midiEventData[1], midiEventData[2],
  21800. midiEventPosition);
  21801. else
  21802. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  21803. }
  21804. midiMessages.clear();
  21805. }
  21806. AudioUnitRender (audioUnit, &flags, &timeStamp,
  21807. 0, numSamples, outputBufferList);
  21808. timeStamp.mSampleTime += numSamples;
  21809. }
  21810. else
  21811. {
  21812. // Not initialised, so just bypass..
  21813. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  21814. buffer.clear (i, 0, buffer.getNumSamples());
  21815. }
  21816. }
  21817. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  21818. {
  21819. AudioPlayHead* const ph = getPlayHead();
  21820. AudioPlayHead::CurrentPositionInfo result;
  21821. if (ph != 0 && ph->getCurrentPosition (result))
  21822. {
  21823. *outCurrentBeat = result.ppqPosition;
  21824. *outCurrentTempo = result.bpm;
  21825. }
  21826. else
  21827. {
  21828. *outCurrentBeat = 0;
  21829. *outCurrentTempo = 120.0;
  21830. }
  21831. return noErr;
  21832. }
  21833. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  21834. Float32* outTimeSig_Numerator,
  21835. UInt32* outTimeSig_Denominator,
  21836. Float64* outCurrentMeasureDownBeat) const
  21837. {
  21838. AudioPlayHead* const ph = getPlayHead();
  21839. AudioPlayHead::CurrentPositionInfo result;
  21840. if (ph != 0 && ph->getCurrentPosition (result))
  21841. {
  21842. *outTimeSig_Numerator = result.timeSigNumerator;
  21843. *outTimeSig_Denominator = result.timeSigDenominator;
  21844. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  21845. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  21846. }
  21847. else
  21848. {
  21849. *outDeltaSampleOffsetToNextBeat = 0;
  21850. *outTimeSig_Numerator = 4;
  21851. *outTimeSig_Denominator = 4;
  21852. *outCurrentMeasureDownBeat = 0;
  21853. }
  21854. return noErr;
  21855. }
  21856. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  21857. Boolean* outTransportStateChanged,
  21858. Float64* outCurrentSampleInTimeLine,
  21859. Boolean* outIsCycling,
  21860. Float64* outCycleStartBeat,
  21861. Float64* outCycleEndBeat)
  21862. {
  21863. AudioPlayHead* const ph = getPlayHead();
  21864. AudioPlayHead::CurrentPositionInfo result;
  21865. if (ph != 0 && ph->getCurrentPosition (result))
  21866. {
  21867. *outIsPlaying = result.isPlaying;
  21868. *outTransportStateChanged = result.isPlaying != wasPlaying;
  21869. wasPlaying = result.isPlaying;
  21870. *outCurrentSampleInTimeLine = roundDoubleToInt (result.timeInSeconds * getSampleRate());
  21871. *outIsCycling = false;
  21872. *outCycleStartBeat = 0;
  21873. *outCycleEndBeat = 0;
  21874. }
  21875. else
  21876. {
  21877. *outIsPlaying = false;
  21878. *outTransportStateChanged = false;
  21879. *outCurrentSampleInTimeLine = 0;
  21880. *outIsCycling = false;
  21881. *outCycleStartBeat = 0;
  21882. *outCycleEndBeat = 0;
  21883. }
  21884. return noErr;
  21885. }
  21886. static VoidArray activeWindows;
  21887. class AudioUnitPluginWindow : public AudioProcessorEditor,
  21888. public Timer
  21889. {
  21890. public:
  21891. AudioUnitPluginWindow (AudioUnitPluginInstance& plugin_)
  21892. : AudioProcessorEditor (&plugin_),
  21893. plugin (plugin_),
  21894. isOpen (false),
  21895. pluginWantsKeys (false),
  21896. wasShowing (false),
  21897. recursiveResize (false),
  21898. viewComponent (0),
  21899. pluginViewRef (0)
  21900. {
  21901. movementWatcher = new CompMovementWatcher (this);
  21902. activeWindows.add (this);
  21903. setOpaque (true);
  21904. setVisible (true);
  21905. setSize (1, 1);
  21906. ComponentDescription viewList [16];
  21907. UInt32 viewListSize = sizeof (viewList);
  21908. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  21909. 0, &viewList, &viewListSize);
  21910. componentRecord = FindNextComponent (0, &viewList[0]);
  21911. }
  21912. ~AudioUnitPluginWindow()
  21913. {
  21914. deleteAndZero (movementWatcher);
  21915. closePluginWindow();
  21916. activeWindows.removeValue (this);
  21917. plugin.editorBeingDeleted (this);
  21918. }
  21919. bool isValid() const throw() { return componentRecord != 0; }
  21920. void componentMovedOrResized()
  21921. {
  21922. if (recursiveResize)
  21923. return;
  21924. Component* const topComp = getTopLevelComponent();
  21925. if (topComp->getPeer() != 0)
  21926. {
  21927. int x = 0, y = 0;
  21928. relativePositionToOtherComponent (topComp, x, y);
  21929. recursiveResize = true;
  21930. if (pluginViewRef != 0)
  21931. {
  21932. HIRect r;
  21933. r.origin.x = (float) x;
  21934. r.origin.y = (float) y;
  21935. r.size.width = (float) getWidth();
  21936. r.size.height = (float) getHeight();
  21937. HIViewSetFrame (pluginViewRef, &r);
  21938. }
  21939. recursiveResize = false;
  21940. }
  21941. }
  21942. void componentVisibilityChanged()
  21943. {
  21944. const bool isShowingNow = isShowing();
  21945. if (wasShowing != isShowingNow)
  21946. {
  21947. wasShowing = isShowingNow;
  21948. if (isShowingNow)
  21949. openPluginWindow();
  21950. else
  21951. closePluginWindow();
  21952. }
  21953. componentMovedOrResized();
  21954. }
  21955. void componentPeerChanged()
  21956. {
  21957. closePluginWindow();
  21958. openPluginWindow();
  21959. }
  21960. void timerCallback()
  21961. {
  21962. if (pluginViewRef != 0)
  21963. {
  21964. HIRect bounds;
  21965. HIViewGetBounds (pluginViewRef, &bounds);
  21966. const int w = jmax (32, (int) bounds.size.width);
  21967. const int h = jmax (32, (int) bounds.size.height);
  21968. if (w != getWidth() || h != getHeight())
  21969. {
  21970. setSize (w, h);
  21971. startTimer (50);
  21972. }
  21973. else
  21974. {
  21975. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  21976. }
  21977. }
  21978. }
  21979. bool keyStateChanged()
  21980. {
  21981. return pluginWantsKeys;
  21982. }
  21983. bool keyPressed (const KeyPress&)
  21984. {
  21985. return pluginWantsKeys;
  21986. }
  21987. void paint (Graphics& g)
  21988. {
  21989. if (isOpen)
  21990. {
  21991. ComponentPeer* const peer = getPeer();
  21992. if (peer != 0)
  21993. {
  21994. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  21995. getScreenY() - peer->getScreenY(),
  21996. getWidth(), getHeight());
  21997. }
  21998. }
  21999. else
  22000. {
  22001. g.fillAll (Colours::black);
  22002. }
  22003. }
  22004. void broughtToFront()
  22005. {
  22006. activeWindows.removeValue (this);
  22007. activeWindows.add (this);
  22008. }
  22009. juce_UseDebuggingNewOperator
  22010. private:
  22011. AudioUnitPluginInstance& plugin;
  22012. bool isOpen, wasShowing, recursiveResize;
  22013. bool pluginWantsKeys;
  22014. ComponentRecord* componentRecord;
  22015. AudioUnitCarbonView viewComponent;
  22016. HIViewRef pluginViewRef;
  22017. void openPluginWindow()
  22018. {
  22019. if (isOpen || getWindowHandle() == 0 || componentRecord == 0)
  22020. return;
  22021. log (T("Opening AU GUI: ") + plugin.getName());
  22022. isOpen = true;
  22023. pluginWantsKeys = true; //xxx any way to find this out? Does it matter?
  22024. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  22025. if (viewComponent != 0)
  22026. {
  22027. Float32Point pos = { getScreenX() - getTopLevelComponent()->getScreenX(),
  22028. getScreenY() - getTopLevelComponent()->getScreenY() };
  22029. Float32Point size = { 250, 200 };
  22030. AudioUnitCarbonViewCreate (viewComponent,
  22031. plugin.audioUnit,
  22032. (WindowRef) getWindowHandle(),
  22033. HIViewGetRoot ((WindowRef) getWindowHandle()),
  22034. &pos, &size,
  22035. (ControlRef*) &pluginViewRef);
  22036. }
  22037. timerCallback(); // to set our comp to the right size
  22038. repaint();
  22039. }
  22040. void closePluginWindow()
  22041. {
  22042. stopTimer();
  22043. if (isOpen)
  22044. {
  22045. log (T("Closing AU GUI: ") + plugin.getName());
  22046. isOpen = false;
  22047. if (viewComponent != 0)
  22048. CloseComponent (viewComponent);
  22049. pluginViewRef = 0;
  22050. }
  22051. }
  22052. class CompMovementWatcher : public ComponentMovementWatcher
  22053. {
  22054. public:
  22055. CompMovementWatcher (AudioUnitPluginWindow* const owner_)
  22056. : ComponentMovementWatcher (owner_),
  22057. owner (owner_)
  22058. {
  22059. }
  22060. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  22061. {
  22062. owner->componentMovedOrResized();
  22063. }
  22064. void componentPeerChanged()
  22065. {
  22066. owner->componentPeerChanged();
  22067. }
  22068. void componentVisibilityChanged (Component&)
  22069. {
  22070. owner->componentVisibilityChanged();
  22071. }
  22072. private:
  22073. AudioUnitPluginWindow* const owner;
  22074. };
  22075. CompMovementWatcher* movementWatcher;
  22076. };
  22077. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  22078. {
  22079. AudioUnitPluginWindow* w = new AudioUnitPluginWindow (*this);
  22080. if (! w->isValid())
  22081. deleteAndZero (w);
  22082. return w;
  22083. }
  22084. const String AudioUnitPluginInstance::getCategory() const
  22085. {
  22086. const char* result = 0;
  22087. switch (componentDesc.componentType)
  22088. {
  22089. case kAudioUnitType_Effect:
  22090. case kAudioUnitType_MusicEffect:
  22091. result = "Effect";
  22092. break;
  22093. case kAudioUnitType_MusicDevice:
  22094. result = "Synth";
  22095. break;
  22096. case kAudioUnitType_Generator:
  22097. result = "Generator";
  22098. break;
  22099. case kAudioUnitType_Panner:
  22100. result = "Panner";
  22101. break;
  22102. default:
  22103. break;
  22104. }
  22105. return result;
  22106. }
  22107. int AudioUnitPluginInstance::getNumParameters()
  22108. {
  22109. return parameterIds.size();
  22110. }
  22111. float AudioUnitPluginInstance::getParameter (int index)
  22112. {
  22113. const ScopedLock sl (lock);
  22114. Float32 value = 0.0f;
  22115. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  22116. {
  22117. AudioUnitGetParameter (audioUnit,
  22118. (UInt32) parameterIds.getUnchecked (index),
  22119. kAudioUnitScope_Global, 0,
  22120. &value);
  22121. }
  22122. return value;
  22123. }
  22124. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  22125. {
  22126. const ScopedLock sl (lock);
  22127. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  22128. {
  22129. AudioUnitSetParameter (audioUnit,
  22130. (UInt32) parameterIds.getUnchecked (index),
  22131. kAudioUnitScope_Global, 0,
  22132. newValue, 0);
  22133. }
  22134. }
  22135. const String AudioUnitPluginInstance::getParameterName (int index)
  22136. {
  22137. AudioUnitParameterInfo info;
  22138. zerostruct (info);
  22139. UInt32 sz = sizeof (info);
  22140. String name;
  22141. if (AudioUnitGetProperty (audioUnit,
  22142. kAudioUnitProperty_ParameterInfo,
  22143. kAudioUnitScope_Global,
  22144. parameterIds [index], &info, &sz) == noErr)
  22145. {
  22146. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  22147. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  22148. else
  22149. name = String (info.name, sizeof (info.name));
  22150. }
  22151. return name;
  22152. }
  22153. const String AudioUnitPluginInstance::getParameterText (int index)
  22154. {
  22155. return String (getParameter (index));
  22156. }
  22157. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  22158. {
  22159. AudioUnitParameterInfo info;
  22160. UInt32 sz = sizeof (info);
  22161. if (AudioUnitGetProperty (audioUnit,
  22162. kAudioUnitProperty_ParameterInfo,
  22163. kAudioUnitScope_Global,
  22164. parameterIds [index], &info, &sz) == noErr)
  22165. {
  22166. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  22167. }
  22168. return true;
  22169. }
  22170. int AudioUnitPluginInstance::getNumPrograms()
  22171. {
  22172. CFArrayRef presets;
  22173. UInt32 sz = sizeof (CFArrayRef);
  22174. int num = 0;
  22175. if (AudioUnitGetProperty (audioUnit,
  22176. kAudioUnitProperty_FactoryPresets,
  22177. kAudioUnitScope_Global,
  22178. 0, &presets, &sz) == noErr)
  22179. {
  22180. num = (int) CFArrayGetCount (presets);
  22181. CFRelease (presets);
  22182. }
  22183. return num;
  22184. }
  22185. int AudioUnitPluginInstance::getCurrentProgram()
  22186. {
  22187. AUPreset current;
  22188. current.presetNumber = 0;
  22189. UInt32 sz = sizeof (AUPreset);
  22190. AudioUnitGetProperty (audioUnit,
  22191. kAudioUnitProperty_FactoryPresets,
  22192. kAudioUnitScope_Global,
  22193. 0, &current, &sz);
  22194. return current.presetNumber;
  22195. }
  22196. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  22197. {
  22198. AUPreset current;
  22199. current.presetNumber = newIndex;
  22200. current.presetName = 0;
  22201. AudioUnitSetProperty (audioUnit,
  22202. kAudioUnitProperty_FactoryPresets,
  22203. kAudioUnitScope_Global,
  22204. 0, &current, sizeof (AUPreset));
  22205. }
  22206. const String AudioUnitPluginInstance::getProgramName (int index)
  22207. {
  22208. String s;
  22209. CFArrayRef presets;
  22210. UInt32 sz = sizeof (CFArrayRef);
  22211. if (AudioUnitGetProperty (audioUnit,
  22212. kAudioUnitProperty_FactoryPresets,
  22213. kAudioUnitScope_Global,
  22214. 0, &presets, &sz) == noErr)
  22215. {
  22216. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  22217. {
  22218. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  22219. if (p != 0 && p->presetNumber == index)
  22220. {
  22221. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  22222. break;
  22223. }
  22224. }
  22225. CFRelease (presets);
  22226. }
  22227. return s;
  22228. }
  22229. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  22230. {
  22231. jassertfalse // xxx not implemented!
  22232. }
  22233. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  22234. {
  22235. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  22236. return T("Input ") + String (index + 1);
  22237. return String::empty;
  22238. }
  22239. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  22240. {
  22241. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  22242. return false;
  22243. return true;
  22244. }
  22245. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  22246. {
  22247. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  22248. return T("Output ") + String (index + 1);
  22249. return String::empty;
  22250. }
  22251. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  22252. {
  22253. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  22254. return false;
  22255. return true;
  22256. }
  22257. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  22258. {
  22259. getCurrentProgramStateInformation (destData);
  22260. }
  22261. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  22262. {
  22263. CFPropertyListRef propertyList = 0;
  22264. UInt32 sz = sizeof (CFPropertyListRef);
  22265. if (AudioUnitGetProperty (audioUnit,
  22266. kAudioUnitProperty_ClassInfo,
  22267. kAudioUnitScope_Global,
  22268. 0, &propertyList, &sz) == noErr)
  22269. {
  22270. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  22271. CFWriteStreamOpen (stream);
  22272. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  22273. CFWriteStreamClose (stream);
  22274. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  22275. destData.setSize (bytesWritten);
  22276. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  22277. CFRelease (data);
  22278. CFRelease (stream);
  22279. CFRelease (propertyList);
  22280. }
  22281. }
  22282. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  22283. {
  22284. setCurrentProgramStateInformation (data, sizeInBytes);
  22285. }
  22286. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  22287. {
  22288. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  22289. (const UInt8*) data,
  22290. sizeInBytes,
  22291. kCFAllocatorNull);
  22292. CFReadStreamOpen (stream);
  22293. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  22294. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  22295. stream,
  22296. 0,
  22297. kCFPropertyListImmutable,
  22298. &format,
  22299. 0);
  22300. CFRelease (stream);
  22301. if (propertyList != 0)
  22302. AudioUnitSetProperty (audioUnit,
  22303. kAudioUnitProperty_ClassInfo,
  22304. kAudioUnitScope_Global,
  22305. 0, &propertyList, sizeof (propertyList));
  22306. }
  22307. AudioUnitPluginFormat::AudioUnitPluginFormat()
  22308. {
  22309. }
  22310. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  22311. {
  22312. }
  22313. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  22314. const File& file)
  22315. {
  22316. if (! fileMightContainThisPluginType (file))
  22317. return;
  22318. PluginDescription desc;
  22319. desc.file = file;
  22320. desc.uid = 0;
  22321. AudioUnitPluginInstance* instance = dynamic_cast <AudioUnitPluginInstance*> (createInstanceFromDescription (desc));
  22322. if (instance == 0)
  22323. return;
  22324. try
  22325. {
  22326. instance->fillInPluginDescription (desc);
  22327. results.add (new PluginDescription (desc));
  22328. }
  22329. catch (...)
  22330. {
  22331. // crashed while loading...
  22332. }
  22333. deleteAndZero (instance);
  22334. }
  22335. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  22336. {
  22337. AudioUnitPluginInstance* result = 0;
  22338. if (fileMightContainThisPluginType (desc.file))
  22339. {
  22340. result = new AudioUnitPluginInstance (desc.file);
  22341. if (result->audioUnit != 0)
  22342. {
  22343. result->initialise();
  22344. }
  22345. else
  22346. {
  22347. deleteAndZero (result);
  22348. }
  22349. }
  22350. return result;
  22351. }
  22352. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const File& f)
  22353. {
  22354. return f.hasFileExtension (T(".component"))
  22355. && f.isDirectory();
  22356. }
  22357. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  22358. {
  22359. return FileSearchPath ("~/Library/Audio/Plug-Ins/Components;/Library/Audio/Plug-Ins/Components");
  22360. }
  22361. #endif
  22362. END_JUCE_NAMESPACE
  22363. #undef log
  22364. #endif
  22365. /********* End of inlined file: juce_AudioUnitPluginFormat.cpp *********/
  22366. /********* Start of inlined file: juce_VSTPluginFormat.cpp *********/
  22367. #if JUCE_PLUGINHOST_VST
  22368. #ifdef _WIN32
  22369. #undef _WIN32_WINNT
  22370. #define _WIN32_WINNT 0x500
  22371. #undef STRICT
  22372. #define STRICT
  22373. #include <windows.h>
  22374. #include <float.h>
  22375. #pragma warning (disable : 4312)
  22376. #elif defined (LINUX)
  22377. #include <float.h>
  22378. #include <sys/time.h>
  22379. #include <X11/Xlib.h>
  22380. #include <X11/Xutil.h>
  22381. #include <X11/Xatom.h>
  22382. #undef Font
  22383. #undef KeyPress
  22384. #undef Drawable
  22385. #undef Time
  22386. #else
  22387. #include <Carbon/Carbon.h>
  22388. #endif
  22389. BEGIN_JUCE_NAMESPACE
  22390. #undef PRAGMA_ALIGN_SUPPORTED
  22391. #define VST_FORCE_DEPRECATED 0
  22392. #ifdef _MSC_VER
  22393. #pragma warning (push)
  22394. #pragma warning (disable: 4996)
  22395. #endif
  22396. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  22397. your include path if you want to add VST support.
  22398. If you're not interested in VSTs, you can disable them by changing the
  22399. JUCE_PLUGINHOST_VST flag in juce_Config.h
  22400. */
  22401. #include "pluginterfaces/vst2.x/aeffectx.h"
  22402. #ifdef _MSC_VER
  22403. #pragma warning (pop)
  22404. #endif
  22405. #if JUCE_LINUX
  22406. #define Font JUCE_NAMESPACE::Font
  22407. #define KeyPress JUCE_NAMESPACE::KeyPress
  22408. #define Drawable JUCE_NAMESPACE::Drawable
  22409. #define Time JUCE_NAMESPACE::Time
  22410. #endif
  22411. #if ! JUCE_WIN32
  22412. #define _fpreset()
  22413. #define _clearfp()
  22414. #endif
  22415. extern void juce_callAnyTimersSynchronously();
  22416. const int fxbVersionNum = 1;
  22417. struct fxProgram
  22418. {
  22419. long chunkMagic; // 'CcnK'
  22420. long byteSize; // of this chunk, excl. magic + byteSize
  22421. long fxMagic; // 'FxCk'
  22422. long version;
  22423. long fxID; // fx unique id
  22424. long fxVersion;
  22425. long numParams;
  22426. char prgName[28];
  22427. float params[1]; // variable no. of parameters
  22428. };
  22429. struct fxSet
  22430. {
  22431. long chunkMagic; // 'CcnK'
  22432. long byteSize; // of this chunk, excl. magic + byteSize
  22433. long fxMagic; // 'FxBk'
  22434. long version;
  22435. long fxID; // fx unique id
  22436. long fxVersion;
  22437. long numPrograms;
  22438. char future[128];
  22439. fxProgram programs[1]; // variable no. of programs
  22440. };
  22441. struct fxChunkSet
  22442. {
  22443. long chunkMagic; // 'CcnK'
  22444. long byteSize; // of this chunk, excl. magic + byteSize
  22445. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  22446. long version;
  22447. long fxID; // fx unique id
  22448. long fxVersion;
  22449. long numPrograms;
  22450. char future[128];
  22451. long chunkSize;
  22452. char chunk[8]; // variable
  22453. };
  22454. struct fxProgramSet
  22455. {
  22456. long chunkMagic; // 'CcnK'
  22457. long byteSize; // of this chunk, excl. magic + byteSize
  22458. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  22459. long version;
  22460. long fxID; // fx unique id
  22461. long fxVersion;
  22462. long numPrograms;
  22463. char name[28];
  22464. long chunkSize;
  22465. char chunk[8]; // variable
  22466. };
  22467. #ifdef JUCE_LITTLE_ENDIAN
  22468. static long vst_swap (const long x) throw() { return (long) swapByteOrder ((uint32) x); }
  22469. static float vst_swapFloat (const float x) throw()
  22470. {
  22471. union { uint32 asInt; float asFloat; } n;
  22472. n.asFloat = x;
  22473. n.asInt = swapByteOrder (n.asInt);
  22474. return n.asFloat;
  22475. }
  22476. #else
  22477. #define vst_swap(x) (x)
  22478. #define vst_swapFloat(x) (x)
  22479. #endif
  22480. typedef AEffect* (*MainCall) (audioMasterCallback);
  22481. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  22482. static int shellUIDToCreate = 0;
  22483. static int insideVSTCallback = 0;
  22484. class VSTPluginWindow;
  22485. // Change this to disable logging of various VST activities
  22486. #ifndef VST_LOGGING
  22487. #define VST_LOGGING 1
  22488. #endif
  22489. #if VST_LOGGING
  22490. #define log(a) Logger::writeToLog(a);
  22491. #else
  22492. #define log(a)
  22493. #endif
  22494. #if JUCE_MAC
  22495. extern bool juce_isHIViewCreatedByJuce (HIViewRef view);
  22496. extern bool juce_isWindowCreatedByJuce (WindowRef window);
  22497. #if JUCE_PPC
  22498. static void* NewCFMFromMachO (void* const machofp) throw()
  22499. {
  22500. void* result = juce_malloc (8);
  22501. ((void**) result)[0] = machofp;
  22502. ((void**) result)[1] = result;
  22503. return result;
  22504. }
  22505. #endif
  22506. #endif
  22507. #if JUCE_LINUX
  22508. extern Display* display;
  22509. extern XContext improbableNumber;
  22510. typedef void (*EventProcPtr) (XEvent* ev);
  22511. static bool xErrorTriggered;
  22512. static int temporaryErrorHandler (Display*, XErrorEvent*)
  22513. {
  22514. xErrorTriggered = true;
  22515. return 0;
  22516. }
  22517. static int getPropertyFromXWindow (Window handle, Atom atom)
  22518. {
  22519. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  22520. xErrorTriggered = false;
  22521. int userSize;
  22522. unsigned long bytes, userCount;
  22523. unsigned char* data;
  22524. Atom userType;
  22525. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  22526. &userType, &userSize, &userCount, &bytes, &data);
  22527. XSetErrorHandler (oldErrorHandler);
  22528. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  22529. : 0;
  22530. }
  22531. static Window getChildWindow (Window windowToCheck)
  22532. {
  22533. Window rootWindow, parentWindow;
  22534. Window* childWindows;
  22535. unsigned int numChildren;
  22536. XQueryTree (display,
  22537. windowToCheck,
  22538. &rootWindow,
  22539. &parentWindow,
  22540. &childWindows,
  22541. &numChildren);
  22542. if (numChildren > 0)
  22543. return childWindows [0];
  22544. return 0;
  22545. }
  22546. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  22547. {
  22548. if (e.mods.isLeftButtonDown())
  22549. {
  22550. ev.xbutton.button = Button1;
  22551. ev.xbutton.state |= Button1Mask;
  22552. }
  22553. else if (e.mods.isRightButtonDown())
  22554. {
  22555. ev.xbutton.button = Button3;
  22556. ev.xbutton.state |= Button3Mask;
  22557. }
  22558. else if (e.mods.isMiddleButtonDown())
  22559. {
  22560. ev.xbutton.button = Button2;
  22561. ev.xbutton.state |= Button2Mask;
  22562. }
  22563. }
  22564. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  22565. {
  22566. if (e.mods.isLeftButtonDown())
  22567. ev.xmotion.state |= Button1Mask;
  22568. else if (e.mods.isRightButtonDown())
  22569. ev.xmotion.state |= Button3Mask;
  22570. else if (e.mods.isMiddleButtonDown())
  22571. ev.xmotion.state |= Button2Mask;
  22572. }
  22573. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  22574. {
  22575. if (e.mods.isLeftButtonDown())
  22576. ev.xcrossing.state |= Button1Mask;
  22577. else if (e.mods.isRightButtonDown())
  22578. ev.xcrossing.state |= Button3Mask;
  22579. else if (e.mods.isMiddleButtonDown())
  22580. ev.xcrossing.state |= Button2Mask;
  22581. }
  22582. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  22583. {
  22584. if (increment < 0)
  22585. {
  22586. ev.xbutton.button = Button5;
  22587. ev.xbutton.state |= Button5Mask;
  22588. }
  22589. else if (increment > 0)
  22590. {
  22591. ev.xbutton.button = Button4;
  22592. ev.xbutton.state |= Button4Mask;
  22593. }
  22594. }
  22595. #endif
  22596. static VoidArray activeModules;
  22597. class ModuleHandle : public ReferenceCountedObject
  22598. {
  22599. public:
  22600. File file;
  22601. MainCall moduleMain;
  22602. String pluginName;
  22603. static ModuleHandle* findOrCreateModule (const File& file)
  22604. {
  22605. for (int i = activeModules.size(); --i >= 0;)
  22606. {
  22607. ModuleHandle* const module = (ModuleHandle*) activeModules.getUnchecked(i);
  22608. if (module->file == file)
  22609. return module;
  22610. }
  22611. _fpreset(); // (doesn't do any harm)
  22612. ++insideVSTCallback;
  22613. shellUIDToCreate = 0;
  22614. log ("Attempting to load VST: " + file.getFullPathName());
  22615. ModuleHandle* m = new ModuleHandle (file);
  22616. if (! m->open())
  22617. deleteAndZero (m);
  22618. --insideVSTCallback;
  22619. _fpreset(); // (doesn't do any harm)
  22620. return m;
  22621. }
  22622. ModuleHandle (const File& file_)
  22623. : file (file_),
  22624. moduleMain (0),
  22625. #if JUCE_WIN32 || JUCE_LINUX
  22626. hModule (0)
  22627. #elif JUCE_MAC
  22628. fragId (0),
  22629. resHandle (0),
  22630. bundleRef (0),
  22631. resFileId (0)
  22632. #endif
  22633. {
  22634. activeModules.add (this);
  22635. #if JUCE_WIN32 || JUCE_LINUX
  22636. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  22637. #elif JUCE_MAC
  22638. PlatformUtilities::makeFSSpecFromPath (&parentDirFSSpec, file_.getParentDirectory().getFullPathName());
  22639. #endif
  22640. }
  22641. ~ModuleHandle()
  22642. {
  22643. activeModules.removeValue (this);
  22644. close();
  22645. }
  22646. juce_UseDebuggingNewOperator
  22647. #if JUCE_WIN32 || JUCE_LINUX
  22648. void* hModule;
  22649. String fullParentDirectoryPathName;
  22650. bool open()
  22651. {
  22652. #if JUCE_WIN32
  22653. static bool timePeriodSet = false;
  22654. if (! timePeriodSet)
  22655. {
  22656. timePeriodSet = true;
  22657. timeBeginPeriod (2);
  22658. }
  22659. #endif
  22660. pluginName = file.getFileNameWithoutExtension();
  22661. hModule = Process::loadDynamicLibrary (file.getFullPathName());
  22662. moduleMain = (MainCall) Process::getProcedureEntryPoint (hModule, "VSTPluginMain");
  22663. if (moduleMain == 0)
  22664. moduleMain = (MainCall) Process::getProcedureEntryPoint (hModule, "main");
  22665. return moduleMain != 0;
  22666. }
  22667. void close()
  22668. {
  22669. _fpreset(); // (doesn't do any harm)
  22670. Process::freeDynamicLibrary (hModule);
  22671. }
  22672. void closeEffect (AEffect* eff)
  22673. {
  22674. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  22675. }
  22676. #else
  22677. CFragConnectionID fragId;
  22678. Handle resHandle;
  22679. CFBundleRef bundleRef;
  22680. FSSpec parentDirFSSpec;
  22681. short resFileId;
  22682. bool open()
  22683. {
  22684. bool ok = false;
  22685. const String filename (file.getFullPathName());
  22686. if (file.hasFileExtension (T(".vst")))
  22687. {
  22688. const char* const utf8 = filename.toUTF8();
  22689. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  22690. strlen (utf8), file.isDirectory());
  22691. if (url != 0)
  22692. {
  22693. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  22694. CFRelease (url);
  22695. if (bundleRef != 0)
  22696. {
  22697. if (CFBundleLoadExecutable (bundleRef))
  22698. {
  22699. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  22700. if (moduleMain == 0)
  22701. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  22702. if (moduleMain != 0)
  22703. {
  22704. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  22705. if (name != 0)
  22706. {
  22707. if (CFGetTypeID (name) == CFStringGetTypeID())
  22708. {
  22709. char buffer[1024];
  22710. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  22711. pluginName = buffer;
  22712. }
  22713. }
  22714. if (pluginName.isEmpty())
  22715. pluginName = file.getFileNameWithoutExtension();
  22716. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  22717. ok = true;
  22718. }
  22719. }
  22720. if (! ok)
  22721. {
  22722. CFBundleUnloadExecutable (bundleRef);
  22723. CFRelease (bundleRef);
  22724. bundleRef = 0;
  22725. }
  22726. }
  22727. }
  22728. }
  22729. #if JUCE_PPC
  22730. else
  22731. {
  22732. FSRef fn;
  22733. if (FSPathMakeRef ((UInt8*) (const char*) filename, &fn, 0) == noErr)
  22734. {
  22735. resFileId = FSOpenResFile (&fn, fsRdPerm);
  22736. if (resFileId != -1)
  22737. {
  22738. const int numEffs = Count1Resources ('aEff');
  22739. for (int i = 0; i < numEffs; ++i)
  22740. {
  22741. resHandle = Get1IndResource ('aEff', i + 1);
  22742. if (resHandle != 0)
  22743. {
  22744. OSType type;
  22745. Str255 name;
  22746. SInt16 id;
  22747. GetResInfo (resHandle, &id, &type, name);
  22748. pluginName = String ((const char*) name + 1, name[0]);
  22749. DetachResource (resHandle);
  22750. HLock (resHandle);
  22751. Ptr ptr;
  22752. Str255 errorText;
  22753. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  22754. name, kPrivateCFragCopy,
  22755. &fragId, &ptr, errorText);
  22756. if (err == noErr)
  22757. {
  22758. moduleMain = (MainCall) newMachOFromCFM (ptr);
  22759. ok = true;
  22760. }
  22761. else
  22762. {
  22763. HUnlock (resHandle);
  22764. }
  22765. break;
  22766. }
  22767. }
  22768. if (! ok)
  22769. CloseResFile (resFileId);
  22770. }
  22771. }
  22772. }
  22773. #endif
  22774. return ok;
  22775. }
  22776. void close()
  22777. {
  22778. #if JUCE_PPC
  22779. if (fragId != 0)
  22780. {
  22781. if (moduleMain != 0)
  22782. disposeMachOFromCFM ((void*) moduleMain);
  22783. CloseConnection (&fragId);
  22784. HUnlock (resHandle);
  22785. if (resFileId != 0)
  22786. CloseResFile (resFileId);
  22787. }
  22788. else
  22789. #endif
  22790. if (bundleRef != 0)
  22791. {
  22792. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  22793. if (CFGetRetainCount (bundleRef) == 1)
  22794. CFBundleUnloadExecutable (bundleRef);
  22795. if (CFGetRetainCount (bundleRef) > 0)
  22796. CFRelease (bundleRef);
  22797. }
  22798. }
  22799. void closeEffect (AEffect* eff)
  22800. {
  22801. #if JUCE_PPC
  22802. if (fragId != 0)
  22803. {
  22804. VoidArray thingsToDelete;
  22805. thingsToDelete.add ((void*) eff->dispatcher);
  22806. thingsToDelete.add ((void*) eff->process);
  22807. thingsToDelete.add ((void*) eff->setParameter);
  22808. thingsToDelete.add ((void*) eff->getParameter);
  22809. thingsToDelete.add ((void*) eff->processReplacing);
  22810. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  22811. for (int i = thingsToDelete.size(); --i >= 0;)
  22812. disposeMachOFromCFM (thingsToDelete[i]);
  22813. }
  22814. else
  22815. #endif
  22816. {
  22817. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  22818. }
  22819. }
  22820. #if JUCE_PPC
  22821. static void* newMachOFromCFM (void* cfmfp)
  22822. {
  22823. if (cfmfp == 0)
  22824. return 0;
  22825. UInt32* const mfp = (UInt32*) juce_malloc (sizeof (UInt32) * 6);
  22826. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  22827. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  22828. mfp[2] = 0x800c0000;
  22829. mfp[3] = 0x804c0004;
  22830. mfp[4] = 0x7c0903a6;
  22831. mfp[5] = 0x4e800420;
  22832. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  22833. return mfp;
  22834. }
  22835. static void disposeMachOFromCFM (void* ptr)
  22836. {
  22837. juce_free (ptr);
  22838. }
  22839. void coerceAEffectFunctionCalls (AEffect* eff)
  22840. {
  22841. if (fragId != 0)
  22842. {
  22843. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  22844. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  22845. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  22846. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  22847. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  22848. }
  22849. }
  22850. #endif
  22851. #endif
  22852. };
  22853. /**
  22854. An instance of a plugin, created by a VSTPluginFormat.
  22855. */
  22856. class VSTPluginInstance : public AudioPluginInstance,
  22857. private Timer,
  22858. private AsyncUpdater
  22859. {
  22860. public:
  22861. ~VSTPluginInstance();
  22862. // AudioPluginInstance methods:
  22863. void fillInPluginDescription (PluginDescription& desc) const
  22864. {
  22865. desc.name = name;
  22866. desc.file = module->file;
  22867. desc.uid = getUID();
  22868. desc.lastFileModTime = desc.file.getLastModificationTime();
  22869. desc.pluginFormatName = "VST";
  22870. desc.category = getCategory();
  22871. {
  22872. char buffer [kVstMaxVendorStrLen + 8];
  22873. zerostruct (buffer);
  22874. dispatch (effGetVendorString, 0, 0, buffer, 0);
  22875. desc.manufacturerName = buffer;
  22876. }
  22877. desc.version = getVersion();
  22878. desc.numInputChannels = getNumInputChannels();
  22879. desc.numOutputChannels = getNumOutputChannels();
  22880. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  22881. }
  22882. const String getName() const { return name; }
  22883. int getUID() const throw();
  22884. bool acceptsMidi() const { return wantsMidiMessages; }
  22885. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  22886. // AudioProcessor methods:
  22887. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  22888. void releaseResources();
  22889. void processBlock (AudioSampleBuffer& buffer,
  22890. MidiBuffer& midiMessages);
  22891. AudioProcessorEditor* createEditor();
  22892. const String getInputChannelName (const int index) const;
  22893. bool isInputChannelStereoPair (int index) const;
  22894. const String getOutputChannelName (const int index) const;
  22895. bool isOutputChannelStereoPair (int index) const;
  22896. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  22897. float getParameter (int index);
  22898. void setParameter (int index, float newValue);
  22899. const String getParameterName (int index);
  22900. const String getParameterText (int index);
  22901. bool isParameterAutomatable (int index) const;
  22902. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  22903. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  22904. void setCurrentProgram (int index);
  22905. const String getProgramName (int index);
  22906. void changeProgramName (int index, const String& newName);
  22907. void getStateInformation (MemoryBlock& destData);
  22908. void getCurrentProgramStateInformation (MemoryBlock& destData);
  22909. void setStateInformation (const void* data, int sizeInBytes);
  22910. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  22911. void timerCallback();
  22912. void handleAsyncUpdate();
  22913. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  22914. juce_UseDebuggingNewOperator
  22915. private:
  22916. friend class VSTPluginWindow;
  22917. friend class VSTPluginFormat;
  22918. AEffect* effect;
  22919. String name;
  22920. CriticalSection lock;
  22921. bool wantsMidiMessages, initialised, isPowerOn;
  22922. mutable StringArray programNames;
  22923. AudioSampleBuffer tempBuffer;
  22924. CriticalSection midiInLock;
  22925. MidiBuffer incomingMidi;
  22926. void* midiEventsToSend;
  22927. int numAllocatedMidiEvents;
  22928. VstTimeInfo vstHostTime;
  22929. float** channels;
  22930. ReferenceCountedObjectPtr <ModuleHandle> module;
  22931. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  22932. bool restoreProgramSettings (const fxProgram* const prog);
  22933. const String getCurrentProgramName();
  22934. void setParamsInProgramBlock (fxProgram* const prog) throw();
  22935. void updateStoredProgramNames();
  22936. void initialise();
  22937. void ensureMidiEventSize (int numEventsNeeded);
  22938. void freeMidiEvents();
  22939. void handleMidiFromPlugin (const VstEvents* const events);
  22940. void createTempParameterStore (MemoryBlock& dest);
  22941. void restoreFromTempParameterStore (const MemoryBlock& mb);
  22942. const String getParameterLabel (int index) const;
  22943. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  22944. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  22945. void setChunkData (const char* data, int size, bool isPreset);
  22946. bool loadFromFXBFile (const void* data, int numBytes);
  22947. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  22948. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  22949. const String getVersion() const throw();
  22950. const String getCategory() const throw();
  22951. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  22952. void setPower (const bool on);
  22953. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  22954. };
  22955. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  22956. : effect (0),
  22957. wantsMidiMessages (false),
  22958. initialised (false),
  22959. isPowerOn (false),
  22960. numAllocatedMidiEvents (0),
  22961. midiEventsToSend (0),
  22962. tempBuffer (1, 1),
  22963. channels (0),
  22964. module (module_)
  22965. {
  22966. try
  22967. {
  22968. _fpreset();
  22969. ++insideVSTCallback;
  22970. name = module->pluginName;
  22971. log (T("Creating VST instance: ") + name);
  22972. #if JUCE_MAC
  22973. if (module->resFileId != 0)
  22974. UseResFile (module->resFileId);
  22975. #if JUCE_PPC
  22976. if (module->fragId != 0)
  22977. {
  22978. static void* audioMasterCoerced = 0;
  22979. if (audioMasterCoerced == 0)
  22980. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  22981. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  22982. }
  22983. else
  22984. #endif
  22985. #endif
  22986. {
  22987. effect = module->moduleMain (&audioMaster);
  22988. }
  22989. --insideVSTCallback;
  22990. if (effect != 0 && effect->magic == kEffectMagic)
  22991. {
  22992. #if JUCE_PPC
  22993. module->coerceAEffectFunctionCalls (effect);
  22994. #endif
  22995. jassert (effect->resvd2 == 0);
  22996. jassert (effect->object != 0);
  22997. _fpreset(); // some dodgy plugs fuck around with this
  22998. }
  22999. else
  23000. {
  23001. effect = 0;
  23002. }
  23003. }
  23004. catch (...)
  23005. {
  23006. --insideVSTCallback;
  23007. }
  23008. }
  23009. VSTPluginInstance::~VSTPluginInstance()
  23010. {
  23011. {
  23012. const ScopedLock sl (lock);
  23013. jassert (insideVSTCallback == 0);
  23014. if (effect != 0 && effect->magic == kEffectMagic)
  23015. {
  23016. try
  23017. {
  23018. #if JUCE_MAC
  23019. if (module->resFileId != 0)
  23020. UseResFile (module->resFileId);
  23021. #endif
  23022. // Must delete any editors before deleting the plugin instance!
  23023. jassert (getActiveEditor() == 0);
  23024. _fpreset(); // some dodgy plugs fuck around with this
  23025. module->closeEffect (effect);
  23026. }
  23027. catch (...)
  23028. {}
  23029. }
  23030. module = 0;
  23031. effect = 0;
  23032. }
  23033. freeMidiEvents();
  23034. juce_free (channels);
  23035. channels = 0;
  23036. }
  23037. void VSTPluginInstance::initialise()
  23038. {
  23039. if (initialised || effect == 0)
  23040. return;
  23041. log (T("Initialising VST: ") + module->pluginName);
  23042. initialised = true;
  23043. dispatch (effIdentify, 0, 0, 0, 0);
  23044. // this code would ask the plugin for its name, but so few plugins
  23045. // actually bother implementing this correctly, that it's better to
  23046. // just ignore it and use the file name instead.
  23047. /* {
  23048. char buffer [256];
  23049. zerostruct (buffer);
  23050. dispatch (effGetEffectName, 0, 0, buffer, 0);
  23051. name = String (buffer).trim();
  23052. if (name.isEmpty())
  23053. name = module->pluginName;
  23054. }
  23055. */
  23056. if (getSampleRate() > 0)
  23057. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  23058. if (getBlockSize() > 0)
  23059. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  23060. dispatch (effOpen, 0, 0, 0, 0);
  23061. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  23062. getSampleRate(), getBlockSize());
  23063. if (getNumPrograms() > 1)
  23064. setCurrentProgram (0);
  23065. else
  23066. dispatch (effSetProgram, 0, 0, 0, 0);
  23067. int i;
  23068. for (i = effect->numInputs; --i >= 0;)
  23069. dispatch (effConnectInput, i, 1, 0, 0);
  23070. for (i = effect->numOutputs; --i >= 0;)
  23071. dispatch (effConnectOutput, i, 1, 0, 0);
  23072. updateStoredProgramNames();
  23073. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  23074. setLatencySamples (effect->initialDelay);
  23075. }
  23076. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  23077. int samplesPerBlockExpected)
  23078. {
  23079. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  23080. sampleRate_, samplesPerBlockExpected);
  23081. setLatencySamples (effect->initialDelay);
  23082. juce_free (channels);
  23083. channels = (float**) juce_calloc (sizeof (float*) * jmax (16, getNumOutputChannels() + 2, getNumInputChannels() + 2));
  23084. vstHostTime.tempo = 120.0;
  23085. vstHostTime.timeSigNumerator = 4;
  23086. vstHostTime.timeSigDenominator = 4;
  23087. vstHostTime.sampleRate = sampleRate_;
  23088. vstHostTime.samplePos = 0;
  23089. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  23090. initialise();
  23091. if (initialised)
  23092. {
  23093. wantsMidiMessages = wantsMidiMessages
  23094. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  23095. if (wantsMidiMessages)
  23096. ensureMidiEventSize (256);
  23097. else
  23098. freeMidiEvents();
  23099. incomingMidi.clear();
  23100. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  23101. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  23102. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  23103. if (! isPowerOn)
  23104. setPower (true);
  23105. // dodgy hack to force some plugins to initialise the sample rate..
  23106. if ((! hasEditor()) && getNumParameters() > 0)
  23107. {
  23108. const float old = getParameter (0);
  23109. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  23110. setParameter (0, old);
  23111. }
  23112. dispatch (effStartProcess, 0, 0, 0, 0);
  23113. }
  23114. }
  23115. void VSTPluginInstance::releaseResources()
  23116. {
  23117. if (initialised)
  23118. {
  23119. dispatch (effStopProcess, 0, 0, 0, 0);
  23120. setPower (false);
  23121. }
  23122. tempBuffer.setSize (1, 1);
  23123. incomingMidi.clear();
  23124. freeMidiEvents();
  23125. juce_free (channels);
  23126. channels = 0;
  23127. }
  23128. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  23129. MidiBuffer& midiMessages)
  23130. {
  23131. const int numSamples = buffer.getNumSamples();
  23132. if (initialised)
  23133. {
  23134. #if JUCE_WIN32
  23135. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  23136. #elif JUCE_LINUX
  23137. timeval micro;
  23138. gettimeofday (&micro, 0);
  23139. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  23140. #elif JUCE_MAC
  23141. UnsignedWide micro;
  23142. Microseconds (&micro);
  23143. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  23144. #endif
  23145. if (wantsMidiMessages)
  23146. {
  23147. MidiBuffer::Iterator iter (midiMessages);
  23148. int eventIndex = 0;
  23149. const uint8* midiData;
  23150. int numBytesOfMidiData, samplePosition;
  23151. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  23152. {
  23153. if (numBytesOfMidiData < 4)
  23154. {
  23155. ensureMidiEventSize (eventIndex);
  23156. VstMidiEvent* const e
  23157. = (VstMidiEvent*) ((VstEvents*) midiEventsToSend)->events [eventIndex++];
  23158. // check that some plugin hasn't messed up our objects
  23159. jassert (e->type == kVstMidiType);
  23160. jassert (e->byteSize == 24);
  23161. e->deltaFrames = jlimit (0, numSamples - 1, samplePosition);
  23162. e->noteLength = 0;
  23163. e->noteOffset = 0;
  23164. e->midiData[0] = midiData[0];
  23165. e->midiData[1] = midiData[1];
  23166. e->midiData[2] = midiData[2];
  23167. e->detune = 0;
  23168. e->noteOffVelocity = 0;
  23169. }
  23170. }
  23171. if (midiEventsToSend == 0)
  23172. ensureMidiEventSize (1);
  23173. ((VstEvents*) midiEventsToSend)->numEvents = eventIndex;
  23174. try
  23175. {
  23176. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend, 0);
  23177. }
  23178. catch (...)
  23179. {}
  23180. }
  23181. int i;
  23182. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  23183. for (i = 0; i < maxChans; ++i)
  23184. channels[i] = buffer.getSampleData (i);
  23185. channels [maxChans] = 0;
  23186. _clearfp();
  23187. if ((effect->flags & effFlagsCanReplacing) != 0)
  23188. {
  23189. try
  23190. {
  23191. effect->processReplacing (effect, channels, channels, numSamples);
  23192. }
  23193. catch (...)
  23194. {}
  23195. }
  23196. else
  23197. {
  23198. tempBuffer.setSize (effect->numOutputs, numSamples);
  23199. tempBuffer.clear();
  23200. float* outs [64];
  23201. for (i = effect->numOutputs; --i >= 0;)
  23202. outs[i] = tempBuffer.getSampleData (i);
  23203. outs [effect->numOutputs] = 0;
  23204. try
  23205. {
  23206. effect->process (effect, channels, outs, numSamples);
  23207. }
  23208. catch (...)
  23209. {}
  23210. for (i = effect->numOutputs; --i >= 0;)
  23211. buffer.copyFrom (i, 0, outs[i], numSamples);
  23212. }
  23213. }
  23214. else
  23215. {
  23216. // Not initialised, so just bypass..
  23217. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  23218. buffer.clear (i, 0, buffer.getNumSamples());
  23219. }
  23220. {
  23221. // copy any incoming midi..
  23222. const ScopedLock sl (midiInLock);
  23223. midiMessages = incomingMidi;
  23224. incomingMidi.clear();
  23225. }
  23226. }
  23227. void VSTPluginInstance::ensureMidiEventSize (int numEventsNeeded)
  23228. {
  23229. if (numEventsNeeded > numAllocatedMidiEvents)
  23230. {
  23231. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  23232. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  23233. if (midiEventsToSend == 0)
  23234. midiEventsToSend = juce_calloc (size);
  23235. else
  23236. midiEventsToSend = juce_realloc (midiEventsToSend, size);
  23237. for (int i = numAllocatedMidiEvents; i < numEventsNeeded; ++i)
  23238. {
  23239. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (sizeof (VstMidiEvent));
  23240. e->type = kVstMidiType;
  23241. e->byteSize = 24;
  23242. ((VstEvents*) midiEventsToSend)->events[i] = (VstEvent*) e;
  23243. }
  23244. numAllocatedMidiEvents = numEventsNeeded;
  23245. }
  23246. }
  23247. void VSTPluginInstance::freeMidiEvents()
  23248. {
  23249. if (midiEventsToSend != 0)
  23250. {
  23251. for (int i = numAllocatedMidiEvents; --i >= 0;)
  23252. juce_free (((VstEvents*) midiEventsToSend)->events[i]);
  23253. juce_free (midiEventsToSend);
  23254. midiEventsToSend = 0;
  23255. numAllocatedMidiEvents = 0;
  23256. }
  23257. }
  23258. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  23259. {
  23260. if (events != 0)
  23261. {
  23262. const ScopedLock sl (midiInLock);
  23263. for (int i = 0; i < events->numEvents; ++i)
  23264. {
  23265. const VstEvent* const e = events->events[i];
  23266. if (e->type == kVstMidiType)
  23267. {
  23268. incomingMidi.addEvent ((const uint8*) ((const VstMidiEvent*) e)->midiData,
  23269. 3, e->deltaFrames);
  23270. }
  23271. }
  23272. }
  23273. }
  23274. static Array <VSTPluginWindow*> activeVSTWindows;
  23275. class VSTPluginWindow : public AudioProcessorEditor,
  23276. public Timer
  23277. {
  23278. public:
  23279. VSTPluginWindow (VSTPluginInstance& plugin_)
  23280. : AudioProcessorEditor (&plugin_),
  23281. plugin (plugin_),
  23282. isOpen (false),
  23283. wasShowing (false),
  23284. pluginRefusesToResize (false),
  23285. pluginWantsKeys (false),
  23286. alreadyInside (false),
  23287. recursiveResize (false)
  23288. {
  23289. #if JUCE_WIN32
  23290. sizeCheckCount = 0;
  23291. pluginHWND = 0;
  23292. #elif JUCE_LINUX
  23293. pluginWindow = None;
  23294. pluginProc = None;
  23295. #else
  23296. pluginViewRef = 0;
  23297. #endif
  23298. movementWatcher = new CompMovementWatcher (this);
  23299. activeVSTWindows.add (this);
  23300. setSize (1, 1);
  23301. setOpaque (true);
  23302. setVisible (true);
  23303. }
  23304. ~VSTPluginWindow()
  23305. {
  23306. deleteAndZero (movementWatcher);
  23307. closePluginWindow();
  23308. activeVSTWindows.removeValue (this);
  23309. plugin.editorBeingDeleted (this);
  23310. }
  23311. void componentMovedOrResized()
  23312. {
  23313. if (recursiveResize)
  23314. return;
  23315. Component* const topComp = getTopLevelComponent();
  23316. if (topComp->getPeer() != 0)
  23317. {
  23318. int x = 0, y = 0;
  23319. relativePositionToOtherComponent (topComp, x, y);
  23320. recursiveResize = true;
  23321. #if JUCE_MAC
  23322. if (pluginViewRef != 0)
  23323. {
  23324. HIRect r;
  23325. r.origin.x = (float) x;
  23326. r.origin.y = (float) y;
  23327. r.size.width = (float) getWidth();
  23328. r.size.height = (float) getHeight();
  23329. HIViewSetFrame (pluginViewRef, &r);
  23330. }
  23331. else if (pluginWindowRef != 0)
  23332. {
  23333. Rect r;
  23334. r.left = getScreenX();
  23335. r.top = getScreenY();
  23336. r.right = r.left + getWidth();
  23337. r.bottom = r.top + getHeight();
  23338. WindowGroupRef group = GetWindowGroup (pluginWindowRef);
  23339. WindowGroupAttributes atts;
  23340. GetWindowGroupAttributes (group, &atts);
  23341. ChangeWindowGroupAttributes (group, 0, kWindowGroupAttrMoveTogether);
  23342. SetWindowBounds (pluginWindowRef, kWindowContentRgn, &r);
  23343. if ((atts & kWindowGroupAttrMoveTogether) != 0)
  23344. ChangeWindowGroupAttributes (group, kWindowGroupAttrMoveTogether, 0);
  23345. }
  23346. else
  23347. {
  23348. repaint();
  23349. }
  23350. #elif JUCE_WIN32
  23351. if (pluginHWND != 0)
  23352. MoveWindow (pluginHWND, x, y, getWidth(), getHeight(), TRUE);
  23353. #elif JUCE_LINUX
  23354. if (pluginWindow != 0)
  23355. {
  23356. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  23357. XMoveWindow (display, pluginWindow, x, y);
  23358. XMapRaised (display, pluginWindow);
  23359. }
  23360. #endif
  23361. recursiveResize = false;
  23362. }
  23363. }
  23364. void componentVisibilityChanged()
  23365. {
  23366. const bool isShowingNow = isShowing();
  23367. if (wasShowing != isShowingNow)
  23368. {
  23369. wasShowing = isShowingNow;
  23370. if (isShowingNow)
  23371. openPluginWindow();
  23372. else
  23373. closePluginWindow();
  23374. }
  23375. componentMovedOrResized();
  23376. }
  23377. void componentPeerChanged()
  23378. {
  23379. closePluginWindow();
  23380. openPluginWindow();
  23381. }
  23382. bool keyStateChanged()
  23383. {
  23384. return pluginWantsKeys;
  23385. }
  23386. bool keyPressed (const KeyPress&)
  23387. {
  23388. return pluginWantsKeys;
  23389. }
  23390. void paint (Graphics& g)
  23391. {
  23392. if (isOpen)
  23393. {
  23394. ComponentPeer* const peer = getPeer();
  23395. if (peer != 0)
  23396. {
  23397. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  23398. getScreenY() - peer->getScreenY(),
  23399. getWidth(), getHeight());
  23400. #if JUCE_MAC
  23401. if (pluginViewRef == 0)
  23402. {
  23403. ERect r;
  23404. r.left = getScreenX() - peer->getScreenX();
  23405. r.right = r.left + getWidth();
  23406. r.top = getScreenY() - peer->getScreenY();
  23407. r.bottom = r.top + getHeight();
  23408. dispatch (effEditDraw, 0, 0, &r, 0);
  23409. }
  23410. #elif JUCE_LINUX
  23411. if (pluginWindow != 0)
  23412. {
  23413. const Rectangle clip (g.getClipBounds());
  23414. XEvent ev;
  23415. zerostruct (ev);
  23416. ev.xexpose.type = Expose;
  23417. ev.xexpose.display = display;
  23418. ev.xexpose.window = pluginWindow;
  23419. ev.xexpose.x = clip.getX();
  23420. ev.xexpose.y = clip.getY();
  23421. ev.xexpose.width = clip.getWidth();
  23422. ev.xexpose.height = clip.getHeight();
  23423. sendEventToChild (&ev);
  23424. }
  23425. #endif
  23426. }
  23427. }
  23428. else
  23429. {
  23430. g.fillAll (Colours::black);
  23431. }
  23432. }
  23433. void timerCallback()
  23434. {
  23435. #if JUCE_WIN32
  23436. if (--sizeCheckCount <= 0)
  23437. {
  23438. sizeCheckCount = 10;
  23439. checkPluginWindowSize();
  23440. }
  23441. #endif
  23442. try
  23443. {
  23444. static bool reentrant = false;
  23445. if (! reentrant)
  23446. {
  23447. reentrant = true;
  23448. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  23449. reentrant = false;
  23450. }
  23451. }
  23452. catch (...)
  23453. {}
  23454. }
  23455. void mouseDown (const MouseEvent& e)
  23456. {
  23457. #if JUCE_MAC
  23458. if (! alreadyInside)
  23459. {
  23460. alreadyInside = true;
  23461. toFront (true);
  23462. dispatch (effEditMouse, e.x, e.y, 0, 0);
  23463. alreadyInside = false;
  23464. }
  23465. else
  23466. {
  23467. PostEvent (::mouseDown, 0);
  23468. }
  23469. #elif JUCE_LINUX
  23470. if (pluginWindow == 0)
  23471. return;
  23472. toFront (true);
  23473. XEvent ev;
  23474. zerostruct (ev);
  23475. ev.xbutton.display = display;
  23476. ev.xbutton.type = ButtonPress;
  23477. ev.xbutton.window = pluginWindow;
  23478. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  23479. ev.xbutton.time = CurrentTime;
  23480. ev.xbutton.x = e.x;
  23481. ev.xbutton.y = e.y;
  23482. ev.xbutton.x_root = e.getScreenX();
  23483. ev.xbutton.y_root = e.getScreenY();
  23484. translateJuceToXButtonModifiers (e, ev);
  23485. sendEventToChild (&ev);
  23486. #else
  23487. (void) e;
  23488. toFront (true);
  23489. #endif
  23490. }
  23491. void broughtToFront()
  23492. {
  23493. activeVSTWindows.removeValue (this);
  23494. activeVSTWindows.add (this);
  23495. #if JUCE_MAC
  23496. dispatch (effEditTop, 0, 0, 0, 0);
  23497. #endif
  23498. }
  23499. juce_UseDebuggingNewOperator
  23500. private:
  23501. VSTPluginInstance& plugin;
  23502. bool isOpen, wasShowing, recursiveResize;
  23503. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  23504. #if JUCE_WIN32
  23505. HWND pluginHWND;
  23506. void* originalWndProc;
  23507. int sizeCheckCount;
  23508. #elif JUCE_MAC
  23509. HIViewRef pluginViewRef;
  23510. WindowRef pluginWindowRef;
  23511. #elif JUCE_LINUX
  23512. Window pluginWindow;
  23513. EventProcPtr pluginProc;
  23514. #endif
  23515. void openPluginWindow()
  23516. {
  23517. if (isOpen || getWindowHandle() == 0)
  23518. return;
  23519. log (T("Opening VST UI: ") + plugin.name);
  23520. isOpen = true;
  23521. ERect* rect = 0;
  23522. dispatch (effEditGetRect, 0, 0, &rect, 0);
  23523. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  23524. // do this before and after like in the steinberg example
  23525. dispatch (effEditGetRect, 0, 0, &rect, 0);
  23526. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  23527. // Install keyboard hooks
  23528. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  23529. #if JUCE_WIN32
  23530. originalWndProc = 0;
  23531. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  23532. if (pluginHWND == 0)
  23533. {
  23534. isOpen = false;
  23535. setSize (300, 150);
  23536. return;
  23537. }
  23538. #pragma warning (push)
  23539. #pragma warning (disable: 4244)
  23540. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  23541. if (! pluginWantsKeys)
  23542. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) vstHookWndProc);
  23543. #pragma warning (pop)
  23544. int w, h;
  23545. RECT r;
  23546. GetWindowRect (pluginHWND, &r);
  23547. w = r.right - r.left;
  23548. h = r.bottom - r.top;
  23549. if (rect != 0)
  23550. {
  23551. const int rw = rect->right - rect->left;
  23552. const int rh = rect->bottom - rect->top;
  23553. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  23554. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  23555. {
  23556. // very dodgy logic to decide which size is right.
  23557. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  23558. {
  23559. SetWindowPos (pluginHWND, 0,
  23560. 0, 0, rw, rh,
  23561. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  23562. GetWindowRect (pluginHWND, &r);
  23563. w = r.right - r.left;
  23564. h = r.bottom - r.top;
  23565. pluginRefusesToResize = (w != rw) || (h != rh);
  23566. w = rw;
  23567. h = rh;
  23568. }
  23569. }
  23570. }
  23571. #elif JUCE_MAC
  23572. HIViewRef root = HIViewGetRoot ((WindowRef) getWindowHandle());
  23573. HIViewFindByID (root, kHIViewWindowContentID, &root);
  23574. pluginViewRef = HIViewGetFirstSubview (root);
  23575. while (pluginViewRef != 0 && juce_isHIViewCreatedByJuce (pluginViewRef))
  23576. pluginViewRef = HIViewGetNextView (pluginViewRef);
  23577. pluginWindowRef = 0;
  23578. if (pluginViewRef == 0)
  23579. {
  23580. WindowGroupRef ourGroup = GetWindowGroup ((WindowRef) getWindowHandle());
  23581. //DebugPrintWindowGroup (ourGroup);
  23582. //DebugPrintAllWindowGroups();
  23583. GetIndexedWindow (ourGroup, 1,
  23584. kWindowGroupContentsVisible,
  23585. &pluginWindowRef);
  23586. if (pluginWindowRef == (WindowRef) getWindowHandle()
  23587. || juce_isWindowCreatedByJuce (pluginWindowRef))
  23588. pluginWindowRef = 0;
  23589. }
  23590. int w = 250, h = 150;
  23591. if (rect != 0)
  23592. {
  23593. w = rect->right - rect->left;
  23594. h = rect->bottom - rect->top;
  23595. if (w == 0 || h == 0)
  23596. {
  23597. w = 250;
  23598. h = 150;
  23599. }
  23600. }
  23601. #elif JUCE_LINUX
  23602. pluginWindow = getChildWindow ((Window) getWindowHandle());
  23603. if (pluginWindow != 0)
  23604. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  23605. XInternAtom (display, "_XEventProc", False));
  23606. int w = 250, h = 150;
  23607. if (rect != 0)
  23608. {
  23609. w = rect->right - rect->left;
  23610. h = rect->bottom - rect->top;
  23611. if (w == 0 || h == 0)
  23612. {
  23613. w = 250;
  23614. h = 150;
  23615. }
  23616. }
  23617. if (pluginWindow != 0)
  23618. XMapRaised (display, pluginWindow);
  23619. #endif
  23620. // double-check it's not too tiny
  23621. w = jmax (w, 32);
  23622. h = jmax (h, 32);
  23623. setSize (w, h);
  23624. #if JUCE_WIN32
  23625. checkPluginWindowSize();
  23626. #endif
  23627. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  23628. repaint();
  23629. }
  23630. void closePluginWindow()
  23631. {
  23632. if (isOpen)
  23633. {
  23634. log (T("Closing VST UI: ") + plugin.getName());
  23635. isOpen = false;
  23636. dispatch (effEditClose, 0, 0, 0, 0);
  23637. #if JUCE_WIN32
  23638. #pragma warning (push)
  23639. #pragma warning (disable: 4244)
  23640. if (pluginHWND != 0 && IsWindow (pluginHWND))
  23641. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) originalWndProc);
  23642. #pragma warning (pop)
  23643. stopTimer();
  23644. if (pluginHWND != 0 && IsWindow (pluginHWND))
  23645. DestroyWindow (pluginHWND);
  23646. pluginHWND = 0;
  23647. #elif JUCE_MAC
  23648. dispatch (effEditSleep, 0, 0, 0, 0);
  23649. pluginViewRef = 0;
  23650. stopTimer();
  23651. #elif JUCE_LINUX
  23652. stopTimer();
  23653. pluginWindow = 0;
  23654. pluginProc = 0;
  23655. #endif
  23656. }
  23657. }
  23658. #if JUCE_WIN32
  23659. void checkPluginWindowSize() throw()
  23660. {
  23661. RECT r;
  23662. GetWindowRect (pluginHWND, &r);
  23663. const int w = r.right - r.left;
  23664. const int h = r.bottom - r.top;
  23665. if (isShowing() && w > 0 && h > 0
  23666. && (w != getWidth() || h != getHeight())
  23667. && ! pluginRefusesToResize)
  23668. {
  23669. setSize (w, h);
  23670. sizeCheckCount = 0;
  23671. }
  23672. }
  23673. #endif
  23674. class CompMovementWatcher : public ComponentMovementWatcher
  23675. {
  23676. public:
  23677. CompMovementWatcher (VSTPluginWindow* const owner_)
  23678. : ComponentMovementWatcher (owner_),
  23679. owner (owner_)
  23680. {
  23681. }
  23682. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  23683. {
  23684. owner->componentMovedOrResized();
  23685. }
  23686. void componentPeerChanged()
  23687. {
  23688. owner->componentPeerChanged();
  23689. }
  23690. void componentVisibilityChanged (Component&)
  23691. {
  23692. owner->componentVisibilityChanged();
  23693. }
  23694. private:
  23695. VSTPluginWindow* const owner;
  23696. };
  23697. CompMovementWatcher* movementWatcher;
  23698. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  23699. {
  23700. return plugin.dispatch (opcode, index, value, ptr, opt);
  23701. }
  23702. // hooks to get keyboard events from VST windows..
  23703. #if JUCE_WIN32
  23704. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  23705. {
  23706. for (int i = activeVSTWindows.size(); --i >= 0;)
  23707. {
  23708. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  23709. if (w->pluginHWND == hW)
  23710. {
  23711. if (message == WM_CHAR
  23712. || message == WM_KEYDOWN
  23713. || message == WM_SYSKEYDOWN
  23714. || message == WM_KEYUP
  23715. || message == WM_SYSKEYUP
  23716. || message == WM_APPCOMMAND)
  23717. {
  23718. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  23719. message, wParam, lParam);
  23720. }
  23721. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  23722. (HWND) w->pluginHWND,
  23723. message,
  23724. wParam,
  23725. lParam);
  23726. }
  23727. }
  23728. return DefWindowProc (hW, message, wParam, lParam);
  23729. }
  23730. #endif
  23731. #if JUCE_LINUX
  23732. // overload mouse/keyboard events to forward them to the plugin's inner window..
  23733. void sendEventToChild (XEvent* event)
  23734. {
  23735. if (pluginProc != 0)
  23736. {
  23737. // if the plugin publishes an event procedure, pass the event directly..
  23738. pluginProc (event);
  23739. }
  23740. else if (pluginWindow != 0)
  23741. {
  23742. // if the plugin has a window, then send the event to the window so that
  23743. // its message thread will pick it up..
  23744. XSendEvent (display, pluginWindow, False, 0L, event);
  23745. XFlush (display);
  23746. }
  23747. }
  23748. void mouseEnter (const MouseEvent& e)
  23749. {
  23750. if (pluginWindow != 0)
  23751. {
  23752. XEvent ev;
  23753. zerostruct (ev);
  23754. ev.xcrossing.display = display;
  23755. ev.xcrossing.type = EnterNotify;
  23756. ev.xcrossing.window = pluginWindow;
  23757. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  23758. ev.xcrossing.time = CurrentTime;
  23759. ev.xcrossing.x = e.x;
  23760. ev.xcrossing.y = e.y;
  23761. ev.xcrossing.x_root = e.getScreenX();
  23762. ev.xcrossing.y_root = e.getScreenY();
  23763. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  23764. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  23765. translateJuceToXCrossingModifiers (e, ev);
  23766. sendEventToChild (&ev);
  23767. }
  23768. }
  23769. void mouseExit (const MouseEvent& e)
  23770. {
  23771. if (pluginWindow != 0)
  23772. {
  23773. XEvent ev;
  23774. zerostruct (ev);
  23775. ev.xcrossing.display = display;
  23776. ev.xcrossing.type = LeaveNotify;
  23777. ev.xcrossing.window = pluginWindow;
  23778. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  23779. ev.xcrossing.time = CurrentTime;
  23780. ev.xcrossing.x = e.x;
  23781. ev.xcrossing.y = e.y;
  23782. ev.xcrossing.x_root = e.getScreenX();
  23783. ev.xcrossing.y_root = e.getScreenY();
  23784. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  23785. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  23786. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  23787. translateJuceToXCrossingModifiers (e, ev);
  23788. sendEventToChild (&ev);
  23789. }
  23790. }
  23791. void mouseMove (const MouseEvent& e)
  23792. {
  23793. if (pluginWindow != 0)
  23794. {
  23795. XEvent ev;
  23796. zerostruct (ev);
  23797. ev.xmotion.display = display;
  23798. ev.xmotion.type = MotionNotify;
  23799. ev.xmotion.window = pluginWindow;
  23800. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  23801. ev.xmotion.time = CurrentTime;
  23802. ev.xmotion.is_hint = NotifyNormal;
  23803. ev.xmotion.x = e.x;
  23804. ev.xmotion.y = e.y;
  23805. ev.xmotion.x_root = e.getScreenX();
  23806. ev.xmotion.y_root = e.getScreenY();
  23807. sendEventToChild (&ev);
  23808. }
  23809. }
  23810. void mouseDrag (const MouseEvent& e)
  23811. {
  23812. if (pluginWindow != 0)
  23813. {
  23814. XEvent ev;
  23815. zerostruct (ev);
  23816. ev.xmotion.display = display;
  23817. ev.xmotion.type = MotionNotify;
  23818. ev.xmotion.window = pluginWindow;
  23819. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  23820. ev.xmotion.time = CurrentTime;
  23821. ev.xmotion.x = e.x ;
  23822. ev.xmotion.y = e.y;
  23823. ev.xmotion.x_root = e.getScreenX();
  23824. ev.xmotion.y_root = e.getScreenY();
  23825. ev.xmotion.is_hint = NotifyNormal;
  23826. translateJuceToXMotionModifiers (e, ev);
  23827. sendEventToChild (&ev);
  23828. }
  23829. }
  23830. void mouseUp (const MouseEvent& e)
  23831. {
  23832. if (pluginWindow != 0)
  23833. {
  23834. XEvent ev;
  23835. zerostruct (ev);
  23836. ev.xbutton.display = display;
  23837. ev.xbutton.type = ButtonRelease;
  23838. ev.xbutton.window = pluginWindow;
  23839. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  23840. ev.xbutton.time = CurrentTime;
  23841. ev.xbutton.x = e.x;
  23842. ev.xbutton.y = e.y;
  23843. ev.xbutton.x_root = e.getScreenX();
  23844. ev.xbutton.y_root = e.getScreenY();
  23845. translateJuceToXButtonModifiers (e, ev);
  23846. sendEventToChild (&ev);
  23847. }
  23848. }
  23849. void mouseWheelMove (const MouseEvent& e,
  23850. float incrementX,
  23851. float incrementY)
  23852. {
  23853. if (pluginWindow != 0)
  23854. {
  23855. XEvent ev;
  23856. zerostruct (ev);
  23857. ev.xbutton.display = display;
  23858. ev.xbutton.type = ButtonPress;
  23859. ev.xbutton.window = pluginWindow;
  23860. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  23861. ev.xbutton.time = CurrentTime;
  23862. ev.xbutton.x = e.x;
  23863. ev.xbutton.y = e.y;
  23864. ev.xbutton.x_root = e.getScreenX();
  23865. ev.xbutton.y_root = e.getScreenY();
  23866. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  23867. sendEventToChild (&ev);
  23868. // TODO - put a usleep here ?
  23869. ev.xbutton.type = ButtonRelease;
  23870. sendEventToChild (&ev);
  23871. }
  23872. }
  23873. #endif
  23874. };
  23875. AudioProcessorEditor* VSTPluginInstance::createEditor()
  23876. {
  23877. if (hasEditor())
  23878. return new VSTPluginWindow (*this);
  23879. return 0;
  23880. }
  23881. void VSTPluginInstance::handleAsyncUpdate()
  23882. {
  23883. // indicates that something about the plugin has changed..
  23884. updateHostDisplay();
  23885. }
  23886. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  23887. {
  23888. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  23889. {
  23890. changeProgramName (getCurrentProgram(), prog->prgName);
  23891. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  23892. setParameter (i, vst_swapFloat (prog->params[i]));
  23893. return true;
  23894. }
  23895. return false;
  23896. }
  23897. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  23898. const int dataSize)
  23899. {
  23900. if (dataSize < 28)
  23901. return false;
  23902. const fxSet* const set = (const fxSet*) data;
  23903. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  23904. || vst_swap (set->version) > fxbVersionNum)
  23905. return false;
  23906. if (vst_swap (set->fxMagic) == 'FxBk')
  23907. {
  23908. // bank of programs
  23909. if (vst_swap (set->numPrograms) >= 0)
  23910. {
  23911. const int oldProg = getCurrentProgram();
  23912. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  23913. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  23914. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  23915. {
  23916. if (i != oldProg)
  23917. {
  23918. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  23919. if (((const char*) prog) - ((const char*) set) >= dataSize)
  23920. return false;
  23921. if (vst_swap (set->numPrograms) > 0)
  23922. setCurrentProgram (i);
  23923. if (! restoreProgramSettings (prog))
  23924. return false;
  23925. }
  23926. }
  23927. if (vst_swap (set->numPrograms) > 0)
  23928. setCurrentProgram (oldProg);
  23929. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  23930. if (((const char*) prog) - ((const char*) set) >= dataSize)
  23931. return false;
  23932. if (! restoreProgramSettings (prog))
  23933. return false;
  23934. }
  23935. }
  23936. else if (vst_swap (set->fxMagic) == 'FxCk')
  23937. {
  23938. // single program
  23939. const fxProgram* const prog = (const fxProgram*) data;
  23940. if (vst_swap (prog->chunkMagic) != 'CcnK')
  23941. return false;
  23942. changeProgramName (getCurrentProgram(), prog->prgName);
  23943. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  23944. setParameter (i, vst_swapFloat (prog->params[i]));
  23945. }
  23946. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  23947. {
  23948. // non-preset chunk
  23949. const fxChunkSet* const cset = (const fxChunkSet*) data;
  23950. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  23951. return false;
  23952. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  23953. }
  23954. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  23955. {
  23956. // preset chunk
  23957. const fxProgramSet* const cset = (const fxProgramSet*) data;
  23958. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  23959. return false;
  23960. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  23961. changeProgramName (getCurrentProgram(), cset->name);
  23962. }
  23963. else
  23964. {
  23965. return false;
  23966. }
  23967. return true;
  23968. }
  23969. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  23970. {
  23971. const int numParams = getNumParameters();
  23972. prog->chunkMagic = vst_swap ('CcnK');
  23973. prog->byteSize = 0;
  23974. prog->fxMagic = vst_swap ('FxCk');
  23975. prog->version = vst_swap (fxbVersionNum);
  23976. prog->fxID = vst_swap (getUID());
  23977. prog->fxVersion = vst_swap (getVersionNumber());
  23978. prog->numParams = vst_swap (numParams);
  23979. getCurrentProgramName().copyToBuffer (prog->prgName, sizeof (prog->prgName) - 1);
  23980. for (int i = 0; i < numParams; ++i)
  23981. prog->params[i] = vst_swapFloat (getParameter (i));
  23982. }
  23983. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  23984. {
  23985. const int numPrograms = getNumPrograms();
  23986. const int numParams = getNumParameters();
  23987. if (usesChunks())
  23988. {
  23989. if (isFXB)
  23990. {
  23991. MemoryBlock chunk;
  23992. getChunkData (chunk, false, maxSizeMB);
  23993. const int totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  23994. dest.setSize (totalLen, true);
  23995. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  23996. set->chunkMagic = vst_swap ('CcnK');
  23997. set->byteSize = 0;
  23998. set->fxMagic = vst_swap ('FBCh');
  23999. set->version = vst_swap (fxbVersionNum);
  24000. set->fxID = vst_swap (getUID());
  24001. set->fxVersion = vst_swap (getVersionNumber());
  24002. set->numPrograms = vst_swap (numPrograms);
  24003. set->chunkSize = vst_swap (chunk.getSize());
  24004. chunk.copyTo (set->chunk, 0, chunk.getSize());
  24005. }
  24006. else
  24007. {
  24008. MemoryBlock chunk;
  24009. getChunkData (chunk, true, maxSizeMB);
  24010. const int totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  24011. dest.setSize (totalLen, true);
  24012. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  24013. set->chunkMagic = vst_swap ('CcnK');
  24014. set->byteSize = 0;
  24015. set->fxMagic = vst_swap ('FPCh');
  24016. set->version = vst_swap (fxbVersionNum);
  24017. set->fxID = vst_swap (getUID());
  24018. set->fxVersion = vst_swap (getVersionNumber());
  24019. set->numPrograms = vst_swap (numPrograms);
  24020. set->chunkSize = vst_swap (chunk.getSize());
  24021. getCurrentProgramName().copyToBuffer (set->name, sizeof (set->name) - 1);
  24022. chunk.copyTo (set->chunk, 0, chunk.getSize());
  24023. }
  24024. }
  24025. else
  24026. {
  24027. if (isFXB)
  24028. {
  24029. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  24030. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  24031. dest.setSize (len, true);
  24032. fxSet* const set = (fxSet*) dest.getData();
  24033. set->chunkMagic = vst_swap ('CcnK');
  24034. set->byteSize = 0;
  24035. set->fxMagic = vst_swap ('FxBk');
  24036. set->version = vst_swap (fxbVersionNum);
  24037. set->fxID = vst_swap (getUID());
  24038. set->fxVersion = vst_swap (getVersionNumber());
  24039. set->numPrograms = vst_swap (numPrograms);
  24040. const int oldProgram = getCurrentProgram();
  24041. MemoryBlock oldSettings;
  24042. createTempParameterStore (oldSettings);
  24043. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  24044. for (int i = 0; i < numPrograms; ++i)
  24045. {
  24046. if (i != oldProgram)
  24047. {
  24048. setCurrentProgram (i);
  24049. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  24050. }
  24051. }
  24052. setCurrentProgram (oldProgram);
  24053. restoreFromTempParameterStore (oldSettings);
  24054. }
  24055. else
  24056. {
  24057. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  24058. dest.setSize (totalLen, true);
  24059. setParamsInProgramBlock ((fxProgram*) dest.getData());
  24060. }
  24061. }
  24062. return true;
  24063. }
  24064. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  24065. {
  24066. if (usesChunks())
  24067. {
  24068. void* data = 0;
  24069. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  24070. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  24071. {
  24072. mb.setSize (bytes);
  24073. mb.copyFrom (data, 0, bytes);
  24074. }
  24075. }
  24076. }
  24077. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  24078. {
  24079. if (size > 0 && usesChunks())
  24080. {
  24081. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  24082. if (! isPreset)
  24083. updateStoredProgramNames();
  24084. }
  24085. }
  24086. void VSTPluginInstance::timerCallback()
  24087. {
  24088. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  24089. stopTimer();
  24090. }
  24091. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  24092. {
  24093. const ScopedLock sl (lock);
  24094. ++insideVSTCallback;
  24095. int result = 0;
  24096. try
  24097. {
  24098. if (effect != 0)
  24099. {
  24100. #if JUCE_MAC
  24101. if (module->resFileId != 0)
  24102. UseResFile (module->resFileId);
  24103. CGrafPtr oldPort;
  24104. if (getActiveEditor() != 0)
  24105. {
  24106. int x = 0, y = 0;
  24107. getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), x, y);
  24108. GetPort (&oldPort);
  24109. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  24110. SetOrigin (-x, -y);
  24111. }
  24112. #endif
  24113. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  24114. #if JUCE_MAC
  24115. if (getActiveEditor() != 0)
  24116. SetPort (oldPort);
  24117. module->resFileId = CurResFile();
  24118. #endif
  24119. --insideVSTCallback;
  24120. return result;
  24121. }
  24122. }
  24123. catch (...)
  24124. {
  24125. //char s[512];
  24126. //sprintf (s, "dispatcher (%d, %d, %d, %x, %f)", opcode, index, value, (int)ptr, opt);
  24127. }
  24128. --insideVSTCallback;
  24129. return result;
  24130. }
  24131. // handles non plugin-specific callbacks..
  24132. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  24133. {
  24134. (void) index;
  24135. (void) value;
  24136. (void) opt;
  24137. switch (opcode)
  24138. {
  24139. case audioMasterCanDo:
  24140. {
  24141. static const char* canDos[] = { "supplyIdle",
  24142. "sendVstEvents",
  24143. "sendVstMidiEvent",
  24144. "sendVstTimeInfo",
  24145. "receiveVstEvents",
  24146. "receiveVstMidiEvent",
  24147. "supportShell",
  24148. "shellCategory" };
  24149. for (int i = 0; i < numElementsInArray (canDos); ++i)
  24150. if (strcmp (canDos[i], (const char*) ptr) == 0)
  24151. return 1;
  24152. return 0;
  24153. }
  24154. case audioMasterVersion:
  24155. return 0x2400;
  24156. case audioMasterCurrentId:
  24157. return shellUIDToCreate;
  24158. case audioMasterGetNumAutomatableParameters:
  24159. return 0;
  24160. case audioMasterGetAutomationState:
  24161. return 1;
  24162. case audioMasterGetVendorVersion:
  24163. return 0x0101;
  24164. case audioMasterGetVendorString:
  24165. case audioMasterGetProductString:
  24166. {
  24167. String hostName ("Juce VST Host");
  24168. if (JUCEApplication::getInstance() != 0)
  24169. hostName = JUCEApplication::getInstance()->getApplicationName();
  24170. hostName.copyToBuffer ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  24171. }
  24172. break;
  24173. case audioMasterGetSampleRate:
  24174. return 44100;
  24175. case audioMasterGetBlockSize:
  24176. return 512;
  24177. case audioMasterSetOutputSampleRate:
  24178. return 0;
  24179. default:
  24180. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  24181. break;
  24182. }
  24183. return 0;
  24184. }
  24185. // handles callbacks for a specific plugin
  24186. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  24187. {
  24188. switch (opcode)
  24189. {
  24190. case audioMasterAutomate:
  24191. sendParamChangeMessageToListeners (index, opt);
  24192. break;
  24193. case audioMasterProcessEvents:
  24194. handleMidiFromPlugin ((const VstEvents*) ptr);
  24195. break;
  24196. case audioMasterGetTime:
  24197. #ifdef _MSC_VER
  24198. #pragma warning (push)
  24199. #pragma warning (disable: 4311)
  24200. #endif
  24201. return (VstIntPtr) &vstHostTime;
  24202. #ifdef _MSC_VER
  24203. #pragma warning (pop)
  24204. #endif
  24205. break;
  24206. case audioMasterIdle:
  24207. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  24208. {
  24209. ++insideVSTCallback;
  24210. #if JUCE_MAC
  24211. if (getActiveEditor() != 0)
  24212. dispatch (effEditIdle, 0, 0, 0, 0);
  24213. #endif
  24214. const MessageManagerLock mml;
  24215. juce_callAnyTimersSynchronously();
  24216. handleUpdateNowIfNeeded();
  24217. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  24218. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  24219. --insideVSTCallback;
  24220. }
  24221. break;
  24222. case audioMasterUpdateDisplay:
  24223. triggerAsyncUpdate();
  24224. break;
  24225. case audioMasterTempoAt:
  24226. // returns (10000 * bpm)
  24227. break;
  24228. case audioMasterNeedIdle:
  24229. startTimer (50);
  24230. break;
  24231. case audioMasterSizeWindow:
  24232. if (getActiveEditor() != 0)
  24233. getActiveEditor()->setSize (index, value);
  24234. return 1;
  24235. case audioMasterGetSampleRate:
  24236. return (VstIntPtr) getSampleRate();
  24237. case audioMasterGetBlockSize:
  24238. return (VstIntPtr) getBlockSize();
  24239. case audioMasterWantMidi:
  24240. wantsMidiMessages = true;
  24241. break;
  24242. case audioMasterGetDirectory:
  24243. #if JUCE_MAC
  24244. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  24245. #else
  24246. return (VstIntPtr) (pointer_sized_uint) (const char*) module->fullParentDirectoryPathName;
  24247. #endif
  24248. case audioMasterGetAutomationState:
  24249. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  24250. break;
  24251. // none of these are handled (yet)..
  24252. case audioMasterBeginEdit:
  24253. case audioMasterEndEdit:
  24254. case audioMasterSetTime:
  24255. case audioMasterPinConnected:
  24256. case audioMasterGetParameterQuantization:
  24257. case audioMasterIOChanged:
  24258. case audioMasterGetInputLatency:
  24259. case audioMasterGetOutputLatency:
  24260. case audioMasterGetPreviousPlug:
  24261. case audioMasterGetNextPlug:
  24262. case audioMasterWillReplaceOrAccumulate:
  24263. case audioMasterGetCurrentProcessLevel:
  24264. case audioMasterOfflineStart:
  24265. case audioMasterOfflineRead:
  24266. case audioMasterOfflineWrite:
  24267. case audioMasterOfflineGetCurrentPass:
  24268. case audioMasterOfflineGetCurrentMetaPass:
  24269. case audioMasterVendorSpecific:
  24270. case audioMasterSetIcon:
  24271. case audioMasterGetLanguage:
  24272. case audioMasterOpenWindow:
  24273. case audioMasterCloseWindow:
  24274. break;
  24275. default:
  24276. return handleGeneralCallback (opcode, index, value, ptr, opt);
  24277. }
  24278. return 0;
  24279. }
  24280. // entry point for all callbacks from the plugin
  24281. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  24282. {
  24283. try
  24284. {
  24285. if (effect != 0 && effect->resvd2 != 0)
  24286. {
  24287. return ((VSTPluginInstance*)(effect->resvd2))
  24288. ->handleCallback (opcode, index, value, ptr, opt);
  24289. }
  24290. return handleGeneralCallback (opcode, index, value, ptr, opt);
  24291. }
  24292. catch (...)
  24293. {
  24294. return 0;
  24295. }
  24296. }
  24297. const String VSTPluginInstance::getVersion() const throw()
  24298. {
  24299. int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  24300. String s;
  24301. if (v != 0)
  24302. {
  24303. int versionBits[4];
  24304. int n = 0;
  24305. while (v != 0)
  24306. {
  24307. versionBits [n++] = (v & 0xff);
  24308. v >>= 8;
  24309. }
  24310. s << 'V';
  24311. while (n > 0)
  24312. {
  24313. s << versionBits [--n];
  24314. if (n > 0)
  24315. s << '.';
  24316. }
  24317. }
  24318. return s;
  24319. }
  24320. int VSTPluginInstance::getUID() const throw()
  24321. {
  24322. int uid = effect != 0 ? effect->uniqueID : 0;
  24323. if (uid == 0)
  24324. uid = module->file.hashCode();
  24325. return uid;
  24326. }
  24327. const String VSTPluginInstance::getCategory() const throw()
  24328. {
  24329. const char* result = 0;
  24330. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  24331. {
  24332. case kPlugCategEffect:
  24333. result = "Effect";
  24334. break;
  24335. case kPlugCategSynth:
  24336. result = "Synth";
  24337. break;
  24338. case kPlugCategAnalysis:
  24339. result = "Anaylsis";
  24340. break;
  24341. case kPlugCategMastering:
  24342. result = "Mastering";
  24343. break;
  24344. case kPlugCategSpacializer:
  24345. result = "Spacial";
  24346. break;
  24347. case kPlugCategRoomFx:
  24348. result = "Reverb";
  24349. break;
  24350. case kPlugSurroundFx:
  24351. result = "Surround";
  24352. break;
  24353. case kPlugCategRestoration:
  24354. result = "Restoration";
  24355. break;
  24356. case kPlugCategGenerator:
  24357. result = "Tone generation";
  24358. break;
  24359. default:
  24360. break;
  24361. }
  24362. return result;
  24363. }
  24364. float VSTPluginInstance::getParameter (int index)
  24365. {
  24366. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  24367. {
  24368. try
  24369. {
  24370. const ScopedLock sl (lock);
  24371. return effect->getParameter (effect, index);
  24372. }
  24373. catch (...)
  24374. {
  24375. }
  24376. }
  24377. return 0.0f;
  24378. }
  24379. void VSTPluginInstance::setParameter (int index, float newValue)
  24380. {
  24381. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  24382. {
  24383. try
  24384. {
  24385. const ScopedLock sl (lock);
  24386. if (effect->getParameter (effect, index) != newValue)
  24387. effect->setParameter (effect, index, newValue);
  24388. }
  24389. catch (...)
  24390. {
  24391. }
  24392. }
  24393. }
  24394. const String VSTPluginInstance::getParameterName (int index)
  24395. {
  24396. if (effect != 0)
  24397. {
  24398. jassert (index >= 0 && index < effect->numParams);
  24399. char nm [256];
  24400. zerostruct (nm);
  24401. dispatch (effGetParamName, index, 0, nm, 0);
  24402. return String (nm).trim();
  24403. }
  24404. return String::empty;
  24405. }
  24406. const String VSTPluginInstance::getParameterLabel (int index) const
  24407. {
  24408. if (effect != 0)
  24409. {
  24410. jassert (index >= 0 && index < effect->numParams);
  24411. char nm [256];
  24412. zerostruct (nm);
  24413. dispatch (effGetParamLabel, index, 0, nm, 0);
  24414. return String (nm).trim();
  24415. }
  24416. return String::empty;
  24417. }
  24418. const String VSTPluginInstance::getParameterText (int index)
  24419. {
  24420. if (effect != 0)
  24421. {
  24422. jassert (index >= 0 && index < effect->numParams);
  24423. char nm [256];
  24424. zerostruct (nm);
  24425. dispatch (effGetParamDisplay, index, 0, nm, 0);
  24426. return String (nm).trim();
  24427. }
  24428. return String::empty;
  24429. }
  24430. bool VSTPluginInstance::isParameterAutomatable (int index) const
  24431. {
  24432. if (effect != 0)
  24433. {
  24434. jassert (index >= 0 && index < effect->numParams);
  24435. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  24436. }
  24437. return false;
  24438. }
  24439. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  24440. {
  24441. dest.setSize (64 + 4 * getNumParameters());
  24442. dest.fillWith (0);
  24443. getCurrentProgramName().copyToBuffer ((char*) dest.getData(), 63);
  24444. float* const p = (float*) (((char*) dest.getData()) + 64);
  24445. for (int i = 0; i < getNumParameters(); ++i)
  24446. p[i] = getParameter(i);
  24447. }
  24448. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  24449. {
  24450. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  24451. float* p = (float*) (((char*) m.getData()) + 64);
  24452. for (int i = 0; i < getNumParameters(); ++i)
  24453. setParameter (i, p[i]);
  24454. }
  24455. void VSTPluginInstance::setCurrentProgram (int newIndex)
  24456. {
  24457. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  24458. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  24459. }
  24460. const String VSTPluginInstance::getProgramName (int index)
  24461. {
  24462. if (index == getCurrentProgram())
  24463. {
  24464. return getCurrentProgramName();
  24465. }
  24466. else if (effect != 0)
  24467. {
  24468. char nm [256];
  24469. zerostruct (nm);
  24470. if (dispatch (effGetProgramNameIndexed,
  24471. jlimit (0, getNumPrograms(), index),
  24472. -1, nm, 0) != 0)
  24473. {
  24474. return String (nm).trim();
  24475. }
  24476. }
  24477. return programNames [index];
  24478. }
  24479. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  24480. {
  24481. if (index == getCurrentProgram())
  24482. {
  24483. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  24484. dispatch (effSetProgramName, 0, 0, (void*) (const char*) newName.substring (0, 24), 0.0f);
  24485. }
  24486. else
  24487. {
  24488. jassertfalse // xxx not implemented!
  24489. }
  24490. }
  24491. void VSTPluginInstance::updateStoredProgramNames()
  24492. {
  24493. if (effect != 0 && getNumPrograms() > 0)
  24494. {
  24495. char nm [256];
  24496. zerostruct (nm);
  24497. // only do this if the plugin can't use indexed names..
  24498. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  24499. {
  24500. const int oldProgram = getCurrentProgram();
  24501. MemoryBlock oldSettings;
  24502. createTempParameterStore (oldSettings);
  24503. for (int i = 0; i < getNumPrograms(); ++i)
  24504. {
  24505. setCurrentProgram (i);
  24506. getCurrentProgramName(); // (this updates the list)
  24507. }
  24508. setCurrentProgram (oldProgram);
  24509. restoreFromTempParameterStore (oldSettings);
  24510. }
  24511. }
  24512. }
  24513. const String VSTPluginInstance::getCurrentProgramName()
  24514. {
  24515. if (effect != 0)
  24516. {
  24517. char nm [256];
  24518. zerostruct (nm);
  24519. dispatch (effGetProgramName, 0, 0, nm, 0);
  24520. const int index = getCurrentProgram();
  24521. if (programNames[index].isEmpty())
  24522. {
  24523. while (programNames.size() < index)
  24524. programNames.add (String::empty);
  24525. programNames.set (index, String (nm).trim());
  24526. }
  24527. return String (nm).trim();
  24528. }
  24529. return String::empty;
  24530. }
  24531. const String VSTPluginInstance::getInputChannelName (const int index) const
  24532. {
  24533. if (index >= 0 && index < getNumInputChannels())
  24534. {
  24535. VstPinProperties pinProps;
  24536. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  24537. return String (pinProps.label, sizeof (pinProps.label));
  24538. }
  24539. return String::empty;
  24540. }
  24541. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  24542. {
  24543. if (index < 0 || index >= getNumInputChannels())
  24544. return false;
  24545. VstPinProperties pinProps;
  24546. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  24547. return (pinProps.flags & kVstPinIsStereo) != 0;
  24548. return true;
  24549. }
  24550. const String VSTPluginInstance::getOutputChannelName (const int index) const
  24551. {
  24552. if (index >= 0 && index < getNumOutputChannels())
  24553. {
  24554. VstPinProperties pinProps;
  24555. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  24556. return String (pinProps.label, sizeof (pinProps.label));
  24557. }
  24558. return String::empty;
  24559. }
  24560. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  24561. {
  24562. if (index < 0 || index >= getNumOutputChannels())
  24563. return false;
  24564. VstPinProperties pinProps;
  24565. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  24566. return (pinProps.flags & kVstPinIsStereo) != 0;
  24567. return true;
  24568. }
  24569. void VSTPluginInstance::setPower (const bool on)
  24570. {
  24571. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  24572. isPowerOn = on;
  24573. }
  24574. const int defaultMaxSizeMB = 64;
  24575. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  24576. {
  24577. saveToFXBFile (destData, true, defaultMaxSizeMB);
  24578. }
  24579. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  24580. {
  24581. saveToFXBFile (destData, false, defaultMaxSizeMB);
  24582. }
  24583. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  24584. {
  24585. loadFromFXBFile (data, sizeInBytes);
  24586. }
  24587. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  24588. {
  24589. loadFromFXBFile (data, sizeInBytes);
  24590. }
  24591. VSTPluginFormat::VSTPluginFormat()
  24592. {
  24593. }
  24594. VSTPluginFormat::~VSTPluginFormat()
  24595. {
  24596. }
  24597. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  24598. const File& file)
  24599. {
  24600. if (! fileMightContainThisPluginType (file))
  24601. return;
  24602. PluginDescription desc;
  24603. desc.file = file;
  24604. desc.uid = 0;
  24605. VSTPluginInstance* instance = dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc));
  24606. if (instance == 0)
  24607. return;
  24608. try
  24609. {
  24610. #if JUCE_MAC
  24611. if (instance->module->resFileId != 0)
  24612. UseResFile (instance->module->resFileId);
  24613. #endif
  24614. instance->fillInPluginDescription (desc);
  24615. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  24616. if (category != kPlugCategShell)
  24617. {
  24618. // Normal plugin...
  24619. results.add (new PluginDescription (desc));
  24620. ++insideVSTCallback;
  24621. instance->dispatch (effOpen, 0, 0, 0, 0);
  24622. --insideVSTCallback;
  24623. }
  24624. else
  24625. {
  24626. // It's a shell plugin, so iterate all the subtypes...
  24627. char shellEffectName [64];
  24628. for (;;)
  24629. {
  24630. zerostruct (shellEffectName);
  24631. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  24632. if (uid == 0)
  24633. {
  24634. break;
  24635. }
  24636. else
  24637. {
  24638. desc.uid = uid;
  24639. desc.name = shellEffectName;
  24640. bool alreadyThere = false;
  24641. for (int i = results.size(); --i >= 0;)
  24642. {
  24643. PluginDescription* const d = results.getUnchecked(i);
  24644. if (d->isDuplicateOf (desc))
  24645. {
  24646. alreadyThere = true;
  24647. break;
  24648. }
  24649. }
  24650. if (! alreadyThere)
  24651. results.add (new PluginDescription (desc));
  24652. }
  24653. }
  24654. }
  24655. }
  24656. catch (...)
  24657. {
  24658. // crashed while loading...
  24659. }
  24660. deleteAndZero (instance);
  24661. }
  24662. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  24663. {
  24664. VSTPluginInstance* result = 0;
  24665. if (fileMightContainThisPluginType (desc.file))
  24666. {
  24667. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  24668. desc.file.getParentDirectory().setAsCurrentWorkingDirectory();
  24669. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (desc.file));
  24670. if (module != 0)
  24671. {
  24672. shellUIDToCreate = desc.uid;
  24673. result = new VSTPluginInstance (module);
  24674. if (result->effect != 0)
  24675. {
  24676. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) result;
  24677. result->initialise();
  24678. }
  24679. else
  24680. {
  24681. deleteAndZero (result);
  24682. }
  24683. }
  24684. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  24685. }
  24686. return result;
  24687. }
  24688. bool VSTPluginFormat::fileMightContainThisPluginType (const File& f)
  24689. {
  24690. #if JUCE_MAC
  24691. if (f.isDirectory() && f.hasFileExtension (T(".vst")))
  24692. return true;
  24693. #if JUCE_PPC
  24694. FSRef fileRef;
  24695. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  24696. {
  24697. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  24698. if (resFileId != -1)
  24699. {
  24700. const int numEffects = Count1Resources ('aEff');
  24701. CloseResFile (resFileId);
  24702. if (numEffects > 0)
  24703. return true;
  24704. }
  24705. }
  24706. #endif
  24707. return false;
  24708. #elif JUCE_WIN32
  24709. return f.existsAsFile()
  24710. && f.hasFileExtension (T(".dll"));
  24711. #elif JUCE_LINUX
  24712. return f.existsAsFile()
  24713. && f.hasFileExtension (T(".so"));
  24714. #endif
  24715. }
  24716. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  24717. {
  24718. #if JUCE_MAC
  24719. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  24720. #elif JUCE_WIN32
  24721. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  24722. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  24723. #elif JUCE_LINUX
  24724. return FileSearchPath ("/usr/lib/vst");
  24725. #endif
  24726. }
  24727. END_JUCE_NAMESPACE
  24728. #undef log
  24729. #endif
  24730. /********* End of inlined file: juce_VSTPluginFormat.cpp *********/
  24731. /********* Start of inlined file: juce_AudioProcessor.cpp *********/
  24732. BEGIN_JUCE_NAMESPACE
  24733. AudioProcessor::AudioProcessor()
  24734. : playHead (0),
  24735. activeEditor (0),
  24736. sampleRate (0),
  24737. blockSize (0),
  24738. numInputChannels (0),
  24739. numOutputChannels (0),
  24740. latencySamples (0),
  24741. suspended (false),
  24742. nonRealtime (false)
  24743. {
  24744. }
  24745. AudioProcessor::~AudioProcessor()
  24746. {
  24747. // ooh, nasty - the editor should have been deleted before the filter
  24748. // that it refers to is deleted..
  24749. jassert (activeEditor == 0);
  24750. #ifdef JUCE_DEBUG
  24751. // This will fail if you've called beginParameterChangeGesture() for one
  24752. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  24753. jassert (changingParams.countNumberOfSetBits() == 0);
  24754. #endif
  24755. }
  24756. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  24757. {
  24758. playHead = newPlayHead;
  24759. }
  24760. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  24761. {
  24762. const ScopedLock sl (listenerLock);
  24763. listeners.addIfNotAlreadyThere (newListener);
  24764. }
  24765. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  24766. {
  24767. const ScopedLock sl (listenerLock);
  24768. listeners.removeValue (listenerToRemove);
  24769. }
  24770. void AudioProcessor::setPlayConfigDetails (const int numIns,
  24771. const int numOuts,
  24772. const double sampleRate_,
  24773. const int blockSize_) throw()
  24774. {
  24775. numInputChannels = numIns;
  24776. numOutputChannels = numOuts;
  24777. sampleRate = sampleRate_;
  24778. blockSize = blockSize_;
  24779. }
  24780. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  24781. {
  24782. nonRealtime = nonRealtime_;
  24783. }
  24784. void AudioProcessor::setLatencySamples (const int newLatency)
  24785. {
  24786. if (latencySamples != newLatency)
  24787. {
  24788. latencySamples = newLatency;
  24789. updateHostDisplay();
  24790. }
  24791. }
  24792. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  24793. const float newValue)
  24794. {
  24795. setParameter (parameterIndex, newValue);
  24796. sendParamChangeMessageToListeners (parameterIndex, newValue);
  24797. }
  24798. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  24799. {
  24800. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  24801. for (int i = listeners.size(); --i >= 0;)
  24802. {
  24803. listenerLock.enter();
  24804. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24805. listenerLock.exit();
  24806. if (l != 0)
  24807. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  24808. }
  24809. }
  24810. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  24811. {
  24812. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  24813. #ifdef JUCE_DEBUG
  24814. // This means you've called beginParameterChangeGesture twice in succession without a matching
  24815. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  24816. jassert (! changingParams [parameterIndex]);
  24817. changingParams.setBit (parameterIndex);
  24818. #endif
  24819. for (int i = listeners.size(); --i >= 0;)
  24820. {
  24821. listenerLock.enter();
  24822. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24823. listenerLock.exit();
  24824. if (l != 0)
  24825. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  24826. }
  24827. }
  24828. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  24829. {
  24830. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  24831. #ifdef JUCE_DEBUG
  24832. // This means you've called endParameterChangeGesture without having previously called
  24833. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  24834. // calls matched correctly.
  24835. jassert (changingParams [parameterIndex]);
  24836. changingParams.clearBit (parameterIndex);
  24837. #endif
  24838. for (int i = listeners.size(); --i >= 0;)
  24839. {
  24840. listenerLock.enter();
  24841. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24842. listenerLock.exit();
  24843. if (l != 0)
  24844. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  24845. }
  24846. }
  24847. void AudioProcessor::updateHostDisplay()
  24848. {
  24849. for (int i = listeners.size(); --i >= 0;)
  24850. {
  24851. listenerLock.enter();
  24852. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24853. listenerLock.exit();
  24854. if (l != 0)
  24855. l->audioProcessorChanged (this);
  24856. }
  24857. }
  24858. bool AudioProcessor::isParameterAutomatable (int /*index*/) const
  24859. {
  24860. return true;
  24861. }
  24862. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  24863. {
  24864. const ScopedLock sl (callbackLock);
  24865. suspended = shouldBeSuspended;
  24866. }
  24867. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  24868. {
  24869. const ScopedLock sl (callbackLock);
  24870. jassert (activeEditor == editor);
  24871. if (activeEditor == editor)
  24872. activeEditor = 0;
  24873. }
  24874. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  24875. {
  24876. if (activeEditor != 0)
  24877. return activeEditor;
  24878. AudioProcessorEditor* const ed = createEditor();
  24879. if (ed != 0)
  24880. {
  24881. // you must give your editor comp a size before returning it..
  24882. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  24883. const ScopedLock sl (callbackLock);
  24884. activeEditor = ed;
  24885. }
  24886. return ed;
  24887. }
  24888. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  24889. {
  24890. getStateInformation (destData);
  24891. }
  24892. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  24893. {
  24894. setStateInformation (data, sizeInBytes);
  24895. }
  24896. // magic number to identify memory blocks that we've stored as XML
  24897. const uint32 magicXmlNumber = 0x21324356;
  24898. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  24899. JUCE_NAMESPACE::MemoryBlock& destData)
  24900. {
  24901. const String xmlString (xml.createDocument (String::empty, true, false));
  24902. const int stringLength = xmlString.length();
  24903. destData.setSize (stringLength + 10);
  24904. char* const d = (char*) destData.getData();
  24905. *(uint32*) d = swapIfBigEndian ((const uint32) magicXmlNumber);
  24906. *(uint32*) (d + 4) = swapIfBigEndian ((const uint32) stringLength);
  24907. xmlString.copyToBuffer (d + 8, stringLength);
  24908. }
  24909. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  24910. const int sizeInBytes)
  24911. {
  24912. if (sizeInBytes > 8
  24913. && littleEndianInt ((const char*) data) == magicXmlNumber)
  24914. {
  24915. const uint32 stringLength = littleEndianInt (((const char*) data) + 4);
  24916. if (stringLength > 0)
  24917. {
  24918. XmlDocument doc (String (((const char*) data) + 8,
  24919. jmin ((sizeInBytes - 8), stringLength)));
  24920. return doc.getDocumentElement();
  24921. }
  24922. }
  24923. return 0;
  24924. }
  24925. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  24926. {
  24927. }
  24928. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  24929. {
  24930. }
  24931. END_JUCE_NAMESPACE
  24932. /********* End of inlined file: juce_AudioProcessor.cpp *********/
  24933. /********* Start of inlined file: juce_AudioProcessorEditor.cpp *********/
  24934. BEGIN_JUCE_NAMESPACE
  24935. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  24936. : owner (owner_)
  24937. {
  24938. // the filter must be valid..
  24939. jassert (owner != 0);
  24940. }
  24941. AudioProcessorEditor::~AudioProcessorEditor()
  24942. {
  24943. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  24944. // filter for some reason..
  24945. jassert (owner->getActiveEditor() != this);
  24946. }
  24947. END_JUCE_NAMESPACE
  24948. /********* End of inlined file: juce_AudioProcessorEditor.cpp *********/
  24949. /********* Start of inlined file: juce_AudioProcessorGraph.cpp *********/
  24950. BEGIN_JUCE_NAMESPACE
  24951. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  24952. AudioProcessorGraph::Node::Node (const uint32 id_,
  24953. AudioProcessor* const processor_) throw()
  24954. : id (id_),
  24955. processor (processor_),
  24956. isPrepared (false)
  24957. {
  24958. jassert (processor_ != 0);
  24959. }
  24960. AudioProcessorGraph::Node::~Node()
  24961. {
  24962. delete processor;
  24963. }
  24964. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  24965. AudioProcessorGraph* const graph)
  24966. {
  24967. if (! isPrepared)
  24968. {
  24969. isPrepared = true;
  24970. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  24971. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  24972. if (ioProc != 0)
  24973. ioProc->setParentGraph (graph);
  24974. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  24975. processor->getNumOutputChannels(),
  24976. sampleRate, blockSize);
  24977. processor->prepareToPlay (sampleRate, blockSize);
  24978. }
  24979. }
  24980. void AudioProcessorGraph::Node::unprepare()
  24981. {
  24982. if (isPrepared)
  24983. {
  24984. isPrepared = false;
  24985. processor->releaseResources();
  24986. }
  24987. }
  24988. AudioProcessorGraph::AudioProcessorGraph()
  24989. : lastNodeId (0),
  24990. renderingBuffers (1, 1),
  24991. currentAudioOutputBuffer (1, 1)
  24992. {
  24993. }
  24994. AudioProcessorGraph::~AudioProcessorGraph()
  24995. {
  24996. clearRenderingSequence();
  24997. clear();
  24998. }
  24999. const String AudioProcessorGraph::getName() const
  25000. {
  25001. return "Audio Graph";
  25002. }
  25003. void AudioProcessorGraph::clear()
  25004. {
  25005. nodes.clear();
  25006. connections.clear();
  25007. triggerAsyncUpdate();
  25008. }
  25009. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const throw()
  25010. {
  25011. for (int i = nodes.size(); --i >= 0;)
  25012. if (nodes.getUnchecked(i)->id == nodeId)
  25013. return nodes.getUnchecked(i);
  25014. return 0;
  25015. }
  25016. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  25017. uint32 nodeId)
  25018. {
  25019. if (newProcessor == 0)
  25020. {
  25021. jassertfalse
  25022. return 0;
  25023. }
  25024. if (nodeId == 0)
  25025. {
  25026. nodeId = ++lastNodeId;
  25027. }
  25028. else
  25029. {
  25030. // you can't add a node with an id that already exists in the graph..
  25031. jassert (getNodeForId (nodeId) == 0);
  25032. removeNode (nodeId);
  25033. }
  25034. lastNodeId = nodeId;
  25035. Node* const n = new Node (nodeId, newProcessor);
  25036. nodes.add (n);
  25037. triggerAsyncUpdate();
  25038. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  25039. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  25040. if (ioProc != 0)
  25041. ioProc->setParentGraph (this);
  25042. return n;
  25043. }
  25044. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  25045. {
  25046. disconnectNode (nodeId);
  25047. for (int i = nodes.size(); --i >= 0;)
  25048. {
  25049. if (nodes.getUnchecked(i)->id == nodeId)
  25050. {
  25051. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  25052. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  25053. if (ioProc != 0)
  25054. ioProc->setParentGraph (0);
  25055. nodes.remove (i);
  25056. triggerAsyncUpdate();
  25057. return true;
  25058. }
  25059. }
  25060. return false;
  25061. }
  25062. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  25063. const int sourceChannelIndex,
  25064. const uint32 destNodeId,
  25065. const int destChannelIndex) const throw()
  25066. {
  25067. for (int i = connections.size(); --i >= 0;)
  25068. {
  25069. const Connection* const c = connections.getUnchecked(i);
  25070. if (c->sourceNodeId == sourceNodeId
  25071. && c->destNodeId == destNodeId
  25072. && c->sourceChannelIndex == sourceChannelIndex
  25073. && c->destChannelIndex == destChannelIndex)
  25074. {
  25075. return c;
  25076. }
  25077. }
  25078. return 0;
  25079. }
  25080. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  25081. const uint32 possibleDestNodeId) const throw()
  25082. {
  25083. for (int i = connections.size(); --i >= 0;)
  25084. {
  25085. const Connection* const c = connections.getUnchecked(i);
  25086. if (c->sourceNodeId == possibleSourceNodeId
  25087. && c->destNodeId == possibleDestNodeId)
  25088. {
  25089. return true;
  25090. }
  25091. }
  25092. return false;
  25093. }
  25094. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  25095. const int sourceChannelIndex,
  25096. const uint32 destNodeId,
  25097. const int destChannelIndex) const throw()
  25098. {
  25099. if (sourceChannelIndex < 0
  25100. || destChannelIndex < 0
  25101. || sourceNodeId == destNodeId
  25102. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  25103. return false;
  25104. const Node* const source = getNodeForId (sourceNodeId);
  25105. if (source == 0
  25106. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  25107. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  25108. return false;
  25109. const Node* const dest = getNodeForId (destNodeId);
  25110. if (dest == 0
  25111. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  25112. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  25113. return false;
  25114. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  25115. destNodeId, destChannelIndex) == 0;
  25116. }
  25117. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  25118. const int sourceChannelIndex,
  25119. const uint32 destNodeId,
  25120. const int destChannelIndex)
  25121. {
  25122. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  25123. return false;
  25124. Connection* const c = new Connection();
  25125. c->sourceNodeId = sourceNodeId;
  25126. c->sourceChannelIndex = sourceChannelIndex;
  25127. c->destNodeId = destNodeId;
  25128. c->destChannelIndex = destChannelIndex;
  25129. connections.add (c);
  25130. triggerAsyncUpdate();
  25131. return true;
  25132. }
  25133. void AudioProcessorGraph::removeConnection (const int index)
  25134. {
  25135. connections.remove (index);
  25136. triggerAsyncUpdate();
  25137. }
  25138. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  25139. const uint32 destNodeId, const int destChannelIndex)
  25140. {
  25141. bool doneAnything = false;
  25142. for (int i = connections.size(); --i >= 0;)
  25143. {
  25144. const Connection* const c = connections.getUnchecked(i);
  25145. if (c->sourceNodeId == sourceNodeId
  25146. && c->destNodeId == destNodeId
  25147. && c->sourceChannelIndex == sourceChannelIndex
  25148. && c->destChannelIndex == destChannelIndex)
  25149. {
  25150. removeConnection (i);
  25151. doneAnything = true;
  25152. triggerAsyncUpdate();
  25153. }
  25154. }
  25155. return doneAnything;
  25156. }
  25157. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  25158. {
  25159. bool doneAnything = false;
  25160. for (int i = connections.size(); --i >= 0;)
  25161. {
  25162. const Connection* const c = connections.getUnchecked(i);
  25163. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  25164. {
  25165. removeConnection (i);
  25166. doneAnything = true;
  25167. triggerAsyncUpdate();
  25168. }
  25169. }
  25170. return doneAnything;
  25171. }
  25172. bool AudioProcessorGraph::removeIllegalConnections()
  25173. {
  25174. bool doneAnything = false;
  25175. for (int i = connections.size(); --i >= 0;)
  25176. {
  25177. const Connection* const c = connections.getUnchecked(i);
  25178. const Node* const source = getNodeForId (c->sourceNodeId);
  25179. const Node* const dest = getNodeForId (c->destNodeId);
  25180. if (source == 0 || dest == 0
  25181. || (c->sourceChannelIndex != midiChannelIndex
  25182. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  25183. || (c->sourceChannelIndex == midiChannelIndex
  25184. && ! source->processor->producesMidi())
  25185. || (c->destChannelIndex != midiChannelIndex
  25186. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  25187. || (c->destChannelIndex == midiChannelIndex
  25188. && ! dest->processor->acceptsMidi()))
  25189. {
  25190. removeConnection (i);
  25191. doneAnything = true;
  25192. triggerAsyncUpdate();
  25193. }
  25194. }
  25195. return doneAnything;
  25196. }
  25197. namespace GraphRenderingOps
  25198. {
  25199. class AudioGraphRenderingOp
  25200. {
  25201. public:
  25202. AudioGraphRenderingOp() throw() {}
  25203. virtual ~AudioGraphRenderingOp() throw() {}
  25204. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  25205. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  25206. const int numSamples) throw() = 0;
  25207. juce_UseDebuggingNewOperator
  25208. };
  25209. class ClearChannelOp : public AudioGraphRenderingOp
  25210. {
  25211. public:
  25212. ClearChannelOp (const int channelNum_) throw()
  25213. : channelNum (channelNum_)
  25214. {}
  25215. ~ClearChannelOp() throw() {}
  25216. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  25217. {
  25218. sharedBufferChans.clear (channelNum, 0, numSamples);
  25219. }
  25220. private:
  25221. const int channelNum;
  25222. ClearChannelOp (const ClearChannelOp&);
  25223. const ClearChannelOp& operator= (const ClearChannelOp&);
  25224. };
  25225. class CopyChannelOp : public AudioGraphRenderingOp
  25226. {
  25227. public:
  25228. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  25229. : srcChannelNum (srcChannelNum_),
  25230. dstChannelNum (dstChannelNum_)
  25231. {}
  25232. ~CopyChannelOp() throw() {}
  25233. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  25234. {
  25235. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  25236. }
  25237. private:
  25238. const int srcChannelNum, dstChannelNum;
  25239. CopyChannelOp (const CopyChannelOp&);
  25240. const CopyChannelOp& operator= (const CopyChannelOp&);
  25241. };
  25242. class AddChannelOp : public AudioGraphRenderingOp
  25243. {
  25244. public:
  25245. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  25246. : srcChannelNum (srcChannelNum_),
  25247. dstChannelNum (dstChannelNum_)
  25248. {}
  25249. ~AddChannelOp() throw() {}
  25250. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  25251. {
  25252. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  25253. }
  25254. private:
  25255. const int srcChannelNum, dstChannelNum;
  25256. AddChannelOp (const AddChannelOp&);
  25257. const AddChannelOp& operator= (const AddChannelOp&);
  25258. };
  25259. class ClearMidiBufferOp : public AudioGraphRenderingOp
  25260. {
  25261. public:
  25262. ClearMidiBufferOp (const int bufferNum_) throw()
  25263. : bufferNum (bufferNum_)
  25264. {}
  25265. ~ClearMidiBufferOp() throw() {}
  25266. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  25267. {
  25268. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  25269. }
  25270. private:
  25271. const int bufferNum;
  25272. ClearMidiBufferOp (const ClearMidiBufferOp&);
  25273. const ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  25274. };
  25275. class CopyMidiBufferOp : public AudioGraphRenderingOp
  25276. {
  25277. public:
  25278. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  25279. : srcBufferNum (srcBufferNum_),
  25280. dstBufferNum (dstBufferNum_)
  25281. {}
  25282. ~CopyMidiBufferOp() throw() {}
  25283. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  25284. {
  25285. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  25286. }
  25287. private:
  25288. const int srcBufferNum, dstBufferNum;
  25289. CopyMidiBufferOp (const CopyMidiBufferOp&);
  25290. const CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  25291. };
  25292. class AddMidiBufferOp : public AudioGraphRenderingOp
  25293. {
  25294. public:
  25295. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  25296. : srcBufferNum (srcBufferNum_),
  25297. dstBufferNum (dstBufferNum_)
  25298. {}
  25299. ~AddMidiBufferOp() throw() {}
  25300. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  25301. {
  25302. sharedMidiBuffers.getUnchecked (dstBufferNum)
  25303. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  25304. }
  25305. private:
  25306. const int srcBufferNum, dstBufferNum;
  25307. AddMidiBufferOp (const AddMidiBufferOp&);
  25308. const AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  25309. };
  25310. class ProcessBufferOp : public AudioGraphRenderingOp
  25311. {
  25312. public:
  25313. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  25314. const Array <int>& audioChannelsToUse_,
  25315. const int totalChans_,
  25316. const int midiBufferToUse_) throw()
  25317. : node (node_),
  25318. processor (node_->processor),
  25319. audioChannelsToUse (audioChannelsToUse_),
  25320. totalChans (totalChans_),
  25321. midiBufferToUse (midiBufferToUse_)
  25322. {
  25323. channels = (float**) juce_calloc (sizeof (float*) * totalChans_);
  25324. }
  25325. ~ProcessBufferOp() throw()
  25326. {
  25327. juce_free (channels);
  25328. }
  25329. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  25330. {
  25331. for (int i = totalChans; --i >= 0;)
  25332. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  25333. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  25334. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  25335. }
  25336. const AudioProcessorGraph::Node::Ptr node;
  25337. AudioProcessor* const processor;
  25338. private:
  25339. Array <int> audioChannelsToUse;
  25340. float** channels;
  25341. int totalChans;
  25342. int midiBufferToUse;
  25343. ProcessBufferOp (const ProcessBufferOp&);
  25344. const ProcessBufferOp& operator= (const ProcessBufferOp&);
  25345. };
  25346. /** Used to calculate the correct sequence of rendering ops needed, based on
  25347. the best re-use of shared buffers at each stage.
  25348. */
  25349. class RenderingOpSequenceCalculator
  25350. {
  25351. public:
  25352. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  25353. const VoidArray& orderedNodes_,
  25354. VoidArray& renderingOps)
  25355. : graph (graph_),
  25356. orderedNodes (orderedNodes_)
  25357. {
  25358. nodeIds.add (-2); // first buffer is read-only zeros
  25359. channels.add (0);
  25360. midiNodeIds.add (-2);
  25361. for (int i = 0; i < orderedNodes.size(); ++i)
  25362. {
  25363. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  25364. renderingOps, i);
  25365. markAnyUnusedBuffersAsFree (i);
  25366. }
  25367. }
  25368. int getNumBuffersNeeded() const throw() { return nodeIds.size(); }
  25369. int getNumMidiBuffersNeeded() const throw() { return midiNodeIds.size(); }
  25370. juce_UseDebuggingNewOperator
  25371. private:
  25372. AudioProcessorGraph& graph;
  25373. const VoidArray& orderedNodes;
  25374. Array <int> nodeIds, channels, midiNodeIds;
  25375. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  25376. VoidArray& renderingOps,
  25377. const int ourRenderingIndex)
  25378. {
  25379. const int numIns = node->processor->getNumInputChannels();
  25380. const int numOuts = node->processor->getNumOutputChannels();
  25381. const int totalChans = jmax (numIns, numOuts);
  25382. Array <int> audioChannelsToUse;
  25383. int midiBufferToUse = -1;
  25384. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  25385. {
  25386. // get a list of all the inputs to this node
  25387. Array <int> sourceNodes, sourceOutputChans;
  25388. for (int i = graph.getNumConnections(); --i >= 0;)
  25389. {
  25390. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  25391. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  25392. {
  25393. sourceNodes.add (c->sourceNodeId);
  25394. sourceOutputChans.add (c->sourceChannelIndex);
  25395. }
  25396. }
  25397. int bufIndex = -1;
  25398. if (sourceNodes.size() == 0)
  25399. {
  25400. // unconnected input channel
  25401. if (inputChan >= numOuts)
  25402. {
  25403. bufIndex = getReadOnlyEmptyBuffer();
  25404. jassert (bufIndex >= 0);
  25405. }
  25406. else
  25407. {
  25408. bufIndex = getFreeBuffer (false);
  25409. renderingOps.add (new ClearChannelOp (bufIndex));
  25410. }
  25411. }
  25412. else if (sourceNodes.size() == 1)
  25413. {
  25414. // channel with a straightforward single input..
  25415. const int srcNode = sourceNodes.getUnchecked(0);
  25416. const int srcChan = sourceOutputChans.getUnchecked(0);
  25417. bufIndex = getBufferContaining (srcNode, srcChan);
  25418. if (bufIndex < 0)
  25419. {
  25420. // if not found, this is probably a feedback loop
  25421. bufIndex = getReadOnlyEmptyBuffer();
  25422. jassert (bufIndex >= 0);
  25423. }
  25424. if (inputChan < numOuts
  25425. && isBufferNeededLater (ourRenderingIndex,
  25426. inputChan,
  25427. srcNode, srcChan))
  25428. {
  25429. // can't mess up this channel because it's needed later by another node, so we
  25430. // need to use a copy of it..
  25431. const int newFreeBuffer = getFreeBuffer (false);
  25432. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  25433. bufIndex = newFreeBuffer;
  25434. }
  25435. }
  25436. else
  25437. {
  25438. // channel with a mix of several inputs..
  25439. // try to find a re-usable channel from our inputs..
  25440. int reusableInputIndex = -1;
  25441. for (int i = 0; i < sourceNodes.size(); ++i)
  25442. {
  25443. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  25444. sourceOutputChans.getUnchecked(i));
  25445. if (sourceBufIndex >= 0
  25446. && ! isBufferNeededLater (ourRenderingIndex,
  25447. inputChan,
  25448. sourceNodes.getUnchecked(i),
  25449. sourceOutputChans.getUnchecked(i)))
  25450. {
  25451. // we've found one of our input chans that can be re-used..
  25452. reusableInputIndex = i;
  25453. bufIndex = sourceBufIndex;
  25454. break;
  25455. }
  25456. }
  25457. if (reusableInputIndex < 0)
  25458. {
  25459. // can't re-use any of our input chans, so get a new one and copy everything into it..
  25460. bufIndex = getFreeBuffer (false);
  25461. jassert (bufIndex != 0);
  25462. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  25463. sourceOutputChans.getUnchecked (0));
  25464. if (srcIndex < 0)
  25465. {
  25466. // if not found, this is probably a feedback loop
  25467. renderingOps.add (new ClearChannelOp (bufIndex));
  25468. }
  25469. else
  25470. {
  25471. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  25472. }
  25473. reusableInputIndex = 0;
  25474. }
  25475. for (int j = 0; j < sourceNodes.size(); ++j)
  25476. {
  25477. if (j != reusableInputIndex)
  25478. {
  25479. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  25480. sourceOutputChans.getUnchecked(j));
  25481. if (srcIndex >= 0)
  25482. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  25483. }
  25484. }
  25485. }
  25486. jassert (bufIndex >= 0);
  25487. audioChannelsToUse.add (bufIndex);
  25488. if (inputChan < numOuts)
  25489. markBufferAsContaining (bufIndex, node->id, inputChan);
  25490. }
  25491. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  25492. {
  25493. const int bufIndex = getFreeBuffer (false);
  25494. jassert (bufIndex != 0);
  25495. audioChannelsToUse.add (bufIndex);
  25496. markBufferAsContaining (bufIndex, node->id, outputChan);
  25497. }
  25498. // Now the same thing for midi..
  25499. Array <int> midiSourceNodes;
  25500. for (int i = graph.getNumConnections(); --i >= 0;)
  25501. {
  25502. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  25503. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  25504. midiSourceNodes.add (c->sourceNodeId);
  25505. }
  25506. if (midiSourceNodes.size() == 0)
  25507. {
  25508. // No midi inputs..
  25509. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  25510. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  25511. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  25512. }
  25513. else if (midiSourceNodes.size() == 1)
  25514. {
  25515. // One midi input..
  25516. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  25517. AudioProcessorGraph::midiChannelIndex);
  25518. if (midiBufferToUse >= 0)
  25519. {
  25520. if (isBufferNeededLater (ourRenderingIndex,
  25521. AudioProcessorGraph::midiChannelIndex,
  25522. midiSourceNodes.getUnchecked(0),
  25523. AudioProcessorGraph::midiChannelIndex))
  25524. {
  25525. // can't mess up this channel because it's needed later by another node, so we
  25526. // need to use a copy of it..
  25527. const int newFreeBuffer = getFreeBuffer (true);
  25528. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  25529. midiBufferToUse = newFreeBuffer;
  25530. }
  25531. }
  25532. else
  25533. {
  25534. // probably a feedback loop, so just use an empty one..
  25535. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  25536. }
  25537. }
  25538. else
  25539. {
  25540. // More than one midi input being mixed..
  25541. int reusableInputIndex = -1;
  25542. for (int i = 0; i < midiSourceNodes.size(); ++i)
  25543. {
  25544. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  25545. AudioProcessorGraph::midiChannelIndex);
  25546. if (sourceBufIndex >= 0
  25547. && ! isBufferNeededLater (ourRenderingIndex,
  25548. AudioProcessorGraph::midiChannelIndex,
  25549. midiSourceNodes.getUnchecked(i),
  25550. AudioProcessorGraph::midiChannelIndex))
  25551. {
  25552. // we've found one of our input buffers that can be re-used..
  25553. reusableInputIndex = i;
  25554. midiBufferToUse = sourceBufIndex;
  25555. break;
  25556. }
  25557. }
  25558. if (reusableInputIndex < 0)
  25559. {
  25560. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  25561. midiBufferToUse = getFreeBuffer (true);
  25562. jassert (midiBufferToUse >= 0);
  25563. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  25564. AudioProcessorGraph::midiChannelIndex);
  25565. if (srcIndex >= 0)
  25566. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  25567. else
  25568. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  25569. reusableInputIndex = 0;
  25570. }
  25571. for (int j = 0; j < midiSourceNodes.size(); ++j)
  25572. {
  25573. if (j != reusableInputIndex)
  25574. {
  25575. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  25576. AudioProcessorGraph::midiChannelIndex);
  25577. if (srcIndex >= 0)
  25578. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  25579. }
  25580. }
  25581. }
  25582. if (node->processor->producesMidi())
  25583. markBufferAsContaining (midiBufferToUse, node->id,
  25584. AudioProcessorGraph::midiChannelIndex);
  25585. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  25586. totalChans, midiBufferToUse));
  25587. }
  25588. int getFreeBuffer (const bool forMidi)
  25589. {
  25590. if (forMidi)
  25591. {
  25592. for (int i = 1; i < midiNodeIds.size(); ++i)
  25593. if (midiNodeIds.getUnchecked(i) < 0)
  25594. return i;
  25595. midiNodeIds.add (-1);
  25596. return midiNodeIds.size() - 1;
  25597. }
  25598. else
  25599. {
  25600. for (int i = 1; i < nodeIds.size(); ++i)
  25601. if (nodeIds.getUnchecked(i) < 0)
  25602. return i;
  25603. nodeIds.add (-1);
  25604. channels.add (0);
  25605. return nodeIds.size() - 1;
  25606. }
  25607. }
  25608. int getReadOnlyEmptyBuffer() const throw()
  25609. {
  25610. return 0;
  25611. }
  25612. int getBufferContaining (const int nodeId, const int outputChannel) const throw()
  25613. {
  25614. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  25615. {
  25616. for (int i = midiNodeIds.size(); --i >= 0;)
  25617. if (midiNodeIds.getUnchecked(i) == nodeId)
  25618. return i;
  25619. }
  25620. else
  25621. {
  25622. for (int i = nodeIds.size(); --i >= 0;)
  25623. if (nodeIds.getUnchecked(i) == nodeId
  25624. && channels.getUnchecked(i) == outputChannel)
  25625. return i;
  25626. }
  25627. return -1;
  25628. }
  25629. void markAnyUnusedBuffersAsFree (const int stepIndex)
  25630. {
  25631. int i;
  25632. for (i = 0; i < nodeIds.size(); ++i)
  25633. {
  25634. if (nodeIds.getUnchecked(i) >= 0
  25635. && ! isBufferNeededLater (stepIndex, -1,
  25636. nodeIds.getUnchecked(i),
  25637. channels.getUnchecked(i)))
  25638. {
  25639. nodeIds.set (i, -1);
  25640. }
  25641. }
  25642. for (i = 0; i < midiNodeIds.size(); ++i)
  25643. {
  25644. if (midiNodeIds.getUnchecked(i) >= 0
  25645. && ! isBufferNeededLater (stepIndex, -1,
  25646. midiNodeIds.getUnchecked(i),
  25647. AudioProcessorGraph::midiChannelIndex))
  25648. {
  25649. midiNodeIds.set (i, -1);
  25650. }
  25651. }
  25652. }
  25653. bool isBufferNeededLater (int stepIndexToSearchFrom,
  25654. int inputChannelOfIndexToIgnore,
  25655. const int nodeId,
  25656. const int outputChanIndex) const throw()
  25657. {
  25658. while (stepIndexToSearchFrom < orderedNodes.size())
  25659. {
  25660. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  25661. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  25662. {
  25663. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  25664. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  25665. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  25666. return true;
  25667. }
  25668. else
  25669. {
  25670. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  25671. if (i != inputChannelOfIndexToIgnore
  25672. && graph.getConnectionBetween (nodeId, outputChanIndex,
  25673. node->id, i) != 0)
  25674. return true;
  25675. }
  25676. inputChannelOfIndexToIgnore = -1;
  25677. ++stepIndexToSearchFrom;
  25678. }
  25679. return false;
  25680. }
  25681. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  25682. {
  25683. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  25684. {
  25685. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  25686. midiNodeIds.set (bufferNum, nodeId);
  25687. }
  25688. else
  25689. {
  25690. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  25691. nodeIds.set (bufferNum, nodeId);
  25692. channels.set (bufferNum, outputIndex);
  25693. }
  25694. }
  25695. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  25696. const RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  25697. };
  25698. }
  25699. void AudioProcessorGraph::clearRenderingSequence()
  25700. {
  25701. const ScopedLock sl (renderLock);
  25702. for (int i = renderingOps.size(); --i >= 0;)
  25703. {
  25704. GraphRenderingOps::AudioGraphRenderingOp* const r
  25705. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  25706. renderingOps.remove (i);
  25707. delete r;
  25708. }
  25709. }
  25710. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  25711. const uint32 possibleDestinationId,
  25712. const int recursionCheck) const throw()
  25713. {
  25714. if (recursionCheck > 0)
  25715. {
  25716. for (int i = connections.size(); --i >= 0;)
  25717. {
  25718. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  25719. if (c->destNodeId == possibleDestinationId
  25720. && (c->sourceNodeId == possibleInputId
  25721. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  25722. return true;
  25723. }
  25724. }
  25725. return false;
  25726. }
  25727. void AudioProcessorGraph::buildRenderingSequence()
  25728. {
  25729. VoidArray newRenderingOps;
  25730. int numRenderingBuffersNeeded = 2;
  25731. int numMidiBuffersNeeded = 1;
  25732. {
  25733. MessageManagerLock mml;
  25734. VoidArray orderedNodes;
  25735. int i;
  25736. for (i = 0; i < nodes.size(); ++i)
  25737. {
  25738. Node* const node = nodes.getUnchecked(i);
  25739. node->prepare (getSampleRate(), getBlockSize(), this);
  25740. int j = 0;
  25741. for (; j < orderedNodes.size(); ++j)
  25742. if (isAnInputTo (node->id,
  25743. ((Node*) orderedNodes.getUnchecked (j))->id,
  25744. nodes.size() + 1))
  25745. break;
  25746. orderedNodes.insert (j, node);
  25747. }
  25748. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  25749. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  25750. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  25751. }
  25752. VoidArray oldRenderingOps (renderingOps);
  25753. {
  25754. // swap over to the new rendering sequence..
  25755. const ScopedLock sl (renderLock);
  25756. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  25757. renderingBuffers.clear();
  25758. for (int i = midiBuffers.size(); --i >= 0;)
  25759. midiBuffers.getUnchecked(i)->clear();
  25760. while (midiBuffers.size() < numMidiBuffersNeeded)
  25761. midiBuffers.add (new MidiBuffer());
  25762. renderingOps = newRenderingOps;
  25763. }
  25764. for (int i = oldRenderingOps.size(); --i >= 0;)
  25765. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  25766. }
  25767. void AudioProcessorGraph::handleAsyncUpdate()
  25768. {
  25769. buildRenderingSequence();
  25770. }
  25771. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  25772. {
  25773. currentAudioInputBuffer = 0;
  25774. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  25775. currentMidiInputBuffer = 0;
  25776. currentMidiOutputBuffer.clear();
  25777. clearRenderingSequence();
  25778. buildRenderingSequence();
  25779. }
  25780. void AudioProcessorGraph::releaseResources()
  25781. {
  25782. for (int i = 0; i < nodes.size(); ++i)
  25783. nodes.getUnchecked(i)->unprepare();
  25784. renderingBuffers.setSize (1, 1);
  25785. midiBuffers.clear();
  25786. currentAudioInputBuffer = 0;
  25787. currentAudioOutputBuffer.setSize (1, 1);
  25788. currentMidiInputBuffer = 0;
  25789. currentMidiOutputBuffer.clear();
  25790. }
  25791. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  25792. {
  25793. const int numSamples = buffer.getNumSamples();
  25794. const ScopedLock sl (renderLock);
  25795. currentAudioInputBuffer = &buffer;
  25796. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  25797. currentAudioOutputBuffer.clear();
  25798. currentMidiInputBuffer = &midiMessages;
  25799. currentMidiOutputBuffer.clear();
  25800. int i;
  25801. for (i = 0; i < renderingOps.size(); ++i)
  25802. {
  25803. GraphRenderingOps::AudioGraphRenderingOp* const op
  25804. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  25805. op->perform (renderingBuffers, midiBuffers, numSamples);
  25806. }
  25807. for (i = 0; i < buffer.getNumChannels(); ++i)
  25808. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  25809. }
  25810. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  25811. {
  25812. return "Input " + String (channelIndex + 1);
  25813. }
  25814. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  25815. {
  25816. return "Output " + String (channelIndex + 1);
  25817. }
  25818. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  25819. {
  25820. return true;
  25821. }
  25822. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  25823. {
  25824. return true;
  25825. }
  25826. bool AudioProcessorGraph::acceptsMidi() const
  25827. {
  25828. return true;
  25829. }
  25830. bool AudioProcessorGraph::producesMidi() const
  25831. {
  25832. return true;
  25833. }
  25834. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  25835. {
  25836. }
  25837. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  25838. {
  25839. }
  25840. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  25841. : type (type_),
  25842. graph (0)
  25843. {
  25844. }
  25845. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  25846. {
  25847. }
  25848. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  25849. {
  25850. switch (type)
  25851. {
  25852. case audioOutputNode:
  25853. return "Audio Output";
  25854. case audioInputNode:
  25855. return "Audio Input";
  25856. case midiOutputNode:
  25857. return "Midi Output";
  25858. case midiInputNode:
  25859. return "Midi Input";
  25860. default:
  25861. break;
  25862. }
  25863. return String::empty;
  25864. }
  25865. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  25866. {
  25867. d.name = getName();
  25868. d.uid = d.name.hashCode();
  25869. d.category = "I/O devices";
  25870. d.pluginFormatName = "Internal";
  25871. d.manufacturerName = "Raw Material Software";
  25872. d.version = "1.0";
  25873. d.isInstrument = false;
  25874. d.numInputChannels = getNumInputChannels();
  25875. if (type == audioOutputNode && graph != 0)
  25876. d.numInputChannels = graph->getNumInputChannels();
  25877. d.numOutputChannels = getNumOutputChannels();
  25878. if (type == audioInputNode && graph != 0)
  25879. d.numOutputChannels = graph->getNumOutputChannels();
  25880. }
  25881. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  25882. {
  25883. jassert (graph != 0);
  25884. }
  25885. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  25886. {
  25887. }
  25888. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  25889. MidiBuffer& midiMessages)
  25890. {
  25891. jassert (graph != 0);
  25892. switch (type)
  25893. {
  25894. case audioOutputNode:
  25895. {
  25896. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  25897. buffer.getNumChannels()); --i >= 0;)
  25898. {
  25899. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  25900. }
  25901. break;
  25902. }
  25903. case audioInputNode:
  25904. {
  25905. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  25906. buffer.getNumChannels()); --i >= 0;)
  25907. {
  25908. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  25909. }
  25910. break;
  25911. }
  25912. case midiOutputNode:
  25913. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  25914. break;
  25915. case midiInputNode:
  25916. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  25917. break;
  25918. default:
  25919. break;
  25920. }
  25921. }
  25922. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  25923. {
  25924. return type == midiOutputNode;
  25925. }
  25926. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  25927. {
  25928. return type == midiInputNode;
  25929. }
  25930. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  25931. {
  25932. switch (type)
  25933. {
  25934. case audioOutputNode:
  25935. return "Output " + String (channelIndex + 1);
  25936. case midiOutputNode:
  25937. return "Midi Output";
  25938. default:
  25939. break;
  25940. }
  25941. return String::empty;
  25942. }
  25943. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  25944. {
  25945. switch (type)
  25946. {
  25947. case audioInputNode:
  25948. return "Input " + String (channelIndex + 1);
  25949. case midiInputNode:
  25950. return "Midi Input";
  25951. default:
  25952. break;
  25953. }
  25954. return String::empty;
  25955. }
  25956. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  25957. {
  25958. return type == audioInputNode || type == audioOutputNode;
  25959. }
  25960. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  25961. {
  25962. return isInputChannelStereoPair (index);
  25963. }
  25964. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const throw()
  25965. {
  25966. return type == audioInputNode || type == midiInputNode;
  25967. }
  25968. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const throw()
  25969. {
  25970. return type == audioOutputNode || type == midiOutputNode;
  25971. }
  25972. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  25973. {
  25974. return 0;
  25975. }
  25976. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  25977. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  25978. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  25979. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  25980. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  25981. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  25982. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  25983. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  25984. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  25985. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  25986. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  25987. {
  25988. }
  25989. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  25990. {
  25991. }
  25992. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph) throw()
  25993. {
  25994. graph = newGraph;
  25995. if (graph != 0)
  25996. {
  25997. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  25998. type == audioInputNode ? graph->getNumInputChannels() : 0,
  25999. getSampleRate(),
  26000. getBlockSize());
  26001. updateHostDisplay();
  26002. }
  26003. }
  26004. END_JUCE_NAMESPACE
  26005. /********* End of inlined file: juce_AudioProcessorGraph.cpp *********/
  26006. /********* Start of inlined file: juce_AudioProcessorPlayer.cpp *********/
  26007. BEGIN_JUCE_NAMESPACE
  26008. AudioProcessorPlayer::AudioProcessorPlayer()
  26009. : processor (0),
  26010. sampleRate (0),
  26011. blockSize (0),
  26012. isPrepared (false),
  26013. numInputChans (0),
  26014. numOutputChans (0),
  26015. tempBuffer (1, 1)
  26016. {
  26017. }
  26018. AudioProcessorPlayer::~AudioProcessorPlayer()
  26019. {
  26020. setProcessor (0);
  26021. }
  26022. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  26023. {
  26024. if (processor != processorToPlay)
  26025. {
  26026. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  26027. {
  26028. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  26029. sampleRate, blockSize);
  26030. processorToPlay->prepareToPlay (sampleRate, blockSize);
  26031. }
  26032. lock.enter();
  26033. AudioProcessor* const oldOne = isPrepared ? processor : 0;
  26034. processor = processorToPlay;
  26035. isPrepared = true;
  26036. lock.exit();
  26037. if (oldOne != 0)
  26038. oldOne->releaseResources();
  26039. }
  26040. }
  26041. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  26042. int numInputChannels,
  26043. float** outputChannelData,
  26044. int numOutputChannels,
  26045. int numSamples)
  26046. {
  26047. // these should have been prepared by audioDeviceAboutToStart()...
  26048. jassert (sampleRate > 0 && blockSize > 0);
  26049. incomingMidi.clear();
  26050. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  26051. int i, totalNumChans = 0;
  26052. if (numInputChannels > numOutputChannels)
  26053. {
  26054. // if there aren't enough output channels for the number of
  26055. // inputs, we need to create some temporary extra ones (can't
  26056. // use the input data in case it gets written to)
  26057. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  26058. false, false, true);
  26059. for (i = 0; i < numOutputChannels; ++i)
  26060. {
  26061. channels[totalNumChans] = outputChannelData[i];
  26062. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  26063. ++totalNumChans;
  26064. }
  26065. for (i = numOutputChannels; i < numInputChannels; ++i)
  26066. {
  26067. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  26068. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  26069. ++totalNumChans;
  26070. }
  26071. }
  26072. else
  26073. {
  26074. for (i = 0; i < numInputChannels; ++i)
  26075. {
  26076. channels[totalNumChans] = outputChannelData[i];
  26077. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  26078. ++totalNumChans;
  26079. }
  26080. for (i = numInputChannels; i < numOutputChannels; ++i)
  26081. {
  26082. channels[totalNumChans] = outputChannelData[i];
  26083. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  26084. ++totalNumChans;
  26085. }
  26086. }
  26087. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  26088. const ScopedLock sl (lock);
  26089. if (processor != 0)
  26090. processor->processBlock (buffer, incomingMidi);
  26091. }
  26092. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  26093. {
  26094. const ScopedLock sl (lock);
  26095. sampleRate = device->getCurrentSampleRate();
  26096. blockSize = device->getCurrentBufferSizeSamples();
  26097. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  26098. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  26099. messageCollector.reset (sampleRate);
  26100. zeromem (channels, sizeof (channels));
  26101. if (processor != 0)
  26102. {
  26103. if (isPrepared)
  26104. processor->releaseResources();
  26105. AudioProcessor* const oldProcessor = processor;
  26106. setProcessor (0);
  26107. setProcessor (oldProcessor);
  26108. }
  26109. }
  26110. void AudioProcessorPlayer::audioDeviceStopped()
  26111. {
  26112. const ScopedLock sl (lock);
  26113. if (processor != 0 && isPrepared)
  26114. processor->releaseResources();
  26115. sampleRate = 0.0;
  26116. blockSize = 0;
  26117. isPrepared = false;
  26118. tempBuffer.setSize (1, 1);
  26119. }
  26120. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  26121. {
  26122. messageCollector.addMessageToQueue (message);
  26123. }
  26124. END_JUCE_NAMESPACE
  26125. /********* End of inlined file: juce_AudioProcessorPlayer.cpp *********/
  26126. /********* Start of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  26127. BEGIN_JUCE_NAMESPACE
  26128. class ProcessorParameterPropertyComp : public PropertyComponent,
  26129. public AudioProcessorListener,
  26130. public AsyncUpdater
  26131. {
  26132. public:
  26133. ProcessorParameterPropertyComp (const String& name,
  26134. AudioProcessor* const owner_,
  26135. const int index_)
  26136. : PropertyComponent (name),
  26137. owner (owner_),
  26138. index (index_)
  26139. {
  26140. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  26141. owner_->addListener (this);
  26142. }
  26143. ~ProcessorParameterPropertyComp()
  26144. {
  26145. owner->removeListener (this);
  26146. deleteAllChildren();
  26147. }
  26148. void refresh()
  26149. {
  26150. slider->setValue (owner->getParameter (index), false);
  26151. }
  26152. void audioProcessorChanged (AudioProcessor*) {}
  26153. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  26154. {
  26155. if (parameterIndex == index)
  26156. triggerAsyncUpdate();
  26157. }
  26158. void handleAsyncUpdate()
  26159. {
  26160. refresh();
  26161. }
  26162. juce_UseDebuggingNewOperator
  26163. private:
  26164. AudioProcessor* const owner;
  26165. const int index;
  26166. Slider* slider;
  26167. class ParamSlider : public Slider
  26168. {
  26169. public:
  26170. ParamSlider (AudioProcessor* const owner_, const int index_)
  26171. : Slider (String::empty),
  26172. owner (owner_),
  26173. index (index_)
  26174. {
  26175. setRange (0.0, 1.0, 0.0);
  26176. setSliderStyle (Slider::LinearBar);
  26177. setTextBoxIsEditable (false);
  26178. setScrollWheelEnabled (false);
  26179. }
  26180. ~ParamSlider()
  26181. {
  26182. }
  26183. void valueChanged()
  26184. {
  26185. const float newVal = (float) getValue();
  26186. if (owner->getParameter (index) != newVal)
  26187. owner->setParameter (index, newVal);
  26188. }
  26189. const String getTextFromValue (double /*value*/)
  26190. {
  26191. return owner->getParameterText (index);
  26192. }
  26193. juce_UseDebuggingNewOperator
  26194. private:
  26195. AudioProcessor* const owner;
  26196. const int index;
  26197. };
  26198. };
  26199. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner)
  26200. : AudioProcessorEditor (owner)
  26201. {
  26202. setOpaque (true);
  26203. addAndMakeVisible (panel = new PropertyPanel());
  26204. Array <PropertyComponent*> params;
  26205. const int numParams = owner->getNumParameters();
  26206. int totalHeight = 0;
  26207. for (int i = 0; i < numParams; ++i)
  26208. {
  26209. String name (owner->getParameterName (i));
  26210. if (name.trim().isEmpty())
  26211. name = "Unnamed";
  26212. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner, i);
  26213. params.add (pc);
  26214. totalHeight += pc->getPreferredHeight();
  26215. }
  26216. panel->addProperties (params);
  26217. setSize (400, jlimit (25, 400, totalHeight));
  26218. }
  26219. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  26220. {
  26221. deleteAllChildren();
  26222. }
  26223. void GenericAudioProcessorEditor::paint (Graphics& g)
  26224. {
  26225. g.fillAll (Colours::white);
  26226. }
  26227. void GenericAudioProcessorEditor::resized()
  26228. {
  26229. panel->setSize (getWidth(), getHeight());
  26230. }
  26231. END_JUCE_NAMESPACE
  26232. /********* End of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  26233. /********* Start of inlined file: juce_Sampler.cpp *********/
  26234. BEGIN_JUCE_NAMESPACE
  26235. SamplerSound::SamplerSound (const String& name_,
  26236. AudioFormatReader& source,
  26237. const BitArray& midiNotes_,
  26238. const int midiNoteForNormalPitch,
  26239. const double attackTimeSecs,
  26240. const double releaseTimeSecs,
  26241. const double maxSampleLengthSeconds)
  26242. : name (name_),
  26243. midiNotes (midiNotes_),
  26244. midiRootNote (midiNoteForNormalPitch)
  26245. {
  26246. sourceSampleRate = source.sampleRate;
  26247. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  26248. {
  26249. data = 0;
  26250. length = 0;
  26251. attackSamples = 0;
  26252. releaseSamples = 0;
  26253. }
  26254. else
  26255. {
  26256. length = jmin ((int) source.lengthInSamples,
  26257. (int) (maxSampleLengthSeconds * sourceSampleRate));
  26258. data = new AudioSampleBuffer (jmin (2, source.numChannels), length + 4);
  26259. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  26260. attackSamples = roundDoubleToInt (attackTimeSecs * sourceSampleRate);
  26261. releaseSamples = roundDoubleToInt (releaseTimeSecs * sourceSampleRate);
  26262. }
  26263. }
  26264. SamplerSound::~SamplerSound()
  26265. {
  26266. delete data;
  26267. data = 0;
  26268. }
  26269. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  26270. {
  26271. return midiNotes [midiNoteNumber];
  26272. }
  26273. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  26274. {
  26275. return true;
  26276. }
  26277. SamplerVoice::SamplerVoice()
  26278. : pitchRatio (0.0),
  26279. sourceSamplePosition (0.0),
  26280. lgain (0.0f),
  26281. rgain (0.0f),
  26282. isInAttack (false),
  26283. isInRelease (false)
  26284. {
  26285. }
  26286. SamplerVoice::~SamplerVoice()
  26287. {
  26288. }
  26289. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  26290. {
  26291. return dynamic_cast <const SamplerSound*> (sound) != 0;
  26292. }
  26293. void SamplerVoice::startNote (const int midiNoteNumber,
  26294. const float velocity,
  26295. SynthesiserSound* s,
  26296. const int /*currentPitchWheelPosition*/)
  26297. {
  26298. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  26299. jassert (sound != 0); // this object can only play SamplerSounds!
  26300. if (sound != 0)
  26301. {
  26302. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  26303. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  26304. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  26305. sourceSamplePosition = 0.0;
  26306. lgain = velocity;
  26307. rgain = velocity;
  26308. isInAttack = (sound->attackSamples > 0);
  26309. isInRelease = false;
  26310. if (isInAttack)
  26311. {
  26312. attackReleaseLevel = 0.0f;
  26313. attackDelta = (float) (pitchRatio / sound->attackSamples);
  26314. }
  26315. else
  26316. {
  26317. attackReleaseLevel = 1.0f;
  26318. attackDelta = 0.0f;
  26319. }
  26320. if (sound->releaseSamples > 0)
  26321. {
  26322. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  26323. }
  26324. else
  26325. {
  26326. releaseDelta = 0.0f;
  26327. }
  26328. }
  26329. }
  26330. void SamplerVoice::stopNote (const bool allowTailOff)
  26331. {
  26332. if (allowTailOff)
  26333. {
  26334. isInAttack = false;
  26335. isInRelease = true;
  26336. }
  26337. else
  26338. {
  26339. clearCurrentNote();
  26340. }
  26341. }
  26342. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  26343. {
  26344. }
  26345. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  26346. const int /*newValue*/)
  26347. {
  26348. }
  26349. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  26350. {
  26351. const SamplerSound* const playingSound = (SamplerSound*) (SynthesiserSound*) getCurrentlyPlayingSound();
  26352. if (playingSound != 0)
  26353. {
  26354. const float* const inL = playingSound->data->getSampleData (0, 0);
  26355. const float* const inR = playingSound->data->getNumChannels() > 1
  26356. ? playingSound->data->getSampleData (1, 0) : 0;
  26357. float* outL = outputBuffer.getSampleData (0, startSample);
  26358. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  26359. while (--numSamples >= 0)
  26360. {
  26361. const int pos = (int) sourceSamplePosition;
  26362. const float alpha = (float) (sourceSamplePosition - pos);
  26363. const float invAlpha = 1.0f - alpha;
  26364. // just using a very simple linear interpolation here..
  26365. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  26366. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  26367. : l;
  26368. l *= lgain;
  26369. r *= rgain;
  26370. if (isInAttack)
  26371. {
  26372. l *= attackReleaseLevel;
  26373. r *= attackReleaseLevel;
  26374. attackReleaseLevel += attackDelta;
  26375. if (attackReleaseLevel >= 1.0f)
  26376. {
  26377. attackReleaseLevel = 1.0f;
  26378. isInAttack = false;
  26379. }
  26380. }
  26381. else if (isInRelease)
  26382. {
  26383. l *= attackReleaseLevel;
  26384. r *= attackReleaseLevel;
  26385. attackReleaseLevel += releaseDelta;
  26386. if (attackReleaseLevel <= 0.0f)
  26387. {
  26388. stopNote (false);
  26389. break;
  26390. }
  26391. }
  26392. if (outR != 0)
  26393. {
  26394. *outL++ += l;
  26395. *outR++ += r;
  26396. }
  26397. else
  26398. {
  26399. *outL++ += (l + r) * 0.5f;
  26400. }
  26401. sourceSamplePosition += pitchRatio;
  26402. if (sourceSamplePosition > playingSound->length)
  26403. {
  26404. stopNote (false);
  26405. break;
  26406. }
  26407. }
  26408. }
  26409. }
  26410. END_JUCE_NAMESPACE
  26411. /********* End of inlined file: juce_Sampler.cpp *********/
  26412. /********* Start of inlined file: juce_Synthesiser.cpp *********/
  26413. BEGIN_JUCE_NAMESPACE
  26414. SynthesiserSound::SynthesiserSound()
  26415. {
  26416. }
  26417. SynthesiserSound::~SynthesiserSound()
  26418. {
  26419. }
  26420. SynthesiserVoice::SynthesiserVoice()
  26421. : currentSampleRate (44100.0),
  26422. currentlyPlayingNote (-1),
  26423. noteOnTime (0),
  26424. currentlyPlayingSound (0)
  26425. {
  26426. }
  26427. SynthesiserVoice::~SynthesiserVoice()
  26428. {
  26429. }
  26430. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  26431. {
  26432. return currentlyPlayingSound != 0
  26433. && currentlyPlayingSound->appliesToChannel (midiChannel);
  26434. }
  26435. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  26436. {
  26437. currentSampleRate = newRate;
  26438. }
  26439. void SynthesiserVoice::clearCurrentNote()
  26440. {
  26441. currentlyPlayingNote = -1;
  26442. currentlyPlayingSound = 0;
  26443. }
  26444. Synthesiser::Synthesiser()
  26445. : voices (2),
  26446. sounds (2),
  26447. sampleRate (0),
  26448. lastNoteOnCounter (0),
  26449. shouldStealNotes (true)
  26450. {
  26451. zeromem (lastPitchWheelValues, sizeof (lastPitchWheelValues));
  26452. }
  26453. Synthesiser::~Synthesiser()
  26454. {
  26455. }
  26456. SynthesiserVoice* Synthesiser::getVoice (const int index) const throw()
  26457. {
  26458. const ScopedLock sl (lock);
  26459. return voices [index];
  26460. }
  26461. void Synthesiser::clearVoices()
  26462. {
  26463. const ScopedLock sl (lock);
  26464. voices.clear();
  26465. }
  26466. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  26467. {
  26468. const ScopedLock sl (lock);
  26469. voices.add (newVoice);
  26470. }
  26471. void Synthesiser::removeVoice (const int index)
  26472. {
  26473. const ScopedLock sl (lock);
  26474. voices.remove (index);
  26475. }
  26476. void Synthesiser::clearSounds()
  26477. {
  26478. const ScopedLock sl (lock);
  26479. sounds.clear();
  26480. }
  26481. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  26482. {
  26483. const ScopedLock sl (lock);
  26484. sounds.add (newSound);
  26485. }
  26486. void Synthesiser::removeSound (const int index)
  26487. {
  26488. const ScopedLock sl (lock);
  26489. sounds.remove (index);
  26490. }
  26491. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  26492. {
  26493. shouldStealNotes = shouldStealNotes_;
  26494. }
  26495. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  26496. {
  26497. if (sampleRate != newRate)
  26498. {
  26499. const ScopedLock sl (lock);
  26500. allNotesOff (0, false);
  26501. sampleRate = newRate;
  26502. for (int i = voices.size(); --i >= 0;)
  26503. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  26504. }
  26505. }
  26506. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  26507. const MidiBuffer& midiData,
  26508. int startSample,
  26509. int numSamples)
  26510. {
  26511. // must set the sample rate before using this!
  26512. jassert (sampleRate != 0);
  26513. const ScopedLock sl (lock);
  26514. MidiBuffer::Iterator midiIterator (midiData);
  26515. midiIterator.setNextSamplePosition (startSample);
  26516. MidiMessage m (0xf4, 0.0);
  26517. while (numSamples > 0)
  26518. {
  26519. int midiEventPos;
  26520. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  26521. && midiEventPos < startSample + numSamples;
  26522. const int numThisTime = useEvent ? midiEventPos - startSample
  26523. : numSamples;
  26524. if (numThisTime > 0)
  26525. {
  26526. for (int i = voices.size(); --i >= 0;)
  26527. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  26528. }
  26529. if (useEvent)
  26530. {
  26531. if (m.isNoteOn())
  26532. {
  26533. const int channel = m.getChannel();
  26534. noteOn (channel,
  26535. m.getNoteNumber(),
  26536. m.getFloatVelocity());
  26537. }
  26538. else if (m.isNoteOff())
  26539. {
  26540. noteOff (m.getChannel(),
  26541. m.getNoteNumber(),
  26542. true);
  26543. }
  26544. else if (m.isAllNotesOff() || m.isAllSoundOff())
  26545. {
  26546. allNotesOff (m.getChannel(), true);
  26547. }
  26548. else if (m.isPitchWheel())
  26549. {
  26550. const int channel = m.getChannel();
  26551. const int wheelPos = m.getPitchWheelValue();
  26552. lastPitchWheelValues [channel - 1] = wheelPos;
  26553. handlePitchWheel (channel, wheelPos);
  26554. }
  26555. else if (m.isController())
  26556. {
  26557. handleController (m.getChannel(),
  26558. m.getControllerNumber(),
  26559. m.getControllerValue());
  26560. }
  26561. }
  26562. startSample += numThisTime;
  26563. numSamples -= numThisTime;
  26564. }
  26565. }
  26566. void Synthesiser::noteOn (const int midiChannel,
  26567. const int midiNoteNumber,
  26568. const float velocity)
  26569. {
  26570. const ScopedLock sl (lock);
  26571. for (int i = sounds.size(); --i >= 0;)
  26572. {
  26573. SynthesiserSound* const sound = sounds.getUnchecked(i);
  26574. if (sound->appliesToNote (midiNoteNumber)
  26575. && sound->appliesToChannel (midiChannel))
  26576. {
  26577. startVoice (findFreeVoice (sound, shouldStealNotes),
  26578. sound, midiChannel, midiNoteNumber, velocity);
  26579. }
  26580. }
  26581. }
  26582. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  26583. SynthesiserSound* const sound,
  26584. const int midiChannel,
  26585. const int midiNoteNumber,
  26586. const float velocity)
  26587. {
  26588. if (voice != 0 && sound != 0)
  26589. {
  26590. if (voice->currentlyPlayingSound != 0)
  26591. voice->stopNote (false);
  26592. voice->startNote (midiNoteNumber,
  26593. velocity,
  26594. sound,
  26595. lastPitchWheelValues [midiChannel - 1]);
  26596. voice->currentlyPlayingNote = midiNoteNumber;
  26597. voice->noteOnTime = ++lastNoteOnCounter;
  26598. voice->currentlyPlayingSound = sound;
  26599. }
  26600. }
  26601. void Synthesiser::noteOff (const int midiChannel,
  26602. const int midiNoteNumber,
  26603. const bool allowTailOff)
  26604. {
  26605. const ScopedLock sl (lock);
  26606. for (int i = voices.size(); --i >= 0;)
  26607. {
  26608. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26609. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  26610. {
  26611. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  26612. if (sound != 0
  26613. && sound->appliesToNote (midiNoteNumber)
  26614. && sound->appliesToChannel (midiChannel))
  26615. {
  26616. voice->stopNote (allowTailOff);
  26617. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  26618. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  26619. }
  26620. }
  26621. }
  26622. }
  26623. void Synthesiser::allNotesOff (const int midiChannel,
  26624. const bool allowTailOff)
  26625. {
  26626. const ScopedLock sl (lock);
  26627. for (int i = voices.size(); --i >= 0;)
  26628. {
  26629. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26630. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  26631. voice->stopNote (allowTailOff);
  26632. }
  26633. }
  26634. void Synthesiser::handlePitchWheel (const int midiChannel,
  26635. const int wheelValue)
  26636. {
  26637. const ScopedLock sl (lock);
  26638. for (int i = voices.size(); --i >= 0;)
  26639. {
  26640. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26641. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  26642. {
  26643. voice->pitchWheelMoved (wheelValue);
  26644. }
  26645. }
  26646. }
  26647. void Synthesiser::handleController (const int midiChannel,
  26648. const int controllerNumber,
  26649. const int controllerValue)
  26650. {
  26651. const ScopedLock sl (lock);
  26652. for (int i = voices.size(); --i >= 0;)
  26653. {
  26654. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26655. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  26656. voice->controllerMoved (controllerNumber, controllerValue);
  26657. }
  26658. }
  26659. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  26660. const bool stealIfNoneAvailable) const
  26661. {
  26662. const ScopedLock sl (lock);
  26663. for (int i = voices.size(); --i >= 0;)
  26664. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  26665. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  26666. return voices.getUnchecked (i);
  26667. if (stealIfNoneAvailable)
  26668. {
  26669. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  26670. SynthesiserVoice* oldest = 0;
  26671. for (int i = voices.size(); --i >= 0;)
  26672. {
  26673. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26674. if (voice->canPlaySound (soundToPlay)
  26675. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  26676. oldest = voice;
  26677. }
  26678. jassert (oldest != 0);
  26679. return oldest;
  26680. }
  26681. return 0;
  26682. }
  26683. END_JUCE_NAMESPACE
  26684. /********* End of inlined file: juce_Synthesiser.cpp *********/
  26685. /********* Start of inlined file: juce_FileBasedDocument.cpp *********/
  26686. BEGIN_JUCE_NAMESPACE
  26687. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  26688. const String& fileWildcard_,
  26689. const String& openFileDialogTitle_,
  26690. const String& saveFileDialogTitle_)
  26691. : changedSinceSave (false),
  26692. fileExtension (fileExtension_),
  26693. fileWildcard (fileWildcard_),
  26694. openFileDialogTitle (openFileDialogTitle_),
  26695. saveFileDialogTitle (saveFileDialogTitle_)
  26696. {
  26697. }
  26698. FileBasedDocument::~FileBasedDocument()
  26699. {
  26700. }
  26701. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  26702. {
  26703. changedSinceSave = hasChanged;
  26704. }
  26705. void FileBasedDocument::changed()
  26706. {
  26707. changedSinceSave = true;
  26708. sendChangeMessage (this);
  26709. }
  26710. void FileBasedDocument::setFile (const File& newFile)
  26711. {
  26712. if (documentFile != newFile)
  26713. {
  26714. documentFile = newFile;
  26715. changedSinceSave = true;
  26716. }
  26717. }
  26718. bool FileBasedDocument::loadFrom (const File& newFile,
  26719. const bool showMessageOnFailure)
  26720. {
  26721. MouseCursor::showWaitCursor();
  26722. const File oldFile (documentFile);
  26723. documentFile = newFile;
  26724. String error;
  26725. if (newFile.existsAsFile())
  26726. {
  26727. error = loadDocument (newFile);
  26728. if (error.isEmpty())
  26729. {
  26730. setChangedFlag (false);
  26731. MouseCursor::hideWaitCursor();
  26732. setLastDocumentOpened (newFile);
  26733. return true;
  26734. }
  26735. }
  26736. else
  26737. {
  26738. error = "The file doesn't exist";
  26739. }
  26740. documentFile = oldFile;
  26741. MouseCursor::hideWaitCursor();
  26742. if (showMessageOnFailure)
  26743. {
  26744. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  26745. TRANS("Failed to open file..."),
  26746. TRANS("There was an error while trying to load the file:\n\n")
  26747. + newFile.getFullPathName()
  26748. + T("\n\n")
  26749. + error);
  26750. }
  26751. return false;
  26752. }
  26753. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  26754. {
  26755. FileChooser fc (openFileDialogTitle,
  26756. getLastDocumentOpened(),
  26757. fileWildcard);
  26758. if (fc.browseForFileToOpen())
  26759. return loadFrom (fc.getResult(), showMessageOnFailure);
  26760. return false;
  26761. }
  26762. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  26763. const bool showMessageOnFailure)
  26764. {
  26765. return saveAs (documentFile,
  26766. false,
  26767. askUserForFileIfNotSpecified,
  26768. showMessageOnFailure);
  26769. }
  26770. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  26771. const bool warnAboutOverwritingExistingFiles,
  26772. const bool askUserForFileIfNotSpecified,
  26773. const bool showMessageOnFailure)
  26774. {
  26775. if (newFile == File::nonexistent)
  26776. {
  26777. if (askUserForFileIfNotSpecified)
  26778. {
  26779. return saveAsInteractive (true);
  26780. }
  26781. else
  26782. {
  26783. // can't save to an unspecified file
  26784. jassertfalse
  26785. return failedToWriteToFile;
  26786. }
  26787. }
  26788. if (warnAboutOverwritingExistingFiles && newFile.exists())
  26789. {
  26790. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  26791. TRANS("File already exists"),
  26792. TRANS("There's already a file called:\n\n")
  26793. + newFile.getFullPathName()
  26794. + TRANS("\n\nAre you sure you want to overwrite it?"),
  26795. TRANS("overwrite"),
  26796. TRANS("cancel")))
  26797. {
  26798. return userCancelledSave;
  26799. }
  26800. }
  26801. MouseCursor::showWaitCursor();
  26802. const File oldFile (documentFile);
  26803. documentFile = newFile;
  26804. String error (saveDocument (newFile));
  26805. if (error.isEmpty())
  26806. {
  26807. setChangedFlag (false);
  26808. MouseCursor::hideWaitCursor();
  26809. return savedOk;
  26810. }
  26811. documentFile = oldFile;
  26812. MouseCursor::hideWaitCursor();
  26813. if (showMessageOnFailure)
  26814. {
  26815. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  26816. TRANS("Error writing to file..."),
  26817. TRANS("An error occurred while trying to save \"")
  26818. + getDocumentTitle()
  26819. + TRANS("\" to the file:\n\n")
  26820. + newFile.getFullPathName()
  26821. + T("\n\n")
  26822. + error);
  26823. }
  26824. return failedToWriteToFile;
  26825. }
  26826. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  26827. {
  26828. if (! hasChangedSinceSaved())
  26829. return savedOk;
  26830. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  26831. TRANS("Closing document..."),
  26832. TRANS("Do you want to save the changes to \"")
  26833. + getDocumentTitle() + T("\"?"),
  26834. TRANS("save"),
  26835. TRANS("discard changes"),
  26836. TRANS("cancel"));
  26837. if (r == 1)
  26838. {
  26839. // save changes
  26840. return save (true, true);
  26841. }
  26842. else if (r == 2)
  26843. {
  26844. // discard changes
  26845. return savedOk;
  26846. }
  26847. return userCancelledSave;
  26848. }
  26849. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  26850. {
  26851. File f;
  26852. if (documentFile.existsAsFile())
  26853. f = documentFile;
  26854. else
  26855. f = getLastDocumentOpened();
  26856. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  26857. if (legalFilename.isEmpty())
  26858. legalFilename = "unnamed";
  26859. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  26860. f = f.getSiblingFile (legalFilename);
  26861. else
  26862. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  26863. f = f.withFileExtension (fileExtension)
  26864. .getNonexistentSibling (true);
  26865. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  26866. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  26867. {
  26868. setLastDocumentOpened (fc.getResult());
  26869. File chosen (fc.getResult());
  26870. if (chosen.getFileExtension().isEmpty())
  26871. chosen = chosen.withFileExtension (fileExtension);
  26872. return saveAs (chosen, false, false, true);
  26873. }
  26874. return userCancelledSave;
  26875. }
  26876. END_JUCE_NAMESPACE
  26877. /********* End of inlined file: juce_FileBasedDocument.cpp *********/
  26878. /********* Start of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  26879. BEGIN_JUCE_NAMESPACE
  26880. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  26881. : maxNumberOfItems (10)
  26882. {
  26883. }
  26884. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  26885. {
  26886. }
  26887. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  26888. {
  26889. maxNumberOfItems = jmax (1, newMaxNumber);
  26890. while (getNumFiles() > maxNumberOfItems)
  26891. files.remove (getNumFiles() - 1);
  26892. }
  26893. int RecentlyOpenedFilesList::getNumFiles() const
  26894. {
  26895. return files.size();
  26896. }
  26897. const File RecentlyOpenedFilesList::getFile (const int index) const
  26898. {
  26899. return File (files [index]);
  26900. }
  26901. void RecentlyOpenedFilesList::clear()
  26902. {
  26903. files.clear();
  26904. }
  26905. void RecentlyOpenedFilesList::addFile (const File& file)
  26906. {
  26907. const String path (file.getFullPathName());
  26908. files.removeString (path, true);
  26909. files.insert (0, path);
  26910. setMaxNumberOfItems (maxNumberOfItems);
  26911. }
  26912. void RecentlyOpenedFilesList::removeNonExistentFiles()
  26913. {
  26914. for (int i = getNumFiles(); --i >= 0;)
  26915. if (! getFile(i).exists())
  26916. files.remove (i);
  26917. }
  26918. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  26919. const int baseItemId,
  26920. const bool showFullPaths,
  26921. const bool dontAddNonExistentFiles,
  26922. const File** filesToAvoid)
  26923. {
  26924. int num = 0;
  26925. for (int i = 0; i < getNumFiles(); ++i)
  26926. {
  26927. const File f (getFile(i));
  26928. if ((! dontAddNonExistentFiles) || f.exists())
  26929. {
  26930. bool needsAvoiding = false;
  26931. if (filesToAvoid != 0)
  26932. {
  26933. const File** files = filesToAvoid;
  26934. while (*files != 0)
  26935. {
  26936. if (f == **files)
  26937. {
  26938. needsAvoiding = true;
  26939. break;
  26940. }
  26941. ++files;
  26942. }
  26943. }
  26944. if (! needsAvoiding)
  26945. {
  26946. menuToAddTo.addItem (baseItemId + i,
  26947. showFullPaths ? f.getFullPathName()
  26948. : f.getFileName());
  26949. ++num;
  26950. }
  26951. }
  26952. }
  26953. return num;
  26954. }
  26955. const String RecentlyOpenedFilesList::toString() const
  26956. {
  26957. return files.joinIntoString (T("\n"));
  26958. }
  26959. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  26960. {
  26961. clear();
  26962. files.addLines (stringifiedVersion);
  26963. setMaxNumberOfItems (maxNumberOfItems);
  26964. }
  26965. END_JUCE_NAMESPACE
  26966. /********* End of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  26967. /********* Start of inlined file: juce_UndoManager.cpp *********/
  26968. BEGIN_JUCE_NAMESPACE
  26969. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  26970. const int minimumTransactions)
  26971. : totalUnitsStored (0),
  26972. nextIndex (0),
  26973. newTransaction (true),
  26974. reentrancyCheck (false)
  26975. {
  26976. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  26977. minimumTransactions);
  26978. }
  26979. UndoManager::~UndoManager()
  26980. {
  26981. clearUndoHistory();
  26982. }
  26983. void UndoManager::clearUndoHistory()
  26984. {
  26985. transactions.clear();
  26986. transactionNames.clear();
  26987. totalUnitsStored = 0;
  26988. nextIndex = 0;
  26989. sendChangeMessage (this);
  26990. }
  26991. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  26992. {
  26993. return totalUnitsStored;
  26994. }
  26995. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  26996. const int minimumTransactions)
  26997. {
  26998. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  26999. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  27000. }
  27001. bool UndoManager::perform (UndoableAction* const command, const String& actionName)
  27002. {
  27003. if (command != 0)
  27004. {
  27005. if (actionName.isNotEmpty())
  27006. currentTransactionName = actionName;
  27007. if (reentrancyCheck)
  27008. {
  27009. jassertfalse // don't call perform() recursively from the UndoableAction::perform() or
  27010. // undo() methods, or else these actions won't actually get done.
  27011. return false;
  27012. }
  27013. else
  27014. {
  27015. bool success = false;
  27016. JUCE_TRY
  27017. {
  27018. success = command->perform();
  27019. }
  27020. JUCE_CATCH_EXCEPTION
  27021. jassert (success);
  27022. if (success)
  27023. {
  27024. if (nextIndex > 0 && ! newTransaction)
  27025. {
  27026. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  27027. jassert (commandSet != 0);
  27028. if (commandSet == 0)
  27029. return false;
  27030. commandSet->add (command);
  27031. }
  27032. else
  27033. {
  27034. OwnedArray<UndoableAction>* commandSet = new OwnedArray<UndoableAction>();
  27035. commandSet->add (command);
  27036. transactions.insert (nextIndex, commandSet);
  27037. transactionNames.insert (nextIndex, currentTransactionName);
  27038. ++nextIndex;
  27039. }
  27040. totalUnitsStored += command->getSizeInUnits();
  27041. newTransaction = false;
  27042. }
  27043. while (nextIndex < transactions.size())
  27044. {
  27045. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  27046. for (int i = lastSet->size(); --i >= 0;)
  27047. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  27048. transactions.removeLast();
  27049. transactionNames.remove (transactionNames.size() - 1);
  27050. }
  27051. while (nextIndex > 0
  27052. && totalUnitsStored > maxNumUnitsToKeep
  27053. && transactions.size() > minimumTransactionsToKeep)
  27054. {
  27055. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  27056. for (int i = firstSet->size(); --i >= 0;)
  27057. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  27058. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  27059. transactions.remove (0);
  27060. transactionNames.remove (0);
  27061. --nextIndex;
  27062. }
  27063. sendChangeMessage (this);
  27064. return success;
  27065. }
  27066. }
  27067. return false;
  27068. }
  27069. void UndoManager::beginNewTransaction (const String& actionName)
  27070. {
  27071. newTransaction = true;
  27072. currentTransactionName = actionName;
  27073. }
  27074. void UndoManager::setCurrentTransactionName (const String& newName)
  27075. {
  27076. currentTransactionName = newName;
  27077. }
  27078. bool UndoManager::canUndo() const
  27079. {
  27080. return nextIndex > 0;
  27081. }
  27082. bool UndoManager::canRedo() const
  27083. {
  27084. return nextIndex < transactions.size();
  27085. }
  27086. const String UndoManager::getUndoDescription() const
  27087. {
  27088. return transactionNames [nextIndex - 1];
  27089. }
  27090. const String UndoManager::getRedoDescription() const
  27091. {
  27092. return transactionNames [nextIndex];
  27093. }
  27094. bool UndoManager::undo()
  27095. {
  27096. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  27097. if (commandSet == 0)
  27098. return false;
  27099. reentrancyCheck = true;
  27100. bool failed = false;
  27101. for (int i = commandSet->size(); --i >= 0;)
  27102. {
  27103. if (! commandSet->getUnchecked(i)->undo())
  27104. {
  27105. jassertfalse
  27106. failed = true;
  27107. break;
  27108. }
  27109. }
  27110. reentrancyCheck = false;
  27111. if (failed)
  27112. {
  27113. clearUndoHistory();
  27114. }
  27115. else
  27116. {
  27117. --nextIndex;
  27118. }
  27119. beginNewTransaction();
  27120. sendChangeMessage (this);
  27121. return true;
  27122. }
  27123. bool UndoManager::redo()
  27124. {
  27125. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  27126. if (commandSet == 0)
  27127. return false;
  27128. reentrancyCheck = true;
  27129. bool failed = false;
  27130. for (int i = 0; i < commandSet->size(); ++i)
  27131. {
  27132. if (! commandSet->getUnchecked(i)->perform())
  27133. {
  27134. jassertfalse
  27135. failed = true;
  27136. break;
  27137. }
  27138. }
  27139. reentrancyCheck = false;
  27140. if (failed)
  27141. {
  27142. clearUndoHistory();
  27143. }
  27144. else
  27145. {
  27146. ++nextIndex;
  27147. }
  27148. beginNewTransaction();
  27149. sendChangeMessage (this);
  27150. return true;
  27151. }
  27152. bool UndoManager::undoCurrentTransactionOnly()
  27153. {
  27154. return newTransaction ? false
  27155. : undo();
  27156. }
  27157. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  27158. {
  27159. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  27160. if (commandSet != 0 && ! newTransaction)
  27161. {
  27162. for (int i = 0; i < commandSet->size(); ++i)
  27163. actionsFound.add (commandSet->getUnchecked(i));
  27164. }
  27165. }
  27166. END_JUCE_NAMESPACE
  27167. /********* End of inlined file: juce_UndoManager.cpp *********/
  27168. /********* Start of inlined file: juce_ActionBroadcaster.cpp *********/
  27169. BEGIN_JUCE_NAMESPACE
  27170. ActionBroadcaster::ActionBroadcaster() throw()
  27171. {
  27172. // are you trying to create this object before or after juce has been intialised??
  27173. jassert (MessageManager::instance != 0);
  27174. }
  27175. ActionBroadcaster::~ActionBroadcaster()
  27176. {
  27177. // all event-based objects must be deleted BEFORE juce is shut down!
  27178. jassert (MessageManager::instance != 0);
  27179. }
  27180. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  27181. {
  27182. actionListenerList.addActionListener (listener);
  27183. }
  27184. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  27185. {
  27186. jassert (actionListenerList.isValidMessageListener());
  27187. if (actionListenerList.isValidMessageListener())
  27188. actionListenerList.removeActionListener (listener);
  27189. }
  27190. void ActionBroadcaster::removeAllActionListeners()
  27191. {
  27192. actionListenerList.removeAllActionListeners();
  27193. }
  27194. void ActionBroadcaster::sendActionMessage (const String& message) const
  27195. {
  27196. actionListenerList.sendActionMessage (message);
  27197. }
  27198. END_JUCE_NAMESPACE
  27199. /********* End of inlined file: juce_ActionBroadcaster.cpp *********/
  27200. /********* Start of inlined file: juce_ActionListenerList.cpp *********/
  27201. BEGIN_JUCE_NAMESPACE
  27202. // special message of our own with a string in it
  27203. class ActionMessage : public Message
  27204. {
  27205. public:
  27206. const String message;
  27207. ActionMessage (const String& messageText,
  27208. void* const listener_) throw()
  27209. : message (messageText)
  27210. {
  27211. pointerParameter = listener_;
  27212. }
  27213. ~ActionMessage() throw()
  27214. {
  27215. }
  27216. private:
  27217. ActionMessage (const ActionMessage&);
  27218. const ActionMessage& operator= (const ActionMessage&);
  27219. };
  27220. ActionListenerList::ActionListenerList() throw()
  27221. {
  27222. }
  27223. ActionListenerList::~ActionListenerList() throw()
  27224. {
  27225. }
  27226. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  27227. {
  27228. const ScopedLock sl (actionListenerLock_);
  27229. jassert (listener != 0);
  27230. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  27231. if (listener != 0)
  27232. actionListeners_.add (listener);
  27233. }
  27234. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  27235. {
  27236. const ScopedLock sl (actionListenerLock_);
  27237. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  27238. actionListeners_.removeValue (listener);
  27239. }
  27240. void ActionListenerList::removeAllActionListeners() throw()
  27241. {
  27242. const ScopedLock sl (actionListenerLock_);
  27243. actionListeners_.clear();
  27244. }
  27245. void ActionListenerList::sendActionMessage (const String& message) const
  27246. {
  27247. const ScopedLock sl (actionListenerLock_);
  27248. for (int i = actionListeners_.size(); --i >= 0;)
  27249. {
  27250. postMessage (new ActionMessage (message,
  27251. (ActionListener*) actionListeners_.getUnchecked(i)));
  27252. }
  27253. }
  27254. void ActionListenerList::handleMessage (const Message& message)
  27255. {
  27256. const ActionMessage& am = (const ActionMessage&) message;
  27257. if (actionListeners_.contains (am.pointerParameter))
  27258. ((ActionListener*) am.pointerParameter)->actionListenerCallback (am.message);
  27259. }
  27260. END_JUCE_NAMESPACE
  27261. /********* End of inlined file: juce_ActionListenerList.cpp *********/
  27262. /********* Start of inlined file: juce_AsyncUpdater.cpp *********/
  27263. BEGIN_JUCE_NAMESPACE
  27264. AsyncUpdater::AsyncUpdater() throw()
  27265. : asyncMessagePending (false)
  27266. {
  27267. internalAsyncHandler.owner = this;
  27268. }
  27269. AsyncUpdater::~AsyncUpdater()
  27270. {
  27271. }
  27272. void AsyncUpdater::triggerAsyncUpdate() throw()
  27273. {
  27274. if (! asyncMessagePending)
  27275. {
  27276. asyncMessagePending = true;
  27277. internalAsyncHandler.postMessage (new Message());
  27278. }
  27279. }
  27280. void AsyncUpdater::cancelPendingUpdate() throw()
  27281. {
  27282. asyncMessagePending = false;
  27283. }
  27284. void AsyncUpdater::handleUpdateNowIfNeeded()
  27285. {
  27286. if (asyncMessagePending)
  27287. {
  27288. asyncMessagePending = false;
  27289. handleAsyncUpdate();
  27290. }
  27291. }
  27292. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  27293. {
  27294. owner->handleUpdateNowIfNeeded();
  27295. }
  27296. END_JUCE_NAMESPACE
  27297. /********* End of inlined file: juce_AsyncUpdater.cpp *********/
  27298. /********* Start of inlined file: juce_ChangeBroadcaster.cpp *********/
  27299. BEGIN_JUCE_NAMESPACE
  27300. ChangeBroadcaster::ChangeBroadcaster() throw()
  27301. {
  27302. // are you trying to create this object before or after juce has been intialised??
  27303. jassert (MessageManager::instance != 0);
  27304. }
  27305. ChangeBroadcaster::~ChangeBroadcaster()
  27306. {
  27307. // all event-based objects must be deleted BEFORE juce is shut down!
  27308. jassert (MessageManager::instance != 0);
  27309. }
  27310. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  27311. {
  27312. changeListenerList.addChangeListener (listener);
  27313. }
  27314. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  27315. {
  27316. jassert (changeListenerList.isValidMessageListener());
  27317. if (changeListenerList.isValidMessageListener())
  27318. changeListenerList.removeChangeListener (listener);
  27319. }
  27320. void ChangeBroadcaster::removeAllChangeListeners() throw()
  27321. {
  27322. changeListenerList.removeAllChangeListeners();
  27323. }
  27324. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  27325. {
  27326. changeListenerList.sendChangeMessage (objectThatHasChanged);
  27327. }
  27328. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  27329. {
  27330. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  27331. }
  27332. void ChangeBroadcaster::dispatchPendingMessages()
  27333. {
  27334. changeListenerList.dispatchPendingMessages();
  27335. }
  27336. END_JUCE_NAMESPACE
  27337. /********* End of inlined file: juce_ChangeBroadcaster.cpp *********/
  27338. /********* Start of inlined file: juce_ChangeListenerList.cpp *********/
  27339. BEGIN_JUCE_NAMESPACE
  27340. ChangeListenerList::ChangeListenerList() throw()
  27341. : lastChangedObject (0),
  27342. messagePending (false)
  27343. {
  27344. }
  27345. ChangeListenerList::~ChangeListenerList() throw()
  27346. {
  27347. }
  27348. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  27349. {
  27350. const ScopedLock sl (lock);
  27351. jassert (listener != 0);
  27352. if (listener != 0)
  27353. listeners.add (listener);
  27354. }
  27355. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  27356. {
  27357. const ScopedLock sl (lock);
  27358. listeners.removeValue (listener);
  27359. }
  27360. void ChangeListenerList::removeAllChangeListeners() throw()
  27361. {
  27362. const ScopedLock sl (lock);
  27363. listeners.clear();
  27364. }
  27365. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  27366. {
  27367. const ScopedLock sl (lock);
  27368. if ((! messagePending) && (listeners.size() > 0))
  27369. {
  27370. lastChangedObject = objectThatHasChanged;
  27371. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  27372. messagePending = true;
  27373. }
  27374. }
  27375. void ChangeListenerList::handleMessage (const Message& message)
  27376. {
  27377. sendSynchronousChangeMessage (message.pointerParameter);
  27378. }
  27379. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  27380. {
  27381. const ScopedLock sl (lock);
  27382. messagePending = false;
  27383. for (int i = listeners.size(); --i >= 0;)
  27384. {
  27385. ChangeListener* const l = (ChangeListener*) listeners.getUnchecked (i);
  27386. {
  27387. const ScopedUnlock tempUnlocker (lock);
  27388. l->changeListenerCallback (objectThatHasChanged);
  27389. }
  27390. i = jmin (i, listeners.size());
  27391. }
  27392. }
  27393. void ChangeListenerList::dispatchPendingMessages()
  27394. {
  27395. if (messagePending)
  27396. sendSynchronousChangeMessage (lastChangedObject);
  27397. }
  27398. END_JUCE_NAMESPACE
  27399. /********* End of inlined file: juce_ChangeListenerList.cpp *********/
  27400. /********* Start of inlined file: juce_InterprocessConnection.cpp *********/
  27401. BEGIN_JUCE_NAMESPACE
  27402. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  27403. const uint32 magicMessageHeaderNumber)
  27404. : Thread ("Juce IPC connection"),
  27405. socket (0),
  27406. pipe (0),
  27407. callbackConnectionState (false),
  27408. useMessageThread (callbacksOnMessageThread),
  27409. magicMessageHeader (magicMessageHeaderNumber),
  27410. pipeReceiveMessageTimeout (-1)
  27411. {
  27412. }
  27413. InterprocessConnection::~InterprocessConnection()
  27414. {
  27415. callbackConnectionState = false;
  27416. disconnect();
  27417. }
  27418. bool InterprocessConnection::connectToSocket (const String& hostName,
  27419. const int portNumber,
  27420. const int timeOutMillisecs)
  27421. {
  27422. disconnect();
  27423. const ScopedLock sl (pipeAndSocketLock);
  27424. socket = new StreamingSocket();
  27425. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  27426. {
  27427. connectionMadeInt();
  27428. startThread();
  27429. return true;
  27430. }
  27431. else
  27432. {
  27433. deleteAndZero (socket);
  27434. return false;
  27435. }
  27436. }
  27437. bool InterprocessConnection::connectToPipe (const String& pipeName,
  27438. const int pipeReceiveMessageTimeoutMs)
  27439. {
  27440. disconnect();
  27441. NamedPipe* const newPipe = new NamedPipe();
  27442. if (newPipe->openExisting (pipeName))
  27443. {
  27444. const ScopedLock sl (pipeAndSocketLock);
  27445. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  27446. initialiseWithPipe (newPipe);
  27447. return true;
  27448. }
  27449. else
  27450. {
  27451. delete newPipe;
  27452. return false;
  27453. }
  27454. }
  27455. bool InterprocessConnection::createPipe (const String& pipeName,
  27456. const int pipeReceiveMessageTimeoutMs)
  27457. {
  27458. disconnect();
  27459. NamedPipe* const newPipe = new NamedPipe();
  27460. if (newPipe->createNewPipe (pipeName))
  27461. {
  27462. const ScopedLock sl (pipeAndSocketLock);
  27463. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  27464. initialiseWithPipe (newPipe);
  27465. return true;
  27466. }
  27467. else
  27468. {
  27469. delete newPipe;
  27470. return false;
  27471. }
  27472. }
  27473. void InterprocessConnection::disconnect()
  27474. {
  27475. if (socket != 0)
  27476. socket->close();
  27477. if (pipe != 0)
  27478. {
  27479. pipe->cancelPendingReads();
  27480. pipe->close();
  27481. }
  27482. stopThread (4000);
  27483. {
  27484. const ScopedLock sl (pipeAndSocketLock);
  27485. deleteAndZero (socket);
  27486. deleteAndZero (pipe);
  27487. }
  27488. connectionLostInt();
  27489. }
  27490. bool InterprocessConnection::isConnected() const
  27491. {
  27492. const ScopedLock sl (pipeAndSocketLock);
  27493. return ((socket != 0 && socket->isConnected())
  27494. || (pipe != 0 && pipe->isOpen()))
  27495. && isThreadRunning();
  27496. }
  27497. const String InterprocessConnection::getConnectedHostName() const
  27498. {
  27499. if (pipe != 0)
  27500. {
  27501. return "localhost";
  27502. }
  27503. else if (socket != 0)
  27504. {
  27505. if (! socket->isLocal())
  27506. return socket->getHostName();
  27507. return "localhost";
  27508. }
  27509. return String::empty;
  27510. }
  27511. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  27512. {
  27513. uint32 messageHeader[2];
  27514. messageHeader [0] = swapIfBigEndian (magicMessageHeader);
  27515. messageHeader [1] = swapIfBigEndian ((uint32) message.getSize());
  27516. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  27517. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  27518. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  27519. int bytesWritten = 0;
  27520. const ScopedLock sl (pipeAndSocketLock);
  27521. if (socket != 0)
  27522. {
  27523. bytesWritten = socket->write (messageData.getData(), messageData.getSize());
  27524. }
  27525. else if (pipe != 0)
  27526. {
  27527. bytesWritten = pipe->write (messageData.getData(), messageData.getSize());
  27528. }
  27529. if (bytesWritten < 0)
  27530. {
  27531. // error..
  27532. return false;
  27533. }
  27534. return (bytesWritten == messageData.getSize());
  27535. }
  27536. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  27537. {
  27538. jassert (socket == 0);
  27539. socket = socket_;
  27540. connectionMadeInt();
  27541. startThread();
  27542. }
  27543. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  27544. {
  27545. jassert (pipe == 0);
  27546. pipe = pipe_;
  27547. connectionMadeInt();
  27548. startThread();
  27549. }
  27550. const int messageMagicNumber = 0xb734128b;
  27551. void InterprocessConnection::handleMessage (const Message& message)
  27552. {
  27553. if (message.intParameter1 == messageMagicNumber)
  27554. {
  27555. switch (message.intParameter2)
  27556. {
  27557. case 0:
  27558. {
  27559. MemoryBlock* const data = (MemoryBlock*) message.pointerParameter;
  27560. messageReceived (*data);
  27561. delete data;
  27562. break;
  27563. }
  27564. case 1:
  27565. connectionMade();
  27566. break;
  27567. case 2:
  27568. connectionLost();
  27569. break;
  27570. }
  27571. }
  27572. }
  27573. void InterprocessConnection::connectionMadeInt()
  27574. {
  27575. if (! callbackConnectionState)
  27576. {
  27577. callbackConnectionState = true;
  27578. if (useMessageThread)
  27579. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  27580. else
  27581. connectionMade();
  27582. }
  27583. }
  27584. void InterprocessConnection::connectionLostInt()
  27585. {
  27586. if (callbackConnectionState)
  27587. {
  27588. callbackConnectionState = false;
  27589. if (useMessageThread)
  27590. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  27591. else
  27592. connectionLost();
  27593. }
  27594. }
  27595. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  27596. {
  27597. jassert (callbackConnectionState);
  27598. if (useMessageThread)
  27599. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  27600. else
  27601. messageReceived (data);
  27602. }
  27603. bool InterprocessConnection::readNextMessageInt()
  27604. {
  27605. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  27606. uint32 messageHeader[2];
  27607. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader))
  27608. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  27609. if (bytes == sizeof (messageHeader)
  27610. && swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  27611. {
  27612. const int bytesInMessage = (int) swapIfBigEndian (messageHeader[1]);
  27613. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  27614. {
  27615. MemoryBlock messageData (bytesInMessage, true);
  27616. int bytesRead = 0;
  27617. while (bytesRead < bytesInMessage)
  27618. {
  27619. if (threadShouldExit())
  27620. return false;
  27621. const int numThisTime = jmin (bytesInMessage, 65536);
  27622. const int bytesIn = (socket != 0) ? socket->read (((char*) messageData.getData()) + bytesRead, numThisTime)
  27623. : pipe->read (((char*) messageData.getData()) + bytesRead, numThisTime,
  27624. pipeReceiveMessageTimeout);
  27625. if (bytesIn <= 0)
  27626. break;
  27627. bytesRead += bytesIn;
  27628. }
  27629. if (bytesRead >= 0)
  27630. deliverDataInt (messageData);
  27631. }
  27632. }
  27633. else if (bytes < 0)
  27634. {
  27635. {
  27636. const ScopedLock sl (pipeAndSocketLock);
  27637. deleteAndZero (socket);
  27638. }
  27639. connectionLostInt();
  27640. return false;
  27641. }
  27642. return true;
  27643. }
  27644. void InterprocessConnection::run()
  27645. {
  27646. while (! threadShouldExit())
  27647. {
  27648. if (socket != 0)
  27649. {
  27650. const int ready = socket->waitUntilReady (true, 0);
  27651. if (ready < 0)
  27652. {
  27653. {
  27654. const ScopedLock sl (pipeAndSocketLock);
  27655. deleteAndZero (socket);
  27656. }
  27657. connectionLostInt();
  27658. break;
  27659. }
  27660. else if (ready > 0)
  27661. {
  27662. if (! readNextMessageInt())
  27663. break;
  27664. }
  27665. else
  27666. {
  27667. Thread::sleep (2);
  27668. }
  27669. }
  27670. else if (pipe != 0)
  27671. {
  27672. if (! pipe->isOpen())
  27673. {
  27674. {
  27675. const ScopedLock sl (pipeAndSocketLock);
  27676. deleteAndZero (pipe);
  27677. }
  27678. connectionLostInt();
  27679. break;
  27680. }
  27681. else
  27682. {
  27683. if (! readNextMessageInt())
  27684. break;
  27685. }
  27686. }
  27687. else
  27688. {
  27689. break;
  27690. }
  27691. }
  27692. }
  27693. END_JUCE_NAMESPACE
  27694. /********* End of inlined file: juce_InterprocessConnection.cpp *********/
  27695. /********* Start of inlined file: juce_InterprocessConnectionServer.cpp *********/
  27696. BEGIN_JUCE_NAMESPACE
  27697. InterprocessConnectionServer::InterprocessConnectionServer()
  27698. : Thread ("Juce IPC server"),
  27699. socket (0)
  27700. {
  27701. }
  27702. InterprocessConnectionServer::~InterprocessConnectionServer()
  27703. {
  27704. stop();
  27705. }
  27706. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  27707. {
  27708. stop();
  27709. socket = new StreamingSocket();
  27710. if (socket->createListener (portNumber))
  27711. {
  27712. startThread();
  27713. return true;
  27714. }
  27715. deleteAndZero (socket);
  27716. return false;
  27717. }
  27718. void InterprocessConnectionServer::stop()
  27719. {
  27720. signalThreadShouldExit();
  27721. if (socket != 0)
  27722. socket->close();
  27723. stopThread (4000);
  27724. deleteAndZero (socket);
  27725. }
  27726. void InterprocessConnectionServer::run()
  27727. {
  27728. while ((! threadShouldExit()) && socket != 0)
  27729. {
  27730. StreamingSocket* const clientSocket = socket->waitForNextConnection();
  27731. if (clientSocket != 0)
  27732. {
  27733. InterprocessConnection* newConnection = createConnectionObject();
  27734. if (newConnection != 0)
  27735. {
  27736. newConnection->initialiseWithSocket (clientSocket);
  27737. }
  27738. else
  27739. {
  27740. delete clientSocket;
  27741. }
  27742. }
  27743. }
  27744. }
  27745. END_JUCE_NAMESPACE
  27746. /********* End of inlined file: juce_InterprocessConnectionServer.cpp *********/
  27747. /********* Start of inlined file: juce_Message.cpp *********/
  27748. BEGIN_JUCE_NAMESPACE
  27749. Message::Message() throw()
  27750. {
  27751. }
  27752. Message::~Message() throw()
  27753. {
  27754. }
  27755. Message::Message (const int intParameter1_,
  27756. const int intParameter2_,
  27757. const int intParameter3_,
  27758. void* const pointerParameter_) throw()
  27759. : intParameter1 (intParameter1_),
  27760. intParameter2 (intParameter2_),
  27761. intParameter3 (intParameter3_),
  27762. pointerParameter (pointerParameter_)
  27763. {
  27764. }
  27765. END_JUCE_NAMESPACE
  27766. /********* End of inlined file: juce_Message.cpp *********/
  27767. /********* Start of inlined file: juce_MessageListener.cpp *********/
  27768. BEGIN_JUCE_NAMESPACE
  27769. MessageListener::MessageListener() throw()
  27770. {
  27771. // are you trying to create a messagelistener before or after juce has been intialised??
  27772. jassert (MessageManager::instance != 0);
  27773. if (MessageManager::instance != 0)
  27774. MessageManager::instance->messageListeners.add (this);
  27775. }
  27776. MessageListener::~MessageListener()
  27777. {
  27778. if (MessageManager::instance != 0)
  27779. MessageManager::instance->messageListeners.removeValue (this);
  27780. }
  27781. void MessageListener::postMessage (Message* const message) const throw()
  27782. {
  27783. message->messageRecipient = const_cast <MessageListener*> (this);
  27784. if (MessageManager::instance == 0)
  27785. MessageManager::getInstance();
  27786. MessageManager::instance->postMessageToQueue (message);
  27787. }
  27788. bool MessageListener::isValidMessageListener() const throw()
  27789. {
  27790. return (MessageManager::instance != 0)
  27791. && MessageManager::instance->messageListeners.contains (this);
  27792. }
  27793. END_JUCE_NAMESPACE
  27794. /********* End of inlined file: juce_MessageListener.cpp *********/
  27795. /********* Start of inlined file: juce_MessageManager.cpp *********/
  27796. BEGIN_JUCE_NAMESPACE
  27797. // platform-specific functions..
  27798. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  27799. bool juce_postMessageToSystemQueue (void* message);
  27800. MessageManager* MessageManager::instance = 0;
  27801. static const int quitMessageId = 0xfffff321;
  27802. MessageManager::MessageManager() throw()
  27803. : broadcastListeners (0),
  27804. quitMessagePosted (false),
  27805. quitMessageReceived (false),
  27806. useMaximumForceWhenQuitting (true),
  27807. messageCounter (0),
  27808. lastMessageCounter (-1),
  27809. isInMessageDispatcher (0),
  27810. needToGetRidOfWaitCursor (false),
  27811. timeBeforeWaitCursor (0),
  27812. lastActivityCheckOkTime (0)
  27813. {
  27814. currentLockingThreadId = messageThreadId = Thread::getCurrentThreadId();
  27815. }
  27816. MessageManager::~MessageManager() throw()
  27817. {
  27818. jassert (instance == this);
  27819. instance = 0;
  27820. deleteAndZero (broadcastListeners);
  27821. doPlatformSpecificShutdown();
  27822. }
  27823. MessageManager* MessageManager::getInstance() throw()
  27824. {
  27825. if (instance == 0)
  27826. {
  27827. instance = new MessageManager();
  27828. doPlatformSpecificInitialisation();
  27829. instance->setTimeBeforeShowingWaitCursor (500);
  27830. }
  27831. return instance;
  27832. }
  27833. void MessageManager::postMessageToQueue (Message* const message)
  27834. {
  27835. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  27836. delete message;
  27837. }
  27838. // not for public use..
  27839. void MessageManager::deliverMessage (void* message)
  27840. {
  27841. const MessageManagerLock lock;
  27842. Message* const m = (Message*) message;
  27843. MessageListener* const recipient = m->messageRecipient;
  27844. if (messageListeners.contains (recipient))
  27845. {
  27846. JUCE_TRY
  27847. {
  27848. recipient->handleMessage (*m);
  27849. }
  27850. JUCE_CATCH_EXCEPTION
  27851. if (needToGetRidOfWaitCursor)
  27852. {
  27853. needToGetRidOfWaitCursor = false;
  27854. MouseCursor::hideWaitCursor();
  27855. }
  27856. ++messageCounter;
  27857. }
  27858. else if (recipient == 0 && m->intParameter1 == quitMessageId)
  27859. {
  27860. quitMessageReceived = true;
  27861. useMaximumForceWhenQuitting = (m->intParameter2 != 0);
  27862. }
  27863. delete m;
  27864. }
  27865. bool MessageManager::dispatchNextMessage (const bool returnImmediatelyIfNoMessages,
  27866. bool* const wasAMessageDispatched)
  27867. {
  27868. if (quitMessageReceived)
  27869. {
  27870. if (wasAMessageDispatched != 0)
  27871. *wasAMessageDispatched = false;
  27872. return false;
  27873. }
  27874. ++isInMessageDispatcher;
  27875. bool result = false;
  27876. JUCE_TRY
  27877. {
  27878. result = juce_dispatchNextMessageOnSystemQueue (returnImmediatelyIfNoMessages);
  27879. if (wasAMessageDispatched != 0)
  27880. *wasAMessageDispatched = result;
  27881. if (instance == 0)
  27882. return false;
  27883. }
  27884. JUCE_CATCH_EXCEPTION
  27885. --isInMessageDispatcher;
  27886. ++messageCounter;
  27887. return result || ! returnImmediatelyIfNoMessages;
  27888. }
  27889. void MessageManager::dispatchPendingMessages (int maxNumberOfMessagesToDispatch)
  27890. {
  27891. jassert (isThisTheMessageThread()); // must only be called by the message thread
  27892. while (--maxNumberOfMessagesToDispatch >= 0 && ! quitMessageReceived)
  27893. {
  27894. ++isInMessageDispatcher;
  27895. bool carryOn = false;
  27896. JUCE_TRY
  27897. {
  27898. carryOn = juce_dispatchNextMessageOnSystemQueue (true);
  27899. }
  27900. JUCE_CATCH_EXCEPTION
  27901. --isInMessageDispatcher;
  27902. ++messageCounter;
  27903. if (! carryOn)
  27904. break;
  27905. }
  27906. }
  27907. bool MessageManager::runDispatchLoop()
  27908. {
  27909. jassert (isThisTheMessageThread()); // must only be called by the message thread
  27910. while (dispatchNextMessage())
  27911. {
  27912. }
  27913. return useMaximumForceWhenQuitting;
  27914. }
  27915. void MessageManager::postQuitMessage (const bool useMaximumForce)
  27916. {
  27917. Message* const m = new Message (quitMessageId, (useMaximumForce) ? 1 : 0, 0, 0);
  27918. m->messageRecipient = 0;
  27919. postMessageToQueue (m);
  27920. quitMessagePosted = true;
  27921. }
  27922. bool MessageManager::hasQuitMessageBeenPosted() const throw()
  27923. {
  27924. return quitMessagePosted;
  27925. }
  27926. void MessageManager::deliverBroadcastMessage (const String& value)
  27927. {
  27928. if (broadcastListeners != 0)
  27929. broadcastListeners->sendActionMessage (value);
  27930. }
  27931. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  27932. {
  27933. if (broadcastListeners == 0)
  27934. broadcastListeners = new ActionListenerList();
  27935. broadcastListeners->addActionListener (listener);
  27936. }
  27937. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  27938. {
  27939. if (broadcastListeners != 0)
  27940. broadcastListeners->removeActionListener (listener);
  27941. }
  27942. // This gets called occasionally by the timer thread (to save using an extra thread
  27943. // for it).
  27944. void MessageManager::inactivityCheckCallback() throw()
  27945. {
  27946. if (instance != 0)
  27947. instance->inactivityCheckCallbackInt();
  27948. }
  27949. void MessageManager::inactivityCheckCallbackInt() throw()
  27950. {
  27951. const unsigned int now = Time::getApproximateMillisecondCounter();
  27952. if (isInMessageDispatcher > 0
  27953. && lastMessageCounter == messageCounter
  27954. && timeBeforeWaitCursor > 0
  27955. && lastActivityCheckOkTime > 0
  27956. && ! ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  27957. {
  27958. if (now >= lastActivityCheckOkTime + timeBeforeWaitCursor
  27959. && ! needToGetRidOfWaitCursor)
  27960. {
  27961. // been in the same message call too long..
  27962. MouseCursor::showWaitCursor();
  27963. needToGetRidOfWaitCursor = true;
  27964. }
  27965. }
  27966. else
  27967. {
  27968. lastActivityCheckOkTime = now;
  27969. lastMessageCounter = messageCounter;
  27970. }
  27971. }
  27972. void MessageManager::delayWaitCursor() throw()
  27973. {
  27974. if (instance != 0)
  27975. {
  27976. instance->messageCounter++;
  27977. if (instance->needToGetRidOfWaitCursor)
  27978. {
  27979. instance->needToGetRidOfWaitCursor = false;
  27980. MouseCursor::hideWaitCursor();
  27981. }
  27982. }
  27983. }
  27984. void MessageManager::setTimeBeforeShowingWaitCursor (const int millisecs) throw()
  27985. {
  27986. // if this is a bit too small you'll get a lot of unwanted hourglass cursors..
  27987. jassert (millisecs <= 0 || millisecs > 200);
  27988. timeBeforeWaitCursor = millisecs;
  27989. if (millisecs > 0)
  27990. startTimer (millisecs / 2); // (see timerCallback() for explanation of this)
  27991. else
  27992. stopTimer();
  27993. }
  27994. void MessageManager::timerCallback()
  27995. {
  27996. // dummy callback - the message manager is just a Timer to ensure that there are always
  27997. // some events coming in - otherwise it'll show the egg-timer/beachball-of-death.
  27998. ++messageCounter;
  27999. }
  28000. int MessageManager::getTimeBeforeShowingWaitCursor() const throw()
  28001. {
  28002. return timeBeforeWaitCursor;
  28003. }
  28004. bool MessageManager::isThisTheMessageThread() const throw()
  28005. {
  28006. return Thread::getCurrentThreadId() == messageThreadId;
  28007. }
  28008. void MessageManager::setCurrentMessageThread (const int threadId) throw()
  28009. {
  28010. messageThreadId = threadId;
  28011. }
  28012. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  28013. {
  28014. return Thread::getCurrentThreadId() == currentLockingThreadId;
  28015. }
  28016. MessageManagerLock::MessageManagerLock() throw()
  28017. : locked (false)
  28018. {
  28019. if (MessageManager::instance != 0)
  28020. {
  28021. MessageManager::instance->messageDispatchLock.enter();
  28022. lastLockingThreadId = MessageManager::instance->currentLockingThreadId;
  28023. MessageManager::instance->currentLockingThreadId = Thread::getCurrentThreadId();
  28024. locked = true;
  28025. }
  28026. }
  28027. MessageManagerLock::MessageManagerLock (Thread* const thread) throw()
  28028. : locked (false)
  28029. {
  28030. jassert (thread != 0); // This will only work if you give it a valid thread!
  28031. if (MessageManager::instance != 0)
  28032. {
  28033. for (;;)
  28034. {
  28035. if (MessageManager::instance->messageDispatchLock.tryEnter())
  28036. {
  28037. locked = true;
  28038. lastLockingThreadId = MessageManager::instance->currentLockingThreadId;
  28039. MessageManager::instance->currentLockingThreadId = Thread::getCurrentThreadId();
  28040. break;
  28041. }
  28042. if (thread != 0 && thread->threadShouldExit())
  28043. break;
  28044. Thread::sleep (1);
  28045. }
  28046. }
  28047. }
  28048. MessageManagerLock::~MessageManagerLock() throw()
  28049. {
  28050. if (locked && MessageManager::instance != 0)
  28051. {
  28052. MessageManager::instance->currentLockingThreadId = lastLockingThreadId;
  28053. MessageManager::instance->messageDispatchLock.exit();
  28054. }
  28055. }
  28056. END_JUCE_NAMESPACE
  28057. /********* End of inlined file: juce_MessageManager.cpp *********/
  28058. /********* Start of inlined file: juce_MultiTimer.cpp *********/
  28059. BEGIN_JUCE_NAMESPACE
  28060. class InternalMultiTimerCallback : public Timer
  28061. {
  28062. public:
  28063. InternalMultiTimerCallback (const int timerId_, MultiTimer& owner_)
  28064. : timerId (timerId_),
  28065. owner (owner_)
  28066. {
  28067. }
  28068. ~InternalMultiTimerCallback()
  28069. {
  28070. }
  28071. void timerCallback()
  28072. {
  28073. owner.timerCallback (timerId);
  28074. }
  28075. const int timerId;
  28076. private:
  28077. MultiTimer& owner;
  28078. };
  28079. MultiTimer::MultiTimer() throw()
  28080. {
  28081. }
  28082. MultiTimer::MultiTimer (const MultiTimer&) throw()
  28083. {
  28084. }
  28085. MultiTimer::~MultiTimer()
  28086. {
  28087. const ScopedLock sl (timerListLock);
  28088. for (int i = timers.size(); --i >= 0;)
  28089. delete (InternalMultiTimerCallback*) timers.getUnchecked(i);
  28090. timers.clear();
  28091. }
  28092. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  28093. {
  28094. const ScopedLock sl (timerListLock);
  28095. for (int i = timers.size(); --i >= 0;)
  28096. {
  28097. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  28098. if (t->timerId == timerId)
  28099. {
  28100. t->startTimer (intervalInMilliseconds);
  28101. return;
  28102. }
  28103. }
  28104. InternalMultiTimerCallback* const newTimer = new InternalMultiTimerCallback (timerId, *this);
  28105. timers.add (newTimer);
  28106. newTimer->startTimer (intervalInMilliseconds);
  28107. }
  28108. void MultiTimer::stopTimer (const int timerId) throw()
  28109. {
  28110. const ScopedLock sl (timerListLock);
  28111. for (int i = timers.size(); --i >= 0;)
  28112. {
  28113. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  28114. if (t->timerId == timerId)
  28115. t->stopTimer();
  28116. }
  28117. }
  28118. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  28119. {
  28120. const ScopedLock sl (timerListLock);
  28121. for (int i = timers.size(); --i >= 0;)
  28122. {
  28123. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  28124. if (t->timerId == timerId)
  28125. return t->isTimerRunning();
  28126. }
  28127. return false;
  28128. }
  28129. int MultiTimer::getTimerInterval (const int timerId) const throw()
  28130. {
  28131. const ScopedLock sl (timerListLock);
  28132. for (int i = timers.size(); --i >= 0;)
  28133. {
  28134. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  28135. if (t->timerId == timerId)
  28136. return t->getTimerInterval();
  28137. }
  28138. return 0;
  28139. }
  28140. END_JUCE_NAMESPACE
  28141. /********* End of inlined file: juce_MultiTimer.cpp *********/
  28142. /********* Start of inlined file: juce_Timer.cpp *********/
  28143. BEGIN_JUCE_NAMESPACE
  28144. class InternalTimerThread : private Thread,
  28145. private MessageListener,
  28146. private DeletedAtShutdown,
  28147. private AsyncUpdater
  28148. {
  28149. private:
  28150. friend class Timer;
  28151. static InternalTimerThread* instance;
  28152. static CriticalSection lock;
  28153. Timer* volatile firstTimer;
  28154. bool volatile callbackNeeded;
  28155. InternalTimerThread (const InternalTimerThread&);
  28156. const InternalTimerThread& operator= (const InternalTimerThread&);
  28157. void addTimer (Timer* const t) throw()
  28158. {
  28159. #ifdef JUCE_DEBUG
  28160. Timer* tt = firstTimer;
  28161. while (tt != 0)
  28162. {
  28163. // trying to add a timer that's already here - shouldn't get to this point,
  28164. // so if you get this assertion, let me know!
  28165. jassert (tt != t);
  28166. tt = tt->next;
  28167. }
  28168. jassert (t->previous == 0 && t->next == 0);
  28169. #endif
  28170. Timer* i = firstTimer;
  28171. if (i == 0 || i->countdownMs > t->countdownMs)
  28172. {
  28173. t->next = firstTimer;
  28174. firstTimer = t;
  28175. }
  28176. else
  28177. {
  28178. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  28179. i = i->next;
  28180. jassert (i != 0);
  28181. t->next = i->next;
  28182. t->previous = i;
  28183. i->next = t;
  28184. }
  28185. if (t->next != 0)
  28186. t->next->previous = t;
  28187. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  28188. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  28189. notify();
  28190. }
  28191. void removeTimer (Timer* const t) throw()
  28192. {
  28193. #ifdef JUCE_DEBUG
  28194. Timer* tt = firstTimer;
  28195. bool found = false;
  28196. while (tt != 0)
  28197. {
  28198. if (tt == t)
  28199. {
  28200. found = true;
  28201. break;
  28202. }
  28203. tt = tt->next;
  28204. }
  28205. // trying to remove a timer that's not here - shouldn't get to this point,
  28206. // so if you get this assertion, let me know!
  28207. jassert (found);
  28208. #endif
  28209. if (t->previous != 0)
  28210. {
  28211. jassert (firstTimer != t);
  28212. t->previous->next = t->next;
  28213. }
  28214. else
  28215. {
  28216. jassert (firstTimer == t);
  28217. firstTimer = t->next;
  28218. }
  28219. if (t->next != 0)
  28220. t->next->previous = t->previous;
  28221. t->next = 0;
  28222. t->previous = 0;
  28223. }
  28224. void decrementAllCounters (const int numMillisecs) const
  28225. {
  28226. Timer* t = firstTimer;
  28227. while (t != 0)
  28228. {
  28229. t->countdownMs -= numMillisecs;
  28230. t = t->next;
  28231. }
  28232. }
  28233. void handleAsyncUpdate()
  28234. {
  28235. startThread (7);
  28236. }
  28237. public:
  28238. InternalTimerThread()
  28239. : Thread ("Juce Timer"),
  28240. firstTimer (0),
  28241. callbackNeeded (false)
  28242. {
  28243. triggerAsyncUpdate();
  28244. }
  28245. ~InternalTimerThread() throw()
  28246. {
  28247. stopThread (4000);
  28248. jassert (instance == this || instance == 0);
  28249. if (instance == this)
  28250. instance = 0;
  28251. }
  28252. void run()
  28253. {
  28254. uint32 lastTime = Time::getMillisecondCounter();
  28255. uint32 lastMessageManagerCallback = lastTime;
  28256. while (! threadShouldExit())
  28257. {
  28258. uint32 now = Time::getMillisecondCounter();
  28259. if (now <= lastTime)
  28260. {
  28261. wait (2);
  28262. continue;
  28263. }
  28264. const int elapsed = now - lastTime;
  28265. lastTime = now;
  28266. lock.enter();
  28267. decrementAllCounters (elapsed);
  28268. const int timeUntilFirstTimer = (firstTimer != 0) ? firstTimer->countdownMs
  28269. : 1000;
  28270. lock.exit();
  28271. if (timeUntilFirstTimer <= 0)
  28272. {
  28273. callbackNeeded = true;
  28274. postMessage (new Message());
  28275. // sometimes, our message could get discarded by the OS (particularly when running as an RTAS when the app has a modal loop),
  28276. // so this is how long to wait before assuming the message has been lost and trying again.
  28277. const uint32 messageDeliveryTimeout = now + 2000;
  28278. while (callbackNeeded)
  28279. {
  28280. wait (4);
  28281. if (threadShouldExit())
  28282. return;
  28283. now = Time::getMillisecondCounter();
  28284. if (now > lastMessageManagerCallback + 200)
  28285. {
  28286. lastMessageManagerCallback = now;
  28287. MessageManager::inactivityCheckCallback();
  28288. }
  28289. if (now > messageDeliveryTimeout)
  28290. break;
  28291. }
  28292. }
  28293. else
  28294. {
  28295. // don't wait for too long because running this loop also helps keep the
  28296. // Time::getApproximateMillisecondTimer value stay up-to-date
  28297. wait (jlimit (1, 50, timeUntilFirstTimer));
  28298. }
  28299. if (now > lastMessageManagerCallback + 200)
  28300. {
  28301. lastMessageManagerCallback = now;
  28302. MessageManager::inactivityCheckCallback();
  28303. }
  28304. }
  28305. }
  28306. void handleMessage (const Message&)
  28307. {
  28308. const ScopedLock sl (lock);
  28309. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  28310. {
  28311. Timer* const t = firstTimer;
  28312. t->countdownMs = t->periodMs;
  28313. removeTimer (t);
  28314. addTimer (t);
  28315. const ScopedUnlock ul (lock);
  28316. callbackNeeded = false;
  28317. JUCE_TRY
  28318. {
  28319. t->timerCallback();
  28320. }
  28321. JUCE_CATCH_EXCEPTION
  28322. }
  28323. callbackNeeded = false;
  28324. }
  28325. static void callAnyTimersSynchronously()
  28326. {
  28327. if (InternalTimerThread::instance != 0)
  28328. {
  28329. const Message m;
  28330. InternalTimerThread::instance->handleMessage (m);
  28331. }
  28332. }
  28333. static inline void add (Timer* const tim) throw()
  28334. {
  28335. if (instance == 0)
  28336. instance = new InternalTimerThread();
  28337. instance->addTimer (tim);
  28338. }
  28339. static inline void remove (Timer* const tim) throw()
  28340. {
  28341. if (instance != 0)
  28342. instance->removeTimer (tim);
  28343. }
  28344. static inline void resetCounter (Timer* const tim,
  28345. const int newCounter) throw()
  28346. {
  28347. if (instance != 0)
  28348. {
  28349. tim->countdownMs = newCounter;
  28350. tim->periodMs = newCounter;
  28351. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  28352. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  28353. {
  28354. instance->removeTimer (tim);
  28355. instance->addTimer (tim);
  28356. }
  28357. }
  28358. }
  28359. };
  28360. InternalTimerThread* InternalTimerThread::instance = 0;
  28361. CriticalSection InternalTimerThread::lock;
  28362. void juce_callAnyTimersSynchronously()
  28363. {
  28364. InternalTimerThread::callAnyTimersSynchronously();
  28365. }
  28366. #ifdef JUCE_DEBUG
  28367. static SortedSet <Timer*> activeTimers;
  28368. #endif
  28369. Timer::Timer() throw()
  28370. : countdownMs (0),
  28371. periodMs (0),
  28372. previous (0),
  28373. next (0)
  28374. {
  28375. #ifdef JUCE_DEBUG
  28376. activeTimers.add (this);
  28377. #endif
  28378. }
  28379. Timer::Timer (const Timer&) throw()
  28380. : countdownMs (0),
  28381. periodMs (0),
  28382. previous (0),
  28383. next (0)
  28384. {
  28385. #ifdef JUCE_DEBUG
  28386. activeTimers.add (this);
  28387. #endif
  28388. }
  28389. Timer::~Timer()
  28390. {
  28391. stopTimer();
  28392. #ifdef JUCE_DEBUG
  28393. activeTimers.removeValue (this);
  28394. #endif
  28395. }
  28396. void Timer::startTimer (const int interval) throw()
  28397. {
  28398. const ScopedLock sl (InternalTimerThread::lock);
  28399. #ifdef JUCE_DEBUG
  28400. // this isn't a valid object! Your timer might be a dangling pointer or something..
  28401. jassert (activeTimers.contains (this));
  28402. #endif
  28403. if (periodMs == 0)
  28404. {
  28405. countdownMs = interval;
  28406. periodMs = jmax (1, interval);
  28407. InternalTimerThread::add (this);
  28408. }
  28409. else
  28410. {
  28411. InternalTimerThread::resetCounter (this, interval);
  28412. }
  28413. }
  28414. void Timer::stopTimer() throw()
  28415. {
  28416. const ScopedLock sl (InternalTimerThread::lock);
  28417. #ifdef JUCE_DEBUG
  28418. // this isn't a valid object! Your timer might be a dangling pointer or something..
  28419. jassert (activeTimers.contains (this));
  28420. #endif
  28421. if (periodMs > 0)
  28422. {
  28423. InternalTimerThread::remove (this);
  28424. periodMs = 0;
  28425. }
  28426. }
  28427. END_JUCE_NAMESPACE
  28428. /********* End of inlined file: juce_Timer.cpp *********/
  28429. /********* Start of inlined file: juce_Component.cpp *********/
  28430. BEGIN_JUCE_NAMESPACE
  28431. Component* Component::componentUnderMouse = 0;
  28432. Component* Component::currentlyFocusedComponent = 0;
  28433. static Array <Component*> modalComponentStack (4), modalComponentReturnValueKeys (4);
  28434. static Array <int> modalReturnValues (4);
  28435. static const int customCommandMessage = 0x7fff0001;
  28436. static const int exitModalStateMessage = 0x7fff0002;
  28437. // these are also used by ComponentPeer
  28438. int64 juce_recentMouseDownTimes [4] = { 0, 0, 0, 0 };
  28439. int juce_recentMouseDownX [4] = { 0, 0, 0, 0 };
  28440. int juce_recentMouseDownY [4] = { 0, 0, 0, 0 };
  28441. Component* juce_recentMouseDownComponent [4] = { 0, 0, 0, 0 };
  28442. int juce_LastMousePosX = 0;
  28443. int juce_LastMousePosY = 0;
  28444. int juce_MouseClickCounter = 0;
  28445. bool juce_MouseHasMovedSignificantlySincePressed = false;
  28446. static int countMouseClicks() throw()
  28447. {
  28448. int numClicks = 0;
  28449. if (juce_recentMouseDownTimes[0] != 0)
  28450. {
  28451. if (! juce_MouseHasMovedSignificantlySincePressed)
  28452. ++numClicks;
  28453. for (int i = 1; i < numElementsInArray (juce_recentMouseDownTimes); ++i)
  28454. {
  28455. if (juce_recentMouseDownTimes[0] - juce_recentMouseDownTimes [i]
  28456. < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  28457. && abs (juce_recentMouseDownX[0] - juce_recentMouseDownX[i]) < 8
  28458. && abs (juce_recentMouseDownY[0] - juce_recentMouseDownY[i]) < 8
  28459. && juce_recentMouseDownComponent[0] == juce_recentMouseDownComponent [i])
  28460. {
  28461. ++numClicks;
  28462. }
  28463. else
  28464. {
  28465. break;
  28466. }
  28467. }
  28468. }
  28469. return numClicks;
  28470. }
  28471. static int unboundedMouseOffsetX = 0;
  28472. static int unboundedMouseOffsetY = 0;
  28473. static bool isUnboundedMouseModeOn = false;
  28474. static bool isCursorVisibleUntilOffscreen;
  28475. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  28476. static uint32 nextComponentUID = 0;
  28477. Component::Component() throw()
  28478. : parentComponent_ (0),
  28479. componentUID (++nextComponentUID),
  28480. numDeepMouseListeners (0),
  28481. childComponentList_ (16),
  28482. lookAndFeel_ (0),
  28483. effect_ (0),
  28484. bufferedImage_ (0),
  28485. mouseListeners_ (0),
  28486. keyListeners_ (0),
  28487. componentListeners_ (0),
  28488. propertySet_ (0),
  28489. componentFlags_ (0)
  28490. {
  28491. }
  28492. Component::Component (const String& name) throw()
  28493. : componentName_ (name),
  28494. parentComponent_ (0),
  28495. componentUID (++nextComponentUID),
  28496. numDeepMouseListeners (0),
  28497. childComponentList_ (16),
  28498. lookAndFeel_ (0),
  28499. effect_ (0),
  28500. bufferedImage_ (0),
  28501. mouseListeners_ (0),
  28502. keyListeners_ (0),
  28503. componentListeners_ (0),
  28504. propertySet_ (0),
  28505. componentFlags_ (0)
  28506. {
  28507. }
  28508. Component::~Component()
  28509. {
  28510. if (parentComponent_ != 0)
  28511. {
  28512. parentComponent_->removeChildComponent (this);
  28513. }
  28514. else if ((currentlyFocusedComponent == this)
  28515. || isParentOf (currentlyFocusedComponent))
  28516. {
  28517. giveAwayFocus();
  28518. }
  28519. if (componentUnderMouse == this)
  28520. componentUnderMouse = 0;
  28521. if (flags.hasHeavyweightPeerFlag)
  28522. removeFromDesktop();
  28523. modalComponentStack.removeValue (this);
  28524. for (int i = childComponentList_.size(); --i >= 0;)
  28525. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  28526. delete bufferedImage_;
  28527. delete mouseListeners_;
  28528. delete keyListeners_;
  28529. delete componentListeners_;
  28530. delete propertySet_;
  28531. }
  28532. void Component::setName (const String& name)
  28533. {
  28534. // if component methods are being called from threads other than the message
  28535. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28536. checkMessageManagerIsLocked
  28537. if (componentName_ != name)
  28538. {
  28539. componentName_ = name;
  28540. if (flags.hasHeavyweightPeerFlag)
  28541. {
  28542. ComponentPeer* const peer = getPeer();
  28543. jassert (peer != 0);
  28544. if (peer != 0)
  28545. peer->setTitle (name);
  28546. }
  28547. if (componentListeners_ != 0)
  28548. {
  28549. const ComponentDeletionWatcher deletionChecker (this);
  28550. for (int i = componentListeners_->size(); --i >= 0;)
  28551. {
  28552. ((ComponentListener*) componentListeners_->getUnchecked (i))
  28553. ->componentNameChanged (*this);
  28554. if (deletionChecker.hasBeenDeleted())
  28555. return;
  28556. i = jmin (i, componentListeners_->size());
  28557. }
  28558. }
  28559. }
  28560. }
  28561. void Component::setVisible (bool shouldBeVisible)
  28562. {
  28563. if (flags.visibleFlag != shouldBeVisible)
  28564. {
  28565. // if component methods are being called from threads other than the message
  28566. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28567. checkMessageManagerIsLocked
  28568. const ComponentDeletionWatcher deletionChecker (this);
  28569. flags.visibleFlag = shouldBeVisible;
  28570. internalRepaint (0, 0, getWidth(), getHeight());
  28571. sendFakeMouseMove();
  28572. if (! shouldBeVisible)
  28573. {
  28574. if (currentlyFocusedComponent == this
  28575. || isParentOf (currentlyFocusedComponent))
  28576. {
  28577. if (parentComponent_ != 0)
  28578. parentComponent_->grabKeyboardFocus();
  28579. else
  28580. giveAwayFocus();
  28581. }
  28582. }
  28583. sendVisibilityChangeMessage();
  28584. if ((! deletionChecker.hasBeenDeleted()) && flags.hasHeavyweightPeerFlag)
  28585. {
  28586. ComponentPeer* const peer = getPeer();
  28587. jassert (peer != 0);
  28588. if (peer != 0)
  28589. {
  28590. peer->setVisible (shouldBeVisible);
  28591. internalHierarchyChanged();
  28592. }
  28593. }
  28594. }
  28595. }
  28596. void Component::visibilityChanged()
  28597. {
  28598. }
  28599. void Component::sendVisibilityChangeMessage()
  28600. {
  28601. const ComponentDeletionWatcher deletionChecker (this);
  28602. visibilityChanged();
  28603. if ((! deletionChecker.hasBeenDeleted()) && componentListeners_ != 0)
  28604. {
  28605. for (int i = componentListeners_->size(); --i >= 0;)
  28606. {
  28607. ((ComponentListener*) componentListeners_->getUnchecked (i))
  28608. ->componentVisibilityChanged (*this);
  28609. if (deletionChecker.hasBeenDeleted())
  28610. return;
  28611. i = jmin (i, componentListeners_->size());
  28612. }
  28613. }
  28614. }
  28615. bool Component::isShowing() const throw()
  28616. {
  28617. if (flags.visibleFlag)
  28618. {
  28619. if (parentComponent_ != 0)
  28620. {
  28621. return parentComponent_->isShowing();
  28622. }
  28623. else
  28624. {
  28625. const ComponentPeer* const peer = getPeer();
  28626. return peer != 0 && ! peer->isMinimised();
  28627. }
  28628. }
  28629. return false;
  28630. }
  28631. class FadeOutProxyComponent : public Component,
  28632. public Timer
  28633. {
  28634. public:
  28635. FadeOutProxyComponent (Component* comp,
  28636. const int fadeLengthMs,
  28637. const int deltaXToMove,
  28638. const int deltaYToMove,
  28639. const float scaleFactorAtEnd)
  28640. : lastTime (0),
  28641. alpha (1.0f),
  28642. scale (1.0f)
  28643. {
  28644. image = comp->createComponentSnapshot (Rectangle (0, 0, comp->getWidth(), comp->getHeight()));
  28645. setBounds (comp->getBounds());
  28646. comp->getParentComponent()->addAndMakeVisible (this);
  28647. toBehind (comp);
  28648. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  28649. centreX = comp->getX() + comp->getWidth() * 0.5f;
  28650. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  28651. centreY = comp->getY() + comp->getHeight() * 0.5f;
  28652. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  28653. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  28654. setInterceptsMouseClicks (false, false);
  28655. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  28656. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  28657. }
  28658. ~FadeOutProxyComponent()
  28659. {
  28660. delete image;
  28661. }
  28662. void paint (Graphics& g)
  28663. {
  28664. g.setOpacity (alpha);
  28665. g.drawImage (image,
  28666. 0, 0, getWidth(), getHeight(),
  28667. 0, 0, image->getWidth(), image->getHeight());
  28668. }
  28669. void timerCallback()
  28670. {
  28671. const uint32 now = Time::getMillisecondCounter();
  28672. if (lastTime == 0)
  28673. lastTime = now;
  28674. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  28675. lastTime = now;
  28676. alpha += alphaChangePerMs * msPassed;
  28677. if (alpha > 0)
  28678. {
  28679. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  28680. {
  28681. centreX += xChangePerMs * msPassed;
  28682. centreY += yChangePerMs * msPassed;
  28683. scale += scaleChangePerMs * msPassed;
  28684. const int w = roundFloatToInt (image->getWidth() * scale);
  28685. const int h = roundFloatToInt (image->getHeight() * scale);
  28686. setBounds (roundFloatToInt (centreX) - w / 2,
  28687. roundFloatToInt (centreY) - h / 2,
  28688. w, h);
  28689. }
  28690. repaint();
  28691. }
  28692. else
  28693. {
  28694. delete this;
  28695. }
  28696. }
  28697. juce_UseDebuggingNewOperator
  28698. private:
  28699. Image* image;
  28700. uint32 lastTime;
  28701. float alpha, alphaChangePerMs;
  28702. float centreX, xChangePerMs;
  28703. float centreY, yChangePerMs;
  28704. float scale, scaleChangePerMs;
  28705. FadeOutProxyComponent (const FadeOutProxyComponent&);
  28706. const FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  28707. };
  28708. void Component::fadeOutComponent (const int millisecondsToFade,
  28709. const int deltaXToMove,
  28710. const int deltaYToMove,
  28711. const float scaleFactorAtEnd)
  28712. {
  28713. //xxx won't work for comps without parents
  28714. if (isShowing() && millisecondsToFade > 0)
  28715. new FadeOutProxyComponent (this, millisecondsToFade,
  28716. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  28717. setVisible (false);
  28718. }
  28719. bool Component::isValidComponent() const throw()
  28720. {
  28721. return (this != 0) && isValidMessageListener();
  28722. }
  28723. void* Component::getWindowHandle() const throw()
  28724. {
  28725. const ComponentPeer* const peer = getPeer();
  28726. if (peer != 0)
  28727. return peer->getNativeHandle();
  28728. return 0;
  28729. }
  28730. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  28731. {
  28732. // if component methods are being called from threads other than the message
  28733. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28734. checkMessageManagerIsLocked
  28735. if (! isOpaque())
  28736. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  28737. int currentStyleFlags = 0;
  28738. // don't use getPeer(), so that we only get the peer that's specifically
  28739. // for this comp, and not for one of its parents.
  28740. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  28741. if (peer != 0)
  28742. currentStyleFlags = peer->getStyleFlags();
  28743. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  28744. {
  28745. const ComponentDeletionWatcher deletionChecker (this);
  28746. #if JUCE_LINUX
  28747. // it's wise to give the component a non-zero size before
  28748. // putting it on the desktop, as X windows get confused by this, and
  28749. // a (1, 1) minimum size is enforced here.
  28750. setSize (jmax (1, getWidth()),
  28751. jmax (1, getHeight()));
  28752. #endif
  28753. int x = 0, y = 0;
  28754. relativePositionToGlobal (x, y);
  28755. bool wasFullscreen = false;
  28756. bool wasMinimised = false;
  28757. ComponentBoundsConstrainer* currentConstainer = 0;
  28758. Rectangle oldNonFullScreenBounds;
  28759. if (peer != 0)
  28760. {
  28761. wasFullscreen = peer->isFullScreen();
  28762. wasMinimised = peer->isMinimised();
  28763. currentConstainer = peer->getConstrainer();
  28764. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  28765. removeFromDesktop();
  28766. }
  28767. if (parentComponent_ != 0)
  28768. parentComponent_->removeChildComponent (this);
  28769. if (! deletionChecker.hasBeenDeleted())
  28770. {
  28771. flags.hasHeavyweightPeerFlag = true;
  28772. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  28773. Desktop::getInstance().addDesktopComponent (this);
  28774. bounds_.setPosition (x, y);
  28775. peer->setBounds (x, y, getWidth(), getHeight(), false);
  28776. peer->setVisible (isVisible());
  28777. if (wasFullscreen)
  28778. {
  28779. peer->setFullScreen (true);
  28780. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  28781. }
  28782. if (wasMinimised)
  28783. peer->setMinimised (true);
  28784. if (isAlwaysOnTop())
  28785. peer->setAlwaysOnTop (true);
  28786. peer->setConstrainer (currentConstainer);
  28787. repaint();
  28788. }
  28789. internalHierarchyChanged();
  28790. }
  28791. }
  28792. void Component::removeFromDesktop()
  28793. {
  28794. // if component methods are being called from threads other than the message
  28795. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28796. checkMessageManagerIsLocked
  28797. if (flags.hasHeavyweightPeerFlag)
  28798. {
  28799. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  28800. flags.hasHeavyweightPeerFlag = false;
  28801. jassert (peer != 0);
  28802. delete peer;
  28803. Desktop::getInstance().removeDesktopComponent (this);
  28804. }
  28805. }
  28806. bool Component::isOnDesktop() const throw()
  28807. {
  28808. return flags.hasHeavyweightPeerFlag;
  28809. }
  28810. void Component::userTriedToCloseWindow()
  28811. {
  28812. /* This means that the user's trying to get rid of your window with the 'close window' system
  28813. menu option (on windows) or possibly the task manager - you should really handle this
  28814. and delete or hide your component in an appropriate way.
  28815. If you want to ignore the event and don't want to trigger this assertion, just override
  28816. this method and do nothing.
  28817. */
  28818. jassertfalse
  28819. }
  28820. void Component::minimisationStateChanged (bool)
  28821. {
  28822. }
  28823. void Component::setOpaque (const bool shouldBeOpaque) throw()
  28824. {
  28825. if (shouldBeOpaque != flags.opaqueFlag)
  28826. {
  28827. flags.opaqueFlag = shouldBeOpaque;
  28828. if (flags.hasHeavyweightPeerFlag)
  28829. {
  28830. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  28831. if (peer != 0)
  28832. {
  28833. // to make it recreate the heavyweight window
  28834. addToDesktop (peer->getStyleFlags());
  28835. }
  28836. }
  28837. repaint();
  28838. }
  28839. }
  28840. bool Component::isOpaque() const throw()
  28841. {
  28842. return flags.opaqueFlag;
  28843. }
  28844. void Component::setBufferedToImage (const bool shouldBeBuffered) throw()
  28845. {
  28846. if (shouldBeBuffered != flags.bufferToImageFlag)
  28847. {
  28848. deleteAndZero (bufferedImage_);
  28849. flags.bufferToImageFlag = shouldBeBuffered;
  28850. }
  28851. }
  28852. void Component::toFront (const bool setAsForeground)
  28853. {
  28854. // if component methods are being called from threads other than the message
  28855. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28856. checkMessageManagerIsLocked
  28857. if (flags.hasHeavyweightPeerFlag)
  28858. {
  28859. ComponentPeer* const peer = getPeer();
  28860. if (peer != 0)
  28861. {
  28862. peer->toFront (setAsForeground);
  28863. if (setAsForeground && ! hasKeyboardFocus (true))
  28864. grabKeyboardFocus();
  28865. }
  28866. }
  28867. else if (parentComponent_ != 0)
  28868. {
  28869. if (parentComponent_->childComponentList_.getLast() != this)
  28870. {
  28871. const int index = parentComponent_->childComponentList_.indexOf (this);
  28872. if (index >= 0)
  28873. {
  28874. int insertIndex = -1;
  28875. if (! flags.alwaysOnTopFlag)
  28876. {
  28877. insertIndex = parentComponent_->childComponentList_.size() - 1;
  28878. while (insertIndex > 0
  28879. && parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  28880. {
  28881. --insertIndex;
  28882. }
  28883. }
  28884. if (index != insertIndex)
  28885. {
  28886. parentComponent_->childComponentList_.move (index, insertIndex);
  28887. sendFakeMouseMove();
  28888. repaintParent();
  28889. }
  28890. }
  28891. }
  28892. if (setAsForeground)
  28893. {
  28894. internalBroughtToFront();
  28895. grabKeyboardFocus();
  28896. }
  28897. }
  28898. }
  28899. void Component::toBehind (Component* const other)
  28900. {
  28901. if (other != 0)
  28902. {
  28903. // the two components must belong to the same parent..
  28904. jassert (parentComponent_ == other->parentComponent_);
  28905. if (parentComponent_ != 0)
  28906. {
  28907. const int index = parentComponent_->childComponentList_.indexOf (this);
  28908. int otherIndex = parentComponent_->childComponentList_.indexOf (other);
  28909. if (index >= 0
  28910. && otherIndex >= 0
  28911. && index != otherIndex - 1
  28912. && other != this)
  28913. {
  28914. if (index < otherIndex)
  28915. --otherIndex;
  28916. parentComponent_->childComponentList_.move (index, otherIndex);
  28917. sendFakeMouseMove();
  28918. repaintParent();
  28919. }
  28920. }
  28921. else if (isOnDesktop())
  28922. {
  28923. jassert (other->isOnDesktop());
  28924. if (other->isOnDesktop())
  28925. {
  28926. ComponentPeer* const us = getPeer();
  28927. ComponentPeer* const them = other->getPeer();
  28928. jassert (us != 0 && them != 0);
  28929. if (us != 0 && them != 0)
  28930. us->toBehind (them);
  28931. }
  28932. }
  28933. }
  28934. }
  28935. void Component::toBack()
  28936. {
  28937. if (isOnDesktop())
  28938. {
  28939. jassertfalse //xxx need to add this to native window
  28940. }
  28941. else if (parentComponent_ != 0
  28942. && parentComponent_->childComponentList_.getFirst() != this)
  28943. {
  28944. const int index = parentComponent_->childComponentList_.indexOf (this);
  28945. if (index > 0)
  28946. {
  28947. int insertIndex = 0;
  28948. if (flags.alwaysOnTopFlag)
  28949. {
  28950. while (insertIndex < parentComponent_->childComponentList_.size()
  28951. && ! parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  28952. {
  28953. ++insertIndex;
  28954. }
  28955. }
  28956. if (index != insertIndex)
  28957. {
  28958. parentComponent_->childComponentList_.move (index, insertIndex);
  28959. sendFakeMouseMove();
  28960. repaintParent();
  28961. }
  28962. }
  28963. }
  28964. }
  28965. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  28966. {
  28967. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  28968. {
  28969. flags.alwaysOnTopFlag = shouldStayOnTop;
  28970. if (isOnDesktop())
  28971. {
  28972. ComponentPeer* const peer = getPeer();
  28973. jassert (peer != 0);
  28974. if (peer != 0)
  28975. {
  28976. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  28977. {
  28978. // some kinds of peer can't change their always-on-top status, so
  28979. // for these, we'll need to create a new window
  28980. const int oldFlags = peer->getStyleFlags();
  28981. removeFromDesktop();
  28982. addToDesktop (oldFlags);
  28983. }
  28984. }
  28985. }
  28986. if (shouldStayOnTop)
  28987. toFront (false);
  28988. internalHierarchyChanged();
  28989. }
  28990. }
  28991. bool Component::isAlwaysOnTop() const throw()
  28992. {
  28993. return flags.alwaysOnTopFlag;
  28994. }
  28995. int Component::proportionOfWidth (const float proportion) const throw()
  28996. {
  28997. return roundDoubleToInt (proportion * bounds_.getWidth());
  28998. }
  28999. int Component::proportionOfHeight (const float proportion) const throw()
  29000. {
  29001. return roundDoubleToInt (proportion * bounds_.getHeight());
  29002. }
  29003. int Component::getParentWidth() const throw()
  29004. {
  29005. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  29006. : getParentMonitorArea().getWidth();
  29007. }
  29008. int Component::getParentHeight() const throw()
  29009. {
  29010. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  29011. : getParentMonitorArea().getHeight();
  29012. }
  29013. int Component::getScreenX() const throw()
  29014. {
  29015. return (parentComponent_ != 0) ? parentComponent_->getScreenX() + getX()
  29016. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenX()
  29017. : getX());
  29018. }
  29019. int Component::getScreenY() const throw()
  29020. {
  29021. return (parentComponent_ != 0) ? parentComponent_->getScreenY() + getY()
  29022. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenY()
  29023. : getY());
  29024. }
  29025. void Component::relativePositionToGlobal (int& x, int& y) const throw()
  29026. {
  29027. const Component* c = this;
  29028. do
  29029. {
  29030. if (c->flags.hasHeavyweightPeerFlag)
  29031. {
  29032. c->getPeer()->relativePositionToGlobal (x, y);
  29033. break;
  29034. }
  29035. x += c->getX();
  29036. y += c->getY();
  29037. c = c->parentComponent_;
  29038. }
  29039. while (c != 0);
  29040. }
  29041. void Component::globalPositionToRelative (int& x, int& y) const throw()
  29042. {
  29043. if (flags.hasHeavyweightPeerFlag)
  29044. {
  29045. getPeer()->globalPositionToRelative (x, y);
  29046. }
  29047. else
  29048. {
  29049. if (parentComponent_ != 0)
  29050. parentComponent_->globalPositionToRelative (x, y);
  29051. x -= getX();
  29052. y -= getY();
  29053. }
  29054. }
  29055. void Component::relativePositionToOtherComponent (const Component* const targetComponent, int& x, int& y) const throw()
  29056. {
  29057. if (targetComponent != 0)
  29058. {
  29059. const Component* c = this;
  29060. do
  29061. {
  29062. if (c == targetComponent)
  29063. return;
  29064. if (c->flags.hasHeavyweightPeerFlag)
  29065. {
  29066. c->getPeer()->relativePositionToGlobal (x, y);
  29067. break;
  29068. }
  29069. x += c->getX();
  29070. y += c->getY();
  29071. c = c->parentComponent_;
  29072. }
  29073. while (c != 0);
  29074. targetComponent->globalPositionToRelative (x, y);
  29075. }
  29076. }
  29077. void Component::setBounds (int x, int y, int w, int h)
  29078. {
  29079. // if component methods are being called from threads other than the message
  29080. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29081. checkMessageManagerIsLocked
  29082. if (w < 0) w = 0;
  29083. if (h < 0) h = 0;
  29084. const bool wasResized = (getWidth() != w || getHeight() != h);
  29085. const bool wasMoved = (getX() != x || getY() != y);
  29086. #ifdef JUCE_DEBUG
  29087. // It's a very bad idea to try to resize a window during its paint() method!
  29088. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  29089. #endif
  29090. if (wasMoved || wasResized)
  29091. {
  29092. if (flags.visibleFlag)
  29093. {
  29094. // send a fake mouse move to trigger enter/exit messages if needed..
  29095. sendFakeMouseMove();
  29096. if (! flags.hasHeavyweightPeerFlag)
  29097. repaintParent();
  29098. }
  29099. bounds_.setBounds (x, y, w, h);
  29100. if (wasResized)
  29101. repaint();
  29102. else if (! flags.hasHeavyweightPeerFlag)
  29103. repaintParent();
  29104. if (flags.hasHeavyweightPeerFlag)
  29105. {
  29106. ComponentPeer* const peer = getPeer();
  29107. if (peer != 0)
  29108. {
  29109. if (wasMoved && wasResized)
  29110. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  29111. else if (wasMoved)
  29112. peer->setPosition (getX(), getY());
  29113. else if (wasResized)
  29114. peer->setSize (getWidth(), getHeight());
  29115. }
  29116. }
  29117. sendMovedResizedMessages (wasMoved, wasResized);
  29118. }
  29119. }
  29120. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  29121. {
  29122. JUCE_TRY
  29123. {
  29124. if (wasMoved)
  29125. moved();
  29126. if (wasResized)
  29127. {
  29128. resized();
  29129. for (int i = childComponentList_.size(); --i >= 0;)
  29130. {
  29131. childComponentList_.getUnchecked(i)->parentSizeChanged();
  29132. i = jmin (i, childComponentList_.size());
  29133. }
  29134. }
  29135. if (parentComponent_ != 0)
  29136. parentComponent_->childBoundsChanged (this);
  29137. if (componentListeners_ != 0)
  29138. {
  29139. const ComponentDeletionWatcher deletionChecker (this);
  29140. for (int i = componentListeners_->size(); --i >= 0;)
  29141. {
  29142. ((ComponentListener*) componentListeners_->getUnchecked (i))
  29143. ->componentMovedOrResized (*this, wasMoved, wasResized);
  29144. if (deletionChecker.hasBeenDeleted())
  29145. return;
  29146. i = jmin (i, componentListeners_->size());
  29147. }
  29148. }
  29149. }
  29150. JUCE_CATCH_EXCEPTION
  29151. }
  29152. void Component::setSize (const int w, const int h)
  29153. {
  29154. setBounds (getX(), getY(), w, h);
  29155. }
  29156. void Component::setTopLeftPosition (const int x, const int y)
  29157. {
  29158. setBounds (x, y, getWidth(), getHeight());
  29159. }
  29160. void Component::setTopRightPosition (const int x, const int y)
  29161. {
  29162. setTopLeftPosition (x - getWidth(), y);
  29163. }
  29164. void Component::setBounds (const Rectangle& r)
  29165. {
  29166. setBounds (r.getX(),
  29167. r.getY(),
  29168. r.getWidth(),
  29169. r.getHeight());
  29170. }
  29171. void Component::setBoundsRelative (const float x, const float y,
  29172. const float w, const float h)
  29173. {
  29174. const int pw = getParentWidth();
  29175. const int ph = getParentHeight();
  29176. setBounds (roundFloatToInt (x * pw),
  29177. roundFloatToInt (y * ph),
  29178. roundFloatToInt (w * pw),
  29179. roundFloatToInt (h * ph));
  29180. }
  29181. void Component::setCentrePosition (const int x, const int y)
  29182. {
  29183. setTopLeftPosition (x - getWidth() / 2,
  29184. y - getHeight() / 2);
  29185. }
  29186. void Component::setCentreRelative (const float x, const float y)
  29187. {
  29188. setCentrePosition (roundFloatToInt (getParentWidth() * x),
  29189. roundFloatToInt (getParentHeight() * y));
  29190. }
  29191. void Component::centreWithSize (const int width, const int height)
  29192. {
  29193. setBounds ((getParentWidth() - width) / 2,
  29194. (getParentHeight() - height) / 2,
  29195. width,
  29196. height);
  29197. }
  29198. void Component::setBoundsInset (const BorderSize& borders)
  29199. {
  29200. setBounds (borders.getLeft(),
  29201. borders.getTop(),
  29202. getParentWidth() - (borders.getLeftAndRight()),
  29203. getParentHeight() - (borders.getTopAndBottom()));
  29204. }
  29205. void Component::setBoundsToFit (int x, int y, int width, int height,
  29206. const Justification& justification,
  29207. const bool onlyReduceInSize)
  29208. {
  29209. // it's no good calling this method unless both the component and
  29210. // target rectangle have a finite size.
  29211. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  29212. if (getWidth() > 0 && getHeight() > 0
  29213. && width > 0 && height > 0)
  29214. {
  29215. int newW, newH;
  29216. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  29217. {
  29218. newW = getWidth();
  29219. newH = getHeight();
  29220. }
  29221. else
  29222. {
  29223. const double imageRatio = getHeight() / (double) getWidth();
  29224. const double targetRatio = height / (double) width;
  29225. if (imageRatio <= targetRatio)
  29226. {
  29227. newW = width;
  29228. newH = jmin (height, roundDoubleToInt (newW * imageRatio));
  29229. }
  29230. else
  29231. {
  29232. newH = height;
  29233. newW = jmin (width, roundDoubleToInt (newH / imageRatio));
  29234. }
  29235. }
  29236. if (newW > 0 && newH > 0)
  29237. {
  29238. int newX, newY;
  29239. justification.applyToRectangle (newX, newY, newW, newH,
  29240. x, y, width, height);
  29241. setBounds (newX, newY, newW, newH);
  29242. }
  29243. }
  29244. }
  29245. bool Component::hitTest (int x, int y)
  29246. {
  29247. if (! flags.ignoresMouseClicksFlag)
  29248. return true;
  29249. if (flags.allowChildMouseClicksFlag)
  29250. {
  29251. for (int i = getNumChildComponents(); --i >= 0;)
  29252. {
  29253. Component* const c = getChildComponent (i);
  29254. if (c->isVisible()
  29255. && c->bounds_.contains (x, y)
  29256. && c->hitTest (x - c->getX(),
  29257. y - c->getY()))
  29258. {
  29259. return true;
  29260. }
  29261. }
  29262. }
  29263. return false;
  29264. }
  29265. void Component::setInterceptsMouseClicks (const bool allowClicks,
  29266. const bool allowClicksOnChildComponents) throw()
  29267. {
  29268. flags.ignoresMouseClicksFlag = ! allowClicks;
  29269. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  29270. }
  29271. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  29272. bool& allowsClicksOnChildComponents) const throw()
  29273. {
  29274. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  29275. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  29276. }
  29277. bool Component::contains (const int x, const int y)
  29278. {
  29279. if (((unsigned int) x) < (unsigned int) getWidth()
  29280. && ((unsigned int) y) < (unsigned int) getHeight()
  29281. && hitTest (x, y))
  29282. {
  29283. if (parentComponent_ != 0)
  29284. {
  29285. return parentComponent_->contains (x + getX(),
  29286. y + getY());
  29287. }
  29288. else if (flags.hasHeavyweightPeerFlag)
  29289. {
  29290. const ComponentPeer* const peer = getPeer();
  29291. if (peer != 0)
  29292. return peer->contains (x, y, true);
  29293. }
  29294. }
  29295. return false;
  29296. }
  29297. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  29298. {
  29299. if (! contains (x, y))
  29300. return false;
  29301. Component* p = this;
  29302. while (p->parentComponent_ != 0)
  29303. {
  29304. x += p->getX();
  29305. y += p->getY();
  29306. p = p->parentComponent_;
  29307. }
  29308. const Component* const c = p->getComponentAt (x, y);
  29309. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  29310. }
  29311. Component* Component::getComponentAt (const int x, const int y)
  29312. {
  29313. if (flags.visibleFlag
  29314. && ((unsigned int) x) < (unsigned int) getWidth()
  29315. && ((unsigned int) y) < (unsigned int) getHeight()
  29316. && hitTest (x, y))
  29317. {
  29318. for (int i = childComponentList_.size(); --i >= 0;)
  29319. {
  29320. Component* const child = childComponentList_.getUnchecked(i);
  29321. Component* const c = child->getComponentAt (x - child->getX(),
  29322. y - child->getY());
  29323. if (c != 0)
  29324. return c;
  29325. }
  29326. return this;
  29327. }
  29328. return 0;
  29329. }
  29330. void Component::addChildComponent (Component* const child, int zOrder)
  29331. {
  29332. // if component methods are being called from threads other than the message
  29333. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29334. checkMessageManagerIsLocked
  29335. if (child != 0 && child->parentComponent_ != this)
  29336. {
  29337. if (child->parentComponent_ != 0)
  29338. child->parentComponent_->removeChildComponent (child);
  29339. else
  29340. child->removeFromDesktop();
  29341. child->parentComponent_ = this;
  29342. if (child->isVisible())
  29343. child->repaintParent();
  29344. if (! child->isAlwaysOnTop())
  29345. {
  29346. if (zOrder < 0 || zOrder > childComponentList_.size())
  29347. zOrder = childComponentList_.size();
  29348. while (zOrder > 0)
  29349. {
  29350. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  29351. break;
  29352. --zOrder;
  29353. }
  29354. }
  29355. childComponentList_.insert (zOrder, child);
  29356. child->internalHierarchyChanged();
  29357. internalChildrenChanged();
  29358. }
  29359. }
  29360. void Component::addAndMakeVisible (Component* const child, int zOrder)
  29361. {
  29362. if (child != 0)
  29363. {
  29364. child->setVisible (true);
  29365. addChildComponent (child, zOrder);
  29366. }
  29367. }
  29368. void Component::removeChildComponent (Component* const child)
  29369. {
  29370. removeChildComponent (childComponentList_.indexOf (child));
  29371. }
  29372. Component* Component::removeChildComponent (const int index)
  29373. {
  29374. // if component methods are being called from threads other than the message
  29375. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29376. checkMessageManagerIsLocked
  29377. Component* const child = childComponentList_ [index];
  29378. if (child != 0)
  29379. {
  29380. sendFakeMouseMove();
  29381. child->repaintParent();
  29382. childComponentList_.remove (index);
  29383. child->parentComponent_ = 0;
  29384. JUCE_TRY
  29385. {
  29386. if ((currentlyFocusedComponent == child)
  29387. || child->isParentOf (currentlyFocusedComponent))
  29388. {
  29389. // get rid first to force the grabKeyboardFocus to change to us.
  29390. giveAwayFocus();
  29391. grabKeyboardFocus();
  29392. }
  29393. }
  29394. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  29395. catch (const std::exception& e)
  29396. {
  29397. currentlyFocusedComponent = 0;
  29398. Desktop::getInstance().triggerFocusCallback();
  29399. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  29400. }
  29401. catch (...)
  29402. {
  29403. currentlyFocusedComponent = 0;
  29404. Desktop::getInstance().triggerFocusCallback();
  29405. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  29406. }
  29407. #endif
  29408. child->internalHierarchyChanged();
  29409. internalChildrenChanged();
  29410. }
  29411. return child;
  29412. }
  29413. void Component::removeAllChildren()
  29414. {
  29415. for (int i = childComponentList_.size(); --i >= 0;)
  29416. removeChildComponent (i);
  29417. }
  29418. void Component::deleteAllChildren()
  29419. {
  29420. for (int i = childComponentList_.size(); --i >= 0;)
  29421. delete (removeChildComponent (i));
  29422. }
  29423. int Component::getNumChildComponents() const throw()
  29424. {
  29425. return childComponentList_.size();
  29426. }
  29427. Component* Component::getChildComponent (const int index) const throw()
  29428. {
  29429. return childComponentList_ [index];
  29430. }
  29431. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  29432. {
  29433. return childComponentList_.indexOf (const_cast <Component*> (child));
  29434. }
  29435. Component* Component::getTopLevelComponent() const throw()
  29436. {
  29437. const Component* comp = this;
  29438. while (comp->parentComponent_ != 0)
  29439. comp = comp->parentComponent_;
  29440. return (Component*) comp;
  29441. }
  29442. bool Component::isParentOf (const Component* possibleChild) const throw()
  29443. {
  29444. while (possibleChild->isValidComponent())
  29445. {
  29446. possibleChild = possibleChild->parentComponent_;
  29447. if (possibleChild == this)
  29448. return true;
  29449. }
  29450. return false;
  29451. }
  29452. void Component::parentHierarchyChanged()
  29453. {
  29454. }
  29455. void Component::childrenChanged()
  29456. {
  29457. }
  29458. void Component::internalChildrenChanged()
  29459. {
  29460. const ComponentDeletionWatcher deletionChecker (this);
  29461. const bool hasListeners = componentListeners_ != 0;
  29462. childrenChanged();
  29463. if (hasListeners)
  29464. {
  29465. if (deletionChecker.hasBeenDeleted())
  29466. return;
  29467. for (int i = componentListeners_->size(); --i >= 0;)
  29468. {
  29469. ((ComponentListener*) componentListeners_->getUnchecked (i))
  29470. ->componentChildrenChanged (*this);
  29471. if (deletionChecker.hasBeenDeleted())
  29472. return;
  29473. i = jmin (i, componentListeners_->size());
  29474. }
  29475. }
  29476. }
  29477. void Component::internalHierarchyChanged()
  29478. {
  29479. parentHierarchyChanged();
  29480. const ComponentDeletionWatcher deletionChecker (this);
  29481. if (componentListeners_ != 0)
  29482. {
  29483. for (int i = componentListeners_->size(); --i >= 0;)
  29484. {
  29485. ((ComponentListener*) componentListeners_->getUnchecked (i))
  29486. ->componentParentHierarchyChanged (*this);
  29487. if (deletionChecker.hasBeenDeleted())
  29488. return;
  29489. i = jmin (i, componentListeners_->size());
  29490. }
  29491. }
  29492. for (int i = childComponentList_.size(); --i >= 0;)
  29493. {
  29494. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  29495. // you really shouldn't delete the parent component during a callback telling you
  29496. // that it's changed..
  29497. jassert (! deletionChecker.hasBeenDeleted());
  29498. if (deletionChecker.hasBeenDeleted())
  29499. return;
  29500. i = jmin (i, childComponentList_.size());
  29501. }
  29502. }
  29503. void* Component::runModalLoopCallback (void* userData)
  29504. {
  29505. return (void*) (pointer_sized_int) ((Component*) userData)->runModalLoop();
  29506. }
  29507. int Component::runModalLoop()
  29508. {
  29509. if (! MessageManager::getInstance()->isThisTheMessageThread())
  29510. {
  29511. // use a callback so this can be called from non-gui threads
  29512. return (int) (pointer_sized_int)
  29513. MessageManager::getInstance()
  29514. ->callFunctionOnMessageThread (&runModalLoopCallback, (void*) this);
  29515. }
  29516. Component* const prevFocused = getCurrentlyFocusedComponent();
  29517. ComponentDeletionWatcher* deletionChecker = 0;
  29518. if (prevFocused != 0)
  29519. deletionChecker = new ComponentDeletionWatcher (prevFocused);
  29520. if (! isCurrentlyModal())
  29521. enterModalState();
  29522. JUCE_TRY
  29523. {
  29524. while (flags.currentlyModalFlag && flags.visibleFlag)
  29525. {
  29526. if (! MessageManager::getInstance()->dispatchNextMessage())
  29527. break;
  29528. // check whether this component was deleted during the last message
  29529. if (! isValidMessageListener())
  29530. break;
  29531. }
  29532. }
  29533. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  29534. catch (const std::exception& e)
  29535. {
  29536. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  29537. return 0;
  29538. }
  29539. catch (...)
  29540. {
  29541. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  29542. return 0;
  29543. }
  29544. #endif
  29545. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  29546. int returnValue = 0;
  29547. if (modalIndex >= 0)
  29548. {
  29549. modalComponentReturnValueKeys.remove (modalIndex);
  29550. returnValue = modalReturnValues.remove (modalIndex);
  29551. }
  29552. modalComponentStack.removeValue (this);
  29553. if (deletionChecker != 0)
  29554. {
  29555. if (! deletionChecker->hasBeenDeleted())
  29556. prevFocused->grabKeyboardFocus();
  29557. delete deletionChecker;
  29558. }
  29559. return returnValue;
  29560. }
  29561. void Component::enterModalState (const bool takeKeyboardFocus)
  29562. {
  29563. // if component methods are being called from threads other than the message
  29564. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29565. checkMessageManagerIsLocked
  29566. // Check for an attempt to make a component modal when it already is!
  29567. // This can cause nasty problems..
  29568. jassert (! flags.currentlyModalFlag);
  29569. if (! isCurrentlyModal())
  29570. {
  29571. modalComponentStack.add (this);
  29572. modalComponentReturnValueKeys.add (this);
  29573. modalReturnValues.add (0);
  29574. flags.currentlyModalFlag = true;
  29575. setVisible (true);
  29576. if (takeKeyboardFocus)
  29577. grabKeyboardFocus();
  29578. }
  29579. }
  29580. void Component::exitModalState (const int returnValue)
  29581. {
  29582. if (isCurrentlyModal())
  29583. {
  29584. if (MessageManager::getInstance()->isThisTheMessageThread())
  29585. {
  29586. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  29587. if (modalIndex >= 0)
  29588. {
  29589. modalReturnValues.set (modalIndex, returnValue);
  29590. }
  29591. else
  29592. {
  29593. modalComponentReturnValueKeys.add (this);
  29594. modalReturnValues.add (returnValue);
  29595. }
  29596. modalComponentStack.removeValue (this);
  29597. flags.currentlyModalFlag = false;
  29598. }
  29599. else
  29600. {
  29601. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  29602. }
  29603. }
  29604. }
  29605. bool Component::isCurrentlyModal() const throw()
  29606. {
  29607. return flags.currentlyModalFlag
  29608. && getCurrentlyModalComponent() == this;
  29609. }
  29610. bool Component::isCurrentlyBlockedByAnotherModalComponent() const throw()
  29611. {
  29612. Component* const mc = getCurrentlyModalComponent();
  29613. return mc != 0
  29614. && mc != this
  29615. && (! mc->isParentOf (this))
  29616. && ! mc->canModalEventBeSentToComponent (this);
  29617. }
  29618. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent() throw()
  29619. {
  29620. Component* const c = (Component*) modalComponentStack.getLast();
  29621. return c->isValidComponent() ? c : 0;
  29622. }
  29623. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  29624. {
  29625. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  29626. }
  29627. bool Component::isBroughtToFrontOnMouseClick() const throw()
  29628. {
  29629. return flags.bringToFrontOnClickFlag;
  29630. }
  29631. void Component::setMouseCursor (const MouseCursor& cursor) throw()
  29632. {
  29633. cursor_ = cursor;
  29634. if (flags.visibleFlag)
  29635. {
  29636. int mx, my;
  29637. getMouseXYRelative (mx, my);
  29638. if (flags.draggingFlag || reallyContains (mx, my, false))
  29639. {
  29640. internalUpdateMouseCursor (false);
  29641. }
  29642. }
  29643. }
  29644. const MouseCursor Component::getMouseCursor()
  29645. {
  29646. return cursor_;
  29647. }
  29648. void Component::updateMouseCursor() const throw()
  29649. {
  29650. sendFakeMouseMove();
  29651. }
  29652. void Component::internalUpdateMouseCursor (const bool forcedUpdate) throw()
  29653. {
  29654. ComponentPeer* const peer = getPeer();
  29655. if (peer != 0)
  29656. {
  29657. MouseCursor mc (getMouseCursor());
  29658. if (isUnboundedMouseModeOn && (unboundedMouseOffsetX != 0
  29659. || unboundedMouseOffsetY != 0
  29660. || ! isCursorVisibleUntilOffscreen))
  29661. {
  29662. mc = MouseCursor::NoCursor;
  29663. }
  29664. static void* currentCursorHandle = 0;
  29665. if (forcedUpdate || mc.getHandle() != currentCursorHandle)
  29666. {
  29667. currentCursorHandle = mc.getHandle();
  29668. mc.showInWindow (peer);
  29669. }
  29670. }
  29671. }
  29672. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  29673. {
  29674. flags.repaintOnMouseActivityFlag = shouldRepaint;
  29675. }
  29676. void Component::repaintParent() throw()
  29677. {
  29678. if (flags.visibleFlag)
  29679. internalRepaint (0, 0, getWidth(), getHeight());
  29680. }
  29681. void Component::repaint() throw()
  29682. {
  29683. repaint (0, 0, getWidth(), getHeight());
  29684. }
  29685. void Component::repaint (const int x, const int y,
  29686. const int w, const int h) throw()
  29687. {
  29688. deleteAndZero (bufferedImage_);
  29689. if (flags.visibleFlag)
  29690. internalRepaint (x, y, w, h);
  29691. }
  29692. void Component::internalRepaint (int x, int y, int w, int h)
  29693. {
  29694. // if component methods are being called from threads other than the message
  29695. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29696. checkMessageManagerIsLocked
  29697. if (x < 0)
  29698. {
  29699. w += x;
  29700. x = 0;
  29701. }
  29702. if (x + w > getWidth())
  29703. w = getWidth() - x;
  29704. if (w > 0)
  29705. {
  29706. if (y < 0)
  29707. {
  29708. h += y;
  29709. y = 0;
  29710. }
  29711. if (y + h > getHeight())
  29712. h = getHeight() - y;
  29713. if (h > 0)
  29714. {
  29715. if (parentComponent_ != 0)
  29716. {
  29717. x += getX();
  29718. y += getY();
  29719. if (parentComponent_->flags.visibleFlag)
  29720. parentComponent_->internalRepaint (x, y, w, h);
  29721. }
  29722. else if (flags.hasHeavyweightPeerFlag)
  29723. {
  29724. ComponentPeer* const peer = getPeer();
  29725. if (peer != 0)
  29726. peer->repaint (x, y, w, h);
  29727. }
  29728. }
  29729. }
  29730. }
  29731. void Component::paintEntireComponent (Graphics& originalContext)
  29732. {
  29733. jassert (! originalContext.isClipEmpty());
  29734. #ifdef JUCE_DEBUG
  29735. flags.isInsidePaintCall = true;
  29736. #endif
  29737. Graphics* g = &originalContext;
  29738. Image* effectImage = 0;
  29739. if (effect_ != 0)
  29740. {
  29741. effectImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  29742. getWidth(), getHeight(),
  29743. ! flags.opaqueFlag);
  29744. g = new Graphics (*effectImage);
  29745. }
  29746. g->saveState();
  29747. clipObscuredRegions (*g, g->getClipBounds(), 0, 0);
  29748. if (! g->isClipEmpty())
  29749. {
  29750. if (bufferedImage_ != 0)
  29751. {
  29752. g->setColour (Colours::black);
  29753. g->drawImageAt (bufferedImage_, 0, 0);
  29754. }
  29755. else
  29756. {
  29757. if (flags.bufferToImageFlag)
  29758. {
  29759. if (bufferedImage_ == 0)
  29760. {
  29761. bufferedImage_ = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  29762. getWidth(), getHeight(), ! flags.opaqueFlag);
  29763. Graphics imG (*bufferedImage_);
  29764. paint (imG);
  29765. }
  29766. g->setColour (Colours::black);
  29767. g->drawImageAt (bufferedImage_, 0, 0);
  29768. }
  29769. else
  29770. {
  29771. paint (*g);
  29772. g->resetToDefaultState();
  29773. }
  29774. }
  29775. }
  29776. g->restoreState();
  29777. for (int i = 0; i < childComponentList_.size(); ++i)
  29778. {
  29779. Component* const child = childComponentList_.getUnchecked (i);
  29780. if (child->isVisible())
  29781. {
  29782. g->saveState();
  29783. if (g->reduceClipRegion (child->getX(), child->getY(),
  29784. child->getWidth(), child->getHeight()))
  29785. {
  29786. for (int j = i + 1; j < childComponentList_.size(); ++j)
  29787. {
  29788. const Component* const sibling = childComponentList_.getUnchecked (j);
  29789. if (sibling->flags.opaqueFlag && sibling->isVisible())
  29790. g->excludeClipRegion (sibling->getX(), sibling->getY(),
  29791. sibling->getWidth(), sibling->getHeight());
  29792. }
  29793. if (! g->isClipEmpty())
  29794. {
  29795. g->setOrigin (child->getX(), child->getY());
  29796. child->paintEntireComponent (*g);
  29797. }
  29798. }
  29799. g->restoreState();
  29800. }
  29801. }
  29802. JUCE_TRY
  29803. {
  29804. g->saveState();
  29805. paintOverChildren (*g);
  29806. g->restoreState();
  29807. }
  29808. JUCE_CATCH_EXCEPTION
  29809. if (effect_ != 0)
  29810. {
  29811. delete g;
  29812. effect_->applyEffect (*effectImage, originalContext);
  29813. delete effectImage;
  29814. }
  29815. #ifdef JUCE_DEBUG
  29816. flags.isInsidePaintCall = false;
  29817. #endif
  29818. }
  29819. Image* Component::createComponentSnapshot (const Rectangle& areaToGrab,
  29820. const bool clipImageToComponentBounds)
  29821. {
  29822. Rectangle r (areaToGrab);
  29823. if (clipImageToComponentBounds)
  29824. r = r.getIntersection (Rectangle (0, 0, getWidth(), getHeight()));
  29825. Image* const componentImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  29826. jmax (1, r.getWidth()),
  29827. jmax (1, r.getHeight()),
  29828. true);
  29829. Graphics imageContext (*componentImage);
  29830. imageContext.setOrigin (-r.getX(),
  29831. -r.getY());
  29832. paintEntireComponent (imageContext);
  29833. return componentImage;
  29834. }
  29835. void Component::setComponentEffect (ImageEffectFilter* const effect)
  29836. {
  29837. if (effect_ != effect)
  29838. {
  29839. effect_ = effect;
  29840. repaint();
  29841. }
  29842. }
  29843. LookAndFeel& Component::getLookAndFeel() const throw()
  29844. {
  29845. const Component* c = this;
  29846. do
  29847. {
  29848. if (c->lookAndFeel_ != 0)
  29849. return *(c->lookAndFeel_);
  29850. c = c->parentComponent_;
  29851. }
  29852. while (c != 0);
  29853. return LookAndFeel::getDefaultLookAndFeel();
  29854. }
  29855. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  29856. {
  29857. if (lookAndFeel_ != newLookAndFeel)
  29858. {
  29859. lookAndFeel_ = newLookAndFeel;
  29860. sendLookAndFeelChange();
  29861. }
  29862. }
  29863. void Component::lookAndFeelChanged()
  29864. {
  29865. }
  29866. void Component::sendLookAndFeelChange()
  29867. {
  29868. repaint();
  29869. lookAndFeelChanged();
  29870. // (it's not a great idea to do anything that would delete this component
  29871. // during the lookAndFeelChanged() callback)
  29872. jassert (isValidComponent());
  29873. const ComponentDeletionWatcher deletionChecker (this);
  29874. for (int i = childComponentList_.size(); --i >= 0;)
  29875. {
  29876. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  29877. if (deletionChecker.hasBeenDeleted())
  29878. return;
  29879. i = jmin (i, childComponentList_.size());
  29880. }
  29881. }
  29882. static const String getColourPropertyName (const int colourId) throw()
  29883. {
  29884. String s;
  29885. s.preallocateStorage (18);
  29886. s << T("jcclr_") << colourId;
  29887. return s;
  29888. }
  29889. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const throw()
  29890. {
  29891. const String customColour (getComponentProperty (getColourPropertyName (colourId),
  29892. inheritFromParent,
  29893. String::empty));
  29894. if (customColour.isNotEmpty())
  29895. return Colour (customColour.getIntValue());
  29896. return getLookAndFeel().findColour (colourId);
  29897. }
  29898. bool Component::isColourSpecified (const int colourId) const throw()
  29899. {
  29900. return getComponentProperty (getColourPropertyName (colourId),
  29901. false,
  29902. String::empty).isNotEmpty();
  29903. }
  29904. void Component::removeColour (const int colourId)
  29905. {
  29906. if (isColourSpecified (colourId))
  29907. {
  29908. removeComponentProperty (getColourPropertyName (colourId));
  29909. colourChanged();
  29910. }
  29911. }
  29912. void Component::setColour (const int colourId, const Colour& colour)
  29913. {
  29914. const String colourName (getColourPropertyName (colourId));
  29915. const String customColour (getComponentProperty (colourName, false, String::empty));
  29916. if (customColour.isEmpty() || Colour (customColour.getIntValue()) != colour)
  29917. {
  29918. setComponentProperty (colourName, colour);
  29919. colourChanged();
  29920. }
  29921. }
  29922. void Component::copyAllExplicitColoursTo (Component& target) const throw()
  29923. {
  29924. if (propertySet_ != 0)
  29925. {
  29926. const StringPairArray& props = propertySet_->getAllProperties();
  29927. const StringArray& keys = props.getAllKeys();
  29928. for (int i = 0; i < keys.size(); ++i)
  29929. {
  29930. if (keys[i].startsWith (T("jcclr_")))
  29931. {
  29932. target.setComponentProperty (keys[i],
  29933. props.getAllValues() [i]);
  29934. }
  29935. }
  29936. target.colourChanged();
  29937. }
  29938. }
  29939. void Component::colourChanged()
  29940. {
  29941. }
  29942. const Rectangle Component::getUnclippedArea() const
  29943. {
  29944. int x = 0, y = 0, w = getWidth(), h = getHeight();
  29945. Component* p = parentComponent_;
  29946. int px = getX();
  29947. int py = getY();
  29948. while (p != 0)
  29949. {
  29950. if (! Rectangle::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  29951. return Rectangle();
  29952. px += p->getX();
  29953. py += p->getY();
  29954. p = p->parentComponent_;
  29955. }
  29956. return Rectangle (x, y, w, h);
  29957. }
  29958. void Component::clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  29959. const int deltaX, const int deltaY) const throw()
  29960. {
  29961. for (int i = childComponentList_.size(); --i >= 0;)
  29962. {
  29963. const Component* const c = childComponentList_.getUnchecked(i);
  29964. if (c->isVisible())
  29965. {
  29966. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  29967. if (! newClip.isEmpty())
  29968. {
  29969. if (c->isOpaque())
  29970. {
  29971. g.excludeClipRegion (deltaX + newClip.getX(),
  29972. deltaY + newClip.getY(),
  29973. newClip.getWidth(),
  29974. newClip.getHeight());
  29975. }
  29976. else
  29977. {
  29978. newClip.translate (-c->getX(), -c->getY());
  29979. c->clipObscuredRegions (g, newClip,
  29980. c->getX() + deltaX,
  29981. c->getY() + deltaY);
  29982. }
  29983. }
  29984. }
  29985. }
  29986. }
  29987. void Component::getVisibleArea (RectangleList& result,
  29988. const bool includeSiblings) const
  29989. {
  29990. result.clear();
  29991. const Rectangle unclipped (getUnclippedArea());
  29992. if (! unclipped.isEmpty())
  29993. {
  29994. result.add (unclipped);
  29995. if (includeSiblings)
  29996. {
  29997. const Component* const c = getTopLevelComponent();
  29998. int x = 0, y = 0;
  29999. c->relativePositionToOtherComponent (this, x, y);
  30000. c->subtractObscuredRegions (result, x, y,
  30001. Rectangle (0, 0, c->getWidth(), c->getHeight()),
  30002. this);
  30003. }
  30004. subtractObscuredRegions (result, 0, 0, unclipped, 0);
  30005. result.consolidate();
  30006. }
  30007. }
  30008. void Component::subtractObscuredRegions (RectangleList& result,
  30009. const int deltaX,
  30010. const int deltaY,
  30011. const Rectangle& clipRect,
  30012. const Component* const compToAvoid) const throw()
  30013. {
  30014. for (int i = childComponentList_.size(); --i >= 0;)
  30015. {
  30016. const Component* const c = childComponentList_.getUnchecked(i);
  30017. if (c != compToAvoid && c->isVisible())
  30018. {
  30019. if (c->isOpaque())
  30020. {
  30021. Rectangle childBounds (c->bounds_.getIntersection (clipRect));
  30022. childBounds.translate (deltaX, deltaY);
  30023. result.subtract (childBounds);
  30024. }
  30025. else
  30026. {
  30027. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  30028. newClip.translate (-c->getX(), -c->getY());
  30029. c->subtractObscuredRegions (result,
  30030. c->getX() + deltaX,
  30031. c->getY() + deltaY,
  30032. newClip,
  30033. compToAvoid);
  30034. }
  30035. }
  30036. }
  30037. }
  30038. void Component::mouseEnter (const MouseEvent&)
  30039. {
  30040. // base class does nothing
  30041. }
  30042. void Component::mouseExit (const MouseEvent&)
  30043. {
  30044. // base class does nothing
  30045. }
  30046. void Component::mouseDown (const MouseEvent&)
  30047. {
  30048. // base class does nothing
  30049. }
  30050. void Component::mouseUp (const MouseEvent&)
  30051. {
  30052. // base class does nothing
  30053. }
  30054. void Component::mouseDrag (const MouseEvent&)
  30055. {
  30056. // base class does nothing
  30057. }
  30058. void Component::mouseMove (const MouseEvent&)
  30059. {
  30060. // base class does nothing
  30061. }
  30062. void Component::mouseDoubleClick (const MouseEvent&)
  30063. {
  30064. // base class does nothing
  30065. }
  30066. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  30067. {
  30068. // the base class just passes this event up to its parent..
  30069. if (parentComponent_ != 0)
  30070. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  30071. wheelIncrementX, wheelIncrementY);
  30072. }
  30073. void Component::resized()
  30074. {
  30075. // base class does nothing
  30076. }
  30077. void Component::moved()
  30078. {
  30079. // base class does nothing
  30080. }
  30081. void Component::childBoundsChanged (Component*)
  30082. {
  30083. // base class does nothing
  30084. }
  30085. void Component::parentSizeChanged()
  30086. {
  30087. // base class does nothing
  30088. }
  30089. void Component::addComponentListener (ComponentListener* const newListener) throw()
  30090. {
  30091. if (componentListeners_ == 0)
  30092. componentListeners_ = new VoidArray (4);
  30093. componentListeners_->addIfNotAlreadyThere (newListener);
  30094. }
  30095. void Component::removeComponentListener (ComponentListener* const listenerToRemove) throw()
  30096. {
  30097. jassert (isValidComponent());
  30098. if (componentListeners_ != 0)
  30099. componentListeners_->removeValue (listenerToRemove);
  30100. }
  30101. void Component::inputAttemptWhenModal()
  30102. {
  30103. getTopLevelComponent()->toFront (true);
  30104. getLookAndFeel().playAlertSound();
  30105. }
  30106. bool Component::canModalEventBeSentToComponent (const Component*)
  30107. {
  30108. return false;
  30109. }
  30110. void Component::internalModalInputAttempt()
  30111. {
  30112. Component* const current = getCurrentlyModalComponent();
  30113. if (current != 0)
  30114. current->inputAttemptWhenModal();
  30115. }
  30116. void Component::paint (Graphics&)
  30117. {
  30118. // all painting is done in the subclasses
  30119. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  30120. }
  30121. void Component::paintOverChildren (Graphics&)
  30122. {
  30123. // all painting is done in the subclasses
  30124. }
  30125. void Component::handleMessage (const Message& message)
  30126. {
  30127. if (message.intParameter1 == exitModalStateMessage)
  30128. {
  30129. exitModalState (message.intParameter2);
  30130. }
  30131. else if (message.intParameter1 == customCommandMessage)
  30132. {
  30133. handleCommandMessage (message.intParameter2);
  30134. }
  30135. }
  30136. void Component::postCommandMessage (const int commandId) throw()
  30137. {
  30138. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  30139. }
  30140. void Component::handleCommandMessage (int)
  30141. {
  30142. // used by subclasses
  30143. }
  30144. void Component::addMouseListener (MouseListener* const newListener,
  30145. const bool wantsEventsForAllNestedChildComponents) throw()
  30146. {
  30147. // if component methods are being called from threads other than the message
  30148. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30149. checkMessageManagerIsLocked
  30150. if (mouseListeners_ == 0)
  30151. mouseListeners_ = new VoidArray (4);
  30152. if (! mouseListeners_->contains (newListener))
  30153. {
  30154. if (wantsEventsForAllNestedChildComponents)
  30155. {
  30156. mouseListeners_->insert (0, newListener);
  30157. ++numDeepMouseListeners;
  30158. }
  30159. else
  30160. {
  30161. mouseListeners_->add (newListener);
  30162. }
  30163. }
  30164. }
  30165. void Component::removeMouseListener (MouseListener* const listenerToRemove) throw()
  30166. {
  30167. // if component methods are being called from threads other than the message
  30168. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30169. checkMessageManagerIsLocked
  30170. if (mouseListeners_ != 0)
  30171. {
  30172. const int index = mouseListeners_->indexOf (listenerToRemove);
  30173. if (index >= 0)
  30174. {
  30175. if (index < numDeepMouseListeners)
  30176. --numDeepMouseListeners;
  30177. mouseListeners_->remove (index);
  30178. }
  30179. }
  30180. }
  30181. void Component::internalMouseEnter (int x, int y, int64 time)
  30182. {
  30183. if (isCurrentlyBlockedByAnotherModalComponent())
  30184. {
  30185. // if something else is modal, always just show a normal mouse cursor
  30186. if (componentUnderMouse == this)
  30187. {
  30188. ComponentPeer* const peer = getPeer();
  30189. if (peer != 0)
  30190. {
  30191. MouseCursor mc (MouseCursor::NormalCursor);
  30192. mc.showInWindow (peer);
  30193. }
  30194. }
  30195. return;
  30196. }
  30197. if (! flags.mouseInsideFlag)
  30198. {
  30199. flags.mouseInsideFlag = true;
  30200. flags.mouseOverFlag = true;
  30201. flags.draggingFlag = false;
  30202. if (isValidComponent())
  30203. {
  30204. const ComponentDeletionWatcher deletionChecker (this);
  30205. if (flags.repaintOnMouseActivityFlag)
  30206. repaint();
  30207. const MouseEvent me (x, y,
  30208. ModifierKeys::getCurrentModifiers(),
  30209. this,
  30210. Time (time),
  30211. x, y,
  30212. Time (time),
  30213. 0, false);
  30214. mouseEnter (me);
  30215. if (deletionChecker.hasBeenDeleted())
  30216. return;
  30217. Desktop::getInstance().resetTimer();
  30218. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30219. {
  30220. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseEnter (me);
  30221. if (deletionChecker.hasBeenDeleted())
  30222. return;
  30223. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30224. }
  30225. if (mouseListeners_ != 0)
  30226. {
  30227. for (int i = mouseListeners_->size(); --i >= 0;)
  30228. {
  30229. ((MouseListener*) mouseListeners_->getUnchecked(i))->mouseEnter (me);
  30230. if (deletionChecker.hasBeenDeleted())
  30231. return;
  30232. i = jmin (i, mouseListeners_->size());
  30233. }
  30234. }
  30235. const Component* p = parentComponent_;
  30236. while (p != 0)
  30237. {
  30238. const ComponentDeletionWatcher parentDeletionChecker (p);
  30239. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30240. {
  30241. ((MouseListener*) (p->mouseListeners_->getUnchecked(i)))->mouseEnter (me);
  30242. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30243. return;
  30244. i = jmin (i, p->numDeepMouseListeners);
  30245. }
  30246. p = p->parentComponent_;
  30247. }
  30248. }
  30249. }
  30250. if (componentUnderMouse == this)
  30251. internalUpdateMouseCursor (true);
  30252. }
  30253. void Component::internalMouseExit (int x, int y, int64 time)
  30254. {
  30255. const ComponentDeletionWatcher deletionChecker (this);
  30256. if (flags.draggingFlag)
  30257. {
  30258. internalMouseUp (ModifierKeys::getCurrentModifiers().getRawFlags(), x, y, time);
  30259. if (deletionChecker.hasBeenDeleted())
  30260. return;
  30261. }
  30262. enableUnboundedMouseMovement (false);
  30263. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  30264. {
  30265. flags.mouseInsideFlag = false;
  30266. flags.mouseOverFlag = false;
  30267. flags.draggingFlag = false;
  30268. if (flags.repaintOnMouseActivityFlag)
  30269. repaint();
  30270. const MouseEvent me (x, y,
  30271. ModifierKeys::getCurrentModifiers(),
  30272. this,
  30273. Time (time),
  30274. x, y,
  30275. Time (time),
  30276. 0, false);
  30277. mouseExit (me);
  30278. if (deletionChecker.hasBeenDeleted())
  30279. return;
  30280. Desktop::getInstance().resetTimer();
  30281. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30282. {
  30283. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseExit (me);
  30284. if (deletionChecker.hasBeenDeleted())
  30285. return;
  30286. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30287. }
  30288. if (mouseListeners_ != 0)
  30289. {
  30290. for (int i = mouseListeners_->size(); --i >= 0;)
  30291. {
  30292. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  30293. if (deletionChecker.hasBeenDeleted())
  30294. return;
  30295. i = jmin (i, mouseListeners_->size());
  30296. }
  30297. }
  30298. const Component* p = parentComponent_;
  30299. while (p != 0)
  30300. {
  30301. const ComponentDeletionWatcher parentDeletionChecker (p);
  30302. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30303. {
  30304. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseExit (me);
  30305. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30306. return;
  30307. i = jmin (i, p->numDeepMouseListeners);
  30308. }
  30309. p = p->parentComponent_;
  30310. }
  30311. }
  30312. }
  30313. class InternalDragRepeater : public Timer
  30314. {
  30315. public:
  30316. InternalDragRepeater()
  30317. {}
  30318. ~InternalDragRepeater()
  30319. {}
  30320. void timerCallback()
  30321. {
  30322. Component* const c = Component::getComponentUnderMouse();
  30323. if (c != 0 && c->isMouseButtonDown())
  30324. {
  30325. int x, y;
  30326. c->getMouseXYRelative (x, y);
  30327. // the offsets have been added on, so must be taken off before calling the
  30328. // drag.. otherwise they'll be added twice
  30329. x -= unboundedMouseOffsetX;
  30330. y -= unboundedMouseOffsetY;
  30331. c->internalMouseDrag (x, y, Time::currentTimeMillis());
  30332. }
  30333. }
  30334. juce_UseDebuggingNewOperator
  30335. };
  30336. static InternalDragRepeater* dragRepeater = 0;
  30337. void Component::beginDragAutoRepeat (const int interval)
  30338. {
  30339. if (interval > 0)
  30340. {
  30341. if (dragRepeater == 0)
  30342. dragRepeater = new InternalDragRepeater();
  30343. if (dragRepeater->getTimerInterval() != interval)
  30344. dragRepeater->startTimer (interval);
  30345. }
  30346. else
  30347. {
  30348. deleteAndZero (dragRepeater);
  30349. }
  30350. }
  30351. void Component::internalMouseDown (const int x, const int y)
  30352. {
  30353. const ComponentDeletionWatcher deletionChecker (this);
  30354. if (isCurrentlyBlockedByAnotherModalComponent())
  30355. {
  30356. internalModalInputAttempt();
  30357. if (deletionChecker.hasBeenDeleted())
  30358. return;
  30359. // If processing the input attempt has exited the modal loop, we'll allow the event
  30360. // to be delivered..
  30361. if (isCurrentlyBlockedByAnotherModalComponent())
  30362. {
  30363. // allow blocked mouse-events to go to global listeners..
  30364. const MouseEvent me (x, y,
  30365. ModifierKeys::getCurrentModifiers(),
  30366. this,
  30367. Time (juce_recentMouseDownTimes[0]),
  30368. x, y,
  30369. Time (juce_recentMouseDownTimes[0]),
  30370. countMouseClicks(),
  30371. false);
  30372. Desktop::getInstance().resetTimer();
  30373. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30374. {
  30375. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  30376. if (deletionChecker.hasBeenDeleted())
  30377. return;
  30378. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30379. }
  30380. return;
  30381. }
  30382. }
  30383. {
  30384. Component* c = this;
  30385. while (c != 0)
  30386. {
  30387. if (c->isBroughtToFrontOnMouseClick())
  30388. {
  30389. c->toFront (true);
  30390. if (deletionChecker.hasBeenDeleted())
  30391. return;
  30392. }
  30393. c = c->parentComponent_;
  30394. }
  30395. }
  30396. if (! flags.dontFocusOnMouseClickFlag)
  30397. grabFocusInternal (focusChangedByMouseClick);
  30398. if (! deletionChecker.hasBeenDeleted())
  30399. {
  30400. flags.draggingFlag = true;
  30401. flags.mouseOverFlag = true;
  30402. if (flags.repaintOnMouseActivityFlag)
  30403. repaint();
  30404. const MouseEvent me (x, y,
  30405. ModifierKeys::getCurrentModifiers(),
  30406. this,
  30407. Time (juce_recentMouseDownTimes[0]),
  30408. x, y,
  30409. Time (juce_recentMouseDownTimes[0]),
  30410. countMouseClicks(),
  30411. false);
  30412. mouseDown (me);
  30413. if (deletionChecker.hasBeenDeleted())
  30414. return;
  30415. Desktop::getInstance().resetTimer();
  30416. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30417. {
  30418. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  30419. if (deletionChecker.hasBeenDeleted())
  30420. return;
  30421. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30422. }
  30423. if (mouseListeners_ != 0)
  30424. {
  30425. for (int i = mouseListeners_->size(); --i >= 0;)
  30426. {
  30427. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  30428. if (deletionChecker.hasBeenDeleted())
  30429. return;
  30430. i = jmin (i, mouseListeners_->size());
  30431. }
  30432. }
  30433. const Component* p = parentComponent_;
  30434. while (p != 0)
  30435. {
  30436. const ComponentDeletionWatcher parentDeletionChecker (p);
  30437. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30438. {
  30439. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDown (me);
  30440. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30441. return;
  30442. i = jmin (i, p->numDeepMouseListeners);
  30443. }
  30444. p = p->parentComponent_;
  30445. }
  30446. }
  30447. }
  30448. void Component::internalMouseUp (const int oldModifiers, int x, int y, const int64 time)
  30449. {
  30450. if (isValidComponent() && flags.draggingFlag)
  30451. {
  30452. flags.draggingFlag = false;
  30453. deleteAndZero (dragRepeater);
  30454. x += unboundedMouseOffsetX;
  30455. y += unboundedMouseOffsetY;
  30456. juce_LastMousePosX = x;
  30457. juce_LastMousePosY = y;
  30458. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  30459. const ComponentDeletionWatcher deletionChecker (this);
  30460. if (flags.repaintOnMouseActivityFlag)
  30461. repaint();
  30462. int mdx = juce_recentMouseDownX[0];
  30463. int mdy = juce_recentMouseDownY[0];
  30464. globalPositionToRelative (mdx, mdy);
  30465. const MouseEvent me (x, y,
  30466. oldModifiers,
  30467. this,
  30468. Time (time),
  30469. mdx, mdy,
  30470. Time (juce_recentMouseDownTimes [0]),
  30471. countMouseClicks(),
  30472. juce_MouseHasMovedSignificantlySincePressed
  30473. || juce_recentMouseDownTimes[0] + 300 < time);
  30474. mouseUp (me);
  30475. if (deletionChecker.hasBeenDeleted())
  30476. return;
  30477. Desktop::getInstance().resetTimer();
  30478. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30479. {
  30480. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseUp (me);
  30481. if (deletionChecker.hasBeenDeleted())
  30482. return;
  30483. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30484. }
  30485. if (mouseListeners_ != 0)
  30486. {
  30487. for (int i = mouseListeners_->size(); --i >= 0;)
  30488. {
  30489. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  30490. if (deletionChecker.hasBeenDeleted())
  30491. return;
  30492. i = jmin (i, mouseListeners_->size());
  30493. }
  30494. }
  30495. {
  30496. const Component* p = parentComponent_;
  30497. while (p != 0)
  30498. {
  30499. const ComponentDeletionWatcher parentDeletionChecker (p);
  30500. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30501. {
  30502. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseUp (me);
  30503. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30504. return;
  30505. i = jmin (i, p->numDeepMouseListeners);
  30506. }
  30507. p = p->parentComponent_;
  30508. }
  30509. }
  30510. // check for double-click
  30511. if (me.getNumberOfClicks() >= 2)
  30512. {
  30513. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  30514. mouseDoubleClick (me);
  30515. int i;
  30516. for (i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30517. {
  30518. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDoubleClick (me);
  30519. if (deletionChecker.hasBeenDeleted())
  30520. return;
  30521. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30522. }
  30523. for (i = numListeners; --i >= 0;)
  30524. {
  30525. if (deletionChecker.hasBeenDeleted() || mouseListeners_ == 0)
  30526. return;
  30527. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  30528. if (ml != 0)
  30529. ml->mouseDoubleClick (me);
  30530. }
  30531. if (deletionChecker.hasBeenDeleted())
  30532. return;
  30533. const Component* p = parentComponent_;
  30534. while (p != 0)
  30535. {
  30536. const ComponentDeletionWatcher parentDeletionChecker (p);
  30537. for (i = p->numDeepMouseListeners; --i >= 0;)
  30538. {
  30539. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDoubleClick (me);
  30540. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30541. return;
  30542. i = jmin (i, p->numDeepMouseListeners);
  30543. }
  30544. p = p->parentComponent_;
  30545. }
  30546. }
  30547. }
  30548. enableUnboundedMouseMovement (false);
  30549. }
  30550. void Component::internalMouseDrag (int x, int y, const int64 time)
  30551. {
  30552. if (isValidComponent() && flags.draggingFlag)
  30553. {
  30554. flags.mouseOverFlag = reallyContains (x, y, false);
  30555. x += unboundedMouseOffsetX;
  30556. y += unboundedMouseOffsetY;
  30557. juce_LastMousePosX = x;
  30558. juce_LastMousePosY = y;
  30559. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  30560. juce_MouseHasMovedSignificantlySincePressed
  30561. = juce_MouseHasMovedSignificantlySincePressed
  30562. || abs (juce_recentMouseDownX[0] - juce_LastMousePosX) >= 4
  30563. || abs (juce_recentMouseDownY[0] - juce_LastMousePosY) >= 4;
  30564. const ComponentDeletionWatcher deletionChecker (this);
  30565. int mdx = juce_recentMouseDownX[0];
  30566. int mdy = juce_recentMouseDownY[0];
  30567. globalPositionToRelative (mdx, mdy);
  30568. const MouseEvent me (x, y,
  30569. ModifierKeys::getCurrentModifiers(),
  30570. this,
  30571. Time (time),
  30572. mdx, mdy,
  30573. Time (juce_recentMouseDownTimes[0]),
  30574. countMouseClicks(),
  30575. juce_MouseHasMovedSignificantlySincePressed
  30576. || juce_recentMouseDownTimes[0] + 300 < time);
  30577. mouseDrag (me);
  30578. if (deletionChecker.hasBeenDeleted())
  30579. return;
  30580. Desktop::getInstance().resetTimer();
  30581. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30582. {
  30583. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDrag (me);
  30584. if (deletionChecker.hasBeenDeleted())
  30585. return;
  30586. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30587. }
  30588. if (mouseListeners_ != 0)
  30589. {
  30590. for (int i = mouseListeners_->size(); --i >= 0;)
  30591. {
  30592. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  30593. if (deletionChecker.hasBeenDeleted())
  30594. return;
  30595. i = jmin (i, mouseListeners_->size());
  30596. }
  30597. }
  30598. const Component* p = parentComponent_;
  30599. while (p != 0)
  30600. {
  30601. const ComponentDeletionWatcher parentDeletionChecker (p);
  30602. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30603. {
  30604. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDrag (me);
  30605. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30606. return;
  30607. i = jmin (i, p->numDeepMouseListeners);
  30608. }
  30609. p = p->parentComponent_;
  30610. }
  30611. if (this == componentUnderMouse)
  30612. {
  30613. if (isUnboundedMouseModeOn)
  30614. {
  30615. Rectangle screenArea (getParentMonitorArea().expanded (-2, -2));
  30616. int mx, my;
  30617. Desktop::getMousePosition (mx, my);
  30618. if (! screenArea.contains (mx, my))
  30619. {
  30620. int deltaX = 0, deltaY = 0;
  30621. if (mx <= screenArea.getX() || mx >= screenArea.getRight())
  30622. deltaX = getScreenX() + getWidth() / 2 - mx;
  30623. if (my <= screenArea.getY() || my >= screenArea.getBottom())
  30624. deltaY = getScreenY() + getHeight() / 2 - my;
  30625. unboundedMouseOffsetX -= deltaX;
  30626. unboundedMouseOffsetY -= deltaY;
  30627. Desktop::setMousePosition (mx + deltaX,
  30628. my + deltaY);
  30629. }
  30630. else if (isCursorVisibleUntilOffscreen
  30631. && (unboundedMouseOffsetX != 0 || unboundedMouseOffsetY != 0)
  30632. && screenArea.contains (mx + unboundedMouseOffsetX,
  30633. my + unboundedMouseOffsetY))
  30634. {
  30635. mx += unboundedMouseOffsetX;
  30636. my += unboundedMouseOffsetY;
  30637. unboundedMouseOffsetX = 0;
  30638. unboundedMouseOffsetY = 0;
  30639. Desktop::setMousePosition (mx, my);
  30640. }
  30641. }
  30642. internalUpdateMouseCursor (false);
  30643. }
  30644. }
  30645. }
  30646. void Component::internalMouseMove (const int x, const int y, const int64 time)
  30647. {
  30648. const ComponentDeletionWatcher deletionChecker (this);
  30649. if (isValidComponent())
  30650. {
  30651. const MouseEvent me (x, y,
  30652. ModifierKeys::getCurrentModifiers(),
  30653. this,
  30654. Time (time),
  30655. x, y,
  30656. Time (time),
  30657. 0, false);
  30658. if (isCurrentlyBlockedByAnotherModalComponent())
  30659. {
  30660. // allow blocked mouse-events to go to global listeners..
  30661. Desktop::getInstance().sendMouseMove();
  30662. }
  30663. else
  30664. {
  30665. if (this == componentUnderMouse)
  30666. internalUpdateMouseCursor (false);
  30667. flags.mouseOverFlag = true;
  30668. mouseMove (me);
  30669. if (deletionChecker.hasBeenDeleted())
  30670. return;
  30671. Desktop::getInstance().resetTimer();
  30672. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30673. {
  30674. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseMove (me);
  30675. if (deletionChecker.hasBeenDeleted())
  30676. return;
  30677. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30678. }
  30679. if (mouseListeners_ != 0)
  30680. {
  30681. for (int i = mouseListeners_->size(); --i >= 0;)
  30682. {
  30683. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  30684. if (deletionChecker.hasBeenDeleted())
  30685. return;
  30686. i = jmin (i, mouseListeners_->size());
  30687. }
  30688. }
  30689. const Component* p = parentComponent_;
  30690. while (p != 0)
  30691. {
  30692. const ComponentDeletionWatcher parentDeletionChecker (p);
  30693. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30694. {
  30695. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseMove (me);
  30696. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30697. return;
  30698. i = jmin (i, p->numDeepMouseListeners);
  30699. }
  30700. p = p->parentComponent_;
  30701. }
  30702. }
  30703. }
  30704. }
  30705. void Component::internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time)
  30706. {
  30707. const ComponentDeletionWatcher deletionChecker (this);
  30708. const float wheelIncrementX = intAmountX * (1.0f / 256.0f);
  30709. const float wheelIncrementY = intAmountY * (1.0f / 256.0f);
  30710. int mx, my;
  30711. getMouseXYRelative (mx, my);
  30712. const MouseEvent me (mx, my,
  30713. ModifierKeys::getCurrentModifiers(),
  30714. this,
  30715. Time (time),
  30716. mx, my,
  30717. Time (time),
  30718. 0, false);
  30719. if (isCurrentlyBlockedByAnotherModalComponent())
  30720. {
  30721. // allow blocked mouse-events to go to global listeners..
  30722. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30723. {
  30724. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30725. if (deletionChecker.hasBeenDeleted())
  30726. return;
  30727. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30728. }
  30729. }
  30730. else
  30731. {
  30732. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30733. if (deletionChecker.hasBeenDeleted())
  30734. return;
  30735. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30736. {
  30737. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30738. if (deletionChecker.hasBeenDeleted())
  30739. return;
  30740. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30741. }
  30742. if (mouseListeners_ != 0)
  30743. {
  30744. for (int i = mouseListeners_->size(); --i >= 0;)
  30745. {
  30746. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30747. if (deletionChecker.hasBeenDeleted())
  30748. return;
  30749. i = jmin (i, mouseListeners_->size());
  30750. }
  30751. }
  30752. const Component* p = parentComponent_;
  30753. while (p != 0)
  30754. {
  30755. const ComponentDeletionWatcher parentDeletionChecker (p);
  30756. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30757. {
  30758. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30759. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30760. return;
  30761. i = jmin (i, p->numDeepMouseListeners);
  30762. }
  30763. p = p->parentComponent_;
  30764. }
  30765. sendFakeMouseMove();
  30766. }
  30767. }
  30768. void Component::sendFakeMouseMove() const
  30769. {
  30770. ComponentPeer* const peer = getPeer();
  30771. if (peer != 0)
  30772. peer->sendFakeMouseMove();
  30773. }
  30774. void Component::broughtToFront()
  30775. {
  30776. }
  30777. void Component::internalBroughtToFront()
  30778. {
  30779. if (isValidComponent())
  30780. {
  30781. if (flags.hasHeavyweightPeerFlag)
  30782. Desktop::getInstance().componentBroughtToFront (this);
  30783. const ComponentDeletionWatcher deletionChecker (this);
  30784. broughtToFront();
  30785. if (deletionChecker.hasBeenDeleted())
  30786. return;
  30787. if (componentListeners_ != 0)
  30788. {
  30789. for (int i = componentListeners_->size(); --i >= 0;)
  30790. {
  30791. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30792. ->componentBroughtToFront (*this);
  30793. if (deletionChecker.hasBeenDeleted())
  30794. return;
  30795. i = jmin (i, componentListeners_->size());
  30796. }
  30797. }
  30798. // when brought to the front and there's a modal component blocking this one,
  30799. // we need to bring the modal one to the front instead..
  30800. Component* const cm = getCurrentlyModalComponent();
  30801. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  30802. {
  30803. cm->getTopLevelComponent()->toFront (false);
  30804. }
  30805. }
  30806. }
  30807. void Component::focusGained (FocusChangeType)
  30808. {
  30809. // base class does nothing
  30810. }
  30811. void Component::internalFocusGain (const FocusChangeType cause)
  30812. {
  30813. const ComponentDeletionWatcher deletionChecker (this);
  30814. focusGained (cause);
  30815. if (! deletionChecker.hasBeenDeleted())
  30816. internalChildFocusChange (cause);
  30817. }
  30818. void Component::focusLost (FocusChangeType)
  30819. {
  30820. // base class does nothing
  30821. }
  30822. void Component::internalFocusLoss (const FocusChangeType cause)
  30823. {
  30824. const ComponentDeletionWatcher deletionChecker (this);
  30825. focusLost (focusChangedDirectly);
  30826. if (! deletionChecker.hasBeenDeleted())
  30827. internalChildFocusChange (cause);
  30828. }
  30829. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  30830. {
  30831. // base class does nothing
  30832. }
  30833. void Component::internalChildFocusChange (FocusChangeType cause)
  30834. {
  30835. const bool childIsNowFocused = hasKeyboardFocus (true);
  30836. if (flags.childCompFocusedFlag != childIsNowFocused)
  30837. {
  30838. flags.childCompFocusedFlag = childIsNowFocused;
  30839. const ComponentDeletionWatcher deletionChecker (this);
  30840. focusOfChildComponentChanged (cause);
  30841. if (deletionChecker.hasBeenDeleted())
  30842. return;
  30843. }
  30844. if (parentComponent_ != 0)
  30845. parentComponent_->internalChildFocusChange (cause);
  30846. }
  30847. bool Component::isEnabled() const throw()
  30848. {
  30849. return (! flags.isDisabledFlag)
  30850. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  30851. }
  30852. void Component::setEnabled (const bool shouldBeEnabled)
  30853. {
  30854. if (flags.isDisabledFlag == shouldBeEnabled)
  30855. {
  30856. flags.isDisabledFlag = ! shouldBeEnabled;
  30857. // if any parent components are disabled, setting our flag won't make a difference,
  30858. // so no need to send a change message
  30859. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  30860. sendEnablementChangeMessage();
  30861. }
  30862. }
  30863. void Component::sendEnablementChangeMessage()
  30864. {
  30865. const ComponentDeletionWatcher deletionChecker (this);
  30866. enablementChanged();
  30867. if (deletionChecker.hasBeenDeleted())
  30868. return;
  30869. for (int i = getNumChildComponents(); --i >= 0;)
  30870. {
  30871. Component* const c = getChildComponent (i);
  30872. if (c != 0)
  30873. {
  30874. c->sendEnablementChangeMessage();
  30875. if (deletionChecker.hasBeenDeleted())
  30876. return;
  30877. }
  30878. }
  30879. }
  30880. void Component::enablementChanged()
  30881. {
  30882. }
  30883. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  30884. {
  30885. flags.wantsFocusFlag = wantsFocus;
  30886. }
  30887. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  30888. {
  30889. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  30890. }
  30891. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  30892. {
  30893. return ! flags.dontFocusOnMouseClickFlag;
  30894. }
  30895. bool Component::getWantsKeyboardFocus() const throw()
  30896. {
  30897. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  30898. }
  30899. void Component::setFocusContainer (const bool isFocusContainer) throw()
  30900. {
  30901. flags.isFocusContainerFlag = isFocusContainer;
  30902. }
  30903. bool Component::isFocusContainer() const throw()
  30904. {
  30905. return flags.isFocusContainerFlag;
  30906. }
  30907. int Component::getExplicitFocusOrder() const throw()
  30908. {
  30909. return getComponentPropertyInt (T("_jexfo"), false, 0);
  30910. }
  30911. void Component::setExplicitFocusOrder (const int newFocusOrderIndex) throw()
  30912. {
  30913. setComponentProperty (T("_jexfo"), newFocusOrderIndex);
  30914. }
  30915. KeyboardFocusTraverser* Component::createFocusTraverser()
  30916. {
  30917. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  30918. return new KeyboardFocusTraverser();
  30919. return parentComponent_->createFocusTraverser();
  30920. }
  30921. void Component::takeKeyboardFocus (const FocusChangeType cause)
  30922. {
  30923. // give the focus to this component
  30924. if (currentlyFocusedComponent != this)
  30925. {
  30926. JUCE_TRY
  30927. {
  30928. // get the focus onto our desktop window
  30929. ComponentPeer* const peer = getPeer();
  30930. if (peer != 0)
  30931. {
  30932. const ComponentDeletionWatcher deletionChecker (this);
  30933. peer->grabFocus();
  30934. if (peer->isFocused() && currentlyFocusedComponent != this)
  30935. {
  30936. Component* const componentLosingFocus = currentlyFocusedComponent;
  30937. currentlyFocusedComponent = this;
  30938. Desktop::getInstance().triggerFocusCallback();
  30939. // call this after setting currentlyFocusedComponent so that the one that's
  30940. // losing it has a chance to see where focus is going
  30941. if (componentLosingFocus->isValidComponent())
  30942. componentLosingFocus->internalFocusLoss (cause);
  30943. if (currentlyFocusedComponent == this)
  30944. {
  30945. focusGained (cause);
  30946. if (! deletionChecker.hasBeenDeleted())
  30947. internalChildFocusChange (cause);
  30948. }
  30949. }
  30950. }
  30951. }
  30952. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  30953. catch (const std::exception& e)
  30954. {
  30955. currentlyFocusedComponent = 0;
  30956. Desktop::getInstance().triggerFocusCallback();
  30957. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  30958. }
  30959. catch (...)
  30960. {
  30961. currentlyFocusedComponent = 0;
  30962. Desktop::getInstance().triggerFocusCallback();
  30963. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  30964. }
  30965. #endif
  30966. }
  30967. }
  30968. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  30969. {
  30970. if (isShowing())
  30971. {
  30972. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  30973. {
  30974. takeKeyboardFocus (cause);
  30975. }
  30976. else
  30977. {
  30978. if (isParentOf (currentlyFocusedComponent)
  30979. && currentlyFocusedComponent->isShowing())
  30980. {
  30981. // do nothing if the focused component is actually a child of ours..
  30982. }
  30983. else
  30984. {
  30985. // find the default child component..
  30986. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  30987. if (traverser != 0)
  30988. {
  30989. Component* const defaultComp = traverser->getDefaultComponent (this);
  30990. delete traverser;
  30991. if (defaultComp != 0)
  30992. {
  30993. defaultComp->grabFocusInternal (cause, false);
  30994. return;
  30995. }
  30996. }
  30997. if (canTryParent && parentComponent_ != 0)
  30998. {
  30999. // if no children want it and we're allowed to try our parent comp,
  31000. // then pass up to parent, which will try our siblings.
  31001. parentComponent_->grabFocusInternal (cause, true);
  31002. }
  31003. }
  31004. }
  31005. }
  31006. }
  31007. void Component::grabKeyboardFocus()
  31008. {
  31009. // if component methods are being called from threads other than the message
  31010. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31011. checkMessageManagerIsLocked
  31012. grabFocusInternal (focusChangedDirectly);
  31013. }
  31014. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  31015. {
  31016. // if component methods are being called from threads other than the message
  31017. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31018. checkMessageManagerIsLocked
  31019. if (parentComponent_ != 0)
  31020. {
  31021. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  31022. if (traverser != 0)
  31023. {
  31024. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  31025. : traverser->getPreviousComponent (this);
  31026. delete traverser;
  31027. if (nextComp != 0)
  31028. {
  31029. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  31030. {
  31031. const ComponentDeletionWatcher deletionChecker (nextComp);
  31032. internalModalInputAttempt();
  31033. if (deletionChecker.hasBeenDeleted()
  31034. || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  31035. return;
  31036. }
  31037. nextComp->grabFocusInternal (focusChangedByTabKey);
  31038. return;
  31039. }
  31040. }
  31041. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  31042. }
  31043. }
  31044. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const throw()
  31045. {
  31046. return (currentlyFocusedComponent == this)
  31047. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  31048. }
  31049. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  31050. {
  31051. return currentlyFocusedComponent;
  31052. }
  31053. void Component::giveAwayFocus()
  31054. {
  31055. // use a copy so we can clear the value before the call
  31056. Component* const componentLosingFocus = currentlyFocusedComponent;
  31057. currentlyFocusedComponent = 0;
  31058. Desktop::getInstance().triggerFocusCallback();
  31059. if (componentLosingFocus->isValidComponent())
  31060. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  31061. }
  31062. bool Component::isMouseOver() const throw()
  31063. {
  31064. return flags.mouseOverFlag;
  31065. }
  31066. bool Component::isMouseButtonDown() const throw()
  31067. {
  31068. return flags.draggingFlag;
  31069. }
  31070. bool Component::isMouseOverOrDragging() const throw()
  31071. {
  31072. return flags.mouseOverFlag || flags.draggingFlag;
  31073. }
  31074. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  31075. {
  31076. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  31077. }
  31078. void Component::getMouseXYRelative (int& mx, int& my) const throw()
  31079. {
  31080. Desktop::getMousePosition (mx, my);
  31081. globalPositionToRelative (mx, my);
  31082. mx += unboundedMouseOffsetX;
  31083. my += unboundedMouseOffsetY;
  31084. }
  31085. void Component::enableUnboundedMouseMovement (bool enable,
  31086. bool keepCursorVisibleUntilOffscreen) throw()
  31087. {
  31088. enable = enable && isMouseButtonDown();
  31089. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  31090. if (enable != isUnboundedMouseModeOn)
  31091. {
  31092. if ((! enable) && ((! isCursorVisibleUntilOffscreen)
  31093. || unboundedMouseOffsetX != 0
  31094. || unboundedMouseOffsetY != 0))
  31095. {
  31096. // when released, return the mouse to within the component's bounds
  31097. int mx, my;
  31098. getMouseXYRelative (mx, my);
  31099. mx = jlimit (0, getWidth(), mx);
  31100. my = jlimit (0, getHeight(), my);
  31101. relativePositionToGlobal (mx, my);
  31102. Desktop::setMousePosition (mx, my);
  31103. }
  31104. isUnboundedMouseModeOn = enable;
  31105. unboundedMouseOffsetX = 0;
  31106. unboundedMouseOffsetY = 0;
  31107. internalUpdateMouseCursor (true);
  31108. }
  31109. }
  31110. Component* JUCE_CALLTYPE Component::getComponentUnderMouse() throw()
  31111. {
  31112. return componentUnderMouse;
  31113. }
  31114. const Rectangle Component::getParentMonitorArea() const throw()
  31115. {
  31116. int centreX = getWidth() / 2;
  31117. int centreY = getHeight() / 2;
  31118. relativePositionToGlobal (centreX, centreY);
  31119. return Desktop::getInstance().getMonitorAreaContaining (centreX, centreY);
  31120. }
  31121. void Component::addKeyListener (KeyListener* const newListener) throw()
  31122. {
  31123. if (keyListeners_ == 0)
  31124. keyListeners_ = new VoidArray (4);
  31125. keyListeners_->addIfNotAlreadyThere (newListener);
  31126. }
  31127. void Component::removeKeyListener (KeyListener* const listenerToRemove) throw()
  31128. {
  31129. if (keyListeners_ != 0)
  31130. keyListeners_->removeValue (listenerToRemove);
  31131. }
  31132. bool Component::keyPressed (const KeyPress&)
  31133. {
  31134. return false;
  31135. }
  31136. bool Component::keyStateChanged()
  31137. {
  31138. return false;
  31139. }
  31140. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  31141. {
  31142. if (parentComponent_ != 0)
  31143. parentComponent_->modifierKeysChanged (modifiers);
  31144. }
  31145. void Component::internalModifierKeysChanged()
  31146. {
  31147. sendFakeMouseMove();
  31148. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  31149. }
  31150. ComponentPeer* Component::getPeer() const throw()
  31151. {
  31152. if (flags.hasHeavyweightPeerFlag)
  31153. return ComponentPeer::getPeerFor (this);
  31154. else if (parentComponent_ != 0)
  31155. return parentComponent_->getPeer();
  31156. else
  31157. return 0;
  31158. }
  31159. const String Component::getComponentProperty (const String& keyName,
  31160. const bool useParentComponentIfNotFound,
  31161. const String& defaultReturnValue) const throw()
  31162. {
  31163. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  31164. return propertySet_->getValue (keyName, defaultReturnValue);
  31165. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  31166. return parentComponent_->getComponentProperty (keyName, true, defaultReturnValue);
  31167. return defaultReturnValue;
  31168. }
  31169. int Component::getComponentPropertyInt (const String& keyName,
  31170. const bool useParentComponentIfNotFound,
  31171. const int defaultReturnValue) const throw()
  31172. {
  31173. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  31174. return propertySet_->getIntValue (keyName, defaultReturnValue);
  31175. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  31176. return parentComponent_->getComponentPropertyInt (keyName, true, defaultReturnValue);
  31177. return defaultReturnValue;
  31178. }
  31179. double Component::getComponentPropertyDouble (const String& keyName,
  31180. const bool useParentComponentIfNotFound,
  31181. const double defaultReturnValue) const throw()
  31182. {
  31183. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  31184. return propertySet_->getDoubleValue (keyName, defaultReturnValue);
  31185. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  31186. return parentComponent_->getComponentPropertyDouble (keyName, true, defaultReturnValue);
  31187. return defaultReturnValue;
  31188. }
  31189. bool Component::getComponentPropertyBool (const String& keyName,
  31190. const bool useParentComponentIfNotFound,
  31191. const bool defaultReturnValue) const throw()
  31192. {
  31193. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  31194. return propertySet_->getBoolValue (keyName, defaultReturnValue);
  31195. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  31196. return parentComponent_->getComponentPropertyBool (keyName, true, defaultReturnValue);
  31197. return defaultReturnValue;
  31198. }
  31199. const Colour Component::getComponentPropertyColour (const String& keyName,
  31200. const bool useParentComponentIfNotFound,
  31201. const Colour& defaultReturnValue) const throw()
  31202. {
  31203. return Colour ((uint32) getComponentPropertyInt (keyName,
  31204. useParentComponentIfNotFound,
  31205. defaultReturnValue.getARGB()));
  31206. }
  31207. void Component::setComponentProperty (const String& keyName, const String& value) throw()
  31208. {
  31209. if (propertySet_ == 0)
  31210. propertySet_ = new PropertySet();
  31211. propertySet_->setValue (keyName, value);
  31212. }
  31213. void Component::setComponentProperty (const String& keyName, const int value) throw()
  31214. {
  31215. if (propertySet_ == 0)
  31216. propertySet_ = new PropertySet();
  31217. propertySet_->setValue (keyName, value);
  31218. }
  31219. void Component::setComponentProperty (const String& keyName, const double value) throw()
  31220. {
  31221. if (propertySet_ == 0)
  31222. propertySet_ = new PropertySet();
  31223. propertySet_->setValue (keyName, value);
  31224. }
  31225. void Component::setComponentProperty (const String& keyName, const bool value) throw()
  31226. {
  31227. if (propertySet_ == 0)
  31228. propertySet_ = new PropertySet();
  31229. propertySet_->setValue (keyName, value);
  31230. }
  31231. void Component::setComponentProperty (const String& keyName, const Colour& colour) throw()
  31232. {
  31233. setComponentProperty (keyName, (int) colour.getARGB());
  31234. }
  31235. void Component::removeComponentProperty (const String& keyName) throw()
  31236. {
  31237. if (propertySet_ != 0)
  31238. propertySet_->removeValue (keyName);
  31239. }
  31240. ComponentDeletionWatcher::ComponentDeletionWatcher (const Component* const componentToWatch_) throw()
  31241. : componentToWatch (componentToWatch_),
  31242. componentUID (componentToWatch_->getComponentUID())
  31243. {
  31244. // not possible to check on an already-deleted object..
  31245. jassert (componentToWatch_->isValidComponent());
  31246. }
  31247. ComponentDeletionWatcher::~ComponentDeletionWatcher() throw() {}
  31248. bool ComponentDeletionWatcher::hasBeenDeleted() const throw()
  31249. {
  31250. return ! (componentToWatch->isValidComponent()
  31251. && componentToWatch->getComponentUID() == componentUID);
  31252. }
  31253. const Component* ComponentDeletionWatcher::getComponent() const throw()
  31254. {
  31255. return hasBeenDeleted() ? 0 : componentToWatch;
  31256. }
  31257. END_JUCE_NAMESPACE
  31258. /********* End of inlined file: juce_Component.cpp *********/
  31259. /********* Start of inlined file: juce_ComponentListener.cpp *********/
  31260. BEGIN_JUCE_NAMESPACE
  31261. void ComponentListener::componentMovedOrResized (Component&, bool, bool)
  31262. {
  31263. }
  31264. void ComponentListener::componentBroughtToFront (Component&)
  31265. {
  31266. }
  31267. void ComponentListener::componentVisibilityChanged (Component&)
  31268. {
  31269. }
  31270. void ComponentListener::componentChildrenChanged (Component&)
  31271. {
  31272. }
  31273. void ComponentListener::componentParentHierarchyChanged (Component&)
  31274. {
  31275. }
  31276. void ComponentListener::componentNameChanged (Component&)
  31277. {
  31278. }
  31279. END_JUCE_NAMESPACE
  31280. /********* End of inlined file: juce_ComponentListener.cpp *********/
  31281. /********* Start of inlined file: juce_Desktop.cpp *********/
  31282. BEGIN_JUCE_NAMESPACE
  31283. extern void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords,
  31284. const bool clipToWorkArea) throw();
  31285. static Desktop* juce_desktopInstance = 0;
  31286. Desktop::Desktop() throw()
  31287. : mouseListeners (2),
  31288. desktopComponents (4),
  31289. monitorCoordsClipped (2),
  31290. monitorCoordsUnclipped (2),
  31291. lastMouseX (0),
  31292. lastMouseY (0)
  31293. {
  31294. refreshMonitorSizes();
  31295. }
  31296. Desktop::~Desktop() throw()
  31297. {
  31298. jassert (juce_desktopInstance == this);
  31299. juce_desktopInstance = 0;
  31300. // doh! If you don't delete all your windows before exiting, you're going to
  31301. // be leaking memory!
  31302. jassert (desktopComponents.size() == 0);
  31303. }
  31304. Desktop& JUCE_CALLTYPE Desktop::getInstance() throw()
  31305. {
  31306. if (juce_desktopInstance == 0)
  31307. juce_desktopInstance = new Desktop();
  31308. return *juce_desktopInstance;
  31309. }
  31310. void Desktop::refreshMonitorSizes() throw()
  31311. {
  31312. const Array <Rectangle> oldClipped (monitorCoordsClipped);
  31313. const Array <Rectangle> oldUnclipped (monitorCoordsUnclipped);
  31314. monitorCoordsClipped.clear();
  31315. monitorCoordsUnclipped.clear();
  31316. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  31317. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  31318. jassert (monitorCoordsClipped.size() > 0
  31319. && monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  31320. if (oldClipped != monitorCoordsClipped
  31321. || oldUnclipped != monitorCoordsUnclipped)
  31322. {
  31323. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  31324. {
  31325. ComponentPeer* const p = ComponentPeer::getPeer (i);
  31326. if (p != 0)
  31327. p->handleScreenSizeChange();
  31328. }
  31329. }
  31330. }
  31331. int Desktop::getNumDisplayMonitors() const throw()
  31332. {
  31333. return monitorCoordsClipped.size();
  31334. }
  31335. const Rectangle Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  31336. {
  31337. return clippedToWorkArea ? monitorCoordsClipped [index]
  31338. : monitorCoordsUnclipped [index];
  31339. }
  31340. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  31341. {
  31342. RectangleList rl;
  31343. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  31344. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  31345. return rl;
  31346. }
  31347. const Rectangle Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  31348. {
  31349. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  31350. }
  31351. const Rectangle Desktop::getMonitorAreaContaining (int cx, int cy, const bool clippedToWorkArea) const throw()
  31352. {
  31353. Rectangle best (getMainMonitorArea (clippedToWorkArea));
  31354. double bestDistance = 1.0e10;
  31355. for (int i = getNumDisplayMonitors(); --i >= 0;)
  31356. {
  31357. const Rectangle rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  31358. if (rect.contains (cx, cy))
  31359. return rect;
  31360. const double distance = juce_hypot ((double) (rect.getCentreX() - cx),
  31361. (double) (rect.getCentreY() - cy));
  31362. if (distance < bestDistance)
  31363. {
  31364. bestDistance = distance;
  31365. best = rect;
  31366. }
  31367. }
  31368. return best;
  31369. }
  31370. int Desktop::getNumComponents() const throw()
  31371. {
  31372. return desktopComponents.size();
  31373. }
  31374. Component* Desktop::getComponent (const int index) const throw()
  31375. {
  31376. return (Component*) desktopComponents [index];
  31377. }
  31378. Component* Desktop::findComponentAt (const int screenX,
  31379. const int screenY) const
  31380. {
  31381. for (int i = desktopComponents.size(); --i >= 0;)
  31382. {
  31383. Component* const c = (Component*) desktopComponents.getUnchecked(i);
  31384. int x = screenX, y = screenY;
  31385. c->globalPositionToRelative (x, y);
  31386. if (c->contains (x, y))
  31387. return c->getComponentAt (x, y);
  31388. }
  31389. return 0;
  31390. }
  31391. void Desktop::addDesktopComponent (Component* const c) throw()
  31392. {
  31393. jassert (c != 0);
  31394. jassert (! desktopComponents.contains (c));
  31395. desktopComponents.addIfNotAlreadyThere (c);
  31396. }
  31397. void Desktop::removeDesktopComponent (Component* const c) throw()
  31398. {
  31399. desktopComponents.removeValue (c);
  31400. }
  31401. void Desktop::componentBroughtToFront (Component* const c) throw()
  31402. {
  31403. const int index = desktopComponents.indexOf (c);
  31404. jassert (index >= 0);
  31405. if (index >= 0)
  31406. desktopComponents.move (index, -1);
  31407. }
  31408. // from Component.cpp
  31409. extern int juce_recentMouseDownX [4];
  31410. extern int juce_recentMouseDownY [4];
  31411. extern int juce_MouseClickCounter;
  31412. void Desktop::getLastMouseDownPosition (int& x, int& y) throw()
  31413. {
  31414. x = juce_recentMouseDownX [0];
  31415. y = juce_recentMouseDownY [0];
  31416. }
  31417. int Desktop::getMouseButtonClickCounter() throw()
  31418. {
  31419. return juce_MouseClickCounter;
  31420. }
  31421. void Desktop::addGlobalMouseListener (MouseListener* const listener) throw()
  31422. {
  31423. jassert (listener != 0);
  31424. if (listener != 0)
  31425. {
  31426. mouseListeners.add (listener);
  31427. resetTimer();
  31428. }
  31429. }
  31430. void Desktop::removeGlobalMouseListener (MouseListener* const listener) throw()
  31431. {
  31432. mouseListeners.removeValue (listener);
  31433. resetTimer();
  31434. }
  31435. void Desktop::addFocusChangeListener (FocusChangeListener* const listener) throw()
  31436. {
  31437. jassert (listener != 0);
  31438. if (listener != 0)
  31439. focusListeners.add (listener);
  31440. }
  31441. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener) throw()
  31442. {
  31443. focusListeners.removeValue (listener);
  31444. }
  31445. void Desktop::triggerFocusCallback() throw()
  31446. {
  31447. triggerAsyncUpdate();
  31448. }
  31449. void Desktop::handleAsyncUpdate()
  31450. {
  31451. for (int i = focusListeners.size(); --i >= 0;)
  31452. {
  31453. ((FocusChangeListener*) focusListeners.getUnchecked (i))->globalFocusChanged (Component::getCurrentlyFocusedComponent());
  31454. i = jmin (i, focusListeners.size());
  31455. }
  31456. }
  31457. void Desktop::timerCallback()
  31458. {
  31459. int x, y;
  31460. getMousePosition (x, y);
  31461. if (lastMouseX != x || lastMouseY != y)
  31462. sendMouseMove();
  31463. }
  31464. void Desktop::sendMouseMove()
  31465. {
  31466. if (mouseListeners.size() > 0)
  31467. {
  31468. startTimer (20);
  31469. int x, y;
  31470. getMousePosition (x, y);
  31471. lastMouseX = x;
  31472. lastMouseY = y;
  31473. Component* const target = findComponentAt (x, y);
  31474. if (target != 0)
  31475. {
  31476. target->globalPositionToRelative (x, y);
  31477. ComponentDeletionWatcher deletionChecker (target);
  31478. const MouseEvent me (x, y,
  31479. ModifierKeys::getCurrentModifiers(),
  31480. target,
  31481. Time::getCurrentTime(),
  31482. x, y,
  31483. Time::getCurrentTime(),
  31484. 0, false);
  31485. for (int i = mouseListeners.size(); --i >= 0;)
  31486. {
  31487. if (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  31488. ((MouseListener*) mouseListeners[i])->mouseDrag (me);
  31489. else
  31490. ((MouseListener*) mouseListeners[i])->mouseMove (me);
  31491. if (deletionChecker.hasBeenDeleted())
  31492. return;
  31493. i = jmin (i, mouseListeners.size());
  31494. }
  31495. }
  31496. }
  31497. }
  31498. void Desktop::resetTimer() throw()
  31499. {
  31500. if (mouseListeners.size() == 0)
  31501. stopTimer();
  31502. else
  31503. startTimer (100);
  31504. getMousePosition (lastMouseX, lastMouseY);
  31505. }
  31506. END_JUCE_NAMESPACE
  31507. /********* End of inlined file: juce_Desktop.cpp *********/
  31508. /********* Start of inlined file: juce_ArrowButton.cpp *********/
  31509. BEGIN_JUCE_NAMESPACE
  31510. ArrowButton::ArrowButton (const String& name,
  31511. float arrowDirectionInRadians,
  31512. const Colour& arrowColour)
  31513. : Button (name),
  31514. colour (arrowColour)
  31515. {
  31516. path.lineTo (0.0f, 1.0f);
  31517. path.lineTo (1.0f, 0.5f);
  31518. path.closeSubPath();
  31519. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  31520. 0.5f, 0.5f));
  31521. setComponentEffect (&shadow);
  31522. buttonStateChanged();
  31523. }
  31524. ArrowButton::~ArrowButton()
  31525. {
  31526. }
  31527. void ArrowButton::paintButton (Graphics& g,
  31528. bool /*isMouseOverButton*/,
  31529. bool /*isButtonDown*/)
  31530. {
  31531. g.setColour (colour);
  31532. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  31533. (float) offset,
  31534. (float) (getWidth() - 3),
  31535. (float) (getHeight() - 3),
  31536. false));
  31537. }
  31538. void ArrowButton::buttonStateChanged()
  31539. {
  31540. offset = (isDown()) ? 1 : 0;
  31541. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  31542. 0.3f, -1, 0);
  31543. }
  31544. END_JUCE_NAMESPACE
  31545. /********* End of inlined file: juce_ArrowButton.cpp *********/
  31546. /********* Start of inlined file: juce_Button.cpp *********/
  31547. BEGIN_JUCE_NAMESPACE
  31548. Button::Button (const String& name)
  31549. : Component (name),
  31550. shortcuts (2),
  31551. keySource (0),
  31552. text (name),
  31553. buttonListeners (2),
  31554. repeatTimer (0),
  31555. buttonPressTime (0),
  31556. lastTimeCallbackTime (0),
  31557. commandManagerToUse (0),
  31558. autoRepeatDelay (-1),
  31559. autoRepeatSpeed (0),
  31560. autoRepeatMinimumDelay (-1),
  31561. radioGroupId (0),
  31562. commandID (0),
  31563. connectedEdgeFlags (0),
  31564. buttonState (buttonNormal),
  31565. isOn (false),
  31566. clickTogglesState (false),
  31567. needsToRelease (false),
  31568. needsRepainting (false),
  31569. isKeyDown (false),
  31570. triggerOnMouseDown (false),
  31571. generateTooltip (false)
  31572. {
  31573. setWantsKeyboardFocus (true);
  31574. }
  31575. Button::~Button()
  31576. {
  31577. if (commandManagerToUse != 0)
  31578. commandManagerToUse->removeListener (this);
  31579. delete repeatTimer;
  31580. clearShortcuts();
  31581. }
  31582. void Button::setButtonText (const String& newText) throw()
  31583. {
  31584. if (text != newText)
  31585. {
  31586. text = newText;
  31587. repaint();
  31588. }
  31589. }
  31590. void Button::setTooltip (const String& newTooltip)
  31591. {
  31592. SettableTooltipClient::setTooltip (newTooltip);
  31593. generateTooltip = false;
  31594. }
  31595. const String Button::getTooltip()
  31596. {
  31597. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  31598. {
  31599. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  31600. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  31601. for (int i = 0; i < keyPresses.size(); ++i)
  31602. {
  31603. const String key (keyPresses.getReference(i).getTextDescription());
  31604. if (key.length() == 1)
  31605. tt << " [shortcut: '" << key << "']";
  31606. else
  31607. tt << " [" << key << ']';
  31608. }
  31609. return tt;
  31610. }
  31611. return SettableTooltipClient::getTooltip();
  31612. }
  31613. void Button::setConnectedEdges (const int connectedEdgeFlags_) throw()
  31614. {
  31615. if (connectedEdgeFlags != connectedEdgeFlags_)
  31616. {
  31617. connectedEdgeFlags = connectedEdgeFlags_;
  31618. repaint();
  31619. }
  31620. }
  31621. void Button::setToggleState (const bool shouldBeOn,
  31622. const bool sendChangeNotification)
  31623. {
  31624. if (shouldBeOn != isOn)
  31625. {
  31626. const ComponentDeletionWatcher deletionWatcher (this);
  31627. isOn = shouldBeOn;
  31628. repaint();
  31629. if (sendChangeNotification)
  31630. sendClickMessage (ModifierKeys());
  31631. if ((! deletionWatcher.hasBeenDeleted()) && isOn)
  31632. turnOffOtherButtonsInGroup (sendChangeNotification);
  31633. }
  31634. }
  31635. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  31636. {
  31637. clickTogglesState = shouldToggle;
  31638. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  31639. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  31640. // it is that this button represents, and the button will update its state to reflect this
  31641. // in the applicationCommandListChanged() method.
  31642. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  31643. }
  31644. bool Button::getClickingTogglesState() const throw()
  31645. {
  31646. return clickTogglesState;
  31647. }
  31648. void Button::setRadioGroupId (const int newGroupId)
  31649. {
  31650. if (radioGroupId != newGroupId)
  31651. {
  31652. radioGroupId = newGroupId;
  31653. if (isOn)
  31654. turnOffOtherButtonsInGroup (true);
  31655. }
  31656. }
  31657. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  31658. {
  31659. Component* const p = getParentComponent();
  31660. if (p != 0 && radioGroupId != 0)
  31661. {
  31662. const ComponentDeletionWatcher deletionWatcher (this);
  31663. for (int i = p->getNumChildComponents(); --i >= 0;)
  31664. {
  31665. Component* const c = p->getChildComponent (i);
  31666. if (c != this)
  31667. {
  31668. Button* const b = dynamic_cast <Button*> (c);
  31669. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  31670. {
  31671. b->setToggleState (false, sendChangeNotification);
  31672. if (deletionWatcher.hasBeenDeleted())
  31673. return;
  31674. }
  31675. }
  31676. }
  31677. }
  31678. }
  31679. void Button::enablementChanged()
  31680. {
  31681. updateState (0);
  31682. repaint();
  31683. }
  31684. Button::ButtonState Button::updateState (const MouseEvent* const e) throw()
  31685. {
  31686. ButtonState state = buttonNormal;
  31687. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  31688. {
  31689. int mx, my;
  31690. if (e == 0)
  31691. {
  31692. getMouseXYRelative (mx, my);
  31693. }
  31694. else
  31695. {
  31696. const MouseEvent e2 (e->getEventRelativeTo (this));
  31697. mx = e2.x;
  31698. my = e2.y;
  31699. }
  31700. const bool over = reallyContains (mx, my, true);
  31701. const bool down = isMouseButtonDown();
  31702. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  31703. state = buttonDown;
  31704. else if (over)
  31705. state = buttonOver;
  31706. }
  31707. setState (state);
  31708. return state;
  31709. }
  31710. void Button::setState (const ButtonState newState)
  31711. {
  31712. if (buttonState != newState)
  31713. {
  31714. buttonState = newState;
  31715. repaint();
  31716. if (buttonState == buttonDown)
  31717. {
  31718. buttonPressTime = Time::getApproximateMillisecondCounter();
  31719. lastTimeCallbackTime = buttonPressTime;
  31720. }
  31721. sendStateMessage();
  31722. }
  31723. }
  31724. bool Button::isDown() const throw()
  31725. {
  31726. return buttonState == buttonDown;
  31727. }
  31728. bool Button::isOver() const throw()
  31729. {
  31730. return buttonState != buttonNormal;
  31731. }
  31732. void Button::buttonStateChanged()
  31733. {
  31734. }
  31735. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  31736. {
  31737. const uint32 now = Time::getApproximateMillisecondCounter();
  31738. return now > buttonPressTime ? now - buttonPressTime : 0;
  31739. }
  31740. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  31741. {
  31742. triggerOnMouseDown = isTriggeredOnMouseDown;
  31743. }
  31744. void Button::clicked()
  31745. {
  31746. }
  31747. void Button::clicked (const ModifierKeys& /*modifiers*/)
  31748. {
  31749. clicked();
  31750. }
  31751. static const int clickMessageId = 0x2f3f4f99;
  31752. void Button::triggerClick()
  31753. {
  31754. postCommandMessage (clickMessageId);
  31755. }
  31756. void Button::internalClickCallback (const ModifierKeys& modifiers)
  31757. {
  31758. if (clickTogglesState)
  31759. setToggleState ((radioGroupId != 0) || ! isOn, false);
  31760. sendClickMessage (modifiers);
  31761. }
  31762. void Button::flashButtonState() throw()
  31763. {
  31764. if (isEnabled())
  31765. {
  31766. needsToRelease = true;
  31767. setState (buttonDown);
  31768. getRepeatTimer().startTimer (100);
  31769. }
  31770. }
  31771. void Button::handleCommandMessage (int commandId)
  31772. {
  31773. if (commandId == clickMessageId)
  31774. {
  31775. if (isEnabled())
  31776. {
  31777. flashButtonState();
  31778. internalClickCallback (ModifierKeys::getCurrentModifiers());
  31779. }
  31780. }
  31781. else
  31782. {
  31783. Component::handleCommandMessage (commandId);
  31784. }
  31785. }
  31786. void Button::addButtonListener (ButtonListener* const newListener) throw()
  31787. {
  31788. jassert (newListener != 0);
  31789. jassert (! buttonListeners.contains (newListener)); // trying to add a listener to the list twice!
  31790. if (newListener != 0)
  31791. buttonListeners.add (newListener);
  31792. }
  31793. void Button::removeButtonListener (ButtonListener* const listener) throw()
  31794. {
  31795. jassert (buttonListeners.contains (listener)); // trying to remove a listener that isn't on the list!
  31796. buttonListeners.removeValue (listener);
  31797. }
  31798. void Button::sendClickMessage (const ModifierKeys& modifiers)
  31799. {
  31800. const ComponentDeletionWatcher cdw (this);
  31801. if (commandManagerToUse != 0 && commandID != 0)
  31802. {
  31803. ApplicationCommandTarget::InvocationInfo info (commandID);
  31804. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  31805. info.originatingComponent = this;
  31806. commandManagerToUse->invoke (info, true);
  31807. }
  31808. clicked (modifiers);
  31809. if (! cdw.hasBeenDeleted())
  31810. {
  31811. for (int i = buttonListeners.size(); --i >= 0;)
  31812. {
  31813. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  31814. if (bl != 0)
  31815. {
  31816. bl->buttonClicked (this);
  31817. if (cdw.hasBeenDeleted())
  31818. return;
  31819. }
  31820. }
  31821. }
  31822. }
  31823. void Button::sendStateMessage()
  31824. {
  31825. const ComponentDeletionWatcher cdw (this);
  31826. buttonStateChanged();
  31827. if (cdw.hasBeenDeleted())
  31828. return;
  31829. for (int i = buttonListeners.size(); --i >= 0;)
  31830. {
  31831. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  31832. if (bl != 0)
  31833. {
  31834. bl->buttonStateChanged (this);
  31835. if (cdw.hasBeenDeleted())
  31836. return;
  31837. }
  31838. }
  31839. }
  31840. void Button::paint (Graphics& g)
  31841. {
  31842. if (needsToRelease && isEnabled())
  31843. {
  31844. needsToRelease = false;
  31845. needsRepainting = true;
  31846. }
  31847. paintButton (g, isOver(), isDown());
  31848. }
  31849. void Button::mouseEnter (const MouseEvent& e)
  31850. {
  31851. updateState (&e);
  31852. }
  31853. void Button::mouseExit (const MouseEvent& e)
  31854. {
  31855. updateState (&e);
  31856. }
  31857. void Button::mouseDown (const MouseEvent& e)
  31858. {
  31859. updateState (&e);
  31860. if (isDown())
  31861. {
  31862. if (autoRepeatDelay >= 0)
  31863. getRepeatTimer().startTimer (autoRepeatDelay);
  31864. if (triggerOnMouseDown)
  31865. internalClickCallback (e.mods);
  31866. }
  31867. }
  31868. void Button::mouseUp (const MouseEvent& e)
  31869. {
  31870. const bool wasDown = isDown();
  31871. updateState (&e);
  31872. if (wasDown && isOver() && ! triggerOnMouseDown)
  31873. internalClickCallback (e.mods);
  31874. }
  31875. void Button::mouseDrag (const MouseEvent& e)
  31876. {
  31877. const ButtonState oldState = buttonState;
  31878. updateState (&e);
  31879. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  31880. getRepeatTimer().startTimer (autoRepeatSpeed);
  31881. }
  31882. void Button::focusGained (FocusChangeType)
  31883. {
  31884. updateState (0);
  31885. repaint();
  31886. }
  31887. void Button::focusLost (FocusChangeType)
  31888. {
  31889. updateState (0);
  31890. repaint();
  31891. }
  31892. void Button::setVisible (bool shouldBeVisible)
  31893. {
  31894. if (shouldBeVisible != isVisible())
  31895. {
  31896. Component::setVisible (shouldBeVisible);
  31897. if (! shouldBeVisible)
  31898. needsToRelease = false;
  31899. updateState (0);
  31900. }
  31901. else
  31902. {
  31903. Component::setVisible (shouldBeVisible);
  31904. }
  31905. }
  31906. void Button::parentHierarchyChanged()
  31907. {
  31908. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  31909. if (newKeySource != keySource)
  31910. {
  31911. if (keySource->isValidComponent())
  31912. keySource->removeKeyListener (this);
  31913. keySource = newKeySource;
  31914. if (keySource->isValidComponent())
  31915. keySource->addKeyListener (this);
  31916. }
  31917. }
  31918. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  31919. const int commandID_,
  31920. const bool generateTooltip_)
  31921. {
  31922. commandID = commandID_;
  31923. generateTooltip = generateTooltip_;
  31924. if (commandManagerToUse != commandManagerToUse_)
  31925. {
  31926. if (commandManagerToUse != 0)
  31927. commandManagerToUse->removeListener (this);
  31928. commandManagerToUse = commandManagerToUse_;
  31929. if (commandManagerToUse != 0)
  31930. commandManagerToUse->addListener (this);
  31931. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  31932. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  31933. // it is that this button represents, and the button will update its state to reflect this
  31934. // in the applicationCommandListChanged() method.
  31935. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  31936. }
  31937. if (commandManagerToUse != 0)
  31938. applicationCommandListChanged();
  31939. else
  31940. setEnabled (true);
  31941. }
  31942. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  31943. {
  31944. if (info.commandID == commandID
  31945. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  31946. {
  31947. flashButtonState();
  31948. }
  31949. }
  31950. void Button::applicationCommandListChanged()
  31951. {
  31952. if (commandManagerToUse != 0)
  31953. {
  31954. ApplicationCommandInfo info (0);
  31955. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  31956. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  31957. if (target != 0)
  31958. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  31959. }
  31960. }
  31961. void Button::addShortcut (const KeyPress& key)
  31962. {
  31963. if (key.isValid())
  31964. {
  31965. jassert (! isRegisteredForShortcut (key)); // already registered!
  31966. shortcuts.add (key);
  31967. parentHierarchyChanged();
  31968. }
  31969. }
  31970. void Button::clearShortcuts()
  31971. {
  31972. shortcuts.clear();
  31973. parentHierarchyChanged();
  31974. }
  31975. bool Button::isShortcutPressed() const throw()
  31976. {
  31977. if (! isCurrentlyBlockedByAnotherModalComponent())
  31978. {
  31979. for (int i = shortcuts.size(); --i >= 0;)
  31980. if (shortcuts.getReference(i).isCurrentlyDown())
  31981. return true;
  31982. }
  31983. return false;
  31984. }
  31985. bool Button::isRegisteredForShortcut (const KeyPress& key) const throw()
  31986. {
  31987. for (int i = shortcuts.size(); --i >= 0;)
  31988. if (key == shortcuts.getReference(i))
  31989. return true;
  31990. return false;
  31991. }
  31992. bool Button::keyStateChanged (Component*)
  31993. {
  31994. if (! isEnabled())
  31995. return false;
  31996. const bool wasDown = isKeyDown;
  31997. isKeyDown = isShortcutPressed();
  31998. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  31999. getRepeatTimer().startTimer (autoRepeatDelay);
  32000. updateState (0);
  32001. if (isEnabled() && wasDown && ! isKeyDown)
  32002. internalClickCallback (ModifierKeys::getCurrentModifiers());
  32003. return isKeyDown || wasDown;
  32004. }
  32005. bool Button::keyPressed (const KeyPress&, Component*)
  32006. {
  32007. // returning true will avoid forwarding events for keys that we're using as shortcuts
  32008. return isShortcutPressed();
  32009. }
  32010. bool Button::keyPressed (const KeyPress& key)
  32011. {
  32012. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  32013. {
  32014. triggerClick();
  32015. return true;
  32016. }
  32017. return false;
  32018. }
  32019. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  32020. const int repeatMillisecs,
  32021. const int minimumDelayInMillisecs) throw()
  32022. {
  32023. autoRepeatDelay = initialDelayMillisecs;
  32024. autoRepeatSpeed = repeatMillisecs;
  32025. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  32026. }
  32027. void Button::repeatTimerCallback() throw()
  32028. {
  32029. if (needsRepainting)
  32030. {
  32031. getRepeatTimer().stopTimer();
  32032. updateState (0);
  32033. needsRepainting = false;
  32034. }
  32035. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  32036. {
  32037. int repeatSpeed = autoRepeatSpeed;
  32038. if (autoRepeatMinimumDelay >= 0)
  32039. {
  32040. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  32041. timeHeldDown *= timeHeldDown;
  32042. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  32043. }
  32044. repeatSpeed = jmax (1, repeatSpeed);
  32045. getRepeatTimer().startTimer (repeatSpeed);
  32046. const uint32 now = Time::getApproximateMillisecondCounter();
  32047. const int numTimesToCallback
  32048. = (now > lastTimeCallbackTime) ? jmax (1, (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  32049. lastTimeCallbackTime = now;
  32050. const ComponentDeletionWatcher cdw (this);
  32051. for (int i = numTimesToCallback; --i >= 0;)
  32052. {
  32053. internalClickCallback (ModifierKeys::getCurrentModifiers());
  32054. if (cdw.hasBeenDeleted() || ! isDown())
  32055. return;
  32056. }
  32057. }
  32058. else if (! needsToRelease)
  32059. {
  32060. getRepeatTimer().stopTimer();
  32061. }
  32062. }
  32063. class InternalButtonRepeatTimer : public Timer
  32064. {
  32065. public:
  32066. InternalButtonRepeatTimer (Button& owner_) throw()
  32067. : owner (owner_)
  32068. {
  32069. }
  32070. ~InternalButtonRepeatTimer()
  32071. {
  32072. }
  32073. void timerCallback()
  32074. {
  32075. owner.repeatTimerCallback();
  32076. }
  32077. private:
  32078. Button& owner;
  32079. InternalButtonRepeatTimer (const InternalButtonRepeatTimer&);
  32080. const InternalButtonRepeatTimer& operator= (const InternalButtonRepeatTimer&);
  32081. };
  32082. Timer& Button::getRepeatTimer() throw()
  32083. {
  32084. if (repeatTimer == 0)
  32085. repeatTimer = new InternalButtonRepeatTimer (*this);
  32086. return *repeatTimer;
  32087. }
  32088. END_JUCE_NAMESPACE
  32089. /********* End of inlined file: juce_Button.cpp *********/
  32090. /********* Start of inlined file: juce_DrawableButton.cpp *********/
  32091. BEGIN_JUCE_NAMESPACE
  32092. DrawableButton::DrawableButton (const String& name,
  32093. const DrawableButton::ButtonStyle buttonStyle)
  32094. : Button (name),
  32095. style (buttonStyle),
  32096. normalImage (0),
  32097. overImage (0),
  32098. downImage (0),
  32099. disabledImage (0),
  32100. normalImageOn (0),
  32101. overImageOn (0),
  32102. downImageOn (0),
  32103. disabledImageOn (0),
  32104. edgeIndent (3)
  32105. {
  32106. if (buttonStyle == ImageOnButtonBackground)
  32107. {
  32108. backgroundOff = Colour (0xffbbbbff);
  32109. backgroundOn = Colour (0xff3333ff);
  32110. }
  32111. else
  32112. {
  32113. backgroundOff = Colours::transparentBlack;
  32114. backgroundOn = Colour (0xaabbbbff);
  32115. }
  32116. }
  32117. DrawableButton::~DrawableButton()
  32118. {
  32119. deleteImages();
  32120. }
  32121. void DrawableButton::deleteImages()
  32122. {
  32123. deleteAndZero (normalImage);
  32124. deleteAndZero (overImage);
  32125. deleteAndZero (downImage);
  32126. deleteAndZero (disabledImage);
  32127. deleteAndZero (normalImageOn);
  32128. deleteAndZero (overImageOn);
  32129. deleteAndZero (downImageOn);
  32130. deleteAndZero (disabledImageOn);
  32131. }
  32132. void DrawableButton::setImages (const Drawable* normal,
  32133. const Drawable* over,
  32134. const Drawable* down,
  32135. const Drawable* disabled,
  32136. const Drawable* normalOn,
  32137. const Drawable* overOn,
  32138. const Drawable* downOn,
  32139. const Drawable* disabledOn)
  32140. {
  32141. deleteImages();
  32142. jassert (normal != 0); // you really need to give it at least a normal image..
  32143. if (normal != 0)
  32144. normalImage = normal->createCopy();
  32145. if (over != 0)
  32146. overImage = over->createCopy();
  32147. if (down != 0)
  32148. downImage = down->createCopy();
  32149. if (disabled != 0)
  32150. disabledImage = disabled->createCopy();
  32151. if (normalOn != 0)
  32152. normalImageOn = normalOn->createCopy();
  32153. if (overOn != 0)
  32154. overImageOn = overOn->createCopy();
  32155. if (downOn != 0)
  32156. downImageOn = downOn->createCopy();
  32157. if (disabledOn != 0)
  32158. disabledImageOn = disabledOn->createCopy();
  32159. repaint();
  32160. }
  32161. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  32162. {
  32163. if (style != newStyle)
  32164. {
  32165. style = newStyle;
  32166. repaint();
  32167. }
  32168. }
  32169. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  32170. const Colour& toggledOnColour)
  32171. {
  32172. if (backgroundOff != toggledOffColour
  32173. || backgroundOn != toggledOnColour)
  32174. {
  32175. backgroundOff = toggledOffColour;
  32176. backgroundOn = toggledOnColour;
  32177. repaint();
  32178. }
  32179. }
  32180. const Colour& DrawableButton::getBackgroundColour() const throw()
  32181. {
  32182. return getToggleState() ? backgroundOn
  32183. : backgroundOff;
  32184. }
  32185. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  32186. {
  32187. edgeIndent = numPixelsIndent;
  32188. repaint();
  32189. }
  32190. void DrawableButton::paintButton (Graphics& g,
  32191. bool isMouseOverButton,
  32192. bool isButtonDown)
  32193. {
  32194. Rectangle imageSpace;
  32195. if (style == ImageOnButtonBackground)
  32196. {
  32197. const int insetX = getWidth() / 4;
  32198. const int insetY = getHeight() / 4;
  32199. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  32200. getLookAndFeel().drawButtonBackground (g, *this,
  32201. getBackgroundColour(),
  32202. isMouseOverButton,
  32203. isButtonDown);
  32204. }
  32205. else
  32206. {
  32207. g.fillAll (getBackgroundColour());
  32208. const int textH = (style == ImageAboveTextLabel)
  32209. ? jmin (16, proportionOfHeight (0.25f))
  32210. : 0;
  32211. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  32212. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  32213. imageSpace.setBounds (indentX, indentY,
  32214. getWidth() - indentX * 2,
  32215. getHeight() - indentY * 2 - textH);
  32216. if (textH > 0)
  32217. {
  32218. g.setFont ((float) textH);
  32219. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  32220. g.drawFittedText (getName(),
  32221. 2, getHeight() - textH - 1,
  32222. getWidth() - 4, textH,
  32223. Justification::centred, 1);
  32224. }
  32225. }
  32226. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  32227. g.setOpacity (1.0f);
  32228. const Drawable* imageToDraw = 0;
  32229. if (isEnabled())
  32230. {
  32231. imageToDraw = getCurrentImage();
  32232. }
  32233. else
  32234. {
  32235. imageToDraw = getToggleState() ? disabledImageOn
  32236. : disabledImage;
  32237. if (imageToDraw == 0)
  32238. {
  32239. g.setOpacity (0.4f);
  32240. imageToDraw = getNormalImage();
  32241. }
  32242. }
  32243. if (imageToDraw != 0)
  32244. {
  32245. if (style == ImageRaw)
  32246. {
  32247. imageToDraw->draw (g);
  32248. }
  32249. else
  32250. {
  32251. imageToDraw->drawWithin (g,
  32252. imageSpace.getX(),
  32253. imageSpace.getY(),
  32254. imageSpace.getWidth(),
  32255. imageSpace.getHeight(),
  32256. RectanglePlacement::centred);
  32257. }
  32258. }
  32259. }
  32260. const Drawable* DrawableButton::getCurrentImage() const throw()
  32261. {
  32262. if (isDown())
  32263. return getDownImage();
  32264. if (isOver())
  32265. return getOverImage();
  32266. return getNormalImage();
  32267. }
  32268. const Drawable* DrawableButton::getNormalImage() const throw()
  32269. {
  32270. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  32271. : normalImage;
  32272. }
  32273. const Drawable* DrawableButton::getOverImage() const throw()
  32274. {
  32275. const Drawable* d = normalImage;
  32276. if (getToggleState())
  32277. {
  32278. if (overImageOn != 0)
  32279. d = overImageOn;
  32280. else if (normalImageOn != 0)
  32281. d = normalImageOn;
  32282. else if (overImage != 0)
  32283. d = overImage;
  32284. }
  32285. else
  32286. {
  32287. if (overImage != 0)
  32288. d = overImage;
  32289. }
  32290. return d;
  32291. }
  32292. const Drawable* DrawableButton::getDownImage() const throw()
  32293. {
  32294. const Drawable* d = normalImage;
  32295. if (getToggleState())
  32296. {
  32297. if (downImageOn != 0)
  32298. d = downImageOn;
  32299. else if (overImageOn != 0)
  32300. d = overImageOn;
  32301. else if (normalImageOn != 0)
  32302. d = normalImageOn;
  32303. else if (downImage != 0)
  32304. d = downImage;
  32305. else
  32306. d = getOverImage();
  32307. }
  32308. else
  32309. {
  32310. if (downImage != 0)
  32311. d = downImage;
  32312. else
  32313. d = getOverImage();
  32314. }
  32315. return d;
  32316. }
  32317. END_JUCE_NAMESPACE
  32318. /********* End of inlined file: juce_DrawableButton.cpp *********/
  32319. /********* Start of inlined file: juce_HyperlinkButton.cpp *********/
  32320. BEGIN_JUCE_NAMESPACE
  32321. HyperlinkButton::HyperlinkButton (const String& linkText,
  32322. const URL& linkURL)
  32323. : Button (linkText),
  32324. url (linkURL),
  32325. font (14.0f, Font::underlined),
  32326. resizeFont (true),
  32327. justification (Justification::centred)
  32328. {
  32329. setMouseCursor (MouseCursor::PointingHandCursor);
  32330. setTooltip (linkURL.toString (false));
  32331. }
  32332. HyperlinkButton::~HyperlinkButton()
  32333. {
  32334. }
  32335. void HyperlinkButton::setFont (const Font& newFont,
  32336. const bool resizeToMatchComponentHeight,
  32337. const Justification& justificationType)
  32338. {
  32339. font = newFont;
  32340. resizeFont = resizeToMatchComponentHeight;
  32341. justification = justificationType;
  32342. repaint();
  32343. }
  32344. void HyperlinkButton::setURL (const URL& newURL) throw()
  32345. {
  32346. url = newURL;
  32347. setTooltip (newURL.toString (false));
  32348. }
  32349. const Font HyperlinkButton::getFontToUse() const
  32350. {
  32351. Font f (font);
  32352. if (resizeFont)
  32353. f.setHeight (getHeight() * 0.7f);
  32354. return f;
  32355. }
  32356. void HyperlinkButton::changeWidthToFitText()
  32357. {
  32358. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  32359. }
  32360. void HyperlinkButton::colourChanged()
  32361. {
  32362. repaint();
  32363. }
  32364. void HyperlinkButton::clicked()
  32365. {
  32366. if (url.isWellFormed())
  32367. url.launchInDefaultBrowser();
  32368. }
  32369. void HyperlinkButton::paintButton (Graphics& g,
  32370. bool isMouseOverButton,
  32371. bool isButtonDown)
  32372. {
  32373. const Colour textColour (findColour (textColourId));
  32374. if (isEnabled())
  32375. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  32376. : textColour);
  32377. else
  32378. g.setColour (textColour.withMultipliedAlpha (0.4f));
  32379. g.setFont (getFontToUse());
  32380. g.drawText (getButtonText(),
  32381. 2, 0, getWidth() - 2, getHeight(),
  32382. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  32383. true);
  32384. }
  32385. END_JUCE_NAMESPACE
  32386. /********* End of inlined file: juce_HyperlinkButton.cpp *********/
  32387. /********* Start of inlined file: juce_ImageButton.cpp *********/
  32388. BEGIN_JUCE_NAMESPACE
  32389. ImageButton::ImageButton (const String& text)
  32390. : Button (text),
  32391. scaleImageToFit (true),
  32392. preserveProportions (true),
  32393. alphaThreshold (0),
  32394. imageX (0),
  32395. imageY (0),
  32396. imageW (0),
  32397. imageH (0),
  32398. normalImage (0),
  32399. overImage (0),
  32400. downImage (0)
  32401. {
  32402. }
  32403. ImageButton::~ImageButton()
  32404. {
  32405. deleteImages();
  32406. }
  32407. void ImageButton::deleteImages()
  32408. {
  32409. if (normalImage != 0)
  32410. {
  32411. if (ImageCache::isImageInCache (normalImage))
  32412. ImageCache::release (normalImage);
  32413. else
  32414. delete normalImage;
  32415. }
  32416. if (overImage != 0)
  32417. {
  32418. if (ImageCache::isImageInCache (overImage))
  32419. ImageCache::release (overImage);
  32420. else
  32421. delete overImage;
  32422. }
  32423. if (downImage != 0)
  32424. {
  32425. if (ImageCache::isImageInCache (downImage))
  32426. ImageCache::release (downImage);
  32427. else
  32428. delete downImage;
  32429. }
  32430. }
  32431. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  32432. const bool rescaleImagesWhenButtonSizeChanges,
  32433. const bool preserveImageProportions,
  32434. Image* const normalImage_,
  32435. const float imageOpacityWhenNormal,
  32436. const Colour& overlayColourWhenNormal,
  32437. Image* const overImage_,
  32438. const float imageOpacityWhenOver,
  32439. const Colour& overlayColourWhenOver,
  32440. Image* const downImage_,
  32441. const float imageOpacityWhenDown,
  32442. const Colour& overlayColourWhenDown,
  32443. const float hitTestAlphaThreshold)
  32444. {
  32445. deleteImages();
  32446. normalImage = normalImage_;
  32447. overImage = overImage_;
  32448. downImage = downImage_;
  32449. if (resizeButtonNowToFitThisImage && normalImage != 0)
  32450. {
  32451. imageW = normalImage->getWidth();
  32452. imageH = normalImage->getHeight();
  32453. setSize (imageW, imageH);
  32454. }
  32455. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  32456. preserveProportions = preserveImageProportions;
  32457. normalOpacity = imageOpacityWhenNormal;
  32458. normalOverlay = overlayColourWhenNormal;
  32459. overOpacity = imageOpacityWhenOver;
  32460. overOverlay = overlayColourWhenOver;
  32461. downOpacity = imageOpacityWhenDown;
  32462. downOverlay = overlayColourWhenDown;
  32463. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundFloatToInt (255.0f * hitTestAlphaThreshold));
  32464. repaint();
  32465. }
  32466. Image* ImageButton::getCurrentImage() const
  32467. {
  32468. if (isDown())
  32469. return getDownImage();
  32470. if (isOver())
  32471. return getOverImage();
  32472. return getNormalImage();
  32473. }
  32474. Image* ImageButton::getNormalImage() const throw()
  32475. {
  32476. return normalImage;
  32477. }
  32478. Image* ImageButton::getOverImage() const throw()
  32479. {
  32480. return (overImage != 0) ? overImage
  32481. : normalImage;
  32482. }
  32483. Image* ImageButton::getDownImage() const throw()
  32484. {
  32485. return (downImage != 0) ? downImage
  32486. : getOverImage();
  32487. }
  32488. void ImageButton::paintButton (Graphics& g,
  32489. bool isMouseOverButton,
  32490. bool isButtonDown)
  32491. {
  32492. if (! isEnabled())
  32493. {
  32494. isMouseOverButton = false;
  32495. isButtonDown = false;
  32496. }
  32497. Image* const im = getCurrentImage();
  32498. if (im != 0)
  32499. {
  32500. const int iw = im->getWidth();
  32501. const int ih = im->getHeight();
  32502. imageW = getWidth();
  32503. imageH = getHeight();
  32504. imageX = (imageW - iw) >> 1;
  32505. imageY = (imageH - ih) >> 1;
  32506. if (scaleImageToFit)
  32507. {
  32508. if (preserveProportions)
  32509. {
  32510. int newW, newH;
  32511. const float imRatio = ih / (float)iw;
  32512. const float destRatio = imageH / (float)imageW;
  32513. if (imRatio > destRatio)
  32514. {
  32515. newW = roundFloatToInt (imageH / imRatio);
  32516. newH = imageH;
  32517. }
  32518. else
  32519. {
  32520. newW = imageW;
  32521. newH = roundFloatToInt (imageW * imRatio);
  32522. }
  32523. imageX = (imageW - newW) / 2;
  32524. imageY = (imageH - newH) / 2;
  32525. imageW = newW;
  32526. imageH = newH;
  32527. }
  32528. else
  32529. {
  32530. imageX = 0;
  32531. imageY = 0;
  32532. }
  32533. }
  32534. const Colour& overlayColour = (isButtonDown) ? downOverlay
  32535. : ((isMouseOverButton) ? overOverlay
  32536. : normalOverlay);
  32537. if (! overlayColour.isOpaque())
  32538. {
  32539. g.setOpacity ((isButtonDown) ? downOpacity
  32540. : ((isMouseOverButton) ? overOpacity
  32541. : normalOpacity));
  32542. if (scaleImageToFit)
  32543. g.drawImage (im, imageX, imageY, imageW, imageH, 0, 0, iw, ih, false);
  32544. else
  32545. g.drawImageAt (im, imageX, imageY, false);
  32546. }
  32547. if (! overlayColour.isTransparent())
  32548. {
  32549. g.setColour (overlayColour);
  32550. if (scaleImageToFit)
  32551. g.drawImage (im, imageX, imageY, imageW, imageH, 0, 0, iw, ih, true);
  32552. else
  32553. g.drawImageAt (im, imageX, imageY, true);
  32554. }
  32555. }
  32556. }
  32557. bool ImageButton::hitTest (int x, int y)
  32558. {
  32559. if (alphaThreshold == 0)
  32560. return true;
  32561. Image* const im = getCurrentImage();
  32562. return im == 0
  32563. || (imageW > 0 && imageH > 0
  32564. && alphaThreshold < im->getPixelAt (((x - imageX) * im->getWidth()) / imageW,
  32565. ((y - imageY) * im->getHeight()) / imageH).getAlpha());
  32566. }
  32567. END_JUCE_NAMESPACE
  32568. /********* End of inlined file: juce_ImageButton.cpp *********/
  32569. /********* Start of inlined file: juce_ShapeButton.cpp *********/
  32570. BEGIN_JUCE_NAMESPACE
  32571. ShapeButton::ShapeButton (const String& text,
  32572. const Colour& normalColour_,
  32573. const Colour& overColour_,
  32574. const Colour& downColour_)
  32575. : Button (text),
  32576. normalColour (normalColour_),
  32577. overColour (overColour_),
  32578. downColour (downColour_),
  32579. maintainShapeProportions (false),
  32580. outlineWidth (0.0f)
  32581. {
  32582. }
  32583. ShapeButton::~ShapeButton()
  32584. {
  32585. }
  32586. void ShapeButton::setColours (const Colour& newNormalColour,
  32587. const Colour& newOverColour,
  32588. const Colour& newDownColour)
  32589. {
  32590. normalColour = newNormalColour;
  32591. overColour = newOverColour;
  32592. downColour = newDownColour;
  32593. }
  32594. void ShapeButton::setOutline (const Colour& newOutlineColour,
  32595. const float newOutlineWidth)
  32596. {
  32597. outlineColour = newOutlineColour;
  32598. outlineWidth = newOutlineWidth;
  32599. }
  32600. void ShapeButton::setShape (const Path& newShape,
  32601. const bool resizeNowToFitThisShape,
  32602. const bool maintainShapeProportions_,
  32603. const bool hasShadow)
  32604. {
  32605. shape = newShape;
  32606. maintainShapeProportions = maintainShapeProportions_;
  32607. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  32608. setComponentEffect ((hasShadow) ? &shadow : 0);
  32609. if (resizeNowToFitThisShape)
  32610. {
  32611. float x, y, w, h;
  32612. shape.getBounds (x, y, w, h);
  32613. shape.applyTransform (AffineTransform::translation (-x, -y));
  32614. if (hasShadow)
  32615. {
  32616. w += 4.0f;
  32617. h += 4.0f;
  32618. shape.applyTransform (AffineTransform::translation (2.0f, 2.0f));
  32619. }
  32620. setSize (1 + (int) (w + outlineWidth),
  32621. 1 + (int) (h + outlineWidth));
  32622. }
  32623. }
  32624. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  32625. {
  32626. if (! isEnabled())
  32627. {
  32628. isMouseOverButton = false;
  32629. isButtonDown = false;
  32630. }
  32631. g.setColour ((isButtonDown) ? downColour
  32632. : (isMouseOverButton) ? overColour
  32633. : normalColour);
  32634. int w = getWidth();
  32635. int h = getHeight();
  32636. if (getComponentEffect() != 0)
  32637. {
  32638. w -= 4;
  32639. h -= 4;
  32640. }
  32641. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  32642. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  32643. w - offset - outlineWidth,
  32644. h - offset - outlineWidth,
  32645. maintainShapeProportions));
  32646. g.fillPath (shape, trans);
  32647. if (outlineWidth > 0.0f)
  32648. {
  32649. g.setColour (outlineColour);
  32650. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  32651. }
  32652. }
  32653. END_JUCE_NAMESPACE
  32654. /********* End of inlined file: juce_ShapeButton.cpp *********/
  32655. /********* Start of inlined file: juce_TextButton.cpp *********/
  32656. BEGIN_JUCE_NAMESPACE
  32657. TextButton::TextButton (const String& name,
  32658. const String& toolTip)
  32659. : Button (name)
  32660. {
  32661. setTooltip (toolTip);
  32662. }
  32663. TextButton::~TextButton()
  32664. {
  32665. }
  32666. void TextButton::paintButton (Graphics& g,
  32667. bool isMouseOverButton,
  32668. bool isButtonDown)
  32669. {
  32670. getLookAndFeel().drawButtonBackground (g, *this,
  32671. findColour (getToggleState() ? buttonOnColourId
  32672. : buttonColourId),
  32673. isMouseOverButton,
  32674. isButtonDown);
  32675. getLookAndFeel().drawButtonText (g, *this,
  32676. isMouseOverButton,
  32677. isButtonDown);
  32678. }
  32679. void TextButton::colourChanged()
  32680. {
  32681. repaint();
  32682. }
  32683. const Font TextButton::getFont()
  32684. {
  32685. return Font (jmin (15.0f, getHeight() * 0.6f));
  32686. }
  32687. void TextButton::changeWidthToFitText (const int newHeight)
  32688. {
  32689. if (newHeight >= 0)
  32690. setSize (jmax (1, getWidth()), newHeight);
  32691. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  32692. getHeight());
  32693. }
  32694. END_JUCE_NAMESPACE
  32695. /********* End of inlined file: juce_TextButton.cpp *********/
  32696. /********* Start of inlined file: juce_ToggleButton.cpp *********/
  32697. BEGIN_JUCE_NAMESPACE
  32698. ToggleButton::ToggleButton (const String& buttonText)
  32699. : Button (buttonText)
  32700. {
  32701. setClickingTogglesState (true);
  32702. }
  32703. ToggleButton::~ToggleButton()
  32704. {
  32705. }
  32706. void ToggleButton::paintButton (Graphics& g,
  32707. bool isMouseOverButton,
  32708. bool isButtonDown)
  32709. {
  32710. getLookAndFeel().drawToggleButton (g, *this,
  32711. isMouseOverButton,
  32712. isButtonDown);
  32713. }
  32714. void ToggleButton::changeWidthToFitText()
  32715. {
  32716. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  32717. }
  32718. void ToggleButton::colourChanged()
  32719. {
  32720. repaint();
  32721. }
  32722. END_JUCE_NAMESPACE
  32723. /********* End of inlined file: juce_ToggleButton.cpp *********/
  32724. /********* Start of inlined file: juce_ToolbarButton.cpp *********/
  32725. BEGIN_JUCE_NAMESPACE
  32726. ToolbarButton::ToolbarButton (const int itemId,
  32727. const String& buttonText,
  32728. Drawable* const normalImage_,
  32729. Drawable* const toggledOnImage_)
  32730. : ToolbarItemComponent (itemId, buttonText, true),
  32731. normalImage (normalImage_),
  32732. toggledOnImage (toggledOnImage_)
  32733. {
  32734. }
  32735. ToolbarButton::~ToolbarButton()
  32736. {
  32737. delete normalImage;
  32738. delete toggledOnImage;
  32739. }
  32740. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  32741. bool /*isToolbarVertical*/,
  32742. int& preferredSize,
  32743. int& minSize, int& maxSize)
  32744. {
  32745. preferredSize = minSize = maxSize = toolbarDepth;
  32746. return true;
  32747. }
  32748. void ToolbarButton::paintButtonArea (Graphics& g,
  32749. int width, int height,
  32750. bool /*isMouseOver*/,
  32751. bool /*isMouseDown*/)
  32752. {
  32753. Drawable* d = normalImage;
  32754. if (getToggleState() && toggledOnImage != 0)
  32755. d = toggledOnImage;
  32756. if (! isEnabled())
  32757. {
  32758. Image im (Image::ARGB, width, height, true);
  32759. Graphics g2 (im);
  32760. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred);
  32761. im.desaturate();
  32762. g.drawImageAt (&im, 0, 0);
  32763. }
  32764. else
  32765. {
  32766. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred);
  32767. }
  32768. }
  32769. void ToolbarButton::contentAreaChanged (const Rectangle&)
  32770. {
  32771. }
  32772. END_JUCE_NAMESPACE
  32773. /********* End of inlined file: juce_ToolbarButton.cpp *********/
  32774. /********* Start of inlined file: juce_ComboBox.cpp *********/
  32775. BEGIN_JUCE_NAMESPACE
  32776. ComboBox::ComboBox (const String& name)
  32777. : Component (name),
  32778. items (4),
  32779. currentIndex (-1),
  32780. isButtonDown (false),
  32781. separatorPending (false),
  32782. menuActive (false),
  32783. listeners (2),
  32784. label (0)
  32785. {
  32786. noChoicesMessage = TRANS("(no choices)");
  32787. setRepaintsOnMouseActivity (true);
  32788. lookAndFeelChanged();
  32789. }
  32790. ComboBox::~ComboBox()
  32791. {
  32792. if (menuActive)
  32793. PopupMenu::dismissAllActiveMenus();
  32794. deleteAllChildren();
  32795. }
  32796. void ComboBox::setEditableText (const bool isEditable)
  32797. {
  32798. label->setEditable (isEditable, isEditable, false);
  32799. setWantsKeyboardFocus (! isEditable);
  32800. resized();
  32801. }
  32802. bool ComboBox::isTextEditable() const throw()
  32803. {
  32804. return label->isEditable();
  32805. }
  32806. void ComboBox::setJustificationType (const Justification& justification) throw()
  32807. {
  32808. label->setJustificationType (justification);
  32809. }
  32810. const Justification ComboBox::getJustificationType() const throw()
  32811. {
  32812. return label->getJustificationType();
  32813. }
  32814. void ComboBox::setTooltip (const String& newTooltip)
  32815. {
  32816. SettableTooltipClient::setTooltip (newTooltip);
  32817. label->setTooltip (newTooltip);
  32818. }
  32819. void ComboBox::addItem (const String& newItemText,
  32820. const int newItemId) throw()
  32821. {
  32822. // you can't add empty strings to the list..
  32823. jassert (newItemText.isNotEmpty());
  32824. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  32825. jassert (newItemId != 0);
  32826. // you shouldn't use duplicate item IDs!
  32827. jassert (getItemForId (newItemId) == 0);
  32828. if (newItemText.isNotEmpty() && newItemId != 0)
  32829. {
  32830. if (separatorPending)
  32831. {
  32832. separatorPending = false;
  32833. ItemInfo* const item = new ItemInfo();
  32834. item->itemId = 0;
  32835. item->isEnabled = false;
  32836. item->isHeading = false;
  32837. items.add (item);
  32838. }
  32839. ItemInfo* const item = new ItemInfo();
  32840. item->name = newItemText;
  32841. item->itemId = newItemId;
  32842. item->isEnabled = true;
  32843. item->isHeading = false;
  32844. items.add (item);
  32845. }
  32846. }
  32847. void ComboBox::addSeparator() throw()
  32848. {
  32849. separatorPending = (items.size() > 0);
  32850. }
  32851. void ComboBox::addSectionHeading (const String& headingName) throw()
  32852. {
  32853. // you can't add empty strings to the list..
  32854. jassert (headingName.isNotEmpty());
  32855. if (headingName.isNotEmpty())
  32856. {
  32857. if (separatorPending)
  32858. {
  32859. separatorPending = false;
  32860. ItemInfo* const item = new ItemInfo();
  32861. item->itemId = 0;
  32862. item->isEnabled = false;
  32863. item->isHeading = false;
  32864. items.add (item);
  32865. }
  32866. ItemInfo* const item = new ItemInfo();
  32867. item->name = headingName;
  32868. item->itemId = 0;
  32869. item->isEnabled = true;
  32870. item->isHeading = true;
  32871. items.add (item);
  32872. }
  32873. }
  32874. void ComboBox::setItemEnabled (const int itemId,
  32875. const bool isEnabled) throw()
  32876. {
  32877. ItemInfo* const item = getItemForId (itemId);
  32878. if (item != 0)
  32879. item->isEnabled = isEnabled;
  32880. }
  32881. void ComboBox::changeItemText (const int itemId,
  32882. const String& newText) throw()
  32883. {
  32884. ItemInfo* const item = getItemForId (itemId);
  32885. jassert (item != 0);
  32886. if (item != 0)
  32887. item->name = newText;
  32888. }
  32889. void ComboBox::clear (const bool dontSendChangeMessage)
  32890. {
  32891. items.clear();
  32892. separatorPending = false;
  32893. if (! label->isEditable())
  32894. setSelectedItemIndex (-1, dontSendChangeMessage);
  32895. }
  32896. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  32897. {
  32898. jassert (itemId != 0);
  32899. if (itemId != 0)
  32900. {
  32901. for (int i = items.size(); --i >= 0;)
  32902. if (items.getUnchecked(i)->itemId == itemId)
  32903. return items.getUnchecked(i);
  32904. }
  32905. return 0;
  32906. }
  32907. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  32908. {
  32909. int n = 0;
  32910. for (int i = 0; i < items.size(); ++i)
  32911. {
  32912. ItemInfo* const item = items.getUnchecked(i);
  32913. if (item->isRealItem())
  32914. {
  32915. if (n++ == index)
  32916. return item;
  32917. }
  32918. }
  32919. return 0;
  32920. }
  32921. int ComboBox::getNumItems() const throw()
  32922. {
  32923. int n = 0;
  32924. for (int i = items.size(); --i >= 0;)
  32925. {
  32926. ItemInfo* const item = items.getUnchecked(i);
  32927. if (item->isRealItem())
  32928. ++n;
  32929. }
  32930. return n;
  32931. }
  32932. const String ComboBox::getItemText (const int index) const throw()
  32933. {
  32934. ItemInfo* const item = getItemForIndex (index);
  32935. if (item != 0)
  32936. return item->name;
  32937. return String::empty;
  32938. }
  32939. int ComboBox::getItemId (const int index) const throw()
  32940. {
  32941. ItemInfo* const item = getItemForIndex (index);
  32942. return (item != 0) ? item->itemId : 0;
  32943. }
  32944. bool ComboBox::ItemInfo::isSeparator() const throw()
  32945. {
  32946. return name.isEmpty();
  32947. }
  32948. bool ComboBox::ItemInfo::isRealItem() const throw()
  32949. {
  32950. return ! (isHeading || name.isEmpty());
  32951. }
  32952. int ComboBox::getSelectedItemIndex() const throw()
  32953. {
  32954. return (currentIndex >= 0 && getText() == getItemText (currentIndex))
  32955. ? currentIndex
  32956. : -1;
  32957. }
  32958. void ComboBox::setSelectedItemIndex (const int index,
  32959. const bool dontSendChangeMessage) throw()
  32960. {
  32961. if (currentIndex != index || label->getText() != getItemText (currentIndex))
  32962. {
  32963. if (((unsigned int) index) < (unsigned int) getNumItems())
  32964. currentIndex = index;
  32965. else
  32966. currentIndex = -1;
  32967. label->setText (getItemText (currentIndex), false);
  32968. if (! dontSendChangeMessage)
  32969. triggerAsyncUpdate();
  32970. }
  32971. }
  32972. void ComboBox::setSelectedId (const int newItemId,
  32973. const bool dontSendChangeMessage) throw()
  32974. {
  32975. for (int i = getNumItems(); --i >= 0;)
  32976. {
  32977. if (getItemId(i) == newItemId)
  32978. {
  32979. setSelectedItemIndex (i, dontSendChangeMessage);
  32980. break;
  32981. }
  32982. }
  32983. }
  32984. int ComboBox::getSelectedId() const throw()
  32985. {
  32986. const ItemInfo* const item = getItemForIndex (currentIndex);
  32987. return (item != 0 && getText() == item->name)
  32988. ? item->itemId
  32989. : 0;
  32990. }
  32991. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  32992. {
  32993. jassert (listener != 0);
  32994. if (listener != 0)
  32995. listeners.add (listener);
  32996. }
  32997. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  32998. {
  32999. listeners.removeValue (listener);
  33000. }
  33001. void ComboBox::handleAsyncUpdate()
  33002. {
  33003. for (int i = listeners.size(); --i >= 0;)
  33004. {
  33005. ((ComboBoxListener*) listeners.getUnchecked (i))->comboBoxChanged (this);
  33006. i = jmin (i, listeners.size());
  33007. }
  33008. }
  33009. const String ComboBox::getText() const throw()
  33010. {
  33011. return label->getText();
  33012. }
  33013. void ComboBox::setText (const String& newText,
  33014. const bool dontSendChangeMessage) throw()
  33015. {
  33016. for (int i = items.size(); --i >= 0;)
  33017. {
  33018. ItemInfo* const item = items.getUnchecked(i);
  33019. if (item->isRealItem()
  33020. && item->name == newText)
  33021. {
  33022. setSelectedId (item->itemId, dontSendChangeMessage);
  33023. return;
  33024. }
  33025. }
  33026. currentIndex = -1;
  33027. if (label->getText() != newText)
  33028. {
  33029. label->setText (newText, false);
  33030. if (! dontSendChangeMessage)
  33031. triggerAsyncUpdate();
  33032. }
  33033. repaint();
  33034. }
  33035. void ComboBox::showEditor()
  33036. {
  33037. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  33038. label->showEditor();
  33039. }
  33040. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  33041. {
  33042. textWhenNothingSelected = newMessage;
  33043. repaint();
  33044. }
  33045. const String ComboBox::getTextWhenNothingSelected() const throw()
  33046. {
  33047. return textWhenNothingSelected;
  33048. }
  33049. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  33050. {
  33051. noChoicesMessage = newMessage;
  33052. }
  33053. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  33054. {
  33055. return noChoicesMessage;
  33056. }
  33057. void ComboBox::paint (Graphics& g)
  33058. {
  33059. getLookAndFeel().drawComboBox (g,
  33060. getWidth(),
  33061. getHeight(),
  33062. isButtonDown,
  33063. label->getRight(),
  33064. 0,
  33065. getWidth() - label->getRight(),
  33066. getHeight(),
  33067. *this);
  33068. if (textWhenNothingSelected.isNotEmpty()
  33069. && label->getText().isEmpty()
  33070. && ! label->isBeingEdited())
  33071. {
  33072. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  33073. g.setFont (label->getFont());
  33074. g.drawFittedText (textWhenNothingSelected,
  33075. label->getX() + 2, label->getY() + 1,
  33076. label->getWidth() - 4, label->getHeight() - 2,
  33077. label->getJustificationType(),
  33078. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  33079. }
  33080. }
  33081. void ComboBox::resized()
  33082. {
  33083. if (getHeight() > 0 && getWidth() > 0)
  33084. getLookAndFeel().positionComboBoxText (*this, *label);
  33085. }
  33086. void ComboBox::enablementChanged()
  33087. {
  33088. repaint();
  33089. }
  33090. void ComboBox::lookAndFeelChanged()
  33091. {
  33092. repaint();
  33093. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  33094. if (label != 0)
  33095. {
  33096. newLabel->setEditable (label->isEditable());
  33097. newLabel->setJustificationType (label->getJustificationType());
  33098. newLabel->setTooltip (label->getTooltip());
  33099. newLabel->setText (label->getText(), false);
  33100. }
  33101. delete label;
  33102. label = newLabel;
  33103. addAndMakeVisible (newLabel);
  33104. newLabel->addListener (this);
  33105. newLabel->addMouseListener (this, false);
  33106. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  33107. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  33108. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  33109. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  33110. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  33111. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  33112. resized();
  33113. }
  33114. void ComboBox::colourChanged()
  33115. {
  33116. lookAndFeelChanged();
  33117. }
  33118. bool ComboBox::keyPressed (const KeyPress& key)
  33119. {
  33120. bool used = false;
  33121. if (key.isKeyCode (KeyPress::upKey)
  33122. || key.isKeyCode (KeyPress::leftKey))
  33123. {
  33124. setSelectedItemIndex (jmax (0, currentIndex - 1));
  33125. used = true;
  33126. }
  33127. else if (key.isKeyCode (KeyPress::downKey)
  33128. || key.isKeyCode (KeyPress::rightKey))
  33129. {
  33130. setSelectedItemIndex (jmin (currentIndex + 1, getNumItems() - 1));
  33131. used = true;
  33132. }
  33133. else if (key.isKeyCode (KeyPress::returnKey))
  33134. {
  33135. showPopup();
  33136. used = true;
  33137. }
  33138. return used;
  33139. }
  33140. bool ComboBox::keyStateChanged()
  33141. {
  33142. // only forward key events that aren't used by this component
  33143. return KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  33144. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  33145. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  33146. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey);
  33147. }
  33148. void ComboBox::focusGained (FocusChangeType)
  33149. {
  33150. repaint();
  33151. }
  33152. void ComboBox::focusLost (FocusChangeType)
  33153. {
  33154. repaint();
  33155. }
  33156. void ComboBox::labelTextChanged (Label*)
  33157. {
  33158. triggerAsyncUpdate();
  33159. }
  33160. void ComboBox::showPopup()
  33161. {
  33162. if (! menuActive)
  33163. {
  33164. const int currentId = getSelectedId();
  33165. ComponentDeletionWatcher deletionWatcher (this);
  33166. PopupMenu menu;
  33167. menu.setLookAndFeel (&getLookAndFeel());
  33168. for (int i = 0; i < items.size(); ++i)
  33169. {
  33170. const ItemInfo* const item = items.getUnchecked(i);
  33171. if (item->isSeparator())
  33172. menu.addSeparator();
  33173. else if (item->isHeading)
  33174. menu.addSectionHeader (item->name);
  33175. else
  33176. menu.addItem (item->itemId, item->name,
  33177. item->isEnabled, item->itemId == currentId);
  33178. }
  33179. if (items.size() == 0)
  33180. menu.addItem (1, noChoicesMessage, false);
  33181. const int itemHeight = jlimit (12, 24, getHeight());
  33182. menuActive = true;
  33183. const int resultId = menu.showAt (this, currentId,
  33184. getWidth(), 1, itemHeight);
  33185. if (deletionWatcher.hasBeenDeleted())
  33186. return;
  33187. menuActive = false;
  33188. if (resultId != 0)
  33189. setSelectedId (resultId);
  33190. }
  33191. }
  33192. void ComboBox::mouseDown (const MouseEvent& e)
  33193. {
  33194. beginDragAutoRepeat (300);
  33195. isButtonDown = isEnabled();
  33196. if (isButtonDown
  33197. && (e.eventComponent == this || ! label->isEditable()))
  33198. {
  33199. showPopup();
  33200. }
  33201. }
  33202. void ComboBox::mouseDrag (const MouseEvent& e)
  33203. {
  33204. beginDragAutoRepeat (50);
  33205. if (isButtonDown && ! e.mouseWasClicked())
  33206. showPopup();
  33207. }
  33208. void ComboBox::mouseUp (const MouseEvent& e2)
  33209. {
  33210. if (isButtonDown)
  33211. {
  33212. isButtonDown = false;
  33213. repaint();
  33214. const MouseEvent e (e2.getEventRelativeTo (this));
  33215. if (reallyContains (e.x, e.y, true)
  33216. && (e2.eventComponent == this || ! label->isEditable()))
  33217. {
  33218. showPopup();
  33219. }
  33220. }
  33221. }
  33222. END_JUCE_NAMESPACE
  33223. /********* End of inlined file: juce_ComboBox.cpp *********/
  33224. /********* Start of inlined file: juce_Label.cpp *********/
  33225. BEGIN_JUCE_NAMESPACE
  33226. Label::Label (const String& componentName,
  33227. const String& labelText)
  33228. : Component (componentName),
  33229. text (labelText),
  33230. font (15.0f),
  33231. justification (Justification::centredLeft),
  33232. editor (0),
  33233. listeners (2),
  33234. ownerComponent (0),
  33235. deletionWatcher (0),
  33236. editSingleClick (false),
  33237. editDoubleClick (false),
  33238. lossOfFocusDiscardsChanges (false)
  33239. {
  33240. setColour (TextEditor::textColourId, Colours::black);
  33241. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  33242. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  33243. }
  33244. Label::~Label()
  33245. {
  33246. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33247. ownerComponent->removeComponentListener (this);
  33248. deleteAndZero (deletionWatcher);
  33249. if (editor != 0)
  33250. delete editor;
  33251. }
  33252. void Label::setText (const String& newText,
  33253. const bool broadcastChangeMessage)
  33254. {
  33255. hideEditor (true);
  33256. if (text != newText)
  33257. {
  33258. text = newText;
  33259. if (broadcastChangeMessage)
  33260. triggerAsyncUpdate();
  33261. repaint();
  33262. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33263. componentMovedOrResized (*ownerComponent, true, true);
  33264. }
  33265. }
  33266. const String Label::getText (const bool returnActiveEditorContents) const throw()
  33267. {
  33268. return (returnActiveEditorContents && isBeingEdited())
  33269. ? editor->getText()
  33270. : text;
  33271. }
  33272. void Label::setFont (const Font& newFont) throw()
  33273. {
  33274. font = newFont;
  33275. repaint();
  33276. }
  33277. const Font& Label::getFont() const throw()
  33278. {
  33279. return font;
  33280. }
  33281. void Label::setEditable (const bool editOnSingleClick,
  33282. const bool editOnDoubleClick,
  33283. const bool lossOfFocusDiscardsChanges_) throw()
  33284. {
  33285. editSingleClick = editOnSingleClick;
  33286. editDoubleClick = editOnDoubleClick;
  33287. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  33288. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  33289. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  33290. }
  33291. void Label::setJustificationType (const Justification& justification_) throw()
  33292. {
  33293. justification = justification_;
  33294. repaint();
  33295. }
  33296. void Label::attachToComponent (Component* owner,
  33297. const bool onLeft)
  33298. {
  33299. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33300. ownerComponent->removeComponentListener (this);
  33301. deleteAndZero (deletionWatcher);
  33302. ownerComponent = owner;
  33303. leftOfOwnerComp = onLeft;
  33304. if (ownerComponent != 0)
  33305. {
  33306. deletionWatcher = new ComponentDeletionWatcher (owner);
  33307. setVisible (owner->isVisible());
  33308. ownerComponent->addComponentListener (this);
  33309. componentParentHierarchyChanged (*ownerComponent);
  33310. componentMovedOrResized (*ownerComponent, true, true);
  33311. }
  33312. }
  33313. void Label::componentMovedOrResized (Component& component,
  33314. bool /*wasMoved*/,
  33315. bool /*wasResized*/)
  33316. {
  33317. if (leftOfOwnerComp)
  33318. {
  33319. setSize (jmin (getFont().getStringWidth (text) + 8, component.getX()),
  33320. component.getHeight());
  33321. setTopRightPosition (component.getX(), component.getY());
  33322. }
  33323. else
  33324. {
  33325. setSize (component.getWidth(),
  33326. 8 + roundFloatToInt (getFont().getHeight()));
  33327. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  33328. }
  33329. }
  33330. void Label::componentParentHierarchyChanged (Component& component)
  33331. {
  33332. if (component.getParentComponent() != 0)
  33333. component.getParentComponent()->addChildComponent (this);
  33334. }
  33335. void Label::componentVisibilityChanged (Component& component)
  33336. {
  33337. setVisible (component.isVisible());
  33338. }
  33339. void Label::textWasEdited()
  33340. {
  33341. }
  33342. void Label::showEditor()
  33343. {
  33344. if (editor == 0)
  33345. {
  33346. addAndMakeVisible (editor = createEditorComponent());
  33347. editor->setText (getText());
  33348. editor->addListener (this);
  33349. editor->grabKeyboardFocus();
  33350. editor->setHighlightedRegion (0, text.length());
  33351. editor->addListener (this);
  33352. resized();
  33353. repaint();
  33354. enterModalState();
  33355. editor->grabKeyboardFocus();
  33356. }
  33357. }
  33358. bool Label::updateFromTextEditorContents()
  33359. {
  33360. jassert (editor != 0);
  33361. const String newText (editor->getText());
  33362. if (text != newText)
  33363. {
  33364. text = newText;
  33365. triggerAsyncUpdate();
  33366. repaint();
  33367. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33368. componentMovedOrResized (*ownerComponent, true, true);
  33369. return true;
  33370. }
  33371. return false;
  33372. }
  33373. void Label::hideEditor (const bool discardCurrentEditorContents)
  33374. {
  33375. if (editor != 0)
  33376. {
  33377. const bool changed = (! discardCurrentEditorContents)
  33378. && updateFromTextEditorContents();
  33379. deleteAndZero (editor);
  33380. repaint();
  33381. if (changed)
  33382. textWasEdited();
  33383. exitModalState (0);
  33384. }
  33385. }
  33386. void Label::inputAttemptWhenModal()
  33387. {
  33388. if (editor != 0)
  33389. {
  33390. if (lossOfFocusDiscardsChanges)
  33391. textEditorEscapeKeyPressed (*editor);
  33392. else
  33393. textEditorReturnKeyPressed (*editor);
  33394. }
  33395. }
  33396. bool Label::isBeingEdited() const throw()
  33397. {
  33398. return editor != 0;
  33399. }
  33400. TextEditor* Label::createEditorComponent()
  33401. {
  33402. TextEditor* const ed = new TextEditor (getName());
  33403. ed->setFont (font);
  33404. // copy these colours from our own settings..
  33405. const int cols[] = { TextEditor::backgroundColourId,
  33406. TextEditor::textColourId,
  33407. TextEditor::highlightColourId,
  33408. TextEditor::highlightedTextColourId,
  33409. TextEditor::caretColourId,
  33410. TextEditor::outlineColourId,
  33411. TextEditor::focusedOutlineColourId,
  33412. TextEditor::shadowColourId };
  33413. for (int i = 0; i < numElementsInArray (cols); ++i)
  33414. ed->setColour (cols[i], findColour (cols[i]));
  33415. return ed;
  33416. }
  33417. void Label::paint (Graphics& g)
  33418. {
  33419. g.fillAll (findColour (backgroundColourId));
  33420. if (editor == 0)
  33421. {
  33422. const float alpha = isEnabled() ? 1.0f : 0.5f;
  33423. g.setColour (findColour (textColourId).withMultipliedAlpha (alpha));
  33424. g.setFont (font);
  33425. g.drawFittedText (text,
  33426. 3, 1, getWidth() - 6, getHeight() - 2,
  33427. justification,
  33428. jmax (1, (int) (getHeight() / font.getHeight())));
  33429. g.setColour (findColour (outlineColourId).withMultipliedAlpha (alpha));
  33430. g.drawRect (0, 0, getWidth(), getHeight());
  33431. }
  33432. else if (isEnabled())
  33433. {
  33434. g.setColour (editor->findColour (TextEditor::backgroundColourId)
  33435. .overlaidWith (findColour (outlineColourId)));
  33436. g.drawRect (0, 0, getWidth(), getHeight());
  33437. }
  33438. }
  33439. void Label::mouseUp (const MouseEvent& e)
  33440. {
  33441. if (editSingleClick
  33442. && e.mouseWasClicked()
  33443. && contains (e.x, e.y)
  33444. && ! e.mods.isPopupMenu())
  33445. {
  33446. showEditor();
  33447. }
  33448. }
  33449. void Label::mouseDoubleClick (const MouseEvent& e)
  33450. {
  33451. if (editDoubleClick && ! e.mods.isPopupMenu())
  33452. showEditor();
  33453. }
  33454. void Label::resized()
  33455. {
  33456. if (editor != 0)
  33457. editor->setBoundsInset (BorderSize (0));
  33458. }
  33459. void Label::focusGained (FocusChangeType cause)
  33460. {
  33461. if (editSingleClick && cause == focusChangedByTabKey)
  33462. showEditor();
  33463. }
  33464. void Label::enablementChanged()
  33465. {
  33466. repaint();
  33467. }
  33468. void Label::colourChanged()
  33469. {
  33470. repaint();
  33471. }
  33472. // We'll use a custom focus traverser here to make sure focus goes from the
  33473. // text editor to another component rather than back to the label itself.
  33474. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  33475. {
  33476. public:
  33477. LabelKeyboardFocusTraverser() {}
  33478. Component* getNextComponent (Component* current)
  33479. {
  33480. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  33481. ? current->getParentComponent() : current);
  33482. }
  33483. Component* getPreviousComponent (Component* current)
  33484. {
  33485. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  33486. ? current->getParentComponent() : current);
  33487. }
  33488. };
  33489. KeyboardFocusTraverser* Label::createFocusTraverser()
  33490. {
  33491. return new LabelKeyboardFocusTraverser();
  33492. }
  33493. void Label::addListener (LabelListener* const listener) throw()
  33494. {
  33495. jassert (listener != 0);
  33496. if (listener != 0)
  33497. listeners.add (listener);
  33498. }
  33499. void Label::removeListener (LabelListener* const listener) throw()
  33500. {
  33501. listeners.removeValue (listener);
  33502. }
  33503. void Label::handleAsyncUpdate()
  33504. {
  33505. for (int i = listeners.size(); --i >= 0;)
  33506. {
  33507. ((LabelListener*) listeners.getUnchecked (i))->labelTextChanged (this);
  33508. i = jmin (i, listeners.size());
  33509. }
  33510. }
  33511. void Label::textEditorTextChanged (TextEditor& ed)
  33512. {
  33513. if (editor != 0)
  33514. {
  33515. jassert (&ed == editor);
  33516. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  33517. {
  33518. if (lossOfFocusDiscardsChanges)
  33519. textEditorEscapeKeyPressed (ed);
  33520. else
  33521. textEditorReturnKeyPressed (ed);
  33522. }
  33523. }
  33524. }
  33525. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  33526. {
  33527. if (editor != 0)
  33528. {
  33529. jassert (&ed == editor);
  33530. (void) ed;
  33531. const bool changed = updateFromTextEditorContents();
  33532. hideEditor (true);
  33533. if (changed)
  33534. textWasEdited();
  33535. }
  33536. }
  33537. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  33538. {
  33539. if (editor != 0)
  33540. {
  33541. jassert (&ed == editor);
  33542. (void) ed;
  33543. editor->setText (text, false);
  33544. hideEditor (true);
  33545. }
  33546. }
  33547. void Label::textEditorFocusLost (TextEditor& ed)
  33548. {
  33549. textEditorTextChanged (ed);
  33550. }
  33551. END_JUCE_NAMESPACE
  33552. /********* End of inlined file: juce_Label.cpp *********/
  33553. /********* Start of inlined file: juce_ListBox.cpp *********/
  33554. BEGIN_JUCE_NAMESPACE
  33555. class ListBoxRowComponent : public Component
  33556. {
  33557. public:
  33558. ListBoxRowComponent (ListBox& owner_)
  33559. : owner (owner_),
  33560. row (-1),
  33561. selected (false),
  33562. isDragging (false)
  33563. {
  33564. }
  33565. ~ListBoxRowComponent()
  33566. {
  33567. deleteAllChildren();
  33568. }
  33569. void paint (Graphics& g)
  33570. {
  33571. if (owner.getModel() != 0)
  33572. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  33573. }
  33574. void update (const int row_, const bool selected_)
  33575. {
  33576. if (row != row_ || selected != selected_)
  33577. {
  33578. repaint();
  33579. row = row_;
  33580. selected = selected_;
  33581. }
  33582. if (owner.getModel() != 0)
  33583. {
  33584. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  33585. if (customComp != 0)
  33586. {
  33587. addAndMakeVisible (customComp);
  33588. customComp->setBounds (0, 0, getWidth(), getHeight());
  33589. for (int i = getNumChildComponents(); --i >= 0;)
  33590. if (getChildComponent (i) != customComp)
  33591. delete getChildComponent (i);
  33592. }
  33593. else
  33594. {
  33595. deleteAllChildren();
  33596. }
  33597. }
  33598. }
  33599. void mouseDown (const MouseEvent& e)
  33600. {
  33601. isDragging = false;
  33602. selectRowOnMouseUp = false;
  33603. if (isEnabled())
  33604. {
  33605. if (! selected)
  33606. {
  33607. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  33608. if (owner.getModel() != 0)
  33609. owner.getModel()->listBoxItemClicked (row, e);
  33610. }
  33611. else
  33612. {
  33613. selectRowOnMouseUp = true;
  33614. }
  33615. }
  33616. }
  33617. void mouseUp (const MouseEvent& e)
  33618. {
  33619. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  33620. {
  33621. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  33622. if (owner.getModel() != 0)
  33623. owner.getModel()->listBoxItemClicked (row, e);
  33624. }
  33625. }
  33626. void mouseDoubleClick (const MouseEvent& e)
  33627. {
  33628. if (owner.getModel() != 0 && isEnabled())
  33629. owner.getModel()->listBoxItemDoubleClicked (row, e);
  33630. }
  33631. void mouseDrag (const MouseEvent& e)
  33632. {
  33633. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  33634. {
  33635. const SparseSet <int> selectedRows (owner.getSelectedRows());
  33636. if (selectedRows.size() > 0)
  33637. {
  33638. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  33639. if (dragDescription.isNotEmpty())
  33640. {
  33641. isDragging = true;
  33642. DragAndDropContainer* const dragContainer
  33643. = DragAndDropContainer::findParentDragContainerFor (this);
  33644. if (dragContainer != 0)
  33645. {
  33646. Image* dragImage = owner.createSnapshotOfSelectedRows();
  33647. dragImage->multiplyAllAlphas (0.6f);
  33648. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  33649. }
  33650. else
  33651. {
  33652. // to be able to do a drag-and-drop operation, the listbox needs to
  33653. // be inside a component which is also a DragAndDropContainer.
  33654. jassertfalse
  33655. }
  33656. }
  33657. }
  33658. }
  33659. }
  33660. void resized()
  33661. {
  33662. if (getNumChildComponents() > 0)
  33663. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  33664. }
  33665. juce_UseDebuggingNewOperator
  33666. bool neededFlag;
  33667. private:
  33668. ListBox& owner;
  33669. int row;
  33670. bool selected, isDragging, selectRowOnMouseUp;
  33671. ListBoxRowComponent (const ListBoxRowComponent&);
  33672. const ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  33673. };
  33674. class ListViewport : public Viewport
  33675. {
  33676. public:
  33677. int firstIndex, firstWholeIndex, lastWholeIndex;
  33678. bool hasUpdated;
  33679. ListViewport (ListBox& owner_)
  33680. : owner (owner_)
  33681. {
  33682. setWantsKeyboardFocus (false);
  33683. setViewedComponent (new Component());
  33684. getViewedComponent()->addMouseListener (this, false);
  33685. getViewedComponent()->setWantsKeyboardFocus (false);
  33686. }
  33687. ~ListViewport()
  33688. {
  33689. getViewedComponent()->removeMouseListener (this);
  33690. getViewedComponent()->deleteAllChildren();
  33691. }
  33692. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  33693. {
  33694. return (ListBoxRowComponent*) getViewedComponent()
  33695. ->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents()));
  33696. }
  33697. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  33698. {
  33699. const int index = getIndexOfChildComponent (rowComponent);
  33700. const int num = getViewedComponent()->getNumChildComponents();
  33701. for (int i = num; --i >= 0;)
  33702. if (((firstIndex + i) % jmax (1, num)) == index)
  33703. return firstIndex + i;
  33704. return -1;
  33705. }
  33706. Component* getComponentForRowIfOnscreen (const int row) const throw()
  33707. {
  33708. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  33709. ? getComponentForRow (row) : 0;
  33710. }
  33711. void visibleAreaChanged (int, int, int, int)
  33712. {
  33713. updateVisibleArea (true);
  33714. if (owner.getModel() != 0)
  33715. owner.getModel()->listWasScrolled();
  33716. }
  33717. void updateVisibleArea (const bool makeSureItUpdatesContent)
  33718. {
  33719. hasUpdated = false;
  33720. const int newX = getViewedComponent()->getX();
  33721. int newY = getViewedComponent()->getY();
  33722. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  33723. const int newH = owner.totalItems * owner.getRowHeight();
  33724. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  33725. newY = getMaximumVisibleHeight() - newH;
  33726. getViewedComponent()->setBounds (newX, newY, newW, newH);
  33727. if (makeSureItUpdatesContent && ! hasUpdated)
  33728. updateContents();
  33729. }
  33730. void updateContents()
  33731. {
  33732. hasUpdated = true;
  33733. const int rowHeight = owner.getRowHeight();
  33734. if (rowHeight > 0)
  33735. {
  33736. const int y = getViewPositionY();
  33737. const int w = getViewedComponent()->getWidth();
  33738. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  33739. while (numNeeded > getViewedComponent()->getNumChildComponents())
  33740. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  33741. jassert (numNeeded >= 0);
  33742. while (numNeeded < getViewedComponent()->getNumChildComponents())
  33743. {
  33744. Component* const rowToRemove
  33745. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  33746. delete rowToRemove;
  33747. }
  33748. firstIndex = y / rowHeight;
  33749. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  33750. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  33751. for (int i = 0; i < numNeeded; ++i)
  33752. {
  33753. const int row = i + firstIndex;
  33754. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  33755. if (rowComp != 0)
  33756. {
  33757. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  33758. rowComp->update (row, owner.isRowSelected (row));
  33759. }
  33760. }
  33761. }
  33762. if (owner.headerComponent != 0)
  33763. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  33764. owner.outlineThickness,
  33765. jmax (owner.getWidth() - owner.outlineThickness * 2,
  33766. getViewedComponent()->getWidth()),
  33767. owner.headerComponent->getHeight());
  33768. }
  33769. void paint (Graphics& g)
  33770. {
  33771. if (isOpaque())
  33772. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  33773. }
  33774. bool keyPressed (const KeyPress& key)
  33775. {
  33776. if (key.isKeyCode (KeyPress::upKey)
  33777. || key.isKeyCode (KeyPress::downKey)
  33778. || key.isKeyCode (KeyPress::pageUpKey)
  33779. || key.isKeyCode (KeyPress::pageDownKey)
  33780. || key.isKeyCode (KeyPress::homeKey)
  33781. || key.isKeyCode (KeyPress::endKey))
  33782. {
  33783. // we want to avoid these keypresses going to the viewport, and instead allow
  33784. // them to pass up to our listbox..
  33785. return false;
  33786. }
  33787. return Viewport::keyPressed (key);
  33788. }
  33789. juce_UseDebuggingNewOperator
  33790. private:
  33791. ListBox& owner;
  33792. ListViewport (const ListViewport&);
  33793. const ListViewport& operator= (const ListViewport&);
  33794. };
  33795. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  33796. : Component (name),
  33797. model (model_),
  33798. headerComponent (0),
  33799. totalItems (0),
  33800. rowHeight (22),
  33801. minimumRowWidth (0),
  33802. outlineThickness (0),
  33803. lastRowSelected (-1),
  33804. mouseMoveSelects (false),
  33805. multipleSelection (false),
  33806. hasDoneInitialUpdate (false)
  33807. {
  33808. addAndMakeVisible (viewport = new ListViewport (*this));
  33809. setWantsKeyboardFocus (true);
  33810. }
  33811. ListBox::~ListBox()
  33812. {
  33813. deleteAllChildren();
  33814. }
  33815. void ListBox::setModel (ListBoxModel* const newModel)
  33816. {
  33817. if (model != newModel)
  33818. {
  33819. model = newModel;
  33820. updateContent();
  33821. }
  33822. }
  33823. void ListBox::setMultipleSelectionEnabled (bool b)
  33824. {
  33825. multipleSelection = b;
  33826. }
  33827. void ListBox::setMouseMoveSelectsRows (bool b)
  33828. {
  33829. mouseMoveSelects = b;
  33830. if (b)
  33831. addMouseListener (this, true);
  33832. }
  33833. void ListBox::paint (Graphics& g)
  33834. {
  33835. if (! hasDoneInitialUpdate)
  33836. updateContent();
  33837. g.fillAll (findColour (backgroundColourId));
  33838. }
  33839. void ListBox::paintOverChildren (Graphics& g)
  33840. {
  33841. if (outlineThickness > 0)
  33842. {
  33843. g.setColour (findColour (outlineColourId));
  33844. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  33845. }
  33846. }
  33847. void ListBox::resized()
  33848. {
  33849. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  33850. outlineThickness,
  33851. outlineThickness,
  33852. outlineThickness));
  33853. viewport->setSingleStepSizes (20, getRowHeight());
  33854. viewport->updateVisibleArea (false);
  33855. }
  33856. void ListBox::visibilityChanged()
  33857. {
  33858. viewport->updateVisibleArea (true);
  33859. }
  33860. Viewport* ListBox::getViewport() const throw()
  33861. {
  33862. return viewport;
  33863. }
  33864. void ListBox::updateContent()
  33865. {
  33866. hasDoneInitialUpdate = true;
  33867. totalItems = (model != 0) ? model->getNumRows() : 0;
  33868. bool selectionChanged = false;
  33869. if (selected [selected.size() - 1] >= totalItems)
  33870. {
  33871. selected.removeRange (totalItems, INT_MAX - totalItems);
  33872. lastRowSelected = getSelectedRow (0);
  33873. selectionChanged = true;
  33874. }
  33875. viewport->updateVisibleArea (isVisible());
  33876. viewport->resized();
  33877. if (selectionChanged && model != 0)
  33878. model->selectedRowsChanged (lastRowSelected);
  33879. }
  33880. void ListBox::selectRow (const int row,
  33881. bool dontScroll,
  33882. bool deselectOthersFirst)
  33883. {
  33884. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  33885. }
  33886. void ListBox::selectRowInternal (const int row,
  33887. bool dontScroll,
  33888. bool deselectOthersFirst,
  33889. bool isMouseClick)
  33890. {
  33891. if (! multipleSelection)
  33892. deselectOthersFirst = true;
  33893. if ((! isRowSelected (row))
  33894. || (deselectOthersFirst && getNumSelectedRows() > 1))
  33895. {
  33896. if (((unsigned int) row) < (unsigned int) totalItems)
  33897. {
  33898. if (deselectOthersFirst)
  33899. selected.clear();
  33900. selected.addRange (row, 1);
  33901. if (getHeight() == 0 || getWidth() == 0)
  33902. dontScroll = true;
  33903. viewport->hasUpdated = false;
  33904. if (row < viewport->firstWholeIndex && ! dontScroll)
  33905. {
  33906. viewport->setViewPosition (viewport->getViewPositionX(),
  33907. row * getRowHeight());
  33908. }
  33909. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  33910. {
  33911. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  33912. if (row >= lastRowSelected + rowsOnScreen
  33913. && rowsOnScreen < totalItems - 1
  33914. && ! isMouseClick)
  33915. {
  33916. viewport->setViewPosition (viewport->getViewPositionX(),
  33917. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  33918. * getRowHeight());
  33919. }
  33920. else
  33921. {
  33922. viewport->setViewPosition (viewport->getViewPositionX(),
  33923. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  33924. }
  33925. }
  33926. if (! viewport->hasUpdated)
  33927. viewport->updateContents();
  33928. lastRowSelected = row;
  33929. model->selectedRowsChanged (row);
  33930. }
  33931. else
  33932. {
  33933. if (deselectOthersFirst)
  33934. deselectAllRows();
  33935. }
  33936. }
  33937. }
  33938. void ListBox::deselectRow (const int row)
  33939. {
  33940. if (selected.contains (row))
  33941. {
  33942. selected.removeRange (row, 1);
  33943. if (row == lastRowSelected)
  33944. lastRowSelected = getSelectedRow (0);
  33945. viewport->updateContents();
  33946. model->selectedRowsChanged (lastRowSelected);
  33947. }
  33948. }
  33949. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  33950. const bool sendNotificationEventToModel)
  33951. {
  33952. selected = setOfRowsToBeSelected;
  33953. selected.removeRange (totalItems, INT_MAX - totalItems);
  33954. if (! isRowSelected (lastRowSelected))
  33955. lastRowSelected = getSelectedRow (0);
  33956. viewport->updateContents();
  33957. if ((model != 0) && sendNotificationEventToModel)
  33958. model->selectedRowsChanged (lastRowSelected);
  33959. }
  33960. const SparseSet<int> ListBox::getSelectedRows() const
  33961. {
  33962. return selected;
  33963. }
  33964. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  33965. {
  33966. if (multipleSelection && (firstRow != lastRow))
  33967. {
  33968. const int numRows = totalItems - 1;
  33969. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  33970. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  33971. selected.addRange (jmin (firstRow, lastRow),
  33972. abs (firstRow - lastRow) + 1);
  33973. selected.removeRange (lastRow, 1);
  33974. }
  33975. selectRowInternal (lastRow, false, false, true);
  33976. }
  33977. void ListBox::flipRowSelection (const int row)
  33978. {
  33979. if (isRowSelected (row))
  33980. deselectRow (row);
  33981. else
  33982. selectRowInternal (row, false, false, true);
  33983. }
  33984. void ListBox::deselectAllRows()
  33985. {
  33986. if (! selected.isEmpty())
  33987. {
  33988. selected.clear();
  33989. lastRowSelected = -1;
  33990. viewport->updateContents();
  33991. if (model != 0)
  33992. model->selectedRowsChanged (lastRowSelected);
  33993. }
  33994. }
  33995. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  33996. const ModifierKeys& mods)
  33997. {
  33998. if (multipleSelection && mods.isCommandDown())
  33999. {
  34000. flipRowSelection (row);
  34001. }
  34002. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  34003. {
  34004. selectRangeOfRows (lastRowSelected, row);
  34005. }
  34006. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  34007. {
  34008. selectRowInternal (row, false, true, true);
  34009. }
  34010. }
  34011. int ListBox::getNumSelectedRows() const
  34012. {
  34013. return selected.size();
  34014. }
  34015. int ListBox::getSelectedRow (const int index) const
  34016. {
  34017. return (((unsigned int) index) < (unsigned int) selected.size())
  34018. ? selected [index] : -1;
  34019. }
  34020. bool ListBox::isRowSelected (const int row) const
  34021. {
  34022. return selected.contains (row);
  34023. }
  34024. int ListBox::getLastRowSelected() const
  34025. {
  34026. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  34027. }
  34028. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  34029. {
  34030. if (((unsigned int) x) < (unsigned int) getWidth())
  34031. {
  34032. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  34033. if (((unsigned int) row) < (unsigned int) totalItems)
  34034. return row;
  34035. }
  34036. return -1;
  34037. }
  34038. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  34039. {
  34040. if (((unsigned int) x) < (unsigned int) getWidth())
  34041. {
  34042. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  34043. return jlimit (0, totalItems, row);
  34044. }
  34045. return -1;
  34046. }
  34047. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  34048. {
  34049. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  34050. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  34051. }
  34052. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  34053. {
  34054. return viewport->getRowNumberOfComponent (rowComponent);
  34055. }
  34056. const Rectangle ListBox::getRowPosition (const int rowNumber,
  34057. const bool relativeToComponentTopLeft) const throw()
  34058. {
  34059. const int rowHeight = getRowHeight();
  34060. int y = viewport->getY() + rowHeight * rowNumber;
  34061. if (relativeToComponentTopLeft)
  34062. y -= viewport->getViewPositionY();
  34063. return Rectangle (viewport->getX(), y,
  34064. viewport->getViewedComponent()->getWidth(), rowHeight);
  34065. }
  34066. void ListBox::setVerticalPosition (const double proportion)
  34067. {
  34068. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  34069. viewport->setViewPosition (viewport->getViewPositionX(),
  34070. jmax (0, roundDoubleToInt (proportion * offscreen)));
  34071. }
  34072. double ListBox::getVerticalPosition() const
  34073. {
  34074. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  34075. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  34076. : 0;
  34077. }
  34078. int ListBox::getVisibleRowWidth() const throw()
  34079. {
  34080. return viewport->getViewWidth();
  34081. }
  34082. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  34083. {
  34084. if (row < viewport->firstWholeIndex)
  34085. {
  34086. viewport->setViewPosition (viewport->getViewPositionX(),
  34087. row * getRowHeight());
  34088. }
  34089. else if (row >= viewport->lastWholeIndex)
  34090. {
  34091. viewport->setViewPosition (viewport->getViewPositionX(),
  34092. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  34093. }
  34094. }
  34095. bool ListBox::keyPressed (const KeyPress& key)
  34096. {
  34097. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  34098. const bool multiple = multipleSelection
  34099. && (lastRowSelected >= 0)
  34100. && (key.getModifiers().isShiftDown()
  34101. || key.getModifiers().isCtrlDown()
  34102. || key.getModifiers().isCommandDown());
  34103. if (key.isKeyCode (KeyPress::upKey))
  34104. {
  34105. if (multiple)
  34106. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  34107. else
  34108. selectRow (jmax (0, lastRowSelected - 1));
  34109. }
  34110. else if (key.isKeyCode (KeyPress::returnKey)
  34111. && isRowSelected (lastRowSelected))
  34112. {
  34113. if (model != 0)
  34114. model->returnKeyPressed (lastRowSelected);
  34115. }
  34116. else if (key.isKeyCode (KeyPress::pageUpKey))
  34117. {
  34118. if (multiple)
  34119. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  34120. else
  34121. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  34122. }
  34123. else if (key.isKeyCode (KeyPress::pageDownKey))
  34124. {
  34125. if (multiple)
  34126. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  34127. else
  34128. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  34129. }
  34130. else if (key.isKeyCode (KeyPress::homeKey))
  34131. {
  34132. if (multiple && key.getModifiers().isShiftDown())
  34133. selectRangeOfRows (lastRowSelected, 0);
  34134. else
  34135. selectRow (0);
  34136. }
  34137. else if (key.isKeyCode (KeyPress::endKey))
  34138. {
  34139. if (multiple && key.getModifiers().isShiftDown())
  34140. selectRangeOfRows (lastRowSelected, totalItems - 1);
  34141. else
  34142. selectRow (totalItems - 1);
  34143. }
  34144. else if (key.isKeyCode (KeyPress::downKey))
  34145. {
  34146. if (multiple)
  34147. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  34148. else
  34149. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  34150. }
  34151. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  34152. && isRowSelected (lastRowSelected))
  34153. {
  34154. if (model != 0)
  34155. model->deleteKeyPressed (lastRowSelected);
  34156. }
  34157. else if (multiple && key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  34158. {
  34159. selectRangeOfRows (0, INT_MAX);
  34160. }
  34161. else
  34162. {
  34163. return false;
  34164. }
  34165. return true;
  34166. }
  34167. bool ListBox::keyStateChanged()
  34168. {
  34169. return KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  34170. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  34171. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  34172. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  34173. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  34174. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  34175. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey);
  34176. }
  34177. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  34178. {
  34179. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  34180. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  34181. }
  34182. void ListBox::mouseMove (const MouseEvent& e)
  34183. {
  34184. if (mouseMoveSelects)
  34185. {
  34186. const MouseEvent e2 (e.getEventRelativeTo (this));
  34187. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  34188. lastMouseX = e2.x;
  34189. lastMouseY = e2.y;
  34190. }
  34191. }
  34192. void ListBox::mouseExit (const MouseEvent& e)
  34193. {
  34194. mouseMove (e);
  34195. }
  34196. void ListBox::mouseUp (const MouseEvent& e)
  34197. {
  34198. if (e.mouseWasClicked() && model != 0)
  34199. model->backgroundClicked();
  34200. }
  34201. void ListBox::setRowHeight (const int newHeight)
  34202. {
  34203. rowHeight = jmax (1, newHeight);
  34204. viewport->setSingleStepSizes (20, rowHeight);
  34205. updateContent();
  34206. }
  34207. int ListBox::getNumRowsOnScreen() const throw()
  34208. {
  34209. return viewport->getMaximumVisibleHeight() / rowHeight;
  34210. }
  34211. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  34212. {
  34213. minimumRowWidth = newMinimumWidth;
  34214. updateContent();
  34215. }
  34216. int ListBox::getVisibleContentWidth() const throw()
  34217. {
  34218. return viewport->getMaximumVisibleWidth();
  34219. }
  34220. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  34221. {
  34222. return viewport->getVerticalScrollBar();
  34223. }
  34224. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  34225. {
  34226. return viewport->getHorizontalScrollBar();
  34227. }
  34228. void ListBox::colourChanged()
  34229. {
  34230. setOpaque (findColour (backgroundColourId).isOpaque());
  34231. viewport->setOpaque (isOpaque());
  34232. repaint();
  34233. }
  34234. void ListBox::setOutlineThickness (const int outlineThickness_)
  34235. {
  34236. outlineThickness = outlineThickness_;
  34237. resized();
  34238. }
  34239. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  34240. {
  34241. if (headerComponent != newHeaderComponent)
  34242. {
  34243. if (headerComponent != 0)
  34244. delete headerComponent;
  34245. headerComponent = newHeaderComponent;
  34246. addAndMakeVisible (newHeaderComponent);
  34247. ListBox::resized();
  34248. }
  34249. }
  34250. void ListBox::repaintRow (const int rowNumber) throw()
  34251. {
  34252. const Rectangle r (getRowPosition (rowNumber, true));
  34253. repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  34254. }
  34255. Image* ListBox::createSnapshotOfSelectedRows()
  34256. {
  34257. Image* snapshot = new Image (Image::ARGB, getWidth(), getHeight(), true);
  34258. Graphics g (*snapshot);
  34259. const int firstRow = getRowContainingPosition (0, 0);
  34260. for (int i = getNumRowsOnScreen() + 2; --i >= 0;)
  34261. {
  34262. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  34263. if (rowComp != 0 && isRowSelected (firstRow + i))
  34264. {
  34265. g.saveState();
  34266. int x = 0, y = 0;
  34267. rowComp->relativePositionToOtherComponent (this, x, y);
  34268. g.setOrigin (x, y);
  34269. g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight());
  34270. rowComp->paintEntireComponent (g);
  34271. g.restoreState();
  34272. }
  34273. }
  34274. return snapshot;
  34275. }
  34276. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  34277. {
  34278. (void) existingComponentToUpdate;
  34279. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  34280. return 0;
  34281. }
  34282. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  34283. {
  34284. }
  34285. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  34286. {
  34287. }
  34288. void ListBoxModel::backgroundClicked()
  34289. {
  34290. }
  34291. void ListBoxModel::selectedRowsChanged (int)
  34292. {
  34293. }
  34294. void ListBoxModel::deleteKeyPressed (int)
  34295. {
  34296. }
  34297. void ListBoxModel::returnKeyPressed (int)
  34298. {
  34299. }
  34300. void ListBoxModel::listWasScrolled()
  34301. {
  34302. }
  34303. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  34304. {
  34305. return String::empty;
  34306. }
  34307. END_JUCE_NAMESPACE
  34308. /********* End of inlined file: juce_ListBox.cpp *********/
  34309. /********* Start of inlined file: juce_ProgressBar.cpp *********/
  34310. BEGIN_JUCE_NAMESPACE
  34311. ProgressBar::ProgressBar (double& progress_)
  34312. : progress (progress_),
  34313. displayPercentage (true)
  34314. {
  34315. currentValue = jlimit (0.0, 1.0, progress);
  34316. }
  34317. ProgressBar::~ProgressBar()
  34318. {
  34319. }
  34320. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  34321. {
  34322. displayPercentage = shouldDisplayPercentage;
  34323. repaint();
  34324. }
  34325. void ProgressBar::setTextToDisplay (const String& text)
  34326. {
  34327. displayPercentage = false;
  34328. displayedMessage = text;
  34329. }
  34330. void ProgressBar::lookAndFeelChanged()
  34331. {
  34332. setOpaque (findColour (backgroundColourId).isOpaque());
  34333. }
  34334. void ProgressBar::colourChanged()
  34335. {
  34336. lookAndFeelChanged();
  34337. }
  34338. void ProgressBar::paint (Graphics& g)
  34339. {
  34340. String text;
  34341. if (displayPercentage)
  34342. {
  34343. if (currentValue >= 0 && currentValue <= 1.0)
  34344. text << roundDoubleToInt (currentValue * 100.0) << T("%");
  34345. }
  34346. else
  34347. {
  34348. text = displayedMessage;
  34349. }
  34350. getLookAndFeel().drawProgressBar (g, *this,
  34351. getWidth(), getHeight(),
  34352. currentValue, text);
  34353. }
  34354. void ProgressBar::visibilityChanged()
  34355. {
  34356. if (isVisible())
  34357. startTimer (30);
  34358. else
  34359. stopTimer();
  34360. }
  34361. void ProgressBar::timerCallback()
  34362. {
  34363. double newProgress = progress;
  34364. if (currentValue != newProgress
  34365. || newProgress < 0 || newProgress >= 1.0
  34366. || currentMessage != displayedMessage)
  34367. {
  34368. if (currentValue < newProgress
  34369. && newProgress >= 0 && newProgress < 1.0
  34370. && currentValue >= 0 && newProgress < 1.0)
  34371. {
  34372. newProgress = jmin (currentValue + 0.02, newProgress);
  34373. }
  34374. currentValue = newProgress;
  34375. currentMessage = displayedMessage;
  34376. repaint();
  34377. }
  34378. }
  34379. END_JUCE_NAMESPACE
  34380. /********* End of inlined file: juce_ProgressBar.cpp *********/
  34381. /********* Start of inlined file: juce_Slider.cpp *********/
  34382. BEGIN_JUCE_NAMESPACE
  34383. class SliderPopupDisplayComponent : public BubbleComponent
  34384. {
  34385. public:
  34386. SliderPopupDisplayComponent (Slider* const owner_)
  34387. : owner (owner_),
  34388. font (15.0f, Font::bold)
  34389. {
  34390. setAlwaysOnTop (true);
  34391. }
  34392. ~SliderPopupDisplayComponent()
  34393. {
  34394. }
  34395. void paintContent (Graphics& g, int w, int h)
  34396. {
  34397. g.setFont (font);
  34398. g.setColour (Colours::black);
  34399. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  34400. }
  34401. void getContentSize (int& w, int& h)
  34402. {
  34403. w = font.getStringWidth (text) + 18;
  34404. h = (int) (font.getHeight() * 1.6f);
  34405. }
  34406. void updatePosition (const String& newText)
  34407. {
  34408. if (text != newText)
  34409. {
  34410. text = newText;
  34411. repaint();
  34412. }
  34413. BubbleComponent::setPosition (owner);
  34414. }
  34415. juce_UseDebuggingNewOperator
  34416. private:
  34417. Slider* owner;
  34418. Font font;
  34419. String text;
  34420. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  34421. const SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  34422. };
  34423. Slider::Slider (const String& name)
  34424. : Component (name),
  34425. listeners (2),
  34426. currentValue (0.0),
  34427. valueMin (0.0),
  34428. valueMax (0.0),
  34429. minimum (0),
  34430. maximum (10),
  34431. interval (0),
  34432. skewFactor (1.0),
  34433. velocityModeSensitivity (1.0),
  34434. velocityModeOffset (0.0),
  34435. velocityModeThreshold (1),
  34436. rotaryStart (float_Pi * 1.2f),
  34437. rotaryEnd (float_Pi * 2.8f),
  34438. numDecimalPlaces (7),
  34439. sliderRegionStart (0),
  34440. sliderRegionSize (1),
  34441. sliderBeingDragged (-1),
  34442. pixelsForFullDragExtent (250),
  34443. style (LinearHorizontal),
  34444. textBoxPos (TextBoxLeft),
  34445. textBoxWidth (80),
  34446. textBoxHeight (20),
  34447. incDecButtonMode (incDecButtonsNotDraggable),
  34448. editableText (true),
  34449. doubleClickToValue (false),
  34450. isVelocityBased (false),
  34451. userKeyOverridesVelocity (true),
  34452. rotaryStop (true),
  34453. incDecButtonsSideBySide (false),
  34454. sendChangeOnlyOnRelease (false),
  34455. popupDisplayEnabled (false),
  34456. menuEnabled (false),
  34457. menuShown (false),
  34458. scrollWheelEnabled (true),
  34459. snapsToMousePos (true),
  34460. valueBox (0),
  34461. incButton (0),
  34462. decButton (0),
  34463. popupDisplay (0),
  34464. parentForPopupDisplay (0)
  34465. {
  34466. setWantsKeyboardFocus (false);
  34467. setRepaintsOnMouseActivity (true);
  34468. lookAndFeelChanged();
  34469. updateText();
  34470. }
  34471. Slider::~Slider()
  34472. {
  34473. deleteAndZero (popupDisplay);
  34474. deleteAllChildren();
  34475. }
  34476. void Slider::handleAsyncUpdate()
  34477. {
  34478. cancelPendingUpdate();
  34479. for (int i = listeners.size(); --i >= 0;)
  34480. {
  34481. ((SliderListener*) listeners.getUnchecked (i))->sliderValueChanged (this);
  34482. i = jmin (i, listeners.size());
  34483. }
  34484. }
  34485. void Slider::sendDragStart()
  34486. {
  34487. startedDragging();
  34488. for (int i = listeners.size(); --i >= 0;)
  34489. {
  34490. ((SliderListener*) listeners.getUnchecked (i))->sliderDragStarted (this);
  34491. i = jmin (i, listeners.size());
  34492. }
  34493. }
  34494. void Slider::sendDragEnd()
  34495. {
  34496. stoppedDragging();
  34497. sliderBeingDragged = -1;
  34498. for (int i = listeners.size(); --i >= 0;)
  34499. {
  34500. ((SliderListener*) listeners.getUnchecked (i))->sliderDragEnded (this);
  34501. i = jmin (i, listeners.size());
  34502. }
  34503. }
  34504. void Slider::addListener (SliderListener* const listener) throw()
  34505. {
  34506. jassert (listener != 0);
  34507. if (listener != 0)
  34508. listeners.add (listener);
  34509. }
  34510. void Slider::removeListener (SliderListener* const listener) throw()
  34511. {
  34512. listeners.removeValue (listener);
  34513. }
  34514. void Slider::setSliderStyle (const SliderStyle newStyle)
  34515. {
  34516. if (style != newStyle)
  34517. {
  34518. style = newStyle;
  34519. repaint();
  34520. lookAndFeelChanged();
  34521. }
  34522. }
  34523. void Slider::setRotaryParameters (const float startAngleRadians,
  34524. const float endAngleRadians,
  34525. const bool stopAtEnd)
  34526. {
  34527. // make sure the values are sensible..
  34528. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  34529. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  34530. jassert (rotaryStart < rotaryEnd);
  34531. rotaryStart = startAngleRadians;
  34532. rotaryEnd = endAngleRadians;
  34533. rotaryStop = stopAtEnd;
  34534. }
  34535. void Slider::setVelocityBasedMode (const bool velBased) throw()
  34536. {
  34537. isVelocityBased = velBased;
  34538. }
  34539. void Slider::setVelocityModeParameters (const double sensitivity,
  34540. const int threshold,
  34541. const double offset,
  34542. const bool userCanPressKeyToSwapMode) throw()
  34543. {
  34544. jassert (threshold >= 0);
  34545. jassert (sensitivity > 0);
  34546. jassert (offset >= 0);
  34547. velocityModeSensitivity = sensitivity;
  34548. velocityModeOffset = offset;
  34549. velocityModeThreshold = threshold;
  34550. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  34551. }
  34552. void Slider::setSkewFactor (const double factor) throw()
  34553. {
  34554. skewFactor = factor;
  34555. }
  34556. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw()
  34557. {
  34558. if (maximum > minimum)
  34559. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  34560. / (maximum - minimum));
  34561. }
  34562. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  34563. {
  34564. jassert (distanceForFullScaleDrag > 0);
  34565. pixelsForFullDragExtent = distanceForFullScaleDrag;
  34566. }
  34567. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  34568. {
  34569. if (incDecButtonMode != mode)
  34570. {
  34571. incDecButtonMode = mode;
  34572. lookAndFeelChanged();
  34573. }
  34574. }
  34575. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  34576. const bool isReadOnly,
  34577. const int textEntryBoxWidth,
  34578. const int textEntryBoxHeight)
  34579. {
  34580. textBoxPos = newPosition;
  34581. editableText = ! isReadOnly;
  34582. textBoxWidth = textEntryBoxWidth;
  34583. textBoxHeight = textEntryBoxHeight;
  34584. repaint();
  34585. lookAndFeelChanged();
  34586. }
  34587. void Slider::setTextBoxIsEditable (const bool shouldBeEditable) throw()
  34588. {
  34589. editableText = shouldBeEditable;
  34590. if (valueBox != 0)
  34591. valueBox->setEditable (shouldBeEditable && isEnabled());
  34592. }
  34593. void Slider::showTextBox()
  34594. {
  34595. jassert (editableText); // this should probably be avoided in read-only sliders.
  34596. if (valueBox != 0)
  34597. valueBox->showEditor();
  34598. }
  34599. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  34600. {
  34601. if (valueBox != 0)
  34602. {
  34603. valueBox->hideEditor (discardCurrentEditorContents);
  34604. if (discardCurrentEditorContents)
  34605. updateText();
  34606. }
  34607. }
  34608. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw()
  34609. {
  34610. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  34611. }
  34612. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw()
  34613. {
  34614. snapsToMousePos = shouldSnapToMouse;
  34615. }
  34616. void Slider::setPopupDisplayEnabled (const bool enabled,
  34617. Component* const parentComponentToUse) throw()
  34618. {
  34619. popupDisplayEnabled = enabled;
  34620. parentForPopupDisplay = parentComponentToUse;
  34621. }
  34622. void Slider::colourChanged()
  34623. {
  34624. lookAndFeelChanged();
  34625. }
  34626. void Slider::lookAndFeelChanged()
  34627. {
  34628. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  34629. : getTextFromValue (currentValue));
  34630. deleteAllChildren();
  34631. valueBox = 0;
  34632. LookAndFeel& lf = getLookAndFeel();
  34633. if (textBoxPos != NoTextBox)
  34634. {
  34635. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  34636. valueBox->setWantsKeyboardFocus (false);
  34637. valueBox->setText (previousTextBoxContent, false);
  34638. valueBox->setEditable (editableText && isEnabled());
  34639. valueBox->addListener (this);
  34640. if (style == LinearBar)
  34641. valueBox->addMouseListener (this, false);
  34642. }
  34643. if (style == IncDecButtons)
  34644. {
  34645. addAndMakeVisible (incButton = lf.createSliderButton (true));
  34646. incButton->addButtonListener (this);
  34647. addAndMakeVisible (decButton = lf.createSliderButton (false));
  34648. decButton->addButtonListener (this);
  34649. if (incDecButtonMode != incDecButtonsNotDraggable)
  34650. {
  34651. incButton->addMouseListener (this, false);
  34652. decButton->addMouseListener (this, false);
  34653. }
  34654. else
  34655. {
  34656. incButton->setRepeatSpeed (300, 100, 20);
  34657. incButton->addMouseListener (decButton, false);
  34658. decButton->setRepeatSpeed (300, 100, 20);
  34659. decButton->addMouseListener (incButton, false);
  34660. }
  34661. }
  34662. setComponentEffect (lf.getSliderEffect());
  34663. resized();
  34664. repaint();
  34665. }
  34666. void Slider::setRange (const double newMin,
  34667. const double newMax,
  34668. const double newInt)
  34669. {
  34670. if (minimum != newMin
  34671. || maximum != newMax
  34672. || interval != newInt)
  34673. {
  34674. minimum = newMin;
  34675. maximum = newMax;
  34676. interval = newInt;
  34677. // figure out the number of DPs needed to display all values at this
  34678. // interval setting.
  34679. numDecimalPlaces = 7;
  34680. if (newInt != 0)
  34681. {
  34682. int v = abs ((int) (newInt * 10000000));
  34683. while ((v % 10) == 0)
  34684. {
  34685. --numDecimalPlaces;
  34686. v /= 10;
  34687. }
  34688. }
  34689. // keep the current values inside the new range..
  34690. if (style != TwoValueHorizontal && style != TwoValueVertical)
  34691. {
  34692. setValue (currentValue, false, false);
  34693. }
  34694. else
  34695. {
  34696. setMinValue (getMinValue(), false, false);
  34697. setMaxValue (getMaxValue(), false, false);
  34698. }
  34699. updateText();
  34700. }
  34701. }
  34702. void Slider::triggerChangeMessage (const bool synchronous)
  34703. {
  34704. if (synchronous)
  34705. handleAsyncUpdate();
  34706. else
  34707. triggerAsyncUpdate();
  34708. valueChanged();
  34709. }
  34710. double Slider::getValue() const throw()
  34711. {
  34712. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  34713. // methods to get the two values.
  34714. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  34715. return currentValue;
  34716. }
  34717. void Slider::setValue (double newValue,
  34718. const bool sendUpdateMessage,
  34719. const bool sendMessageSynchronously)
  34720. {
  34721. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  34722. // methods to set the two values.
  34723. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  34724. newValue = constrainedValue (newValue);
  34725. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  34726. {
  34727. jassert (valueMin <= valueMax);
  34728. newValue = jlimit (valueMin, valueMax, newValue);
  34729. }
  34730. if (currentValue != newValue)
  34731. {
  34732. if (valueBox != 0)
  34733. valueBox->hideEditor (true);
  34734. currentValue = newValue;
  34735. updateText();
  34736. repaint();
  34737. if (popupDisplay != 0)
  34738. {
  34739. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (currentValue));
  34740. popupDisplay->repaint();
  34741. }
  34742. if (sendUpdateMessage)
  34743. triggerChangeMessage (sendMessageSynchronously);
  34744. }
  34745. }
  34746. double Slider::getMinValue() const throw()
  34747. {
  34748. // The minimum value only applies to sliders that are in two- or three-value mode.
  34749. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34750. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34751. return valueMin;
  34752. }
  34753. double Slider::getMaxValue() const throw()
  34754. {
  34755. // The maximum value only applies to sliders that are in two- or three-value mode.
  34756. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34757. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34758. return valueMax;
  34759. }
  34760. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously)
  34761. {
  34762. // The minimum value only applies to sliders that are in two- or three-value mode.
  34763. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34764. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34765. newValue = constrainedValue (newValue);
  34766. if (style == TwoValueHorizontal || style == TwoValueVertical)
  34767. newValue = jmin (valueMax, newValue);
  34768. else
  34769. newValue = jmin (currentValue, newValue);
  34770. if (valueMin != newValue)
  34771. {
  34772. valueMin = newValue;
  34773. repaint();
  34774. if (popupDisplay != 0)
  34775. {
  34776. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMin));
  34777. popupDisplay->repaint();
  34778. }
  34779. if (sendUpdateMessage)
  34780. triggerChangeMessage (sendMessageSynchronously);
  34781. }
  34782. }
  34783. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously)
  34784. {
  34785. // The maximum value only applies to sliders that are in two- or three-value mode.
  34786. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34787. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34788. newValue = constrainedValue (newValue);
  34789. if (style == TwoValueHorizontal || style == TwoValueVertical)
  34790. newValue = jmax (valueMin, newValue);
  34791. else
  34792. newValue = jmax (currentValue, newValue);
  34793. if (valueMax != newValue)
  34794. {
  34795. valueMax = newValue;
  34796. repaint();
  34797. if (popupDisplay != 0)
  34798. {
  34799. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMax));
  34800. popupDisplay->repaint();
  34801. }
  34802. if (sendUpdateMessage)
  34803. triggerChangeMessage (sendMessageSynchronously);
  34804. }
  34805. }
  34806. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  34807. const double valueToSetOnDoubleClick) throw()
  34808. {
  34809. doubleClickToValue = isDoubleClickEnabled;
  34810. doubleClickReturnValue = valueToSetOnDoubleClick;
  34811. }
  34812. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const throw()
  34813. {
  34814. isEnabled_ = doubleClickToValue;
  34815. return doubleClickReturnValue;
  34816. }
  34817. void Slider::updateText()
  34818. {
  34819. if (valueBox != 0)
  34820. valueBox->setText (getTextFromValue (currentValue), false);
  34821. }
  34822. void Slider::setTextValueSuffix (const String& suffix)
  34823. {
  34824. if (textSuffix != suffix)
  34825. {
  34826. textSuffix = suffix;
  34827. updateText();
  34828. }
  34829. }
  34830. const String Slider::getTextFromValue (double v)
  34831. {
  34832. if (numDecimalPlaces > 0)
  34833. return String (v, numDecimalPlaces) + textSuffix;
  34834. else
  34835. return String (roundDoubleToInt (v)) + textSuffix;
  34836. }
  34837. double Slider::getValueFromText (const String& text)
  34838. {
  34839. String t (text.trimStart());
  34840. if (t.endsWith (textSuffix))
  34841. t = t.substring (0, t.length() - textSuffix.length());
  34842. while (t.startsWithChar (T('+')))
  34843. t = t.substring (1).trimStart();
  34844. return t.initialSectionContainingOnly (T("0123456789.,-"))
  34845. .getDoubleValue();
  34846. }
  34847. double Slider::proportionOfLengthToValue (double proportion)
  34848. {
  34849. if (skewFactor != 1.0 && proportion > 0.0)
  34850. proportion = exp (log (proportion) / skewFactor);
  34851. return minimum + (maximum - minimum) * proportion;
  34852. }
  34853. double Slider::valueToProportionOfLength (double value)
  34854. {
  34855. const double n = (value - minimum) / (maximum - minimum);
  34856. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  34857. }
  34858. double Slider::snapValue (double attemptedValue, const bool)
  34859. {
  34860. return attemptedValue;
  34861. }
  34862. void Slider::startedDragging()
  34863. {
  34864. }
  34865. void Slider::stoppedDragging()
  34866. {
  34867. }
  34868. void Slider::valueChanged()
  34869. {
  34870. }
  34871. void Slider::enablementChanged()
  34872. {
  34873. repaint();
  34874. }
  34875. void Slider::setPopupMenuEnabled (const bool menuEnabled_) throw()
  34876. {
  34877. menuEnabled = menuEnabled_;
  34878. }
  34879. void Slider::setScrollWheelEnabled (const bool enabled) throw()
  34880. {
  34881. scrollWheelEnabled = enabled;
  34882. }
  34883. void Slider::labelTextChanged (Label* label)
  34884. {
  34885. const double newValue = snapValue (getValueFromText (label->getText()), false);
  34886. if (getValue() != newValue)
  34887. {
  34888. sendDragStart();
  34889. setValue (newValue, true, true);
  34890. sendDragEnd();
  34891. }
  34892. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  34893. }
  34894. void Slider::buttonClicked (Button* button)
  34895. {
  34896. if (style == IncDecButtons)
  34897. {
  34898. sendDragStart();
  34899. if (button == incButton)
  34900. setValue (snapValue (getValue() + interval, false), true, true);
  34901. else if (button == decButton)
  34902. setValue (snapValue (getValue() - interval, false), true, true);
  34903. sendDragEnd();
  34904. }
  34905. }
  34906. double Slider::constrainedValue (double value) const throw()
  34907. {
  34908. if (interval > 0)
  34909. value = minimum + interval * floor ((value - minimum) / interval + 0.5);
  34910. if (value <= minimum || maximum <= minimum)
  34911. value = minimum;
  34912. else if (value >= maximum)
  34913. value = maximum;
  34914. return value;
  34915. }
  34916. float Slider::getLinearSliderPos (const double value)
  34917. {
  34918. double sliderPosProportional;
  34919. if (maximum > minimum)
  34920. {
  34921. if (value < minimum)
  34922. {
  34923. sliderPosProportional = 0.0;
  34924. }
  34925. else if (value > maximum)
  34926. {
  34927. sliderPosProportional = 1.0;
  34928. }
  34929. else
  34930. {
  34931. sliderPosProportional = valueToProportionOfLength (value);
  34932. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  34933. }
  34934. }
  34935. else
  34936. {
  34937. sliderPosProportional = 0.5;
  34938. }
  34939. if (style == LinearVertical || style == IncDecButtons)
  34940. sliderPosProportional = 1.0 - sliderPosProportional;
  34941. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  34942. }
  34943. bool Slider::isHorizontal() const throw()
  34944. {
  34945. return style == LinearHorizontal
  34946. || style == LinearBar
  34947. || style == TwoValueHorizontal
  34948. || style == ThreeValueHorizontal;
  34949. }
  34950. bool Slider::isVertical() const throw()
  34951. {
  34952. return style == LinearVertical
  34953. || style == TwoValueVertical
  34954. || style == ThreeValueVertical;
  34955. }
  34956. bool Slider::incDecDragDirectionIsHorizontal() const throw()
  34957. {
  34958. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  34959. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  34960. }
  34961. float Slider::getPositionOfValue (const double value)
  34962. {
  34963. if (isHorizontal() || isVertical())
  34964. {
  34965. return getLinearSliderPos (value);
  34966. }
  34967. else
  34968. {
  34969. jassertfalse // not a valid call on a slider that doesn't work linearly!
  34970. return 0.0f;
  34971. }
  34972. }
  34973. void Slider::paint (Graphics& g)
  34974. {
  34975. if (style != IncDecButtons)
  34976. {
  34977. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  34978. {
  34979. const float sliderPos = (float) valueToProportionOfLength (currentValue);
  34980. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  34981. getLookAndFeel().drawRotarySlider (g,
  34982. sliderRect.getX(),
  34983. sliderRect.getY(),
  34984. sliderRect.getWidth(),
  34985. sliderRect.getHeight(),
  34986. sliderPos,
  34987. rotaryStart, rotaryEnd,
  34988. *this);
  34989. }
  34990. else
  34991. {
  34992. getLookAndFeel().drawLinearSlider (g,
  34993. sliderRect.getX(),
  34994. sliderRect.getY(),
  34995. sliderRect.getWidth(),
  34996. sliderRect.getHeight(),
  34997. getLinearSliderPos (currentValue),
  34998. getLinearSliderPos (valueMin),
  34999. getLinearSliderPos (valueMax),
  35000. style,
  35001. *this);
  35002. }
  35003. if (style == LinearBar && valueBox == 0)
  35004. {
  35005. g.setColour (findColour (Slider::textBoxOutlineColourId));
  35006. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  35007. }
  35008. }
  35009. }
  35010. void Slider::resized()
  35011. {
  35012. int minXSpace = 0;
  35013. int minYSpace = 0;
  35014. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  35015. minXSpace = 30;
  35016. else
  35017. minYSpace = 15;
  35018. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  35019. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  35020. if (style == LinearBar)
  35021. {
  35022. if (valueBox != 0)
  35023. valueBox->setBounds (0, 0, getWidth(), getHeight());
  35024. }
  35025. else
  35026. {
  35027. if (textBoxPos == NoTextBox)
  35028. {
  35029. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  35030. }
  35031. else if (textBoxPos == TextBoxLeft)
  35032. {
  35033. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  35034. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  35035. }
  35036. else if (textBoxPos == TextBoxRight)
  35037. {
  35038. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  35039. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  35040. }
  35041. else if (textBoxPos == TextBoxAbove)
  35042. {
  35043. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  35044. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  35045. }
  35046. else if (textBoxPos == TextBoxBelow)
  35047. {
  35048. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  35049. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  35050. }
  35051. }
  35052. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  35053. if (style == LinearBar)
  35054. {
  35055. const int barIndent = 1;
  35056. sliderRegionStart = barIndent;
  35057. sliderRegionSize = getWidth() - barIndent * 2;
  35058. sliderRect.setBounds (sliderRegionStart, barIndent,
  35059. sliderRegionSize, getHeight() - barIndent * 2);
  35060. }
  35061. else if (isHorizontal())
  35062. {
  35063. sliderRegionStart = sliderRect.getX() + indent;
  35064. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  35065. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  35066. sliderRegionSize, sliderRect.getHeight());
  35067. }
  35068. else if (isVertical())
  35069. {
  35070. sliderRegionStart = sliderRect.getY() + indent;
  35071. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  35072. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  35073. sliderRect.getWidth(), sliderRegionSize);
  35074. }
  35075. else
  35076. {
  35077. sliderRegionStart = 0;
  35078. sliderRegionSize = 100;
  35079. }
  35080. if (style == IncDecButtons)
  35081. {
  35082. Rectangle buttonRect (sliderRect);
  35083. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  35084. buttonRect.expand (-2, 0);
  35085. else
  35086. buttonRect.expand (0, -2);
  35087. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  35088. if (incDecButtonsSideBySide)
  35089. {
  35090. decButton->setBounds (buttonRect.getX(),
  35091. buttonRect.getY(),
  35092. buttonRect.getWidth() / 2,
  35093. buttonRect.getHeight());
  35094. decButton->setConnectedEdges (Button::ConnectedOnRight);
  35095. incButton->setBounds (buttonRect.getCentreX(),
  35096. buttonRect.getY(),
  35097. buttonRect.getWidth() / 2,
  35098. buttonRect.getHeight());
  35099. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  35100. }
  35101. else
  35102. {
  35103. incButton->setBounds (buttonRect.getX(),
  35104. buttonRect.getY(),
  35105. buttonRect.getWidth(),
  35106. buttonRect.getHeight() / 2);
  35107. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  35108. decButton->setBounds (buttonRect.getX(),
  35109. buttonRect.getCentreY(),
  35110. buttonRect.getWidth(),
  35111. buttonRect.getHeight() / 2);
  35112. decButton->setConnectedEdges (Button::ConnectedOnTop);
  35113. }
  35114. }
  35115. }
  35116. void Slider::focusOfChildComponentChanged (FocusChangeType)
  35117. {
  35118. repaint();
  35119. }
  35120. void Slider::mouseDown (const MouseEvent& e)
  35121. {
  35122. mouseWasHidden = false;
  35123. incDecDragged = false;
  35124. if (isEnabled())
  35125. {
  35126. if (e.mods.isPopupMenu() && menuEnabled)
  35127. {
  35128. menuShown = true;
  35129. PopupMenu m;
  35130. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  35131. m.addSeparator();
  35132. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  35133. {
  35134. PopupMenu rotaryMenu;
  35135. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  35136. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  35137. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  35138. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  35139. }
  35140. const int r = m.show();
  35141. if (r == 1)
  35142. {
  35143. setVelocityBasedMode (! isVelocityBased);
  35144. }
  35145. else if (r == 2)
  35146. {
  35147. setSliderStyle (Rotary);
  35148. }
  35149. else if (r == 3)
  35150. {
  35151. setSliderStyle (RotaryHorizontalDrag);
  35152. }
  35153. else if (r == 4)
  35154. {
  35155. setSliderStyle (RotaryVerticalDrag);
  35156. }
  35157. }
  35158. else if (maximum > minimum)
  35159. {
  35160. menuShown = false;
  35161. if (valueBox != 0)
  35162. valueBox->hideEditor (true);
  35163. sliderBeingDragged = 0;
  35164. if (style == TwoValueHorizontal
  35165. || style == TwoValueVertical
  35166. || style == ThreeValueHorizontal
  35167. || style == ThreeValueVertical)
  35168. {
  35169. const float mousePos = (float) (isVertical() ? e.y : e.x);
  35170. const float normalPosDistance = fabsf (getLinearSliderPos (currentValue) - mousePos);
  35171. const float minPosDistance = fabsf (getLinearSliderPos (valueMin) - 0.1f - mousePos);
  35172. const float maxPosDistance = fabsf (getLinearSliderPos (valueMax) + 0.1f - mousePos);
  35173. if (style == TwoValueHorizontal || style == TwoValueVertical)
  35174. {
  35175. if (maxPosDistance <= minPosDistance)
  35176. sliderBeingDragged = 2;
  35177. else
  35178. sliderBeingDragged = 1;
  35179. }
  35180. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  35181. {
  35182. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  35183. sliderBeingDragged = 1;
  35184. else if (normalPosDistance >= maxPosDistance)
  35185. sliderBeingDragged = 2;
  35186. }
  35187. }
  35188. minMaxDiff = valueMax - valueMin;
  35189. mouseXWhenLastDragged = e.x;
  35190. mouseYWhenLastDragged = e.y;
  35191. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  35192. * valueToProportionOfLength (currentValue);
  35193. if (sliderBeingDragged == 2)
  35194. valueWhenLastDragged = valueMax;
  35195. else if (sliderBeingDragged == 1)
  35196. valueWhenLastDragged = valueMin;
  35197. else
  35198. valueWhenLastDragged = currentValue;
  35199. valueOnMouseDown = valueWhenLastDragged;
  35200. if (popupDisplayEnabled)
  35201. {
  35202. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  35203. popupDisplay = popup;
  35204. if (parentForPopupDisplay != 0)
  35205. {
  35206. parentForPopupDisplay->addChildComponent (popup);
  35207. }
  35208. else
  35209. {
  35210. popup->addToDesktop (0);
  35211. }
  35212. popup->setVisible (true);
  35213. }
  35214. sendDragStart();
  35215. mouseDrag (e);
  35216. }
  35217. }
  35218. }
  35219. void Slider::mouseUp (const MouseEvent&)
  35220. {
  35221. if (isEnabled()
  35222. && (! menuShown)
  35223. && (maximum > minimum)
  35224. && (style != IncDecButtons || incDecDragged))
  35225. {
  35226. restoreMouseIfHidden();
  35227. if (sendChangeOnlyOnRelease && valueOnMouseDown != currentValue)
  35228. triggerChangeMessage (false);
  35229. sendDragEnd();
  35230. deleteAndZero (popupDisplay);
  35231. if (style == IncDecButtons)
  35232. {
  35233. incButton->setState (Button::buttonNormal);
  35234. decButton->setState (Button::buttonNormal);
  35235. }
  35236. }
  35237. }
  35238. void Slider::restoreMouseIfHidden()
  35239. {
  35240. if (mouseWasHidden)
  35241. {
  35242. mouseWasHidden = false;
  35243. Component* c = Component::getComponentUnderMouse();
  35244. if (c == 0)
  35245. c = this;
  35246. c->enableUnboundedMouseMovement (false);
  35247. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  35248. : ((sliderBeingDragged == 1) ? getMinValue()
  35249. : currentValue);
  35250. const int pixelPos = (int) getLinearSliderPos (pos);
  35251. int x = isHorizontal() ? pixelPos : (getWidth() / 2);
  35252. int y = isVertical() ? pixelPos : (getHeight() / 2);
  35253. relativePositionToGlobal (x, y);
  35254. Desktop::setMousePosition (x, y);
  35255. }
  35256. }
  35257. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  35258. {
  35259. if (isEnabled()
  35260. && style != IncDecButtons
  35261. && style != Rotary
  35262. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  35263. {
  35264. restoreMouseIfHidden();
  35265. }
  35266. }
  35267. static double smallestAngleBetween (double a1, double a2)
  35268. {
  35269. return jmin (fabs (a1 - a2),
  35270. fabs (a1 + double_Pi * 2.0 - a2),
  35271. fabs (a2 + double_Pi * 2.0 - a1));
  35272. }
  35273. void Slider::mouseDrag (const MouseEvent& e)
  35274. {
  35275. if (isEnabled()
  35276. && (! menuShown)
  35277. && (maximum > minimum))
  35278. {
  35279. if (style == Rotary)
  35280. {
  35281. int dx = e.x - sliderRect.getCentreX();
  35282. int dy = e.y - sliderRect.getCentreY();
  35283. if (dx * dx + dy * dy > 25)
  35284. {
  35285. double angle = atan2 ((double) dx, (double) -dy);
  35286. while (angle < 0.0)
  35287. angle += double_Pi * 2.0;
  35288. if (rotaryStop && ! e.mouseWasClicked())
  35289. {
  35290. if (fabs (angle - lastAngle) > double_Pi)
  35291. {
  35292. if (angle >= lastAngle)
  35293. angle -= double_Pi * 2.0;
  35294. else
  35295. angle += double_Pi * 2.0;
  35296. }
  35297. if (angle >= lastAngle)
  35298. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  35299. else
  35300. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  35301. }
  35302. else
  35303. {
  35304. while (angle < rotaryStart)
  35305. angle += double_Pi * 2.0;
  35306. if (angle > rotaryEnd)
  35307. {
  35308. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  35309. angle = rotaryStart;
  35310. else
  35311. angle = rotaryEnd;
  35312. }
  35313. }
  35314. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  35315. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  35316. lastAngle = angle;
  35317. }
  35318. }
  35319. else
  35320. {
  35321. if (style == LinearBar && e.mouseWasClicked()
  35322. && valueBox != 0 && valueBox->isEditable())
  35323. return;
  35324. if (style == IncDecButtons)
  35325. {
  35326. if (! incDecDragged)
  35327. incDecDragged = e.getDistanceFromDragStart() > 10 && ! e.mouseWasClicked();
  35328. if (! incDecDragged)
  35329. return;
  35330. }
  35331. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  35332. : false))
  35333. || ((maximum - minimum) / sliderRegionSize < interval))
  35334. {
  35335. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  35336. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  35337. if (style == RotaryHorizontalDrag
  35338. || style == RotaryVerticalDrag
  35339. || style == IncDecButtons
  35340. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  35341. && ! snapsToMousePos))
  35342. {
  35343. const int mouseDiff = (style == RotaryHorizontalDrag
  35344. || style == LinearHorizontal
  35345. || style == LinearBar
  35346. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  35347. ? e.getDistanceFromDragStartX()
  35348. : -e.getDistanceFromDragStartY();
  35349. double newPos = valueToProportionOfLength (valueOnMouseDown)
  35350. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  35351. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  35352. if (style == IncDecButtons)
  35353. {
  35354. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  35355. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  35356. }
  35357. }
  35358. else
  35359. {
  35360. if (style == LinearVertical)
  35361. scaledMousePos = 1.0 - scaledMousePos;
  35362. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  35363. }
  35364. }
  35365. else
  35366. {
  35367. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  35368. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  35369. ? e.x - mouseXWhenLastDragged
  35370. : e.y - mouseYWhenLastDragged;
  35371. const double maxSpeed = jmax (200, sliderRegionSize);
  35372. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  35373. if (speed != 0)
  35374. {
  35375. speed = 0.2 * velocityModeSensitivity
  35376. * (1.0 + sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  35377. + jmax (0.0, (double) (speed - velocityModeThreshold))
  35378. / maxSpeed))));
  35379. if (mouseDiff < 0)
  35380. speed = -speed;
  35381. if (style == LinearVertical || style == RotaryVerticalDrag
  35382. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  35383. speed = -speed;
  35384. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  35385. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  35386. e.originalComponent->enableUnboundedMouseMovement (true, false);
  35387. mouseWasHidden = true;
  35388. }
  35389. }
  35390. }
  35391. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  35392. if (sliderBeingDragged == 0)
  35393. {
  35394. setValue (snapValue (valueWhenLastDragged, true),
  35395. ! sendChangeOnlyOnRelease, true);
  35396. }
  35397. else if (sliderBeingDragged == 1)
  35398. {
  35399. setMinValue (snapValue (valueWhenLastDragged, true),
  35400. ! sendChangeOnlyOnRelease, false);
  35401. if (e.mods.isShiftDown())
  35402. setMaxValue (getMinValue() + minMaxDiff, false);
  35403. else
  35404. minMaxDiff = valueMax - valueMin;
  35405. }
  35406. else
  35407. {
  35408. jassert (sliderBeingDragged == 2);
  35409. setMaxValue (snapValue (valueWhenLastDragged, true),
  35410. ! sendChangeOnlyOnRelease, false);
  35411. if (e.mods.isShiftDown())
  35412. setMinValue (getMaxValue() - minMaxDiff, false);
  35413. else
  35414. minMaxDiff = valueMax - valueMin;
  35415. }
  35416. mouseXWhenLastDragged = e.x;
  35417. mouseYWhenLastDragged = e.y;
  35418. }
  35419. }
  35420. void Slider::mouseDoubleClick (const MouseEvent&)
  35421. {
  35422. if (doubleClickToValue
  35423. && isEnabled()
  35424. && style != IncDecButtons
  35425. && minimum <= doubleClickReturnValue
  35426. && maximum >= doubleClickReturnValue)
  35427. {
  35428. sendDragStart();
  35429. setValue (doubleClickReturnValue, true, true);
  35430. sendDragEnd();
  35431. }
  35432. }
  35433. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  35434. {
  35435. if (scrollWheelEnabled && isEnabled())
  35436. {
  35437. if (maximum > minimum && ! isMouseButtonDownAnywhere())
  35438. {
  35439. if (valueBox != 0)
  35440. valueBox->hideEditor (false);
  35441. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  35442. const double currentPos = valueToProportionOfLength (currentValue);
  35443. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  35444. double delta = (newValue != currentValue)
  35445. ? jmax (fabs (newValue - currentValue), interval) : 0;
  35446. if (currentValue > newValue)
  35447. delta = -delta;
  35448. sendDragStart();
  35449. setValue (snapValue (currentValue + delta, false), true, true);
  35450. sendDragEnd();
  35451. }
  35452. }
  35453. else
  35454. {
  35455. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  35456. }
  35457. }
  35458. void SliderListener::sliderDragStarted (Slider*)
  35459. {
  35460. }
  35461. void SliderListener::sliderDragEnded (Slider*)
  35462. {
  35463. }
  35464. END_JUCE_NAMESPACE
  35465. /********* End of inlined file: juce_Slider.cpp *********/
  35466. /********* Start of inlined file: juce_TableHeaderComponent.cpp *********/
  35467. BEGIN_JUCE_NAMESPACE
  35468. class DragOverlayComp : public Component
  35469. {
  35470. public:
  35471. DragOverlayComp (Image* const image_)
  35472. : image (image_)
  35473. {
  35474. image->multiplyAllAlphas (0.8f);
  35475. setAlwaysOnTop (true);
  35476. }
  35477. ~DragOverlayComp()
  35478. {
  35479. delete image;
  35480. }
  35481. void paint (Graphics& g)
  35482. {
  35483. g.drawImageAt (image, 0, 0);
  35484. }
  35485. private:
  35486. Image* image;
  35487. DragOverlayComp (const DragOverlayComp&);
  35488. const DragOverlayComp& operator= (const DragOverlayComp&);
  35489. };
  35490. TableHeaderComponent::TableHeaderComponent()
  35491. : listeners (2),
  35492. dragOverlayComp (0),
  35493. columnsChanged (false),
  35494. columnsResized (false),
  35495. sortChanged (false),
  35496. menuActive (true),
  35497. stretchToFit (false),
  35498. columnIdBeingResized (0),
  35499. columnIdBeingDragged (0),
  35500. columnIdUnderMouse (0),
  35501. lastDeliberateWidth (0)
  35502. {
  35503. }
  35504. TableHeaderComponent::~TableHeaderComponent()
  35505. {
  35506. delete dragOverlayComp;
  35507. }
  35508. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  35509. {
  35510. menuActive = hasMenu;
  35511. }
  35512. bool TableHeaderComponent::isPopupMenuActive() const throw() { return menuActive; }
  35513. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const throw()
  35514. {
  35515. if (onlyCountVisibleColumns)
  35516. {
  35517. int num = 0;
  35518. for (int i = columns.size(); --i >= 0;)
  35519. if (columns.getUnchecked(i)->isVisible())
  35520. ++num;
  35521. return num;
  35522. }
  35523. else
  35524. {
  35525. return columns.size();
  35526. }
  35527. }
  35528. const String TableHeaderComponent::getColumnName (const int columnId) const throw()
  35529. {
  35530. const ColumnInfo* const ci = getInfoForId (columnId);
  35531. return ci != 0 ? ci->name : String::empty;
  35532. }
  35533. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  35534. {
  35535. ColumnInfo* const ci = getInfoForId (columnId);
  35536. if (ci != 0 && ci->name != newName)
  35537. {
  35538. ci->name = newName;
  35539. sendColumnsChanged();
  35540. }
  35541. }
  35542. void TableHeaderComponent::addColumn (const String& columnName,
  35543. const int columnId,
  35544. const int width,
  35545. const int minimumWidth,
  35546. const int maximumWidth,
  35547. const int propertyFlags,
  35548. const int insertIndex)
  35549. {
  35550. // can't have a duplicate or null ID!
  35551. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  35552. jassert (width > 0);
  35553. ColumnInfo* const ci = new ColumnInfo();
  35554. ci->name = columnName;
  35555. ci->id = columnId;
  35556. ci->width = width;
  35557. ci->lastDeliberateWidth = width;
  35558. ci->minimumWidth = minimumWidth;
  35559. ci->maximumWidth = maximumWidth;
  35560. if (ci->maximumWidth < 0)
  35561. ci->maximumWidth = INT_MAX;
  35562. jassert (ci->maximumWidth >= ci->minimumWidth);
  35563. ci->propertyFlags = propertyFlags;
  35564. columns.insert (insertIndex, ci);
  35565. sendColumnsChanged();
  35566. }
  35567. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  35568. {
  35569. const int index = getIndexOfColumnId (columnIdToRemove, false);
  35570. if (index >= 0)
  35571. {
  35572. columns.remove (index);
  35573. sortChanged = true;
  35574. sendColumnsChanged();
  35575. }
  35576. }
  35577. void TableHeaderComponent::removeAllColumns()
  35578. {
  35579. if (columns.size() > 0)
  35580. {
  35581. columns.clear();
  35582. sendColumnsChanged();
  35583. }
  35584. }
  35585. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  35586. {
  35587. const int currentIndex = getIndexOfColumnId (columnId, false);
  35588. newIndex = visibleIndexToTotalIndex (newIndex);
  35589. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  35590. {
  35591. columns.move (currentIndex, newIndex);
  35592. sendColumnsChanged();
  35593. }
  35594. }
  35595. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  35596. {
  35597. ColumnInfo* const ci = getInfoForId (columnId);
  35598. if (ci != 0 && ci->width != newWidth)
  35599. {
  35600. const int numColumns = getNumColumns (true);
  35601. ci->lastDeliberateWidth = ci->width
  35602. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  35603. if (stretchToFit)
  35604. {
  35605. const int index = getIndexOfColumnId (columnId, true) + 1;
  35606. if (((unsigned int) index) < (unsigned int) numColumns)
  35607. {
  35608. const int x = getColumnPosition (index).getX();
  35609. if (lastDeliberateWidth == 0)
  35610. lastDeliberateWidth = getTotalWidth();
  35611. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  35612. }
  35613. }
  35614. repaint();
  35615. columnsResized = true;
  35616. triggerAsyncUpdate();
  35617. }
  35618. }
  35619. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw()
  35620. {
  35621. int n = 0;
  35622. for (int i = 0; i < columns.size(); ++i)
  35623. {
  35624. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  35625. {
  35626. if (columns.getUnchecked(i)->id == columnId)
  35627. return n;
  35628. ++n;
  35629. }
  35630. }
  35631. return -1;
  35632. }
  35633. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw()
  35634. {
  35635. if (onlyCountVisibleColumns)
  35636. index = visibleIndexToTotalIndex (index);
  35637. const ColumnInfo* const ci = columns [index];
  35638. return (ci != 0) ? ci->id : 0;
  35639. }
  35640. const Rectangle TableHeaderComponent::getColumnPosition (const int index) const throw()
  35641. {
  35642. int x = 0, width = 0, n = 0;
  35643. for (int i = 0; i < columns.size(); ++i)
  35644. {
  35645. x += width;
  35646. if (columns.getUnchecked(i)->isVisible())
  35647. {
  35648. width = columns.getUnchecked(i)->width;
  35649. if (n++ == index)
  35650. break;
  35651. }
  35652. else
  35653. {
  35654. width = 0;
  35655. }
  35656. }
  35657. return Rectangle (x, 0, width, getHeight());
  35658. }
  35659. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const throw()
  35660. {
  35661. if (xToFind >= 0)
  35662. {
  35663. int x = 0;
  35664. for (int i = 0; i < columns.size(); ++i)
  35665. {
  35666. const ColumnInfo* const ci = columns.getUnchecked(i);
  35667. if (ci->isVisible())
  35668. {
  35669. x += ci->width;
  35670. if (xToFind < x)
  35671. return ci->id;
  35672. }
  35673. }
  35674. }
  35675. return 0;
  35676. }
  35677. int TableHeaderComponent::getTotalWidth() const throw()
  35678. {
  35679. int w = 0;
  35680. for (int i = columns.size(); --i >= 0;)
  35681. if (columns.getUnchecked(i)->isVisible())
  35682. w += columns.getUnchecked(i)->width;
  35683. return w;
  35684. }
  35685. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  35686. {
  35687. stretchToFit = shouldStretchToFit;
  35688. lastDeliberateWidth = getTotalWidth();
  35689. resized();
  35690. }
  35691. bool TableHeaderComponent::isStretchToFitActive() const throw()
  35692. {
  35693. return stretchToFit;
  35694. }
  35695. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  35696. {
  35697. if (stretchToFit && getWidth() > 0
  35698. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  35699. {
  35700. lastDeliberateWidth = targetTotalWidth;
  35701. resizeColumnsToFit (0, targetTotalWidth);
  35702. }
  35703. }
  35704. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  35705. {
  35706. targetTotalWidth = jmax (targetTotalWidth, 0);
  35707. StretchableObjectResizer sor;
  35708. int i;
  35709. for (i = firstColumnIndex; i < columns.size(); ++i)
  35710. {
  35711. ColumnInfo* const ci = columns.getUnchecked(i);
  35712. if (ci->isVisible())
  35713. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  35714. }
  35715. sor.resizeToFit (targetTotalWidth);
  35716. int visIndex = 0;
  35717. for (i = firstColumnIndex; i < columns.size(); ++i)
  35718. {
  35719. ColumnInfo* const ci = columns.getUnchecked(i);
  35720. if (ci->isVisible())
  35721. {
  35722. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  35723. (int) floor (sor.getItemSize (visIndex++)));
  35724. if (newWidth != ci->width)
  35725. {
  35726. ci->width = newWidth;
  35727. repaint();
  35728. columnsResized = true;
  35729. triggerAsyncUpdate();
  35730. }
  35731. }
  35732. }
  35733. }
  35734. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  35735. {
  35736. ColumnInfo* const ci = getInfoForId (columnId);
  35737. if (ci != 0 && shouldBeVisible != ci->isVisible())
  35738. {
  35739. if (shouldBeVisible)
  35740. ci->propertyFlags |= visible;
  35741. else
  35742. ci->propertyFlags &= ~visible;
  35743. sendColumnsChanged();
  35744. resized();
  35745. }
  35746. }
  35747. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  35748. {
  35749. const ColumnInfo* const ci = getInfoForId (columnId);
  35750. return ci != 0 && ci->isVisible();
  35751. }
  35752. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  35753. {
  35754. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  35755. {
  35756. for (int i = columns.size(); --i >= 0;)
  35757. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  35758. ColumnInfo* const ci = getInfoForId (columnId);
  35759. if (ci != 0)
  35760. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  35761. reSortTable();
  35762. }
  35763. }
  35764. int TableHeaderComponent::getSortColumnId() const throw()
  35765. {
  35766. for (int i = columns.size(); --i >= 0;)
  35767. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  35768. return columns.getUnchecked(i)->id;
  35769. return 0;
  35770. }
  35771. bool TableHeaderComponent::isSortedForwards() const throw()
  35772. {
  35773. for (int i = columns.size(); --i >= 0;)
  35774. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  35775. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  35776. return true;
  35777. }
  35778. void TableHeaderComponent::reSortTable()
  35779. {
  35780. sortChanged = true;
  35781. repaint();
  35782. triggerAsyncUpdate();
  35783. }
  35784. const String TableHeaderComponent::toString() const
  35785. {
  35786. String s;
  35787. XmlElement doc (T("TABLELAYOUT"));
  35788. doc.setAttribute (T("sortedCol"), getSortColumnId());
  35789. doc.setAttribute (T("sortForwards"), isSortedForwards());
  35790. for (int i = 0; i < columns.size(); ++i)
  35791. {
  35792. const ColumnInfo* const ci = columns.getUnchecked (i);
  35793. XmlElement* const e = new XmlElement (T("COLUMN"));
  35794. doc.addChildElement (e);
  35795. e->setAttribute (T("id"), ci->id);
  35796. e->setAttribute (T("visible"), ci->isVisible());
  35797. e->setAttribute (T("width"), ci->width);
  35798. }
  35799. return doc.createDocument (String::empty, true, false);
  35800. }
  35801. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  35802. {
  35803. XmlDocument doc (storedVersion);
  35804. XmlElement* const storedXml = doc.getDocumentElement();
  35805. int index = 0;
  35806. if (storedXml != 0 && storedXml->hasTagName (T("TABLELAYOUT")))
  35807. {
  35808. forEachXmlChildElement (*storedXml, col)
  35809. {
  35810. const int tabId = col->getIntAttribute (T("id"));
  35811. ColumnInfo* const ci = getInfoForId (tabId);
  35812. if (ci != 0)
  35813. {
  35814. columns.move (columns.indexOf (ci), index);
  35815. ci->width = col->getIntAttribute (T("width"));
  35816. setColumnVisible (tabId, col->getBoolAttribute (T("visible")));
  35817. }
  35818. ++index;
  35819. }
  35820. columnsResized = true;
  35821. sendColumnsChanged();
  35822. setSortColumnId (storedXml->getIntAttribute (T("sortedCol")),
  35823. storedXml->getBoolAttribute (T("sortForwards"), true));
  35824. }
  35825. delete storedXml;
  35826. }
  35827. void TableHeaderComponent::addListener (TableHeaderListener* const newListener) throw()
  35828. {
  35829. listeners.addIfNotAlreadyThere (newListener);
  35830. }
  35831. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove) throw()
  35832. {
  35833. listeners.removeValue (listenerToRemove);
  35834. }
  35835. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  35836. {
  35837. const ColumnInfo* const ci = getInfoForId (columnId);
  35838. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  35839. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  35840. }
  35841. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  35842. {
  35843. for (int i = 0; i < columns.size(); ++i)
  35844. {
  35845. const ColumnInfo* const ci = columns.getUnchecked(i);
  35846. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  35847. menu.addItem (ci->id, ci->name,
  35848. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  35849. isColumnVisible (ci->id));
  35850. }
  35851. }
  35852. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  35853. {
  35854. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  35855. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  35856. }
  35857. void TableHeaderComponent::paint (Graphics& g)
  35858. {
  35859. LookAndFeel& lf = getLookAndFeel();
  35860. lf.drawTableHeaderBackground (g, *this);
  35861. const Rectangle clip (g.getClipBounds());
  35862. int x = 0;
  35863. for (int i = 0; i < columns.size(); ++i)
  35864. {
  35865. const ColumnInfo* const ci = columns.getUnchecked(i);
  35866. if (ci->isVisible())
  35867. {
  35868. if (x + ci->width > clip.getX()
  35869. && (ci->id != columnIdBeingDragged
  35870. || dragOverlayComp == 0
  35871. || ! dragOverlayComp->isVisible()))
  35872. {
  35873. g.saveState();
  35874. g.setOrigin (x, 0);
  35875. g.reduceClipRegion (0, 0, ci->width, getHeight());
  35876. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  35877. ci->id == columnIdUnderMouse,
  35878. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  35879. ci->propertyFlags);
  35880. g.restoreState();
  35881. }
  35882. x += ci->width;
  35883. if (x >= clip.getRight())
  35884. break;
  35885. }
  35886. }
  35887. }
  35888. void TableHeaderComponent::resized()
  35889. {
  35890. }
  35891. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  35892. {
  35893. updateColumnUnderMouse (e.x, e.y);
  35894. }
  35895. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  35896. {
  35897. updateColumnUnderMouse (e.x, e.y);
  35898. }
  35899. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  35900. {
  35901. updateColumnUnderMouse (e.x, e.y);
  35902. }
  35903. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  35904. {
  35905. repaint();
  35906. columnIdBeingResized = 0;
  35907. columnIdBeingDragged = 0;
  35908. if (columnIdUnderMouse != 0)
  35909. {
  35910. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  35911. if (e.mods.isPopupMenu())
  35912. columnClicked (columnIdUnderMouse, e.mods);
  35913. }
  35914. if (menuActive && e.mods.isPopupMenu())
  35915. showColumnChooserMenu (columnIdUnderMouse);
  35916. }
  35917. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  35918. {
  35919. if (columnIdBeingResized == 0
  35920. && columnIdBeingDragged == 0
  35921. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  35922. {
  35923. deleteAndZero (dragOverlayComp);
  35924. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  35925. if (columnIdBeingResized != 0)
  35926. {
  35927. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  35928. initialColumnWidth = ci->width;
  35929. }
  35930. else
  35931. {
  35932. beginDrag (e);
  35933. }
  35934. }
  35935. if (columnIdBeingResized != 0)
  35936. {
  35937. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  35938. if (ci != 0)
  35939. {
  35940. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  35941. initialColumnWidth + e.getDistanceFromDragStartX());
  35942. if (stretchToFit)
  35943. {
  35944. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  35945. int minWidthOnRight = 0;
  35946. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  35947. if (columns.getUnchecked (i)->isVisible())
  35948. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  35949. const Rectangle currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  35950. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  35951. }
  35952. setColumnWidth (columnIdBeingResized, w);
  35953. }
  35954. }
  35955. else if (columnIdBeingDragged != 0)
  35956. {
  35957. if (e.y >= -50 && e.y < getHeight() + 50)
  35958. {
  35959. beginDrag (e);
  35960. if (dragOverlayComp != 0)
  35961. {
  35962. dragOverlayComp->setVisible (true);
  35963. dragOverlayComp->setBounds (jlimit (0,
  35964. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  35965. e.x - draggingColumnOffset),
  35966. 0,
  35967. dragOverlayComp->getWidth(),
  35968. getHeight());
  35969. for (int i = columns.size(); --i >= 0;)
  35970. {
  35971. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  35972. int newIndex = currentIndex;
  35973. if (newIndex > 0)
  35974. {
  35975. // if the previous column isn't draggable, we can't move our column
  35976. // past it, because that'd change the undraggable column's position..
  35977. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  35978. if ((previous->propertyFlags & draggable) != 0)
  35979. {
  35980. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  35981. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  35982. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  35983. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  35984. {
  35985. --newIndex;
  35986. }
  35987. }
  35988. }
  35989. if (newIndex < columns.size() - 1)
  35990. {
  35991. // if the next column isn't draggable, we can't move our column
  35992. // past it, because that'd change the undraggable column's position..
  35993. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  35994. if ((nextCol->propertyFlags & draggable) != 0)
  35995. {
  35996. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  35997. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  35998. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  35999. > abs (dragOverlayComp->getRight() - rightOfNext))
  36000. {
  36001. ++newIndex;
  36002. }
  36003. }
  36004. }
  36005. if (newIndex != currentIndex)
  36006. moveColumn (columnIdBeingDragged, newIndex);
  36007. else
  36008. break;
  36009. }
  36010. }
  36011. }
  36012. else
  36013. {
  36014. endDrag (draggingColumnOriginalIndex);
  36015. }
  36016. }
  36017. }
  36018. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  36019. {
  36020. if (columnIdBeingDragged == 0)
  36021. {
  36022. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  36023. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  36024. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  36025. {
  36026. columnIdBeingDragged = 0;
  36027. }
  36028. else
  36029. {
  36030. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  36031. const Rectangle columnRect (getColumnPosition (draggingColumnOriginalIndex));
  36032. const int temp = columnIdBeingDragged;
  36033. columnIdBeingDragged = 0;
  36034. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  36035. columnIdBeingDragged = temp;
  36036. dragOverlayComp->setBounds (columnRect);
  36037. for (int i = listeners.size(); --i >= 0;)
  36038. {
  36039. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  36040. i = jmin (i, listeners.size() - 1);
  36041. }
  36042. }
  36043. }
  36044. }
  36045. void TableHeaderComponent::endDrag (const int finalIndex)
  36046. {
  36047. if (columnIdBeingDragged != 0)
  36048. {
  36049. moveColumn (columnIdBeingDragged, finalIndex);
  36050. columnIdBeingDragged = 0;
  36051. repaint();
  36052. for (int i = listeners.size(); --i >= 0;)
  36053. {
  36054. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  36055. i = jmin (i, listeners.size() - 1);
  36056. }
  36057. }
  36058. }
  36059. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  36060. {
  36061. mouseDrag (e);
  36062. for (int i = columns.size(); --i >= 0;)
  36063. if (columns.getUnchecked (i)->isVisible())
  36064. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  36065. columnIdBeingResized = 0;
  36066. repaint();
  36067. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  36068. updateColumnUnderMouse (e.x, e.y);
  36069. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  36070. columnClicked (columnIdUnderMouse, e.mods);
  36071. deleteAndZero (dragOverlayComp);
  36072. }
  36073. const MouseCursor TableHeaderComponent::getMouseCursor()
  36074. {
  36075. int x, y;
  36076. getMouseXYRelative (x, y);
  36077. if (columnIdBeingResized != 0 || (getResizeDraggerAt (x) != 0 && ! isMouseButtonDown()))
  36078. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  36079. return Component::getMouseCursor();
  36080. }
  36081. bool TableHeaderComponent::ColumnInfo::isVisible() const throw()
  36082. {
  36083. return (propertyFlags & TableHeaderComponent::visible) != 0;
  36084. }
  36085. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const throw()
  36086. {
  36087. for (int i = columns.size(); --i >= 0;)
  36088. if (columns.getUnchecked(i)->id == id)
  36089. return columns.getUnchecked(i);
  36090. return 0;
  36091. }
  36092. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const throw()
  36093. {
  36094. int n = 0;
  36095. for (int i = 0; i < columns.size(); ++i)
  36096. {
  36097. if (columns.getUnchecked(i)->isVisible())
  36098. {
  36099. if (n == visibleIndex)
  36100. return i;
  36101. ++n;
  36102. }
  36103. }
  36104. return -1;
  36105. }
  36106. void TableHeaderComponent::sendColumnsChanged()
  36107. {
  36108. if (stretchToFit && lastDeliberateWidth > 0)
  36109. resizeAllColumnsToFit (lastDeliberateWidth);
  36110. repaint();
  36111. columnsChanged = true;
  36112. triggerAsyncUpdate();
  36113. }
  36114. void TableHeaderComponent::handleAsyncUpdate()
  36115. {
  36116. const bool changed = columnsChanged || sortChanged;
  36117. const bool sized = columnsResized || changed;
  36118. const bool sorted = sortChanged;
  36119. columnsChanged = false;
  36120. columnsResized = false;
  36121. sortChanged = false;
  36122. if (sorted)
  36123. {
  36124. for (int i = listeners.size(); --i >= 0;)
  36125. {
  36126. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  36127. i = jmin (i, listeners.size() - 1);
  36128. }
  36129. }
  36130. if (changed)
  36131. {
  36132. for (int i = listeners.size(); --i >= 0;)
  36133. {
  36134. listeners.getUnchecked(i)->tableColumnsChanged (this);
  36135. i = jmin (i, listeners.size() - 1);
  36136. }
  36137. }
  36138. if (sized)
  36139. {
  36140. for (int i = listeners.size(); --i >= 0;)
  36141. {
  36142. listeners.getUnchecked(i)->tableColumnsResized (this);
  36143. i = jmin (i, listeners.size() - 1);
  36144. }
  36145. }
  36146. }
  36147. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const throw()
  36148. {
  36149. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  36150. {
  36151. const int draggableDistance = 3;
  36152. int x = 0;
  36153. for (int i = 0; i < columns.size(); ++i)
  36154. {
  36155. const ColumnInfo* const ci = columns.getUnchecked(i);
  36156. if (ci->isVisible())
  36157. {
  36158. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  36159. && (ci->propertyFlags & resizable) != 0)
  36160. return ci->id;
  36161. x += ci->width;
  36162. }
  36163. }
  36164. }
  36165. return 0;
  36166. }
  36167. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  36168. {
  36169. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  36170. ? getColumnIdAtX (x) : 0;
  36171. if (newCol != columnIdUnderMouse)
  36172. {
  36173. columnIdUnderMouse = newCol;
  36174. repaint();
  36175. }
  36176. }
  36177. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  36178. {
  36179. PopupMenu m;
  36180. addMenuItems (m, columnIdClicked);
  36181. if (m.getNumItems() > 0)
  36182. {
  36183. const int result = m.show();
  36184. if (result != 0)
  36185. reactToMenuItem (result, columnIdClicked);
  36186. }
  36187. }
  36188. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  36189. {
  36190. }
  36191. END_JUCE_NAMESPACE
  36192. /********* End of inlined file: juce_TableHeaderComponent.cpp *********/
  36193. /********* Start of inlined file: juce_TableListBox.cpp *********/
  36194. BEGIN_JUCE_NAMESPACE
  36195. static const tchar* const tableColumnPropertyTag = T("_tableColumnID");
  36196. class TableListRowComp : public Component
  36197. {
  36198. public:
  36199. TableListRowComp (TableListBox& owner_)
  36200. : owner (owner_),
  36201. row (-1),
  36202. isSelected (false)
  36203. {
  36204. }
  36205. ~TableListRowComp()
  36206. {
  36207. deleteAllChildren();
  36208. }
  36209. void paint (Graphics& g)
  36210. {
  36211. TableListBoxModel* const model = owner.getModel();
  36212. if (model != 0)
  36213. {
  36214. const TableHeaderComponent* const header = owner.getHeader();
  36215. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  36216. const int numColumns = header->getNumColumns (true);
  36217. for (int i = 0; i < numColumns; ++i)
  36218. {
  36219. if (! columnsWithComponents [i])
  36220. {
  36221. const int columnId = header->getColumnIdOfIndex (i, true);
  36222. Rectangle columnRect (header->getColumnPosition (i));
  36223. columnRect.setSize (columnRect.getWidth(), getHeight());
  36224. g.saveState();
  36225. g.reduceClipRegion (columnRect);
  36226. g.setOrigin (columnRect.getX(), 0);
  36227. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  36228. g.restoreState();
  36229. }
  36230. }
  36231. }
  36232. }
  36233. void update (const int newRow, const bool isNowSelected)
  36234. {
  36235. if (newRow != row || isNowSelected != isSelected)
  36236. {
  36237. row = newRow;
  36238. isSelected = isNowSelected;
  36239. repaint();
  36240. }
  36241. if (row < owner.getNumRows())
  36242. {
  36243. jassert (row >= 0);
  36244. const tchar* const tagPropertyName = T("_tableLastUseNum");
  36245. const int newTag = Random::getSystemRandom().nextInt();
  36246. const TableHeaderComponent* const header = owner.getHeader();
  36247. const int numColumns = header->getNumColumns (true);
  36248. int i;
  36249. columnsWithComponents.clear();
  36250. if (owner.getModel() != 0)
  36251. {
  36252. for (i = 0; i < numColumns; ++i)
  36253. {
  36254. const int columnId = header->getColumnIdOfIndex (i, true);
  36255. Component* const newComp
  36256. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  36257. findChildComponentForColumn (columnId));
  36258. if (newComp != 0)
  36259. {
  36260. addAndMakeVisible (newComp);
  36261. newComp->setComponentProperty (tagPropertyName, newTag);
  36262. newComp->setComponentProperty (tableColumnPropertyTag, columnId);
  36263. const Rectangle columnRect (header->getColumnPosition (i));
  36264. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  36265. columnsWithComponents.setBit (i);
  36266. }
  36267. }
  36268. }
  36269. for (i = getNumChildComponents(); --i >= 0;)
  36270. {
  36271. Component* const c = getChildComponent (i);
  36272. if (c->getComponentPropertyInt (tagPropertyName, false, 0) != newTag)
  36273. delete c;
  36274. }
  36275. }
  36276. else
  36277. {
  36278. columnsWithComponents.clear();
  36279. deleteAllChildren();
  36280. }
  36281. }
  36282. void resized()
  36283. {
  36284. for (int i = getNumChildComponents(); --i >= 0;)
  36285. {
  36286. Component* const c = getChildComponent (i);
  36287. const int columnId = c->getComponentPropertyInt (tableColumnPropertyTag, false, 0);
  36288. if (columnId != 0)
  36289. {
  36290. const Rectangle columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  36291. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  36292. }
  36293. }
  36294. }
  36295. void mouseDown (const MouseEvent& e)
  36296. {
  36297. isDragging = false;
  36298. selectRowOnMouseUp = false;
  36299. if (isEnabled())
  36300. {
  36301. if (! isSelected)
  36302. {
  36303. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  36304. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  36305. if (columnId != 0 && owner.getModel() != 0)
  36306. owner.getModel()->cellClicked (row, columnId, e);
  36307. }
  36308. else
  36309. {
  36310. selectRowOnMouseUp = true;
  36311. }
  36312. }
  36313. }
  36314. void mouseDrag (const MouseEvent& e)
  36315. {
  36316. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  36317. {
  36318. const SparseSet <int> selectedRows (owner.getSelectedRows());
  36319. if (selectedRows.size() > 0)
  36320. {
  36321. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  36322. if (dragDescription.isNotEmpty())
  36323. {
  36324. isDragging = true;
  36325. DragAndDropContainer* const dragContainer
  36326. = DragAndDropContainer::findParentDragContainerFor (this);
  36327. if (dragContainer != 0)
  36328. {
  36329. Image* dragImage = owner.createSnapshotOfSelectedRows();
  36330. dragImage->multiplyAllAlphas (0.6f);
  36331. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  36332. }
  36333. else
  36334. {
  36335. // to be able to do a drag-and-drop operation, the listbox needs to
  36336. // be inside a component which is also a DragAndDropContainer.
  36337. jassertfalse
  36338. }
  36339. }
  36340. }
  36341. }
  36342. }
  36343. void mouseUp (const MouseEvent& e)
  36344. {
  36345. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  36346. {
  36347. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  36348. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  36349. if (columnId != 0 && owner.getModel() != 0)
  36350. owner.getModel()->cellClicked (row, columnId, e);
  36351. }
  36352. }
  36353. void mouseDoubleClick (const MouseEvent& e)
  36354. {
  36355. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  36356. if (columnId != 0 && owner.getModel() != 0)
  36357. owner.getModel()->cellDoubleClicked (row, columnId, e);
  36358. }
  36359. juce_UseDebuggingNewOperator
  36360. private:
  36361. TableListBox& owner;
  36362. int row;
  36363. bool isSelected, isDragging, selectRowOnMouseUp;
  36364. BitArray columnsWithComponents;
  36365. Component* findChildComponentForColumn (const int columnId) const
  36366. {
  36367. for (int i = getNumChildComponents(); --i >= 0;)
  36368. {
  36369. Component* const c = getChildComponent (i);
  36370. if (c->getComponentPropertyInt (tableColumnPropertyTag, false, 0) == columnId)
  36371. return c;
  36372. }
  36373. return 0;
  36374. }
  36375. TableListRowComp (const TableListRowComp&);
  36376. const TableListRowComp& operator= (const TableListRowComp&);
  36377. };
  36378. class TableListBoxHeader : public TableHeaderComponent
  36379. {
  36380. public:
  36381. TableListBoxHeader (TableListBox& owner_)
  36382. : owner (owner_)
  36383. {
  36384. }
  36385. ~TableListBoxHeader()
  36386. {
  36387. }
  36388. void addMenuItems (PopupMenu& menu, const int columnIdClicked)
  36389. {
  36390. if (owner.isAutoSizeMenuOptionShown())
  36391. {
  36392. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  36393. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  36394. menu.addSeparator();
  36395. }
  36396. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  36397. }
  36398. void reactToMenuItem (const int menuReturnId, const int columnIdClicked)
  36399. {
  36400. if (menuReturnId == 0xf836743)
  36401. {
  36402. owner.autoSizeColumn (columnIdClicked);
  36403. }
  36404. else if (menuReturnId == 0xf836744)
  36405. {
  36406. owner.autoSizeAllColumns();
  36407. }
  36408. else
  36409. {
  36410. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  36411. }
  36412. }
  36413. juce_UseDebuggingNewOperator
  36414. private:
  36415. TableListBox& owner;
  36416. TableListBoxHeader (const TableListBoxHeader&);
  36417. const TableListBoxHeader& operator= (const TableListBoxHeader&);
  36418. };
  36419. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  36420. : ListBox (name, 0),
  36421. model (model_),
  36422. autoSizeOptionsShown (true)
  36423. {
  36424. ListBox::model = this;
  36425. header = new TableListBoxHeader (*this);
  36426. header->setSize (100, 28);
  36427. header->addListener (this);
  36428. setHeaderComponent (header);
  36429. }
  36430. TableListBox::~TableListBox()
  36431. {
  36432. deleteAllChildren();
  36433. }
  36434. void TableListBox::setModel (TableListBoxModel* const newModel)
  36435. {
  36436. if (model != newModel)
  36437. {
  36438. model = newModel;
  36439. updateContent();
  36440. }
  36441. }
  36442. int TableListBox::getHeaderHeight() const throw()
  36443. {
  36444. return header->getHeight();
  36445. }
  36446. void TableListBox::setHeaderHeight (const int newHeight)
  36447. {
  36448. header->setSize (header->getWidth(), newHeight);
  36449. resized();
  36450. }
  36451. void TableListBox::autoSizeColumn (const int columnId)
  36452. {
  36453. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  36454. if (width > 0)
  36455. header->setColumnWidth (columnId, width);
  36456. }
  36457. void TableListBox::autoSizeAllColumns()
  36458. {
  36459. for (int i = 0; i < header->getNumColumns (true); ++i)
  36460. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  36461. }
  36462. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  36463. {
  36464. autoSizeOptionsShown = shouldBeShown;
  36465. }
  36466. bool TableListBox::isAutoSizeMenuOptionShown() const throw()
  36467. {
  36468. return autoSizeOptionsShown;
  36469. }
  36470. const Rectangle TableListBox::getCellPosition (const int columnId,
  36471. const int rowNumber,
  36472. const bool relativeToComponentTopLeft) const
  36473. {
  36474. Rectangle headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  36475. if (relativeToComponentTopLeft)
  36476. headerCell.translate (header->getX(), 0);
  36477. const Rectangle row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  36478. return Rectangle (headerCell.getX(), row.getY(),
  36479. headerCell.getWidth(), row.getHeight());
  36480. }
  36481. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  36482. {
  36483. ScrollBar* const scrollbar = getHorizontalScrollBar();
  36484. if (scrollbar != 0)
  36485. {
  36486. const Rectangle pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  36487. double x = scrollbar->getCurrentRangeStart();
  36488. const double w = scrollbar->getCurrentRangeSize();
  36489. if (pos.getX() < x)
  36490. x = pos.getX();
  36491. else if (pos.getRight() > x + w)
  36492. x += jmax (0.0, pos.getRight() - (x + w));
  36493. scrollbar->setCurrentRangeStart (x);
  36494. }
  36495. }
  36496. int TableListBox::getNumRows()
  36497. {
  36498. return model != 0 ? model->getNumRows() : 0;
  36499. }
  36500. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  36501. {
  36502. }
  36503. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate)
  36504. {
  36505. if (existingComponentToUpdate == 0)
  36506. existingComponentToUpdate = new TableListRowComp (*this);
  36507. ((TableListRowComp*) existingComponentToUpdate)->update (rowNumber, isRowSelected);
  36508. return existingComponentToUpdate;
  36509. }
  36510. void TableListBox::selectedRowsChanged (int row)
  36511. {
  36512. if (model != 0)
  36513. model->selectedRowsChanged (row);
  36514. }
  36515. void TableListBox::deleteKeyPressed (int row)
  36516. {
  36517. if (model != 0)
  36518. model->deleteKeyPressed (row);
  36519. }
  36520. void TableListBox::returnKeyPressed (int row)
  36521. {
  36522. if (model != 0)
  36523. model->returnKeyPressed (row);
  36524. }
  36525. void TableListBox::backgroundClicked()
  36526. {
  36527. if (model != 0)
  36528. model->backgroundClicked();
  36529. }
  36530. void TableListBox::listWasScrolled()
  36531. {
  36532. if (model != 0)
  36533. model->listWasScrolled();
  36534. }
  36535. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  36536. {
  36537. setMinimumContentWidth (header->getTotalWidth());
  36538. repaint();
  36539. updateColumnComponents();
  36540. }
  36541. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  36542. {
  36543. setMinimumContentWidth (header->getTotalWidth());
  36544. repaint();
  36545. updateColumnComponents();
  36546. }
  36547. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  36548. {
  36549. if (model != 0)
  36550. model->sortOrderChanged (header->getSortColumnId(),
  36551. header->isSortedForwards());
  36552. }
  36553. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  36554. {
  36555. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  36556. repaint();
  36557. }
  36558. void TableListBox::resized()
  36559. {
  36560. ListBox::resized();
  36561. header->resizeAllColumnsToFit (getVisibleContentWidth());
  36562. setMinimumContentWidth (header->getTotalWidth());
  36563. }
  36564. void TableListBox::updateColumnComponents() const
  36565. {
  36566. const int firstRow = getRowContainingPosition (0, 0);
  36567. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  36568. {
  36569. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  36570. if (rowComp != 0)
  36571. rowComp->resized();
  36572. }
  36573. }
  36574. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  36575. {
  36576. }
  36577. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  36578. {
  36579. }
  36580. void TableListBoxModel::backgroundClicked()
  36581. {
  36582. }
  36583. void TableListBoxModel::sortOrderChanged (int, const bool)
  36584. {
  36585. }
  36586. int TableListBoxModel::getColumnAutoSizeWidth (int)
  36587. {
  36588. return 0;
  36589. }
  36590. void TableListBoxModel::selectedRowsChanged (int)
  36591. {
  36592. }
  36593. void TableListBoxModel::deleteKeyPressed (int)
  36594. {
  36595. }
  36596. void TableListBoxModel::returnKeyPressed (int)
  36597. {
  36598. }
  36599. void TableListBoxModel::listWasScrolled()
  36600. {
  36601. }
  36602. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  36603. {
  36604. return String::empty;
  36605. }
  36606. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  36607. {
  36608. (void) existingComponentToUpdate;
  36609. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  36610. return 0;
  36611. }
  36612. END_JUCE_NAMESPACE
  36613. /********* End of inlined file: juce_TableListBox.cpp *********/
  36614. /********* Start of inlined file: juce_TextEditor.cpp *********/
  36615. BEGIN_JUCE_NAMESPACE
  36616. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  36617. // a word or space that can't be broken down any further
  36618. struct TextAtom
  36619. {
  36620. String atomText;
  36621. float width;
  36622. uint16 numChars;
  36623. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (atomText[0]); }
  36624. bool isNewLine() const throw() { return atomText[0] == T('\r') || atomText[0] == T('\n'); }
  36625. const String getText (const tchar passwordCharacter) const throw()
  36626. {
  36627. if (passwordCharacter == 0)
  36628. return atomText;
  36629. else
  36630. return String::repeatedString (String::charToString (passwordCharacter),
  36631. atomText.length());
  36632. }
  36633. const String getTrimmedText (const tchar passwordCharacter) const throw()
  36634. {
  36635. if (passwordCharacter == 0)
  36636. return atomText.substring (0, numChars);
  36637. else if (isNewLine())
  36638. return String::empty;
  36639. else
  36640. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  36641. }
  36642. };
  36643. // a run of text with a single font and colour
  36644. class UniformTextSection
  36645. {
  36646. public:
  36647. UniformTextSection (const String& text,
  36648. const Font& font_,
  36649. const Colour& colour_,
  36650. const tchar passwordCharacter) throw()
  36651. : font (font_),
  36652. colour (colour_),
  36653. atoms (64)
  36654. {
  36655. initialiseAtoms (text, passwordCharacter);
  36656. }
  36657. UniformTextSection (const UniformTextSection& other) throw()
  36658. : font (other.font),
  36659. colour (other.colour),
  36660. atoms (64)
  36661. {
  36662. for (int i = 0; i < other.atoms.size(); ++i)
  36663. atoms.add (new TextAtom (*(const TextAtom*) other.atoms.getUnchecked(i)));
  36664. }
  36665. ~UniformTextSection() throw()
  36666. {
  36667. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  36668. }
  36669. void clear() throw()
  36670. {
  36671. for (int i = atoms.size(); --i >= 0;)
  36672. {
  36673. TextAtom* const atom = getAtom(i);
  36674. delete atom;
  36675. }
  36676. atoms.clear();
  36677. }
  36678. int getNumAtoms() const throw()
  36679. {
  36680. return atoms.size();
  36681. }
  36682. TextAtom* getAtom (const int index) const throw()
  36683. {
  36684. return (TextAtom*) atoms.getUnchecked (index);
  36685. }
  36686. void append (const UniformTextSection& other, const tchar passwordCharacter) throw()
  36687. {
  36688. if (other.atoms.size() > 0)
  36689. {
  36690. TextAtom* const lastAtom = (TextAtom*) atoms.getLast();
  36691. int i = 0;
  36692. if (lastAtom != 0)
  36693. {
  36694. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  36695. {
  36696. TextAtom* const first = other.getAtom(0);
  36697. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  36698. {
  36699. lastAtom->atomText += first->atomText;
  36700. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  36701. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  36702. delete first;
  36703. ++i;
  36704. }
  36705. }
  36706. }
  36707. while (i < other.atoms.size())
  36708. {
  36709. atoms.add (other.getAtom(i));
  36710. ++i;
  36711. }
  36712. }
  36713. }
  36714. UniformTextSection* split (const int indexToBreakAt,
  36715. const tchar passwordCharacter) throw()
  36716. {
  36717. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  36718. font, colour,
  36719. passwordCharacter);
  36720. int index = 0;
  36721. for (int i = 0; i < atoms.size(); ++i)
  36722. {
  36723. TextAtom* const atom = getAtom(i);
  36724. const int nextIndex = index + atom->numChars;
  36725. if (index == indexToBreakAt)
  36726. {
  36727. int j;
  36728. for (j = i; j < atoms.size(); ++j)
  36729. section2->atoms.add (getAtom (j));
  36730. for (j = atoms.size(); --j >= i;)
  36731. atoms.remove (j);
  36732. break;
  36733. }
  36734. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  36735. {
  36736. TextAtom* const secondAtom = new TextAtom();
  36737. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  36738. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  36739. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  36740. section2->atoms.add (secondAtom);
  36741. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  36742. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  36743. atom->numChars = (uint16) (indexToBreakAt - index);
  36744. int j;
  36745. for (j = i + 1; j < atoms.size(); ++j)
  36746. section2->atoms.add (getAtom (j));
  36747. for (j = atoms.size(); --j > i;)
  36748. atoms.remove (j);
  36749. break;
  36750. }
  36751. index = nextIndex;
  36752. }
  36753. return section2;
  36754. }
  36755. const String getAllText() const throw()
  36756. {
  36757. String s;
  36758. s.preallocateStorage (getTotalLength());
  36759. tchar* endOfString = (tchar*) &(s[0]);
  36760. for (int i = 0; i < atoms.size(); ++i)
  36761. {
  36762. const TextAtom* const atom = getAtom(i);
  36763. memcpy (endOfString, &(atom->atomText[0]), atom->numChars * sizeof (tchar));
  36764. endOfString += atom->numChars;
  36765. }
  36766. *endOfString = 0;
  36767. jassert ((endOfString - (tchar*) &(s[0])) <= getTotalLength());
  36768. return s;
  36769. }
  36770. const String getTextSubstring (const int startCharacter,
  36771. const int endCharacter) const throw()
  36772. {
  36773. int index = 0;
  36774. int totalLen = 0;
  36775. int i;
  36776. for (i = 0; i < atoms.size(); ++i)
  36777. {
  36778. const TextAtom* const atom = getAtom (i);
  36779. const int nextIndex = index + atom->numChars;
  36780. if (startCharacter < nextIndex)
  36781. {
  36782. if (endCharacter <= index)
  36783. break;
  36784. const int start = jmax (0, startCharacter - index);
  36785. const int end = jmin (endCharacter - index, atom->numChars);
  36786. jassert (end >= start);
  36787. totalLen += end - start;
  36788. }
  36789. index = nextIndex;
  36790. }
  36791. String s;
  36792. s.preallocateStorage (totalLen + 1);
  36793. tchar* psz = (tchar*) (const tchar*) s;
  36794. index = 0;
  36795. for (i = 0; i < atoms.size(); ++i)
  36796. {
  36797. const TextAtom* const atom = getAtom (i);
  36798. const int nextIndex = index + atom->numChars;
  36799. if (startCharacter < nextIndex)
  36800. {
  36801. if (endCharacter <= index)
  36802. break;
  36803. const int start = jmax (0, startCharacter - index);
  36804. const int len = jmin (endCharacter - index, atom->numChars) - start;
  36805. memcpy (psz, ((const tchar*) atom->atomText) + start, len * sizeof (tchar));
  36806. psz += len;
  36807. *psz = 0;
  36808. }
  36809. index = nextIndex;
  36810. }
  36811. return s;
  36812. }
  36813. int getTotalLength() const throw()
  36814. {
  36815. int c = 0;
  36816. for (int i = atoms.size(); --i >= 0;)
  36817. c += getAtom(i)->numChars;
  36818. return c;
  36819. }
  36820. void setFont (const Font& newFont,
  36821. const tchar passwordCharacter) throw()
  36822. {
  36823. if (font != newFont)
  36824. {
  36825. font = newFont;
  36826. for (int i = atoms.size(); --i >= 0;)
  36827. {
  36828. TextAtom* const atom = (TextAtom*) atoms.getUnchecked(i);
  36829. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  36830. }
  36831. }
  36832. }
  36833. juce_UseDebuggingNewOperator
  36834. Font font;
  36835. Colour colour;
  36836. private:
  36837. VoidArray atoms;
  36838. void initialiseAtoms (const String& textToParse,
  36839. const tchar passwordCharacter) throw()
  36840. {
  36841. int i = 0;
  36842. const int len = textToParse.length();
  36843. const tchar* const text = (const tchar*) textToParse;
  36844. while (i < len)
  36845. {
  36846. int start = i;
  36847. // create a whitespace atom unless it starts with non-ws
  36848. if (CharacterFunctions::isWhitespace (text[i])
  36849. && text[i] != T('\r')
  36850. && text[i] != T('\n'))
  36851. {
  36852. while (i < len
  36853. && CharacterFunctions::isWhitespace (text[i])
  36854. && text[i] != T('\r')
  36855. && text[i] != T('\n'))
  36856. {
  36857. ++i;
  36858. }
  36859. }
  36860. else
  36861. {
  36862. if (text[i] == T('\r'))
  36863. {
  36864. ++i;
  36865. if ((i < len) && (text[i] == T('\n')))
  36866. {
  36867. ++start;
  36868. ++i;
  36869. }
  36870. }
  36871. else if (text[i] == T('\n'))
  36872. {
  36873. ++i;
  36874. }
  36875. else
  36876. {
  36877. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  36878. ++i;
  36879. }
  36880. }
  36881. TextAtom* const atom = new TextAtom();
  36882. atom->atomText = String (text + start, i - start);
  36883. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  36884. atom->numChars = (uint16) (i - start);
  36885. atoms.add (atom);
  36886. }
  36887. }
  36888. const UniformTextSection& operator= (const UniformTextSection& other);
  36889. };
  36890. class TextEditorIterator
  36891. {
  36892. public:
  36893. TextEditorIterator (const VoidArray& sections_,
  36894. const float wordWrapWidth_,
  36895. const tchar passwordCharacter_) throw()
  36896. : indexInText (0),
  36897. lineY (0),
  36898. lineHeight (0),
  36899. maxDescent (0),
  36900. atomX (0),
  36901. atomRight (0),
  36902. atom (0),
  36903. currentSection (0),
  36904. sections (sections_),
  36905. sectionIndex (0),
  36906. atomIndex (0),
  36907. wordWrapWidth (wordWrapWidth_),
  36908. passwordCharacter (passwordCharacter_)
  36909. {
  36910. jassert (wordWrapWidth_ > 0);
  36911. if (sections.size() > 0)
  36912. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  36913. if (currentSection != 0)
  36914. {
  36915. lineHeight = currentSection->font.getHeight();
  36916. maxDescent = currentSection->font.getDescent();
  36917. }
  36918. }
  36919. TextEditorIterator (const TextEditorIterator& other) throw()
  36920. : indexInText (other.indexInText),
  36921. lineY (other.lineY),
  36922. lineHeight (other.lineHeight),
  36923. maxDescent (other.maxDescent),
  36924. atomX (other.atomX),
  36925. atomRight (other.atomRight),
  36926. atom (other.atom),
  36927. currentSection (other.currentSection),
  36928. sections (other.sections),
  36929. sectionIndex (other.sectionIndex),
  36930. atomIndex (other.atomIndex),
  36931. wordWrapWidth (other.wordWrapWidth),
  36932. passwordCharacter (other.passwordCharacter),
  36933. tempAtom (other.tempAtom)
  36934. {
  36935. }
  36936. ~TextEditorIterator() throw()
  36937. {
  36938. }
  36939. bool next() throw()
  36940. {
  36941. if (atom == &tempAtom)
  36942. {
  36943. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  36944. if (numRemaining > 0)
  36945. {
  36946. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  36947. atomX = 0;
  36948. if (tempAtom.numChars > 0)
  36949. lineY += lineHeight;
  36950. indexInText += tempAtom.numChars;
  36951. GlyphArrangement g;
  36952. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  36953. int split;
  36954. for (split = 0; split < g.getNumGlyphs(); ++split)
  36955. if (SHOULD_WRAP (g.getGlyph (split).getRight(), wordWrapWidth))
  36956. break;
  36957. if (split > 0 && split <= numRemaining)
  36958. {
  36959. tempAtom.numChars = (uint16) split;
  36960. tempAtom.width = g.getGlyph (split - 1).getRight();
  36961. atomRight = atomX + tempAtom.width;
  36962. return true;
  36963. }
  36964. }
  36965. }
  36966. bool forceNewLine = false;
  36967. if (sectionIndex >= sections.size())
  36968. {
  36969. moveToEndOfLastAtom();
  36970. return false;
  36971. }
  36972. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  36973. {
  36974. if (atomIndex >= currentSection->getNumAtoms())
  36975. {
  36976. if (++sectionIndex >= sections.size())
  36977. {
  36978. moveToEndOfLastAtom();
  36979. return false;
  36980. }
  36981. atomIndex = 0;
  36982. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  36983. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  36984. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  36985. }
  36986. else
  36987. {
  36988. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  36989. if (! lastAtom->isWhitespace())
  36990. {
  36991. // handle the case where the last atom in a section is actually part of the same
  36992. // word as the first atom of the next section...
  36993. float right = atomRight + lastAtom->width;
  36994. float lineHeight2 = lineHeight;
  36995. float maxDescent2 = maxDescent;
  36996. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  36997. {
  36998. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked (section);
  36999. if (s->getNumAtoms() == 0)
  37000. break;
  37001. const TextAtom* const nextAtom = s->getAtom (0);
  37002. if (nextAtom->isWhitespace())
  37003. break;
  37004. right += nextAtom->width;
  37005. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  37006. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  37007. if (SHOULD_WRAP (right, wordWrapWidth))
  37008. {
  37009. lineHeight = lineHeight2;
  37010. maxDescent = maxDescent2;
  37011. forceNewLine = true;
  37012. break;
  37013. }
  37014. if (s->getNumAtoms() > 1)
  37015. break;
  37016. }
  37017. }
  37018. }
  37019. }
  37020. if (atom != 0)
  37021. {
  37022. atomX = atomRight;
  37023. indexInText += atom->numChars;
  37024. if (atom->isNewLine())
  37025. {
  37026. atomX = 0;
  37027. lineY += lineHeight;
  37028. }
  37029. }
  37030. atom = currentSection->getAtom (atomIndex);
  37031. atomRight = atomX + atom->width;
  37032. ++atomIndex;
  37033. if (SHOULD_WRAP (atomRight, wordWrapWidth) || forceNewLine)
  37034. {
  37035. if (atom->isWhitespace())
  37036. {
  37037. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  37038. atomRight = jmin (atomRight, wordWrapWidth);
  37039. }
  37040. else
  37041. {
  37042. return wrapCurrentAtom();
  37043. }
  37044. }
  37045. return true;
  37046. }
  37047. bool wrapCurrentAtom() throw()
  37048. {
  37049. atomRight = atom->width;
  37050. if (SHOULD_WRAP (atomRight, wordWrapWidth)) // atom too big to fit on a line, so break it up..
  37051. {
  37052. tempAtom = *atom;
  37053. tempAtom.width = 0;
  37054. tempAtom.numChars = 0;
  37055. atom = &tempAtom;
  37056. if (atomX > 0)
  37057. {
  37058. atomX = 0;
  37059. lineY += lineHeight;
  37060. }
  37061. return next();
  37062. }
  37063. atomX = 0;
  37064. lineY += lineHeight;
  37065. return true;
  37066. }
  37067. void draw (Graphics& g, const UniformTextSection*& lastSection) const throw()
  37068. {
  37069. if (passwordCharacter != 0 || ! atom->isWhitespace())
  37070. {
  37071. if (lastSection != currentSection)
  37072. {
  37073. lastSection = currentSection;
  37074. g.setColour (currentSection->colour);
  37075. g.setFont (currentSection->font);
  37076. }
  37077. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  37078. GlyphArrangement ga;
  37079. ga.addLineOfText (currentSection->font,
  37080. atom->getTrimmedText (passwordCharacter),
  37081. atomX,
  37082. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  37083. ga.draw (g);
  37084. }
  37085. }
  37086. void drawSelection (Graphics& g,
  37087. const int selectionStart,
  37088. const int selectionEnd) const throw()
  37089. {
  37090. const int startX = roundFloatToInt (indexToX (selectionStart));
  37091. const int endX = roundFloatToInt (indexToX (selectionEnd));
  37092. const int y = roundFloatToInt (lineY);
  37093. const int nextY = roundFloatToInt (lineY + lineHeight);
  37094. g.fillRect (startX, y, endX - startX, nextY - y);
  37095. }
  37096. void drawSelectedText (Graphics& g,
  37097. const int selectionStart,
  37098. const int selectionEnd,
  37099. const Colour& selectedTextColour) const throw()
  37100. {
  37101. if (passwordCharacter != 0 || ! atom->isWhitespace())
  37102. {
  37103. GlyphArrangement ga;
  37104. ga.addLineOfText (currentSection->font,
  37105. atom->getTrimmedText (passwordCharacter),
  37106. atomX,
  37107. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  37108. if (selectionEnd < indexInText + atom->numChars)
  37109. {
  37110. GlyphArrangement ga2 (ga);
  37111. ga2.removeRangeOfGlyphs (0, selectionEnd - indexInText);
  37112. ga.removeRangeOfGlyphs (selectionEnd - indexInText, -1);
  37113. g.setColour (currentSection->colour);
  37114. ga2.draw (g);
  37115. }
  37116. if (selectionStart > indexInText)
  37117. {
  37118. GlyphArrangement ga2 (ga);
  37119. ga2.removeRangeOfGlyphs (selectionStart - indexInText, -1);
  37120. ga.removeRangeOfGlyphs (0, selectionStart - indexInText);
  37121. g.setColour (currentSection->colour);
  37122. ga2.draw (g);
  37123. }
  37124. g.setColour (selectedTextColour);
  37125. ga.draw (g);
  37126. }
  37127. }
  37128. float indexToX (const int indexToFind) const throw()
  37129. {
  37130. if (indexToFind <= indexInText)
  37131. return atomX;
  37132. if (indexToFind >= indexInText + atom->numChars)
  37133. return atomRight;
  37134. GlyphArrangement g;
  37135. g.addLineOfText (currentSection->font,
  37136. atom->getText (passwordCharacter),
  37137. atomX, 0.0f);
  37138. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  37139. }
  37140. int xToIndex (const float xToFind) const throw()
  37141. {
  37142. if (xToFind <= atomX || atom->isNewLine())
  37143. return indexInText;
  37144. if (xToFind >= atomRight)
  37145. return indexInText + atom->numChars;
  37146. GlyphArrangement g;
  37147. g.addLineOfText (currentSection->font,
  37148. atom->getText (passwordCharacter),
  37149. atomX, 0.0f);
  37150. int j;
  37151. for (j = 0; j < atom->numChars; ++j)
  37152. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  37153. break;
  37154. return indexInText + j;
  37155. }
  37156. void updateLineHeight() throw()
  37157. {
  37158. float x = atomRight;
  37159. int tempSectionIndex = sectionIndex;
  37160. int tempAtomIndex = atomIndex;
  37161. const UniformTextSection* currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  37162. while (! SHOULD_WRAP (x, wordWrapWidth))
  37163. {
  37164. if (tempSectionIndex >= sections.size())
  37165. break;
  37166. bool checkSize = false;
  37167. if (tempAtomIndex >= currentSection->getNumAtoms())
  37168. {
  37169. if (++tempSectionIndex >= sections.size())
  37170. break;
  37171. tempAtomIndex = 0;
  37172. currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  37173. checkSize = true;
  37174. }
  37175. const TextAtom* const atom = currentSection->getAtom (tempAtomIndex);
  37176. if (atom == 0)
  37177. break;
  37178. x += atom->width;
  37179. if (SHOULD_WRAP (x, wordWrapWidth) || atom->isNewLine())
  37180. break;
  37181. if (checkSize)
  37182. {
  37183. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  37184. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  37185. }
  37186. ++tempAtomIndex;
  37187. }
  37188. }
  37189. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_) throw()
  37190. {
  37191. while (next())
  37192. {
  37193. if (indexInText + atom->numChars >= index)
  37194. {
  37195. updateLineHeight();
  37196. if (indexInText + atom->numChars > index)
  37197. {
  37198. cx = indexToX (index);
  37199. cy = lineY;
  37200. lineHeight_ = lineHeight;
  37201. return true;
  37202. }
  37203. }
  37204. }
  37205. cx = atomX;
  37206. cy = lineY;
  37207. lineHeight_ = lineHeight;
  37208. return false;
  37209. }
  37210. juce_UseDebuggingNewOperator
  37211. int indexInText;
  37212. float lineY, lineHeight, maxDescent;
  37213. float atomX, atomRight;
  37214. const TextAtom* atom;
  37215. const UniformTextSection* currentSection;
  37216. private:
  37217. const VoidArray& sections;
  37218. int sectionIndex, atomIndex;
  37219. const float wordWrapWidth;
  37220. const tchar passwordCharacter;
  37221. TextAtom tempAtom;
  37222. const TextEditorIterator& operator= (const TextEditorIterator&);
  37223. void moveToEndOfLastAtom() throw()
  37224. {
  37225. if (atom != 0)
  37226. {
  37227. atomX = atomRight;
  37228. if (atom->isNewLine())
  37229. {
  37230. atomX = 0.0f;
  37231. lineY += lineHeight;
  37232. }
  37233. }
  37234. }
  37235. };
  37236. class TextEditorInsertAction : public UndoableAction
  37237. {
  37238. TextEditor& owner;
  37239. const String text;
  37240. const int insertIndex, oldCaretPos, newCaretPos;
  37241. const Font font;
  37242. const Colour colour;
  37243. TextEditorInsertAction (const TextEditorInsertAction&);
  37244. const TextEditorInsertAction& operator= (const TextEditorInsertAction&);
  37245. public:
  37246. TextEditorInsertAction (TextEditor& owner_,
  37247. const String& text_,
  37248. const int insertIndex_,
  37249. const Font& font_,
  37250. const Colour& colour_,
  37251. const int oldCaretPos_,
  37252. const int newCaretPos_) throw()
  37253. : owner (owner_),
  37254. text (text_),
  37255. insertIndex (insertIndex_),
  37256. oldCaretPos (oldCaretPos_),
  37257. newCaretPos (newCaretPos_),
  37258. font (font_),
  37259. colour (colour_)
  37260. {
  37261. }
  37262. ~TextEditorInsertAction()
  37263. {
  37264. }
  37265. bool perform()
  37266. {
  37267. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  37268. return true;
  37269. }
  37270. bool undo()
  37271. {
  37272. owner.remove (insertIndex, insertIndex + text.length(), 0, oldCaretPos);
  37273. return true;
  37274. }
  37275. int getSizeInUnits()
  37276. {
  37277. return text.length() + 16;
  37278. }
  37279. };
  37280. class TextEditorRemoveAction : public UndoableAction
  37281. {
  37282. TextEditor& owner;
  37283. const int startIndex, endIndex, oldCaretPos, newCaretPos;
  37284. VoidArray removedSections;
  37285. TextEditorRemoveAction (const TextEditorRemoveAction&);
  37286. const TextEditorRemoveAction& operator= (const TextEditorRemoveAction&);
  37287. public:
  37288. TextEditorRemoveAction (TextEditor& owner_,
  37289. const int startIndex_,
  37290. const int endIndex_,
  37291. const int oldCaretPos_,
  37292. const int newCaretPos_,
  37293. const VoidArray& removedSections_) throw()
  37294. : owner (owner_),
  37295. startIndex (startIndex_),
  37296. endIndex (endIndex_),
  37297. oldCaretPos (oldCaretPos_),
  37298. newCaretPos (newCaretPos_),
  37299. removedSections (removedSections_)
  37300. {
  37301. }
  37302. ~TextEditorRemoveAction()
  37303. {
  37304. for (int i = removedSections.size(); --i >= 0;)
  37305. {
  37306. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  37307. section->clear();
  37308. delete section;
  37309. }
  37310. }
  37311. bool perform()
  37312. {
  37313. owner.remove (startIndex, endIndex, 0, newCaretPos);
  37314. return true;
  37315. }
  37316. bool undo()
  37317. {
  37318. owner.reinsert (startIndex, removedSections);
  37319. owner.moveCursorTo (oldCaretPos, false);
  37320. return true;
  37321. }
  37322. int getSizeInUnits()
  37323. {
  37324. int n = 0;
  37325. for (int i = removedSections.size(); --i >= 0;)
  37326. {
  37327. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  37328. n += section->getTotalLength();
  37329. }
  37330. return n + 16;
  37331. }
  37332. };
  37333. class TextHolderComponent : public Component,
  37334. public Timer
  37335. {
  37336. TextEditor* const owner;
  37337. TextHolderComponent (const TextHolderComponent&);
  37338. const TextHolderComponent& operator= (const TextHolderComponent&);
  37339. public:
  37340. TextHolderComponent (TextEditor* const owner_)
  37341. : owner (owner_)
  37342. {
  37343. setWantsKeyboardFocus (false);
  37344. setInterceptsMouseClicks (false, true);
  37345. }
  37346. ~TextHolderComponent()
  37347. {
  37348. }
  37349. void paint (Graphics& g)
  37350. {
  37351. owner->drawContent (g);
  37352. }
  37353. void timerCallback()
  37354. {
  37355. owner->timerCallbackInt();
  37356. }
  37357. const MouseCursor getMouseCursor()
  37358. {
  37359. return owner->getMouseCursor();
  37360. }
  37361. };
  37362. class TextEditorViewport : public Viewport
  37363. {
  37364. TextEditor* const owner;
  37365. float lastWordWrapWidth;
  37366. TextEditorViewport (const TextEditorViewport&);
  37367. const TextEditorViewport& operator= (const TextEditorViewport&);
  37368. public:
  37369. TextEditorViewport (TextEditor* const owner_)
  37370. : owner (owner_),
  37371. lastWordWrapWidth (0)
  37372. {
  37373. }
  37374. ~TextEditorViewport()
  37375. {
  37376. }
  37377. void visibleAreaChanged (int, int, int, int)
  37378. {
  37379. const float wordWrapWidth = owner->getWordWrapWidth();
  37380. if (wordWrapWidth != lastWordWrapWidth)
  37381. {
  37382. lastWordWrapWidth = wordWrapWidth;
  37383. owner->updateTextHolderSize();
  37384. }
  37385. }
  37386. };
  37387. const int flashSpeedIntervalMs = 380;
  37388. const int textChangeMessageId = 0x10003001;
  37389. const int returnKeyMessageId = 0x10003002;
  37390. const int escapeKeyMessageId = 0x10003003;
  37391. const int focusLossMessageId = 0x10003004;
  37392. TextEditor::TextEditor (const String& name,
  37393. const tchar passwordCharacter_)
  37394. : Component (name),
  37395. borderSize (1, 1, 1, 3),
  37396. readOnly (false),
  37397. multiline (false),
  37398. wordWrap (false),
  37399. returnKeyStartsNewLine (false),
  37400. caretVisible (true),
  37401. popupMenuEnabled (true),
  37402. selectAllTextWhenFocused (false),
  37403. scrollbarVisible (true),
  37404. wasFocused (false),
  37405. caretFlashState (true),
  37406. keepCursorOnScreen (true),
  37407. tabKeyUsed (false),
  37408. menuActive (false),
  37409. cursorX (0),
  37410. cursorY (0),
  37411. cursorHeight (0),
  37412. maxTextLength (0),
  37413. selectionStart (0),
  37414. selectionEnd (0),
  37415. leftIndent (4),
  37416. topIndent (4),
  37417. lastTransactionTime (0),
  37418. currentFont (14.0f),
  37419. totalNumChars (0),
  37420. caretPosition (0),
  37421. sections (8),
  37422. passwordCharacter (passwordCharacter_),
  37423. dragType (notDragging),
  37424. listeners (2)
  37425. {
  37426. setOpaque (true);
  37427. addAndMakeVisible (viewport = new TextEditorViewport (this));
  37428. viewport->setViewedComponent (textHolder = new TextHolderComponent (this));
  37429. viewport->setWantsKeyboardFocus (false);
  37430. viewport->setScrollBarsShown (false, false);
  37431. setMouseCursor (MouseCursor::IBeamCursor);
  37432. setWantsKeyboardFocus (true);
  37433. }
  37434. TextEditor::~TextEditor()
  37435. {
  37436. clearInternal (0);
  37437. delete viewport;
  37438. }
  37439. void TextEditor::newTransaction() throw()
  37440. {
  37441. lastTransactionTime = Time::getApproximateMillisecondCounter();
  37442. undoManager.beginNewTransaction();
  37443. }
  37444. void TextEditor::doUndoRedo (const bool isRedo)
  37445. {
  37446. if (! isReadOnly())
  37447. {
  37448. if ((isRedo) ? undoManager.redo()
  37449. : undoManager.undo())
  37450. {
  37451. scrollToMakeSureCursorIsVisible();
  37452. repaint();
  37453. textChanged();
  37454. }
  37455. }
  37456. }
  37457. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  37458. const bool shouldWordWrap)
  37459. {
  37460. multiline = shouldBeMultiLine;
  37461. wordWrap = shouldWordWrap && shouldBeMultiLine;
  37462. setScrollbarsShown (scrollbarVisible);
  37463. viewport->setViewPosition (0, 0);
  37464. resized();
  37465. scrollToMakeSureCursorIsVisible();
  37466. }
  37467. bool TextEditor::isMultiLine() const throw()
  37468. {
  37469. return multiline;
  37470. }
  37471. void TextEditor::setScrollbarsShown (bool enabled) throw()
  37472. {
  37473. scrollbarVisible = enabled;
  37474. enabled = enabled && isMultiLine();
  37475. viewport->setScrollBarsShown (enabled, enabled);
  37476. }
  37477. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  37478. {
  37479. readOnly = shouldBeReadOnly;
  37480. enablementChanged();
  37481. }
  37482. bool TextEditor::isReadOnly() const throw()
  37483. {
  37484. return readOnly || ! isEnabled();
  37485. }
  37486. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  37487. {
  37488. returnKeyStartsNewLine = shouldStartNewLine;
  37489. }
  37490. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw()
  37491. {
  37492. tabKeyUsed = shouldTabKeyBeUsed;
  37493. }
  37494. void TextEditor::setPopupMenuEnabled (const bool b) throw()
  37495. {
  37496. popupMenuEnabled = b;
  37497. }
  37498. void TextEditor::setSelectAllWhenFocused (const bool b) throw()
  37499. {
  37500. selectAllTextWhenFocused = b;
  37501. }
  37502. const Font TextEditor::getFont() const throw()
  37503. {
  37504. return currentFont;
  37505. }
  37506. void TextEditor::setFont (const Font& newFont) throw()
  37507. {
  37508. currentFont = newFont;
  37509. scrollToMakeSureCursorIsVisible();
  37510. }
  37511. void TextEditor::applyFontToAllText (const Font& newFont)
  37512. {
  37513. currentFont = newFont;
  37514. const Colour overallColour (findColour (textColourId));
  37515. for (int i = sections.size(); --i >= 0;)
  37516. {
  37517. UniformTextSection* const uts = (UniformTextSection*) sections.getUnchecked(i);
  37518. uts->setFont (newFont, passwordCharacter);
  37519. uts->colour = overallColour;
  37520. }
  37521. coalesceSimilarSections();
  37522. updateTextHolderSize();
  37523. scrollToMakeSureCursorIsVisible();
  37524. repaint();
  37525. }
  37526. void TextEditor::colourChanged()
  37527. {
  37528. setOpaque (findColour (backgroundColourId).isOpaque());
  37529. repaint();
  37530. }
  37531. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible) throw()
  37532. {
  37533. caretVisible = shouldCaretBeVisible;
  37534. if (shouldCaretBeVisible)
  37535. textHolder->startTimer (flashSpeedIntervalMs);
  37536. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  37537. : MouseCursor::NormalCursor);
  37538. }
  37539. void TextEditor::setInputRestrictions (const int maxLen,
  37540. const String& chars) throw()
  37541. {
  37542. maxTextLength = jmax (0, maxLen);
  37543. allowedCharacters = chars;
  37544. }
  37545. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw()
  37546. {
  37547. textToShowWhenEmpty = text;
  37548. colourForTextWhenEmpty = colourToUse;
  37549. }
  37550. void TextEditor::setPasswordCharacter (const tchar newPasswordCharacter) throw()
  37551. {
  37552. if (passwordCharacter != newPasswordCharacter)
  37553. {
  37554. passwordCharacter = newPasswordCharacter;
  37555. resized();
  37556. repaint();
  37557. }
  37558. }
  37559. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  37560. {
  37561. viewport->setScrollBarThickness (newThicknessPixels);
  37562. }
  37563. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  37564. {
  37565. viewport->setScrollBarButtonVisibility (buttonsVisible);
  37566. }
  37567. void TextEditor::clear()
  37568. {
  37569. clearInternal (0);
  37570. updateTextHolderSize();
  37571. undoManager.clearUndoHistory();
  37572. }
  37573. void TextEditor::setText (const String& newText,
  37574. const bool sendTextChangeMessage)
  37575. {
  37576. const int newLength = newText.length();
  37577. if (newLength != getTotalNumChars() || getText() != newText)
  37578. {
  37579. const int oldCursorPos = caretPosition;
  37580. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  37581. clearInternal (0);
  37582. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  37583. // if you're adding text with line-feeds to a single-line text editor, it
  37584. // ain't gonna look right!
  37585. jassert (multiline || ! newText.containsAnyOf (T("\r\n")));
  37586. if (cursorWasAtEnd && ! isMultiLine())
  37587. moveCursorTo (getTotalNumChars(), false);
  37588. else
  37589. moveCursorTo (oldCursorPos, false);
  37590. if (sendTextChangeMessage)
  37591. textChanged();
  37592. repaint();
  37593. }
  37594. updateTextHolderSize();
  37595. scrollToMakeSureCursorIsVisible();
  37596. undoManager.clearUndoHistory();
  37597. }
  37598. void TextEditor::textChanged() throw()
  37599. {
  37600. updateTextHolderSize();
  37601. postCommandMessage (textChangeMessageId);
  37602. }
  37603. void TextEditor::returnPressed()
  37604. {
  37605. postCommandMessage (returnKeyMessageId);
  37606. }
  37607. void TextEditor::escapePressed()
  37608. {
  37609. postCommandMessage (escapeKeyMessageId);
  37610. }
  37611. void TextEditor::addListener (TextEditorListener* const newListener) throw()
  37612. {
  37613. jassert (newListener != 0)
  37614. if (newListener != 0)
  37615. listeners.add (newListener);
  37616. }
  37617. void TextEditor::removeListener (TextEditorListener* const listenerToRemove) throw()
  37618. {
  37619. listeners.removeValue (listenerToRemove);
  37620. }
  37621. void TextEditor::timerCallbackInt()
  37622. {
  37623. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  37624. if (caretFlashState != newState)
  37625. {
  37626. caretFlashState = newState;
  37627. if (caretFlashState)
  37628. wasFocused = true;
  37629. if (caretVisible
  37630. && hasKeyboardFocus (false)
  37631. && ! isReadOnly())
  37632. {
  37633. repaintCaret();
  37634. }
  37635. }
  37636. const unsigned int now = Time::getApproximateMillisecondCounter();
  37637. if (now > lastTransactionTime + 200)
  37638. newTransaction();
  37639. }
  37640. void TextEditor::repaintCaret()
  37641. {
  37642. if (! findColour (caretColourId).isTransparent())
  37643. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundFloatToInt (cursorX) - 1,
  37644. borderSize.getTop() + textHolder->getY() + topIndent + roundFloatToInt (cursorY) - 1,
  37645. 4,
  37646. roundFloatToInt (cursorHeight) + 2);
  37647. }
  37648. void TextEditor::repaintText (int textStartIndex, int textEndIndex)
  37649. {
  37650. if (textStartIndex > textEndIndex && textEndIndex > 0)
  37651. swapVariables (textStartIndex, textEndIndex);
  37652. float x = 0, y = 0, lh = currentFont.getHeight();
  37653. const float wordWrapWidth = getWordWrapWidth();
  37654. if (wordWrapWidth > 0)
  37655. {
  37656. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  37657. i.getCharPosition (textStartIndex, x, y, lh);
  37658. const int y1 = (int) y;
  37659. int y2;
  37660. if (textEndIndex >= 0)
  37661. {
  37662. i.getCharPosition (textEndIndex, x, y, lh);
  37663. y2 = (int) (y + lh * 2.0f);
  37664. }
  37665. else
  37666. {
  37667. y2 = textHolder->getHeight();
  37668. }
  37669. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  37670. }
  37671. }
  37672. void TextEditor::moveCaret (int newCaretPos) throw()
  37673. {
  37674. if (newCaretPos < 0)
  37675. newCaretPos = 0;
  37676. else if (newCaretPos > getTotalNumChars())
  37677. newCaretPos = getTotalNumChars();
  37678. if (newCaretPos != getCaretPosition())
  37679. {
  37680. repaintCaret();
  37681. caretFlashState = true;
  37682. caretPosition = newCaretPos;
  37683. textHolder->startTimer (flashSpeedIntervalMs);
  37684. scrollToMakeSureCursorIsVisible();
  37685. repaintCaret();
  37686. }
  37687. }
  37688. void TextEditor::setCaretPosition (const int newIndex) throw()
  37689. {
  37690. moveCursorTo (newIndex, false);
  37691. }
  37692. int TextEditor::getCaretPosition() const throw()
  37693. {
  37694. return caretPosition;
  37695. }
  37696. float TextEditor::getWordWrapWidth() const throw()
  37697. {
  37698. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  37699. : 1.0e10f;
  37700. }
  37701. void TextEditor::updateTextHolderSize() throw()
  37702. {
  37703. const float wordWrapWidth = getWordWrapWidth();
  37704. if (wordWrapWidth > 0)
  37705. {
  37706. float maxWidth = 0.0f;
  37707. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  37708. while (i.next())
  37709. maxWidth = jmax (maxWidth, i.atomRight);
  37710. const int w = leftIndent + roundFloatToInt (maxWidth);
  37711. const int h = topIndent + roundFloatToInt (jmax (i.lineY + i.lineHeight,
  37712. currentFont.getHeight()));
  37713. textHolder->setSize (w + 1, h + 1);
  37714. }
  37715. }
  37716. int TextEditor::getTextWidth() const throw()
  37717. {
  37718. return textHolder->getWidth();
  37719. }
  37720. int TextEditor::getTextHeight() const throw()
  37721. {
  37722. return textHolder->getHeight();
  37723. }
  37724. void TextEditor::setIndents (const int newLeftIndent,
  37725. const int newTopIndent) throw()
  37726. {
  37727. leftIndent = newLeftIndent;
  37728. topIndent = newTopIndent;
  37729. }
  37730. void TextEditor::setBorder (const BorderSize& border) throw()
  37731. {
  37732. borderSize = border;
  37733. resized();
  37734. }
  37735. const BorderSize TextEditor::getBorder() const throw()
  37736. {
  37737. return borderSize;
  37738. }
  37739. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor) throw()
  37740. {
  37741. keepCursorOnScreen = shouldScrollToShowCursor;
  37742. }
  37743. void TextEditor::scrollToMakeSureCursorIsVisible() throw()
  37744. {
  37745. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  37746. getCharPosition (caretPosition,
  37747. cursorX, cursorY,
  37748. cursorHeight);
  37749. if (keepCursorOnScreen)
  37750. {
  37751. int x = viewport->getViewPositionX();
  37752. int y = viewport->getViewPositionY();
  37753. const int relativeCursorX = roundFloatToInt (cursorX) - x;
  37754. const int relativeCursorY = roundFloatToInt (cursorY) - y;
  37755. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  37756. {
  37757. x += relativeCursorX - proportionOfWidth (0.2f);
  37758. }
  37759. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  37760. {
  37761. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  37762. }
  37763. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  37764. if (! isMultiLine())
  37765. {
  37766. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  37767. }
  37768. else
  37769. {
  37770. const int curH = roundFloatToInt (cursorHeight);
  37771. if (relativeCursorY < 0)
  37772. {
  37773. y = jmax (0, relativeCursorY + y);
  37774. }
  37775. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  37776. {
  37777. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  37778. }
  37779. }
  37780. viewport->setViewPosition (x, y);
  37781. }
  37782. }
  37783. void TextEditor::moveCursorTo (const int newPosition,
  37784. const bool isSelecting) throw()
  37785. {
  37786. if (isSelecting)
  37787. {
  37788. moveCaret (newPosition);
  37789. const int oldSelStart = selectionStart;
  37790. const int oldSelEnd = selectionEnd;
  37791. if (dragType == notDragging)
  37792. {
  37793. if (abs (getCaretPosition() - selectionStart) < abs (getCaretPosition() - selectionEnd))
  37794. dragType = draggingSelectionStart;
  37795. else
  37796. dragType = draggingSelectionEnd;
  37797. }
  37798. if (dragType == draggingSelectionStart)
  37799. {
  37800. selectionStart = getCaretPosition();
  37801. if (selectionEnd < selectionStart)
  37802. {
  37803. swapVariables (selectionStart, selectionEnd);
  37804. dragType = draggingSelectionEnd;
  37805. }
  37806. }
  37807. else
  37808. {
  37809. selectionEnd = getCaretPosition();
  37810. if (selectionEnd < selectionStart)
  37811. {
  37812. swapVariables (selectionStart, selectionEnd);
  37813. dragType = draggingSelectionStart;
  37814. }
  37815. }
  37816. jassert (selectionStart <= selectionEnd);
  37817. jassert (oldSelStart <= oldSelEnd);
  37818. repaintText (jmin (oldSelStart, selectionStart),
  37819. jmax (oldSelEnd, selectionEnd));
  37820. }
  37821. else
  37822. {
  37823. dragType = notDragging;
  37824. if (selectionEnd > selectionStart)
  37825. repaintText (selectionStart, selectionEnd);
  37826. moveCaret (newPosition);
  37827. selectionStart = getCaretPosition();
  37828. selectionEnd = getCaretPosition();
  37829. }
  37830. }
  37831. int TextEditor::getTextIndexAt (const int x,
  37832. const int y) throw()
  37833. {
  37834. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  37835. (float) (y + viewport->getViewPositionY() - topIndent));
  37836. }
  37837. void TextEditor::insertTextAtCursor (String newText)
  37838. {
  37839. if (allowedCharacters.isNotEmpty())
  37840. newText = newText.retainCharacters (allowedCharacters);
  37841. if (! isMultiLine())
  37842. newText = newText.replaceCharacters (T("\r\n"), T(" "));
  37843. else
  37844. newText = newText.replace (T("\r\n"), T("\n"));
  37845. const int newCaretPos = selectionStart + newText.length();
  37846. const int insertIndex = selectionStart;
  37847. remove (selectionStart, selectionEnd,
  37848. &undoManager,
  37849. newCaretPos);
  37850. if (maxTextLength > 0)
  37851. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  37852. if (newText.isNotEmpty())
  37853. insert (newText,
  37854. insertIndex,
  37855. currentFont,
  37856. findColour (textColourId),
  37857. &undoManager,
  37858. newCaretPos);
  37859. textChanged();
  37860. }
  37861. void TextEditor::setHighlightedRegion (int startPos, int numChars) throw()
  37862. {
  37863. moveCursorTo (startPos, false);
  37864. moveCursorTo (startPos + numChars, true);
  37865. }
  37866. void TextEditor::copy()
  37867. {
  37868. const String selection (getTextSubstring (selectionStart, selectionEnd));
  37869. if (selection.isNotEmpty())
  37870. SystemClipboard::copyTextToClipboard (selection);
  37871. }
  37872. void TextEditor::paste()
  37873. {
  37874. if (! isReadOnly())
  37875. {
  37876. const String clip (SystemClipboard::getTextFromClipboard());
  37877. if (clip.isNotEmpty())
  37878. insertTextAtCursor (clip);
  37879. }
  37880. }
  37881. void TextEditor::cut()
  37882. {
  37883. if (! isReadOnly())
  37884. {
  37885. moveCaret (selectionEnd);
  37886. insertTextAtCursor (String::empty);
  37887. }
  37888. }
  37889. void TextEditor::drawContent (Graphics& g)
  37890. {
  37891. const float wordWrapWidth = getWordWrapWidth();
  37892. if (wordWrapWidth > 0)
  37893. {
  37894. g.setOrigin (leftIndent, topIndent);
  37895. const Rectangle clip (g.getClipBounds());
  37896. Colour selectedTextColour;
  37897. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  37898. while (i.lineY + 200.0 < clip.getY() && i.next())
  37899. {}
  37900. if (selectionStart < selectionEnd)
  37901. {
  37902. g.setColour (findColour (highlightColourId)
  37903. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  37904. selectedTextColour = findColour (highlightedTextColourId);
  37905. TextEditorIterator i2 (i);
  37906. while (i2.next() && i2.lineY < clip.getBottom())
  37907. {
  37908. i2.updateLineHeight();
  37909. if (i2.lineY + i2.lineHeight >= clip.getY()
  37910. && selectionEnd >= i2.indexInText
  37911. && selectionStart <= i2.indexInText + i2.atom->numChars)
  37912. {
  37913. i2.drawSelection (g, selectionStart, selectionEnd);
  37914. }
  37915. }
  37916. }
  37917. const UniformTextSection* lastSection = 0;
  37918. while (i.next() && i.lineY < clip.getBottom())
  37919. {
  37920. i.updateLineHeight();
  37921. if (i.lineY + i.lineHeight >= clip.getY())
  37922. {
  37923. if (selectionEnd >= i.indexInText
  37924. && selectionStart <= i.indexInText + i.atom->numChars)
  37925. {
  37926. i.drawSelectedText (g, selectionStart, selectionEnd, selectedTextColour);
  37927. lastSection = 0;
  37928. }
  37929. else
  37930. {
  37931. i.draw (g, lastSection);
  37932. }
  37933. }
  37934. }
  37935. }
  37936. }
  37937. void TextEditor::paint (Graphics& g)
  37938. {
  37939. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  37940. }
  37941. void TextEditor::paintOverChildren (Graphics& g)
  37942. {
  37943. if (caretFlashState
  37944. && hasKeyboardFocus (false)
  37945. && caretVisible
  37946. && ! isReadOnly())
  37947. {
  37948. g.setColour (findColour (caretColourId));
  37949. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  37950. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  37951. 2.0f, cursorHeight);
  37952. }
  37953. if (textToShowWhenEmpty.isNotEmpty()
  37954. && (! hasKeyboardFocus (false))
  37955. && getTotalNumChars() == 0)
  37956. {
  37957. g.setColour (colourForTextWhenEmpty);
  37958. g.setFont (getFont());
  37959. if (isMultiLine())
  37960. {
  37961. g.drawText (textToShowWhenEmpty,
  37962. 0, 0, getWidth(), getHeight(),
  37963. Justification::centred, true);
  37964. }
  37965. else
  37966. {
  37967. g.drawText (textToShowWhenEmpty,
  37968. leftIndent, topIndent,
  37969. viewport->getWidth() - leftIndent,
  37970. viewport->getHeight() - topIndent,
  37971. Justification::centredLeft, true);
  37972. }
  37973. }
  37974. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  37975. }
  37976. void TextEditor::mouseDown (const MouseEvent& e)
  37977. {
  37978. beginDragAutoRepeat (100);
  37979. newTransaction();
  37980. if (wasFocused || ! selectAllTextWhenFocused)
  37981. {
  37982. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  37983. {
  37984. moveCursorTo (getTextIndexAt (e.x, e.y),
  37985. e.mods.isShiftDown());
  37986. }
  37987. else
  37988. {
  37989. PopupMenu m;
  37990. addPopupMenuItems (m, &e);
  37991. menuActive = true;
  37992. const int result = m.show();
  37993. menuActive = false;
  37994. if (result != 0)
  37995. performPopupMenuAction (result);
  37996. }
  37997. }
  37998. }
  37999. void TextEditor::mouseDrag (const MouseEvent& e)
  38000. {
  38001. if (wasFocused || ! selectAllTextWhenFocused)
  38002. {
  38003. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  38004. {
  38005. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  38006. }
  38007. }
  38008. }
  38009. void TextEditor::mouseUp (const MouseEvent& e)
  38010. {
  38011. newTransaction();
  38012. textHolder->startTimer (flashSpeedIntervalMs);
  38013. if (wasFocused || ! selectAllTextWhenFocused)
  38014. {
  38015. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  38016. {
  38017. moveCaret (getTextIndexAt (e.x, e.y));
  38018. }
  38019. }
  38020. wasFocused = true;
  38021. }
  38022. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  38023. {
  38024. int tokenEnd = getTextIndexAt (e.x, e.y);
  38025. int tokenStart = tokenEnd;
  38026. if (e.getNumberOfClicks() > 3)
  38027. {
  38028. tokenStart = 0;
  38029. tokenEnd = getTotalNumChars();
  38030. }
  38031. else
  38032. {
  38033. const String t (getText());
  38034. const int totalLength = getTotalNumChars();
  38035. while (tokenEnd < totalLength)
  38036. {
  38037. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]))
  38038. ++tokenEnd;
  38039. else
  38040. break;
  38041. }
  38042. tokenStart = tokenEnd;
  38043. while (tokenStart > 0)
  38044. {
  38045. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]))
  38046. --tokenStart;
  38047. else
  38048. break;
  38049. }
  38050. if (e.getNumberOfClicks() > 2)
  38051. {
  38052. while (tokenEnd < totalLength)
  38053. {
  38054. if (t [tokenEnd] != T('\r') && t [tokenEnd] != T('\n'))
  38055. ++tokenEnd;
  38056. else
  38057. break;
  38058. }
  38059. while (tokenStart > 0)
  38060. {
  38061. if (t [tokenStart - 1] != T('\r') && t [tokenStart - 1] != T('\n'))
  38062. --tokenStart;
  38063. else
  38064. break;
  38065. }
  38066. }
  38067. }
  38068. moveCursorTo (tokenEnd, false);
  38069. moveCursorTo (tokenStart, true);
  38070. }
  38071. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  38072. {
  38073. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  38074. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  38075. }
  38076. bool TextEditor::keyPressed (const KeyPress& key)
  38077. {
  38078. if (isReadOnly() && key != KeyPress (T('c'), ModifierKeys::commandModifier, 0))
  38079. return false;
  38080. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  38081. if (key.isKeyCode (KeyPress::leftKey)
  38082. || key.isKeyCode (KeyPress::upKey))
  38083. {
  38084. newTransaction();
  38085. int newPos;
  38086. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  38087. newPos = indexAtPosition (cursorX, cursorY - 1);
  38088. else if (moveInWholeWordSteps)
  38089. newPos = findWordBreakBefore (getCaretPosition());
  38090. else
  38091. newPos = getCaretPosition() - 1;
  38092. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  38093. }
  38094. else if (key.isKeyCode (KeyPress::rightKey)
  38095. || key.isKeyCode (KeyPress::downKey))
  38096. {
  38097. newTransaction();
  38098. int newPos;
  38099. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  38100. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  38101. else if (moveInWholeWordSteps)
  38102. newPos = findWordBreakAfter (getCaretPosition());
  38103. else
  38104. newPos = getCaretPosition() + 1;
  38105. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  38106. }
  38107. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  38108. {
  38109. newTransaction();
  38110. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  38111. key.getModifiers().isShiftDown());
  38112. }
  38113. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  38114. {
  38115. newTransaction();
  38116. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  38117. key.getModifiers().isShiftDown());
  38118. }
  38119. else if (key.isKeyCode (KeyPress::homeKey))
  38120. {
  38121. newTransaction();
  38122. if (isMultiLine() && ! moveInWholeWordSteps)
  38123. moveCursorTo (indexAtPosition (0.0f, cursorY),
  38124. key.getModifiers().isShiftDown());
  38125. else
  38126. moveCursorTo (0, key.getModifiers().isShiftDown());
  38127. }
  38128. else if (key.isKeyCode (KeyPress::endKey))
  38129. {
  38130. newTransaction();
  38131. if (isMultiLine() && ! moveInWholeWordSteps)
  38132. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  38133. key.getModifiers().isShiftDown());
  38134. else
  38135. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  38136. }
  38137. else if (key.isKeyCode (KeyPress::backspaceKey))
  38138. {
  38139. if (moveInWholeWordSteps)
  38140. {
  38141. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  38142. }
  38143. else
  38144. {
  38145. if (selectionStart == selectionEnd && selectionStart > 0)
  38146. --selectionStart;
  38147. }
  38148. cut();
  38149. }
  38150. else if (key.isKeyCode (KeyPress::deleteKey))
  38151. {
  38152. if (key.getModifiers().isShiftDown())
  38153. copy();
  38154. if (selectionStart == selectionEnd
  38155. && selectionEnd < getTotalNumChars())
  38156. {
  38157. ++selectionEnd;
  38158. }
  38159. cut();
  38160. }
  38161. else if (key == KeyPress (T('c'), ModifierKeys::commandModifier, 0)
  38162. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  38163. {
  38164. newTransaction();
  38165. copy();
  38166. }
  38167. else if (key == KeyPress (T('x'), ModifierKeys::commandModifier, 0))
  38168. {
  38169. newTransaction();
  38170. copy();
  38171. cut();
  38172. }
  38173. else if (key == KeyPress (T('v'), ModifierKeys::commandModifier, 0)
  38174. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  38175. {
  38176. newTransaction();
  38177. paste();
  38178. }
  38179. else if (key == KeyPress (T('z'), ModifierKeys::commandModifier, 0))
  38180. {
  38181. newTransaction();
  38182. doUndoRedo (false);
  38183. }
  38184. else if (key == KeyPress (T('y'), ModifierKeys::commandModifier, 0))
  38185. {
  38186. newTransaction();
  38187. doUndoRedo (true);
  38188. }
  38189. else if (key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  38190. {
  38191. newTransaction();
  38192. moveCursorTo (getTotalNumChars(), false);
  38193. moveCursorTo (0, true);
  38194. }
  38195. else if (key == KeyPress::returnKey)
  38196. {
  38197. newTransaction();
  38198. if (returnKeyStartsNewLine)
  38199. insertTextAtCursor (T("\n"));
  38200. else
  38201. returnPressed();
  38202. }
  38203. else if (key.isKeyCode (KeyPress::escapeKey))
  38204. {
  38205. newTransaction();
  38206. moveCursorTo (getCaretPosition(), false);
  38207. escapePressed();
  38208. }
  38209. else if (key.getTextCharacter() >= ' '
  38210. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  38211. {
  38212. insertTextAtCursor (String::charToString (key.getTextCharacter()));
  38213. lastTransactionTime = Time::getApproximateMillisecondCounter();
  38214. }
  38215. else
  38216. {
  38217. return false;
  38218. }
  38219. return true;
  38220. }
  38221. bool TextEditor::keyStateChanged()
  38222. {
  38223. // (overridden to avoid forwarding key events to the parent)
  38224. return true;
  38225. }
  38226. const int baseMenuItemID = 0x7fff0000;
  38227. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  38228. {
  38229. const bool writable = ! isReadOnly();
  38230. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  38231. m.addItem (baseMenuItemID + 2, TRANS("copy"), selectionStart < selectionEnd);
  38232. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  38233. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  38234. m.addSeparator();
  38235. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  38236. m.addSeparator();
  38237. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  38238. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  38239. }
  38240. void TextEditor::performPopupMenuAction (const int menuItemID)
  38241. {
  38242. switch (menuItemID)
  38243. {
  38244. case baseMenuItemID + 1:
  38245. copy();
  38246. cut();
  38247. break;
  38248. case baseMenuItemID + 2:
  38249. copy();
  38250. break;
  38251. case baseMenuItemID + 3:
  38252. paste();
  38253. break;
  38254. case baseMenuItemID + 4:
  38255. cut();
  38256. break;
  38257. case baseMenuItemID + 5:
  38258. moveCursorTo (getTotalNumChars(), false);
  38259. moveCursorTo (0, true);
  38260. break;
  38261. case baseMenuItemID + 6:
  38262. doUndoRedo (false);
  38263. break;
  38264. case baseMenuItemID + 7:
  38265. doUndoRedo (true);
  38266. break;
  38267. default:
  38268. break;
  38269. }
  38270. }
  38271. void TextEditor::focusGained (FocusChangeType)
  38272. {
  38273. newTransaction();
  38274. caretFlashState = true;
  38275. if (selectAllTextWhenFocused)
  38276. {
  38277. moveCursorTo (0, false);
  38278. moveCursorTo (getTotalNumChars(), true);
  38279. }
  38280. repaint();
  38281. if (caretVisible)
  38282. textHolder->startTimer (flashSpeedIntervalMs);
  38283. ComponentPeer* const peer = getPeer();
  38284. if (peer != 0)
  38285. peer->textInputRequired (getScreenX() - peer->getScreenX(),
  38286. getScreenY() - peer->getScreenY());
  38287. }
  38288. void TextEditor::focusLost (FocusChangeType)
  38289. {
  38290. newTransaction();
  38291. wasFocused = false;
  38292. textHolder->stopTimer();
  38293. caretFlashState = false;
  38294. postCommandMessage (focusLossMessageId);
  38295. repaint();
  38296. }
  38297. void TextEditor::resized()
  38298. {
  38299. viewport->setBoundsInset (borderSize);
  38300. viewport->setSingleStepSizes (16, roundFloatToInt (currentFont.getHeight()));
  38301. updateTextHolderSize();
  38302. if (! isMultiLine())
  38303. {
  38304. scrollToMakeSureCursorIsVisible();
  38305. }
  38306. else
  38307. {
  38308. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  38309. getCharPosition (caretPosition,
  38310. cursorX, cursorY,
  38311. cursorHeight);
  38312. }
  38313. }
  38314. void TextEditor::handleCommandMessage (const int commandId)
  38315. {
  38316. const ComponentDeletionWatcher deletionChecker (this);
  38317. for (int i = listeners.size(); --i >= 0;)
  38318. {
  38319. TextEditorListener* const tl = (TextEditorListener*) listeners [i];
  38320. if (tl != 0)
  38321. {
  38322. switch (commandId)
  38323. {
  38324. case textChangeMessageId:
  38325. tl->textEditorTextChanged (*this);
  38326. break;
  38327. case returnKeyMessageId:
  38328. tl->textEditorReturnKeyPressed (*this);
  38329. break;
  38330. case escapeKeyMessageId:
  38331. tl->textEditorEscapeKeyPressed (*this);
  38332. break;
  38333. case focusLossMessageId:
  38334. tl->textEditorFocusLost (*this);
  38335. break;
  38336. default:
  38337. jassertfalse
  38338. break;
  38339. }
  38340. if (i > 0 && deletionChecker.hasBeenDeleted())
  38341. return;
  38342. }
  38343. }
  38344. }
  38345. void TextEditor::enablementChanged()
  38346. {
  38347. setMouseCursor (MouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  38348. : MouseCursor::IBeamCursor));
  38349. repaint();
  38350. }
  38351. void TextEditor::clearInternal (UndoManager* const um) throw()
  38352. {
  38353. remove (0, getTotalNumChars(), um, caretPosition);
  38354. }
  38355. void TextEditor::insert (const String& text,
  38356. const int insertIndex,
  38357. const Font& font,
  38358. const Colour& colour,
  38359. UndoManager* const um,
  38360. const int caretPositionToMoveTo) throw()
  38361. {
  38362. if (text.isNotEmpty())
  38363. {
  38364. if (um != 0)
  38365. {
  38366. um->perform (new TextEditorInsertAction (*this,
  38367. text,
  38368. insertIndex,
  38369. font,
  38370. colour,
  38371. caretPosition,
  38372. caretPositionToMoveTo));
  38373. }
  38374. else
  38375. {
  38376. repaintText (insertIndex, -1); // must do this before and after changing the data, in case
  38377. // a line gets moved due to word wrap
  38378. int index = 0;
  38379. int nextIndex = 0;
  38380. for (int i = 0; i < sections.size(); ++i)
  38381. {
  38382. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  38383. if (insertIndex == index)
  38384. {
  38385. sections.insert (i, new UniformTextSection (text,
  38386. font, colour,
  38387. passwordCharacter));
  38388. break;
  38389. }
  38390. else if (insertIndex > index && insertIndex < nextIndex)
  38391. {
  38392. splitSection (i, insertIndex - index);
  38393. sections.insert (i + 1, new UniformTextSection (text,
  38394. font, colour,
  38395. passwordCharacter));
  38396. break;
  38397. }
  38398. index = nextIndex;
  38399. }
  38400. if (nextIndex == insertIndex)
  38401. sections.add (new UniformTextSection (text,
  38402. font, colour,
  38403. passwordCharacter));
  38404. coalesceSimilarSections();
  38405. totalNumChars = -1;
  38406. moveCursorTo (caretPositionToMoveTo, false);
  38407. repaintText (insertIndex, -1);
  38408. }
  38409. }
  38410. }
  38411. void TextEditor::reinsert (const int insertIndex,
  38412. const VoidArray& sectionsToInsert) throw()
  38413. {
  38414. int index = 0;
  38415. int nextIndex = 0;
  38416. for (int i = 0; i < sections.size(); ++i)
  38417. {
  38418. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  38419. if (insertIndex == index)
  38420. {
  38421. for (int j = sectionsToInsert.size(); --j >= 0;)
  38422. sections.insert (i, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  38423. break;
  38424. }
  38425. else if (insertIndex > index && insertIndex < nextIndex)
  38426. {
  38427. splitSection (i, insertIndex - index);
  38428. for (int j = sectionsToInsert.size(); --j >= 0;)
  38429. sections.insert (i + 1, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  38430. break;
  38431. }
  38432. index = nextIndex;
  38433. }
  38434. if (nextIndex == insertIndex)
  38435. {
  38436. for (int j = 0; j < sectionsToInsert.size(); ++j)
  38437. sections.add (new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  38438. }
  38439. coalesceSimilarSections();
  38440. totalNumChars = -1;
  38441. }
  38442. void TextEditor::remove (const int startIndex,
  38443. int endIndex,
  38444. UndoManager* const um,
  38445. const int caretPositionToMoveTo) throw()
  38446. {
  38447. if (endIndex > startIndex)
  38448. {
  38449. int index = 0;
  38450. for (int i = 0; i < sections.size(); ++i)
  38451. {
  38452. const int nextIndex = index + ((UniformTextSection*) sections[i])->getTotalLength();
  38453. if (startIndex > index && startIndex < nextIndex)
  38454. {
  38455. splitSection (i, startIndex - index);
  38456. --i;
  38457. }
  38458. else if (endIndex > index && endIndex < nextIndex)
  38459. {
  38460. splitSection (i, endIndex - index);
  38461. --i;
  38462. }
  38463. else
  38464. {
  38465. index = nextIndex;
  38466. if (index > endIndex)
  38467. break;
  38468. }
  38469. }
  38470. index = 0;
  38471. if (um != 0)
  38472. {
  38473. VoidArray removedSections;
  38474. for (int i = 0; i < sections.size(); ++i)
  38475. {
  38476. if (endIndex <= startIndex)
  38477. break;
  38478. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  38479. const int nextIndex = index + section->getTotalLength();
  38480. if (startIndex <= index && endIndex >= nextIndex)
  38481. removedSections.add (new UniformTextSection (*section));
  38482. index = nextIndex;
  38483. }
  38484. um->perform (new TextEditorRemoveAction (*this,
  38485. startIndex,
  38486. endIndex,
  38487. caretPosition,
  38488. caretPositionToMoveTo,
  38489. removedSections));
  38490. }
  38491. else
  38492. {
  38493. for (int i = 0; i < sections.size(); ++i)
  38494. {
  38495. if (endIndex <= startIndex)
  38496. break;
  38497. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  38498. const int nextIndex = index + section->getTotalLength();
  38499. if (startIndex <= index && endIndex >= nextIndex)
  38500. {
  38501. sections.remove(i);
  38502. endIndex -= (nextIndex - index);
  38503. section->clear();
  38504. delete section;
  38505. --i;
  38506. }
  38507. else
  38508. {
  38509. index = nextIndex;
  38510. }
  38511. }
  38512. coalesceSimilarSections();
  38513. totalNumChars = -1;
  38514. moveCursorTo (caretPositionToMoveTo, false);
  38515. repaintText (startIndex, -1);
  38516. }
  38517. }
  38518. }
  38519. const String TextEditor::getText() const throw()
  38520. {
  38521. String t;
  38522. for (int i = 0; i < sections.size(); ++i)
  38523. t += ((const UniformTextSection*) sections.getUnchecked(i))->getAllText();
  38524. return t;
  38525. }
  38526. const String TextEditor::getTextSubstring (const int startCharacter, const int endCharacter) const throw()
  38527. {
  38528. String t;
  38529. int index = 0;
  38530. for (int i = 0; i < sections.size(); ++i)
  38531. {
  38532. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked(i);
  38533. const int nextIndex = index + s->getTotalLength();
  38534. if (startCharacter < nextIndex)
  38535. {
  38536. if (endCharacter <= index)
  38537. break;
  38538. const int start = jmax (index, startCharacter);
  38539. t += s->getTextSubstring (start - index, endCharacter - index);
  38540. }
  38541. index = nextIndex;
  38542. }
  38543. return t;
  38544. }
  38545. const String TextEditor::getHighlightedText() const throw()
  38546. {
  38547. return getTextSubstring (getHighlightedRegionStart(),
  38548. getHighlightedRegionStart() + getHighlightedRegionLength());
  38549. }
  38550. int TextEditor::getTotalNumChars() throw()
  38551. {
  38552. if (totalNumChars < 0)
  38553. {
  38554. totalNumChars = 0;
  38555. for (int i = sections.size(); --i >= 0;)
  38556. totalNumChars += ((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  38557. }
  38558. return totalNumChars;
  38559. }
  38560. bool TextEditor::isEmpty() const throw()
  38561. {
  38562. if (totalNumChars != 0)
  38563. {
  38564. for (int i = sections.size(); --i >= 0;)
  38565. if (((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength() > 0)
  38566. return false;
  38567. }
  38568. return true;
  38569. }
  38570. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const throw()
  38571. {
  38572. const float wordWrapWidth = getWordWrapWidth();
  38573. if (wordWrapWidth > 0 && sections.size() > 0)
  38574. {
  38575. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  38576. i.getCharPosition (index, cx, cy, lineHeight);
  38577. }
  38578. else
  38579. {
  38580. cx = cy = 0;
  38581. lineHeight = currentFont.getHeight();
  38582. }
  38583. }
  38584. int TextEditor::indexAtPosition (const float x, const float y) throw()
  38585. {
  38586. const float wordWrapWidth = getWordWrapWidth();
  38587. if (wordWrapWidth > 0)
  38588. {
  38589. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  38590. while (i.next())
  38591. {
  38592. if (i.lineY + getHeight() > y)
  38593. i.updateLineHeight();
  38594. if (i.lineY + i.lineHeight > y)
  38595. {
  38596. if (i.lineY > y)
  38597. return jmax (0, i.indexInText - 1);
  38598. if (i.atomX >= x)
  38599. return i.indexInText;
  38600. if (x < i.atomRight)
  38601. return i.xToIndex (x);
  38602. }
  38603. }
  38604. }
  38605. return getTotalNumChars();
  38606. }
  38607. static int getCharacterCategory (const tchar character) throw()
  38608. {
  38609. return CharacterFunctions::isLetterOrDigit (character)
  38610. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  38611. }
  38612. int TextEditor::findWordBreakAfter (const int position) const throw()
  38613. {
  38614. const String t (getTextSubstring (position, position + 512));
  38615. const int totalLength = t.length();
  38616. int i = 0;
  38617. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  38618. ++i;
  38619. const int type = getCharacterCategory (t[i]);
  38620. while (i < totalLength && type == getCharacterCategory (t[i]))
  38621. ++i;
  38622. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  38623. ++i;
  38624. return position + i;
  38625. }
  38626. int TextEditor::findWordBreakBefore (const int position) const throw()
  38627. {
  38628. if (position <= 0)
  38629. return 0;
  38630. const int startOfBuffer = jmax (0, position - 512);
  38631. const String t (getTextSubstring (startOfBuffer, position));
  38632. int i = position - startOfBuffer;
  38633. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  38634. --i;
  38635. if (i > 0)
  38636. {
  38637. const int type = getCharacterCategory (t [i - 1]);
  38638. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  38639. --i;
  38640. }
  38641. jassert (startOfBuffer + i >= 0);
  38642. return startOfBuffer + i;
  38643. }
  38644. void TextEditor::splitSection (const int sectionIndex,
  38645. const int charToSplitAt) throw()
  38646. {
  38647. jassert (sections[sectionIndex] != 0);
  38648. sections.insert (sectionIndex + 1,
  38649. ((UniformTextSection*) sections.getUnchecked (sectionIndex))
  38650. ->split (charToSplitAt, passwordCharacter));
  38651. }
  38652. void TextEditor::coalesceSimilarSections() throw()
  38653. {
  38654. for (int i = 0; i < sections.size() - 1; ++i)
  38655. {
  38656. UniformTextSection* const s1 = (UniformTextSection*) (sections.getUnchecked (i));
  38657. UniformTextSection* const s2 = (UniformTextSection*) (sections.getUnchecked (i + 1));
  38658. if (s1->font == s2->font
  38659. && s1->colour == s2->colour)
  38660. {
  38661. s1->append (*s2, passwordCharacter);
  38662. sections.remove (i + 1);
  38663. delete s2;
  38664. --i;
  38665. }
  38666. }
  38667. }
  38668. END_JUCE_NAMESPACE
  38669. /********* End of inlined file: juce_TextEditor.cpp *********/
  38670. /********* Start of inlined file: juce_Toolbar.cpp *********/
  38671. BEGIN_JUCE_NAMESPACE
  38672. const tchar* const Toolbar::toolbarDragDescriptor = T("_toolbarItem_");
  38673. class ToolbarSpacerComp : public ToolbarItemComponent
  38674. {
  38675. public:
  38676. ToolbarSpacerComp (const int itemId, const float fixedSize_, const bool drawBar_)
  38677. : ToolbarItemComponent (itemId, String::empty, false),
  38678. fixedSize (fixedSize_),
  38679. drawBar (drawBar_)
  38680. {
  38681. }
  38682. ~ToolbarSpacerComp()
  38683. {
  38684. }
  38685. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  38686. int& preferredSize, int& minSize, int& maxSize)
  38687. {
  38688. if (fixedSize <= 0)
  38689. {
  38690. preferredSize = toolbarThickness * 2;
  38691. minSize = 4;
  38692. maxSize = 32768;
  38693. }
  38694. else
  38695. {
  38696. maxSize = roundFloatToInt (toolbarThickness * fixedSize);
  38697. minSize = drawBar ? maxSize : jmin (4, maxSize);
  38698. preferredSize = maxSize;
  38699. if (getEditingMode() == editableOnPalette)
  38700. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  38701. }
  38702. return true;
  38703. }
  38704. void paintButtonArea (Graphics&, int, int, bool, bool)
  38705. {
  38706. }
  38707. void contentAreaChanged (const Rectangle&)
  38708. {
  38709. }
  38710. int getResizeOrder() const throw()
  38711. {
  38712. return fixedSize <= 0 ? 0 : 1;
  38713. }
  38714. void paint (Graphics& g)
  38715. {
  38716. const int w = getWidth();
  38717. const int h = getHeight();
  38718. if (drawBar)
  38719. {
  38720. g.setColour (findColour (Toolbar::separatorColourId, true));
  38721. const float thickness = 0.2f;
  38722. if (isToolbarVertical())
  38723. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  38724. else
  38725. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  38726. }
  38727. if (getEditingMode() != normalMode && ! drawBar)
  38728. {
  38729. g.setColour (findColour (Toolbar::separatorColourId, true));
  38730. const int indentX = jmin (2, (w - 3) / 2);
  38731. const int indentY = jmin (2, (h - 3) / 2);
  38732. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  38733. if (fixedSize <= 0)
  38734. {
  38735. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  38736. if (isToolbarVertical())
  38737. {
  38738. x1 = w * 0.5f;
  38739. y1 = h * 0.4f;
  38740. x2 = x1;
  38741. y2 = indentX * 2.0f;
  38742. x3 = x1;
  38743. y3 = h * 0.6f;
  38744. x4 = x1;
  38745. y4 = h - y2;
  38746. hw = w * 0.15f;
  38747. hl = w * 0.2f;
  38748. }
  38749. else
  38750. {
  38751. x1 = w * 0.4f;
  38752. y1 = h * 0.5f;
  38753. x2 = indentX * 2.0f;
  38754. y2 = y1;
  38755. x3 = w * 0.6f;
  38756. y3 = y1;
  38757. x4 = w - x2;
  38758. y4 = y1;
  38759. hw = h * 0.15f;
  38760. hl = h * 0.2f;
  38761. }
  38762. Path p;
  38763. p.addArrow (x1, y1, x2, y2, 1.5f, hw, hl);
  38764. p.addArrow (x3, y3, x4, y4, 1.5f, hw, hl);
  38765. g.fillPath (p);
  38766. }
  38767. }
  38768. }
  38769. juce_UseDebuggingNewOperator
  38770. private:
  38771. const float fixedSize;
  38772. const bool drawBar;
  38773. ToolbarSpacerComp (const ToolbarSpacerComp&);
  38774. const ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  38775. };
  38776. class MissingItemsComponent : public PopupMenuCustomComponent
  38777. {
  38778. public:
  38779. MissingItemsComponent (Toolbar& owner_, const int height_)
  38780. : PopupMenuCustomComponent (true),
  38781. owner (owner_),
  38782. height (height_)
  38783. {
  38784. for (int i = owner_.items.size(); --i >= 0;)
  38785. {
  38786. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  38787. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  38788. {
  38789. oldIndexes.insert (0, i);
  38790. addAndMakeVisible (tc, 0);
  38791. }
  38792. }
  38793. layout (400);
  38794. }
  38795. ~MissingItemsComponent()
  38796. {
  38797. // deleting the toolbar while its menu it open??
  38798. jassert (owner.isValidComponent());
  38799. for (int i = 0; i < getNumChildComponents(); ++i)
  38800. {
  38801. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  38802. if (tc != 0)
  38803. {
  38804. tc->setVisible (false);
  38805. const int index = oldIndexes.remove (i);
  38806. owner.addChildComponent (tc, index);
  38807. --i;
  38808. }
  38809. }
  38810. owner.resized();
  38811. }
  38812. void layout (const int preferredWidth)
  38813. {
  38814. const int indent = 8;
  38815. int x = indent;
  38816. int y = indent;
  38817. int maxX = 0;
  38818. for (int i = 0; i < getNumChildComponents(); ++i)
  38819. {
  38820. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  38821. if (tc != 0)
  38822. {
  38823. int preferredSize = 1, minSize = 1, maxSize = 1;
  38824. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  38825. {
  38826. if (x + preferredSize > preferredWidth && x > indent)
  38827. {
  38828. x = indent;
  38829. y += height;
  38830. }
  38831. tc->setBounds (x, y, preferredSize, height);
  38832. x += preferredSize;
  38833. maxX = jmax (maxX, x);
  38834. }
  38835. }
  38836. }
  38837. setSize (maxX + 8, y + height + 8);
  38838. }
  38839. void getIdealSize (int& idealWidth, int& idealHeight)
  38840. {
  38841. idealWidth = getWidth();
  38842. idealHeight = getHeight();
  38843. }
  38844. juce_UseDebuggingNewOperator
  38845. private:
  38846. Toolbar& owner;
  38847. const int height;
  38848. Array <int> oldIndexes;
  38849. MissingItemsComponent (const MissingItemsComponent&);
  38850. const MissingItemsComponent& operator= (const MissingItemsComponent&);
  38851. };
  38852. Toolbar::Toolbar()
  38853. : vertical (false),
  38854. isEditingActive (false),
  38855. toolbarStyle (Toolbar::iconsOnly)
  38856. {
  38857. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  38858. missingItemsButton->setAlwaysOnTop (true);
  38859. missingItemsButton->addButtonListener (this);
  38860. }
  38861. Toolbar::~Toolbar()
  38862. {
  38863. animator.cancelAllAnimations (true);
  38864. deleteAllChildren();
  38865. }
  38866. void Toolbar::setVertical (const bool shouldBeVertical)
  38867. {
  38868. if (vertical != shouldBeVertical)
  38869. {
  38870. vertical = shouldBeVertical;
  38871. resized();
  38872. }
  38873. }
  38874. void Toolbar::clear()
  38875. {
  38876. for (int i = items.size(); --i >= 0;)
  38877. {
  38878. ToolbarItemComponent* const tc = items.getUnchecked(i);
  38879. items.remove (i);
  38880. delete tc;
  38881. }
  38882. resized();
  38883. }
  38884. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  38885. {
  38886. if (itemId == ToolbarItemFactory::separatorBarId)
  38887. return new ToolbarSpacerComp (itemId, 0.1f, true);
  38888. else if (itemId == ToolbarItemFactory::spacerId)
  38889. return new ToolbarSpacerComp (itemId, 0.5f, false);
  38890. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  38891. return new ToolbarSpacerComp (itemId, 0, false);
  38892. return factory.createItem (itemId);
  38893. }
  38894. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  38895. const int itemId,
  38896. const int insertIndex)
  38897. {
  38898. // An ID can't be zero - this might indicate a mistake somewhere?
  38899. jassert (itemId != 0);
  38900. ToolbarItemComponent* const tc = createItem (factory, itemId);
  38901. if (tc != 0)
  38902. {
  38903. #ifdef JUCE_DEBUG
  38904. Array <int> allowedIds;
  38905. factory.getAllToolbarItemIds (allowedIds);
  38906. // If your factory can create an item for a given ID, it must also return
  38907. // that ID from its getAllToolbarItemIds() method!
  38908. jassert (allowedIds.contains (itemId));
  38909. #endif
  38910. items.insert (insertIndex, tc);
  38911. addAndMakeVisible (tc, insertIndex);
  38912. }
  38913. }
  38914. void Toolbar::addItem (ToolbarItemFactory& factory,
  38915. const int itemId,
  38916. const int insertIndex)
  38917. {
  38918. addItemInternal (factory, itemId, insertIndex);
  38919. resized();
  38920. }
  38921. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  38922. {
  38923. Array <int> ids;
  38924. factoryToUse.getDefaultItemSet (ids);
  38925. clear();
  38926. for (int i = 0; i < ids.size(); ++i)
  38927. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  38928. resized();
  38929. }
  38930. void Toolbar::removeToolbarItem (const int itemIndex)
  38931. {
  38932. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  38933. if (tc != 0)
  38934. {
  38935. items.removeValue (tc);
  38936. delete tc;
  38937. resized();
  38938. }
  38939. }
  38940. int Toolbar::getNumItems() const throw()
  38941. {
  38942. return items.size();
  38943. }
  38944. int Toolbar::getItemId (const int itemIndex) const throw()
  38945. {
  38946. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  38947. return tc != 0 ? tc->getItemId() : 0;
  38948. }
  38949. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  38950. {
  38951. return items [itemIndex];
  38952. }
  38953. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  38954. {
  38955. for (;;)
  38956. {
  38957. index += delta;
  38958. ToolbarItemComponent* const tc = getItemComponent (index);
  38959. if (tc == 0)
  38960. break;
  38961. if (tc->isActive)
  38962. return tc;
  38963. }
  38964. return 0;
  38965. }
  38966. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  38967. {
  38968. if (toolbarStyle != newStyle)
  38969. {
  38970. toolbarStyle = newStyle;
  38971. updateAllItemPositions (false);
  38972. }
  38973. }
  38974. const String Toolbar::toString() const
  38975. {
  38976. String s (T("TB:"));
  38977. for (int i = 0; i < getNumItems(); ++i)
  38978. s << getItemId(i) << T(' ');
  38979. return s.trimEnd();
  38980. }
  38981. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  38982. const String& savedVersion)
  38983. {
  38984. if (! savedVersion.startsWith (T("TB:")))
  38985. return false;
  38986. StringArray tokens;
  38987. tokens.addTokens (savedVersion.substring (3), false);
  38988. clear();
  38989. for (int i = 0; i < tokens.size(); ++i)
  38990. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  38991. resized();
  38992. return true;
  38993. }
  38994. void Toolbar::paint (Graphics& g)
  38995. {
  38996. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  38997. }
  38998. int Toolbar::getThickness() const throw()
  38999. {
  39000. return vertical ? getWidth() : getHeight();
  39001. }
  39002. int Toolbar::getLength() const throw()
  39003. {
  39004. return vertical ? getHeight() : getWidth();
  39005. }
  39006. void Toolbar::setEditingActive (const bool active)
  39007. {
  39008. if (isEditingActive != active)
  39009. {
  39010. isEditingActive = active;
  39011. updateAllItemPositions (false);
  39012. }
  39013. }
  39014. void Toolbar::resized()
  39015. {
  39016. updateAllItemPositions (false);
  39017. }
  39018. void Toolbar::updateAllItemPositions (const bool animate)
  39019. {
  39020. if (getWidth() > 0 && getHeight() > 0)
  39021. {
  39022. StretchableObjectResizer resizer;
  39023. int i;
  39024. for (i = 0; i < items.size(); ++i)
  39025. {
  39026. ToolbarItemComponent* const tc = items.getUnchecked(i);
  39027. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  39028. : ToolbarItemComponent::normalMode);
  39029. tc->setStyle (toolbarStyle);
  39030. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  39031. int preferredSize = 1, minSize = 1, maxSize = 1;
  39032. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  39033. preferredSize, minSize, maxSize))
  39034. {
  39035. tc->isActive = true;
  39036. resizer.addItem (preferredSize, minSize, maxSize,
  39037. spacer != 0 ? spacer->getResizeOrder() : 2);
  39038. }
  39039. else
  39040. {
  39041. tc->isActive = false;
  39042. tc->setVisible (false);
  39043. }
  39044. }
  39045. resizer.resizeToFit (getLength());
  39046. int totalLength = 0;
  39047. for (i = 0; i < resizer.getNumItems(); ++i)
  39048. totalLength += (int) resizer.getItemSize (i);
  39049. const bool itemsOffTheEnd = totalLength > getLength();
  39050. const int extrasButtonSize = getThickness() / 2;
  39051. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  39052. missingItemsButton->setVisible (itemsOffTheEnd);
  39053. missingItemsButton->setEnabled (! isEditingActive);
  39054. if (vertical)
  39055. missingItemsButton->setCentrePosition (getWidth() / 2,
  39056. getHeight() - 4 - extrasButtonSize / 2);
  39057. else
  39058. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  39059. getHeight() / 2);
  39060. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  39061. : missingItemsButton->getX()) - 4
  39062. : getLength();
  39063. int pos = 0, activeIndex = 0;
  39064. for (i = 0; i < items.size(); ++i)
  39065. {
  39066. ToolbarItemComponent* const tc = items.getUnchecked(i);
  39067. if (tc->isActive)
  39068. {
  39069. const int size = (int) resizer.getItemSize (activeIndex++);
  39070. Rectangle newBounds;
  39071. if (vertical)
  39072. newBounds.setBounds (0, pos, getWidth(), size);
  39073. else
  39074. newBounds.setBounds (pos, 0, size, getHeight());
  39075. if (animate)
  39076. {
  39077. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  39078. }
  39079. else
  39080. {
  39081. animator.cancelAnimation (tc, false);
  39082. tc->setBounds (newBounds);
  39083. }
  39084. pos += size;
  39085. tc->setVisible (pos <= maxLength
  39086. && ((! tc->isBeingDragged)
  39087. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  39088. }
  39089. }
  39090. }
  39091. }
  39092. void Toolbar::buttonClicked (Button*)
  39093. {
  39094. jassert (missingItemsButton->isShowing());
  39095. if (missingItemsButton->isShowing())
  39096. {
  39097. PopupMenu m;
  39098. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  39099. m.showAt (missingItemsButton);
  39100. }
  39101. }
  39102. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  39103. Component* /*sourceComponent*/)
  39104. {
  39105. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  39106. }
  39107. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  39108. {
  39109. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  39110. if (tc != 0)
  39111. {
  39112. if (getNumItems() == 0)
  39113. {
  39114. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  39115. {
  39116. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  39117. if (palette != 0)
  39118. palette->replaceComponent (tc);
  39119. }
  39120. else
  39121. {
  39122. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  39123. }
  39124. items.add (tc);
  39125. addChildComponent (tc);
  39126. updateAllItemPositions (false);
  39127. }
  39128. else
  39129. {
  39130. for (int i = getNumItems(); --i >= 0;)
  39131. {
  39132. int currentIndex = getIndexOfChildComponent (tc);
  39133. if (currentIndex < 0)
  39134. {
  39135. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  39136. {
  39137. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  39138. if (palette != 0)
  39139. palette->replaceComponent (tc);
  39140. }
  39141. else
  39142. {
  39143. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  39144. }
  39145. items.add (tc);
  39146. addChildComponent (tc);
  39147. currentIndex = getIndexOfChildComponent (tc);
  39148. updateAllItemPositions (true);
  39149. }
  39150. int newIndex = currentIndex;
  39151. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  39152. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  39153. const Rectangle current (animator.getComponentDestination (getChildComponent (newIndex)));
  39154. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  39155. if (prev != 0)
  39156. {
  39157. const Rectangle previousPos (animator.getComponentDestination (prev));
  39158. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  39159. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  39160. {
  39161. newIndex = getIndexOfChildComponent (prev);
  39162. }
  39163. }
  39164. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  39165. if (next != 0)
  39166. {
  39167. const Rectangle nextPos (animator.getComponentDestination (next));
  39168. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  39169. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  39170. {
  39171. newIndex = getIndexOfChildComponent (next) + 1;
  39172. }
  39173. }
  39174. if (newIndex != currentIndex)
  39175. {
  39176. items.removeValue (tc);
  39177. removeChildComponent (tc);
  39178. addChildComponent (tc, newIndex);
  39179. items.insert (newIndex, tc);
  39180. updateAllItemPositions (true);
  39181. }
  39182. else
  39183. {
  39184. break;
  39185. }
  39186. }
  39187. }
  39188. }
  39189. }
  39190. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  39191. {
  39192. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  39193. if (tc != 0)
  39194. {
  39195. if (isParentOf (tc))
  39196. {
  39197. items.removeValue (tc);
  39198. removeChildComponent (tc);
  39199. updateAllItemPositions (true);
  39200. }
  39201. }
  39202. }
  39203. void Toolbar::itemDropped (const String&, Component*, int, int)
  39204. {
  39205. }
  39206. void Toolbar::mouseDown (const MouseEvent& e)
  39207. {
  39208. if (e.mods.isPopupMenu())
  39209. {
  39210. }
  39211. }
  39212. class ToolbarCustomisationDialog : public DialogWindow
  39213. {
  39214. public:
  39215. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  39216. Toolbar* const toolbar_,
  39217. const int optionFlags)
  39218. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  39219. toolbar (toolbar_)
  39220. {
  39221. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  39222. setResizable (true, true);
  39223. setResizeLimits (400, 300, 1500, 1000);
  39224. positionNearBar();
  39225. }
  39226. ~ToolbarCustomisationDialog()
  39227. {
  39228. setContentComponent (0, true);
  39229. }
  39230. void closeButtonPressed()
  39231. {
  39232. setVisible (false);
  39233. }
  39234. bool canModalEventBeSentToComponent (const Component* comp)
  39235. {
  39236. return toolbar->isParentOf (comp);
  39237. }
  39238. void positionNearBar()
  39239. {
  39240. const Rectangle screenSize (toolbar->getParentMonitorArea());
  39241. const int tbx = toolbar->getScreenX();
  39242. const int tby = toolbar->getScreenY();
  39243. const int gap = 8;
  39244. int x, y;
  39245. if (toolbar->isVertical())
  39246. {
  39247. y = tby;
  39248. if (tbx > screenSize.getCentreX())
  39249. x = tbx - getWidth() - gap;
  39250. else
  39251. x = tbx + toolbar->getWidth() + gap;
  39252. }
  39253. else
  39254. {
  39255. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  39256. if (tby > screenSize.getCentreY())
  39257. y = tby - getHeight() - gap;
  39258. else
  39259. y = tby + toolbar->getHeight() + gap;
  39260. }
  39261. setTopLeftPosition (x, y);
  39262. }
  39263. private:
  39264. Toolbar* const toolbar;
  39265. class CustomiserPanel : public Component,
  39266. private ComboBoxListener,
  39267. private ButtonListener
  39268. {
  39269. public:
  39270. CustomiserPanel (ToolbarItemFactory& factory_,
  39271. Toolbar* const toolbar_,
  39272. const int optionFlags)
  39273. : factory (factory_),
  39274. toolbar (toolbar_),
  39275. styleBox (0),
  39276. defaultButton (0)
  39277. {
  39278. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  39279. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  39280. | Toolbar::allowIconsWithTextChoice
  39281. | Toolbar::allowTextOnlyChoice)) != 0)
  39282. {
  39283. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  39284. styleBox->setEditableText (false);
  39285. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  39286. styleBox->addItem (TRANS("Show icons only"), 1);
  39287. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  39288. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  39289. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  39290. styleBox->addItem (TRANS("Show descriptions only"), 3);
  39291. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  39292. styleBox->setSelectedId (1);
  39293. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  39294. styleBox->setSelectedId (2);
  39295. else if (toolbar_->getStyle() == Toolbar::textOnly)
  39296. styleBox->setSelectedId (3);
  39297. styleBox->addListener (this);
  39298. }
  39299. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  39300. {
  39301. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  39302. defaultButton->addButtonListener (this);
  39303. }
  39304. addAndMakeVisible (instructions = new Label (String::empty,
  39305. TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\nItems on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")));
  39306. instructions->setFont (Font (13.0f));
  39307. setSize (500, 300);
  39308. }
  39309. ~CustomiserPanel()
  39310. {
  39311. deleteAllChildren();
  39312. }
  39313. void comboBoxChanged (ComboBox*)
  39314. {
  39315. if (styleBox->getSelectedId() == 1)
  39316. toolbar->setStyle (Toolbar::iconsOnly);
  39317. else if (styleBox->getSelectedId() == 2)
  39318. toolbar->setStyle (Toolbar::iconsWithText);
  39319. else if (styleBox->getSelectedId() == 3)
  39320. toolbar->setStyle (Toolbar::textOnly);
  39321. palette->resized(); // to make it update the styles
  39322. }
  39323. void buttonClicked (Button*)
  39324. {
  39325. toolbar->addDefaultItems (factory);
  39326. }
  39327. void paint (Graphics& g)
  39328. {
  39329. Colour background;
  39330. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  39331. if (dw != 0)
  39332. background = dw->getBackgroundColour();
  39333. g.setColour (background.contrasting().withAlpha (0.3f));
  39334. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  39335. }
  39336. void resized()
  39337. {
  39338. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  39339. if (styleBox != 0)
  39340. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  39341. if (defaultButton != 0)
  39342. {
  39343. defaultButton->changeWidthToFitText (22);
  39344. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  39345. }
  39346. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  39347. }
  39348. private:
  39349. ToolbarItemFactory& factory;
  39350. Toolbar* const toolbar;
  39351. Label* instructions;
  39352. ToolbarItemPalette* palette;
  39353. ComboBox* styleBox;
  39354. TextButton* defaultButton;
  39355. };
  39356. };
  39357. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  39358. {
  39359. setEditingActive (true);
  39360. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  39361. dw.runModalLoop();
  39362. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  39363. setEditingActive (false);
  39364. }
  39365. END_JUCE_NAMESPACE
  39366. /********* End of inlined file: juce_Toolbar.cpp *********/
  39367. /********* Start of inlined file: juce_ToolbarItemComponent.cpp *********/
  39368. BEGIN_JUCE_NAMESPACE
  39369. ToolbarItemFactory::ToolbarItemFactory()
  39370. {
  39371. }
  39372. ToolbarItemFactory::~ToolbarItemFactory()
  39373. {
  39374. }
  39375. class ItemDragAndDropOverlayComponent : public Component
  39376. {
  39377. public:
  39378. ItemDragAndDropOverlayComponent()
  39379. : isDragging (false)
  39380. {
  39381. setAlwaysOnTop (true);
  39382. setRepaintsOnMouseActivity (true);
  39383. setMouseCursor (MouseCursor::DraggingHandCursor);
  39384. }
  39385. ~ItemDragAndDropOverlayComponent()
  39386. {
  39387. }
  39388. void paint (Graphics& g)
  39389. {
  39390. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39391. if (isMouseOverOrDragging()
  39392. && tc != 0
  39393. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  39394. {
  39395. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  39396. g.drawRect (0, 0, getWidth(), getHeight(),
  39397. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  39398. }
  39399. }
  39400. void mouseDown (const MouseEvent& e)
  39401. {
  39402. isDragging = false;
  39403. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39404. if (tc != 0)
  39405. {
  39406. tc->dragOffsetX = e.x;
  39407. tc->dragOffsetY = e.y;
  39408. }
  39409. }
  39410. void mouseDrag (const MouseEvent& e)
  39411. {
  39412. if (! (isDragging || e.mouseWasClicked()))
  39413. {
  39414. isDragging = true;
  39415. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  39416. if (dnd != 0)
  39417. {
  39418. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), 0, true);
  39419. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39420. if (tc != 0)
  39421. {
  39422. tc->isBeingDragged = true;
  39423. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  39424. tc->setVisible (false);
  39425. }
  39426. }
  39427. }
  39428. }
  39429. void mouseUp (const MouseEvent&)
  39430. {
  39431. isDragging = false;
  39432. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39433. if (tc != 0)
  39434. {
  39435. tc->isBeingDragged = false;
  39436. Toolbar* const tb = tc->getToolbar();
  39437. if (tb != 0)
  39438. tb->updateAllItemPositions (true);
  39439. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  39440. delete tc;
  39441. }
  39442. }
  39443. void parentSizeChanged()
  39444. {
  39445. setBounds (0, 0, getParentWidth(), getParentHeight());
  39446. }
  39447. juce_UseDebuggingNewOperator
  39448. private:
  39449. bool isDragging;
  39450. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  39451. const ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  39452. };
  39453. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  39454. const String& labelText,
  39455. const bool isBeingUsedAsAButton_)
  39456. : Button (labelText),
  39457. itemId (itemId_),
  39458. mode (normalMode),
  39459. toolbarStyle (Toolbar::iconsOnly),
  39460. overlayComp (0),
  39461. dragOffsetX (0),
  39462. dragOffsetY (0),
  39463. isActive (true),
  39464. isBeingDragged (false),
  39465. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  39466. {
  39467. // Your item ID can't be 0!
  39468. jassert (itemId_ != 0);
  39469. }
  39470. ToolbarItemComponent::~ToolbarItemComponent()
  39471. {
  39472. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  39473. delete overlayComp;
  39474. }
  39475. Toolbar* ToolbarItemComponent::getToolbar() const
  39476. {
  39477. return dynamic_cast <Toolbar*> (getParentComponent());
  39478. }
  39479. bool ToolbarItemComponent::isToolbarVertical() const
  39480. {
  39481. const Toolbar* const t = getToolbar();
  39482. return t != 0 && t->isVertical();
  39483. }
  39484. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  39485. {
  39486. if (toolbarStyle != newStyle)
  39487. {
  39488. toolbarStyle = newStyle;
  39489. repaint();
  39490. resized();
  39491. }
  39492. }
  39493. void ToolbarItemComponent::paintButton (Graphics& g, bool isMouseOver, bool isMouseDown)
  39494. {
  39495. if (isBeingUsedAsAButton)
  39496. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  39497. isMouseOver, isMouseDown, *this);
  39498. if (toolbarStyle != Toolbar::iconsOnly)
  39499. {
  39500. const int indent = contentArea.getX();
  39501. int y = indent;
  39502. int h = getHeight() - indent * 2;
  39503. if (toolbarStyle == Toolbar::iconsWithText)
  39504. {
  39505. y = contentArea.getBottom() + indent / 2;
  39506. h -= contentArea.getHeight();
  39507. }
  39508. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  39509. getButtonText(), *this);
  39510. }
  39511. if (! contentArea.isEmpty())
  39512. {
  39513. g.saveState();
  39514. g.setOrigin (contentArea.getX(), contentArea.getY());
  39515. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  39516. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), isMouseOver, isMouseDown);
  39517. g.restoreState();
  39518. }
  39519. }
  39520. void ToolbarItemComponent::resized()
  39521. {
  39522. if (toolbarStyle != Toolbar::textOnly)
  39523. {
  39524. const int indent = jmin (proportionOfWidth (0.08f),
  39525. proportionOfHeight (0.08f));
  39526. contentArea = Rectangle (indent, indent,
  39527. getWidth() - indent * 2,
  39528. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  39529. : (getHeight() - indent * 2));
  39530. }
  39531. else
  39532. {
  39533. contentArea = Rectangle();
  39534. }
  39535. contentAreaChanged (contentArea);
  39536. }
  39537. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  39538. {
  39539. if (mode != newMode)
  39540. {
  39541. mode = newMode;
  39542. repaint();
  39543. if (mode == normalMode)
  39544. {
  39545. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  39546. delete overlayComp;
  39547. overlayComp = 0;
  39548. }
  39549. else if (overlayComp == 0)
  39550. {
  39551. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  39552. overlayComp->parentSizeChanged();
  39553. }
  39554. resized();
  39555. }
  39556. }
  39557. END_JUCE_NAMESPACE
  39558. /********* End of inlined file: juce_ToolbarItemComponent.cpp *********/
  39559. /********* Start of inlined file: juce_ToolbarItemPalette.cpp *********/
  39560. BEGIN_JUCE_NAMESPACE
  39561. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  39562. Toolbar* const toolbar_)
  39563. : factory (factory_),
  39564. toolbar (toolbar_)
  39565. {
  39566. Component* const itemHolder = new Component();
  39567. Array <int> allIds;
  39568. factory_.getAllToolbarItemIds (allIds);
  39569. for (int i = 0; i < allIds.size(); ++i)
  39570. {
  39571. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  39572. jassert (tc != 0);
  39573. if (tc != 0)
  39574. {
  39575. itemHolder->addAndMakeVisible (tc);
  39576. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  39577. }
  39578. }
  39579. viewport = new Viewport();
  39580. viewport->setViewedComponent (itemHolder);
  39581. addAndMakeVisible (viewport);
  39582. }
  39583. ToolbarItemPalette::~ToolbarItemPalette()
  39584. {
  39585. viewport->getViewedComponent()->deleteAllChildren();
  39586. deleteAllChildren();
  39587. }
  39588. void ToolbarItemPalette::resized()
  39589. {
  39590. viewport->setBoundsInset (BorderSize (1));
  39591. Component* const itemHolder = viewport->getViewedComponent();
  39592. const int indent = 8;
  39593. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  39594. const int height = toolbar->getThickness();
  39595. int x = indent;
  39596. int y = indent;
  39597. int maxX = 0;
  39598. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  39599. {
  39600. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  39601. if (tc != 0)
  39602. {
  39603. tc->setStyle (toolbar->getStyle());
  39604. int preferredSize = 1, minSize = 1, maxSize = 1;
  39605. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  39606. {
  39607. if (x + preferredSize > preferredWidth && x > indent)
  39608. {
  39609. x = indent;
  39610. y += height;
  39611. }
  39612. tc->setBounds (x, y, preferredSize, height);
  39613. x += preferredSize + 8;
  39614. maxX = jmax (maxX, x);
  39615. }
  39616. }
  39617. }
  39618. itemHolder->setSize (maxX, y + height + 8);
  39619. }
  39620. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  39621. {
  39622. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  39623. jassert (tc != 0);
  39624. if (tc != 0)
  39625. {
  39626. tc->setBounds (comp->getBounds());
  39627. tc->setStyle (toolbar->getStyle());
  39628. tc->setEditingMode (comp->getEditingMode());
  39629. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  39630. }
  39631. }
  39632. END_JUCE_NAMESPACE
  39633. /********* End of inlined file: juce_ToolbarItemPalette.cpp *********/
  39634. /********* Start of inlined file: juce_TreeView.cpp *********/
  39635. BEGIN_JUCE_NAMESPACE
  39636. class TreeViewContentComponent : public Component
  39637. {
  39638. public:
  39639. TreeViewContentComponent (TreeView* const owner_)
  39640. : owner (owner_),
  39641. isDragging (false)
  39642. {
  39643. }
  39644. ~TreeViewContentComponent()
  39645. {
  39646. deleteAllChildren();
  39647. }
  39648. void mouseDown (const MouseEvent& e)
  39649. {
  39650. isDragging = false;
  39651. needSelectionOnMouseUp = false;
  39652. Rectangle pos;
  39653. TreeViewItem* const item = findItemAt (e.y, pos);
  39654. if (item != 0 && e.x >= pos.getX())
  39655. {
  39656. if (! owner->isMultiSelectEnabled())
  39657. item->setSelected (true, true);
  39658. else if (item->isSelected())
  39659. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  39660. else
  39661. selectBasedOnModifiers (item, e.mods);
  39662. MouseEvent e2 (e);
  39663. e2.x -= pos.getX();
  39664. e2.y -= pos.getY();
  39665. item->itemClicked (e2);
  39666. }
  39667. }
  39668. void mouseUp (const MouseEvent& e)
  39669. {
  39670. Rectangle pos;
  39671. TreeViewItem* const item = findItemAt (e.y, pos);
  39672. if (item != 0 && e.mouseWasClicked())
  39673. {
  39674. if (needSelectionOnMouseUp)
  39675. {
  39676. selectBasedOnModifiers (item, e.mods);
  39677. }
  39678. else if (e.mouseWasClicked())
  39679. {
  39680. if (e.x >= pos.getX() - owner->getIndentSize()
  39681. && e.x < pos.getX())
  39682. {
  39683. item->setOpen (! item->isOpen());
  39684. }
  39685. }
  39686. }
  39687. }
  39688. void mouseDoubleClick (const MouseEvent& e)
  39689. {
  39690. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  39691. {
  39692. Rectangle pos;
  39693. TreeViewItem* const item = findItemAt (e.y, pos);
  39694. if (item != 0 && e.x >= pos.getX())
  39695. {
  39696. MouseEvent e2 (e);
  39697. e2.x -= pos.getX();
  39698. e2.y -= pos.getY();
  39699. item->itemDoubleClicked (e2);
  39700. }
  39701. }
  39702. }
  39703. void mouseDrag (const MouseEvent& e)
  39704. {
  39705. if (isEnabled() && ! (e.mouseWasClicked() || isDragging))
  39706. {
  39707. isDragging = true;
  39708. Rectangle pos;
  39709. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  39710. if (item != 0 && e.getMouseDownX() >= pos.getX())
  39711. {
  39712. const String dragDescription (item->getDragSourceDescription());
  39713. if (dragDescription.isNotEmpty())
  39714. {
  39715. DragAndDropContainer* const dragContainer
  39716. = DragAndDropContainer::findParentDragContainerFor (this);
  39717. if (dragContainer != 0)
  39718. {
  39719. pos.setSize (pos.getWidth(), item->itemHeight);
  39720. Image* dragImage = Component::createComponentSnapshot (pos, true);
  39721. dragImage->multiplyAllAlphas (0.6f);
  39722. dragContainer->startDragging (dragDescription, owner, dragImage, true);
  39723. }
  39724. else
  39725. {
  39726. // to be able to do a drag-and-drop operation, the treeview needs to
  39727. // be inside a component which is also a DragAndDropContainer.
  39728. jassertfalse
  39729. }
  39730. }
  39731. }
  39732. }
  39733. }
  39734. void paint (Graphics& g);
  39735. TreeViewItem* findItemAt (int y, Rectangle& itemPosition) const;
  39736. void updateComponents()
  39737. {
  39738. int xAdjust = 0, yAdjust = 0;
  39739. if ((! owner->rootItemVisible) && owner->rootItem != 0)
  39740. {
  39741. yAdjust = owner->rootItem->itemHeight;
  39742. xAdjust = owner->getIndentSize();
  39743. }
  39744. const int visibleTop = -getY();
  39745. const int visibleBottom = visibleTop + getParentHeight();
  39746. BitArray itemsToKeep;
  39747. TreeViewItem* item = owner->rootItem;
  39748. int y = -yAdjust;
  39749. while (item != 0 && y < visibleBottom)
  39750. {
  39751. y += item->itemHeight;
  39752. if (y >= visibleTop)
  39753. {
  39754. const int index = rowComponentIds.indexOf (item->uid);
  39755. if (index < 0)
  39756. {
  39757. Component* const comp = item->createItemComponent();
  39758. if (comp != 0)
  39759. {
  39760. addAndMakeVisible (comp);
  39761. itemsToKeep.setBit (rowComponentItems.size());
  39762. rowComponentItems.add (item);
  39763. rowComponentIds.add (item->uid);
  39764. rowComponents.add (comp);
  39765. }
  39766. }
  39767. else
  39768. {
  39769. itemsToKeep.setBit (index);
  39770. }
  39771. }
  39772. item = item->getNextVisibleItem (true);
  39773. }
  39774. for (int i = rowComponentItems.size(); --i >= 0;)
  39775. {
  39776. Component* const comp = (Component*) (rowComponents.getUnchecked(i));
  39777. bool keep = false;
  39778. if ((itemsToKeep[i] || (comp == Component::getComponentUnderMouse() && comp->isMouseButtonDown()))
  39779. && isParentOf (comp))
  39780. {
  39781. if (itemsToKeep[i])
  39782. {
  39783. const TreeViewItem* const item = (TreeViewItem*) rowComponentItems.getUnchecked(i);
  39784. Rectangle pos (item->getItemPosition (false));
  39785. pos.translate (-xAdjust, -yAdjust);
  39786. pos.setSize (pos.getWidth() + xAdjust, item->itemHeight);
  39787. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  39788. {
  39789. keep = true;
  39790. comp->setBounds (pos);
  39791. }
  39792. }
  39793. else
  39794. {
  39795. comp->setSize (0, 0);
  39796. }
  39797. }
  39798. if (! keep)
  39799. {
  39800. delete comp;
  39801. rowComponents.remove (i);
  39802. rowComponentIds.remove (i);
  39803. rowComponentItems.remove (i);
  39804. }
  39805. }
  39806. }
  39807. void resized()
  39808. {
  39809. owner->itemsChanged();
  39810. }
  39811. juce_UseDebuggingNewOperator
  39812. private:
  39813. TreeView* const owner;
  39814. VoidArray rowComponentItems;
  39815. Array <int> rowComponentIds;
  39816. VoidArray rowComponents;
  39817. bool isDragging, needSelectionOnMouseUp;
  39818. TreeViewContentComponent (const TreeViewContentComponent&);
  39819. const TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  39820. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  39821. {
  39822. TreeViewItem* firstSelected = 0;
  39823. if (modifiers.isShiftDown() && ((firstSelected = owner->getSelectedItem (0)) != 0))
  39824. {
  39825. TreeViewItem* const lastSelected = owner->getSelectedItem (owner->getNumSelectedItems() - 1);
  39826. jassert (lastSelected != 0);
  39827. int rowStart = firstSelected->getRowNumberInTree();
  39828. int rowEnd = lastSelected->getRowNumberInTree();
  39829. if (rowStart > rowEnd)
  39830. swapVariables (rowStart, rowEnd);
  39831. int ourRow = item->getRowNumberInTree();
  39832. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  39833. if (ourRow > otherEnd)
  39834. swapVariables (ourRow, otherEnd);
  39835. for (int i = ourRow; i <= otherEnd; ++i)
  39836. owner->getItemOnRow (i)->setSelected (true, false);
  39837. }
  39838. else
  39839. {
  39840. const bool cmd = modifiers.isCommandDown();
  39841. item->setSelected ((! cmd) || (! item->isSelected()), ! cmd);
  39842. }
  39843. }
  39844. };
  39845. class TreeViewport : public Viewport
  39846. {
  39847. public:
  39848. TreeViewport() throw() {}
  39849. ~TreeViewport() throw() {}
  39850. void updateComponents()
  39851. {
  39852. if (getViewedComponent() != 0)
  39853. ((TreeViewContentComponent*) getViewedComponent())->updateComponents();
  39854. repaint();
  39855. }
  39856. void visibleAreaChanged (int, int, int, int)
  39857. {
  39858. updateComponents();
  39859. }
  39860. juce_UseDebuggingNewOperator
  39861. private:
  39862. TreeViewport (const TreeViewport&);
  39863. const TreeViewport& operator= (const TreeViewport&);
  39864. };
  39865. TreeView::TreeView (const String& componentName)
  39866. : Component (componentName),
  39867. rootItem (0),
  39868. indentSize (24),
  39869. defaultOpenness (false),
  39870. needsRecalculating (true),
  39871. rootItemVisible (true),
  39872. multiSelectEnabled (false)
  39873. {
  39874. addAndMakeVisible (viewport = new TreeViewport());
  39875. viewport->setViewedComponent (new TreeViewContentComponent (this));
  39876. viewport->setWantsKeyboardFocus (false);
  39877. setWantsKeyboardFocus (true);
  39878. }
  39879. TreeView::~TreeView()
  39880. {
  39881. if (rootItem != 0)
  39882. rootItem->setOwnerView (0);
  39883. deleteAllChildren();
  39884. }
  39885. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  39886. {
  39887. if (rootItem != newRootItem)
  39888. {
  39889. if (newRootItem != 0)
  39890. {
  39891. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  39892. if (newRootItem->ownerView != 0)
  39893. newRootItem->ownerView->setRootItem (0);
  39894. }
  39895. if (rootItem != 0)
  39896. rootItem->setOwnerView (0);
  39897. rootItem = newRootItem;
  39898. if (newRootItem != 0)
  39899. newRootItem->setOwnerView (this);
  39900. needsRecalculating = true;
  39901. handleAsyncUpdate();
  39902. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  39903. {
  39904. rootItem->setOpen (false); // force a re-open
  39905. rootItem->setOpen (true);
  39906. }
  39907. }
  39908. }
  39909. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  39910. {
  39911. rootItemVisible = shouldBeVisible;
  39912. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  39913. {
  39914. rootItem->setOpen (false); // force a re-open
  39915. rootItem->setOpen (true);
  39916. }
  39917. itemsChanged();
  39918. }
  39919. void TreeView::colourChanged()
  39920. {
  39921. setOpaque (findColour (backgroundColourId).isOpaque());
  39922. repaint();
  39923. }
  39924. void TreeView::setIndentSize (const int newIndentSize)
  39925. {
  39926. if (indentSize != newIndentSize)
  39927. {
  39928. indentSize = newIndentSize;
  39929. resized();
  39930. }
  39931. }
  39932. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  39933. {
  39934. if (defaultOpenness != isOpenByDefault)
  39935. {
  39936. defaultOpenness = isOpenByDefault;
  39937. itemsChanged();
  39938. }
  39939. }
  39940. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  39941. {
  39942. multiSelectEnabled = canMultiSelect;
  39943. }
  39944. void TreeView::clearSelectedItems()
  39945. {
  39946. if (rootItem != 0)
  39947. rootItem->deselectAllRecursively();
  39948. }
  39949. int TreeView::getNumSelectedItems() const throw()
  39950. {
  39951. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  39952. }
  39953. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  39954. {
  39955. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  39956. }
  39957. int TreeView::getNumRowsInTree() const
  39958. {
  39959. if (rootItem != 0)
  39960. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  39961. return 0;
  39962. }
  39963. TreeViewItem* TreeView::getItemOnRow (int index) const
  39964. {
  39965. if (! rootItemVisible)
  39966. ++index;
  39967. if (rootItem != 0 && index >= 0)
  39968. return rootItem->getItemOnRow (index);
  39969. return 0;
  39970. }
  39971. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  39972. {
  39973. XmlElement* e = 0;
  39974. if (rootItem != 0)
  39975. {
  39976. e = rootItem->createXmlOpenness();
  39977. if (e != 0 && alsoIncludeScrollPosition)
  39978. e->setAttribute (T("scrollPos"), viewport->getViewPositionY());
  39979. }
  39980. return e;
  39981. }
  39982. void TreeView::restoreOpennessState (const XmlElement& newState)
  39983. {
  39984. if (rootItem != 0)
  39985. {
  39986. rootItem->restoreFromXml (newState);
  39987. if (newState.hasAttribute (T("scrollPos")))
  39988. viewport->setViewPosition (viewport->getViewPositionX(),
  39989. newState.getIntAttribute (T("scrollPos")));
  39990. }
  39991. }
  39992. void TreeView::paint (Graphics& g)
  39993. {
  39994. g.fillAll (findColour (backgroundColourId));
  39995. }
  39996. void TreeView::resized()
  39997. {
  39998. viewport->setBounds (0, 0, getWidth(), getHeight());
  39999. itemsChanged();
  40000. }
  40001. void TreeView::moveSelectedRow (int delta)
  40002. {
  40003. int rowSelected = 0;
  40004. TreeViewItem* const firstSelected = getSelectedItem (0);
  40005. if (firstSelected != 0)
  40006. rowSelected = firstSelected->getRowNumberInTree();
  40007. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  40008. TreeViewItem* item = getItemOnRow (rowSelected);
  40009. if (item != 0)
  40010. {
  40011. item->setSelected (true, true);
  40012. scrollToKeepItemVisible (item);
  40013. }
  40014. }
  40015. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  40016. {
  40017. if (item != 0 && item->ownerView == this)
  40018. {
  40019. handleAsyncUpdate();
  40020. item = item->getDeepestOpenParentItem();
  40021. int y = item->y;
  40022. if (! rootItemVisible)
  40023. y -= rootItem->itemHeight;
  40024. int viewTop = viewport->getViewPositionY();
  40025. if (y < viewTop)
  40026. {
  40027. viewport->setViewPosition (viewport->getViewPositionX(), y);
  40028. }
  40029. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  40030. {
  40031. viewport->setViewPosition (viewport->getViewPositionX(),
  40032. (y + item->itemHeight) - viewport->getViewHeight());
  40033. }
  40034. }
  40035. }
  40036. bool TreeView::keyPressed (const KeyPress& key)
  40037. {
  40038. if (key.isKeyCode (KeyPress::upKey))
  40039. {
  40040. moveSelectedRow (-1);
  40041. }
  40042. else if (key.isKeyCode (KeyPress::downKey))
  40043. {
  40044. moveSelectedRow (1);
  40045. }
  40046. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  40047. {
  40048. if (rootItem != 0)
  40049. {
  40050. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  40051. if (key.isKeyCode (KeyPress::pageUpKey))
  40052. rowsOnScreen = -rowsOnScreen;
  40053. moveSelectedRow (rowsOnScreen);
  40054. }
  40055. }
  40056. else if (key.isKeyCode (KeyPress::homeKey))
  40057. {
  40058. moveSelectedRow (-0x3fffffff);
  40059. }
  40060. else if (key.isKeyCode (KeyPress::endKey))
  40061. {
  40062. moveSelectedRow (0x3fffffff);
  40063. }
  40064. else if (key.isKeyCode (KeyPress::returnKey))
  40065. {
  40066. TreeViewItem* const firstSelected = getSelectedItem (0);
  40067. if (firstSelected != 0)
  40068. firstSelected->setOpen (! firstSelected->isOpen());
  40069. }
  40070. else if (key.isKeyCode (KeyPress::leftKey))
  40071. {
  40072. TreeViewItem* const firstSelected = getSelectedItem (0);
  40073. if (firstSelected != 0)
  40074. {
  40075. if (firstSelected->isOpen())
  40076. {
  40077. firstSelected->setOpen (false);
  40078. }
  40079. else
  40080. {
  40081. TreeViewItem* parent = firstSelected->parentItem;
  40082. if ((! rootItemVisible) && parent == rootItem)
  40083. parent = 0;
  40084. if (parent != 0)
  40085. {
  40086. parent->setSelected (true, true);
  40087. scrollToKeepItemVisible (parent);
  40088. }
  40089. }
  40090. }
  40091. }
  40092. else if (key.isKeyCode (KeyPress::rightKey))
  40093. {
  40094. TreeViewItem* const firstSelected = getSelectedItem (0);
  40095. if (firstSelected != 0)
  40096. {
  40097. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  40098. moveSelectedRow (1);
  40099. else
  40100. firstSelected->setOpen (true);
  40101. }
  40102. }
  40103. else
  40104. {
  40105. return false;
  40106. }
  40107. return true;
  40108. }
  40109. void TreeView::itemsChanged() throw()
  40110. {
  40111. needsRecalculating = true;
  40112. repaint();
  40113. triggerAsyncUpdate();
  40114. }
  40115. void TreeView::handleAsyncUpdate()
  40116. {
  40117. if (needsRecalculating)
  40118. {
  40119. needsRecalculating = false;
  40120. const ScopedLock sl (nodeAlterationLock);
  40121. if (rootItem != 0)
  40122. rootItem->updatePositions (0);
  40123. ((TreeViewport*) viewport)->updateComponents();
  40124. if (rootItem != 0)
  40125. {
  40126. viewport->getViewedComponent()
  40127. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  40128. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  40129. }
  40130. else
  40131. {
  40132. viewport->getViewedComponent()->setSize (0, 0);
  40133. }
  40134. }
  40135. }
  40136. void TreeViewContentComponent::paint (Graphics& g)
  40137. {
  40138. if (owner->rootItem != 0)
  40139. {
  40140. owner->handleAsyncUpdate();
  40141. int w = getWidth();
  40142. if (! owner->rootItemVisible)
  40143. {
  40144. const int indentWidth = owner->getIndentSize();
  40145. g.setOrigin (-indentWidth, -owner->rootItem->itemHeight);
  40146. w += indentWidth;
  40147. }
  40148. owner->rootItem->paintRecursively (g, w);
  40149. }
  40150. }
  40151. TreeViewItem* TreeViewContentComponent::findItemAt (int y, Rectangle& itemPosition) const
  40152. {
  40153. if (owner->rootItem != 0)
  40154. {
  40155. owner->handleAsyncUpdate();
  40156. if (! owner->rootItemVisible)
  40157. y += owner->rootItem->itemHeight;
  40158. TreeViewItem* const ti = owner->rootItem->findItemRecursively (y);
  40159. if (ti != 0)
  40160. {
  40161. itemPosition = ti->getItemPosition (false);
  40162. if (! owner->rootItemVisible)
  40163. itemPosition.translate (-owner->getIndentSize(),
  40164. -owner->rootItem->itemHeight);
  40165. }
  40166. return ti;
  40167. }
  40168. return 0;
  40169. }
  40170. #define opennessDefault 0
  40171. #define opennessClosed 1
  40172. #define opennessOpen 2
  40173. TreeViewItem::TreeViewItem()
  40174. : ownerView (0),
  40175. parentItem (0),
  40176. subItems (8),
  40177. y (0),
  40178. itemHeight (0),
  40179. totalHeight (0),
  40180. selected (false),
  40181. redrawNeeded (true),
  40182. drawLinesInside (true),
  40183. openness (opennessDefault)
  40184. {
  40185. static int nextUID = 0;
  40186. uid = nextUID++;
  40187. }
  40188. TreeViewItem::~TreeViewItem()
  40189. {
  40190. }
  40191. const String TreeViewItem::getUniqueName() const
  40192. {
  40193. return String::empty;
  40194. }
  40195. void TreeViewItem::itemOpennessChanged (bool)
  40196. {
  40197. }
  40198. int TreeViewItem::getNumSubItems() const throw()
  40199. {
  40200. return subItems.size();
  40201. }
  40202. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  40203. {
  40204. return subItems [index];
  40205. }
  40206. void TreeViewItem::clearSubItems()
  40207. {
  40208. if (subItems.size() > 0)
  40209. {
  40210. if (ownerView != 0)
  40211. {
  40212. const ScopedLock sl (ownerView->nodeAlterationLock);
  40213. subItems.clear();
  40214. treeHasChanged();
  40215. }
  40216. else
  40217. {
  40218. subItems.clear();
  40219. }
  40220. }
  40221. }
  40222. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  40223. {
  40224. if (newItem != 0)
  40225. {
  40226. newItem->parentItem = this;
  40227. newItem->setOwnerView (ownerView);
  40228. newItem->y = 0;
  40229. newItem->itemHeight = newItem->getItemHeight();
  40230. newItem->totalHeight = 0;
  40231. newItem->itemWidth = newItem->getItemWidth();
  40232. newItem->totalWidth = 0;
  40233. if (ownerView != 0)
  40234. {
  40235. const ScopedLock sl (ownerView->nodeAlterationLock);
  40236. subItems.insert (insertPosition, newItem);
  40237. treeHasChanged();
  40238. if (newItem->isOpen())
  40239. newItem->itemOpennessChanged (true);
  40240. }
  40241. else
  40242. {
  40243. subItems.insert (insertPosition, newItem);
  40244. if (newItem->isOpen())
  40245. newItem->itemOpennessChanged (true);
  40246. }
  40247. }
  40248. }
  40249. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  40250. {
  40251. if (ownerView != 0)
  40252. ownerView->nodeAlterationLock.enter();
  40253. if (((unsigned int) index) < (unsigned int) subItems.size())
  40254. {
  40255. subItems.remove (index, deleteItem);
  40256. treeHasChanged();
  40257. }
  40258. if (ownerView != 0)
  40259. ownerView->nodeAlterationLock.exit();
  40260. }
  40261. bool TreeViewItem::isOpen() const throw()
  40262. {
  40263. if (openness == opennessDefault)
  40264. return ownerView != 0 && ownerView->defaultOpenness;
  40265. else
  40266. return openness == opennessOpen;
  40267. }
  40268. void TreeViewItem::setOpen (const bool shouldBeOpen)
  40269. {
  40270. if (isOpen() != shouldBeOpen)
  40271. {
  40272. openness = shouldBeOpen ? opennessOpen
  40273. : opennessClosed;
  40274. treeHasChanged();
  40275. itemOpennessChanged (isOpen());
  40276. }
  40277. }
  40278. bool TreeViewItem::isSelected() const throw()
  40279. {
  40280. return selected;
  40281. }
  40282. void TreeViewItem::deselectAllRecursively()
  40283. {
  40284. setSelected (false, false);
  40285. for (int i = 0; i < subItems.size(); ++i)
  40286. subItems.getUnchecked(i)->deselectAllRecursively();
  40287. }
  40288. void TreeViewItem::setSelected (const bool shouldBeSelected,
  40289. const bool deselectOtherItemsFirst)
  40290. {
  40291. if (deselectOtherItemsFirst)
  40292. getTopLevelItem()->deselectAllRecursively();
  40293. if (shouldBeSelected != selected)
  40294. {
  40295. selected = shouldBeSelected;
  40296. if (ownerView != 0)
  40297. ownerView->repaint();
  40298. itemSelectionChanged (shouldBeSelected);
  40299. }
  40300. }
  40301. void TreeViewItem::paintItem (Graphics&, int, int)
  40302. {
  40303. }
  40304. void TreeViewItem::itemClicked (const MouseEvent&)
  40305. {
  40306. }
  40307. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  40308. {
  40309. if (mightContainSubItems())
  40310. setOpen (! isOpen());
  40311. }
  40312. void TreeViewItem::itemSelectionChanged (bool)
  40313. {
  40314. }
  40315. const String TreeViewItem::getDragSourceDescription()
  40316. {
  40317. return String::empty;
  40318. }
  40319. const Rectangle TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  40320. {
  40321. const int indentX = getIndentX();
  40322. int width = itemWidth;
  40323. if (ownerView != 0 && width < 0)
  40324. width = ownerView->viewport->getViewWidth() - indentX;
  40325. Rectangle r (indentX, y, jmax (0, width), totalHeight);
  40326. if (relativeToTreeViewTopLeft)
  40327. r.setPosition (r.getX() - ownerView->viewport->getViewPositionX(),
  40328. r.getY() - ownerView->viewport->getViewPositionY());
  40329. return r;
  40330. }
  40331. void TreeViewItem::treeHasChanged() const throw()
  40332. {
  40333. if (ownerView != 0)
  40334. ownerView->itemsChanged();
  40335. }
  40336. void TreeViewItem::updatePositions (int newY)
  40337. {
  40338. y = newY;
  40339. itemHeight = getItemHeight();
  40340. totalHeight = itemHeight;
  40341. itemWidth = getItemWidth();
  40342. totalWidth = jmax (itemWidth, 0);
  40343. if (isOpen())
  40344. {
  40345. const int ourIndent = getIndentX();
  40346. newY += totalHeight;
  40347. for (int i = 0; i < subItems.size(); ++i)
  40348. {
  40349. TreeViewItem* const ti = subItems.getUnchecked(i);
  40350. ti->updatePositions (newY);
  40351. newY += ti->totalHeight;
  40352. totalHeight += ti->totalHeight;
  40353. totalWidth = jmax (totalWidth, ti->totalWidth + ourIndent);
  40354. }
  40355. }
  40356. }
  40357. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  40358. {
  40359. TreeViewItem* result = this;
  40360. TreeViewItem* item = this;
  40361. while (item->parentItem != 0)
  40362. {
  40363. item = item->parentItem;
  40364. if (! item->isOpen())
  40365. result = item;
  40366. }
  40367. return result;
  40368. }
  40369. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  40370. {
  40371. ownerView = newOwner;
  40372. for (int i = subItems.size(); --i >= 0;)
  40373. subItems.getUnchecked(i)->setOwnerView (newOwner);
  40374. }
  40375. int TreeViewItem::getIndentX() const throw()
  40376. {
  40377. const int indentWidth = ownerView->getIndentSize();
  40378. int x = indentWidth;
  40379. TreeViewItem* p = parentItem;
  40380. while (p != 0)
  40381. {
  40382. x += indentWidth;
  40383. p = p->parentItem;
  40384. }
  40385. return x;
  40386. }
  40387. void TreeViewItem::paintRecursively (Graphics& g, int width)
  40388. {
  40389. jassert (ownerView != 0);
  40390. if (ownerView == 0)
  40391. return;
  40392. const int indent = getIndentX();
  40393. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  40394. g.setColour (ownerView->findColour (TreeView::linesColourId));
  40395. const float halfH = itemHeight * 0.5f;
  40396. int depth = 0;
  40397. TreeViewItem* p = parentItem;
  40398. while (p != 0)
  40399. {
  40400. ++depth;
  40401. p = p->parentItem;
  40402. }
  40403. const int indentWidth = ownerView->getIndentSize();
  40404. float x = (depth + 0.5f) * indentWidth;
  40405. if (x > 0)
  40406. {
  40407. if (depth >= 0)
  40408. {
  40409. if (parentItem != 0 && parentItem->drawLinesInside)
  40410. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  40411. if ((parentItem != 0 && parentItem->drawLinesInside)
  40412. || (parentItem == 0 && drawLinesInside))
  40413. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  40414. }
  40415. p = parentItem;
  40416. int d = depth;
  40417. while (p != 0 && --d >= 0)
  40418. {
  40419. x -= (float) indentWidth;
  40420. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  40421. && ! p->isLastOfSiblings())
  40422. {
  40423. g.drawLine (x, 0, x, (float) itemHeight);
  40424. }
  40425. p = p->parentItem;
  40426. }
  40427. if (mightContainSubItems())
  40428. {
  40429. ownerView->getLookAndFeel()
  40430. .drawTreeviewPlusMinusBox (g,
  40431. depth * indentWidth, 0,
  40432. indentWidth, itemHeight,
  40433. ! isOpen());
  40434. }
  40435. }
  40436. {
  40437. g.saveState();
  40438. g.setOrigin (indent, 0);
  40439. if (g.reduceClipRegion (0, 0, itemW, itemHeight))
  40440. paintItem (g, itemW, itemHeight);
  40441. g.restoreState();
  40442. }
  40443. if (isOpen())
  40444. {
  40445. const Rectangle clip (g.getClipBounds());
  40446. for (int i = 0; i < subItems.size(); ++i)
  40447. {
  40448. TreeViewItem* const ti = subItems.getUnchecked(i);
  40449. const int relY = ti->y - y;
  40450. if (relY >= clip.getBottom())
  40451. break;
  40452. if (relY + ti->totalHeight >= clip.getY())
  40453. {
  40454. g.saveState();
  40455. g.setOrigin (0, relY);
  40456. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  40457. ti->paintRecursively (g, width);
  40458. g.restoreState();
  40459. }
  40460. }
  40461. }
  40462. }
  40463. bool TreeViewItem::isLastOfSiblings() const throw()
  40464. {
  40465. return parentItem == 0
  40466. || parentItem->subItems.getLast() == this;
  40467. }
  40468. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  40469. {
  40470. return (parentItem == 0) ? this
  40471. : parentItem->getTopLevelItem();
  40472. }
  40473. int TreeViewItem::getNumRows() const throw()
  40474. {
  40475. int num = 1;
  40476. if (isOpen())
  40477. {
  40478. for (int i = subItems.size(); --i >= 0;)
  40479. num += subItems.getUnchecked(i)->getNumRows();
  40480. }
  40481. return num;
  40482. }
  40483. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  40484. {
  40485. if (index == 0)
  40486. return this;
  40487. if (index > 0 && isOpen())
  40488. {
  40489. --index;
  40490. for (int i = 0; i < subItems.size(); ++i)
  40491. {
  40492. TreeViewItem* const item = subItems.getUnchecked(i);
  40493. if (index == 0)
  40494. return item;
  40495. const int numRows = item->getNumRows();
  40496. if (numRows > index)
  40497. return item->getItemOnRow (index);
  40498. index -= numRows;
  40499. }
  40500. }
  40501. return 0;
  40502. }
  40503. TreeViewItem* TreeViewItem::findItemRecursively (int y) throw()
  40504. {
  40505. if (((unsigned int) y) < (unsigned int) totalHeight)
  40506. {
  40507. const int h = itemHeight;
  40508. if (y < h)
  40509. return this;
  40510. if (isOpen())
  40511. {
  40512. y -= h;
  40513. for (int i = 0; i < subItems.size(); ++i)
  40514. {
  40515. TreeViewItem* const ti = subItems.getUnchecked(i);
  40516. if (ti->totalHeight >= y)
  40517. return ti->findItemRecursively (y);
  40518. y -= ti->totalHeight;
  40519. }
  40520. }
  40521. }
  40522. return 0;
  40523. }
  40524. int TreeViewItem::countSelectedItemsRecursively() const throw()
  40525. {
  40526. int total = 0;
  40527. if (isSelected())
  40528. ++total;
  40529. for (int i = subItems.size(); --i >= 0;)
  40530. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  40531. return total;
  40532. }
  40533. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  40534. {
  40535. if (isSelected())
  40536. {
  40537. if (index == 0)
  40538. return this;
  40539. --index;
  40540. }
  40541. if (index >= 0)
  40542. {
  40543. for (int i = 0; i < subItems.size(); ++i)
  40544. {
  40545. TreeViewItem* const item = subItems.getUnchecked(i);
  40546. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  40547. if (found != 0)
  40548. return found;
  40549. index -= item->countSelectedItemsRecursively();
  40550. }
  40551. }
  40552. return 0;
  40553. }
  40554. int TreeViewItem::getRowNumberInTree() const throw()
  40555. {
  40556. if (parentItem != 0 && ownerView != 0)
  40557. {
  40558. int n = 1 + parentItem->getRowNumberInTree();
  40559. int ourIndex = parentItem->subItems.indexOf (this);
  40560. jassert (ourIndex >= 0);
  40561. while (--ourIndex >= 0)
  40562. n += parentItem->subItems [ourIndex]->getNumRows();
  40563. if (parentItem->parentItem == 0
  40564. && ! ownerView->rootItemVisible)
  40565. --n;
  40566. return n;
  40567. }
  40568. else
  40569. {
  40570. return 0;
  40571. }
  40572. }
  40573. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  40574. {
  40575. drawLinesInside = drawLines;
  40576. }
  40577. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  40578. {
  40579. if (recurse && isOpen() && subItems.size() > 0)
  40580. return subItems [0];
  40581. if (parentItem != 0)
  40582. {
  40583. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  40584. if (nextIndex >= parentItem->subItems.size())
  40585. return parentItem->getNextVisibleItem (false);
  40586. return parentItem->subItems [nextIndex];
  40587. }
  40588. return 0;
  40589. }
  40590. void TreeViewItem::restoreFromXml (const XmlElement& e)
  40591. {
  40592. if (e.hasTagName (T("CLOSED")))
  40593. {
  40594. setOpen (false);
  40595. }
  40596. else if (e.hasTagName (T("OPEN")))
  40597. {
  40598. setOpen (true);
  40599. forEachXmlChildElement (e, n)
  40600. {
  40601. const String id (n->getStringAttribute (T("id")));
  40602. for (int i = 0; i < subItems.size(); ++i)
  40603. {
  40604. TreeViewItem* const ti = subItems.getUnchecked(i);
  40605. if (ti->getUniqueName() == id)
  40606. {
  40607. ti->restoreFromXml (*n);
  40608. break;
  40609. }
  40610. }
  40611. }
  40612. }
  40613. }
  40614. XmlElement* TreeViewItem::createXmlOpenness() const
  40615. {
  40616. if (openness != opennessDefault)
  40617. {
  40618. const String name (getUniqueName());
  40619. if (name.isNotEmpty())
  40620. {
  40621. XmlElement* e;
  40622. if (isOpen())
  40623. {
  40624. e = new XmlElement (T("OPEN"));
  40625. for (int i = 0; i < subItems.size(); ++i)
  40626. e->addChildElement (subItems.getUnchecked(i)->createXmlOpenness());
  40627. }
  40628. else
  40629. {
  40630. e = new XmlElement (T("CLOSED"));
  40631. }
  40632. e->setAttribute (T("id"), name);
  40633. return e;
  40634. }
  40635. else
  40636. {
  40637. // trying to save the openness for an element that has no name - this won't
  40638. // work because it needs the names to identify what to open.
  40639. jassertfalse
  40640. }
  40641. }
  40642. return 0;
  40643. }
  40644. END_JUCE_NAMESPACE
  40645. /********* End of inlined file: juce_TreeView.cpp *********/
  40646. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  40647. BEGIN_JUCE_NAMESPACE
  40648. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  40649. : fileList (listToShow),
  40650. listeners (2)
  40651. {
  40652. }
  40653. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  40654. {
  40655. }
  40656. FileBrowserListener::~FileBrowserListener()
  40657. {
  40658. }
  40659. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener) throw()
  40660. {
  40661. jassert (listener != 0);
  40662. if (listener != 0)
  40663. listeners.add (listener);
  40664. }
  40665. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener) throw()
  40666. {
  40667. listeners.removeValue (listener);
  40668. }
  40669. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  40670. {
  40671. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  40672. for (int i = listeners.size(); --i >= 0;)
  40673. {
  40674. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  40675. if (deletionWatcher.hasBeenDeleted())
  40676. return;
  40677. i = jmin (i, listeners.size() - 1);
  40678. }
  40679. }
  40680. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  40681. {
  40682. if (fileList.getDirectory().exists())
  40683. {
  40684. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  40685. for (int i = listeners.size(); --i >= 0;)
  40686. {
  40687. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (file, e);
  40688. if (deletionWatcher.hasBeenDeleted())
  40689. return;
  40690. i = jmin (i, listeners.size() - 1);
  40691. }
  40692. }
  40693. }
  40694. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  40695. {
  40696. if (fileList.getDirectory().exists())
  40697. {
  40698. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  40699. for (int i = listeners.size(); --i >= 0;)
  40700. {
  40701. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (file);
  40702. if (deletionWatcher.hasBeenDeleted())
  40703. return;
  40704. i = jmin (i, listeners.size() - 1);
  40705. }
  40706. }
  40707. }
  40708. END_JUCE_NAMESPACE
  40709. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  40710. /********* Start of inlined file: juce_DirectoryContentsList.cpp *********/
  40711. BEGIN_JUCE_NAMESPACE
  40712. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  40713. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  40714. Time* creationTime, bool* isReadOnly) throw();
  40715. bool juce_findFileNext (void* handle, String& resultFile,
  40716. bool* isDirectory, bool* isHidden, int64* fileSize,
  40717. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  40718. void juce_findFileClose (void* handle) throw();
  40719. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  40720. TimeSliceThread& thread_)
  40721. : fileFilter (fileFilter_),
  40722. thread (thread_),
  40723. includeDirectories (false),
  40724. includeFiles (false),
  40725. ignoreHiddenFiles (true),
  40726. fileFindHandle (0),
  40727. shouldStop (true)
  40728. {
  40729. }
  40730. DirectoryContentsList::~DirectoryContentsList()
  40731. {
  40732. clear();
  40733. }
  40734. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  40735. {
  40736. ignoreHiddenFiles = shouldIgnoreHiddenFiles;
  40737. }
  40738. const File& DirectoryContentsList::getDirectory() const throw()
  40739. {
  40740. return root;
  40741. }
  40742. void DirectoryContentsList::setDirectory (const File& directory,
  40743. const bool includeDirectories_,
  40744. const bool includeFiles_)
  40745. {
  40746. if (directory != root
  40747. || includeDirectories != includeDirectories_
  40748. || includeFiles != includeFiles_)
  40749. {
  40750. clear();
  40751. root = directory;
  40752. includeDirectories = includeDirectories_;
  40753. includeFiles = includeFiles_;
  40754. refresh();
  40755. }
  40756. }
  40757. void DirectoryContentsList::clear()
  40758. {
  40759. shouldStop = true;
  40760. thread.removeTimeSliceClient (this);
  40761. if (fileFindHandle != 0)
  40762. {
  40763. juce_findFileClose (fileFindHandle);
  40764. fileFindHandle = 0;
  40765. }
  40766. if (files.size() > 0)
  40767. {
  40768. files.clear();
  40769. changed();
  40770. }
  40771. }
  40772. void DirectoryContentsList::refresh()
  40773. {
  40774. clear();
  40775. if (root.isDirectory())
  40776. {
  40777. String fileFound;
  40778. bool fileFoundIsDir, isHidden, isReadOnly;
  40779. int64 fileSize;
  40780. Time modTime, creationTime;
  40781. String path (root.getFullPathName());
  40782. if (! path.endsWithChar (File::separator))
  40783. path += File::separator;
  40784. jassert (fileFindHandle == 0);
  40785. fileFindHandle = juce_findFileStart (path, T("*"), fileFound,
  40786. &fileFoundIsDir,
  40787. &isHidden,
  40788. &fileSize,
  40789. &modTime,
  40790. &creationTime,
  40791. &isReadOnly);
  40792. if (fileFindHandle != 0 && fileFound.isNotEmpty())
  40793. {
  40794. if (addFile (fileFound, fileFoundIsDir, isHidden,
  40795. fileSize, modTime, creationTime, isReadOnly))
  40796. {
  40797. changed();
  40798. }
  40799. }
  40800. shouldStop = false;
  40801. thread.addTimeSliceClient (this);
  40802. }
  40803. }
  40804. int DirectoryContentsList::getNumFiles() const
  40805. {
  40806. return files.size();
  40807. }
  40808. bool DirectoryContentsList::getFileInfo (const int index,
  40809. FileInfo& result) const
  40810. {
  40811. const ScopedLock sl (fileListLock);
  40812. const FileInfo* const info = files [index];
  40813. if (info != 0)
  40814. {
  40815. result = *info;
  40816. return true;
  40817. }
  40818. return false;
  40819. }
  40820. const File DirectoryContentsList::getFile (const int index) const
  40821. {
  40822. const ScopedLock sl (fileListLock);
  40823. const FileInfo* const info = files [index];
  40824. if (info != 0)
  40825. return root.getChildFile (info->filename);
  40826. return File::nonexistent;
  40827. }
  40828. bool DirectoryContentsList::isStillLoading() const
  40829. {
  40830. return fileFindHandle != 0;
  40831. }
  40832. void DirectoryContentsList::changed()
  40833. {
  40834. sendChangeMessage (this);
  40835. }
  40836. bool DirectoryContentsList::useTimeSlice()
  40837. {
  40838. const uint32 startTime = Time::getApproximateMillisecondCounter();
  40839. bool hasChanged = false;
  40840. for (int i = 100; --i >= 0;)
  40841. {
  40842. if (! checkNextFile (hasChanged))
  40843. {
  40844. if (hasChanged)
  40845. changed();
  40846. return false;
  40847. }
  40848. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  40849. break;
  40850. }
  40851. if (hasChanged)
  40852. changed();
  40853. return true;
  40854. }
  40855. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  40856. {
  40857. if (fileFindHandle != 0)
  40858. {
  40859. String fileFound;
  40860. bool fileFoundIsDir, isHidden, isReadOnly;
  40861. int64 fileSize;
  40862. Time modTime, creationTime;
  40863. if (juce_findFileNext (fileFindHandle, fileFound,
  40864. &fileFoundIsDir, &isHidden,
  40865. &fileSize,
  40866. &modTime,
  40867. &creationTime,
  40868. &isReadOnly))
  40869. {
  40870. if (addFile (fileFound, fileFoundIsDir, isHidden, fileSize,
  40871. modTime, creationTime, isReadOnly))
  40872. {
  40873. hasChanged = true;
  40874. }
  40875. return true;
  40876. }
  40877. else
  40878. {
  40879. juce_findFileClose (fileFindHandle);
  40880. fileFindHandle = 0;
  40881. }
  40882. }
  40883. return false;
  40884. }
  40885. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  40886. const DirectoryContentsList::FileInfo* const second) throw()
  40887. {
  40888. #if JUCE_WIN32
  40889. if (first->isDirectory != second->isDirectory)
  40890. return first->isDirectory ? -1 : 1;
  40891. #endif
  40892. return first->filename.compareIgnoreCase (second->filename);
  40893. }
  40894. bool DirectoryContentsList::addFile (const String& filename,
  40895. const bool isDir,
  40896. const bool isHidden,
  40897. const int64 fileSize,
  40898. const Time& modTime,
  40899. const Time& creationTime,
  40900. const bool isReadOnly)
  40901. {
  40902. if (filename == T("..")
  40903. || filename == T(".")
  40904. || (ignoreHiddenFiles && isHidden))
  40905. return false;
  40906. const File file (root.getChildFile (filename));
  40907. if (((isDir && includeDirectories) || ((! isDir) && includeFiles))
  40908. && (fileFilter == 0
  40909. || ((! isDir) && fileFilter->isFileSuitable (file))
  40910. || (isDir && fileFilter->isDirectorySuitable (file))))
  40911. {
  40912. FileInfo* const info = new FileInfo();
  40913. info->filename = filename;
  40914. info->fileSize = fileSize;
  40915. info->modificationTime = modTime;
  40916. info->creationTime = creationTime;
  40917. info->isDirectory = isDir;
  40918. info->isReadOnly = isReadOnly;
  40919. const ScopedLock sl (fileListLock);
  40920. for (int i = files.size(); --i >= 0;)
  40921. {
  40922. if (files.getUnchecked(i)->filename == info->filename)
  40923. {
  40924. delete info;
  40925. return false;
  40926. }
  40927. }
  40928. files.addSorted (*this, info);
  40929. return true;
  40930. }
  40931. return false;
  40932. }
  40933. END_JUCE_NAMESPACE
  40934. /********* End of inlined file: juce_DirectoryContentsList.cpp *********/
  40935. /********* Start of inlined file: juce_FileBrowserComponent.cpp *********/
  40936. BEGIN_JUCE_NAMESPACE
  40937. class DirectoriesOnlyFilter : public FileFilter
  40938. {
  40939. public:
  40940. DirectoriesOnlyFilter() : FileFilter (String::empty) {}
  40941. bool isFileSuitable (const File&) const { return false; }
  40942. bool isDirectorySuitable (const File&) const { return true; }
  40943. };
  40944. FileBrowserComponent::FileBrowserComponent (FileChooserMode mode_,
  40945. const File& initialFileOrDirectory,
  40946. const FileFilter* fileFilter,
  40947. FilePreviewComponent* previewComp_,
  40948. const bool useTreeView,
  40949. const bool filenameTextBoxIsReadOnly)
  40950. : directoriesOnlyFilter (0),
  40951. mode (mode_),
  40952. listeners (2),
  40953. previewComp (previewComp_),
  40954. thread ("Juce FileBrowser")
  40955. {
  40956. String filename;
  40957. if (initialFileOrDirectory == File::nonexistent)
  40958. {
  40959. currentRoot = File::getCurrentWorkingDirectory();
  40960. }
  40961. else if (initialFileOrDirectory.isDirectory())
  40962. {
  40963. currentRoot = initialFileOrDirectory;
  40964. }
  40965. else
  40966. {
  40967. currentRoot = initialFileOrDirectory.getParentDirectory();
  40968. filename = initialFileOrDirectory.getFileName();
  40969. }
  40970. if (mode_ == chooseDirectoryMode)
  40971. fileFilter = directoriesOnlyFilter = new DirectoriesOnlyFilter();
  40972. fileList = new DirectoryContentsList (fileFilter, thread);
  40973. if (useTreeView)
  40974. {
  40975. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  40976. addAndMakeVisible (tree);
  40977. fileListComponent = tree;
  40978. }
  40979. else
  40980. {
  40981. FileListComponent* const list = new FileListComponent (*fileList);
  40982. list->setOutlineThickness (1);
  40983. addAndMakeVisible (list);
  40984. fileListComponent = list;
  40985. }
  40986. fileListComponent->addListener (this);
  40987. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  40988. currentPathBox->setEditableText (true);
  40989. StringArray rootNames, rootPaths;
  40990. const BitArray separators (getRoots (rootNames, rootPaths));
  40991. for (int i = 0; i < rootNames.size(); ++i)
  40992. {
  40993. if (separators [i])
  40994. currentPathBox->addSeparator();
  40995. currentPathBox->addItem (rootNames[i], i + 1);
  40996. }
  40997. currentPathBox->addSeparator();
  40998. currentPathBox->addListener (this);
  40999. addAndMakeVisible (filenameBox = new TextEditor());
  41000. filenameBox->setMultiLine (false);
  41001. filenameBox->setSelectAllWhenFocused (true);
  41002. filenameBox->setText (filename, false);
  41003. filenameBox->addListener (this);
  41004. filenameBox->setReadOnly (filenameTextBoxIsReadOnly);
  41005. Label* label = new Label ("f", (mode == chooseDirectoryMode) ? TRANS("folder:")
  41006. : TRANS("file:"));
  41007. addAndMakeVisible (label);
  41008. label->attachToComponent (filenameBox, true);
  41009. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  41010. goUpButton->addButtonListener (this);
  41011. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  41012. if (previewComp != 0)
  41013. addAndMakeVisible (previewComp);
  41014. setRoot (currentRoot);
  41015. thread.startThread (4);
  41016. }
  41017. FileBrowserComponent::~FileBrowserComponent()
  41018. {
  41019. if (previewComp != 0)
  41020. removeChildComponent (previewComp);
  41021. deleteAllChildren();
  41022. deleteAndZero (fileList);
  41023. delete directoriesOnlyFilter;
  41024. thread.stopThread (10000);
  41025. }
  41026. void FileBrowserComponent::addListener (FileBrowserListener* const newListener) throw()
  41027. {
  41028. jassert (newListener != 0)
  41029. if (newListener != 0)
  41030. listeners.add (newListener);
  41031. }
  41032. void FileBrowserComponent::removeListener (FileBrowserListener* const listener) throw()
  41033. {
  41034. listeners.removeValue (listener);
  41035. }
  41036. const File FileBrowserComponent::getCurrentFile() const throw()
  41037. {
  41038. return currentRoot.getChildFile (filenameBox->getText());
  41039. }
  41040. bool FileBrowserComponent::currentFileIsValid() const
  41041. {
  41042. if (mode == saveFileMode)
  41043. return ! getCurrentFile().isDirectory();
  41044. else if (mode == loadFileMode)
  41045. return getCurrentFile().existsAsFile();
  41046. else if (mode == chooseDirectoryMode)
  41047. return getCurrentFile().isDirectory();
  41048. jassertfalse
  41049. return false;
  41050. }
  41051. const File FileBrowserComponent::getRoot() const
  41052. {
  41053. return currentRoot;
  41054. }
  41055. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  41056. {
  41057. if (currentRoot != newRootDirectory)
  41058. {
  41059. fileListComponent->scrollToTop();
  41060. if (mode == chooseDirectoryMode)
  41061. filenameBox->setText (String::empty, false);
  41062. String path (newRootDirectory.getFullPathName());
  41063. if (path.isEmpty())
  41064. path += File::separator;
  41065. StringArray rootNames, rootPaths;
  41066. getRoots (rootNames, rootPaths);
  41067. if (! rootPaths.contains (path, true))
  41068. {
  41069. bool alreadyListed = false;
  41070. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  41071. {
  41072. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  41073. {
  41074. alreadyListed = true;
  41075. break;
  41076. }
  41077. }
  41078. if (! alreadyListed)
  41079. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  41080. }
  41081. }
  41082. currentRoot = newRootDirectory;
  41083. fileList->setDirectory (currentRoot, true, true);
  41084. String currentRootName (currentRoot.getFullPathName());
  41085. if (currentRootName.isEmpty())
  41086. currentRootName += File::separator;
  41087. currentPathBox->setText (currentRootName, true);
  41088. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  41089. && currentRoot.getParentDirectory() != currentRoot);
  41090. }
  41091. void FileBrowserComponent::goUp()
  41092. {
  41093. setRoot (getRoot().getParentDirectory());
  41094. }
  41095. void FileBrowserComponent::refresh()
  41096. {
  41097. fileList->refresh();
  41098. }
  41099. const String FileBrowserComponent::getActionVerb() const
  41100. {
  41101. return (mode == chooseDirectoryMode) ? TRANS("Choose")
  41102. : ((mode == saveFileMode) ? TRANS("Save") : TRANS("Open"));
  41103. }
  41104. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  41105. {
  41106. return previewComp;
  41107. }
  41108. void FileBrowserComponent::resized()
  41109. {
  41110. getLookAndFeel()
  41111. .layoutFileBrowserComponent (*this, fileListComponent,
  41112. previewComp, currentPathBox,
  41113. filenameBox, goUpButton);
  41114. }
  41115. void FileBrowserComponent::sendListenerChangeMessage()
  41116. {
  41117. ComponentDeletionWatcher deletionWatcher (this);
  41118. if (previewComp != 0)
  41119. previewComp->selectedFileChanged (getCurrentFile());
  41120. jassert (! deletionWatcher.hasBeenDeleted());
  41121. for (int i = listeners.size(); --i >= 0;)
  41122. {
  41123. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  41124. if (deletionWatcher.hasBeenDeleted())
  41125. return;
  41126. i = jmin (i, listeners.size() - 1);
  41127. }
  41128. }
  41129. void FileBrowserComponent::selectionChanged()
  41130. {
  41131. const File selected (fileListComponent->getSelectedFile());
  41132. if ((mode == chooseDirectoryMode && selected.isDirectory())
  41133. || selected.existsAsFile())
  41134. {
  41135. filenameBox->setText (selected.getRelativePathFrom (getRoot()), false);
  41136. }
  41137. sendListenerChangeMessage();
  41138. }
  41139. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  41140. {
  41141. ComponentDeletionWatcher deletionWatcher (this);
  41142. for (int i = listeners.size(); --i >= 0;)
  41143. {
  41144. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (f, e);
  41145. if (deletionWatcher.hasBeenDeleted())
  41146. return;
  41147. i = jmin (i, listeners.size() - 1);
  41148. }
  41149. }
  41150. void FileBrowserComponent::fileDoubleClicked (const File& f)
  41151. {
  41152. if (f.isDirectory())
  41153. {
  41154. setRoot (f);
  41155. }
  41156. else
  41157. {
  41158. ComponentDeletionWatcher deletionWatcher (this);
  41159. for (int i = listeners.size(); --i >= 0;)
  41160. {
  41161. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (f);
  41162. if (deletionWatcher.hasBeenDeleted())
  41163. return;
  41164. i = jmin (i, listeners.size() - 1);
  41165. }
  41166. }
  41167. }
  41168. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  41169. {
  41170. sendListenerChangeMessage();
  41171. }
  41172. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  41173. {
  41174. if (filenameBox->getText().containsChar (File::separator))
  41175. {
  41176. const File f (currentRoot.getChildFile (filenameBox->getText()));
  41177. if (f.isDirectory())
  41178. {
  41179. setRoot (f);
  41180. filenameBox->setText (String::empty);
  41181. }
  41182. else
  41183. {
  41184. setRoot (f.getParentDirectory());
  41185. filenameBox->setText (f.getFileName());
  41186. }
  41187. }
  41188. else
  41189. {
  41190. fileDoubleClicked (getCurrentFile());
  41191. }
  41192. }
  41193. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  41194. {
  41195. }
  41196. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  41197. {
  41198. if (mode != saveFileMode)
  41199. selectionChanged();
  41200. }
  41201. void FileBrowserComponent::buttonClicked (Button*)
  41202. {
  41203. goUp();
  41204. }
  41205. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  41206. {
  41207. const String newText (currentPathBox->getText().trim().unquoted());
  41208. if (newText.isNotEmpty())
  41209. {
  41210. const int index = currentPathBox->getSelectedId() - 1;
  41211. StringArray rootNames, rootPaths;
  41212. getRoots (rootNames, rootPaths);
  41213. if (rootPaths [index].isNotEmpty())
  41214. {
  41215. setRoot (File (rootPaths [index]));
  41216. }
  41217. else
  41218. {
  41219. File f (newText);
  41220. for (;;)
  41221. {
  41222. if (f.isDirectory())
  41223. {
  41224. setRoot (f);
  41225. break;
  41226. }
  41227. if (f.getParentDirectory() == f)
  41228. break;
  41229. f = f.getParentDirectory();
  41230. }
  41231. }
  41232. }
  41233. }
  41234. const BitArray FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  41235. {
  41236. BitArray separators;
  41237. #if JUCE_WIN32
  41238. OwnedArray<File> roots;
  41239. File::findFileSystemRoots (roots);
  41240. rootPaths.clear();
  41241. for (int i = 0; i < roots.size(); ++i)
  41242. {
  41243. const File* const drive = roots.getUnchecked(i);
  41244. String name (drive->getFullPathName());
  41245. rootPaths.add (name);
  41246. if (drive->isOnHardDisk())
  41247. {
  41248. String volume (drive->getVolumeLabel());
  41249. if (volume.isEmpty())
  41250. volume = TRANS("Hard Drive");
  41251. name << " [" << drive->getVolumeLabel() << ']';
  41252. }
  41253. else if (drive->isOnCDRomDrive())
  41254. {
  41255. name << TRANS(" [CD/DVD drive]");
  41256. }
  41257. rootNames.add (name);
  41258. }
  41259. separators.setBit (rootPaths.size());
  41260. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  41261. rootNames.add ("Documents");
  41262. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  41263. rootNames.add ("Desktop");
  41264. #endif
  41265. #if JUCE_MAC
  41266. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  41267. rootNames.add ("Home folder");
  41268. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  41269. rootNames.add ("Documents");
  41270. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  41271. rootNames.add ("Desktop");
  41272. separators.setBit (rootPaths.size());
  41273. OwnedArray <File> volumes;
  41274. File vol ("/Volumes");
  41275. vol.findChildFiles (volumes, File::findDirectories, false);
  41276. for (int i = 0; i < volumes.size(); ++i)
  41277. {
  41278. const File* const volume = volumes.getUnchecked(i);
  41279. if (volume->isDirectory() && ! volume->getFileName().startsWithChar (T('.')))
  41280. {
  41281. rootPaths.add (volume->getFullPathName());
  41282. rootNames.add (volume->getFileName());
  41283. }
  41284. }
  41285. #endif
  41286. #if JUCE_LINUX
  41287. rootPaths.add ("/");
  41288. rootNames.add ("/");
  41289. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  41290. rootNames.add ("Home folder");
  41291. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  41292. rootNames.add ("Desktop");
  41293. #endif
  41294. return separators;
  41295. }
  41296. END_JUCE_NAMESPACE
  41297. /********* End of inlined file: juce_FileBrowserComponent.cpp *********/
  41298. /********* Start of inlined file: juce_FileChooser.cpp *********/
  41299. BEGIN_JUCE_NAMESPACE
  41300. FileChooser::FileChooser (const String& chooserBoxTitle,
  41301. const File& currentFileOrDirectory,
  41302. const String& fileFilters,
  41303. const bool useNativeDialogBox_)
  41304. : title (chooserBoxTitle),
  41305. filters (fileFilters),
  41306. startingFile (currentFileOrDirectory),
  41307. useNativeDialogBox (useNativeDialogBox_)
  41308. {
  41309. #if JUCE_LINUX
  41310. useNativeDialogBox = false;
  41311. #endif
  41312. if (fileFilters.trim().isEmpty())
  41313. filters = T("*");
  41314. }
  41315. FileChooser::~FileChooser()
  41316. {
  41317. }
  41318. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  41319. {
  41320. return showDialog (false, false, false, false, previewComponent);
  41321. }
  41322. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  41323. {
  41324. return showDialog (false, false, false, true, previewComponent);
  41325. }
  41326. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  41327. {
  41328. return showDialog (false, true, warnAboutOverwritingExistingFiles, false, 0);
  41329. }
  41330. bool FileChooser::browseForDirectory()
  41331. {
  41332. return showDialog (true, false, false, false, 0);
  41333. }
  41334. const File FileChooser::getResult() const
  41335. {
  41336. // if you've used a multiple-file select, you should use the getResults() method
  41337. // to retrieve all the files that were chosen.
  41338. jassert (results.size() <= 1);
  41339. const File* const f = results.getFirst();
  41340. if (f != 0)
  41341. return *f;
  41342. return File::nonexistent;
  41343. }
  41344. const OwnedArray <File>& FileChooser::getResults() const
  41345. {
  41346. return results;
  41347. }
  41348. bool FileChooser::showDialog (const bool isDirectory,
  41349. const bool isSave,
  41350. const bool warnAboutOverwritingExistingFiles,
  41351. const bool selectMultipleFiles,
  41352. FilePreviewComponent* const previewComponent)
  41353. {
  41354. ComponentDeletionWatcher* currentlyFocusedChecker = 0;
  41355. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  41356. if (currentlyFocused != 0)
  41357. currentlyFocusedChecker = new ComponentDeletionWatcher (currentlyFocused);
  41358. results.clear();
  41359. // the preview component needs to be the right size before you pass it in here..
  41360. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  41361. && previewComponent->getHeight() > 10));
  41362. #if JUCE_WIN32
  41363. if (useNativeDialogBox)
  41364. #else
  41365. if (useNativeDialogBox && (previewComponent == 0))
  41366. #endif
  41367. {
  41368. showPlatformDialog (results, title, startingFile, filters,
  41369. isDirectory, isSave,
  41370. warnAboutOverwritingExistingFiles,
  41371. selectMultipleFiles,
  41372. previewComponent);
  41373. }
  41374. else
  41375. {
  41376. jassert (! selectMultipleFiles); // not yet implemented for juce dialogs!
  41377. WildcardFileFilter wildcard (filters, String::empty);
  41378. FileBrowserComponent browserComponent (isDirectory ? FileBrowserComponent::chooseDirectoryMode
  41379. : (isSave ? FileBrowserComponent::saveFileMode
  41380. : FileBrowserComponent::loadFileMode),
  41381. startingFile, &wildcard, previewComponent);
  41382. FileChooserDialogBox box (title, String::empty,
  41383. browserComponent,
  41384. warnAboutOverwritingExistingFiles,
  41385. browserComponent.findColour (AlertWindow::backgroundColourId));
  41386. if (box.show())
  41387. results.add (new File (browserComponent.getCurrentFile()));
  41388. }
  41389. if (currentlyFocused != 0 && ! currentlyFocusedChecker->hasBeenDeleted())
  41390. currentlyFocused->grabKeyboardFocus();
  41391. delete currentlyFocusedChecker;
  41392. return results.size() > 0;
  41393. }
  41394. FilePreviewComponent::FilePreviewComponent()
  41395. {
  41396. }
  41397. FilePreviewComponent::~FilePreviewComponent()
  41398. {
  41399. }
  41400. END_JUCE_NAMESPACE
  41401. /********* End of inlined file: juce_FileChooser.cpp *********/
  41402. /********* Start of inlined file: juce_FileChooserDialogBox.cpp *********/
  41403. BEGIN_JUCE_NAMESPACE
  41404. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  41405. const String& instructions,
  41406. FileBrowserComponent& chooserComponent,
  41407. const bool warnAboutOverwritingExistingFiles_,
  41408. const Colour& backgroundColour)
  41409. : ResizableWindow (name, backgroundColour, true),
  41410. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  41411. {
  41412. content = new ContentComponent();
  41413. content->setName (name);
  41414. content->instructions = instructions;
  41415. content->chooserComponent = &chooserComponent;
  41416. content->addAndMakeVisible (&chooserComponent);
  41417. content->okButton = new TextButton (chooserComponent.getActionVerb());
  41418. content->addAndMakeVisible (content->okButton);
  41419. content->okButton->addButtonListener (this);
  41420. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  41421. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  41422. content->cancelButton = new TextButton (TRANS("Cancel"));
  41423. content->addAndMakeVisible (content->cancelButton);
  41424. content->cancelButton->addButtonListener (this);
  41425. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  41426. setContentComponent (content);
  41427. setResizable (true, true);
  41428. setResizeLimits (300, 300, 1200, 1000);
  41429. content->chooserComponent->addListener (this);
  41430. }
  41431. FileChooserDialogBox::~FileChooserDialogBox()
  41432. {
  41433. content->chooserComponent->removeListener (this);
  41434. }
  41435. bool FileChooserDialogBox::show (int w, int h)
  41436. {
  41437. if (w <= 0)
  41438. {
  41439. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  41440. if (previewComp != 0)
  41441. w = 400 + previewComp->getWidth();
  41442. else
  41443. w = 600;
  41444. }
  41445. if (h <= 0)
  41446. h = 500;
  41447. centreWithSize (w, h);
  41448. const bool ok = (runModalLoop() != 0);
  41449. setVisible (false);
  41450. return ok;
  41451. }
  41452. void FileChooserDialogBox::buttonClicked (Button* button)
  41453. {
  41454. if (button == content->okButton)
  41455. {
  41456. if (warnAboutOverwritingExistingFiles
  41457. && content->chooserComponent->getMode() == FileBrowserComponent::saveFileMode
  41458. && content->chooserComponent->getCurrentFile().exists())
  41459. {
  41460. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  41461. TRANS("File already exists"),
  41462. TRANS("There's already a file called:\n\n")
  41463. + content->chooserComponent->getCurrentFile().getFullPathName()
  41464. + T("\n\nAre you sure you want to overwrite it?"),
  41465. TRANS("overwrite"),
  41466. TRANS("cancel")))
  41467. {
  41468. return;
  41469. }
  41470. }
  41471. exitModalState (1);
  41472. }
  41473. else if (button == content->cancelButton)
  41474. closeButtonPressed();
  41475. }
  41476. void FileChooserDialogBox::closeButtonPressed()
  41477. {
  41478. setVisible (false);
  41479. }
  41480. void FileChooserDialogBox::selectionChanged()
  41481. {
  41482. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  41483. }
  41484. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  41485. {
  41486. }
  41487. void FileChooserDialogBox::fileDoubleClicked (const File&)
  41488. {
  41489. selectionChanged();
  41490. content->okButton->triggerClick();
  41491. }
  41492. FileChooserDialogBox::ContentComponent::ContentComponent()
  41493. {
  41494. setInterceptsMouseClicks (false, true);
  41495. }
  41496. FileChooserDialogBox::ContentComponent::~ContentComponent()
  41497. {
  41498. delete okButton;
  41499. delete cancelButton;
  41500. }
  41501. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  41502. {
  41503. g.setColour (Colours::black);
  41504. text.draw (g);
  41505. }
  41506. void FileChooserDialogBox::ContentComponent::resized()
  41507. {
  41508. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  41509. float left, top, right, bottom;
  41510. text.getBoundingBox (0, text.getNumGlyphs(), left, top, right, bottom, false);
  41511. const int y = roundFloatToInt (bottom) + 10;
  41512. const int buttonHeight = 26;
  41513. const int buttonY = getHeight() - buttonHeight - 8;
  41514. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  41515. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  41516. proportionOfWidth (0.2f), buttonHeight);
  41517. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  41518. proportionOfWidth (0.2f), buttonHeight);
  41519. }
  41520. END_JUCE_NAMESPACE
  41521. /********* End of inlined file: juce_FileChooserDialogBox.cpp *********/
  41522. /********* Start of inlined file: juce_FileFilter.cpp *********/
  41523. BEGIN_JUCE_NAMESPACE
  41524. FileFilter::FileFilter (const String& filterDescription)
  41525. : description (filterDescription)
  41526. {
  41527. }
  41528. FileFilter::~FileFilter()
  41529. {
  41530. }
  41531. const String& FileFilter::getDescription() const throw()
  41532. {
  41533. return description;
  41534. }
  41535. END_JUCE_NAMESPACE
  41536. /********* End of inlined file: juce_FileFilter.cpp *********/
  41537. /********* Start of inlined file: juce_FileListComponent.cpp *********/
  41538. BEGIN_JUCE_NAMESPACE
  41539. Image* juce_createIconForFile (const File& file);
  41540. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  41541. : ListBox (String::empty, 0),
  41542. DirectoryContentsDisplayComponent (listToShow)
  41543. {
  41544. setModel (this);
  41545. fileList.addChangeListener (this);
  41546. }
  41547. FileListComponent::~FileListComponent()
  41548. {
  41549. fileList.removeChangeListener (this);
  41550. deleteAllChildren();
  41551. }
  41552. const File FileListComponent::getSelectedFile() const
  41553. {
  41554. return fileList.getFile (getSelectedRow());
  41555. }
  41556. void FileListComponent::scrollToTop()
  41557. {
  41558. getVerticalScrollBar()->setCurrentRangeStart (0);
  41559. }
  41560. void FileListComponent::changeListenerCallback (void*)
  41561. {
  41562. updateContent();
  41563. if (lastDirectory != fileList.getDirectory())
  41564. {
  41565. lastDirectory = fileList.getDirectory();
  41566. deselectAllRows();
  41567. }
  41568. }
  41569. class FileListItemComponent : public Component,
  41570. public TimeSliceClient,
  41571. public AsyncUpdater
  41572. {
  41573. public:
  41574. FileListItemComponent (FileListComponent& owner_,
  41575. TimeSliceThread& thread_) throw()
  41576. : owner (owner_),
  41577. thread (thread_),
  41578. icon (0)
  41579. {
  41580. }
  41581. ~FileListItemComponent() throw()
  41582. {
  41583. thread.removeTimeSliceClient (this);
  41584. clearIcon();
  41585. }
  41586. void paint (Graphics& g)
  41587. {
  41588. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  41589. file.getFileName(),
  41590. icon,
  41591. fileSize, modTime,
  41592. isDirectory, highlighted,
  41593. index);
  41594. }
  41595. void mouseDown (const MouseEvent& e)
  41596. {
  41597. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  41598. owner.sendMouseClickMessage (file, e);
  41599. }
  41600. void mouseDoubleClick (const MouseEvent&)
  41601. {
  41602. owner.sendDoubleClickMessage (file);
  41603. }
  41604. void update (const File& root,
  41605. const DirectoryContentsList::FileInfo* const fileInfo,
  41606. const int index_,
  41607. const bool highlighted_) throw()
  41608. {
  41609. thread.removeTimeSliceClient (this);
  41610. if (highlighted_ != highlighted
  41611. || index_ != index)
  41612. {
  41613. index = index_;
  41614. highlighted = highlighted_;
  41615. repaint();
  41616. }
  41617. File newFile;
  41618. String newFileSize;
  41619. String newModTime;
  41620. if (fileInfo != 0)
  41621. {
  41622. newFile = root.getChildFile (fileInfo->filename);
  41623. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  41624. newModTime = fileInfo->modificationTime.formatted (T("%d %b '%y %H:%M"));
  41625. }
  41626. if (newFile != file
  41627. || fileSize != newFileSize
  41628. || modTime != newModTime)
  41629. {
  41630. file = newFile;
  41631. fileSize = newFileSize;
  41632. modTime = newModTime;
  41633. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  41634. repaint();
  41635. clearIcon();
  41636. }
  41637. if (file != File::nonexistent
  41638. && icon == 0 && ! isDirectory)
  41639. {
  41640. updateIcon (true);
  41641. if (icon == 0)
  41642. thread.addTimeSliceClient (this);
  41643. }
  41644. }
  41645. bool useTimeSlice()
  41646. {
  41647. updateIcon (false);
  41648. return false;
  41649. }
  41650. void handleAsyncUpdate()
  41651. {
  41652. repaint();
  41653. }
  41654. juce_UseDebuggingNewOperator
  41655. private:
  41656. FileListComponent& owner;
  41657. TimeSliceThread& thread;
  41658. bool highlighted;
  41659. int index;
  41660. File file;
  41661. String fileSize;
  41662. String modTime;
  41663. Image* icon;
  41664. bool isDirectory;
  41665. void clearIcon() throw()
  41666. {
  41667. ImageCache::release (icon);
  41668. icon = 0;
  41669. }
  41670. void updateIcon (const bool onlyUpdateIfCached) throw()
  41671. {
  41672. if (icon == 0)
  41673. {
  41674. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  41675. Image* im = ImageCache::getFromHashCode (hashCode);
  41676. if (im == 0 && ! onlyUpdateIfCached)
  41677. {
  41678. im = juce_createIconForFile (file);
  41679. if (im != 0)
  41680. ImageCache::addImageToCache (im, hashCode);
  41681. }
  41682. if (im != 0)
  41683. {
  41684. icon = im;
  41685. triggerAsyncUpdate();
  41686. }
  41687. }
  41688. }
  41689. };
  41690. int FileListComponent::getNumRows()
  41691. {
  41692. return fileList.getNumFiles();
  41693. }
  41694. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  41695. {
  41696. }
  41697. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  41698. {
  41699. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  41700. if (comp == 0)
  41701. {
  41702. delete existingComponentToUpdate;
  41703. existingComponentToUpdate = comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  41704. }
  41705. DirectoryContentsList::FileInfo fileInfo;
  41706. if (fileList.getFileInfo (row, fileInfo))
  41707. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  41708. else
  41709. comp->update (fileList.getDirectory(), 0, row, isSelected);
  41710. return comp;
  41711. }
  41712. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  41713. {
  41714. sendSelectionChangeMessage();
  41715. }
  41716. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  41717. {
  41718. }
  41719. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  41720. {
  41721. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  41722. }
  41723. END_JUCE_NAMESPACE
  41724. /********* End of inlined file: juce_FileListComponent.cpp *********/
  41725. /********* Start of inlined file: juce_FilenameComponent.cpp *********/
  41726. BEGIN_JUCE_NAMESPACE
  41727. FilenameComponent::FilenameComponent (const String& name,
  41728. const File& currentFile,
  41729. const bool canEditFilename,
  41730. const bool isDirectory,
  41731. const bool isForSaving,
  41732. const String& fileBrowserWildcard,
  41733. const String& enforcedSuffix_,
  41734. const String& textWhenNothingSelected)
  41735. : Component (name),
  41736. maxRecentFiles (30),
  41737. isDir (isDirectory),
  41738. isSaving (isForSaving),
  41739. isFileDragOver (false),
  41740. wildcard (fileBrowserWildcard),
  41741. enforcedSuffix (enforcedSuffix_)
  41742. {
  41743. addAndMakeVisible (filenameBox = new ComboBox (T("fn")));
  41744. filenameBox->setEditableText (canEditFilename);
  41745. filenameBox->addListener (this);
  41746. filenameBox->setTextWhenNothingSelected (textWhenNothingSelected);
  41747. filenameBox->setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  41748. browseButton = 0;
  41749. setBrowseButtonText (T("..."));
  41750. setCurrentFile (currentFile, true);
  41751. }
  41752. FilenameComponent::~FilenameComponent()
  41753. {
  41754. deleteAllChildren();
  41755. }
  41756. void FilenameComponent::paintOverChildren (Graphics& g)
  41757. {
  41758. if (isFileDragOver)
  41759. {
  41760. g.setColour (Colours::red.withAlpha (0.2f));
  41761. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  41762. }
  41763. }
  41764. void FilenameComponent::resized()
  41765. {
  41766. getLookAndFeel().layoutFilenameComponent (*this, filenameBox, browseButton);
  41767. }
  41768. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  41769. {
  41770. browseButtonText = newBrowseButtonText;
  41771. lookAndFeelChanged();
  41772. }
  41773. void FilenameComponent::lookAndFeelChanged()
  41774. {
  41775. deleteAndZero (browseButton);
  41776. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  41777. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  41778. resized();
  41779. browseButton->addButtonListener (this);
  41780. }
  41781. void FilenameComponent::setTooltip (const String& newTooltip)
  41782. {
  41783. SettableTooltipClient::setTooltip (newTooltip);
  41784. filenameBox->setTooltip (newTooltip);
  41785. }
  41786. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  41787. {
  41788. defaultBrowseFile = newDefaultDirectory;
  41789. }
  41790. void FilenameComponent::buttonClicked (Button*)
  41791. {
  41792. FileChooser fc (TRANS("Choose a new file"),
  41793. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  41794. : getCurrentFile(),
  41795. wildcard);
  41796. if (isDir ? fc.browseForDirectory()
  41797. : (isSaving ? fc.browseForFileToSave (false)
  41798. : fc.browseForFileToOpen()))
  41799. {
  41800. setCurrentFile (fc.getResult(), true);
  41801. }
  41802. }
  41803. void FilenameComponent::comboBoxChanged (ComboBox*)
  41804. {
  41805. setCurrentFile (getCurrentFile(), true);
  41806. }
  41807. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  41808. {
  41809. return true;
  41810. }
  41811. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  41812. {
  41813. isFileDragOver = false;
  41814. repaint();
  41815. const File f (filenames[0]);
  41816. if (f.exists() && (f.isDirectory() == isDir))
  41817. setCurrentFile (f, true);
  41818. }
  41819. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  41820. {
  41821. isFileDragOver = true;
  41822. repaint();
  41823. }
  41824. void FilenameComponent::fileDragExit (const StringArray&)
  41825. {
  41826. isFileDragOver = false;
  41827. repaint();
  41828. }
  41829. const File FilenameComponent::getCurrentFile() const
  41830. {
  41831. File f (filenameBox->getText());
  41832. if (enforcedSuffix.isNotEmpty())
  41833. f = f.withFileExtension (enforcedSuffix);
  41834. return f;
  41835. }
  41836. void FilenameComponent::setCurrentFile (File newFile,
  41837. const bool addToRecentlyUsedList,
  41838. const bool sendChangeNotification)
  41839. {
  41840. if (enforcedSuffix.isNotEmpty())
  41841. newFile = newFile.withFileExtension (enforcedSuffix);
  41842. if (newFile.getFullPathName() != lastFilename)
  41843. {
  41844. lastFilename = newFile.getFullPathName();
  41845. if (addToRecentlyUsedList)
  41846. addRecentlyUsedFile (newFile);
  41847. filenameBox->setText (lastFilename, true);
  41848. if (sendChangeNotification)
  41849. triggerAsyncUpdate();
  41850. }
  41851. }
  41852. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  41853. {
  41854. filenameBox->setEditableText (shouldBeEditable);
  41855. }
  41856. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  41857. {
  41858. StringArray names;
  41859. for (int i = 0; i < filenameBox->getNumItems(); ++i)
  41860. names.add (filenameBox->getItemText (i));
  41861. return names;
  41862. }
  41863. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  41864. {
  41865. if (filenames != getRecentlyUsedFilenames())
  41866. {
  41867. filenameBox->clear();
  41868. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  41869. filenameBox->addItem (filenames[i], i + 1);
  41870. }
  41871. }
  41872. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  41873. {
  41874. maxRecentFiles = jmax (1, newMaximum);
  41875. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  41876. }
  41877. void FilenameComponent::addRecentlyUsedFile (const File& file)
  41878. {
  41879. StringArray files (getRecentlyUsedFilenames());
  41880. if (file.getFullPathName().isNotEmpty())
  41881. {
  41882. files.removeString (file.getFullPathName(), true);
  41883. files.insert (0, file.getFullPathName());
  41884. setRecentlyUsedFilenames (files);
  41885. }
  41886. }
  41887. void FilenameComponent::addListener (FilenameComponentListener* const listener) throw()
  41888. {
  41889. jassert (listener != 0);
  41890. if (listener != 0)
  41891. listeners.add (listener);
  41892. }
  41893. void FilenameComponent::removeListener (FilenameComponentListener* const listener) throw()
  41894. {
  41895. listeners.removeValue (listener);
  41896. }
  41897. void FilenameComponent::handleAsyncUpdate()
  41898. {
  41899. for (int i = listeners.size(); --i >= 0;)
  41900. {
  41901. ((FilenameComponentListener*) listeners.getUnchecked (i))->filenameComponentChanged (this);
  41902. i = jmin (i, listeners.size());
  41903. }
  41904. }
  41905. END_JUCE_NAMESPACE
  41906. /********* End of inlined file: juce_FilenameComponent.cpp *********/
  41907. /********* Start of inlined file: juce_FileSearchPathListComponent.cpp *********/
  41908. BEGIN_JUCE_NAMESPACE
  41909. FileSearchPathListComponent::FileSearchPathListComponent()
  41910. {
  41911. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  41912. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  41913. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  41914. listBox->setOutlineThickness (1);
  41915. addAndMakeVisible (addButton = new TextButton ("+"));
  41916. addButton->addButtonListener (this);
  41917. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  41918. addAndMakeVisible (removeButton = new TextButton ("-"));
  41919. removeButton->addButtonListener (this);
  41920. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  41921. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  41922. changeButton->addButtonListener (this);
  41923. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  41924. upButton->addButtonListener (this);
  41925. {
  41926. Path arrowPath;
  41927. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  41928. DrawablePath arrowImage;
  41929. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  41930. arrowImage.setPath (arrowPath);
  41931. ((DrawableButton*) upButton)->setImages (&arrowImage);
  41932. }
  41933. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  41934. downButton->addButtonListener (this);
  41935. {
  41936. Path arrowPath;
  41937. arrowPath.addArrow (50.0f, 0.0f, 50.0f, 100.0f, 40.0f, 100.0f, 50.0f);
  41938. DrawablePath arrowImage;
  41939. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  41940. arrowImage.setPath (arrowPath);
  41941. ((DrawableButton*) downButton)->setImages (&arrowImage);
  41942. }
  41943. updateButtons();
  41944. }
  41945. FileSearchPathListComponent::~FileSearchPathListComponent()
  41946. {
  41947. deleteAllChildren();
  41948. }
  41949. void FileSearchPathListComponent::updateButtons() throw()
  41950. {
  41951. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  41952. removeButton->setEnabled (anythingSelected);
  41953. changeButton->setEnabled (anythingSelected);
  41954. upButton->setEnabled (anythingSelected);
  41955. downButton->setEnabled (anythingSelected);
  41956. }
  41957. void FileSearchPathListComponent::changed() throw()
  41958. {
  41959. listBox->updateContent();
  41960. listBox->repaint();
  41961. updateButtons();
  41962. }
  41963. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  41964. {
  41965. if (newPath.toString() != path.toString())
  41966. {
  41967. path = newPath;
  41968. changed();
  41969. }
  41970. }
  41971. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  41972. {
  41973. defaultBrowseTarget = newDefaultDirectory;
  41974. }
  41975. int FileSearchPathListComponent::getNumRows()
  41976. {
  41977. return path.getNumPaths();
  41978. }
  41979. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  41980. {
  41981. if (rowIsSelected)
  41982. g.fillAll (findColour (TextEditor::highlightColourId));
  41983. g.setColour (findColour (ListBox::textColourId));
  41984. Font f (height * 0.7f);
  41985. f.setHorizontalScale (0.9f);
  41986. g.setFont (f);
  41987. g.drawText (path [rowNumber].getFullPathName(),
  41988. 4, 0, width - 6, height,
  41989. Justification::centredLeft, true);
  41990. }
  41991. void FileSearchPathListComponent::deleteKeyPressed (int row)
  41992. {
  41993. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  41994. {
  41995. path.remove (row);
  41996. changed();
  41997. }
  41998. }
  41999. void FileSearchPathListComponent::returnKeyPressed (int row)
  42000. {
  42001. FileChooser chooser (TRANS("Change folder..."), path [row], T("*"));
  42002. if (chooser.browseForDirectory())
  42003. {
  42004. path.remove (row);
  42005. path.add (chooser.getResult(), row);
  42006. changed();
  42007. }
  42008. }
  42009. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  42010. {
  42011. returnKeyPressed (row);
  42012. }
  42013. void FileSearchPathListComponent::selectedRowsChanged (int)
  42014. {
  42015. updateButtons();
  42016. }
  42017. void FileSearchPathListComponent::paint (Graphics& g)
  42018. {
  42019. g.fillAll (findColour (backgroundColourId));
  42020. }
  42021. void FileSearchPathListComponent::resized()
  42022. {
  42023. const int buttonH = 22;
  42024. const int buttonY = getHeight() - buttonH - 4;
  42025. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  42026. addButton->setBounds (2, buttonY, buttonH, buttonH);
  42027. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  42028. ((TextButton*) changeButton)->changeWidthToFitText (buttonH);
  42029. downButton->setSize (buttonH * 2, buttonH);
  42030. upButton->setSize (buttonH * 2, buttonH);
  42031. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  42032. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  42033. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  42034. }
  42035. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  42036. {
  42037. return true;
  42038. }
  42039. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  42040. {
  42041. for (int i = filenames.size(); --i >= 0;)
  42042. {
  42043. const File f (filenames[i]);
  42044. if (f.isDirectory())
  42045. {
  42046. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  42047. path.add (f, row);
  42048. changed();
  42049. }
  42050. }
  42051. }
  42052. void FileSearchPathListComponent::buttonClicked (Button* button)
  42053. {
  42054. const int currentRow = listBox->getSelectedRow();
  42055. if (button == removeButton)
  42056. {
  42057. deleteKeyPressed (currentRow);
  42058. }
  42059. else if (button == addButton)
  42060. {
  42061. File start (defaultBrowseTarget);
  42062. if (start == File::nonexistent)
  42063. start = path [0];
  42064. if (start == File::nonexistent)
  42065. start = File::getCurrentWorkingDirectory();
  42066. FileChooser chooser (TRANS("Add a folder..."), start, T("*"));
  42067. if (chooser.browseForDirectory())
  42068. {
  42069. path.add (chooser.getResult(), currentRow);
  42070. }
  42071. }
  42072. else if (button == changeButton)
  42073. {
  42074. returnKeyPressed (currentRow);
  42075. }
  42076. else if (button == upButton)
  42077. {
  42078. if (currentRow > 0 && currentRow < path.getNumPaths())
  42079. {
  42080. const File f (path[currentRow]);
  42081. path.remove (currentRow);
  42082. path.add (f, currentRow - 1);
  42083. listBox->selectRow (currentRow - 1);
  42084. }
  42085. }
  42086. else if (button == downButton)
  42087. {
  42088. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  42089. {
  42090. const File f (path[currentRow]);
  42091. path.remove (currentRow);
  42092. path.add (f, currentRow + 1);
  42093. listBox->selectRow (currentRow + 1);
  42094. }
  42095. }
  42096. changed();
  42097. }
  42098. END_JUCE_NAMESPACE
  42099. /********* End of inlined file: juce_FileSearchPathListComponent.cpp *********/
  42100. /********* Start of inlined file: juce_FileTreeComponent.cpp *********/
  42101. BEGIN_JUCE_NAMESPACE
  42102. Image* juce_createIconForFile (const File& file);
  42103. class FileListTreeItem : public TreeViewItem,
  42104. public TimeSliceClient,
  42105. public AsyncUpdater,
  42106. public ChangeListener
  42107. {
  42108. public:
  42109. FileListTreeItem (FileTreeComponent& owner_,
  42110. DirectoryContentsList* const parentContentsList_,
  42111. const int indexInContentsList_,
  42112. const File& file_,
  42113. TimeSliceThread& thread_) throw()
  42114. : file (file_),
  42115. owner (owner_),
  42116. parentContentsList (parentContentsList_),
  42117. indexInContentsList (indexInContentsList_),
  42118. subContentsList (0),
  42119. canDeleteSubContentsList (false),
  42120. thread (thread_),
  42121. icon (0)
  42122. {
  42123. DirectoryContentsList::FileInfo fileInfo;
  42124. if (parentContentsList_ != 0
  42125. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  42126. {
  42127. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  42128. modTime = fileInfo.modificationTime.formatted (T("%d %b '%y %H:%M"));
  42129. isDirectory = fileInfo.isDirectory;
  42130. }
  42131. else
  42132. {
  42133. isDirectory = true;
  42134. }
  42135. }
  42136. ~FileListTreeItem() throw()
  42137. {
  42138. thread.removeTimeSliceClient (this);
  42139. clearSubItems();
  42140. ImageCache::release (icon);
  42141. if (canDeleteSubContentsList)
  42142. delete subContentsList;
  42143. }
  42144. bool mightContainSubItems() { return isDirectory; }
  42145. const String getUniqueName() const { return file.getFullPathName(); }
  42146. int getItemHeight() const { return 22; }
  42147. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  42148. void itemOpennessChanged (bool isNowOpen)
  42149. {
  42150. if (isNowOpen)
  42151. {
  42152. clearSubItems();
  42153. isDirectory = file.isDirectory();
  42154. if (isDirectory)
  42155. {
  42156. if (subContentsList == 0)
  42157. {
  42158. jassert (parentContentsList != 0);
  42159. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  42160. l->setDirectory (file, true, true);
  42161. setSubContentsList (l);
  42162. canDeleteSubContentsList = true;
  42163. }
  42164. changeListenerCallback (0);
  42165. }
  42166. }
  42167. }
  42168. void setSubContentsList (DirectoryContentsList* newList) throw()
  42169. {
  42170. jassert (subContentsList == 0);
  42171. subContentsList = newList;
  42172. newList->addChangeListener (this);
  42173. }
  42174. void changeListenerCallback (void*)
  42175. {
  42176. clearSubItems();
  42177. if (isOpen() && subContentsList != 0)
  42178. {
  42179. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  42180. {
  42181. FileListTreeItem* const item
  42182. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  42183. addSubItem (item);
  42184. }
  42185. }
  42186. }
  42187. void paintItem (Graphics& g, int width, int height)
  42188. {
  42189. if (file != File::nonexistent && ! isDirectory)
  42190. {
  42191. updateIcon (true);
  42192. if (icon == 0)
  42193. thread.addTimeSliceClient (this);
  42194. }
  42195. owner.getLookAndFeel()
  42196. .drawFileBrowserRow (g, width, height,
  42197. file.getFileName(),
  42198. icon,
  42199. fileSize, modTime,
  42200. isDirectory, isSelected(),
  42201. indexInContentsList);
  42202. }
  42203. void itemClicked (const MouseEvent& e)
  42204. {
  42205. owner.sendMouseClickMessage (file, e);
  42206. }
  42207. void itemDoubleClicked (const MouseEvent& e)
  42208. {
  42209. TreeViewItem::itemDoubleClicked (e);
  42210. owner.sendDoubleClickMessage (file);
  42211. }
  42212. void itemSelectionChanged (bool)
  42213. {
  42214. owner.sendSelectionChangeMessage();
  42215. }
  42216. bool useTimeSlice()
  42217. {
  42218. updateIcon (false);
  42219. thread.removeTimeSliceClient (this);
  42220. return false;
  42221. }
  42222. void handleAsyncUpdate()
  42223. {
  42224. owner.repaint();
  42225. }
  42226. const File file;
  42227. juce_UseDebuggingNewOperator
  42228. private:
  42229. FileTreeComponent& owner;
  42230. DirectoryContentsList* parentContentsList;
  42231. int indexInContentsList;
  42232. DirectoryContentsList* subContentsList;
  42233. bool isDirectory, canDeleteSubContentsList;
  42234. TimeSliceThread& thread;
  42235. Image* icon;
  42236. String fileSize;
  42237. String modTime;
  42238. void updateIcon (const bool onlyUpdateIfCached) throw()
  42239. {
  42240. if (icon == 0)
  42241. {
  42242. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  42243. Image* im = ImageCache::getFromHashCode (hashCode);
  42244. if (im == 0 && ! onlyUpdateIfCached)
  42245. {
  42246. im = juce_createIconForFile (file);
  42247. if (im != 0)
  42248. ImageCache::addImageToCache (im, hashCode);
  42249. }
  42250. if (im != 0)
  42251. {
  42252. icon = im;
  42253. triggerAsyncUpdate();
  42254. }
  42255. }
  42256. }
  42257. };
  42258. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  42259. : DirectoryContentsDisplayComponent (listToShow)
  42260. {
  42261. FileListTreeItem* const root
  42262. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  42263. listToShow.getTimeSliceThread());
  42264. root->setSubContentsList (&listToShow);
  42265. setRootItemVisible (false);
  42266. setRootItem (root);
  42267. }
  42268. FileTreeComponent::~FileTreeComponent()
  42269. {
  42270. TreeViewItem* const root = getRootItem();
  42271. setRootItem (0);
  42272. delete root;
  42273. }
  42274. const File FileTreeComponent::getSelectedFile() const
  42275. {
  42276. return getSelectedFile (0);
  42277. }
  42278. const File FileTreeComponent::getSelectedFile (const int index) const throw()
  42279. {
  42280. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  42281. if (item != 0)
  42282. return item->file;
  42283. return File::nonexistent;
  42284. }
  42285. void FileTreeComponent::scrollToTop()
  42286. {
  42287. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  42288. }
  42289. void FileTreeComponent::setDragAndDropDescription (const String& description) throw()
  42290. {
  42291. dragAndDropDescription = description;
  42292. }
  42293. END_JUCE_NAMESPACE
  42294. /********* End of inlined file: juce_FileTreeComponent.cpp *********/
  42295. /********* Start of inlined file: juce_ImagePreviewComponent.cpp *********/
  42296. BEGIN_JUCE_NAMESPACE
  42297. ImagePreviewComponent::ImagePreviewComponent()
  42298. : currentThumbnail (0)
  42299. {
  42300. }
  42301. ImagePreviewComponent::~ImagePreviewComponent()
  42302. {
  42303. delete currentThumbnail;
  42304. }
  42305. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  42306. {
  42307. const int availableW = proportionOfWidth (0.97f);
  42308. const int availableH = getHeight() - 13 * 4;
  42309. const double scale = jmin (1.0,
  42310. availableW / (double) w,
  42311. availableH / (double) h);
  42312. w = roundDoubleToInt (scale * w);
  42313. h = roundDoubleToInt (scale * h);
  42314. }
  42315. void ImagePreviewComponent::selectedFileChanged (const File& file)
  42316. {
  42317. if (fileToLoad != file)
  42318. {
  42319. fileToLoad = file;
  42320. startTimer (100);
  42321. }
  42322. }
  42323. void ImagePreviewComponent::timerCallback()
  42324. {
  42325. stopTimer();
  42326. deleteAndZero (currentThumbnail);
  42327. currentDetails = String::empty;
  42328. repaint();
  42329. FileInputStream* const in = fileToLoad.createInputStream();
  42330. if (in != 0)
  42331. {
  42332. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  42333. if (format != 0)
  42334. {
  42335. currentThumbnail = format->decodeImage (*in);
  42336. if (currentThumbnail != 0)
  42337. {
  42338. int w = currentThumbnail->getWidth();
  42339. int h = currentThumbnail->getHeight();
  42340. currentDetails
  42341. << fileToLoad.getFileName() << "\n"
  42342. << format->getFormatName() << "\n"
  42343. << w << " x " << h << " pixels\n"
  42344. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  42345. getThumbSize (w, h);
  42346. Image* const reduced = currentThumbnail->createCopy (w, h);
  42347. delete currentThumbnail;
  42348. currentThumbnail = reduced;
  42349. }
  42350. }
  42351. delete in;
  42352. }
  42353. }
  42354. void ImagePreviewComponent::paint (Graphics& g)
  42355. {
  42356. if (currentThumbnail != 0)
  42357. {
  42358. g.setFont (13.0f);
  42359. int w = currentThumbnail->getWidth();
  42360. int h = currentThumbnail->getHeight();
  42361. getThumbSize (w, h);
  42362. const int numLines = 4;
  42363. const int totalH = 13 * numLines + h + 4;
  42364. const int y = (getHeight() - totalH) / 2;
  42365. g.drawImageWithin (currentThumbnail,
  42366. (getWidth() - w) / 2, y, w, h,
  42367. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  42368. false);
  42369. g.drawFittedText (currentDetails,
  42370. 0, y + h + 4, getWidth(), 100,
  42371. Justification::centredTop, numLines);
  42372. }
  42373. }
  42374. END_JUCE_NAMESPACE
  42375. /********* End of inlined file: juce_ImagePreviewComponent.cpp *********/
  42376. /********* Start of inlined file: juce_WildcardFileFilter.cpp *********/
  42377. BEGIN_JUCE_NAMESPACE
  42378. WildcardFileFilter::WildcardFileFilter (const String& wildcardPatterns,
  42379. const String& description)
  42380. : FileFilter (description.isEmpty() ? wildcardPatterns
  42381. : (description + T(" (") + wildcardPatterns + T(")")))
  42382. {
  42383. wildcards.addTokens (wildcardPatterns.toLowerCase(), T(";,"), T("\"'"));
  42384. wildcards.trim();
  42385. wildcards.removeEmptyStrings();
  42386. // special case for *.*, because people use it to mean "any file", but it
  42387. // would actually ignore files with no extension.
  42388. for (int i = wildcards.size(); --i >= 0;)
  42389. if (wildcards[i] == T("*.*"))
  42390. wildcards.set (i, T("*"));
  42391. }
  42392. WildcardFileFilter::~WildcardFileFilter()
  42393. {
  42394. }
  42395. bool WildcardFileFilter::isFileSuitable (const File& file) const
  42396. {
  42397. const String filename (file.getFileName());
  42398. for (int i = wildcards.size(); --i >= 0;)
  42399. if (filename.matchesWildcard (wildcards[i], true))
  42400. return true;
  42401. return false;
  42402. }
  42403. bool WildcardFileFilter::isDirectorySuitable (const File&) const
  42404. {
  42405. return true;
  42406. }
  42407. END_JUCE_NAMESPACE
  42408. /********* End of inlined file: juce_WildcardFileFilter.cpp *********/
  42409. /********* Start of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  42410. BEGIN_JUCE_NAMESPACE
  42411. KeyboardFocusTraverser::KeyboardFocusTraverser()
  42412. {
  42413. }
  42414. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  42415. {
  42416. }
  42417. // This will sort a set of components, so that they are ordered in terms of
  42418. // left-to-right and then top-to-bottom.
  42419. class ScreenPositionComparator
  42420. {
  42421. public:
  42422. ScreenPositionComparator() {}
  42423. static int compareElements (const Component* const first, const Component* const second) throw()
  42424. {
  42425. int explicitOrder1 = first->getExplicitFocusOrder();
  42426. if (explicitOrder1 <= 0)
  42427. explicitOrder1 = INT_MAX / 2;
  42428. int explicitOrder2 = second->getExplicitFocusOrder();
  42429. if (explicitOrder2 <= 0)
  42430. explicitOrder2 = INT_MAX / 2;
  42431. if (explicitOrder1 != explicitOrder2)
  42432. return explicitOrder1 - explicitOrder2;
  42433. const int diff = first->getY() - second->getY();
  42434. return (diff == 0) ? first->getX() - second->getX()
  42435. : diff;
  42436. }
  42437. };
  42438. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  42439. {
  42440. if (parent->getNumChildComponents() > 0)
  42441. {
  42442. Array <Component*> localComps;
  42443. ScreenPositionComparator comparator;
  42444. int i;
  42445. for (i = parent->getNumChildComponents(); --i >= 0;)
  42446. {
  42447. Component* const c = parent->getChildComponent (i);
  42448. if (c->isVisible() && c->isEnabled())
  42449. localComps.addSorted (comparator, c);
  42450. }
  42451. for (i = 0; i < localComps.size(); ++i)
  42452. {
  42453. Component* const c = localComps.getUnchecked (i);
  42454. if (c->getWantsKeyboardFocus())
  42455. comps.add (c);
  42456. if (! c->isFocusContainer())
  42457. findAllFocusableComponents (c, comps);
  42458. }
  42459. }
  42460. }
  42461. static Component* getIncrementedComponent (Component* const current, const int delta) throw()
  42462. {
  42463. Component* focusContainer = current->getParentComponent();
  42464. if (focusContainer != 0)
  42465. {
  42466. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  42467. focusContainer = focusContainer->getParentComponent();
  42468. if (focusContainer != 0)
  42469. {
  42470. Array <Component*> comps;
  42471. findAllFocusableComponents (focusContainer, comps);
  42472. if (comps.size() > 0)
  42473. {
  42474. const int index = comps.indexOf (current);
  42475. return comps [(index + comps.size() + delta) % comps.size()];
  42476. }
  42477. }
  42478. }
  42479. return 0;
  42480. }
  42481. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  42482. {
  42483. return getIncrementedComponent (current, 1);
  42484. }
  42485. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  42486. {
  42487. return getIncrementedComponent (current, -1);
  42488. }
  42489. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  42490. {
  42491. Array <Component*> comps;
  42492. if (parentComponent != 0)
  42493. findAllFocusableComponents (parentComponent, comps);
  42494. return comps.getFirst();
  42495. }
  42496. END_JUCE_NAMESPACE
  42497. /********* End of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  42498. /********* Start of inlined file: juce_KeyListener.cpp *********/
  42499. BEGIN_JUCE_NAMESPACE
  42500. bool KeyListener::keyStateChanged (Component*)
  42501. {
  42502. return false;
  42503. }
  42504. END_JUCE_NAMESPACE
  42505. /********* End of inlined file: juce_KeyListener.cpp *********/
  42506. /********* Start of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  42507. BEGIN_JUCE_NAMESPACE
  42508. // N.B. these two includes are put here deliberately to avoid problems with
  42509. // old GCCs failing on long include paths
  42510. const int maxKeys = 3;
  42511. class KeyMappingChangeButton : public Button
  42512. {
  42513. public:
  42514. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  42515. const CommandID commandID_,
  42516. const String& keyName,
  42517. const int keyNum_)
  42518. : Button (keyName),
  42519. owner (owner_),
  42520. commandID (commandID_),
  42521. keyNum (keyNum_)
  42522. {
  42523. setWantsKeyboardFocus (false);
  42524. setTriggeredOnMouseDown (keyNum >= 0);
  42525. if (keyNum_ < 0)
  42526. setTooltip (TRANS("adds a new key-mapping"));
  42527. else
  42528. setTooltip (TRANS("click to change this key-mapping"));
  42529. }
  42530. ~KeyMappingChangeButton()
  42531. {
  42532. }
  42533. void paintButton (Graphics& g, bool isOver, bool isDown)
  42534. {
  42535. if (keyNum >= 0)
  42536. {
  42537. if (isEnabled())
  42538. {
  42539. const float alpha = isDown ? 0.3f : (isOver ? 0.15f : 0.08f);
  42540. g.fillAll (owner->textColour.withAlpha (alpha));
  42541. g.setOpacity (0.3f);
  42542. g.drawBevel (0, 0, getWidth(), getHeight(), 2);
  42543. }
  42544. g.setColour (owner->textColour);
  42545. g.setFont (getHeight() * 0.6f);
  42546. g.drawFittedText (getName(),
  42547. 3, 0, getWidth() - 6, getHeight(),
  42548. Justification::centred, 1);
  42549. }
  42550. else
  42551. {
  42552. const float thickness = 7.0f;
  42553. const float indent = 22.0f;
  42554. Path p;
  42555. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  42556. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  42557. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  42558. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  42559. p.setUsingNonZeroWinding (false);
  42560. g.setColour (owner->textColour.withAlpha (isDown ? 0.7f : (isOver ? 0.5f : 0.3f)));
  42561. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, true));
  42562. }
  42563. if (hasKeyboardFocus (false))
  42564. {
  42565. g.setColour (owner->textColour.withAlpha (0.4f));
  42566. g.drawRect (0, 0, getWidth(), getHeight());
  42567. }
  42568. }
  42569. void clicked()
  42570. {
  42571. if (keyNum >= 0)
  42572. {
  42573. // existing key clicked..
  42574. PopupMenu m;
  42575. m.addItem (1, TRANS("change this key-mapping"));
  42576. m.addSeparator();
  42577. m.addItem (2, TRANS("remove this key-mapping"));
  42578. const int res = m.show();
  42579. if (res == 1)
  42580. {
  42581. owner->assignNewKey (commandID, keyNum);
  42582. }
  42583. else if (res == 2)
  42584. {
  42585. owner->getMappings()->removeKeyPress (commandID, keyNum);
  42586. }
  42587. }
  42588. else
  42589. {
  42590. // + button pressed..
  42591. owner->assignNewKey (commandID, -1);
  42592. }
  42593. }
  42594. void fitToContent (const int h) throw()
  42595. {
  42596. if (keyNum < 0)
  42597. {
  42598. setSize (h, h);
  42599. }
  42600. else
  42601. {
  42602. Font f (h * 0.6f);
  42603. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  42604. }
  42605. }
  42606. juce_UseDebuggingNewOperator
  42607. private:
  42608. KeyMappingEditorComponent* const owner;
  42609. const CommandID commandID;
  42610. const int keyNum;
  42611. KeyMappingChangeButton (const KeyMappingChangeButton&);
  42612. const KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  42613. };
  42614. class KeyMappingItemComponent : public Component
  42615. {
  42616. public:
  42617. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  42618. const CommandID commandID_)
  42619. : owner (owner_),
  42620. commandID (commandID_)
  42621. {
  42622. setInterceptsMouseClicks (false, true);
  42623. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  42624. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  42625. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  42626. {
  42627. KeyMappingChangeButton* const kb
  42628. = new KeyMappingChangeButton (owner_, commandID,
  42629. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  42630. kb->setEnabled (! isReadOnly);
  42631. addAndMakeVisible (kb);
  42632. }
  42633. KeyMappingChangeButton* const kb
  42634. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  42635. addChildComponent (kb);
  42636. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  42637. }
  42638. ~KeyMappingItemComponent()
  42639. {
  42640. deleteAllChildren();
  42641. }
  42642. void paint (Graphics& g)
  42643. {
  42644. g.setFont (getHeight() * 0.7f);
  42645. g.setColour (owner->textColour);
  42646. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  42647. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  42648. Justification::centredLeft, true);
  42649. }
  42650. void resized()
  42651. {
  42652. int x = getWidth() - 4;
  42653. for (int i = getNumChildComponents(); --i >= 0;)
  42654. {
  42655. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  42656. kb->fitToContent (getHeight() - 2);
  42657. kb->setTopRightPosition (x, 1);
  42658. x -= kb->getWidth() + 5;
  42659. }
  42660. }
  42661. juce_UseDebuggingNewOperator
  42662. private:
  42663. KeyMappingEditorComponent* const owner;
  42664. const CommandID commandID;
  42665. KeyMappingItemComponent (const KeyMappingItemComponent&);
  42666. const KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  42667. };
  42668. class KeyMappingTreeViewItem : public TreeViewItem
  42669. {
  42670. public:
  42671. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  42672. const CommandID commandID_)
  42673. : owner (owner_),
  42674. commandID (commandID_)
  42675. {
  42676. }
  42677. ~KeyMappingTreeViewItem()
  42678. {
  42679. }
  42680. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  42681. bool mightContainSubItems() { return false; }
  42682. int getItemHeight() const { return 20; }
  42683. Component* createItemComponent()
  42684. {
  42685. return new KeyMappingItemComponent (owner, commandID);
  42686. }
  42687. juce_UseDebuggingNewOperator
  42688. private:
  42689. KeyMappingEditorComponent* const owner;
  42690. const CommandID commandID;
  42691. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  42692. const KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  42693. };
  42694. class KeyCategoryTreeViewItem : public TreeViewItem
  42695. {
  42696. public:
  42697. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  42698. const String& name)
  42699. : owner (owner_),
  42700. categoryName (name)
  42701. {
  42702. }
  42703. ~KeyCategoryTreeViewItem()
  42704. {
  42705. }
  42706. const String getUniqueName() const { return categoryName + "_cat"; }
  42707. bool mightContainSubItems() { return true; }
  42708. int getItemHeight() const { return 28; }
  42709. void paintItem (Graphics& g, int width, int height)
  42710. {
  42711. g.setFont (height * 0.6f, Font::bold);
  42712. g.setColour (owner->textColour);
  42713. g.drawText (categoryName,
  42714. 2, 0, width - 2, height,
  42715. Justification::centredLeft, true);
  42716. }
  42717. void itemOpennessChanged (bool isNowOpen)
  42718. {
  42719. if (isNowOpen)
  42720. {
  42721. if (getNumSubItems() == 0)
  42722. {
  42723. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  42724. for (int i = 0; i < commands.size(); ++i)
  42725. {
  42726. if (owner->shouldCommandBeIncluded (commands[i]))
  42727. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  42728. }
  42729. }
  42730. }
  42731. else
  42732. {
  42733. clearSubItems();
  42734. }
  42735. }
  42736. juce_UseDebuggingNewOperator
  42737. private:
  42738. KeyMappingEditorComponent* owner;
  42739. String categoryName;
  42740. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  42741. const KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  42742. };
  42743. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  42744. const bool showResetToDefaultButton)
  42745. : mappings (mappingManager),
  42746. textColour (Colours::black)
  42747. {
  42748. jassert (mappingManager != 0); // can't be null!
  42749. mappingManager->addChangeListener (this);
  42750. setLinesDrawnForSubItems (false);
  42751. resetButton = 0;
  42752. if (showResetToDefaultButton)
  42753. {
  42754. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  42755. resetButton->addButtonListener (this);
  42756. }
  42757. addAndMakeVisible (tree = new TreeView());
  42758. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  42759. tree->setRootItemVisible (false);
  42760. tree->setDefaultOpenness (true);
  42761. tree->setRootItem (this);
  42762. }
  42763. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  42764. {
  42765. mappings->removeChangeListener (this);
  42766. deleteAllChildren();
  42767. }
  42768. bool KeyMappingEditorComponent::mightContainSubItems()
  42769. {
  42770. return true;
  42771. }
  42772. const String KeyMappingEditorComponent::getUniqueName() const
  42773. {
  42774. return T("keys");
  42775. }
  42776. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  42777. const Colour& textColour_)
  42778. {
  42779. backgroundColour = mainBackground;
  42780. textColour = textColour_;
  42781. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  42782. }
  42783. void KeyMappingEditorComponent::parentHierarchyChanged()
  42784. {
  42785. changeListenerCallback (0);
  42786. }
  42787. void KeyMappingEditorComponent::resized()
  42788. {
  42789. int h = getHeight();
  42790. if (resetButton != 0)
  42791. {
  42792. const int buttonHeight = 20;
  42793. h -= buttonHeight + 8;
  42794. int x = getWidth() - 8;
  42795. const int y = h + 6;
  42796. resetButton->changeWidthToFitText (buttonHeight);
  42797. resetButton->setTopRightPosition (x, y);
  42798. }
  42799. tree->setBounds (0, 0, getWidth(), h);
  42800. }
  42801. void KeyMappingEditorComponent::buttonClicked (Button* button)
  42802. {
  42803. if (button == resetButton)
  42804. {
  42805. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  42806. TRANS("Reset to defaults"),
  42807. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  42808. TRANS("Reset")))
  42809. {
  42810. mappings->resetToDefaultMappings();
  42811. }
  42812. }
  42813. }
  42814. void KeyMappingEditorComponent::changeListenerCallback (void*)
  42815. {
  42816. XmlElement* openness = tree->getOpennessState (true);
  42817. clearSubItems();
  42818. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  42819. for (int i = 0; i < categories.size(); ++i)
  42820. {
  42821. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  42822. int count = 0;
  42823. for (int j = 0; j < commands.size(); ++j)
  42824. if (shouldCommandBeIncluded (commands[j]))
  42825. ++count;
  42826. if (count > 0)
  42827. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  42828. }
  42829. if (openness != 0)
  42830. {
  42831. tree->restoreOpennessState (*openness);
  42832. delete openness;
  42833. }
  42834. }
  42835. class KeyEntryWindow : public AlertWindow
  42836. {
  42837. public:
  42838. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  42839. : AlertWindow (TRANS("New key-mapping"),
  42840. TRANS("Please press a key combination now..."),
  42841. AlertWindow::NoIcon),
  42842. owner (owner_)
  42843. {
  42844. addButton (TRANS("ok"), 1);
  42845. addButton (TRANS("cancel"), 0);
  42846. // (avoid return + escape keys getting processed by the buttons..)
  42847. for (int i = getNumChildComponents(); --i >= 0;)
  42848. getChildComponent (i)->setWantsKeyboardFocus (false);
  42849. setWantsKeyboardFocus (true);
  42850. grabKeyboardFocus();
  42851. }
  42852. ~KeyEntryWindow()
  42853. {
  42854. }
  42855. bool keyPressed (const KeyPress& key)
  42856. {
  42857. lastPress = key;
  42858. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  42859. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  42860. if (previousCommand != 0)
  42861. {
  42862. message << "\n\n"
  42863. << TRANS("(Currently assigned to \"")
  42864. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  42865. << "\")";
  42866. }
  42867. setMessage (message);
  42868. return true;
  42869. }
  42870. bool keyStateChanged()
  42871. {
  42872. return true;
  42873. }
  42874. KeyPress lastPress;
  42875. juce_UseDebuggingNewOperator
  42876. private:
  42877. KeyMappingEditorComponent* owner;
  42878. KeyEntryWindow (const KeyEntryWindow&);
  42879. const KeyEntryWindow& operator= (const KeyEntryWindow&);
  42880. };
  42881. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  42882. {
  42883. KeyEntryWindow entryWindow (this);
  42884. if (entryWindow.runModalLoop() != 0)
  42885. {
  42886. entryWindow.setVisible (false);
  42887. if (entryWindow.lastPress.isValid())
  42888. {
  42889. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  42890. if (previousCommand != 0)
  42891. {
  42892. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  42893. TRANS("Change key-mapping"),
  42894. TRANS("This key is already assigned to the command \"")
  42895. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  42896. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  42897. TRANS("re-assign"),
  42898. TRANS("cancel")))
  42899. {
  42900. return;
  42901. }
  42902. }
  42903. mappings->removeKeyPress (entryWindow.lastPress);
  42904. if (index >= 0)
  42905. mappings->removeKeyPress (commandID, index);
  42906. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  42907. }
  42908. }
  42909. }
  42910. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  42911. {
  42912. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  42913. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  42914. }
  42915. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  42916. {
  42917. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  42918. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  42919. }
  42920. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  42921. {
  42922. return key.getTextDescription();
  42923. }
  42924. END_JUCE_NAMESPACE
  42925. /********* End of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  42926. /********* Start of inlined file: juce_KeyPress.cpp *********/
  42927. BEGIN_JUCE_NAMESPACE
  42928. KeyPress::KeyPress() throw()
  42929. : keyCode (0),
  42930. mods (0),
  42931. textCharacter (0)
  42932. {
  42933. }
  42934. KeyPress::KeyPress (const int keyCode_,
  42935. const ModifierKeys& mods_,
  42936. const juce_wchar textCharacter_) throw()
  42937. : keyCode (keyCode_),
  42938. mods (mods_),
  42939. textCharacter (textCharacter_)
  42940. {
  42941. }
  42942. KeyPress::KeyPress (const int keyCode_) throw()
  42943. : keyCode (keyCode_),
  42944. textCharacter (0)
  42945. {
  42946. }
  42947. KeyPress::KeyPress (const KeyPress& other) throw()
  42948. : keyCode (other.keyCode),
  42949. mods (other.mods),
  42950. textCharacter (other.textCharacter)
  42951. {
  42952. }
  42953. const KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  42954. {
  42955. keyCode = other.keyCode;
  42956. mods = other.mods;
  42957. textCharacter = other.textCharacter;
  42958. return *this;
  42959. }
  42960. bool KeyPress::operator== (const KeyPress& other) const throw()
  42961. {
  42962. return mods.getRawFlags() == other.mods.getRawFlags()
  42963. && (textCharacter == other.textCharacter
  42964. || textCharacter == 0
  42965. || other.textCharacter == 0)
  42966. && (keyCode == other.keyCode
  42967. || (keyCode < 256
  42968. && other.keyCode < 256
  42969. && CharacterFunctions::toLowerCase ((tchar) keyCode)
  42970. == CharacterFunctions::toLowerCase ((tchar) other.keyCode)));
  42971. }
  42972. bool KeyPress::operator!= (const KeyPress& other) const throw()
  42973. {
  42974. return ! operator== (other);
  42975. }
  42976. bool KeyPress::isCurrentlyDown() const throw()
  42977. {
  42978. return isKeyCurrentlyDown (keyCode)
  42979. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  42980. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  42981. }
  42982. struct KeyNameAndCode
  42983. {
  42984. const char* name;
  42985. int code;
  42986. };
  42987. static const KeyNameAndCode keyNameTranslations[] =
  42988. {
  42989. { "spacebar", KeyPress::spaceKey },
  42990. { "return", KeyPress::returnKey },
  42991. { "escape", KeyPress::escapeKey },
  42992. { "backspace", KeyPress::backspaceKey },
  42993. { "cursor left", KeyPress::leftKey },
  42994. { "cursor right", KeyPress::rightKey },
  42995. { "cursor up", KeyPress::upKey },
  42996. { "cursor down", KeyPress::downKey },
  42997. { "page up", KeyPress::pageUpKey },
  42998. { "page down", KeyPress::pageDownKey },
  42999. { "home", KeyPress::homeKey },
  43000. { "end", KeyPress::endKey },
  43001. { "delete", KeyPress::deleteKey },
  43002. { "insert", KeyPress::insertKey },
  43003. { "tab", KeyPress::tabKey },
  43004. { "play", KeyPress::playKey },
  43005. { "stop", KeyPress::stopKey },
  43006. { "fast forward", KeyPress::fastForwardKey },
  43007. { "rewind", KeyPress::rewindKey }
  43008. };
  43009. static const tchar* const numberPadPrefix = T("numpad ");
  43010. const KeyPress KeyPress::createFromDescription (const String& desc) throw()
  43011. {
  43012. int modifiers = 0;
  43013. if (desc.containsWholeWordIgnoreCase (T("ctrl"))
  43014. || desc.containsWholeWordIgnoreCase (T("control"))
  43015. || desc.containsWholeWordIgnoreCase (T("ctl")))
  43016. modifiers |= ModifierKeys::ctrlModifier;
  43017. if (desc.containsWholeWordIgnoreCase (T("shift"))
  43018. || desc.containsWholeWordIgnoreCase (T("shft")))
  43019. modifiers |= ModifierKeys::shiftModifier;
  43020. if (desc.containsWholeWordIgnoreCase (T("alt"))
  43021. || desc.containsWholeWordIgnoreCase (T("option")))
  43022. modifiers |= ModifierKeys::altModifier;
  43023. if (desc.containsWholeWordIgnoreCase (T("command"))
  43024. || desc.containsWholeWordIgnoreCase (T("cmd")))
  43025. modifiers |= ModifierKeys::commandModifier;
  43026. int key = 0;
  43027. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  43028. {
  43029. if (desc.containsWholeWordIgnoreCase (String (keyNameTranslations[i].name)))
  43030. {
  43031. key = keyNameTranslations[i].code;
  43032. break;
  43033. }
  43034. }
  43035. if (key == 0)
  43036. {
  43037. // see if it's a numpad key..
  43038. if (desc.containsIgnoreCase (numberPadPrefix))
  43039. {
  43040. const tchar lastChar = desc.trimEnd().getLastCharacter();
  43041. if (lastChar >= T('0') && lastChar <= T('9'))
  43042. key = numberPad0 + lastChar - T('0');
  43043. else if (lastChar == T('+'))
  43044. key = numberPadAdd;
  43045. else if (lastChar == T('-'))
  43046. key = numberPadSubtract;
  43047. else if (lastChar == T('*'))
  43048. key = numberPadMultiply;
  43049. else if (lastChar == T('/'))
  43050. key = numberPadDivide;
  43051. else if (lastChar == T('.'))
  43052. key = numberPadDecimalPoint;
  43053. else if (lastChar == T('='))
  43054. key = numberPadEquals;
  43055. else if (desc.endsWith (T("separator")))
  43056. key = numberPadSeparator;
  43057. else if (desc.endsWith (T("delete")))
  43058. key = numberPadDelete;
  43059. }
  43060. if (key == 0)
  43061. {
  43062. // see if it's a function key..
  43063. for (int i = 1; i <= 12; ++i)
  43064. if (desc.containsWholeWordIgnoreCase (T("f") + String (i)))
  43065. key = F1Key + i - 1;
  43066. if (key == 0)
  43067. {
  43068. // give up and use the hex code..
  43069. const int hexCode = desc.fromFirstOccurrenceOf (T("#"), false, false)
  43070. .toLowerCase()
  43071. .retainCharacters (T("0123456789abcdef"))
  43072. .getHexValue32();
  43073. if (hexCode > 0)
  43074. key = hexCode;
  43075. else
  43076. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  43077. }
  43078. }
  43079. }
  43080. return KeyPress (key, ModifierKeys (modifiers), 0);
  43081. }
  43082. const String KeyPress::getTextDescription() const throw()
  43083. {
  43084. String desc;
  43085. if (keyCode > 0)
  43086. {
  43087. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  43088. // want to store it as being a slash, not shift+whatever.
  43089. if (textCharacter == T('/'))
  43090. return "/";
  43091. if (mods.isCtrlDown())
  43092. desc << "ctrl + ";
  43093. if (mods.isShiftDown())
  43094. desc << "shift + ";
  43095. #if JUCE_MAC
  43096. // only do this on the mac, because on Windows ctrl and command are the same,
  43097. // and this would get confusing
  43098. if (mods.isCommandDown())
  43099. desc << "command + ";
  43100. if (mods.isAltDown())
  43101. desc << "option + ";
  43102. #else
  43103. if (mods.isAltDown())
  43104. desc << "alt + ";
  43105. #endif
  43106. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  43107. if (keyCode == keyNameTranslations[i].code)
  43108. return desc + keyNameTranslations[i].name;
  43109. if (keyCode >= F1Key && keyCode <= F16Key)
  43110. desc << 'F' << (1 + keyCode - F1Key);
  43111. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  43112. desc << numberPadPrefix << (keyCode - numberPad0);
  43113. else if (keyCode >= 33 && keyCode < 176)
  43114. desc += CharacterFunctions::toUpperCase ((tchar) keyCode);
  43115. else if (keyCode == numberPadAdd)
  43116. desc << numberPadPrefix << '+';
  43117. else if (keyCode == numberPadSubtract)
  43118. desc << numberPadPrefix << '-';
  43119. else if (keyCode == numberPadMultiply)
  43120. desc << numberPadPrefix << '*';
  43121. else if (keyCode == numberPadDivide)
  43122. desc << numberPadPrefix << '/';
  43123. else if (keyCode == numberPadSeparator)
  43124. desc << numberPadPrefix << "separator";
  43125. else if (keyCode == numberPadDecimalPoint)
  43126. desc << numberPadPrefix << '.';
  43127. else if (keyCode == numberPadDelete)
  43128. desc << numberPadPrefix << "delete";
  43129. else
  43130. desc << '#' << String::toHexString (keyCode);
  43131. }
  43132. return desc;
  43133. }
  43134. END_JUCE_NAMESPACE
  43135. /********* End of inlined file: juce_KeyPress.cpp *********/
  43136. /********* Start of inlined file: juce_KeyPressMappingSet.cpp *********/
  43137. BEGIN_JUCE_NAMESPACE
  43138. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_) throw()
  43139. : commandManager (commandManager_)
  43140. {
  43141. // A manager is needed to get the descriptions of commands, and will be called when
  43142. // a command is invoked. So you can't leave this null..
  43143. jassert (commandManager_ != 0);
  43144. Desktop::getInstance().addFocusChangeListener (this);
  43145. }
  43146. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other) throw()
  43147. : commandManager (other.commandManager)
  43148. {
  43149. Desktop::getInstance().addFocusChangeListener (this);
  43150. }
  43151. KeyPressMappingSet::~KeyPressMappingSet()
  43152. {
  43153. Desktop::getInstance().removeFocusChangeListener (this);
  43154. }
  43155. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const throw()
  43156. {
  43157. for (int i = 0; i < mappings.size(); ++i)
  43158. if (mappings.getUnchecked(i)->commandID == commandID)
  43159. return mappings.getUnchecked (i)->keypresses;
  43160. return Array <KeyPress> ();
  43161. }
  43162. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  43163. const KeyPress& newKeyPress,
  43164. int insertIndex) throw()
  43165. {
  43166. if (findCommandForKeyPress (newKeyPress) != commandID)
  43167. {
  43168. removeKeyPress (newKeyPress);
  43169. if (newKeyPress.isValid())
  43170. {
  43171. for (int i = mappings.size(); --i >= 0;)
  43172. {
  43173. if (mappings.getUnchecked(i)->commandID == commandID)
  43174. {
  43175. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  43176. sendChangeMessage (this);
  43177. return;
  43178. }
  43179. }
  43180. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  43181. if (ci != 0)
  43182. {
  43183. CommandMapping* const cm = new CommandMapping();
  43184. cm->commandID = commandID;
  43185. cm->keypresses.add (newKeyPress);
  43186. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  43187. mappings.add (cm);
  43188. sendChangeMessage (this);
  43189. }
  43190. }
  43191. }
  43192. }
  43193. void KeyPressMappingSet::resetToDefaultMappings() throw()
  43194. {
  43195. mappings.clear();
  43196. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  43197. {
  43198. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  43199. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  43200. {
  43201. addKeyPress (ci->commandID,
  43202. ci->defaultKeypresses.getReference (j));
  43203. }
  43204. }
  43205. sendChangeMessage (this);
  43206. }
  43207. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID) throw()
  43208. {
  43209. clearAllKeyPresses (commandID);
  43210. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  43211. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  43212. {
  43213. addKeyPress (ci->commandID,
  43214. ci->defaultKeypresses.getReference (j));
  43215. }
  43216. }
  43217. void KeyPressMappingSet::clearAllKeyPresses() throw()
  43218. {
  43219. if (mappings.size() > 0)
  43220. {
  43221. sendChangeMessage (this);
  43222. mappings.clear();
  43223. }
  43224. }
  43225. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID) throw()
  43226. {
  43227. for (int i = mappings.size(); --i >= 0;)
  43228. {
  43229. if (mappings.getUnchecked(i)->commandID == commandID)
  43230. {
  43231. mappings.remove (i);
  43232. sendChangeMessage (this);
  43233. }
  43234. }
  43235. }
  43236. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress) throw()
  43237. {
  43238. if (keypress.isValid())
  43239. {
  43240. for (int i = mappings.size(); --i >= 0;)
  43241. {
  43242. CommandMapping* const cm = mappings.getUnchecked(i);
  43243. for (int j = cm->keypresses.size(); --j >= 0;)
  43244. {
  43245. if (keypress == cm->keypresses [j])
  43246. {
  43247. cm->keypresses.remove (j);
  43248. sendChangeMessage (this);
  43249. }
  43250. }
  43251. }
  43252. }
  43253. }
  43254. void KeyPressMappingSet::removeKeyPress (const CommandID commandID,
  43255. const int keyPressIndex) throw()
  43256. {
  43257. for (int i = mappings.size(); --i >= 0;)
  43258. {
  43259. if (mappings.getUnchecked(i)->commandID == commandID)
  43260. {
  43261. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  43262. sendChangeMessage (this);
  43263. break;
  43264. }
  43265. }
  43266. }
  43267. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  43268. {
  43269. for (int i = 0; i < mappings.size(); ++i)
  43270. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  43271. return mappings.getUnchecked(i)->commandID;
  43272. return 0;
  43273. }
  43274. bool KeyPressMappingSet::containsMapping (const CommandID commandID,
  43275. const KeyPress& keyPress) const throw()
  43276. {
  43277. for (int i = mappings.size(); --i >= 0;)
  43278. if (mappings.getUnchecked(i)->commandID == commandID)
  43279. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  43280. return false;
  43281. }
  43282. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  43283. const KeyPress& key,
  43284. const bool isKeyDown,
  43285. const int millisecsSinceKeyPressed,
  43286. Component* const originatingComponent) const
  43287. {
  43288. ApplicationCommandTarget::InvocationInfo info (commandID);
  43289. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  43290. info.isKeyDown = isKeyDown;
  43291. info.keyPress = key;
  43292. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  43293. info.originatingComponent = originatingComponent;
  43294. commandManager->invoke (info, false);
  43295. }
  43296. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  43297. {
  43298. if (xmlVersion.hasTagName (T("KEYMAPPINGS")))
  43299. {
  43300. if (xmlVersion.getBoolAttribute (T("basedOnDefaults"), true))
  43301. {
  43302. // if the XML was created as a set of differences from the default mappings,
  43303. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  43304. resetToDefaultMappings();
  43305. }
  43306. else
  43307. {
  43308. // if the XML was created calling createXml (false), then we need to clear all
  43309. // the keys and treat the xml as describing the entire set of mappings.
  43310. clearAllKeyPresses();
  43311. }
  43312. forEachXmlChildElement (xmlVersion, map)
  43313. {
  43314. const CommandID commandId = map->getStringAttribute (T("commandId")).getHexValue32();
  43315. if (commandId != 0)
  43316. {
  43317. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute (T("key"))));
  43318. if (map->hasTagName (T("MAPPING")))
  43319. {
  43320. addKeyPress (commandId, key);
  43321. }
  43322. else if (map->hasTagName (T("UNMAPPING")))
  43323. {
  43324. if (containsMapping (commandId, key))
  43325. removeKeyPress (key);
  43326. }
  43327. }
  43328. }
  43329. return true;
  43330. }
  43331. return false;
  43332. }
  43333. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  43334. {
  43335. KeyPressMappingSet* defaultSet = 0;
  43336. if (saveDifferencesFromDefaultSet)
  43337. {
  43338. defaultSet = new KeyPressMappingSet (commandManager);
  43339. defaultSet->resetToDefaultMappings();
  43340. }
  43341. XmlElement* const doc = new XmlElement (T("KEYMAPPINGS"));
  43342. doc->setAttribute (T("basedOnDefaults"), saveDifferencesFromDefaultSet);
  43343. int i;
  43344. for (i = 0; i < mappings.size(); ++i)
  43345. {
  43346. const CommandMapping* const cm = mappings.getUnchecked(i);
  43347. for (int j = 0; j < cm->keypresses.size(); ++j)
  43348. {
  43349. if (defaultSet == 0
  43350. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  43351. {
  43352. XmlElement* const map = new XmlElement (T("MAPPING"));
  43353. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  43354. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  43355. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  43356. doc->addChildElement (map);
  43357. }
  43358. }
  43359. }
  43360. if (defaultSet != 0)
  43361. {
  43362. for (i = 0; i < defaultSet->mappings.size(); ++i)
  43363. {
  43364. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  43365. for (int j = 0; j < cm->keypresses.size(); ++j)
  43366. {
  43367. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  43368. {
  43369. XmlElement* const map = new XmlElement (T("UNMAPPING"));
  43370. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  43371. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  43372. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  43373. doc->addChildElement (map);
  43374. }
  43375. }
  43376. }
  43377. delete defaultSet;
  43378. }
  43379. return doc;
  43380. }
  43381. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  43382. Component* originatingComponent)
  43383. {
  43384. bool used = false;
  43385. const CommandID commandID = findCommandForKeyPress (key);
  43386. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  43387. if (ci != 0
  43388. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  43389. {
  43390. ApplicationCommandInfo info (0);
  43391. if (commandManager->getTargetForCommand (commandID, info) != 0
  43392. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  43393. {
  43394. invokeCommand (commandID, key, true, 0, originatingComponent);
  43395. used = true;
  43396. }
  43397. else
  43398. {
  43399. if (originatingComponent != 0)
  43400. originatingComponent->getLookAndFeel().playAlertSound();
  43401. }
  43402. }
  43403. return used;
  43404. }
  43405. bool KeyPressMappingSet::keyStateChanged (Component* originatingComponent)
  43406. {
  43407. bool used = false;
  43408. const uint32 now = Time::getMillisecondCounter();
  43409. for (int i = mappings.size(); --i >= 0;)
  43410. {
  43411. CommandMapping* const cm = mappings.getUnchecked(i);
  43412. if (cm->wantsKeyUpDownCallbacks)
  43413. {
  43414. for (int j = cm->keypresses.size(); --j >= 0;)
  43415. {
  43416. const KeyPress key (cm->keypresses.getReference (j));
  43417. const bool isDown = key.isCurrentlyDown();
  43418. int keyPressEntryIndex = 0;
  43419. bool wasDown = false;
  43420. for (int k = keysDown.size(); --k >= 0;)
  43421. {
  43422. if (key == keysDown.getUnchecked(k)->key)
  43423. {
  43424. keyPressEntryIndex = k;
  43425. wasDown = true;
  43426. break;
  43427. }
  43428. }
  43429. if (isDown != wasDown)
  43430. {
  43431. int millisecs = 0;
  43432. if (isDown)
  43433. {
  43434. KeyPressTime* const k = new KeyPressTime();
  43435. k->key = key;
  43436. k->timeWhenPressed = now;
  43437. keysDown.add (k);
  43438. }
  43439. else
  43440. {
  43441. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  43442. if (now > pressTime)
  43443. millisecs = now - pressTime;
  43444. keysDown.remove (keyPressEntryIndex);
  43445. }
  43446. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  43447. used = true;
  43448. }
  43449. }
  43450. }
  43451. }
  43452. return used;
  43453. }
  43454. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  43455. {
  43456. if (focusedComponent != 0)
  43457. focusedComponent->keyStateChanged();
  43458. }
  43459. END_JUCE_NAMESPACE
  43460. /********* End of inlined file: juce_KeyPressMappingSet.cpp *********/
  43461. /********* Start of inlined file: juce_ModifierKeys.cpp *********/
  43462. BEGIN_JUCE_NAMESPACE
  43463. ModifierKeys::ModifierKeys (const int flags_) throw()
  43464. : flags (flags_)
  43465. {
  43466. }
  43467. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  43468. : flags (other.flags)
  43469. {
  43470. }
  43471. const ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  43472. {
  43473. flags = other.flags;
  43474. return *this;
  43475. }
  43476. int ModifierKeys::currentModifierFlags = 0;
  43477. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  43478. {
  43479. return ModifierKeys (currentModifierFlags);
  43480. }
  43481. END_JUCE_NAMESPACE
  43482. /********* End of inlined file: juce_ModifierKeys.cpp *********/
  43483. /********* Start of inlined file: juce_ComponentAnimator.cpp *********/
  43484. BEGIN_JUCE_NAMESPACE
  43485. struct AnimationTask
  43486. {
  43487. AnimationTask (Component* const comp)
  43488. : component (comp),
  43489. watcher (comp)
  43490. {
  43491. }
  43492. Component* component;
  43493. ComponentDeletionWatcher watcher;
  43494. Rectangle destination;
  43495. int msElapsed, msTotal;
  43496. double startSpeed, midSpeed, endSpeed, lastProgress;
  43497. double left, top, right, bottom;
  43498. bool useTimeslice (const int elapsed)
  43499. {
  43500. if (watcher.hasBeenDeleted())
  43501. return false;
  43502. msElapsed += elapsed;
  43503. double newProgress = msElapsed / (double) msTotal;
  43504. if (newProgress >= 0 && newProgress < 1.0)
  43505. {
  43506. newProgress = timeToDistance (newProgress);
  43507. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  43508. jassert (newProgress >= lastProgress);
  43509. lastProgress = newProgress;
  43510. left += (destination.getX() - left) * delta;
  43511. top += (destination.getY() - top) * delta;
  43512. right += (destination.getRight() - right) * delta;
  43513. bottom += (destination.getBottom() - bottom) * delta;
  43514. if (delta < 1.0)
  43515. {
  43516. const Rectangle newBounds (roundDoubleToInt (left),
  43517. roundDoubleToInt (top),
  43518. roundDoubleToInt (right - left),
  43519. roundDoubleToInt (bottom - top));
  43520. if (newBounds != destination)
  43521. {
  43522. component->setBounds (newBounds);
  43523. return true;
  43524. }
  43525. }
  43526. }
  43527. component->setBounds (destination);
  43528. return false;
  43529. }
  43530. void moveToFinalDestination()
  43531. {
  43532. if (! watcher.hasBeenDeleted())
  43533. component->setBounds (destination);
  43534. }
  43535. private:
  43536. inline double timeToDistance (const double time) const
  43537. {
  43538. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  43539. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  43540. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  43541. }
  43542. };
  43543. ComponentAnimator::ComponentAnimator()
  43544. : lastTime (0)
  43545. {
  43546. }
  43547. ComponentAnimator::~ComponentAnimator()
  43548. {
  43549. cancelAllAnimations (false);
  43550. jassert (tasks.size() == 0);
  43551. }
  43552. void* ComponentAnimator::findTaskFor (Component* const component) const
  43553. {
  43554. for (int i = tasks.size(); --i >= 0;)
  43555. if (component == ((AnimationTask*) tasks.getUnchecked(i))->component)
  43556. return tasks.getUnchecked(i);
  43557. return 0;
  43558. }
  43559. void ComponentAnimator::animateComponent (Component* const component,
  43560. const Rectangle& finalPosition,
  43561. const int millisecondsToSpendMoving,
  43562. const double startSpeed,
  43563. const double endSpeed)
  43564. {
  43565. if (component != 0)
  43566. {
  43567. AnimationTask* at = (AnimationTask*) findTaskFor (component);
  43568. if (at == 0)
  43569. {
  43570. at = new AnimationTask (component);
  43571. tasks.add (at);
  43572. }
  43573. at->msElapsed = 0;
  43574. at->lastProgress = 0;
  43575. at->msTotal = jmax (1, millisecondsToSpendMoving);
  43576. at->destination = finalPosition;
  43577. // the speeds must be 0 or greater!
  43578. jassert (startSpeed >= 0 && endSpeed >= 0)
  43579. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  43580. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  43581. at->midSpeed = invTotalDistance;
  43582. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  43583. at->left = component->getX();
  43584. at->top = component->getY();
  43585. at->right = component->getRight();
  43586. at->bottom = component->getBottom();
  43587. if (! isTimerRunning())
  43588. {
  43589. lastTime = Time::getMillisecondCounter();
  43590. startTimer (1000 / 50);
  43591. }
  43592. }
  43593. }
  43594. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  43595. {
  43596. for (int i = tasks.size(); --i >= 0;)
  43597. {
  43598. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  43599. if (moveComponentsToTheirFinalPositions)
  43600. at->moveToFinalDestination();
  43601. delete at;
  43602. tasks.remove (i);
  43603. }
  43604. }
  43605. void ComponentAnimator::cancelAnimation (Component* const component,
  43606. const bool moveComponentToItsFinalPosition)
  43607. {
  43608. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  43609. if (at != 0)
  43610. {
  43611. if (moveComponentToItsFinalPosition)
  43612. at->moveToFinalDestination();
  43613. tasks.removeValue (at);
  43614. delete at;
  43615. }
  43616. }
  43617. const Rectangle ComponentAnimator::getComponentDestination (Component* const component)
  43618. {
  43619. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  43620. if (at != 0)
  43621. return at->destination;
  43622. else if (component != 0)
  43623. return component->getBounds();
  43624. return Rectangle();
  43625. }
  43626. void ComponentAnimator::timerCallback()
  43627. {
  43628. const uint32 timeNow = Time::getMillisecondCounter();
  43629. if (lastTime == 0 || lastTime == timeNow)
  43630. lastTime = timeNow;
  43631. const int elapsed = timeNow - lastTime;
  43632. for (int i = tasks.size(); --i >= 0;)
  43633. {
  43634. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  43635. if (! at->useTimeslice (elapsed))
  43636. {
  43637. tasks.remove (i);
  43638. delete at;
  43639. }
  43640. }
  43641. lastTime = timeNow;
  43642. if (tasks.size() == 0)
  43643. stopTimer();
  43644. }
  43645. END_JUCE_NAMESPACE
  43646. /********* End of inlined file: juce_ComponentAnimator.cpp *********/
  43647. /********* Start of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  43648. BEGIN_JUCE_NAMESPACE
  43649. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  43650. : minW (0),
  43651. maxW (0x3fffffff),
  43652. minH (0),
  43653. maxH (0x3fffffff),
  43654. minOffTop (0),
  43655. minOffLeft (0),
  43656. minOffBottom (0),
  43657. minOffRight (0),
  43658. aspectRatio (0.0)
  43659. {
  43660. }
  43661. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  43662. {
  43663. }
  43664. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  43665. {
  43666. minW = minimumWidth;
  43667. }
  43668. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  43669. {
  43670. maxW = maximumWidth;
  43671. }
  43672. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  43673. {
  43674. minH = minimumHeight;
  43675. }
  43676. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  43677. {
  43678. maxH = maximumHeight;
  43679. }
  43680. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  43681. {
  43682. jassert (maxW >= minimumWidth);
  43683. jassert (maxH >= minimumHeight);
  43684. jassert (minimumWidth > 0 && minimumHeight > 0);
  43685. minW = minimumWidth;
  43686. minH = minimumHeight;
  43687. if (minW > maxW)
  43688. maxW = minW;
  43689. if (minH > maxH)
  43690. maxH = minH;
  43691. }
  43692. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  43693. {
  43694. jassert (maximumWidth >= minW);
  43695. jassert (maximumHeight >= minH);
  43696. jassert (maximumWidth > 0 && maximumHeight > 0);
  43697. maxW = jmax (minW, maximumWidth);
  43698. maxH = jmax (minH, maximumHeight);
  43699. }
  43700. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  43701. const int minimumHeight,
  43702. const int maximumWidth,
  43703. const int maximumHeight) throw()
  43704. {
  43705. jassert (maximumWidth >= minimumWidth);
  43706. jassert (maximumHeight >= minimumHeight);
  43707. jassert (maximumWidth > 0 && maximumHeight > 0);
  43708. jassert (minimumWidth > 0 && minimumHeight > 0);
  43709. minW = jmax (0, minimumWidth);
  43710. minH = jmax (0, minimumHeight);
  43711. maxW = jmax (minW, maximumWidth);
  43712. maxH = jmax (minH, maximumHeight);
  43713. }
  43714. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  43715. const int minimumWhenOffTheLeft,
  43716. const int minimumWhenOffTheBottom,
  43717. const int minimumWhenOffTheRight) throw()
  43718. {
  43719. minOffTop = minimumWhenOffTheTop;
  43720. minOffLeft = minimumWhenOffTheLeft;
  43721. minOffBottom = minimumWhenOffTheBottom;
  43722. minOffRight = minimumWhenOffTheRight;
  43723. }
  43724. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  43725. {
  43726. aspectRatio = jmax (0.0, widthOverHeight);
  43727. }
  43728. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  43729. {
  43730. return aspectRatio;
  43731. }
  43732. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  43733. int x, int y, int w, int h,
  43734. const bool isStretchingTop,
  43735. const bool isStretchingLeft,
  43736. const bool isStretchingBottom,
  43737. const bool isStretchingRight)
  43738. {
  43739. jassert (component != 0);
  43740. Rectangle limits;
  43741. Component* const p = component->getParentComponent();
  43742. if (p == 0)
  43743. limits = Desktop::getInstance().getAllMonitorDisplayAreas().getBounds();
  43744. else
  43745. limits.setSize (p->getWidth(), p->getHeight());
  43746. if (component->isOnDesktop())
  43747. {
  43748. ComponentPeer* const peer = component->getPeer();
  43749. const BorderSize border (peer->getFrameSize());
  43750. x -= border.getLeft();
  43751. y -= border.getTop();
  43752. w += border.getLeftAndRight();
  43753. h += border.getTopAndBottom();
  43754. checkBounds (x, y, w, h,
  43755. border.addedTo (component->getBounds()), limits,
  43756. isStretchingTop, isStretchingLeft,
  43757. isStretchingBottom, isStretchingRight);
  43758. x += border.getLeft();
  43759. y += border.getTop();
  43760. w -= border.getLeftAndRight();
  43761. h -= border.getTopAndBottom();
  43762. }
  43763. else
  43764. {
  43765. checkBounds (x, y, w, h,
  43766. component->getBounds(), limits,
  43767. isStretchingTop, isStretchingLeft,
  43768. isStretchingBottom, isStretchingRight);
  43769. }
  43770. applyBoundsToComponent (component, x, y, w, h);
  43771. }
  43772. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  43773. int x, int y, int w, int h)
  43774. {
  43775. component->setBounds (x, y, w, h);
  43776. }
  43777. void ComponentBoundsConstrainer::resizeStart()
  43778. {
  43779. }
  43780. void ComponentBoundsConstrainer::resizeEnd()
  43781. {
  43782. }
  43783. void ComponentBoundsConstrainer::checkBounds (int& x, int& y, int& w, int& h,
  43784. const Rectangle& old,
  43785. const Rectangle& limits,
  43786. const bool isStretchingTop,
  43787. const bool isStretchingLeft,
  43788. const bool isStretchingBottom,
  43789. const bool isStretchingRight)
  43790. {
  43791. // constrain the size if it's being stretched..
  43792. if (isStretchingLeft)
  43793. {
  43794. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  43795. w = old.getRight() - x;
  43796. }
  43797. if (isStretchingRight)
  43798. {
  43799. w = jlimit (minW, maxW, w);
  43800. }
  43801. if (isStretchingTop)
  43802. {
  43803. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  43804. h = old.getBottom() - y;
  43805. }
  43806. if (isStretchingBottom)
  43807. {
  43808. h = jlimit (minH, maxH, h);
  43809. }
  43810. // constrain the aspect ratio if one has been specified..
  43811. if (aspectRatio > 0.0 && w > 0 && h > 0)
  43812. {
  43813. bool adjustWidth;
  43814. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  43815. {
  43816. adjustWidth = true;
  43817. }
  43818. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  43819. {
  43820. adjustWidth = false;
  43821. }
  43822. else
  43823. {
  43824. const double oldRatio = (old.getHeight() > 0) ? fabs (old.getWidth() / (double) old.getHeight()) : 0.0;
  43825. const double newRatio = fabs (w / (double) h);
  43826. adjustWidth = (oldRatio > newRatio);
  43827. }
  43828. if (adjustWidth)
  43829. {
  43830. w = roundDoubleToInt (h * aspectRatio);
  43831. if (w > maxW || w < minW)
  43832. {
  43833. w = jlimit (minW, maxW, w);
  43834. h = roundDoubleToInt (w / aspectRatio);
  43835. }
  43836. }
  43837. else
  43838. {
  43839. h = roundDoubleToInt (w / aspectRatio);
  43840. if (h > maxH || h < minH)
  43841. {
  43842. h = jlimit (minH, maxH, h);
  43843. w = roundDoubleToInt (h * aspectRatio);
  43844. }
  43845. }
  43846. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  43847. {
  43848. x = old.getX() + (old.getWidth() - w) / 2;
  43849. }
  43850. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  43851. {
  43852. y = old.getY() + (old.getHeight() - h) / 2;
  43853. }
  43854. else
  43855. {
  43856. if (isStretchingLeft)
  43857. x = old.getRight() - w;
  43858. if (isStretchingTop)
  43859. y = old.getBottom() - h;
  43860. }
  43861. }
  43862. // ...and constrain the position if limits have been set for that.
  43863. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  43864. {
  43865. if (minOffTop > 0)
  43866. {
  43867. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  43868. if (y < limit)
  43869. {
  43870. if (isStretchingTop)
  43871. h -= (limit - y);
  43872. y = limit;
  43873. }
  43874. }
  43875. if (minOffLeft > 0)
  43876. {
  43877. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  43878. if (x < limit)
  43879. {
  43880. if (isStretchingLeft)
  43881. w -= (limit - x);
  43882. x = limit;
  43883. }
  43884. }
  43885. if (minOffBottom > 0)
  43886. {
  43887. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  43888. if (y > limit)
  43889. {
  43890. if (isStretchingBottom)
  43891. h += (limit - y);
  43892. else
  43893. y = limit;
  43894. }
  43895. }
  43896. if (minOffRight > 0)
  43897. {
  43898. const int limit = limits.getRight() - jmin (minOffRight, w);
  43899. if (x > limit)
  43900. {
  43901. if (isStretchingRight)
  43902. w += (limit - x);
  43903. else
  43904. x = limit;
  43905. }
  43906. }
  43907. }
  43908. jassert (w >= 0 && h >= 0);
  43909. }
  43910. END_JUCE_NAMESPACE
  43911. /********* End of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  43912. /********* Start of inlined file: juce_ComponentMovementWatcher.cpp *********/
  43913. BEGIN_JUCE_NAMESPACE
  43914. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  43915. : component (component_),
  43916. lastPeer (0),
  43917. registeredParentComps (4),
  43918. reentrant (false)
  43919. {
  43920. jassert (component != 0); // can't use this with a null pointer..
  43921. #ifdef JUCE_DEBUG
  43922. deletionWatcher = new ComponentDeletionWatcher (component_);
  43923. #endif
  43924. component->addComponentListener (this);
  43925. registerWithParentComps();
  43926. }
  43927. ComponentMovementWatcher::~ComponentMovementWatcher()
  43928. {
  43929. component->removeComponentListener (this);
  43930. unregister();
  43931. #ifdef JUCE_DEBUG
  43932. delete deletionWatcher;
  43933. #endif
  43934. }
  43935. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  43936. {
  43937. #ifdef JUCE_DEBUG
  43938. // agh! don't delete the target component without deleting this object first!
  43939. jassert (! deletionWatcher->hasBeenDeleted());
  43940. #endif
  43941. if (! reentrant)
  43942. {
  43943. reentrant = true;
  43944. ComponentPeer* const peer = component->getPeer();
  43945. if (peer != lastPeer)
  43946. {
  43947. ComponentDeletionWatcher watcher (component);
  43948. componentPeerChanged();
  43949. if (watcher.hasBeenDeleted())
  43950. return;
  43951. lastPeer = peer;
  43952. }
  43953. unregister();
  43954. registerWithParentComps();
  43955. reentrant = false;
  43956. componentMovedOrResized (*component, true, true);
  43957. }
  43958. }
  43959. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  43960. {
  43961. #ifdef JUCE_DEBUG
  43962. // agh! don't delete the target component without deleting this object first!
  43963. jassert (! deletionWatcher->hasBeenDeleted());
  43964. #endif
  43965. if (wasMoved)
  43966. {
  43967. int x = 0, y = 0;
  43968. component->relativePositionToOtherComponent (component->getTopLevelComponent(), x, y);
  43969. wasMoved = (lastX != x || lastY != y);
  43970. lastX = x;
  43971. lastY = y;
  43972. }
  43973. wasResized = (lastWidth != component->getWidth() || lastHeight != component->getHeight());
  43974. lastWidth = component->getWidth();
  43975. lastHeight = component->getHeight();
  43976. if (wasMoved || wasResized)
  43977. componentMovedOrResized (wasMoved, wasResized);
  43978. }
  43979. void ComponentMovementWatcher::registerWithParentComps() throw()
  43980. {
  43981. Component* p = component->getParentComponent();
  43982. while (p != 0)
  43983. {
  43984. p->addComponentListener (this);
  43985. registeredParentComps.add (p);
  43986. p = p->getParentComponent();
  43987. }
  43988. }
  43989. void ComponentMovementWatcher::unregister() throw()
  43990. {
  43991. for (int i = registeredParentComps.size(); --i >= 0;)
  43992. ((Component*) registeredParentComps.getUnchecked(i))->removeComponentListener (this);
  43993. registeredParentComps.clear();
  43994. }
  43995. END_JUCE_NAMESPACE
  43996. /********* End of inlined file: juce_ComponentMovementWatcher.cpp *********/
  43997. /********* Start of inlined file: juce_GroupComponent.cpp *********/
  43998. BEGIN_JUCE_NAMESPACE
  43999. GroupComponent::GroupComponent (const String& componentName,
  44000. const String& labelText)
  44001. : Component (componentName),
  44002. text (labelText),
  44003. justification (Justification::left)
  44004. {
  44005. setInterceptsMouseClicks (false, true);
  44006. }
  44007. GroupComponent::~GroupComponent()
  44008. {
  44009. }
  44010. void GroupComponent::setText (const String& newText) throw()
  44011. {
  44012. if (text != newText)
  44013. {
  44014. text = newText;
  44015. repaint();
  44016. }
  44017. }
  44018. const String GroupComponent::getText() const throw()
  44019. {
  44020. return text;
  44021. }
  44022. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  44023. {
  44024. if (justification.getFlags() != newJustification.getFlags())
  44025. {
  44026. justification = newJustification;
  44027. repaint();
  44028. }
  44029. }
  44030. void GroupComponent::paint (Graphics& g)
  44031. {
  44032. getLookAndFeel()
  44033. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  44034. text, justification,
  44035. *this);
  44036. }
  44037. void GroupComponent::enablementChanged()
  44038. {
  44039. repaint();
  44040. }
  44041. void GroupComponent::colourChanged()
  44042. {
  44043. repaint();
  44044. }
  44045. END_JUCE_NAMESPACE
  44046. /********* End of inlined file: juce_GroupComponent.cpp *********/
  44047. /********* Start of inlined file: juce_MultiDocumentPanel.cpp *********/
  44048. BEGIN_JUCE_NAMESPACE
  44049. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  44050. : DocumentWindow (String::empty, backgroundColour,
  44051. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  44052. {
  44053. }
  44054. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  44055. {
  44056. }
  44057. void MultiDocumentPanelWindow::maximiseButtonPressed()
  44058. {
  44059. MultiDocumentPanel* const owner = getOwner();
  44060. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  44061. if (owner != 0)
  44062. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  44063. }
  44064. void MultiDocumentPanelWindow::closeButtonPressed()
  44065. {
  44066. MultiDocumentPanel* const owner = getOwner();
  44067. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  44068. if (owner != 0)
  44069. owner->closeDocument (getContentComponent(), true);
  44070. }
  44071. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  44072. {
  44073. DocumentWindow::activeWindowStatusChanged();
  44074. updateOrder();
  44075. }
  44076. void MultiDocumentPanelWindow::broughtToFront()
  44077. {
  44078. DocumentWindow::broughtToFront();
  44079. updateOrder();
  44080. }
  44081. void MultiDocumentPanelWindow::updateOrder()
  44082. {
  44083. MultiDocumentPanel* const owner = getOwner();
  44084. if (owner != 0)
  44085. owner->updateOrder();
  44086. }
  44087. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  44088. {
  44089. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  44090. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  44091. }
  44092. class MDITabbedComponentInternal : public TabbedComponent
  44093. {
  44094. public:
  44095. MDITabbedComponentInternal()
  44096. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  44097. {
  44098. }
  44099. ~MDITabbedComponentInternal()
  44100. {
  44101. }
  44102. void currentTabChanged (const int, const String&)
  44103. {
  44104. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  44105. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  44106. if (owner != 0)
  44107. owner->updateOrder();
  44108. }
  44109. };
  44110. MultiDocumentPanel::MultiDocumentPanel()
  44111. : mode (MaximisedWindowsWithTabs),
  44112. tabComponent (0),
  44113. backgroundColour (Colours::lightblue),
  44114. maximumNumDocuments (0),
  44115. numDocsBeforeTabsUsed (0)
  44116. {
  44117. setOpaque (true);
  44118. }
  44119. MultiDocumentPanel::~MultiDocumentPanel()
  44120. {
  44121. closeAllDocuments (false);
  44122. }
  44123. static bool shouldDeleteComp (Component* const c)
  44124. {
  44125. return c->getComponentPropertyBool (T("mdiDocumentDelete_"), false);
  44126. }
  44127. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  44128. {
  44129. while (components.size() > 0)
  44130. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  44131. return false;
  44132. return true;
  44133. }
  44134. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  44135. {
  44136. return new MultiDocumentPanelWindow (backgroundColour);
  44137. }
  44138. void MultiDocumentPanel::addWindow (Component* component)
  44139. {
  44140. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  44141. dw->setResizable (true, false);
  44142. dw->setContentComponent (component, false, true);
  44143. dw->setName (component->getName());
  44144. dw->setBackgroundColour (component->getComponentPropertyColour (T("mdiDocumentBkg_"), false, backgroundColour));
  44145. int x = 4;
  44146. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  44147. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  44148. x += 16;
  44149. dw->setTopLeftPosition (x, x);
  44150. if (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty).isNotEmpty())
  44151. dw->restoreWindowStateFromString (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty));
  44152. addAndMakeVisible (dw);
  44153. dw->toFront (true);
  44154. }
  44155. bool MultiDocumentPanel::addDocument (Component* const component,
  44156. const Colour& backgroundColour,
  44157. const bool deleteWhenRemoved)
  44158. {
  44159. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  44160. // with a frame-within-a-frame! Just pass in the bare content component.
  44161. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  44162. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  44163. return false;
  44164. components.add (component);
  44165. component->setComponentProperty (T("mdiDocumentDelete_"), deleteWhenRemoved);
  44166. component->setComponentProperty (T("mdiDocumentBkg_"), backgroundColour);
  44167. component->addComponentListener (this);
  44168. if (mode == FloatingWindows)
  44169. {
  44170. if (isFullscreenWhenOneDocument())
  44171. {
  44172. if (components.size() == 1)
  44173. {
  44174. addAndMakeVisible (component);
  44175. }
  44176. else
  44177. {
  44178. if (components.size() == 2)
  44179. addWindow (components.getFirst());
  44180. addWindow (component);
  44181. }
  44182. }
  44183. else
  44184. {
  44185. addWindow (component);
  44186. }
  44187. }
  44188. else
  44189. {
  44190. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  44191. {
  44192. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  44193. Array <Component*> temp (components);
  44194. for (int i = 0; i < temp.size(); ++i)
  44195. tabComponent->addTab (temp[i]->getName(), backgroundColour, temp[i], false);
  44196. resized();
  44197. }
  44198. else
  44199. {
  44200. if (tabComponent != 0)
  44201. tabComponent->addTab (component->getName(), backgroundColour, component, false);
  44202. else
  44203. addAndMakeVisible (component);
  44204. }
  44205. setActiveDocument (component);
  44206. }
  44207. resized();
  44208. activeDocumentChanged();
  44209. return true;
  44210. }
  44211. bool MultiDocumentPanel::closeDocument (Component* component,
  44212. const bool checkItsOkToCloseFirst)
  44213. {
  44214. if (components.contains (component))
  44215. {
  44216. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  44217. return false;
  44218. component->removeComponentListener (this);
  44219. const bool shouldDelete = shouldDeleteComp (component);
  44220. component->removeComponentProperty (T("mdiDocumentDelete_"));
  44221. component->removeComponentProperty (T("mdiDocumentBkg_"));
  44222. if (mode == FloatingWindows)
  44223. {
  44224. for (int i = getNumChildComponents(); --i >= 0;)
  44225. {
  44226. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44227. if (dw != 0 && dw->getContentComponent() == component)
  44228. {
  44229. dw->setContentComponent (0, false);
  44230. delete dw;
  44231. break;
  44232. }
  44233. }
  44234. if (shouldDelete)
  44235. delete component;
  44236. components.removeValue (component);
  44237. if (isFullscreenWhenOneDocument() && components.size() == 1)
  44238. {
  44239. for (int i = getNumChildComponents(); --i >= 0;)
  44240. {
  44241. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44242. if (dw != 0)
  44243. {
  44244. dw->setContentComponent (0, false);
  44245. delete dw;
  44246. }
  44247. }
  44248. addAndMakeVisible (components.getFirst());
  44249. }
  44250. }
  44251. else
  44252. {
  44253. jassert (components.indexOf (component) >= 0);
  44254. if (tabComponent != 0)
  44255. {
  44256. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  44257. if (tabComponent->getTabContentComponent (i) == component)
  44258. tabComponent->removeTab (i);
  44259. }
  44260. else
  44261. {
  44262. removeChildComponent (component);
  44263. }
  44264. if (shouldDelete)
  44265. delete component;
  44266. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  44267. deleteAndZero (tabComponent);
  44268. components.removeValue (component);
  44269. if (components.size() > 0 && tabComponent == 0)
  44270. addAndMakeVisible (components.getFirst());
  44271. }
  44272. resized();
  44273. activeDocumentChanged();
  44274. }
  44275. else
  44276. {
  44277. jassertfalse
  44278. }
  44279. return true;
  44280. }
  44281. int MultiDocumentPanel::getNumDocuments() const throw()
  44282. {
  44283. return components.size();
  44284. }
  44285. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  44286. {
  44287. return components [index];
  44288. }
  44289. Component* MultiDocumentPanel::getActiveDocument() const throw()
  44290. {
  44291. if (mode == FloatingWindows)
  44292. {
  44293. for (int i = getNumChildComponents(); --i >= 0;)
  44294. {
  44295. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44296. if (dw != 0 && dw->isActiveWindow())
  44297. return dw->getContentComponent();
  44298. }
  44299. }
  44300. return components.getLast();
  44301. }
  44302. void MultiDocumentPanel::setActiveDocument (Component* component)
  44303. {
  44304. if (mode == FloatingWindows)
  44305. {
  44306. component = getContainerComp (component);
  44307. if (component != 0)
  44308. component->toFront (true);
  44309. }
  44310. else if (tabComponent != 0)
  44311. {
  44312. jassert (components.indexOf (component) >= 0);
  44313. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  44314. {
  44315. if (tabComponent->getTabContentComponent (i) == component)
  44316. {
  44317. tabComponent->setCurrentTabIndex (i);
  44318. break;
  44319. }
  44320. }
  44321. }
  44322. else
  44323. {
  44324. component->grabKeyboardFocus();
  44325. }
  44326. }
  44327. void MultiDocumentPanel::activeDocumentChanged()
  44328. {
  44329. }
  44330. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  44331. {
  44332. maximumNumDocuments = newNumber;
  44333. }
  44334. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  44335. {
  44336. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  44337. }
  44338. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  44339. {
  44340. return numDocsBeforeTabsUsed != 0;
  44341. }
  44342. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  44343. {
  44344. if (mode != newLayoutMode)
  44345. {
  44346. mode = newLayoutMode;
  44347. if (mode == FloatingWindows)
  44348. {
  44349. deleteAndZero (tabComponent);
  44350. }
  44351. else
  44352. {
  44353. for (int i = getNumChildComponents(); --i >= 0;)
  44354. {
  44355. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44356. if (dw != 0)
  44357. {
  44358. dw->getContentComponent()->setComponentProperty (T("mdiDocumentPos_"), dw->getWindowStateAsString());
  44359. dw->setContentComponent (0, false);
  44360. delete dw;
  44361. }
  44362. }
  44363. }
  44364. resized();
  44365. const Array <Component*> tempComps (components);
  44366. components.clear();
  44367. for (int i = 0; i < tempComps.size(); ++i)
  44368. {
  44369. Component* const c = tempComps.getUnchecked(i);
  44370. addDocument (c,
  44371. c->getComponentPropertyColour (T("mdiDocumentBkg_"), false, Colours::white),
  44372. shouldDeleteComp (c));
  44373. }
  44374. }
  44375. }
  44376. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  44377. {
  44378. if (backgroundColour != newBackgroundColour)
  44379. {
  44380. backgroundColour = newBackgroundColour;
  44381. setOpaque (newBackgroundColour.isOpaque());
  44382. repaint();
  44383. }
  44384. }
  44385. void MultiDocumentPanel::paint (Graphics& g)
  44386. {
  44387. g.fillAll (backgroundColour);
  44388. }
  44389. void MultiDocumentPanel::resized()
  44390. {
  44391. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  44392. {
  44393. for (int i = getNumChildComponents(); --i >= 0;)
  44394. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  44395. }
  44396. setWantsKeyboardFocus (components.size() == 0);
  44397. }
  44398. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  44399. {
  44400. if (mode == FloatingWindows)
  44401. {
  44402. for (int i = 0; i < getNumChildComponents(); ++i)
  44403. {
  44404. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44405. if (dw != 0 && dw->getContentComponent() == c)
  44406. {
  44407. c = dw;
  44408. break;
  44409. }
  44410. }
  44411. }
  44412. return c;
  44413. }
  44414. void MultiDocumentPanel::componentNameChanged (Component&)
  44415. {
  44416. if (mode == FloatingWindows)
  44417. {
  44418. for (int i = 0; i < getNumChildComponents(); ++i)
  44419. {
  44420. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44421. if (dw != 0)
  44422. dw->setName (dw->getContentComponent()->getName());
  44423. }
  44424. }
  44425. else if (tabComponent != 0)
  44426. {
  44427. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  44428. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  44429. }
  44430. }
  44431. void MultiDocumentPanel::updateOrder()
  44432. {
  44433. const Array <Component*> oldList (components);
  44434. if (mode == FloatingWindows)
  44435. {
  44436. components.clear();
  44437. for (int i = 0; i < getNumChildComponents(); ++i)
  44438. {
  44439. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44440. if (dw != 0)
  44441. components.add (dw->getContentComponent());
  44442. }
  44443. }
  44444. else
  44445. {
  44446. if (tabComponent != 0)
  44447. {
  44448. Component* const current = tabComponent->getCurrentContentComponent();
  44449. if (current != 0)
  44450. {
  44451. components.removeValue (current);
  44452. components.add (current);
  44453. }
  44454. }
  44455. }
  44456. if (components != oldList)
  44457. activeDocumentChanged();
  44458. }
  44459. END_JUCE_NAMESPACE
  44460. /********* End of inlined file: juce_MultiDocumentPanel.cpp *********/
  44461. /********* Start of inlined file: juce_ResizableBorderComponent.cpp *********/
  44462. BEGIN_JUCE_NAMESPACE
  44463. const int zoneL = 1;
  44464. const int zoneR = 2;
  44465. const int zoneT = 4;
  44466. const int zoneB = 8;
  44467. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  44468. ComponentBoundsConstrainer* const constrainer_)
  44469. : component (componentToResize),
  44470. constrainer (constrainer_),
  44471. borderSize (5),
  44472. mouseZone (0)
  44473. {
  44474. }
  44475. ResizableBorderComponent::~ResizableBorderComponent()
  44476. {
  44477. }
  44478. void ResizableBorderComponent::paint (Graphics& g)
  44479. {
  44480. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  44481. }
  44482. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  44483. {
  44484. updateMouseZone (e);
  44485. }
  44486. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  44487. {
  44488. updateMouseZone (e);
  44489. }
  44490. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  44491. {
  44492. if (component->isValidComponent())
  44493. {
  44494. updateMouseZone (e);
  44495. originalX = component->getX();
  44496. originalY = component->getY();
  44497. originalW = component->getWidth();
  44498. originalH = component->getHeight();
  44499. if (constrainer != 0)
  44500. constrainer->resizeStart();
  44501. }
  44502. else
  44503. {
  44504. jassertfalse
  44505. }
  44506. }
  44507. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  44508. {
  44509. if (! component->isValidComponent())
  44510. {
  44511. jassertfalse
  44512. return;
  44513. }
  44514. int x = originalX;
  44515. int y = originalY;
  44516. int w = originalW;
  44517. int h = originalH;
  44518. const int dx = e.getDistanceFromDragStartX();
  44519. const int dy = e.getDistanceFromDragStartY();
  44520. if ((mouseZone & zoneL) != 0)
  44521. {
  44522. x += dx;
  44523. w -= dx;
  44524. }
  44525. if ((mouseZone & zoneT) != 0)
  44526. {
  44527. y += dy;
  44528. h -= dy;
  44529. }
  44530. if ((mouseZone & zoneR) != 0)
  44531. w += dx;
  44532. if ((mouseZone & zoneB) != 0)
  44533. h += dy;
  44534. if (constrainer != 0)
  44535. constrainer->setBoundsForComponent (component,
  44536. x, y, w, h,
  44537. (mouseZone & zoneT) != 0,
  44538. (mouseZone & zoneL) != 0,
  44539. (mouseZone & zoneB) != 0,
  44540. (mouseZone & zoneR) != 0);
  44541. else
  44542. component->setBounds (x, y, w, h);
  44543. }
  44544. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  44545. {
  44546. if (constrainer != 0)
  44547. constrainer->resizeEnd();
  44548. }
  44549. bool ResizableBorderComponent::hitTest (int x, int y)
  44550. {
  44551. return x < borderSize.getLeft()
  44552. || x >= getWidth() - borderSize.getRight()
  44553. || y < borderSize.getTop()
  44554. || y >= getHeight() - borderSize.getBottom();
  44555. }
  44556. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize) throw()
  44557. {
  44558. if (borderSize != newBorderSize)
  44559. {
  44560. borderSize = newBorderSize;
  44561. repaint();
  44562. }
  44563. }
  44564. const BorderSize ResizableBorderComponent::getBorderThickness() const throw()
  44565. {
  44566. return borderSize;
  44567. }
  44568. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e) throw()
  44569. {
  44570. int newZone = 0;
  44571. if (ResizableBorderComponent::hitTest (e.x, e.y))
  44572. {
  44573. if (e.x < jmax (borderSize.getLeft(), proportionOfWidth (0.1f)))
  44574. newZone |= zoneL;
  44575. else if (e.x >= jmin (getWidth() - borderSize.getRight(), proportionOfWidth (0.9f)))
  44576. newZone |= zoneR;
  44577. if (e.y < jmax (borderSize.getTop(), proportionOfHeight (0.1f)))
  44578. newZone |= zoneT;
  44579. else if (e.y >= jmin (getHeight() - borderSize.getBottom(), proportionOfHeight (0.9f)))
  44580. newZone |= zoneB;
  44581. }
  44582. if (mouseZone != newZone)
  44583. {
  44584. mouseZone = newZone;
  44585. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  44586. switch (newZone)
  44587. {
  44588. case (zoneL | zoneT):
  44589. mc = MouseCursor::TopLeftCornerResizeCursor;
  44590. break;
  44591. case zoneT:
  44592. mc = MouseCursor::TopEdgeResizeCursor;
  44593. break;
  44594. case (zoneR | zoneT):
  44595. mc = MouseCursor::TopRightCornerResizeCursor;
  44596. break;
  44597. case zoneL:
  44598. mc = MouseCursor::LeftEdgeResizeCursor;
  44599. break;
  44600. case zoneR:
  44601. mc = MouseCursor::RightEdgeResizeCursor;
  44602. break;
  44603. case (zoneL | zoneB):
  44604. mc = MouseCursor::BottomLeftCornerResizeCursor;
  44605. break;
  44606. case zoneB:
  44607. mc = MouseCursor::BottomEdgeResizeCursor;
  44608. break;
  44609. case (zoneR | zoneB):
  44610. mc = MouseCursor::BottomRightCornerResizeCursor;
  44611. break;
  44612. default:
  44613. break;
  44614. }
  44615. setMouseCursor (mc);
  44616. }
  44617. }
  44618. END_JUCE_NAMESPACE
  44619. /********* End of inlined file: juce_ResizableBorderComponent.cpp *********/
  44620. /********* Start of inlined file: juce_ResizableCornerComponent.cpp *********/
  44621. BEGIN_JUCE_NAMESPACE
  44622. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  44623. ComponentBoundsConstrainer* const constrainer_)
  44624. : component (componentToResize),
  44625. constrainer (constrainer_)
  44626. {
  44627. setRepaintsOnMouseActivity (true);
  44628. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  44629. }
  44630. ResizableCornerComponent::~ResizableCornerComponent()
  44631. {
  44632. }
  44633. void ResizableCornerComponent::paint (Graphics& g)
  44634. {
  44635. getLookAndFeel()
  44636. .drawCornerResizer (g, getWidth(), getHeight(),
  44637. isMouseOverOrDragging(),
  44638. isMouseButtonDown());
  44639. }
  44640. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  44641. {
  44642. if (component->isValidComponent())
  44643. {
  44644. originalX = component->getX();
  44645. originalY = component->getY();
  44646. originalW = component->getWidth();
  44647. originalH = component->getHeight();
  44648. if (constrainer != 0)
  44649. constrainer->resizeStart();
  44650. }
  44651. else
  44652. {
  44653. jassertfalse
  44654. }
  44655. }
  44656. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  44657. {
  44658. if (! component->isValidComponent())
  44659. {
  44660. jassertfalse
  44661. return;
  44662. }
  44663. int x = originalX;
  44664. int y = originalY;
  44665. int w = originalW + e.getDistanceFromDragStartX();
  44666. int h = originalH + e.getDistanceFromDragStartY();
  44667. if (constrainer != 0)
  44668. constrainer->setBoundsForComponent (component, x, y, w, h,
  44669. false, false, true, true);
  44670. else
  44671. component->setBounds (x, y, w, h);
  44672. }
  44673. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  44674. {
  44675. if (constrainer != 0)
  44676. constrainer->resizeStart();
  44677. }
  44678. bool ResizableCornerComponent::hitTest (int x, int y)
  44679. {
  44680. if (getWidth() <= 0)
  44681. return false;
  44682. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  44683. return y >= yAtX - getHeight() / 4;
  44684. }
  44685. END_JUCE_NAMESPACE
  44686. /********* End of inlined file: juce_ResizableCornerComponent.cpp *********/
  44687. /********* Start of inlined file: juce_ScrollBar.cpp *********/
  44688. BEGIN_JUCE_NAMESPACE
  44689. class ScrollbarButton : public Button
  44690. {
  44691. public:
  44692. int direction;
  44693. ScrollbarButton (const int direction_,
  44694. ScrollBar& owner_) throw()
  44695. : Button (String::empty),
  44696. direction (direction_),
  44697. owner (owner_)
  44698. {
  44699. setWantsKeyboardFocus (false);
  44700. }
  44701. ~ScrollbarButton()
  44702. {
  44703. }
  44704. void paintButton (Graphics& g,
  44705. bool isMouseOver,
  44706. bool isMouseDown)
  44707. {
  44708. getLookAndFeel()
  44709. .drawScrollbarButton (g, owner,
  44710. getWidth(), getHeight(),
  44711. direction,
  44712. owner.isVertical(),
  44713. isMouseOver, isMouseDown);
  44714. }
  44715. void clicked()
  44716. {
  44717. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  44718. }
  44719. juce_UseDebuggingNewOperator
  44720. private:
  44721. ScrollBar& owner;
  44722. ScrollbarButton (const ScrollbarButton&);
  44723. const ScrollbarButton& operator= (const ScrollbarButton&);
  44724. };
  44725. ScrollBar::ScrollBar (const bool vertical_,
  44726. const bool buttonsAreVisible)
  44727. : minimum (0.0),
  44728. maximum (1.0),
  44729. rangeStart (0.0),
  44730. rangeSize (0.1),
  44731. singleStepSize (0.1),
  44732. thumbAreaStart (0),
  44733. thumbAreaSize (0),
  44734. thumbStart (0),
  44735. thumbSize (0),
  44736. initialDelayInMillisecs (100),
  44737. repeatDelayInMillisecs (50),
  44738. minimumDelayInMillisecs (10),
  44739. vertical (vertical_),
  44740. isDraggingThumb (false),
  44741. alwaysVisible (false),
  44742. upButton (0),
  44743. downButton (0),
  44744. listeners (2)
  44745. {
  44746. setButtonVisibility (buttonsAreVisible);
  44747. setRepaintsOnMouseActivity (true);
  44748. setFocusContainer (true);
  44749. }
  44750. ScrollBar::~ScrollBar()
  44751. {
  44752. deleteAllChildren();
  44753. }
  44754. void ScrollBar::setRangeLimits (const double newMinimum,
  44755. const double newMaximum) throw()
  44756. {
  44757. minimum = newMinimum;
  44758. maximum = newMaximum;
  44759. jassert (maximum >= minimum); // these can't be the wrong way round!
  44760. setCurrentRangeStart (rangeStart);
  44761. updateThumbPosition();
  44762. }
  44763. void ScrollBar::setCurrentRange (double newStart,
  44764. double newSize) throw()
  44765. {
  44766. newSize = jlimit (0.0, maximum - minimum, newSize);
  44767. newStart = jlimit (minimum, maximum - newSize, newStart);
  44768. if (rangeStart != newStart
  44769. || rangeSize != newSize)
  44770. {
  44771. rangeStart = newStart;
  44772. rangeSize = newSize;
  44773. updateThumbPosition();
  44774. triggerAsyncUpdate();
  44775. }
  44776. }
  44777. void ScrollBar::setCurrentRangeStart (double newStart) throw()
  44778. {
  44779. setCurrentRange (newStart, rangeSize);
  44780. }
  44781. void ScrollBar::setSingleStepSize (const double newSingleStepSize) throw()
  44782. {
  44783. singleStepSize = newSingleStepSize;
  44784. }
  44785. void ScrollBar::moveScrollbarInSteps (const int howManySteps) throw()
  44786. {
  44787. setCurrentRangeStart (rangeStart + howManySteps * singleStepSize);
  44788. }
  44789. void ScrollBar::moveScrollbarInPages (const int howManyPages) throw()
  44790. {
  44791. setCurrentRangeStart (rangeStart + howManyPages * rangeSize);
  44792. }
  44793. void ScrollBar::scrollToTop() throw()
  44794. {
  44795. setCurrentRangeStart (minimum);
  44796. }
  44797. void ScrollBar::scrollToBottom() throw()
  44798. {
  44799. setCurrentRangeStart (maximum - rangeSize);
  44800. }
  44801. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  44802. const int repeatDelayInMillisecs_,
  44803. const int minimumDelayInMillisecs_) throw()
  44804. {
  44805. initialDelayInMillisecs = initialDelayInMillisecs_;
  44806. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  44807. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  44808. if (upButton != 0)
  44809. {
  44810. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  44811. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  44812. }
  44813. }
  44814. void ScrollBar::addListener (ScrollBarListener* const listener) throw()
  44815. {
  44816. jassert (listener != 0);
  44817. if (listener != 0)
  44818. listeners.add (listener);
  44819. }
  44820. void ScrollBar::removeListener (ScrollBarListener* const listener) throw()
  44821. {
  44822. listeners.removeValue (listener);
  44823. }
  44824. void ScrollBar::handleAsyncUpdate()
  44825. {
  44826. const double value = getCurrentRangeStart();
  44827. for (int i = listeners.size(); --i >= 0;)
  44828. {
  44829. ((ScrollBarListener*) listeners.getUnchecked (i))->scrollBarMoved (this, value);
  44830. i = jmin (i, listeners.size());
  44831. }
  44832. }
  44833. void ScrollBar::updateThumbPosition() throw()
  44834. {
  44835. int newThumbSize = roundDoubleToInt ((maximum > minimum) ? (rangeSize * thumbAreaSize) / (maximum - minimum)
  44836. : thumbAreaSize);
  44837. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  44838. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  44839. if (newThumbSize > thumbAreaSize)
  44840. newThumbSize = thumbAreaSize;
  44841. int newThumbStart = thumbAreaStart;
  44842. if (maximum - minimum > rangeSize)
  44843. newThumbStart += roundDoubleToInt (((rangeStart - minimum) * (thumbAreaSize - newThumbSize))
  44844. / ((maximum - minimum) - rangeSize));
  44845. setVisible (alwaysVisible || (maximum - minimum > rangeSize && rangeSize > 0.0));
  44846. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  44847. {
  44848. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  44849. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  44850. if (vertical)
  44851. repaint (0, repaintStart, getWidth(), repaintSize);
  44852. else
  44853. repaint (repaintStart, 0, repaintSize, getHeight());
  44854. thumbStart = newThumbStart;
  44855. thumbSize = newThumbSize;
  44856. }
  44857. }
  44858. void ScrollBar::setOrientation (const bool shouldBeVertical) throw()
  44859. {
  44860. if (vertical != shouldBeVertical)
  44861. {
  44862. vertical = shouldBeVertical;
  44863. if (upButton != 0)
  44864. {
  44865. ((ScrollbarButton*) upButton)->direction = (vertical) ? 0 : 3;
  44866. ((ScrollbarButton*) downButton)->direction = (vertical) ? 2 : 1;
  44867. }
  44868. updateThumbPosition();
  44869. }
  44870. }
  44871. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  44872. {
  44873. deleteAndZero (upButton);
  44874. deleteAndZero (downButton);
  44875. if (buttonsAreVisible)
  44876. {
  44877. addAndMakeVisible (upButton = new ScrollbarButton ((vertical) ? 0 : 3, *this));
  44878. addAndMakeVisible (downButton = new ScrollbarButton ((vertical) ? 2 : 1, *this));
  44879. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  44880. }
  44881. updateThumbPosition();
  44882. }
  44883. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  44884. {
  44885. alwaysVisible = ! shouldHideWhenFullRange;
  44886. updateThumbPosition();
  44887. }
  44888. void ScrollBar::paint (Graphics& g)
  44889. {
  44890. if (thumbAreaSize > 0)
  44891. {
  44892. LookAndFeel& lf = getLookAndFeel();
  44893. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  44894. ? thumbSize : 0;
  44895. if (vertical)
  44896. {
  44897. lf.drawScrollbar (g, *this,
  44898. 0, thumbAreaStart,
  44899. getWidth(), thumbAreaSize,
  44900. vertical,
  44901. thumbStart, thumb,
  44902. isMouseOver(), isMouseButtonDown());
  44903. }
  44904. else
  44905. {
  44906. lf.drawScrollbar (g, *this,
  44907. thumbAreaStart, 0,
  44908. thumbAreaSize, getHeight(),
  44909. vertical,
  44910. thumbStart, thumb,
  44911. isMouseOver(), isMouseButtonDown());
  44912. }
  44913. }
  44914. }
  44915. void ScrollBar::lookAndFeelChanged()
  44916. {
  44917. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  44918. }
  44919. void ScrollBar::resized()
  44920. {
  44921. const int length = ((vertical) ? getHeight() : getWidth());
  44922. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  44923. : 0;
  44924. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  44925. {
  44926. thumbAreaStart = length >> 1;
  44927. thumbAreaSize = 0;
  44928. }
  44929. else
  44930. {
  44931. thumbAreaStart = buttonSize;
  44932. thumbAreaSize = length - (buttonSize << 1);
  44933. }
  44934. if (upButton != 0)
  44935. {
  44936. if (vertical)
  44937. {
  44938. upButton->setBounds (0, 0, getWidth(), buttonSize);
  44939. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  44940. }
  44941. else
  44942. {
  44943. upButton->setBounds (0, 0, buttonSize, getHeight());
  44944. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  44945. }
  44946. }
  44947. updateThumbPosition();
  44948. }
  44949. void ScrollBar::mouseDown (const MouseEvent& e)
  44950. {
  44951. isDraggingThumb = false;
  44952. lastMousePos = vertical ? e.y : e.x;
  44953. dragStartMousePos = lastMousePos;
  44954. dragStartRange = rangeStart;
  44955. if (dragStartMousePos < thumbStart)
  44956. {
  44957. moveScrollbarInPages (-1);
  44958. startTimer (400);
  44959. }
  44960. else if (dragStartMousePos >= thumbStart + thumbSize)
  44961. {
  44962. moveScrollbarInPages (1);
  44963. startTimer (400);
  44964. }
  44965. else
  44966. {
  44967. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  44968. && (thumbAreaSize > thumbSize);
  44969. }
  44970. }
  44971. void ScrollBar::mouseDrag (const MouseEvent& e)
  44972. {
  44973. if (isDraggingThumb)
  44974. {
  44975. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  44976. setCurrentRangeStart (dragStartRange
  44977. + deltaPixels * ((maximum - minimum) - rangeSize)
  44978. / (thumbAreaSize - thumbSize));
  44979. }
  44980. else
  44981. {
  44982. lastMousePos = (vertical) ? e.y : e.x;
  44983. }
  44984. }
  44985. void ScrollBar::mouseUp (const MouseEvent&)
  44986. {
  44987. isDraggingThumb = false;
  44988. stopTimer();
  44989. repaint();
  44990. }
  44991. void ScrollBar::mouseWheelMove (const MouseEvent&,
  44992. float wheelIncrementX,
  44993. float wheelIncrementY)
  44994. {
  44995. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  44996. if (increment < 0)
  44997. increment = jmin (increment * 10.0f, -1.0f);
  44998. else if (increment > 0)
  44999. increment = jmax (increment * 10.0f, 1.0f);
  45000. setCurrentRangeStart (rangeStart - singleStepSize * increment);
  45001. }
  45002. void ScrollBar::timerCallback()
  45003. {
  45004. if (isMouseButtonDown())
  45005. {
  45006. startTimer (40);
  45007. if (lastMousePos < thumbStart)
  45008. setCurrentRangeStart (rangeStart - rangeSize);
  45009. else if (lastMousePos > thumbStart + thumbSize)
  45010. setCurrentRangeStart (rangeStart + rangeSize);
  45011. }
  45012. else
  45013. {
  45014. stopTimer();
  45015. }
  45016. }
  45017. bool ScrollBar::keyPressed (const KeyPress& key)
  45018. {
  45019. if (! isVisible())
  45020. return false;
  45021. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  45022. moveScrollbarInSteps (-1);
  45023. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  45024. moveScrollbarInSteps (1);
  45025. else if (key.isKeyCode (KeyPress::pageUpKey))
  45026. moveScrollbarInPages (-1);
  45027. else if (key.isKeyCode (KeyPress::pageDownKey))
  45028. moveScrollbarInPages (1);
  45029. else if (key.isKeyCode (KeyPress::homeKey))
  45030. scrollToTop();
  45031. else if (key.isKeyCode (KeyPress::endKey))
  45032. scrollToBottom();
  45033. else
  45034. return false;
  45035. return true;
  45036. }
  45037. END_JUCE_NAMESPACE
  45038. /********* End of inlined file: juce_ScrollBar.cpp *********/
  45039. /********* Start of inlined file: juce_StretchableLayoutManager.cpp *********/
  45040. BEGIN_JUCE_NAMESPACE
  45041. StretchableLayoutManager::StretchableLayoutManager()
  45042. : totalSize (0)
  45043. {
  45044. }
  45045. StretchableLayoutManager::~StretchableLayoutManager()
  45046. {
  45047. }
  45048. void StretchableLayoutManager::clearAllItems()
  45049. {
  45050. items.clear();
  45051. totalSize = 0;
  45052. }
  45053. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  45054. const double minimumSize,
  45055. const double maximumSize,
  45056. const double preferredSize)
  45057. {
  45058. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  45059. if (layout == 0)
  45060. {
  45061. layout = new ItemLayoutProperties();
  45062. layout->itemIndex = itemIndex;
  45063. int i;
  45064. for (i = 0; i < items.size(); ++i)
  45065. if (items.getUnchecked (i)->itemIndex > itemIndex)
  45066. break;
  45067. items.insert (i, layout);
  45068. }
  45069. layout->minSize = minimumSize;
  45070. layout->maxSize = maximumSize;
  45071. layout->preferredSize = preferredSize;
  45072. layout->currentSize = 0;
  45073. }
  45074. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  45075. double& minimumSize,
  45076. double& maximumSize,
  45077. double& preferredSize) const
  45078. {
  45079. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  45080. if (layout != 0)
  45081. {
  45082. minimumSize = layout->minSize;
  45083. maximumSize = layout->maxSize;
  45084. preferredSize = layout->preferredSize;
  45085. return true;
  45086. }
  45087. return false;
  45088. }
  45089. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  45090. {
  45091. totalSize = newTotalSize;
  45092. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  45093. }
  45094. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  45095. {
  45096. int pos = 0;
  45097. for (int i = 0; i < itemIndex; ++i)
  45098. {
  45099. const ItemLayoutProperties* const layout = getInfoFor (i);
  45100. if (layout != 0)
  45101. pos += layout->currentSize;
  45102. }
  45103. return pos;
  45104. }
  45105. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  45106. {
  45107. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  45108. if (layout != 0)
  45109. return layout->currentSize;
  45110. return 0;
  45111. }
  45112. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  45113. {
  45114. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  45115. if (layout != 0)
  45116. return -layout->currentSize / (double) totalSize;
  45117. return 0;
  45118. }
  45119. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  45120. int newPosition)
  45121. {
  45122. for (int i = items.size(); --i >= 0;)
  45123. {
  45124. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  45125. if (layout->itemIndex == itemIndex)
  45126. {
  45127. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  45128. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  45129. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  45130. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  45131. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  45132. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  45133. endPos += layout->currentSize;
  45134. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  45135. updatePrefSizesToMatchCurrentPositions();
  45136. break;
  45137. }
  45138. }
  45139. }
  45140. void StretchableLayoutManager::layOutComponents (Component** const components,
  45141. int numComponents,
  45142. int x, int y, int w, int h,
  45143. const bool vertically,
  45144. const bool resizeOtherDimension)
  45145. {
  45146. setTotalSize (vertically ? h : w);
  45147. int pos = vertically ? y : x;
  45148. for (int i = 0; i < numComponents; ++i)
  45149. {
  45150. const ItemLayoutProperties* const layout = getInfoFor (i);
  45151. if (layout != 0)
  45152. {
  45153. Component* const c = components[i];
  45154. if (c != 0)
  45155. {
  45156. if (i == numComponents - 1)
  45157. {
  45158. // if it's the last item, crop it to exactly fit the available space..
  45159. if (resizeOtherDimension)
  45160. {
  45161. if (vertically)
  45162. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  45163. else
  45164. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  45165. }
  45166. else
  45167. {
  45168. if (vertically)
  45169. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  45170. else
  45171. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  45172. }
  45173. }
  45174. else
  45175. {
  45176. if (resizeOtherDimension)
  45177. {
  45178. if (vertically)
  45179. c->setBounds (x, pos, w, layout->currentSize);
  45180. else
  45181. c->setBounds (pos, y, layout->currentSize, h);
  45182. }
  45183. else
  45184. {
  45185. if (vertically)
  45186. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  45187. else
  45188. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  45189. }
  45190. }
  45191. }
  45192. pos += layout->currentSize;
  45193. }
  45194. }
  45195. }
  45196. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  45197. {
  45198. for (int i = items.size(); --i >= 0;)
  45199. if (items.getUnchecked(i)->itemIndex == itemIndex)
  45200. return items.getUnchecked(i);
  45201. return 0;
  45202. }
  45203. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  45204. const int endIndex,
  45205. const int availableSpace,
  45206. int startPos)
  45207. {
  45208. // calculate the total sizes
  45209. int i;
  45210. double totalIdealSize = 0.0;
  45211. int totalMinimums = 0;
  45212. for (i = startIndex; i < endIndex; ++i)
  45213. {
  45214. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45215. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  45216. totalMinimums += layout->currentSize;
  45217. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  45218. }
  45219. if (totalIdealSize <= 0)
  45220. totalIdealSize = 1.0;
  45221. // now calc the best sizes..
  45222. int extraSpace = availableSpace - totalMinimums;
  45223. while (extraSpace > 0)
  45224. {
  45225. int numWantingMoreSpace = 0;
  45226. int numHavingTakenExtraSpace = 0;
  45227. // first figure out how many comps want a slice of the extra space..
  45228. for (i = startIndex; i < endIndex; ++i)
  45229. {
  45230. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45231. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  45232. const int bestSize = jlimit (layout->currentSize,
  45233. jmax (layout->currentSize,
  45234. sizeToRealSize (layout->maxSize, totalSize)),
  45235. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  45236. if (bestSize > layout->currentSize)
  45237. ++numWantingMoreSpace;
  45238. }
  45239. // ..share out the extra space..
  45240. for (i = startIndex; i < endIndex; ++i)
  45241. {
  45242. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45243. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  45244. int bestSize = jlimit (layout->currentSize,
  45245. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  45246. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  45247. const int extraWanted = bestSize - layout->currentSize;
  45248. if (extraWanted > 0)
  45249. {
  45250. const int extraAllowed = jmin (extraWanted,
  45251. extraSpace / jmax (1, numWantingMoreSpace));
  45252. if (extraAllowed > 0)
  45253. {
  45254. ++numHavingTakenExtraSpace;
  45255. --numWantingMoreSpace;
  45256. layout->currentSize += extraAllowed;
  45257. extraSpace -= extraAllowed;
  45258. }
  45259. }
  45260. }
  45261. if (numHavingTakenExtraSpace <= 0)
  45262. break;
  45263. }
  45264. // ..and calculate the end position
  45265. for (i = startIndex; i < endIndex; ++i)
  45266. {
  45267. ItemLayoutProperties* const layout = items.getUnchecked(i);
  45268. startPos += layout->currentSize;
  45269. }
  45270. return startPos;
  45271. }
  45272. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  45273. const int endIndex) const
  45274. {
  45275. int totalMinimums = 0;
  45276. for (int i = startIndex; i < endIndex; ++i)
  45277. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  45278. return totalMinimums;
  45279. }
  45280. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  45281. {
  45282. int totalMaximums = 0;
  45283. for (int i = startIndex; i < endIndex; ++i)
  45284. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  45285. return totalMaximums;
  45286. }
  45287. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  45288. {
  45289. for (int i = 0; i < items.size(); ++i)
  45290. {
  45291. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45292. layout->preferredSize
  45293. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  45294. : getItemCurrentAbsoluteSize (i);
  45295. }
  45296. }
  45297. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  45298. {
  45299. if (size < 0)
  45300. size *= -totalSpace;
  45301. return roundDoubleToInt (size);
  45302. }
  45303. END_JUCE_NAMESPACE
  45304. /********* End of inlined file: juce_StretchableLayoutManager.cpp *********/
  45305. /********* Start of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  45306. BEGIN_JUCE_NAMESPACE
  45307. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  45308. const int itemIndex_,
  45309. const bool isVertical_)
  45310. : layout (layout_),
  45311. itemIndex (itemIndex_),
  45312. isVertical (isVertical_)
  45313. {
  45314. setRepaintsOnMouseActivity (true);
  45315. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  45316. : MouseCursor::UpDownResizeCursor));
  45317. }
  45318. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  45319. {
  45320. }
  45321. void StretchableLayoutResizerBar::paint (Graphics& g)
  45322. {
  45323. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  45324. getWidth(), getHeight(),
  45325. isVertical,
  45326. isMouseOver(),
  45327. isMouseButtonDown());
  45328. }
  45329. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  45330. {
  45331. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  45332. }
  45333. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  45334. {
  45335. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  45336. : e.getDistanceFromDragStartY());
  45337. layout->setItemPosition (itemIndex, desiredPos);
  45338. hasBeenMoved();
  45339. }
  45340. void StretchableLayoutResizerBar::hasBeenMoved()
  45341. {
  45342. if (getParentComponent() != 0)
  45343. getParentComponent()->resized();
  45344. }
  45345. END_JUCE_NAMESPACE
  45346. /********* End of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  45347. /********* Start of inlined file: juce_StretchableObjectResizer.cpp *********/
  45348. BEGIN_JUCE_NAMESPACE
  45349. StretchableObjectResizer::StretchableObjectResizer()
  45350. {
  45351. }
  45352. StretchableObjectResizer::~StretchableObjectResizer()
  45353. {
  45354. }
  45355. void StretchableObjectResizer::addItem (const double size,
  45356. const double minSize, const double maxSize,
  45357. const int order)
  45358. {
  45359. jassert (order >= 0 && order < INT_MAX); // the order must be >= 0 and less than INT_MAX
  45360. Item* const item = new Item();
  45361. item->size = size;
  45362. item->minSize = minSize;
  45363. item->maxSize = maxSize;
  45364. item->order = order;
  45365. items.add (item);
  45366. }
  45367. double StretchableObjectResizer::getItemSize (const int index) const throw()
  45368. {
  45369. const Item* const it = items [index];
  45370. return it != 0 ? it->size : 0;
  45371. }
  45372. void StretchableObjectResizer::resizeToFit (const double targetSize)
  45373. {
  45374. int order = 0;
  45375. for (;;)
  45376. {
  45377. double currentSize = 0;
  45378. double minSize = 0;
  45379. double maxSize = 0;
  45380. int nextHighestOrder = INT_MAX;
  45381. for (int i = 0; i < items.size(); ++i)
  45382. {
  45383. const Item* const it = items.getUnchecked(i);
  45384. currentSize += it->size;
  45385. if (it->order <= order)
  45386. {
  45387. minSize += it->minSize;
  45388. maxSize += it->maxSize;
  45389. }
  45390. else
  45391. {
  45392. minSize += it->size;
  45393. maxSize += it->size;
  45394. nextHighestOrder = jmin (nextHighestOrder, it->order);
  45395. }
  45396. }
  45397. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  45398. if (thisIterationTarget >= currentSize)
  45399. {
  45400. const double availableExtraSpace = maxSize - currentSize;
  45401. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  45402. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  45403. for (int i = 0; i < items.size(); ++i)
  45404. {
  45405. Item* const it = items.getUnchecked(i);
  45406. if (it->order <= order)
  45407. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  45408. }
  45409. }
  45410. else
  45411. {
  45412. const double amountOfSlack = currentSize - minSize;
  45413. const double targetAmountOfSlack = thisIterationTarget - minSize;
  45414. const double scale = targetAmountOfSlack / amountOfSlack;
  45415. for (int i = 0; i < items.size(); ++i)
  45416. {
  45417. Item* const it = items.getUnchecked(i);
  45418. if (it->order <= order)
  45419. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  45420. }
  45421. }
  45422. if (nextHighestOrder < INT_MAX)
  45423. order = nextHighestOrder;
  45424. else
  45425. break;
  45426. }
  45427. }
  45428. END_JUCE_NAMESPACE
  45429. /********* End of inlined file: juce_StretchableObjectResizer.cpp *********/
  45430. /********* Start of inlined file: juce_TabbedButtonBar.cpp *********/
  45431. BEGIN_JUCE_NAMESPACE
  45432. TabBarButton::TabBarButton (const String& name,
  45433. TabbedButtonBar* const owner_,
  45434. const int index)
  45435. : Button (name),
  45436. owner (owner_),
  45437. tabIndex (index),
  45438. overlapPixels (0)
  45439. {
  45440. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  45441. setComponentEffect (&shadow);
  45442. setWantsKeyboardFocus (false);
  45443. }
  45444. TabBarButton::~TabBarButton()
  45445. {
  45446. }
  45447. void TabBarButton::paintButton (Graphics& g,
  45448. bool isMouseOverButton,
  45449. bool isButtonDown)
  45450. {
  45451. int x, y, w, h;
  45452. getActiveArea (x, y, w, h);
  45453. g.setOrigin (x, y);
  45454. getLookAndFeel()
  45455. .drawTabButton (g, w, h,
  45456. owner->getTabBackgroundColour (tabIndex),
  45457. tabIndex, getButtonText(), *this,
  45458. owner->getOrientation(),
  45459. isMouseOverButton, isButtonDown,
  45460. getToggleState());
  45461. }
  45462. void TabBarButton::clicked (const ModifierKeys& mods)
  45463. {
  45464. if (mods.isPopupMenu())
  45465. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  45466. else
  45467. owner->setCurrentTabIndex (tabIndex);
  45468. }
  45469. bool TabBarButton::hitTest (int mx, int my)
  45470. {
  45471. int x, y, w, h;
  45472. getActiveArea (x, y, w, h);
  45473. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  45474. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  45475. {
  45476. if (((unsigned int) mx) < (unsigned int) getWidth()
  45477. && my >= y + overlapPixels
  45478. && my < y + h - overlapPixels)
  45479. return true;
  45480. }
  45481. else
  45482. {
  45483. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  45484. && ((unsigned int) my) < (unsigned int) getHeight())
  45485. return true;
  45486. }
  45487. Path p;
  45488. getLookAndFeel()
  45489. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  45490. owner->getOrientation(),
  45491. false, false, getToggleState());
  45492. return p.contains ((float) (mx - x),
  45493. (float) (my - y));
  45494. }
  45495. int TabBarButton::getBestTabLength (const int depth)
  45496. {
  45497. return jlimit (depth * 2,
  45498. depth * 7,
  45499. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  45500. }
  45501. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  45502. {
  45503. x = 0;
  45504. y = 0;
  45505. int r = getWidth();
  45506. int b = getHeight();
  45507. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  45508. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  45509. r -= spaceAroundImage;
  45510. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  45511. x += spaceAroundImage;
  45512. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  45513. y += spaceAroundImage;
  45514. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  45515. b -= spaceAroundImage;
  45516. w = r - x;
  45517. h = b - y;
  45518. }
  45519. class TabAreaBehindFrontButtonComponent : public Component
  45520. {
  45521. public:
  45522. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  45523. : owner (owner_)
  45524. {
  45525. setInterceptsMouseClicks (false, false);
  45526. }
  45527. ~TabAreaBehindFrontButtonComponent()
  45528. {
  45529. }
  45530. void paint (Graphics& g)
  45531. {
  45532. getLookAndFeel()
  45533. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  45534. *owner, owner->getOrientation());
  45535. }
  45536. void enablementChanged()
  45537. {
  45538. repaint();
  45539. }
  45540. private:
  45541. TabbedButtonBar* const owner;
  45542. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  45543. const TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  45544. };
  45545. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  45546. : orientation (orientation_),
  45547. currentTabIndex (-1),
  45548. extraTabsButton (0)
  45549. {
  45550. setInterceptsMouseClicks (false, true);
  45551. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  45552. setFocusContainer (true);
  45553. }
  45554. TabbedButtonBar::~TabbedButtonBar()
  45555. {
  45556. deleteAllChildren();
  45557. }
  45558. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  45559. {
  45560. orientation = newOrientation;
  45561. for (int i = getNumChildComponents(); --i >= 0;)
  45562. getChildComponent (i)->resized();
  45563. resized();
  45564. }
  45565. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  45566. {
  45567. return new TabBarButton (name, this, index);
  45568. }
  45569. void TabbedButtonBar::clearTabs()
  45570. {
  45571. tabs.clear();
  45572. tabColours.clear();
  45573. currentTabIndex = -1;
  45574. deleteAndZero (extraTabsButton);
  45575. removeChildComponent (behindFrontTab);
  45576. deleteAllChildren();
  45577. addChildComponent (behindFrontTab);
  45578. setCurrentTabIndex (-1);
  45579. }
  45580. void TabbedButtonBar::addTab (const String& tabName,
  45581. const Colour& tabBackgroundColour,
  45582. int insertIndex)
  45583. {
  45584. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  45585. if (tabName.isNotEmpty())
  45586. {
  45587. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  45588. insertIndex = tabs.size();
  45589. for (int i = tabs.size(); --i >= insertIndex;)
  45590. {
  45591. TabBarButton* const tb = getTabButton (i);
  45592. if (tb != 0)
  45593. tb->tabIndex++;
  45594. }
  45595. tabs.insert (insertIndex, tabName);
  45596. tabColours.insert (insertIndex, tabBackgroundColour);
  45597. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  45598. jassert (tb != 0); // your createTabButton() mustn't return zero!
  45599. addAndMakeVisible (tb, insertIndex);
  45600. resized();
  45601. if (currentTabIndex < 0)
  45602. setCurrentTabIndex (0);
  45603. }
  45604. }
  45605. void TabbedButtonBar::setTabName (const int tabIndex,
  45606. const String& newName)
  45607. {
  45608. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  45609. && tabs[tabIndex] != newName)
  45610. {
  45611. tabs.set (tabIndex, newName);
  45612. TabBarButton* const tb = getTabButton (tabIndex);
  45613. if (tb != 0)
  45614. tb->setButtonText (newName);
  45615. resized();
  45616. }
  45617. }
  45618. void TabbedButtonBar::removeTab (const int tabIndex)
  45619. {
  45620. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  45621. {
  45622. const int oldTabIndex = currentTabIndex;
  45623. if (currentTabIndex == tabIndex)
  45624. currentTabIndex = -1;
  45625. tabs.remove (tabIndex);
  45626. tabColours.remove (tabIndex);
  45627. TabBarButton* const tb = getTabButton (tabIndex);
  45628. if (tb != 0)
  45629. delete tb;
  45630. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  45631. {
  45632. TabBarButton* const tb = getTabButton (i);
  45633. if (tb != 0)
  45634. tb->tabIndex--;
  45635. }
  45636. resized();
  45637. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  45638. }
  45639. }
  45640. void TabbedButtonBar::moveTab (const int currentIndex,
  45641. const int newIndex)
  45642. {
  45643. tabs.move (currentIndex, newIndex);
  45644. tabColours.move (currentIndex, newIndex);
  45645. resized();
  45646. }
  45647. int TabbedButtonBar::getNumTabs() const
  45648. {
  45649. return tabs.size();
  45650. }
  45651. const StringArray TabbedButtonBar::getTabNames() const
  45652. {
  45653. return tabs;
  45654. }
  45655. void TabbedButtonBar::setCurrentTabIndex (int newIndex)
  45656. {
  45657. if (currentTabIndex != newIndex)
  45658. {
  45659. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  45660. newIndex = -1;
  45661. currentTabIndex = newIndex;
  45662. for (int i = 0; i < getNumChildComponents(); ++i)
  45663. {
  45664. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  45665. if (tb != 0)
  45666. tb->setToggleState (tb->tabIndex == newIndex, false);
  45667. }
  45668. resized();
  45669. sendChangeMessage (this);
  45670. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  45671. }
  45672. }
  45673. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  45674. {
  45675. for (int i = getNumChildComponents(); --i >= 0;)
  45676. {
  45677. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  45678. if (tb != 0 && tb->tabIndex == index)
  45679. return tb;
  45680. }
  45681. return 0;
  45682. }
  45683. void TabbedButtonBar::lookAndFeelChanged()
  45684. {
  45685. deleteAndZero (extraTabsButton);
  45686. resized();
  45687. }
  45688. void TabbedButtonBar::resized()
  45689. {
  45690. const double minimumScale = 0.7;
  45691. int depth = getWidth();
  45692. int length = getHeight();
  45693. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  45694. swapVariables (depth, length);
  45695. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  45696. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  45697. int i, totalLength = overlap;
  45698. int numVisibleButtons = tabs.size();
  45699. for (i = 0; i < getNumChildComponents(); ++i)
  45700. {
  45701. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  45702. if (tb != 0)
  45703. {
  45704. totalLength += tb->getBestTabLength (depth) - overlap;
  45705. tb->overlapPixels = overlap / 2;
  45706. }
  45707. }
  45708. double scale = 1.0;
  45709. if (totalLength > length)
  45710. scale = jmax (minimumScale, length / (double) totalLength);
  45711. const bool isTooBig = totalLength * scale > length;
  45712. int tabsButtonPos = 0;
  45713. if (isTooBig)
  45714. {
  45715. if (extraTabsButton == 0)
  45716. {
  45717. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  45718. extraTabsButton->addButtonListener (this);
  45719. extraTabsButton->setAlwaysOnTop (true);
  45720. extraTabsButton->setTriggeredOnMouseDown (true);
  45721. }
  45722. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  45723. extraTabsButton->setSize (buttonSize, buttonSize);
  45724. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  45725. {
  45726. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  45727. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  45728. }
  45729. else
  45730. {
  45731. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  45732. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  45733. }
  45734. totalLength = 0;
  45735. for (i = 0; i < tabs.size(); ++i)
  45736. {
  45737. TabBarButton* const tb = getTabButton (i);
  45738. if (tb != 0)
  45739. {
  45740. const int newLength = totalLength + tb->getBestTabLength (depth);
  45741. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  45742. {
  45743. totalLength += overlap;
  45744. break;
  45745. }
  45746. numVisibleButtons = i + 1;
  45747. totalLength = newLength - overlap;
  45748. }
  45749. }
  45750. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  45751. }
  45752. else
  45753. {
  45754. deleteAndZero (extraTabsButton);
  45755. }
  45756. int pos = 0;
  45757. TabBarButton* frontTab = 0;
  45758. for (i = 0; i < tabs.size(); ++i)
  45759. {
  45760. TabBarButton* const tb = getTabButton (i);
  45761. if (tb != 0)
  45762. {
  45763. const int bestLength = roundDoubleToInt (scale * tb->getBestTabLength (depth));
  45764. if (i < numVisibleButtons)
  45765. {
  45766. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  45767. tb->setBounds (pos, 0, bestLength, getHeight());
  45768. else
  45769. tb->setBounds (0, pos, getWidth(), bestLength);
  45770. tb->toBack();
  45771. if (tb->tabIndex == currentTabIndex)
  45772. frontTab = tb;
  45773. tb->setVisible (true);
  45774. }
  45775. else
  45776. {
  45777. tb->setVisible (false);
  45778. }
  45779. pos += bestLength - overlap;
  45780. }
  45781. }
  45782. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  45783. if (frontTab != 0)
  45784. {
  45785. frontTab->toFront (false);
  45786. behindFrontTab->toBehind (frontTab);
  45787. }
  45788. }
  45789. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  45790. {
  45791. return tabColours [tabIndex];
  45792. }
  45793. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  45794. {
  45795. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  45796. && tabColours [tabIndex] != newColour)
  45797. {
  45798. tabColours.set (tabIndex, newColour);
  45799. repaint();
  45800. }
  45801. }
  45802. void TabbedButtonBar::buttonClicked (Button* button)
  45803. {
  45804. if (extraTabsButton == button)
  45805. {
  45806. PopupMenu m;
  45807. for (int i = 0; i < tabs.size(); ++i)
  45808. {
  45809. TabBarButton* const tb = getTabButton (i);
  45810. if (tb != 0 && ! tb->isVisible())
  45811. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  45812. }
  45813. const int res = m.showAt (extraTabsButton);
  45814. if (res != 0)
  45815. setCurrentTabIndex (res - 1);
  45816. }
  45817. }
  45818. void TabbedButtonBar::currentTabChanged (const int, const String&)
  45819. {
  45820. }
  45821. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  45822. {
  45823. }
  45824. END_JUCE_NAMESPACE
  45825. /********* End of inlined file: juce_TabbedButtonBar.cpp *********/
  45826. /********* Start of inlined file: juce_TabbedComponent.cpp *********/
  45827. BEGIN_JUCE_NAMESPACE
  45828. class TabCompButtonBar : public TabbedButtonBar
  45829. {
  45830. public:
  45831. TabCompButtonBar (TabbedComponent* const owner_,
  45832. const TabbedButtonBar::Orientation orientation)
  45833. : TabbedButtonBar (orientation),
  45834. owner (owner_)
  45835. {
  45836. }
  45837. ~TabCompButtonBar()
  45838. {
  45839. }
  45840. void currentTabChanged (const int newCurrentTabIndex,
  45841. const String& newTabName)
  45842. {
  45843. owner->changeCallback (newCurrentTabIndex, newTabName);
  45844. }
  45845. void popupMenuClickOnTab (const int tabIndex,
  45846. const String& tabName)
  45847. {
  45848. owner->popupMenuClickOnTab (tabIndex, tabName);
  45849. }
  45850. const Colour getTabBackgroundColour (const int tabIndex)
  45851. {
  45852. return owner->tabs->getTabBackgroundColour (tabIndex);
  45853. }
  45854. TabBarButton* createTabButton (const String& tabName, const int tabIndex)
  45855. {
  45856. return owner->createTabButton (tabName, tabIndex);
  45857. }
  45858. juce_UseDebuggingNewOperator
  45859. private:
  45860. TabbedComponent* const owner;
  45861. TabCompButtonBar (const TabCompButtonBar&);
  45862. const TabCompButtonBar& operator= (const TabCompButtonBar&);
  45863. };
  45864. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  45865. : panelComponent (0),
  45866. tabDepth (30),
  45867. outlineColour (Colours::grey),
  45868. outlineThickness (1),
  45869. edgeIndent (0)
  45870. {
  45871. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  45872. }
  45873. TabbedComponent::~TabbedComponent()
  45874. {
  45875. clearTabs();
  45876. delete tabs;
  45877. }
  45878. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  45879. {
  45880. tabs->setOrientation (orientation);
  45881. resized();
  45882. }
  45883. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  45884. {
  45885. return tabs->getOrientation();
  45886. }
  45887. void TabbedComponent::setTabBarDepth (const int newDepth)
  45888. {
  45889. if (tabDepth != newDepth)
  45890. {
  45891. tabDepth = newDepth;
  45892. resized();
  45893. }
  45894. }
  45895. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  45896. {
  45897. return new TabBarButton (tabName, tabs, tabIndex);
  45898. }
  45899. void TabbedComponent::clearTabs()
  45900. {
  45901. if (panelComponent != 0)
  45902. {
  45903. panelComponent->setVisible (false);
  45904. removeChildComponent (panelComponent);
  45905. panelComponent = 0;
  45906. }
  45907. tabs->clearTabs();
  45908. for (int i = contentComponents.size(); --i >= 0;)
  45909. {
  45910. Component* const c = contentComponents.getUnchecked(i);
  45911. // be careful not to delete these components until they've been removed from the tab component
  45912. jassert (c == 0 || c->isValidComponent());
  45913. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  45914. delete c;
  45915. }
  45916. contentComponents.clear();
  45917. }
  45918. void TabbedComponent::addTab (const String& tabName,
  45919. const Colour& tabBackgroundColour,
  45920. Component* const contentComponent,
  45921. const bool deleteComponentWhenNotNeeded,
  45922. const int insertIndex)
  45923. {
  45924. contentComponents.insert (insertIndex, contentComponent);
  45925. if (contentComponent != 0)
  45926. contentComponent->setComponentProperty (T("deleteByTabComp_"), deleteComponentWhenNotNeeded);
  45927. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  45928. }
  45929. void TabbedComponent::setTabName (const int tabIndex,
  45930. const String& newName)
  45931. {
  45932. tabs->setTabName (tabIndex, newName);
  45933. }
  45934. void TabbedComponent::removeTab (const int tabIndex)
  45935. {
  45936. Component* const c = contentComponents [tabIndex];
  45937. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  45938. {
  45939. if (c == panelComponent)
  45940. panelComponent = 0;
  45941. delete c;
  45942. }
  45943. contentComponents.remove (tabIndex);
  45944. tabs->removeTab (tabIndex);
  45945. }
  45946. int TabbedComponent::getNumTabs() const
  45947. {
  45948. return tabs->getNumTabs();
  45949. }
  45950. const StringArray TabbedComponent::getTabNames() const
  45951. {
  45952. return tabs->getTabNames();
  45953. }
  45954. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  45955. {
  45956. return contentComponents [tabIndex];
  45957. }
  45958. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  45959. {
  45960. return tabs->getTabBackgroundColour (tabIndex);
  45961. }
  45962. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  45963. {
  45964. tabs->setTabBackgroundColour (tabIndex, newColour);
  45965. if (getCurrentTabIndex() == tabIndex)
  45966. repaint();
  45967. }
  45968. void TabbedComponent::setCurrentTabIndex (const int newTabIndex)
  45969. {
  45970. tabs->setCurrentTabIndex (newTabIndex);
  45971. }
  45972. int TabbedComponent::getCurrentTabIndex() const
  45973. {
  45974. return tabs->getCurrentTabIndex();
  45975. }
  45976. const String& TabbedComponent::getCurrentTabName() const
  45977. {
  45978. return tabs->getCurrentTabName();
  45979. }
  45980. void TabbedComponent::setOutline (const Colour& colour, int thickness)
  45981. {
  45982. outlineColour = colour;
  45983. outlineThickness = thickness;
  45984. repaint();
  45985. }
  45986. void TabbedComponent::setIndent (const int indentThickness)
  45987. {
  45988. edgeIndent = indentThickness;
  45989. }
  45990. void TabbedComponent::paint (Graphics& g)
  45991. {
  45992. const TabbedButtonBar::Orientation o = getOrientation();
  45993. int x = 0;
  45994. int y = 0;
  45995. int r = getWidth();
  45996. int b = getHeight();
  45997. if (o == TabbedButtonBar::TabsAtTop)
  45998. y += tabDepth;
  45999. else if (o == TabbedButtonBar::TabsAtBottom)
  46000. b -= tabDepth;
  46001. else if (o == TabbedButtonBar::TabsAtLeft)
  46002. x += tabDepth;
  46003. else if (o == TabbedButtonBar::TabsAtRight)
  46004. r -= tabDepth;
  46005. g.reduceClipRegion (x, y, r - x, b - y);
  46006. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  46007. if (outlineThickness > 0)
  46008. {
  46009. if (o == TabbedButtonBar::TabsAtTop)
  46010. --y;
  46011. else if (o == TabbedButtonBar::TabsAtBottom)
  46012. ++b;
  46013. else if (o == TabbedButtonBar::TabsAtLeft)
  46014. --x;
  46015. else if (o == TabbedButtonBar::TabsAtRight)
  46016. ++r;
  46017. g.setColour (outlineColour);
  46018. g.drawRect (x, y, r - x, b - y, outlineThickness);
  46019. }
  46020. }
  46021. void TabbedComponent::resized()
  46022. {
  46023. const TabbedButtonBar::Orientation o = getOrientation();
  46024. const int indent = edgeIndent + outlineThickness;
  46025. BorderSize indents (indent);
  46026. if (o == TabbedButtonBar::TabsAtTop)
  46027. {
  46028. tabs->setBounds (0, 0, getWidth(), tabDepth);
  46029. indents.setTop (tabDepth + edgeIndent);
  46030. }
  46031. else if (o == TabbedButtonBar::TabsAtBottom)
  46032. {
  46033. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  46034. indents.setBottom (tabDepth + edgeIndent);
  46035. }
  46036. else if (o == TabbedButtonBar::TabsAtLeft)
  46037. {
  46038. tabs->setBounds (0, 0, tabDepth, getHeight());
  46039. indents.setLeft (tabDepth + edgeIndent);
  46040. }
  46041. else if (o == TabbedButtonBar::TabsAtRight)
  46042. {
  46043. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  46044. indents.setRight (tabDepth + edgeIndent);
  46045. }
  46046. const Rectangle bounds (indents.subtractedFrom (Rectangle (0, 0, getWidth(), getHeight())));
  46047. for (int i = contentComponents.size(); --i >= 0;)
  46048. if (contentComponents.getUnchecked (i) != 0)
  46049. contentComponents.getUnchecked (i)->setBounds (bounds);
  46050. }
  46051. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  46052. const String& newTabName)
  46053. {
  46054. if (panelComponent != 0)
  46055. {
  46056. panelComponent->setVisible (false);
  46057. removeChildComponent (panelComponent);
  46058. panelComponent = 0;
  46059. }
  46060. if (getCurrentTabIndex() >= 0)
  46061. {
  46062. panelComponent = contentComponents [getCurrentTabIndex()];
  46063. if (panelComponent != 0)
  46064. {
  46065. // do these ops as two stages instead of addAndMakeVisible() so that the
  46066. // component has always got a parent when it gets the visibilityChanged() callback
  46067. addChildComponent (panelComponent);
  46068. panelComponent->setVisible (true);
  46069. panelComponent->toFront (true);
  46070. }
  46071. repaint();
  46072. }
  46073. resized();
  46074. currentTabChanged (newCurrentTabIndex, newTabName);
  46075. }
  46076. void TabbedComponent::currentTabChanged (const int, const String&)
  46077. {
  46078. }
  46079. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  46080. {
  46081. }
  46082. END_JUCE_NAMESPACE
  46083. /********* End of inlined file: juce_TabbedComponent.cpp *********/
  46084. /********* Start of inlined file: juce_Viewport.cpp *********/
  46085. BEGIN_JUCE_NAMESPACE
  46086. Viewport::Viewport (const String& componentName)
  46087. : Component (componentName),
  46088. contentComp (0),
  46089. lastVX (0),
  46090. lastVY (0),
  46091. lastVW (0),
  46092. lastVH (0),
  46093. scrollBarThickness (0),
  46094. singleStepX (16),
  46095. singleStepY (16),
  46096. showHScrollbar (true),
  46097. showVScrollbar (true)
  46098. {
  46099. // content holder is used to clip the contents so they don't overlap the scrollbars
  46100. addAndMakeVisible (contentHolder = new Component());
  46101. contentHolder->setInterceptsMouseClicks (false, true);
  46102. verticalScrollBar = new ScrollBar (true);
  46103. horizontalScrollBar = new ScrollBar (false);
  46104. addChildComponent (verticalScrollBar);
  46105. addChildComponent (horizontalScrollBar);
  46106. verticalScrollBar->addListener (this);
  46107. horizontalScrollBar->addListener (this);
  46108. setInterceptsMouseClicks (false, true);
  46109. setWantsKeyboardFocus (true);
  46110. }
  46111. Viewport::~Viewport()
  46112. {
  46113. contentHolder->deleteAllChildren();
  46114. deleteAllChildren();
  46115. }
  46116. void Viewport::visibleAreaChanged (int, int, int, int)
  46117. {
  46118. }
  46119. void Viewport::setViewedComponent (Component* const newViewedComponent)
  46120. {
  46121. if (contentComp != newViewedComponent)
  46122. {
  46123. if (contentComp->isValidComponent())
  46124. {
  46125. Component* const oldComp = contentComp;
  46126. contentComp = 0;
  46127. delete oldComp;
  46128. }
  46129. contentComp = newViewedComponent;
  46130. if (contentComp != 0)
  46131. {
  46132. contentComp->setTopLeftPosition (0, 0);
  46133. contentHolder->addAndMakeVisible (contentComp);
  46134. contentComp->addComponentListener (this);
  46135. }
  46136. updateVisibleRegion();
  46137. }
  46138. }
  46139. int Viewport::getMaximumVisibleWidth() const throw()
  46140. {
  46141. return jmax (0, getWidth() - (verticalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  46142. }
  46143. int Viewport::getMaximumVisibleHeight() const throw()
  46144. {
  46145. return jmax (0, getHeight() - (horizontalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  46146. }
  46147. void Viewport::setViewPosition (const int xPixelsOffset,
  46148. const int yPixelsOffset)
  46149. {
  46150. if (contentComp != 0)
  46151. contentComp->setTopLeftPosition (-xPixelsOffset,
  46152. -yPixelsOffset);
  46153. }
  46154. void Viewport::setViewPositionProportionately (const double x,
  46155. const double y)
  46156. {
  46157. if (contentComp != 0)
  46158. setViewPosition (jmax (0, roundDoubleToInt (x * (contentComp->getWidth() - getWidth()))),
  46159. jmax (0, roundDoubleToInt (y * (contentComp->getHeight() - getHeight()))));
  46160. }
  46161. void Viewport::componentMovedOrResized (Component&, bool, bool)
  46162. {
  46163. updateVisibleRegion();
  46164. }
  46165. void Viewport::resized()
  46166. {
  46167. updateVisibleRegion();
  46168. }
  46169. void Viewport::updateVisibleRegion()
  46170. {
  46171. if (contentComp != 0)
  46172. {
  46173. const int newVX = -contentComp->getX();
  46174. const int newVY = -contentComp->getY();
  46175. if (newVX == 0 && newVY == 0
  46176. && contentComp->getWidth() <= getWidth()
  46177. && contentComp->getHeight() <= getHeight())
  46178. {
  46179. horizontalScrollBar->setVisible (false);
  46180. verticalScrollBar->setVisible (false);
  46181. }
  46182. if ((contentComp->getWidth() > 0) && showHScrollbar
  46183. && getHeight() > getScrollBarThickness())
  46184. {
  46185. horizontalScrollBar->setRangeLimits (0.0, contentComp->getWidth());
  46186. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  46187. horizontalScrollBar->setSingleStepSize (singleStepX);
  46188. }
  46189. else
  46190. {
  46191. horizontalScrollBar->setVisible (false);
  46192. }
  46193. if ((contentComp->getHeight() > 0) && showVScrollbar
  46194. && getWidth() > getScrollBarThickness())
  46195. {
  46196. verticalScrollBar->setRangeLimits (0.0, contentComp->getHeight());
  46197. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  46198. verticalScrollBar->setSingleStepSize (singleStepY);
  46199. }
  46200. else
  46201. {
  46202. verticalScrollBar->setVisible (false);
  46203. }
  46204. if (verticalScrollBar->isVisible())
  46205. {
  46206. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  46207. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  46208. verticalScrollBar
  46209. ->setBounds (getMaximumVisibleWidth(), 0,
  46210. getScrollBarThickness(), getMaximumVisibleHeight());
  46211. }
  46212. if (horizontalScrollBar->isVisible())
  46213. {
  46214. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  46215. horizontalScrollBar
  46216. ->setBounds (0, getMaximumVisibleHeight(),
  46217. getMaximumVisibleWidth(), getScrollBarThickness());
  46218. }
  46219. contentHolder->setSize (getMaximumVisibleWidth(),
  46220. getMaximumVisibleHeight());
  46221. const int newVW = jmin (contentComp->getRight(), getMaximumVisibleWidth());
  46222. const int newVH = jmin (contentComp->getBottom(), getMaximumVisibleHeight());
  46223. if (newVX != lastVX
  46224. || newVY != lastVY
  46225. || newVW != lastVW
  46226. || newVH != lastVH)
  46227. {
  46228. lastVX = newVX;
  46229. lastVY = newVY;
  46230. lastVW = newVW;
  46231. lastVH = newVH;
  46232. visibleAreaChanged (newVX, newVY, newVW, newVH);
  46233. }
  46234. horizontalScrollBar->handleUpdateNowIfNeeded();
  46235. verticalScrollBar->handleUpdateNowIfNeeded();
  46236. }
  46237. else
  46238. {
  46239. horizontalScrollBar->setVisible (false);
  46240. verticalScrollBar->setVisible (false);
  46241. }
  46242. }
  46243. void Viewport::setSingleStepSizes (const int stepX,
  46244. const int stepY)
  46245. {
  46246. singleStepX = stepX;
  46247. singleStepY = stepY;
  46248. updateVisibleRegion();
  46249. }
  46250. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  46251. const bool showHorizontalScrollbarIfNeeded)
  46252. {
  46253. showVScrollbar = showVerticalScrollbarIfNeeded;
  46254. showHScrollbar = showHorizontalScrollbarIfNeeded;
  46255. updateVisibleRegion();
  46256. }
  46257. void Viewport::setScrollBarThickness (const int thickness)
  46258. {
  46259. scrollBarThickness = thickness;
  46260. updateVisibleRegion();
  46261. }
  46262. int Viewport::getScrollBarThickness() const throw()
  46263. {
  46264. return (scrollBarThickness > 0) ? scrollBarThickness
  46265. : getLookAndFeel().getDefaultScrollbarWidth();
  46266. }
  46267. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  46268. {
  46269. verticalScrollBar->setButtonVisibility (buttonsVisible);
  46270. horizontalScrollBar->setButtonVisibility (buttonsVisible);
  46271. }
  46272. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart)
  46273. {
  46274. if (scrollBarThatHasMoved == horizontalScrollBar)
  46275. {
  46276. setViewPosition (roundDoubleToInt (newRangeStart), getViewPositionY());
  46277. }
  46278. else if (scrollBarThatHasMoved == verticalScrollBar)
  46279. {
  46280. setViewPosition (getViewPositionX(), roundDoubleToInt (newRangeStart));
  46281. }
  46282. }
  46283. void Viewport::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  46284. {
  46285. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  46286. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  46287. }
  46288. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  46289. {
  46290. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  46291. {
  46292. const bool hasVertBar = verticalScrollBar->isVisible();
  46293. const bool hasHorzBar = horizontalScrollBar->isVisible();
  46294. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  46295. {
  46296. horizontalScrollBar->mouseWheelMove (e.getEventRelativeTo (horizontalScrollBar),
  46297. wheelIncrementX, wheelIncrementY);
  46298. return true;
  46299. }
  46300. else if (hasVertBar && wheelIncrementY != 0)
  46301. {
  46302. verticalScrollBar->mouseWheelMove (e.getEventRelativeTo (verticalScrollBar),
  46303. wheelIncrementX, wheelIncrementY);
  46304. return true;
  46305. }
  46306. }
  46307. return false;
  46308. }
  46309. bool Viewport::keyPressed (const KeyPress& key)
  46310. {
  46311. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  46312. || key.isKeyCode (KeyPress::downKey)
  46313. || key.isKeyCode (KeyPress::pageUpKey)
  46314. || key.isKeyCode (KeyPress::pageDownKey)
  46315. || key.isKeyCode (KeyPress::homeKey)
  46316. || key.isKeyCode (KeyPress::endKey);
  46317. if (verticalScrollBar->isVisible() && isUpDownKey)
  46318. return verticalScrollBar->keyPressed (key);
  46319. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  46320. || key.isKeyCode (KeyPress::rightKey);
  46321. if (horizontalScrollBar->isVisible() && (isUpDownKey || isLeftRightKey))
  46322. return horizontalScrollBar->keyPressed (key);
  46323. return false;
  46324. }
  46325. END_JUCE_NAMESPACE
  46326. /********* End of inlined file: juce_Viewport.cpp *********/
  46327. /********* Start of inlined file: juce_LookAndFeel.cpp *********/
  46328. BEGIN_JUCE_NAMESPACE
  46329. static const Colour createBaseColour (const Colour& buttonColour,
  46330. const bool hasKeyboardFocus,
  46331. const bool isMouseOverButton,
  46332. const bool isButtonDown) throw()
  46333. {
  46334. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  46335. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  46336. if (isButtonDown)
  46337. return baseColour.contrasting (0.2f);
  46338. else if (isMouseOverButton)
  46339. return baseColour.contrasting (0.1f);
  46340. return baseColour;
  46341. }
  46342. LookAndFeel::LookAndFeel()
  46343. {
  46344. /* if this fails it means you're trying to create a LookAndFeel object before
  46345. the static Colours have been initialised. That ain't gonna work. It probably
  46346. means that you're using a static LookAndFeel object and that your compiler has
  46347. decided to intialise it before the Colours class.
  46348. */
  46349. jassert (Colours::white == Colour (0xffffffff));
  46350. // set up the standard set of colours..
  46351. #define textButtonColour 0xffbbbbff
  46352. #define textHighlightColour 0x401111ee
  46353. #define standardOutlineColour 0xb2808080
  46354. static const int standardColours[] =
  46355. {
  46356. TextButton::buttonColourId, textButtonColour,
  46357. TextButton::buttonOnColourId, 0xff4444ff,
  46358. TextButton::textColourId, 0xff000000,
  46359. ComboBox::buttonColourId, 0xffbbbbff,
  46360. ComboBox::outlineColourId, standardOutlineColour,
  46361. ToggleButton::textColourId, 0xff000000,
  46362. TextEditor::backgroundColourId, 0xffffffff,
  46363. TextEditor::textColourId, 0xff000000,
  46364. TextEditor::highlightColourId, textHighlightColour,
  46365. TextEditor::highlightedTextColourId, 0xff000000,
  46366. TextEditor::caretColourId, 0xff000000,
  46367. TextEditor::outlineColourId, 0x00000000,
  46368. TextEditor::focusedOutlineColourId, textButtonColour,
  46369. TextEditor::shadowColourId, 0x38000000,
  46370. Label::backgroundColourId, 0x00000000,
  46371. Label::textColourId, 0xff000000,
  46372. Label::outlineColourId, 0x00000000,
  46373. ScrollBar::backgroundColourId, 0x00000000,
  46374. ScrollBar::thumbColourId, 0xffffffff,
  46375. ScrollBar::trackColourId, 0xffffffff,
  46376. TreeView::linesColourId, 0x4c000000,
  46377. TreeView::backgroundColourId, 0x00000000,
  46378. PopupMenu::backgroundColourId, 0xffffffff,
  46379. PopupMenu::textColourId, 0xff000000,
  46380. PopupMenu::headerTextColourId, 0xff000000,
  46381. PopupMenu::highlightedTextColourId, 0xffffffff,
  46382. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  46383. ComboBox::textColourId, 0xff000000,
  46384. ComboBox::backgroundColourId, 0xffffffff,
  46385. ComboBox::arrowColourId, 0x99000000,
  46386. ListBox::backgroundColourId, 0xffffffff,
  46387. ListBox::outlineColourId, standardOutlineColour,
  46388. ListBox::textColourId, 0xff000000,
  46389. Slider::backgroundColourId, 0x00000000,
  46390. Slider::thumbColourId, textButtonColour,
  46391. Slider::trackColourId, 0x7fffffff,
  46392. Slider::rotarySliderFillColourId, 0x7f0000ff,
  46393. Slider::rotarySliderOutlineColourId, 0x66000000,
  46394. Slider::textBoxTextColourId, 0xff000000,
  46395. Slider::textBoxBackgroundColourId, 0xffffffff,
  46396. Slider::textBoxHighlightColourId, textHighlightColour,
  46397. Slider::textBoxOutlineColourId, standardOutlineColour,
  46398. AlertWindow::backgroundColourId, 0xffededed,
  46399. AlertWindow::textColourId, 0xff000000,
  46400. AlertWindow::outlineColourId, 0xff666666,
  46401. ProgressBar::backgroundColourId, 0xffeeeeee,
  46402. ProgressBar::foregroundColourId, 0xffaaaaee,
  46403. TooltipWindow::backgroundColourId, 0xffeeeebb,
  46404. TooltipWindow::textColourId, 0xff000000,
  46405. TooltipWindow::outlineColourId, 0x4c000000,
  46406. Toolbar::backgroundColourId, 0xfff6f8f9,
  46407. Toolbar::separatorColourId, 0x4c000000,
  46408. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  46409. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  46410. Toolbar::labelTextColourId, 0xff000000,
  46411. Toolbar::editingModeOutlineColourId, 0xffff0000,
  46412. HyperlinkButton::textColourId, 0xcc1111ee,
  46413. GroupComponent::outlineColourId, 0x66000000,
  46414. GroupComponent::textColourId, 0xff000000,
  46415. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  46416. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  46417. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  46418. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  46419. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  46420. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  46421. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  46422. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  46423. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  46424. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  46425. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  46426. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  46427. ColourSelector::backgroundColourId, 0xffe5e5e5,
  46428. ColourSelector::labelTextColourId, 0xff000000,
  46429. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  46430. };
  46431. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  46432. setColour (standardColours [i], Colour (standardColours [i + 1]));
  46433. }
  46434. LookAndFeel::~LookAndFeel()
  46435. {
  46436. }
  46437. const Colour LookAndFeel::findColour (const int colourId) const throw()
  46438. {
  46439. const int index = colourIds.indexOf (colourId);
  46440. if (index >= 0)
  46441. return colours [index];
  46442. jassertfalse
  46443. return Colours::black;
  46444. }
  46445. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  46446. {
  46447. const int index = colourIds.indexOf (colourId);
  46448. if (index >= 0)
  46449. colours.set (index, colour);
  46450. colourIds.add (colourId);
  46451. colours.add (colour);
  46452. }
  46453. static LookAndFeel* defaultLF = 0;
  46454. static LookAndFeel* currentDefaultLF = 0;
  46455. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  46456. {
  46457. // if this happens, your app hasn't initialised itself properly.. if you're
  46458. // trying to hack your own main() function, have a look at
  46459. // JUCEApplication::initialiseForGUI()
  46460. jassert (currentDefaultLF != 0);
  46461. return *currentDefaultLF;
  46462. }
  46463. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  46464. {
  46465. if (newDefaultLookAndFeel == 0)
  46466. {
  46467. if (defaultLF == 0)
  46468. defaultLF = new LookAndFeel();
  46469. newDefaultLookAndFeel = defaultLF;
  46470. }
  46471. currentDefaultLF = newDefaultLookAndFeel;
  46472. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  46473. {
  46474. Component* const c = Desktop::getInstance().getComponent (i);
  46475. if (c != 0)
  46476. c->sendLookAndFeelChange();
  46477. }
  46478. }
  46479. void LookAndFeel::clearDefaultLookAndFeel() throw()
  46480. {
  46481. if (currentDefaultLF == defaultLF)
  46482. currentDefaultLF = 0;
  46483. deleteAndZero (defaultLF);
  46484. }
  46485. void LookAndFeel::drawButtonBackground (Graphics& g,
  46486. Button& button,
  46487. const Colour& backgroundColour,
  46488. bool isMouseOverButton,
  46489. bool isButtonDown)
  46490. {
  46491. const int width = button.getWidth();
  46492. const int height = button.getHeight();
  46493. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  46494. const float halfThickness = outlineThickness * 0.5f;
  46495. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  46496. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  46497. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  46498. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  46499. const Colour baseColour (createBaseColour (backgroundColour,
  46500. button.hasKeyboardFocus (true),
  46501. isMouseOverButton, isButtonDown)
  46502. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  46503. drawGlassLozenge (g,
  46504. indentL,
  46505. indentT,
  46506. width - indentL - indentR,
  46507. height - indentT - indentB,
  46508. baseColour, outlineThickness, -1.0f,
  46509. button.isConnectedOnLeft(),
  46510. button.isConnectedOnRight(),
  46511. button.isConnectedOnTop(),
  46512. button.isConnectedOnBottom());
  46513. }
  46514. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  46515. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  46516. {
  46517. g.setFont (button.getFont());
  46518. g.setColour (button.findColour (TextButton::textColourId)
  46519. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  46520. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  46521. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  46522. const int fontHeight = roundFloatToInt (g.getCurrentFont().getHeight() * 0.6f);
  46523. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  46524. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  46525. g.drawFittedText (button.getButtonText(),
  46526. leftIndent,
  46527. yIndent,
  46528. button.getWidth() - leftIndent - rightIndent,
  46529. button.getHeight() - yIndent * 2,
  46530. Justification::centred, 2);
  46531. }
  46532. void LookAndFeel::drawTickBox (Graphics& g,
  46533. Component& component,
  46534. int x, int y, int w, int h,
  46535. const bool ticked,
  46536. const bool isEnabled,
  46537. const bool isMouseOverButton,
  46538. const bool isButtonDown)
  46539. {
  46540. const float boxSize = w * 0.7f;
  46541. drawGlassSphere (g, (float) x, y + (h - boxSize) * 0.5f, boxSize,
  46542. createBaseColour (component.findColour (TextButton::buttonColourId)
  46543. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  46544. true,
  46545. isMouseOverButton,
  46546. isButtonDown),
  46547. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  46548. if (ticked)
  46549. {
  46550. Path tick;
  46551. tick.startNewSubPath (1.5f, 3.0f);
  46552. tick.lineTo (3.0f, 6.0f);
  46553. tick.lineTo (6.0f, 0.0f);
  46554. g.setColour (isEnabled ? Colours::black : Colours::grey);
  46555. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  46556. .translated ((float) x, (float) y));
  46557. g.strokePath (tick, PathStrokeType (2.5f), trans);
  46558. }
  46559. }
  46560. void LookAndFeel::drawToggleButton (Graphics& g,
  46561. ToggleButton& button,
  46562. bool isMouseOverButton,
  46563. bool isButtonDown)
  46564. {
  46565. if (button.hasKeyboardFocus (true))
  46566. {
  46567. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  46568. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  46569. }
  46570. const int tickWidth = jmin (20, button.getHeight() - 4);
  46571. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  46572. tickWidth, tickWidth,
  46573. button.getToggleState(),
  46574. button.isEnabled(),
  46575. isMouseOverButton,
  46576. isButtonDown);
  46577. g.setColour (button.findColour (ToggleButton::textColourId));
  46578. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  46579. if (! button.isEnabled())
  46580. g.setOpacity (0.5f);
  46581. const int textX = tickWidth + 5;
  46582. g.drawFittedText (button.getButtonText(),
  46583. textX, 4,
  46584. button.getWidth() - textX - 2, button.getHeight() - 8,
  46585. Justification::centredLeft, 10);
  46586. }
  46587. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  46588. {
  46589. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  46590. const int tickWidth = jmin (24, button.getHeight());
  46591. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  46592. button.getHeight());
  46593. }
  46594. void LookAndFeel::drawAlertBox (Graphics& g,
  46595. AlertWindow& alert,
  46596. const Rectangle& textArea,
  46597. TextLayout& textLayout)
  46598. {
  46599. const int iconWidth = 80;
  46600. const Colour background (alert.findColour (AlertWindow::backgroundColourId));
  46601. g.fillAll (background);
  46602. int iconSpaceUsed = 0;
  46603. Justification alignment (Justification::horizontallyCentred);
  46604. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  46605. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  46606. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  46607. const Rectangle iconRect (iconSize / -10,
  46608. iconSize / -10,
  46609. iconSize,
  46610. iconSize);
  46611. if (alert.getAlertType() == AlertWindow::QuestionIcon
  46612. || alert.getAlertType() == AlertWindow::InfoIcon)
  46613. {
  46614. if (alert.getAlertType() == AlertWindow::InfoIcon)
  46615. g.setColour (background.overlaidWith (Colour (0x280000ff)));
  46616. else
  46617. g.setColour (background.overlaidWith (Colours::gold.darker().withAlpha (0.25f)));
  46618. g.fillEllipse ((float) iconRect.getX(),
  46619. (float) iconRect.getY(),
  46620. (float) iconRect.getWidth(),
  46621. (float) iconRect.getHeight());
  46622. g.setColour (background);
  46623. g.setFont (iconRect.getHeight() * 0.9f, Font::bold);
  46624. g.drawText ((alert.getAlertType() == AlertWindow::InfoIcon) ? "i"
  46625. : "?",
  46626. iconRect.getX(),
  46627. iconRect.getY(),
  46628. iconRect.getWidth(),
  46629. iconRect.getHeight(),
  46630. Justification::centred, false);
  46631. iconSpaceUsed = iconWidth;
  46632. alignment = Justification::left;
  46633. }
  46634. else if (alert.getAlertType() == AlertWindow::WarningIcon)
  46635. {
  46636. Path p;
  46637. p.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f,
  46638. (float) iconRect.getY(),
  46639. (float) iconRect.getRight(),
  46640. (float) iconRect.getBottom(),
  46641. (float) iconRect.getX(),
  46642. (float) iconRect.getBottom());
  46643. g.setColour (background.overlaidWith (Colour (0x33ff0000)));
  46644. g.fillPath (p.createPathWithRoundedCorners (5.0f));
  46645. g.setColour (background);
  46646. g.setFont (iconRect.getHeight() * 0.9f, Font::bold);
  46647. g.drawText (T("!"),
  46648. iconRect.getX(),
  46649. iconRect.getY(),
  46650. iconRect.getWidth(),
  46651. iconRect.getHeight() + iconRect.getHeight() / 8,
  46652. Justification::centred, false);
  46653. iconSpaceUsed = iconWidth;
  46654. alignment = Justification::left;
  46655. }
  46656. g.setColour (alert.findColour (AlertWindow::textColourId));
  46657. textLayout.drawWithin (g,
  46658. textArea.getX() + iconSpaceUsed,
  46659. textArea.getY(),
  46660. textArea.getWidth() - iconSpaceUsed,
  46661. textArea.getHeight(),
  46662. alignment.getFlags() | Justification::top);
  46663. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  46664. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  46665. }
  46666. int LookAndFeel::getAlertBoxWindowFlags()
  46667. {
  46668. return ComponentPeer::windowAppearsOnTaskbar
  46669. | ComponentPeer::windowHasDropShadow;
  46670. }
  46671. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  46672. int width, int height,
  46673. double progress, const String& textToShow)
  46674. {
  46675. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  46676. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  46677. g.fillAll (background);
  46678. if (progress >= 0.0f && progress < 1.0f)
  46679. {
  46680. drawGlassLozenge (g, 1.0f, 1.0f,
  46681. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  46682. (float) (height - 2),
  46683. foreground,
  46684. 0.5f, 0.0f,
  46685. true, true, true, true);
  46686. }
  46687. else
  46688. {
  46689. // spinning bar..
  46690. g.setColour (foreground);
  46691. const int stripeWidth = height * 2;
  46692. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  46693. Path p;
  46694. for (float x = (float) (-stripeWidth - position); x < width + stripeWidth; x += stripeWidth)
  46695. p.addQuadrilateral (x, 0.0f,
  46696. x + stripeWidth * 0.5f, 0.0f,
  46697. x, (float) height,
  46698. x - stripeWidth * 0.5f, (float) height);
  46699. Image im (Image::ARGB, width, height, true);
  46700. {
  46701. Graphics g (im);
  46702. drawGlassLozenge (g, 1.0f, 1.0f,
  46703. (float) (width - 2),
  46704. (float) (height - 2),
  46705. foreground,
  46706. 0.5f, 0.0f,
  46707. true, true, true, true);
  46708. }
  46709. ImageBrush ib (&im, 0, 0, 0.85f);
  46710. g.setBrush (&ib);
  46711. g.fillPath (p);
  46712. }
  46713. if (textToShow.isNotEmpty())
  46714. {
  46715. g.setColour (Colour::contrasting (background, foreground));
  46716. g.setFont (height * 0.6f);
  46717. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  46718. }
  46719. }
  46720. void LookAndFeel::drawScrollbarButton (Graphics& g,
  46721. ScrollBar& scrollbar,
  46722. int width, int height,
  46723. int buttonDirection,
  46724. bool /*isScrollbarVertical*/,
  46725. bool /*isMouseOverButton*/,
  46726. bool isButtonDown)
  46727. {
  46728. Path p;
  46729. if (buttonDirection == 0)
  46730. p.addTriangle (width * 0.5f, height * 0.2f,
  46731. width * 0.1f, height * 0.7f,
  46732. width * 0.9f, height * 0.7f);
  46733. else if (buttonDirection == 1)
  46734. p.addTriangle (width * 0.8f, height * 0.5f,
  46735. width * 0.3f, height * 0.1f,
  46736. width * 0.3f, height * 0.9f);
  46737. else if (buttonDirection == 2)
  46738. p.addTriangle (width * 0.5f, height * 0.8f,
  46739. width * 0.1f, height * 0.3f,
  46740. width * 0.9f, height * 0.3f);
  46741. else if (buttonDirection == 3)
  46742. p.addTriangle (width * 0.2f, height * 0.5f,
  46743. width * 0.7f, height * 0.1f,
  46744. width * 0.7f, height * 0.9f);
  46745. if (isButtonDown)
  46746. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  46747. else
  46748. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  46749. g.fillPath (p);
  46750. g.setColour (Colour (0x80000000));
  46751. g.strokePath (p, PathStrokeType (0.5f));
  46752. }
  46753. void LookAndFeel::drawScrollbar (Graphics& g,
  46754. ScrollBar& scrollbar,
  46755. int x, int y,
  46756. int width, int height,
  46757. bool isScrollbarVertical,
  46758. int thumbStartPosition,
  46759. int thumbSize,
  46760. bool /*isMouseOver*/,
  46761. bool /*isMouseDown*/)
  46762. {
  46763. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  46764. Path slotPath, thumbPath;
  46765. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  46766. const float slotIndentx2 = slotIndent * 2.0f;
  46767. const float thumbIndent = slotIndent + 1.0f;
  46768. const float thumbIndentx2 = thumbIndent * 2.0f;
  46769. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  46770. if (isScrollbarVertical)
  46771. {
  46772. slotPath.addRoundedRectangle (x + slotIndent,
  46773. y + slotIndent,
  46774. width - slotIndentx2,
  46775. height - slotIndentx2,
  46776. (width - slotIndentx2) * 0.5f);
  46777. if (thumbSize > 0)
  46778. thumbPath.addRoundedRectangle (x + thumbIndent,
  46779. thumbStartPosition + thumbIndent,
  46780. width - thumbIndentx2,
  46781. thumbSize - thumbIndentx2,
  46782. (width - thumbIndentx2) * 0.5f);
  46783. gx1 = (float) x;
  46784. gx2 = x + width * 0.7f;
  46785. }
  46786. else
  46787. {
  46788. slotPath.addRoundedRectangle (x + slotIndent,
  46789. y + slotIndent,
  46790. width - slotIndentx2,
  46791. height - slotIndentx2,
  46792. (height - slotIndentx2) * 0.5f);
  46793. if (thumbSize > 0)
  46794. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  46795. y + thumbIndent,
  46796. thumbSize - thumbIndentx2,
  46797. height - thumbIndentx2,
  46798. (height - thumbIndentx2) * 0.5f);
  46799. gy1 = (float) y;
  46800. gy2 = y + height * 0.7f;
  46801. }
  46802. const Colour thumbColour (scrollbar.findColour (ScrollBar::trackColourId));
  46803. GradientBrush gb (thumbColour.overlaidWith (Colour (0x44000000)),
  46804. gx1, gy1,
  46805. thumbColour.overlaidWith (Colour (0x19000000)),
  46806. gx2, gy2, false);
  46807. g.setBrush (&gb);
  46808. g.fillPath (slotPath);
  46809. if (isScrollbarVertical)
  46810. {
  46811. gx1 = x + width * 0.6f;
  46812. gx2 = (float) x + width;
  46813. }
  46814. else
  46815. {
  46816. gy1 = y + height * 0.6f;
  46817. gy2 = (float) y + height;
  46818. }
  46819. GradientBrush gb2 (Colours::transparentBlack,
  46820. gx1, gy1,
  46821. Colour (0x19000000),
  46822. gx2, gy2, false);
  46823. g.setBrush (&gb2);
  46824. g.fillPath (slotPath);
  46825. g.setColour (thumbColour);
  46826. g.fillPath (thumbPath);
  46827. GradientBrush gb3 (Colour (0x10000000),
  46828. gx1, gy1,
  46829. Colours::transparentBlack,
  46830. gx2, gy2, false);
  46831. g.saveState();
  46832. g.setBrush (&gb3);
  46833. if (isScrollbarVertical)
  46834. g.reduceClipRegion (x + width / 2, y, width, height);
  46835. else
  46836. g.reduceClipRegion (x, y + height / 2, width, height);
  46837. g.fillPath (thumbPath);
  46838. g.restoreState();
  46839. g.setColour (Colour (0x4c000000));
  46840. g.strokePath (thumbPath, PathStrokeType (0.4f));
  46841. }
  46842. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  46843. {
  46844. return 0;
  46845. }
  46846. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  46847. {
  46848. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  46849. }
  46850. int LookAndFeel::getDefaultScrollbarWidth()
  46851. {
  46852. return 18;
  46853. }
  46854. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  46855. {
  46856. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  46857. : scrollbar.getHeight());
  46858. }
  46859. const Path LookAndFeel::getTickShape (const float height)
  46860. {
  46861. static const unsigned char tickShapeData[] =
  46862. {
  46863. 109,0,224,168,68,0,0,119,67,108,0,224,172,68,0,128,146,67,113,0,192,148,68,0,0,219,67,0,96,110,68,0,224,56,68,113,0,64,51,68,0,32,130,68,0,64,20,68,0,224,
  46864. 162,68,108,0,128,3,68,0,128,168,68,113,0,128,221,67,0,192,175,68,0,0,207,67,0,32,179,68,113,0,0,201,67,0,224,173,68,0,0,181,67,0,224,161,68,108,0,128,168,67,
  46865. 0,128,154,68,113,0,128,141,67,0,192,138,68,0,128,108,67,0,64,131,68,113,0,0,62,67,0,128,119,68,0,0,5,67,0,128,114,68,113,0,0,102,67,0,192,88,68,0,128,155,
  46866. 67,0,192,88,68,113,0,0,190,67,0,192,88,68,0,128,232,67,0,224,131,68,108,0,128,246,67,0,192,139,68,113,0,64,33,68,0,128,87,68,0,0,93,68,0,224,26,68,113,0,
  46867. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  46868. };
  46869. Path p;
  46870. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  46871. p.scaleToFit (0, 0, height * 2.0f, height, true);
  46872. return p;
  46873. }
  46874. const Path LookAndFeel::getCrossShape (const float height)
  46875. {
  46876. static const unsigned char crossShapeData[] =
  46877. {
  46878. 109,0,0,17,68,0,96,145,68,108,0,192,13,68,0,192,147,68,113,0,0,213,67,0,64,174,68,0,0,168,67,0,64,174,68,113,0,0,104,67,0,64,174,68,0,0,5,67,0,64,
  46879. 153,68,113,0,0,18,67,0,64,153,68,0,0,24,67,0,64,153,68,113,0,0,135,67,0,64,153,68,0,128,207,67,0,224,130,68,108,0,0,220,67,0,0,126,68,108,0,0,204,67,
  46880. 0,128,117,68,113,0,0,138,67,0,64,82,68,0,0,138,67,0,192,57,68,113,0,0,138,67,0,192,37,68,0,128,210,67,0,64,10,68,113,0,128,220,67,0,64,45,68,0,0,8,
  46881. 68,0,128,78,68,108,0,192,14,68,0,0,87,68,108,0,64,20,68,0,0,80,68,113,0,192,57,68,0,0,32,68,0,128,88,68,0,0,32,68,113,0,64,112,68,0,0,32,68,0,
  46882. 128,124,68,0,64,68,68,113,0,0,121,68,0,192,67,68,0,128,119,68,0,192,67,68,113,0,192,108,68,0,192,67,68,0,32,89,68,0,96,82,68,113,0,128,69,68,0,0,97,68,
  46883. 0,0,56,68,0,64,115,68,108,0,64,49,68,0,128,124,68,108,0,192,55,68,0,96,129,68,113,0,0,92,68,0,224,146,68,0,192,129,68,0,224,146,68,113,0,64,110,68,0,64,
  46884. 168,68,0,64,87,68,0,64,168,68,113,0,128,66,68,0,64,168,68,0,64,27,68,0,32,150,68,99,101
  46885. };
  46886. Path p;
  46887. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  46888. p.scaleToFit (0, 0, height * 2.0f, height, true);
  46889. return p;
  46890. }
  46891. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus)
  46892. {
  46893. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  46894. x += (w - boxSize) >> 1;
  46895. y += (h - boxSize) >> 1;
  46896. w = boxSize;
  46897. h = boxSize;
  46898. g.setColour (Colour (0xe5ffffff));
  46899. g.fillRect (x, y, w, h);
  46900. g.setColour (Colour (0x80000000));
  46901. g.drawRect (x, y, w, h);
  46902. const float size = boxSize / 2 + 1.0f;
  46903. const float centre = (float) (boxSize / 2);
  46904. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  46905. if (isPlus)
  46906. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  46907. }
  46908. void LookAndFeel::drawBubble (Graphics& g,
  46909. float tipX, float tipY,
  46910. float boxX, float boxY,
  46911. float boxW, float boxH)
  46912. {
  46913. int side = 0;
  46914. if (tipX < boxX)
  46915. side = 1;
  46916. else if (tipX > boxX + boxW)
  46917. side = 3;
  46918. else if (tipY > boxY + boxH)
  46919. side = 2;
  46920. const float indent = 2.0f;
  46921. Path p;
  46922. p.addBubble (boxX + indent,
  46923. boxY + indent,
  46924. boxW - indent * 2.0f,
  46925. boxH - indent * 2.0f,
  46926. 5.0f,
  46927. tipX, tipY,
  46928. side,
  46929. 0.5f,
  46930. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  46931. //xxx need to take comp as param for colour
  46932. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  46933. g.fillPath (p);
  46934. //xxx as above
  46935. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  46936. g.strokePath (p, PathStrokeType (1.33f));
  46937. }
  46938. const Font LookAndFeel::getPopupMenuFont()
  46939. {
  46940. return Font (17.0f);
  46941. }
  46942. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  46943. const bool isSeparator,
  46944. int standardMenuItemHeight,
  46945. int& idealWidth,
  46946. int& idealHeight)
  46947. {
  46948. if (isSeparator)
  46949. {
  46950. idealWidth = 50;
  46951. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  46952. }
  46953. else
  46954. {
  46955. Font font (getPopupMenuFont());
  46956. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  46957. font.setHeight (standardMenuItemHeight / 1.3f);
  46958. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundFloatToInt (font.getHeight() * 1.3f);
  46959. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  46960. }
  46961. }
  46962. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  46963. {
  46964. const Colour background (findColour (PopupMenu::backgroundColourId));
  46965. g.fillAll (background);
  46966. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  46967. for (int i = 0; i < height; i += 3)
  46968. g.fillRect (0, i, width, 1);
  46969. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  46970. g.drawRect (0, 0, width, height);
  46971. }
  46972. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  46973. int width, int height,
  46974. bool isScrollUpArrow)
  46975. {
  46976. const Colour background (findColour (PopupMenu::backgroundColourId));
  46977. GradientBrush gb (background,
  46978. 0.0f, height * 0.5f,
  46979. background.withAlpha (0.0f),
  46980. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  46981. false);
  46982. g.setBrush (&gb);
  46983. g.fillRect (1, 1, width - 2, height - 2);
  46984. const float hw = width * 0.5f;
  46985. const float arrowW = height * 0.3f;
  46986. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  46987. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  46988. Path p;
  46989. p.addTriangle (hw - arrowW, y1,
  46990. hw + arrowW, y1,
  46991. hw, y2);
  46992. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  46993. g.fillPath (p);
  46994. }
  46995. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  46996. int width, int height,
  46997. const bool isSeparator,
  46998. const bool isActive,
  46999. const bool isHighlighted,
  47000. const bool isTicked,
  47001. const bool hasSubMenu,
  47002. const String& text,
  47003. const String& shortcutKeyText,
  47004. Image* image,
  47005. const Colour* const textColourToUse)
  47006. {
  47007. const float halfH = height * 0.5f;
  47008. if (isSeparator)
  47009. {
  47010. const float separatorIndent = 5.5f;
  47011. g.setColour (Colour (0x33000000));
  47012. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  47013. g.setColour (Colour (0x66ffffff));
  47014. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  47015. }
  47016. else
  47017. {
  47018. Colour textColour (findColour (PopupMenu::textColourId));
  47019. if (textColourToUse != 0)
  47020. textColour = *textColourToUse;
  47021. if (isHighlighted)
  47022. {
  47023. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  47024. g.fillRect (1, 1, width - 2, height - 2);
  47025. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  47026. }
  47027. else
  47028. {
  47029. g.setColour (textColour);
  47030. }
  47031. if (! isActive)
  47032. g.setOpacity (0.3f);
  47033. Font font (getPopupMenuFont());
  47034. if (font.getHeight() > height / 1.3f)
  47035. font.setHeight (height / 1.3f);
  47036. g.setFont (font);
  47037. const int leftBorder = (height * 5) / 4;
  47038. const int rightBorder = 4;
  47039. if (image != 0)
  47040. {
  47041. g.drawImageWithin (image,
  47042. 2, 1, leftBorder - 4, height - 2,
  47043. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  47044. }
  47045. else if (isTicked)
  47046. {
  47047. const Path tick (getTickShape (1.0f));
  47048. const float th = font.getAscent();
  47049. const float ty = halfH - th * 0.5f;
  47050. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  47051. th, true));
  47052. }
  47053. g.drawFittedText (text,
  47054. leftBorder, 0,
  47055. width - (leftBorder + rightBorder), height,
  47056. Justification::centredLeft, 1);
  47057. if (shortcutKeyText.isNotEmpty())
  47058. {
  47059. Font f2 (g.getCurrentFont());
  47060. f2.setHeight (f2.getHeight() * 0.75f);
  47061. f2.setHorizontalScale (0.95f);
  47062. g.setFont (f2);
  47063. g.drawText (shortcutKeyText,
  47064. leftBorder,
  47065. 0,
  47066. width - (leftBorder + rightBorder + 4),
  47067. height,
  47068. Justification::centredRight,
  47069. true);
  47070. }
  47071. if (hasSubMenu)
  47072. {
  47073. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  47074. const float x = width - height * 0.6f;
  47075. Path p;
  47076. p.addTriangle (x, halfH - arrowH * 0.5f,
  47077. x, halfH + arrowH * 0.5f,
  47078. x + arrowH * 0.6f, halfH);
  47079. g.fillPath (p);
  47080. }
  47081. }
  47082. }
  47083. int LookAndFeel::getMenuWindowFlags()
  47084. {
  47085. return ComponentPeer::windowHasDropShadow;
  47086. }
  47087. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  47088. bool, MenuBarComponent& menuBar)
  47089. {
  47090. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  47091. if (menuBar.isEnabled())
  47092. {
  47093. drawShinyButtonShape (g,
  47094. -4.0f, 0.0f,
  47095. width + 8.0f, (float) height,
  47096. 0.0f,
  47097. baseColour,
  47098. 0.4f,
  47099. true, true, true, true);
  47100. }
  47101. else
  47102. {
  47103. g.fillAll (baseColour);
  47104. }
  47105. }
  47106. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  47107. {
  47108. return Font (menuBar.getHeight() * 0.7f);
  47109. }
  47110. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  47111. {
  47112. return getMenuBarFont (menuBar, itemIndex, itemText)
  47113. .getStringWidth (itemText) + menuBar.getHeight();
  47114. }
  47115. void LookAndFeel::drawMenuBarItem (Graphics& g,
  47116. int width, int height,
  47117. int itemIndex,
  47118. const String& itemText,
  47119. bool isMouseOverItem,
  47120. bool isMenuOpen,
  47121. bool /*isMouseOverBar*/,
  47122. MenuBarComponent& menuBar)
  47123. {
  47124. if (! menuBar.isEnabled())
  47125. {
  47126. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  47127. .withMultipliedAlpha (0.5f));
  47128. }
  47129. else if (isMenuOpen || isMouseOverItem)
  47130. {
  47131. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  47132. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  47133. }
  47134. else
  47135. {
  47136. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  47137. }
  47138. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  47139. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  47140. }
  47141. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  47142. TextEditor& textEditor)
  47143. {
  47144. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  47145. }
  47146. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  47147. {
  47148. if (textEditor.isEnabled())
  47149. {
  47150. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  47151. {
  47152. const int border = 2;
  47153. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  47154. g.drawRect (0, 0, width, height, border);
  47155. g.setOpacity (1.0f);
  47156. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  47157. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  47158. }
  47159. else
  47160. {
  47161. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  47162. g.drawRect (0, 0, width, height);
  47163. g.setOpacity (1.0f);
  47164. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  47165. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  47166. }
  47167. }
  47168. }
  47169. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  47170. const bool isButtonDown,
  47171. int buttonX, int buttonY,
  47172. int buttonW, int buttonH,
  47173. ComboBox& box)
  47174. {
  47175. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  47176. if (box.isEnabled() && box.hasKeyboardFocus (false))
  47177. {
  47178. g.setColour (box.findColour (TextButton::buttonColourId));
  47179. g.drawRect (0, 0, width, height, 2);
  47180. }
  47181. else
  47182. {
  47183. g.setColour (box.findColour (ComboBox::outlineColourId));
  47184. g.drawRect (0, 0, width, height);
  47185. }
  47186. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  47187. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  47188. box.hasKeyboardFocus (true),
  47189. false, isButtonDown)
  47190. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  47191. drawGlassLozenge (g,
  47192. buttonX + outlineThickness, buttonY + outlineThickness,
  47193. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  47194. baseColour, outlineThickness, -1.0f,
  47195. true, true, true, true);
  47196. if (box.isEnabled())
  47197. {
  47198. const float arrowX = 0.3f;
  47199. const float arrowH = 0.2f;
  47200. Path p;
  47201. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  47202. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  47203. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  47204. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  47205. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  47206. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  47207. g.setColour (box.findColour (ComboBox::arrowColourId));
  47208. g.fillPath (p);
  47209. }
  47210. }
  47211. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  47212. {
  47213. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  47214. }
  47215. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  47216. {
  47217. return new Label (String::empty, String::empty);
  47218. }
  47219. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  47220. {
  47221. label.setBounds (1, 1,
  47222. box.getWidth() + 3 - box.getHeight(),
  47223. box.getHeight() - 2);
  47224. label.setFont (getComboBoxFont (box));
  47225. }
  47226. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  47227. int x, int y,
  47228. int width, int height,
  47229. float /*sliderPos*/,
  47230. float /*minSliderPos*/,
  47231. float /*maxSliderPos*/,
  47232. const Slider::SliderStyle /*style*/,
  47233. Slider& slider)
  47234. {
  47235. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  47236. const Colour trackColour (slider.findColour (Slider::trackColourId));
  47237. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  47238. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  47239. Path indent;
  47240. if (slider.isHorizontal())
  47241. {
  47242. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  47243. const float ih = sliderRadius;
  47244. GradientBrush gb (gradCol1, 0.0f, iy,
  47245. gradCol2, 0.0f, iy + ih, false);
  47246. g.setBrush (&gb);
  47247. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  47248. width + sliderRadius, ih,
  47249. 5.0f);
  47250. g.fillPath (indent);
  47251. }
  47252. else
  47253. {
  47254. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  47255. const float iw = sliderRadius;
  47256. GradientBrush gb (gradCol1, ix, 0.0f,
  47257. gradCol2, ix + iw, 0.0f, false);
  47258. g.setBrush (&gb);
  47259. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  47260. iw, height + sliderRadius,
  47261. 5.0f);
  47262. g.fillPath (indent);
  47263. }
  47264. g.setColour (Colour (0x4c000000));
  47265. g.strokePath (indent, PathStrokeType (0.5f));
  47266. }
  47267. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  47268. int x, int y,
  47269. int width, int height,
  47270. float sliderPos,
  47271. float minSliderPos,
  47272. float maxSliderPos,
  47273. const Slider::SliderStyle style,
  47274. Slider& slider)
  47275. {
  47276. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  47277. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  47278. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  47279. slider.isMouseOverOrDragging() && slider.isEnabled(),
  47280. slider.isMouseButtonDown() && slider.isEnabled()));
  47281. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  47282. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  47283. {
  47284. float kx, ky;
  47285. if (style == Slider::LinearVertical)
  47286. {
  47287. kx = x + width * 0.5f;
  47288. ky = sliderPos;
  47289. }
  47290. else
  47291. {
  47292. kx = sliderPos;
  47293. ky = y + height * 0.5f;
  47294. }
  47295. drawGlassSphere (g,
  47296. kx - sliderRadius,
  47297. ky - sliderRadius,
  47298. sliderRadius * 2.0f,
  47299. knobColour, outlineThickness);
  47300. }
  47301. else
  47302. {
  47303. if (style == Slider::ThreeValueVertical)
  47304. {
  47305. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  47306. sliderPos - sliderRadius,
  47307. sliderRadius * 2.0f,
  47308. knobColour, outlineThickness);
  47309. }
  47310. else if (style == Slider::ThreeValueHorizontal)
  47311. {
  47312. drawGlassSphere (g,sliderPos - sliderRadius,
  47313. y + height * 0.5f - sliderRadius,
  47314. sliderRadius * 2.0f,
  47315. knobColour, outlineThickness);
  47316. }
  47317. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  47318. {
  47319. const float sr = jmin (sliderRadius, width * 0.4f);
  47320. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  47321. minSliderPos - sliderRadius,
  47322. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  47323. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  47324. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  47325. }
  47326. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  47327. {
  47328. const float sr = jmin (sliderRadius, height * 0.4f);
  47329. drawGlassPointer (g, minSliderPos - sr,
  47330. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  47331. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  47332. drawGlassPointer (g, maxSliderPos - sliderRadius,
  47333. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  47334. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  47335. }
  47336. }
  47337. }
  47338. void LookAndFeel::drawLinearSlider (Graphics& g,
  47339. int x, int y,
  47340. int width, int height,
  47341. float sliderPos,
  47342. float minSliderPos,
  47343. float maxSliderPos,
  47344. const Slider::SliderStyle style,
  47345. Slider& slider)
  47346. {
  47347. g.fillAll (slider.findColour (Slider::backgroundColourId));
  47348. if (style == Slider::LinearBar)
  47349. {
  47350. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  47351. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  47352. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  47353. false,
  47354. isMouseOver,
  47355. isMouseOver || slider.isMouseButtonDown()));
  47356. drawShinyButtonShape (g,
  47357. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  47358. baseColour,
  47359. slider.isEnabled() ? 0.9f : 0.3f,
  47360. true, true, true, true);
  47361. }
  47362. else
  47363. {
  47364. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  47365. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  47366. }
  47367. }
  47368. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  47369. {
  47370. return jmin (7,
  47371. slider.getHeight() / 2,
  47372. slider.getWidth() / 2) + 2;
  47373. }
  47374. void LookAndFeel::drawRotarySlider (Graphics& g,
  47375. int x, int y,
  47376. int width, int height,
  47377. float sliderPos,
  47378. const float rotaryStartAngle,
  47379. const float rotaryEndAngle,
  47380. Slider& slider)
  47381. {
  47382. const float radius = jmin (width / 2, height / 2) - 2.0f;
  47383. const float centreX = x + width * 0.5f;
  47384. const float centreY = y + height * 0.5f;
  47385. const float rx = centreX - radius;
  47386. const float ry = centreY - radius;
  47387. const float rw = radius * 2.0f;
  47388. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  47389. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  47390. if (radius > 12.0f)
  47391. {
  47392. if (slider.isEnabled())
  47393. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  47394. else
  47395. g.setColour (Colour (0x80808080));
  47396. const float thickness = 0.7f;
  47397. {
  47398. Path filledArc;
  47399. filledArc.addPieSegment (rx, ry, rw, rw,
  47400. rotaryStartAngle,
  47401. angle,
  47402. thickness);
  47403. g.fillPath (filledArc);
  47404. }
  47405. if (thickness > 0)
  47406. {
  47407. const float innerRadius = radius * 0.2f;
  47408. Path p;
  47409. p.addTriangle (-innerRadius, 0.0f,
  47410. 0.0f, -radius * thickness * 1.1f,
  47411. innerRadius, 0.0f);
  47412. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  47413. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  47414. }
  47415. if (slider.isEnabled())
  47416. {
  47417. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  47418. Path outlineArc;
  47419. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  47420. outlineArc.closeSubPath();
  47421. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  47422. }
  47423. }
  47424. else
  47425. {
  47426. if (slider.isEnabled())
  47427. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  47428. else
  47429. g.setColour (Colour (0x80808080));
  47430. Path p;
  47431. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  47432. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  47433. p.addLineSegment (0.0f, 0.0f, 0.0f, -radius, rw * 0.2f);
  47434. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  47435. }
  47436. }
  47437. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  47438. {
  47439. return new TextButton (isIncrement ? "+" : "-", String::empty);
  47440. }
  47441. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  47442. {
  47443. Label* const l = new Label (T("n"), String::empty);
  47444. l->setJustificationType (Justification::centred);
  47445. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  47446. l->setColour (Label::backgroundColourId,
  47447. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  47448. : slider.findColour (Slider::textBoxBackgroundColourId));
  47449. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  47450. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  47451. l->setColour (TextEditor::backgroundColourId,
  47452. slider.findColour (Slider::textBoxBackgroundColourId)
  47453. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  47454. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  47455. return l;
  47456. }
  47457. ImageEffectFilter* LookAndFeel::getSliderEffect()
  47458. {
  47459. return 0;
  47460. }
  47461. static const TextLayout layoutTooltipText (const String& text) throw()
  47462. {
  47463. const float tooltipFontSize = 15.0f;
  47464. const int maxToolTipWidth = 400;
  47465. const Font f (tooltipFontSize, Font::bold);
  47466. TextLayout tl (text, f);
  47467. tl.layout (maxToolTipWidth, Justification::left, true);
  47468. return tl;
  47469. }
  47470. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  47471. {
  47472. const TextLayout tl (layoutTooltipText (tipText));
  47473. width = tl.getWidth() + 14;
  47474. height = tl.getHeight() + 10;
  47475. }
  47476. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  47477. {
  47478. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  47479. const Colour textCol (findColour (TooltipWindow::textColourId));
  47480. g.setColour (findColour (TooltipWindow::outlineColourId));
  47481. g.drawRect (0, 0, width, height);
  47482. const TextLayout tl (layoutTooltipText (text));
  47483. g.setColour (findColour (TooltipWindow::textColourId));
  47484. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  47485. }
  47486. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  47487. {
  47488. return new TextButton (text, TRANS("click to browse for a different file"));
  47489. }
  47490. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  47491. ComboBox* filenameBox,
  47492. Button* browseButton)
  47493. {
  47494. browseButton->setSize (80, filenameComp.getHeight());
  47495. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  47496. if (tb != 0)
  47497. tb->changeWidthToFitText();
  47498. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  47499. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  47500. }
  47501. void LookAndFeel::drawCornerResizer (Graphics& g,
  47502. int w, int h,
  47503. bool /*isMouseOver*/,
  47504. bool /*isMouseDragging*/)
  47505. {
  47506. const float lineThickness = jmin (w, h) * 0.075f;
  47507. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  47508. {
  47509. g.setColour (Colours::lightgrey);
  47510. g.drawLine (w * i,
  47511. h + 1.0f,
  47512. w + 1.0f,
  47513. h * i,
  47514. lineThickness);
  47515. g.setColour (Colours::darkgrey);
  47516. g.drawLine (w * i + lineThickness,
  47517. h + 1.0f,
  47518. w + 1.0f,
  47519. h * i + lineThickness,
  47520. lineThickness);
  47521. }
  47522. }
  47523. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  47524. const BorderSize& /*borders*/)
  47525. {
  47526. }
  47527. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  47528. const BorderSize& border, ResizableWindow&)
  47529. {
  47530. g.setColour (Colour (0x80000000));
  47531. g.drawRect (0, 0, w, h);
  47532. g.setColour (Colour (0x19000000));
  47533. g.drawRect (border.getLeft() - 1,
  47534. border.getTop() - 1,
  47535. w + 2 - border.getLeftAndRight(),
  47536. h + 2 - border.getTopAndBottom());
  47537. }
  47538. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  47539. Graphics& g, int w, int h,
  47540. int titleSpaceX, int titleSpaceW,
  47541. const Image* icon,
  47542. bool drawTitleTextOnLeft)
  47543. {
  47544. const bool isActive = window.isActiveWindow();
  47545. GradientBrush gb (window.getBackgroundColour(),
  47546. 0.0f, 0.0f,
  47547. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  47548. 0.0f, (float) h, false);
  47549. g.setBrush (&gb);
  47550. g.fillAll();
  47551. g.setFont (h * 0.65f, Font::bold);
  47552. int textW = g.getCurrentFont().getStringWidth (window.getName());
  47553. int iconW = 0;
  47554. int iconH = 0;
  47555. if (icon != 0)
  47556. {
  47557. iconH = (int) g.getCurrentFont().getHeight();
  47558. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  47559. }
  47560. textW = jmin (titleSpaceW, textW + iconW);
  47561. int textX = drawTitleTextOnLeft ? titleSpaceX
  47562. : jmax (titleSpaceX, (w - textW) / 2);
  47563. if (textX + textW > titleSpaceX + titleSpaceW)
  47564. textX = titleSpaceX + titleSpaceW - textW;
  47565. if (icon != 0)
  47566. {
  47567. g.setOpacity (isActive ? 1.0f : 0.6f);
  47568. g.drawImageWithin (icon, textX, (h - iconH) / 2, iconW, iconH,
  47569. RectanglePlacement::centred, false);
  47570. textX += iconW;
  47571. textW -= iconW;
  47572. }
  47573. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  47574. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  47575. }
  47576. class GlassWindowButton : public Button
  47577. {
  47578. public:
  47579. GlassWindowButton (const String& name, const Colour& col,
  47580. const Path& normalShape_,
  47581. const Path& toggledShape_) throw()
  47582. : Button (name),
  47583. colour (col),
  47584. normalShape (normalShape_),
  47585. toggledShape (toggledShape_)
  47586. {
  47587. }
  47588. ~GlassWindowButton()
  47589. {
  47590. }
  47591. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  47592. {
  47593. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  47594. if (! isEnabled())
  47595. alpha *= 0.5f;
  47596. float x = 0, y = 0, diam;
  47597. if (getWidth() < getHeight())
  47598. {
  47599. diam = (float) getWidth();
  47600. y = (getHeight() - getWidth()) * 0.5f;
  47601. }
  47602. else
  47603. {
  47604. diam = (float) getHeight();
  47605. y = (getWidth() - getHeight()) * 0.5f;
  47606. }
  47607. x += diam * 0.05f;
  47608. y += diam * 0.05f;
  47609. diam *= 0.9f;
  47610. GradientBrush gb1 (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  47611. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false);
  47612. g.setBrush (&gb1);
  47613. g.fillEllipse (x, y, diam, diam);
  47614. x += 2.0f;
  47615. y += 2.0f;
  47616. diam -= 4.0f;
  47617. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  47618. Path& p = getToggleState() ? toggledShape : normalShape;
  47619. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  47620. diam * 0.4f, diam * 0.4f, true));
  47621. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  47622. g.fillPath (p, t);
  47623. }
  47624. juce_UseDebuggingNewOperator
  47625. private:
  47626. Colour colour;
  47627. Path normalShape, toggledShape;
  47628. GlassWindowButton (const GlassWindowButton&);
  47629. const GlassWindowButton& operator= (const GlassWindowButton&);
  47630. };
  47631. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  47632. {
  47633. Path shape;
  47634. const float crossThickness = 0.25f;
  47635. if (buttonType == DocumentWindow::closeButton)
  47636. {
  47637. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, crossThickness * 1.4f);
  47638. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, crossThickness * 1.4f);
  47639. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  47640. }
  47641. else if (buttonType == DocumentWindow::minimiseButton)
  47642. {
  47643. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  47644. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  47645. }
  47646. else if (buttonType == DocumentWindow::maximiseButton)
  47647. {
  47648. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, crossThickness);
  47649. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  47650. Path fullscreenShape;
  47651. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  47652. fullscreenShape.lineTo (0.0f, 100.0f);
  47653. fullscreenShape.lineTo (0.0f, 0.0f);
  47654. fullscreenShape.lineTo (100.0f, 0.0f);
  47655. fullscreenShape.lineTo (100.0f, 45.0f);
  47656. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  47657. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  47658. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  47659. }
  47660. jassertfalse
  47661. return 0;
  47662. }
  47663. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  47664. int titleBarX,
  47665. int titleBarY,
  47666. int titleBarW,
  47667. int titleBarH,
  47668. Button* minimiseButton,
  47669. Button* maximiseButton,
  47670. Button* closeButton,
  47671. bool positionTitleBarButtonsOnLeft)
  47672. {
  47673. const int buttonW = titleBarH - titleBarH / 8;
  47674. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  47675. : titleBarX + titleBarW - buttonW - buttonW / 4;
  47676. if (closeButton != 0)
  47677. {
  47678. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  47679. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  47680. }
  47681. if (positionTitleBarButtonsOnLeft)
  47682. swapVariables (minimiseButton, maximiseButton);
  47683. if (maximiseButton != 0)
  47684. {
  47685. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  47686. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  47687. }
  47688. if (minimiseButton != 0)
  47689. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  47690. }
  47691. int LookAndFeel::getDefaultMenuBarHeight()
  47692. {
  47693. return 24;
  47694. }
  47695. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  47696. {
  47697. return new DropShadower (0.4f, 1, 5, 10);
  47698. }
  47699. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  47700. int w, int h,
  47701. bool /*isVerticalBar*/,
  47702. bool isMouseOver,
  47703. bool isMouseDragging)
  47704. {
  47705. float alpha = 0.5f;
  47706. if (isMouseOver || isMouseDragging)
  47707. {
  47708. g.fillAll (Colour (0x190000ff));
  47709. alpha = 1.0f;
  47710. }
  47711. const float cx = w * 0.5f;
  47712. const float cy = h * 0.5f;
  47713. const float cr = jmin (w, h) * 0.4f;
  47714. GradientBrush gb (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  47715. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  47716. true);
  47717. g.setBrush (&gb);
  47718. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  47719. }
  47720. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  47721. const String& text,
  47722. const Justification& position,
  47723. GroupComponent& group)
  47724. {
  47725. const float textH = 15.0f;
  47726. const float indent = 3.0f;
  47727. const float textEdgeGap = 4.0f;
  47728. float cs = 5.0f;
  47729. Font f (textH);
  47730. Path p;
  47731. float x = indent;
  47732. float y = f.getAscent() - 3.0f;
  47733. float w = jmax (0.0f, width - x * 2.0f);
  47734. float h = jmax (0.0f, height - y - indent);
  47735. cs = jmin (cs, w * 0.5f, h * 0.5f);
  47736. const float cs2 = 2.0f * cs;
  47737. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  47738. float textX = cs + textEdgeGap;
  47739. if (position.testFlags (Justification::horizontallyCentred))
  47740. textX = cs + (w - cs2 - textW) * 0.5f;
  47741. else if (position.testFlags (Justification::right))
  47742. textX = w - cs - textW - textEdgeGap;
  47743. p.startNewSubPath (x + textX + textW, y);
  47744. p.lineTo (x + w - cs, y);
  47745. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  47746. p.lineTo (x + w, y + h - cs);
  47747. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  47748. p.lineTo (x + cs, y + h);
  47749. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  47750. p.lineTo (x, y + cs);
  47751. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  47752. p.lineTo (x + textX, y);
  47753. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  47754. g.setColour (group.findColour (GroupComponent::outlineColourId)
  47755. .withMultipliedAlpha (alpha));
  47756. g.strokePath (p, PathStrokeType (2.0f));
  47757. g.setColour (group.findColour (GroupComponent::textColourId)
  47758. .withMultipliedAlpha (alpha));
  47759. g.setFont (f);
  47760. g.drawText (text,
  47761. roundFloatToInt (x + textX), 0,
  47762. roundFloatToInt (textW),
  47763. roundFloatToInt (textH),
  47764. Justification::centred, true);
  47765. }
  47766. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  47767. {
  47768. return 1 + tabDepth / 3;
  47769. }
  47770. int LookAndFeel::getTabButtonSpaceAroundImage()
  47771. {
  47772. return 4;
  47773. }
  47774. void LookAndFeel::createTabButtonShape (Path& p,
  47775. int width, int height,
  47776. int /*tabIndex*/,
  47777. const String& /*text*/,
  47778. Button& /*button*/,
  47779. TabbedButtonBar::Orientation orientation,
  47780. const bool /*isMouseOver*/,
  47781. const bool /*isMouseDown*/,
  47782. const bool /*isFrontTab*/)
  47783. {
  47784. const float w = (float) width;
  47785. const float h = (float) height;
  47786. float length = w;
  47787. float depth = h;
  47788. if (orientation == TabbedButtonBar::TabsAtLeft
  47789. || orientation == TabbedButtonBar::TabsAtRight)
  47790. {
  47791. swapVariables (length, depth);
  47792. }
  47793. const float indent = (float) getTabButtonOverlap ((int) depth);
  47794. const float overhang = 4.0f;
  47795. if (orientation == TabbedButtonBar::TabsAtLeft)
  47796. {
  47797. p.startNewSubPath (w, 0.0f);
  47798. p.lineTo (0.0f, indent);
  47799. p.lineTo (0.0f, h - indent);
  47800. p.lineTo (w, h);
  47801. p.lineTo (w + overhang, h + overhang);
  47802. p.lineTo (w + overhang, -overhang);
  47803. }
  47804. else if (orientation == TabbedButtonBar::TabsAtRight)
  47805. {
  47806. p.startNewSubPath (0.0f, 0.0f);
  47807. p.lineTo (w, indent);
  47808. p.lineTo (w, h - indent);
  47809. p.lineTo (0.0f, h);
  47810. p.lineTo (-overhang, h + overhang);
  47811. p.lineTo (-overhang, -overhang);
  47812. }
  47813. else if (orientation == TabbedButtonBar::TabsAtBottom)
  47814. {
  47815. p.startNewSubPath (0.0f, 0.0f);
  47816. p.lineTo (indent, h);
  47817. p.lineTo (w - indent, h);
  47818. p.lineTo (w, 0.0f);
  47819. p.lineTo (w + overhang, -overhang);
  47820. p.lineTo (-overhang, -overhang);
  47821. }
  47822. else
  47823. {
  47824. p.startNewSubPath (0.0f, h);
  47825. p.lineTo (indent, 0.0f);
  47826. p.lineTo (w - indent, 0.0f);
  47827. p.lineTo (w, h);
  47828. p.lineTo (w + overhang, h + overhang);
  47829. p.lineTo (-overhang, h + overhang);
  47830. }
  47831. p.closeSubPath();
  47832. p = p.createPathWithRoundedCorners (3.0f);
  47833. }
  47834. void LookAndFeel::fillTabButtonShape (Graphics& g,
  47835. const Path& path,
  47836. const Colour& preferredColour,
  47837. int /*tabIndex*/,
  47838. const String& /*text*/,
  47839. Button& button,
  47840. TabbedButtonBar::Orientation /*orientation*/,
  47841. const bool /*isMouseOver*/,
  47842. const bool /*isMouseDown*/,
  47843. const bool isFrontTab)
  47844. {
  47845. g.setColour (isFrontTab ? preferredColour
  47846. : preferredColour.withMultipliedAlpha (0.9f));
  47847. g.fillPath (path);
  47848. g.setColour (Colours::black.withAlpha (button.isEnabled() ? 0.5f : 0.25f));
  47849. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  47850. }
  47851. void LookAndFeel::drawTabButtonText (Graphics& g,
  47852. int x, int y, int w, int h,
  47853. const Colour& preferredBackgroundColour,
  47854. int /*tabIndex*/,
  47855. const String& text,
  47856. Button& button,
  47857. TabbedButtonBar::Orientation orientation,
  47858. const bool isMouseOver,
  47859. const bool isMouseDown,
  47860. const bool /*isFrontTab*/)
  47861. {
  47862. int length = w;
  47863. int depth = h;
  47864. if (orientation == TabbedButtonBar::TabsAtLeft
  47865. || orientation == TabbedButtonBar::TabsAtRight)
  47866. {
  47867. swapVariables (length, depth);
  47868. }
  47869. Font font (depth * 0.6f);
  47870. font.setUnderline (button.hasKeyboardFocus (false));
  47871. GlyphArrangement textLayout;
  47872. textLayout.addFittedText (font, text.trim(),
  47873. 0.0f, 0.0f, (float) length, (float) depth,
  47874. Justification::centred,
  47875. jmax (1, depth / 12));
  47876. AffineTransform transform;
  47877. if (orientation == TabbedButtonBar::TabsAtLeft)
  47878. {
  47879. transform = transform.rotated (float_Pi * -0.5f)
  47880. .translated ((float) x, (float) (y + h));
  47881. }
  47882. else if (orientation == TabbedButtonBar::TabsAtRight)
  47883. {
  47884. transform = transform.rotated (float_Pi * 0.5f)
  47885. .translated ((float) (x + w), (float) y);
  47886. }
  47887. else
  47888. {
  47889. transform = transform.translated ((float) x, (float) y);
  47890. }
  47891. g.setColour (preferredBackgroundColour.contrasting());
  47892. if (! (isMouseOver || isMouseDown))
  47893. g.setOpacity (0.8f);
  47894. if (! button.isEnabled())
  47895. g.setOpacity (0.3f);
  47896. textLayout.draw (g, transform);
  47897. }
  47898. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  47899. const String& text,
  47900. int tabDepth,
  47901. Button&)
  47902. {
  47903. Font f (tabDepth * 0.6f);
  47904. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  47905. }
  47906. void LookAndFeel::drawTabButton (Graphics& g,
  47907. int w, int h,
  47908. const Colour& preferredColour,
  47909. int tabIndex,
  47910. const String& text,
  47911. Button& button,
  47912. TabbedButtonBar::Orientation orientation,
  47913. const bool isMouseOver,
  47914. const bool isMouseDown,
  47915. const bool isFrontTab)
  47916. {
  47917. int length = w;
  47918. int depth = h;
  47919. if (orientation == TabbedButtonBar::TabsAtLeft
  47920. || orientation == TabbedButtonBar::TabsAtRight)
  47921. {
  47922. swapVariables (length, depth);
  47923. }
  47924. Path tabShape;
  47925. createTabButtonShape (tabShape, w, h,
  47926. tabIndex, text, button, orientation,
  47927. isMouseOver, isMouseDown, isFrontTab);
  47928. fillTabButtonShape (g, tabShape, preferredColour,
  47929. tabIndex, text, button, orientation,
  47930. isMouseOver, isMouseDown, isFrontTab);
  47931. const int indent = getTabButtonOverlap (depth);
  47932. int x = 0, y = 0;
  47933. if (orientation == TabbedButtonBar::TabsAtLeft
  47934. || orientation == TabbedButtonBar::TabsAtRight)
  47935. {
  47936. y += indent;
  47937. h -= indent * 2;
  47938. }
  47939. else
  47940. {
  47941. x += indent;
  47942. w -= indent * 2;
  47943. }
  47944. drawTabButtonText (g, x, y, w, h, preferredColour,
  47945. tabIndex, text, button, orientation,
  47946. isMouseOver, isMouseDown, isFrontTab);
  47947. }
  47948. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  47949. int w, int h,
  47950. TabbedButtonBar& tabBar,
  47951. TabbedButtonBar::Orientation orientation)
  47952. {
  47953. const float shadowSize = 0.2f;
  47954. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  47955. Rectangle shadowRect;
  47956. if (orientation == TabbedButtonBar::TabsAtLeft)
  47957. {
  47958. x1 = (float) w;
  47959. x2 = w * (1.0f - shadowSize);
  47960. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  47961. }
  47962. else if (orientation == TabbedButtonBar::TabsAtRight)
  47963. {
  47964. x2 = w * shadowSize;
  47965. shadowRect.setBounds (0, 0, (int) x2, h);
  47966. }
  47967. else if (orientation == TabbedButtonBar::TabsAtBottom)
  47968. {
  47969. y2 = h * shadowSize;
  47970. shadowRect.setBounds (0, 0, w, (int) y2);
  47971. }
  47972. else
  47973. {
  47974. y1 = (float) h;
  47975. y2 = h * (1.0f - shadowSize);
  47976. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  47977. }
  47978. GradientBrush gb (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  47979. Colours::transparentBlack, x2, y2,
  47980. false);
  47981. g.setBrush (&gb);
  47982. shadowRect.expand (2, 2);
  47983. g.fillRect (shadowRect);
  47984. g.setColour (Colour (0x80000000));
  47985. if (orientation == TabbedButtonBar::TabsAtLeft)
  47986. {
  47987. g.fillRect (w - 1, 0, 1, h);
  47988. }
  47989. else if (orientation == TabbedButtonBar::TabsAtRight)
  47990. {
  47991. g.fillRect (0, 0, 1, h);
  47992. }
  47993. else if (orientation == TabbedButtonBar::TabsAtBottom)
  47994. {
  47995. g.fillRect (0, 0, w, 1);
  47996. }
  47997. else
  47998. {
  47999. g.fillRect (0, h - 1, w, 1);
  48000. }
  48001. }
  48002. Button* LookAndFeel::createTabBarExtrasButton()
  48003. {
  48004. const float thickness = 7.0f;
  48005. const float indent = 22.0f;
  48006. Path p;
  48007. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  48008. DrawablePath ellipse;
  48009. ellipse.setPath (p);
  48010. ellipse.setSolidFill (Colour (0x99ffffff));
  48011. p.clear();
  48012. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  48013. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  48014. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  48015. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  48016. p.setUsingNonZeroWinding (false);
  48017. DrawablePath dp;
  48018. dp.setPath (p);
  48019. dp.setSolidFill (Colour (0x59000000));
  48020. DrawableComposite normalImage;
  48021. normalImage.insertDrawable (ellipse);
  48022. normalImage.insertDrawable (dp);
  48023. dp.setSolidFill (Colour (0xcc000000));
  48024. DrawableComposite overImage;
  48025. overImage.insertDrawable (ellipse);
  48026. overImage.insertDrawable (dp);
  48027. DrawableButton* db = new DrawableButton (T("tabs"), DrawableButton::ImageFitted);
  48028. db->setImages (&normalImage, &overImage, 0);
  48029. return db;
  48030. }
  48031. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  48032. {
  48033. g.fillAll (Colours::white);
  48034. const int w = header.getWidth();
  48035. const int h = header.getHeight();
  48036. GradientBrush gb (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  48037. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  48038. false);
  48039. g.setBrush (&gb);
  48040. g.fillRect (0, h / 2, w, h);
  48041. g.setColour (Colour (0x33000000));
  48042. g.fillRect (0, h - 1, w, 1);
  48043. for (int i = header.getNumColumns (true); --i >= 0;)
  48044. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  48045. }
  48046. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  48047. int width, int height,
  48048. bool isMouseOver, bool isMouseDown,
  48049. int columnFlags)
  48050. {
  48051. if (isMouseDown)
  48052. g.fillAll (Colour (0x8899aadd));
  48053. else if (isMouseOver)
  48054. g.fillAll (Colour (0x5599aadd));
  48055. int rightOfText = width - 4;
  48056. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  48057. {
  48058. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  48059. const float bottom = height - top;
  48060. const float w = height * 0.5f;
  48061. const float x = rightOfText - (w * 1.25f);
  48062. rightOfText = (int) x;
  48063. Path sortArrow;
  48064. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  48065. g.setColour (Colour (0x99000000));
  48066. g.fillPath (sortArrow);
  48067. }
  48068. g.setColour (Colours::black);
  48069. g.setFont (height * 0.5f, Font::bold);
  48070. const int textX = 4;
  48071. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  48072. }
  48073. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  48074. {
  48075. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  48076. GradientBrush gb (background, 0.0f, 0.0f,
  48077. background.darker (0.1f),
  48078. toolbar.isVertical() ? w - 1.0f : 0.0f,
  48079. toolbar.isVertical() ? 0.0f : h - 1.0f,
  48080. false);
  48081. g.setBrush (&gb);
  48082. g.fillAll();
  48083. }
  48084. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  48085. {
  48086. return createTabBarExtrasButton();
  48087. }
  48088. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  48089. bool isMouseOver, bool isMouseDown,
  48090. ToolbarItemComponent& component)
  48091. {
  48092. if (isMouseDown)
  48093. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  48094. else if (isMouseOver)
  48095. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  48096. }
  48097. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  48098. const String& text, ToolbarItemComponent& component)
  48099. {
  48100. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  48101. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  48102. const float fontHeight = jmin (14.0f, height * 0.85f);
  48103. g.setFont (fontHeight);
  48104. g.drawFittedText (text,
  48105. x, y, width, height,
  48106. Justification::centred,
  48107. jmax (1, height / (int) fontHeight));
  48108. }
  48109. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  48110. bool isOpen, int width, int height)
  48111. {
  48112. const int buttonSize = (height * 3) / 4;
  48113. const int buttonIndent = (height - buttonSize) / 2;
  48114. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen);
  48115. const int textX = buttonIndent * 2 + buttonSize + 2;
  48116. g.setColour (Colours::black);
  48117. g.setFont (height * 0.7f, Font::bold);
  48118. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  48119. }
  48120. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  48121. PropertyComponent&)
  48122. {
  48123. g.setColour (Colour (0x66ffffff));
  48124. g.fillRect (0, 0, width, height - 1);
  48125. }
  48126. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  48127. PropertyComponent& component)
  48128. {
  48129. g.setColour (Colours::black);
  48130. if (! component.isEnabled())
  48131. g.setOpacity (g.getCurrentColour().getAlpha() * 0.6f);
  48132. g.setFont (jmin (height, 24) * 0.65f);
  48133. const Rectangle r (getPropertyComponentContentPosition (component));
  48134. g.drawFittedText (component.getName(),
  48135. 3, r.getY(), r.getX() - 5, r.getHeight(),
  48136. Justification::centredLeft, 2);
  48137. }
  48138. const Rectangle LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  48139. {
  48140. return Rectangle (component.getWidth() / 3, 1,
  48141. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  48142. }
  48143. void LookAndFeel::createFileChooserHeaderText (const String& title,
  48144. const String& instructions,
  48145. GlyphArrangement& text,
  48146. int width)
  48147. {
  48148. text.clear();
  48149. text.addJustifiedText (Font (17.0f, Font::bold), title,
  48150. 8.0f, 22.0f, width - 16.0f,
  48151. Justification::centred);
  48152. text.addJustifiedText (Font (14.0f), instructions,
  48153. 8.0f, 24.0f + 16.0f, width - 16.0f,
  48154. Justification::centred);
  48155. }
  48156. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  48157. const String& filename, Image* icon,
  48158. const String& fileSizeDescription,
  48159. const String& fileTimeDescription,
  48160. const bool isDirectory,
  48161. const bool isItemSelected,
  48162. const int /*itemIndex*/)
  48163. {
  48164. if (isItemSelected)
  48165. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  48166. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  48167. g.setFont (height * 0.7f);
  48168. Image* im = icon;
  48169. Image* toRelease = 0;
  48170. if (im == 0)
  48171. {
  48172. toRelease = im = (isDirectory ? getDefaultFolderImage()
  48173. : getDefaultDocumentFileImage());
  48174. }
  48175. const int x = 32;
  48176. if (im != 0)
  48177. {
  48178. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  48179. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48180. false);
  48181. ImageCache::release (toRelease);
  48182. }
  48183. if (width > 450 && ! isDirectory)
  48184. {
  48185. const int sizeX = roundFloatToInt (width * 0.7f);
  48186. const int dateX = roundFloatToInt (width * 0.8f);
  48187. g.drawFittedText (filename,
  48188. x, 0, sizeX - x, height,
  48189. Justification::centredLeft, 1);
  48190. g.setFont (height * 0.5f);
  48191. g.setColour (Colours::darkgrey);
  48192. if (! isDirectory)
  48193. {
  48194. g.drawFittedText (fileSizeDescription,
  48195. sizeX, 0, dateX - sizeX - 8, height,
  48196. Justification::centredRight, 1);
  48197. g.drawFittedText (fileTimeDescription,
  48198. dateX, 0, width - 8 - dateX, height,
  48199. Justification::centredRight, 1);
  48200. }
  48201. }
  48202. else
  48203. {
  48204. g.drawFittedText (filename,
  48205. x, 0, width - x, height,
  48206. Justification::centredLeft, 1);
  48207. }
  48208. }
  48209. Button* LookAndFeel::createFileBrowserGoUpButton()
  48210. {
  48211. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  48212. Path arrowPath;
  48213. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  48214. DrawablePath arrowImage;
  48215. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  48216. arrowImage.setPath (arrowPath);
  48217. goUpButton->setImages (&arrowImage);
  48218. return goUpButton;
  48219. }
  48220. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  48221. DirectoryContentsDisplayComponent* fileListComponent,
  48222. FilePreviewComponent* previewComp,
  48223. ComboBox* currentPathBox,
  48224. TextEditor* filenameBox,
  48225. Button* goUpButton)
  48226. {
  48227. const int x = 8;
  48228. int w = browserComp.getWidth() - x - x;
  48229. if (previewComp != 0)
  48230. {
  48231. const int previewWidth = w / 3;
  48232. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  48233. w -= previewWidth + 4;
  48234. }
  48235. int y = 4;
  48236. const int controlsHeight = 22;
  48237. const int bottomSectionHeight = controlsHeight + 8;
  48238. const int upButtonWidth = 50;
  48239. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  48240. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  48241. y += controlsHeight + 4;
  48242. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  48243. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  48244. y = listAsComp->getBottom() + 4;
  48245. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  48246. }
  48247. Image* LookAndFeel::getDefaultFolderImage()
  48248. {
  48249. static const unsigned char foldericon_png[] = { 137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,28,8,6,0,0,0,0,194,189,34,0,0,0,4,103,65,77,65,0,0,175,200,55,5,
  48250. 138,233,0,0,0,25,116,69,88,116,83,111,102,116,119,97,114,101,0,65,100,111,98,101,32,73,109,97,103,101,82,101,97,100,121,113,201,101,60,0,0,9,46,73,68,65,84,120,218,98,252,255,255,63,3,50,240,41,95,192,
  48251. 197,205,198,32,202,204,202,33,241,254,235,47,133,47,191,24,180,213,164,133,152,69,24,222,44,234,42,77,188,245,31,170,129,145,145,145,1,29,128,164,226,91,86,113,252,248,207,200,171,37,39,204,239,170,43,
  48252. 254,206,218,88,231,61,62,61,0,1,196,2,149,96,116,200,158,102,194,202,201,227,197,193,206,166,194,204,193,33,195,202,204,38,42,197,197,42,196,193,202,33,240,241,231,15,134,151,95,127,9,2,149,22,0,241,47,
  48253. 152,230,128,134,245,204,63,191,188,103,83,144,16,16,228,229,102,151,76,239,217,32,199,204,198,169,205,254,159,65,245,203,79,6,169,131,151,30,47,1,42,91,10,196,127,208,236,101,76,235,90,43,101,160,40,242,
  48254. 19,32,128,64,78,98,52,12,41,149,145,215,52,89,162,38,35,107,39,196,203,203,192,206,194,206,192,197,198,202,192,203,197,198,192,205,193,206,240,252,227,103,134,139,55,175,191,127,243,242,78,219,187,207,
  48255. 63,215,255,98,23,48,228,227,96,83,98,102,102,85,225,224,228,80,20,224,230,86,226,225,228,150,103,101,97,101,230,227,228,96,224,0,234,191,243,252,5,195,222,19,199,38,191,127,112,161,83,66,199,86,141,131,
  48256. 149,69,146,133,153,69,137,149,133,89,157,141,131,77,83,140,143,243,219,255,31,159,123,0,2,136,69,90,207,129,157,71,68,42,66,71,73,209,210,81,91,27,24,142,140,12,127,255,253,103,0,185,236,31,3,144,6,50,
  48257. 148,68,216,25,216,24,117,4,239,11,243,214,49,50,51,84,178,48,114,240,112,177,114,177,240,115,113,49,241,112,112,48,176,179,178,51,176,48,49,3,85,255,99,248,253,247,15,195,247,159,191,25,30,191,126,253,
  48258. 71,74,76,200,66,75,197,119,138,168,144,160,150,168,0,183,160,152,32,15,175,188,184,32,199,175,191,127,25,214,31,184,120,247,236,209,253,159,0,2,136,133,95,70,93,74,88,80,196,83,69,66,130,149,9,104,219,
  48259. 151,31,191,193,150,194,146,6,136,102,102,98,100,16,227,231,103,16,23,210,230,101,101,102,100,248,255,143,137,225,223,63,6,6,22,102,38,134,239,191,126,49,220,123,241,134,225,227,247,175,64,7,252,101,96,
  48260. 97,249,207,192,193,198,200,160,171,34,192,108,165,235,104,42,204,207,101,42,194,199,197,192,199,201,198,192,197,193,202,192,198,202,194,176,247,194,3,134,155,183,110,61,188,127,124,221,19,128,0,92,146,
  48261. 49,14,64,64,16,69,63,153,85,16,52,18,74,71,112,6,87,119,0,165,160,86,138,32,172,216,29,49,182,84,253,169,94,94,230,127,17,87,133,34,146,174,3,88,126,240,219,164,147,113,31,145,244,152,112,179,211,130,
  48262. 34,31,203,113,162,233,6,36,49,163,174,74,124,140,60,141,144,165,161,220,228,25,3,24,105,255,17,168,101,1,139,245,188,93,104,251,73,239,235,50,90,189,111,175,0,98,249,254,254,249,175,239,223,190,126,6,
  48263. 5,27,19,47,90,170,102,0,249,158,129,129,141,133,25,228,20,6,38,38,72,74,7,185,243,243,247,239,12,23,31,60,98,228,231,253,207,144,227,107,206,32,202,199,193,240,249,251,127,134,95,191,255,49,124,249,250,
  48264. 159,225,237,239,95,12,63,127,1,35,229,31,194,71,32,71,63,123,251,245,223,197,27,183,159,189,187,178,103,61,80,232,59,64,0,177,48,252,5,134,225,255,191,223,126,254,250,13,182,132,1,41,167,176,3,53,128,
  48265. 188,254,226,253,103,96,212,252,96,120,247,249,203,255,79,223,191,254,255,250,235,199,191,239,63,191,255,87,145,17,100,73,116,181,100,252,249,243,63,195,149,123,223,193,14,132,101,55,96,52,3,125,255,15,
  48266. 204,254,15,132,160,232,253,13,20,124,248,226,227,223,23,207,30,221,120,119,255,226,109,160,210,31,0,1,196,242,231,219,135,175,140,255,126,190,7,197,37,35,19,34,216,65,248,211,143,111,255,79,223,121,240,
  48267. 255,211,183,79,76,220,156,172,12,236,204,140,140,252,124,28,140,250,226,82,140,106,82,34,140,124,156,156,12,175,222,253,1,90,4,137,162,63,127,33,161,6,178,242,215,239,255,224,160,255,15,198,12,64,7,48,
  48268. 128,211,200,253,151,111,254,254,248,240,236,44,80,217,71,80,246,4,8,32,160,31,255,255,100,102,248,243,238,199,159,63,16,221,16,19,128,248,31,195,181,199,207,254,255,253,247,133,49,212,78,27,104,8,11,40,
  48269. 94,25,184,216,89,129,108,38,70,144,242,183,31,17,105,230,63,148,248,15,97,49,252,248,249,15,20,85,72,105,9,148,187,254,49,220,127,254,242,207,243,75,135,14,128,130,31,84,64,1,4,16,203,247,143,175,127,
  48270. 48,253,254,246,234,7,48,206,96,137,13,4,64,65,248,234,195,7,6,7,3,57,70,33,46,97,134,111,63,254,50,252,5,250,244,51,216,103,255,192,185,0,150,91,80,44,135,242,127,253,129,164,23,24,96,102,250,207,112,
  48271. 255,213,219,255,247,31,63,188,251,246,201,173,199,176,2,13,32,128,88,62,188,121,241,243,211,231,207,31,126,2,147,236,63,168,6,144,193,223,190,255,254,207,198,198,192,40,35,44,206,240,252,205,79,6,132,
  48272. 223,24,224,150,32,251,28,25,128,211,29,19,170,24,51,48,88,111,61,127,206,248,254,245,179,139,192,18,247,219,239,239,95,192,249,9,32,128,88,126,124,249,248,231,203,183,111,159,128,33,240,15,24,68,160,180,
  48273. 2,204,223,140,12,111,63,127,102,16,228,229,4,6,53,35,195,31,176,119,25,112,3,70,84,55,0,203,50,112,33,134,108,249,103,160,7,159,189,126,253,235,235,227,203,7,255,255,251,247,13,86,63,0,4,16,168,46,248,
  48274. 199,250,231,243,235,159,191,126,254,248,245,251,47,23,11,51,51,48,184,152,24,94,127,250,248,95,68,136,151,241,243,55,96,208,51,160,218,255,31,139,27,144,197,254,98,201,202,79,223,124,96,120,245,232,250,
  48275. 185,119,143,174,95,250,243,243,219,119,152,60,64,0,129,2,234,223,183,215,15,95,48,254,255,253,3,146,109,192,229,5,195,135,47,159,25,248,184,121,24,126,0,227,29,88,240,49,252,101,36,14,255,1,90,249,7,156,
  48276. 222,17,24,24,164,12,207,223,189,99,248,250,252,230,97,96,229,245,2,104,231,111,152,3,0,2,8,228,128,191,15,239,220,120,255,255,223,159,47,160,116,0,42,44,222,124,250,244,239,207,255,63,12,236,108,236,64,
  48277. 67,65,81,0,52,244,63,113,248,47,52,10,96,14,98,2,230,191,119,223,127,48,60,121,254,248,235,151,55,207,46,1,163,252,35,114,128,1,4,16,40,10,254,191,121,249,252,199,175,159,63,191,254,2,230,45,118,22,22,
  48278. 134,219,207,94,252,231,224,100,103,250,247,15,148,32,64,85,12,34,14,254,227,72,6,255,225,9,240,63,138,26,46,96,214,189,249,244,37,195,139,167,143,30,124,253,246,253,9,40,245,255,71,202,30,0,1,196,2,226,
  48279. 0,243,232,159,239,63,127,124,253,11,202,94,64,169,23,31,62,50,138,137,242,49,50,0,211,195,223,255,80,7,252,199,159,6,224,137,145,9,146,231,153,160,165,218,23,96,29,240,244,237,59,134,111,175,31,95,250,
  48280. 252,230,241,83,244,182,1,64,0,177,192,28,14,76,132,31,128,169,19,88,220,126,253,207,206,198,196,32,38,36,0,244,61,11,176,148,251,139,145,3,208,29,0,178,16,82,228,66,42,174,223,192,26,8,152,162,25,222,
  48281. 125,248,200,240,242,253,39,134,151,79,238,126,254,242,242,238,177,15,47,30,190,5,215,242,72,0,32,128,224,14,96,254,255,231,61,168,92,123,241,254,253,127,1,62,78,6,78,110,78,134,223,64,195,254,50,98,183,
  48282. 24,36,12,202,179,224,202,9,88,228,253,132,90,250,246,211,71,134,55,175,94,254,122,255,250,249,247,15,175,159,126,249,251,237,195,135,95,175,110,31,122,117,251,244,49,160,150,111,255,209,218,128,0,1,152,
  48283. 44,183,21,0,65,32,136,110,247,254,255,243,122,9,187,64,105,174,74,22,138,25,173,80,208,194,188,238,156,151,217,217,15,32,182,197,37,83,201,4,31,243,178,169,232,242,214,224,223,252,103,175,35,85,1,41,129,
  48284. 228,148,142,8,214,30,32,149,6,161,204,109,182,53,236,184,156,78,142,147,195,153,89,35,198,3,87,166,249,220,227,198,59,218,48,252,223,185,111,30,1,132,228,128,127,31,222,124,248,248,27,24,152,28,60,220,
  48285. 220,12,44,172,172,224,224,103,5,102,98,144,133,160,236,244,229,231,47,134,239,223,127,49,188,121,251,158,225,241,179,103,12,31,223,189,254,251,227,221,139,55,191,62,188,120,246,235,205,189,59,207,238,
  48286. 94,58,241,228,254,109,144,101,159,128,248,51,40,9,32,97,80,217,255,15,221,1,0,1,4,143,130,207,159,191,126,252,246,234,213,111,94,126,94,118,73,94,9,198,127,64,223,126,252,246,147,225,243,215,239,12,223,
  48287. 128,229,198,251,15,239,24,62,189,126,249,227,203,171,135,47,63,189,122,252,228,235,155,199,247,95,63,188,118,227,197,227,123,247,127,255,250,249,30,104,198,7,32,126,11,181,252,7,212,183,160,4,247,7,155,
  48288. 197,48,0,16,64,112,7,60,121,241,238,189,16,207,15,134,63,63,216,25,95,125,248,198,112,227,241,27,134,15,239,223,50,124,126,245,228,253,143,55,143,158,191,123,116,237,226,171,135,55,175,126,253,252,225,
  48289. 229,183,47,159,95,254,253,245,227,253,175,159,223,223,193,124,7,181,20,84,105,252,70,143,103,124,0,32,128,224,14,224,102,253,251,81,144,253,223,235,167,207,30,254,124,127,231,252,155,143,175,159,188,250,
  48290. 246,254,249,125,96,60,62,248,250,233,253,147,119,207,238,221,6,150,214,175,129,106,191,130,18,19,146,133,120,125,72,8,0,4,16,34,27,190,121,112,251,3,211,159,69,143,110,223,229,120,255,232,230,221,215,
  48291. 79,239,62,4,102,203,207,72,241,9,11,218,63,72,89,137,20,207,98,100,93,16,0,8,32,70,144,1,64,14,168,209,199,7,196,194,160,166,27,212,135,95,96,65,10,173,95,254,34,219,6,51,128,88,7,96,235,21,129,0,64,0,
  48292. 193,28,192,8,174,53,33,152,1,155,133,184,12,196,165,4,151,133,232,0,32,192,0,151,97,210,163,246,134,208,52,0,0,0,0,73,69,78,68,174,66,96,130,0,0};
  48293. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  48294. }
  48295. Image* LookAndFeel::getDefaultDocumentFileImage()
  48296. {
  48297. static const unsigned char fileicon_png[] = { 137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,32,8,6,0,0,0,115,122,122,244,0,0,0,4,103,65,77,65,0,0,175,200,55,5,
  48298. 138,233,0,0,0,25,116,69,88,116,83,111,102,116,119,97,114,101,0,65,100,111,98,101,32,73,109,97,103,101,82,101,97,100,121,113,201,101,60,0,0,4,99,73,68,65,84,120,218,98,252,255,255,63,3,12,48,50,50,50,1,
  48299. 169,127,200,98,148,2,160,153,204,64,243,254,226,146,7,8,32,22,52,203,255,107,233,233,91,76,93,176,184,232,239,239,95,127,24,40,112,8,19,51,203,255,179,23,175,108,1,90,190,28,104,54,43,80,232,207,127,44,
  48300. 62,3,8,32,6,144,24,84,156,25,132,189,252,3,146,255,83,9,220,127,254,242,134,162,138,170,10,208,92,144,3,152,97,118,33,99,128,0,98,66,114,11,200,1,92,255,254,252,225,32,215,215,32,127,64,240,127,80,60,
  48301. 50,40,72,136,169,47,95,179,118,130,136,148,140,0,40,80,128,33,193,136,174,7,32,128,144,29,192,8,117,41,59,209,22,66,241,191,255,16,12,244,19,195,63,48,134,240,255,0,9,115,125,93,239,252,130,130,108,168,
  48302. 249,44,232,102,0,4,16,19,22,62,51,33,11,255,195,44,4,211,255,25,96,16,33,6,117,24,56,226,25,24,202,139,10,75,226,51,115,66,160,105,13,197,17,0,1,196,68,172,79,255,33,91,206,192,192,128,176,22,17,10,200,
  48303. 234,32,161,240,31,24,10,255,24,152,153,153,184,39,244,247,117,107,234,234,105,131,66,1,154,224,193,0,32,128,240,58,0,22,180,255,144,18,13,40,136,33,113,140,36,255,15,17,26,48,12,81,15,145,255,254,251,
  48304. 31,131,0,59,171,84,81,73,105,33,208,216,191,200,161,12,16,64,44,248,131,251,63,10,31,198,253,143,38,6,83,7,11,33,228,232,2,123,4,202,226,228,96,151,132,166,49,144,35,126,131,196,0,2,136,5,103,60,51,252,
  48305. 71,49,12,213,130,255,168,226,232,150,254,255,15,143,6,80,202,3,133,16,200,198,63,127,193,229,17,39,16,127,135,217,7,16,64,88,67,0,28,143,255,25,225,46,135,249,18,155,133,240,178,4,205,145,8,62,52,186,
  48306. 32,234,152,160,118,194,179,35,64,0,177,96,11,123,144,236,95,104,92,162,228,113,36,11,81,125,140,112,56,186,131,96,226,176,172,137,148,229,193,0,32,128,88,112,167,248,255,112,223,48,34,165,110,6,124,190,
  48307. 253,143,61,106,192,9,19,73,28,25,0,4,16,206,40,248,251,15,45,104,209,130,21,51,222,145,18,238,127,180,68,8,244,250,95,164,16,66,6,0,1,196,130,45,253,195,12,250,135,53,206,255,195,131,18,213,98,236,81,
  48308. 243,31,154,11,144,115,8,50,0,8,32,156,81,0,203,227,12,80,223,98,230,4,68,72,96,38,78,84,11,65,9,250,47,146,3,145,1,64,0,97,117,192,95,112,34,68,138,130,255,176,224,251,143,226,51,6,6,68,29,192,136,20,
  48309. 77,200,69,54,35,3,36,49,255,69,77,132,112,0,16,64,44,56,139,94,36,7,96,102,59,164,108,249,31,181,82,98,64,203,174,255,144,234,142,127,88,146,33,64,0,97,205,134,240,120,67,75,76,136,224,198,140,22,6,44,
  48310. 142,66,201,41,255,177,231,2,128,0,194,25,5,255,254,161,134,192,127,6,28,229,0,129,242,1,150,56,33,81,138,209,28,96,0,8,32,172,81,0,78,3,104,190,68,182,224,31,146,197,224,56,6,146,140,176,202,135,17,169,
  48311. 96,130,40,64,56,0,139,93,0,1,132,61,10,64,248,31,106,156,162,199,55,204,65,255,144,178,38,74,84,252,71,51,239,63,246,68,8,16,64,44,216,74,1,88,217,13,203,191,32,1,80,58,7,133,224,127,6,68,114,6,241,65,
  48312. 81,197,8,101,255,71,114,33,92,237,127,228,52,128,233,2,128,0,98,193,149,3,64,117,193,255,127,255,81,75,191,127,168,5,18,136,255,31,45,161,49,32,151,134,72,252,127,12,216,203,98,128,0,98,193,210,144,135,
  48313. 248,30,201,242,127,208,252,140,145,27,160,113,206,136,148,197,192,121,159,17,53,184,225,149,17,22,23,0,4,16,11,182,150,237,63,168,207,96,142,248,143,163,72,6,203,253,67,13,61,6,104,14,66,46,17,254,65,
  48314. 19,40,182,16,0,8,32,22,108,109,235,255,176,234,24,35,79,255,199,222,30,64,81,135,90,35,194,211,4,142,92,0,16,64,88,29,0,107,7,254,251,247,31,53,78,241,54,207,80,29,135,209,96,249,143,189,46,0,8,32,116,
  48315. 7,252,101,102,103,103,228,103,99,96,248,193,198,137,53,248,49,125,204,128,225,227,255,88,18,54,47,176,25,202,205,195,205,6,109,11,194,149,0,4,16,35,204,85,208,254,27,159,128,176,176,142,166,182,142,21,
  48316. 48,4,248,129,41,143,13,217,16,70,52,95,147,0,254,0,187,69,95,223,188,122,125,235,206,141,107,7,129,252,247,64,123,193,237,66,128,0,66,118,0,168,189,198,3,196,252,32,135,64,105,54,228,230,19,185,29,100,
  48317. 168,175,191,0,241,7,32,254,4,196,159,129,246,254,2,73,2,4,16,11,90,72,125,135,210,63,161,138,153,169,212,75,255,15,117,196,15,40,134,119,215,1,2,12,0,187,0,132,247,216,161,197,124,0,0,0,0,73,69,78,68,
  48318. 174,66,96,130,0,0};
  48319. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  48320. }
  48321. void LookAndFeel::playAlertSound()
  48322. {
  48323. PlatformUtilities::beep();
  48324. }
  48325. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  48326. {
  48327. g.setColour (Colours::white.withAlpha (0.7f));
  48328. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  48329. g.setColour (Colours::black.withAlpha (0.2f));
  48330. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  48331. const int totalBlocks = 7;
  48332. const int numBlocks = roundDoubleToInt (totalBlocks * level);
  48333. const float w = (width - 6.0f) / (float) totalBlocks;
  48334. for (int i = 0; i < totalBlocks; ++i)
  48335. {
  48336. if (i >= numBlocks)
  48337. g.setColour (Colours::lightblue.withAlpha (0.6f));
  48338. else
  48339. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  48340. : Colours::red);
  48341. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  48342. }
  48343. }
  48344. static void createRoundedPath (Path& p,
  48345. const float x, const float y,
  48346. const float w, const float h,
  48347. const float cs,
  48348. const bool curveTopLeft, const bool curveTopRight,
  48349. const bool curveBottomLeft, const bool curveBottomRight) throw()
  48350. {
  48351. const float cs2 = 2.0f * cs;
  48352. if (curveTopLeft)
  48353. {
  48354. p.startNewSubPath (x, y + cs);
  48355. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  48356. }
  48357. else
  48358. {
  48359. p.startNewSubPath (x, y);
  48360. }
  48361. if (curveTopRight)
  48362. {
  48363. p.lineTo (x + w - cs, y);
  48364. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  48365. }
  48366. else
  48367. {
  48368. p.lineTo (x + w, y);
  48369. }
  48370. if (curveBottomRight)
  48371. {
  48372. p.lineTo (x + w, y + h - cs);
  48373. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  48374. }
  48375. else
  48376. {
  48377. p.lineTo (x + w, y + h);
  48378. }
  48379. if (curveBottomLeft)
  48380. {
  48381. p.lineTo (x + cs, y + h);
  48382. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  48383. }
  48384. else
  48385. {
  48386. p.lineTo (x, y + h);
  48387. }
  48388. p.closeSubPath();
  48389. }
  48390. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  48391. float x, float y, float w, float h,
  48392. float maxCornerSize,
  48393. const Colour& baseColour,
  48394. const float strokeWidth,
  48395. const bool flatOnLeft,
  48396. const bool flatOnRight,
  48397. const bool flatOnTop,
  48398. const bool flatOnBottom) throw()
  48399. {
  48400. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  48401. return;
  48402. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  48403. Path outline;
  48404. createRoundedPath (outline, x, y, w, h, cs,
  48405. ! (flatOnLeft || flatOnTop),
  48406. ! (flatOnRight || flatOnTop),
  48407. ! (flatOnLeft || flatOnBottom),
  48408. ! (flatOnRight || flatOnBottom));
  48409. ColourGradient cg (baseColour, 0.0f, y,
  48410. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  48411. false);
  48412. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  48413. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  48414. GradientBrush gb (cg);
  48415. g.setBrush (&gb);
  48416. g.fillPath (outline);
  48417. g.setColour (Colour (0x80000000));
  48418. g.strokePath (outline, PathStrokeType (strokeWidth));
  48419. }
  48420. void LookAndFeel::drawGlassSphere (Graphics& g,
  48421. const float x, const float y,
  48422. const float diameter,
  48423. const Colour& colour,
  48424. const float outlineThickness) throw()
  48425. {
  48426. if (diameter <= outlineThickness)
  48427. return;
  48428. Path p;
  48429. p.addEllipse (x, y, diameter, diameter);
  48430. {
  48431. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  48432. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  48433. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  48434. GradientBrush gb (cg);
  48435. g.setBrush (&gb);
  48436. g.fillPath (p);
  48437. }
  48438. {
  48439. GradientBrush gb (Colours::white, 0, y + diameter * 0.06f,
  48440. Colours::transparentWhite, 0, y + diameter * 0.3f, false);
  48441. g.setBrush (&gb);
  48442. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  48443. }
  48444. {
  48445. ColourGradient cg (Colours::transparentBlack,
  48446. x + diameter * 0.5f, y + diameter * 0.5f,
  48447. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  48448. x, y + diameter * 0.5f, true);
  48449. cg.addColour (0.7, Colours::transparentBlack);
  48450. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  48451. GradientBrush gb (cg);
  48452. g.setBrush (&gb);
  48453. g.fillPath (p);
  48454. }
  48455. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  48456. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  48457. }
  48458. void LookAndFeel::drawGlassPointer (Graphics& g,
  48459. const float x, const float y,
  48460. const float diameter,
  48461. const Colour& colour, const float outlineThickness,
  48462. const int direction) throw()
  48463. {
  48464. if (diameter <= outlineThickness)
  48465. return;
  48466. Path p;
  48467. p.startNewSubPath (x + diameter * 0.5f, y);
  48468. p.lineTo (x + diameter, y + diameter * 0.6f);
  48469. p.lineTo (x + diameter, y + diameter);
  48470. p.lineTo (x, y + diameter);
  48471. p.lineTo (x, y + diameter * 0.6f);
  48472. p.closeSubPath();
  48473. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  48474. {
  48475. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  48476. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  48477. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  48478. GradientBrush gb (cg);
  48479. g.setBrush (&gb);
  48480. g.fillPath (p);
  48481. }
  48482. {
  48483. ColourGradient cg (Colours::transparentBlack,
  48484. x + diameter * 0.5f, y + diameter * 0.5f,
  48485. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  48486. x - diameter * 0.2f, y + diameter * 0.5f, true);
  48487. cg.addColour (0.5, Colours::transparentBlack);
  48488. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  48489. GradientBrush gb (cg);
  48490. g.setBrush (&gb);
  48491. g.fillPath (p);
  48492. }
  48493. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  48494. g.strokePath (p, PathStrokeType (outlineThickness));
  48495. }
  48496. void LookAndFeel::drawGlassLozenge (Graphics& g,
  48497. const float x, const float y,
  48498. const float width, const float height,
  48499. const Colour& colour,
  48500. const float outlineThickness,
  48501. const float cornerSize,
  48502. const bool flatOnLeft,
  48503. const bool flatOnRight,
  48504. const bool flatOnTop,
  48505. const bool flatOnBottom) throw()
  48506. {
  48507. if (width <= outlineThickness || height <= outlineThickness)
  48508. return;
  48509. const int intX = (int) x;
  48510. const int intY = (int) y;
  48511. const int intW = (int) width;
  48512. const int intH = (int) height;
  48513. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  48514. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  48515. const int intEdge = (int) edgeBlurRadius;
  48516. Path outline;
  48517. createRoundedPath (outline, x, y, width, height, cs,
  48518. ! (flatOnLeft || flatOnTop),
  48519. ! (flatOnRight || flatOnTop),
  48520. ! (flatOnLeft || flatOnBottom),
  48521. ! (flatOnRight || flatOnBottom));
  48522. {
  48523. ColourGradient cg (colour.darker (0.2f), 0, y,
  48524. colour.darker (0.2f), 0, y + height, false);
  48525. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  48526. cg.addColour (0.4, colour);
  48527. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  48528. GradientBrush gb (cg);
  48529. g.setBrush (&gb);
  48530. g.fillPath (outline);
  48531. }
  48532. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  48533. colour.darker (0.2f), x, y + height * 0.5f, true);
  48534. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  48535. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  48536. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  48537. {
  48538. GradientBrush gb (cg);
  48539. g.saveState();
  48540. g.setBrush (&gb);
  48541. g.reduceClipRegion (intX, intY, intEdge, intH);
  48542. g.fillPath (outline);
  48543. g.restoreState();
  48544. }
  48545. if (! (flatOnRight || flatOnTop || flatOnBottom))
  48546. {
  48547. cg.x1 = x + width - edgeBlurRadius;
  48548. cg.x2 = x + width;
  48549. GradientBrush gb (cg);
  48550. g.saveState();
  48551. g.setBrush (&gb);
  48552. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  48553. g.fillPath (outline);
  48554. g.restoreState();
  48555. }
  48556. {
  48557. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  48558. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  48559. Path highlight;
  48560. createRoundedPath (highlight,
  48561. x + leftIndent,
  48562. y + cs * 0.1f,
  48563. width - (leftIndent + rightIndent),
  48564. height * 0.4f, cs * 0.4f,
  48565. ! (flatOnLeft || flatOnTop),
  48566. ! (flatOnRight || flatOnTop),
  48567. ! (flatOnLeft || flatOnBottom),
  48568. ! (flatOnRight || flatOnBottom));
  48569. GradientBrush gb (colour.brighter (10.0f), 0, y + height * 0.06f,
  48570. Colours::transparentWhite, 0, y + height * 0.4f, false);
  48571. g.setBrush (&gb);
  48572. g.fillPath (highlight);
  48573. }
  48574. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  48575. g.strokePath (outline, PathStrokeType (outlineThickness));
  48576. }
  48577. END_JUCE_NAMESPACE
  48578. /********* End of inlined file: juce_LookAndFeel.cpp *********/
  48579. /********* Start of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  48580. BEGIN_JUCE_NAMESPACE
  48581. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  48582. {
  48583. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  48584. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  48585. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  48586. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  48587. setColour (Slider::thumbColourId, Colours::white);
  48588. setColour (Slider::trackColourId, Colour (0x7f000000));
  48589. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  48590. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  48591. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  48592. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  48593. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  48594. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  48595. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  48596. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  48597. }
  48598. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  48599. {
  48600. }
  48601. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  48602. Button& button,
  48603. const Colour& backgroundColour,
  48604. bool isMouseOverButton,
  48605. bool isButtonDown)
  48606. {
  48607. const int width = button.getWidth();
  48608. const int height = button.getHeight();
  48609. const float indent = 2.0f;
  48610. const int cornerSize = jmin (roundFloatToInt (width * 0.4f),
  48611. roundFloatToInt (height * 0.4f));
  48612. Path p;
  48613. p.addRoundedRectangle (indent, indent,
  48614. width - indent * 2.0f,
  48615. height - indent * 2.0f,
  48616. (float) cornerSize);
  48617. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  48618. if (isMouseOverButton)
  48619. {
  48620. if (isButtonDown)
  48621. bc = bc.brighter();
  48622. else if (bc.getBrightness() > 0.5f)
  48623. bc = bc.darker (0.1f);
  48624. else
  48625. bc = bc.brighter (0.1f);
  48626. }
  48627. g.setColour (bc);
  48628. g.fillPath (p);
  48629. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  48630. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  48631. }
  48632. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  48633. Component& /*component*/,
  48634. int x, int y, int w, int h,
  48635. const bool ticked,
  48636. const bool isEnabled,
  48637. const bool /*isMouseOverButton*/,
  48638. const bool isButtonDown)
  48639. {
  48640. Path box;
  48641. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  48642. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  48643. : Colours::lightgrey.withAlpha (0.1f));
  48644. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  48645. .translated ((float) x, (float) y));
  48646. g.fillPath (box, trans);
  48647. g.setColour (Colours::black.withAlpha (0.6f));
  48648. g.strokePath (box, PathStrokeType (0.9f), trans);
  48649. if (ticked)
  48650. {
  48651. Path tick;
  48652. tick.startNewSubPath (1.5f, 3.0f);
  48653. tick.lineTo (3.0f, 6.0f);
  48654. tick.lineTo (6.0f, 0.0f);
  48655. g.setColour (isEnabled ? Colours::black : Colours::grey);
  48656. g.strokePath (tick, PathStrokeType (2.5f), trans);
  48657. }
  48658. }
  48659. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  48660. ToggleButton& button,
  48661. bool isMouseOverButton,
  48662. bool isButtonDown)
  48663. {
  48664. if (button.hasKeyboardFocus (true))
  48665. {
  48666. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  48667. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  48668. }
  48669. const int tickWidth = jmin (20, button.getHeight() - 4);
  48670. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  48671. tickWidth, tickWidth,
  48672. button.getToggleState(),
  48673. button.isEnabled(),
  48674. isMouseOverButton,
  48675. isButtonDown);
  48676. g.setColour (button.findColour (ToggleButton::textColourId));
  48677. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  48678. if (! button.isEnabled())
  48679. g.setOpacity (0.5f);
  48680. const int textX = tickWidth + 5;
  48681. g.drawFittedText (button.getButtonText(),
  48682. textX, 4,
  48683. button.getWidth() - textX - 2, button.getHeight() - 8,
  48684. Justification::centredLeft, 10);
  48685. }
  48686. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  48687. int width, int height,
  48688. double progress, const String& textToShow)
  48689. {
  48690. if (progress < 0 || progress >= 1.0)
  48691. {
  48692. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  48693. }
  48694. else
  48695. {
  48696. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  48697. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  48698. g.fillAll (background);
  48699. g.setColour (foreground);
  48700. g.fillRect (1, 1,
  48701. jlimit (0, width - 2, roundDoubleToInt (progress * (width - 2))),
  48702. height - 2);
  48703. if (textToShow.isNotEmpty())
  48704. {
  48705. g.setColour (Colour::contrasting (background, foreground));
  48706. g.setFont (height * 0.6f);
  48707. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  48708. }
  48709. }
  48710. }
  48711. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  48712. ScrollBar& bar,
  48713. int width, int height,
  48714. int buttonDirection,
  48715. bool isScrollbarVertical,
  48716. bool isMouseOverButton,
  48717. bool isButtonDown)
  48718. {
  48719. if (isScrollbarVertical)
  48720. width -= 2;
  48721. else
  48722. height -= 2;
  48723. Path p;
  48724. if (buttonDirection == 0)
  48725. p.addTriangle (width * 0.5f, height * 0.2f,
  48726. width * 0.1f, height * 0.7f,
  48727. width * 0.9f, height * 0.7f);
  48728. else if (buttonDirection == 1)
  48729. p.addTriangle (width * 0.8f, height * 0.5f,
  48730. width * 0.3f, height * 0.1f,
  48731. width * 0.3f, height * 0.9f);
  48732. else if (buttonDirection == 2)
  48733. p.addTriangle (width * 0.5f, height * 0.8f,
  48734. width * 0.1f, height * 0.3f,
  48735. width * 0.9f, height * 0.3f);
  48736. else if (buttonDirection == 3)
  48737. p.addTriangle (width * 0.2f, height * 0.5f,
  48738. width * 0.7f, height * 0.1f,
  48739. width * 0.7f, height * 0.9f);
  48740. if (isButtonDown)
  48741. g.setColour (Colours::white);
  48742. else if (isMouseOverButton)
  48743. g.setColour (Colours::white.withAlpha (0.7f));
  48744. else
  48745. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  48746. g.fillPath (p);
  48747. g.setColour (Colours::black.withAlpha (0.5f));
  48748. g.strokePath (p, PathStrokeType (0.5f));
  48749. }
  48750. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  48751. ScrollBar& bar,
  48752. int x, int y,
  48753. int width, int height,
  48754. bool isScrollbarVertical,
  48755. int thumbStartPosition,
  48756. int thumbSize,
  48757. bool isMouseOver,
  48758. bool isMouseDown)
  48759. {
  48760. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  48761. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  48762. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  48763. if (thumbSize > 0.0f)
  48764. {
  48765. Rectangle thumb;
  48766. if (isScrollbarVertical)
  48767. {
  48768. width -= 2;
  48769. g.fillRect (x + roundFloatToInt (width * 0.35f), y,
  48770. roundFloatToInt (width * 0.3f), height);
  48771. thumb.setBounds (x + 1, thumbStartPosition,
  48772. width - 2, thumbSize);
  48773. }
  48774. else
  48775. {
  48776. height -= 2;
  48777. g.fillRect (x, y + roundFloatToInt (height * 0.35f),
  48778. width, roundFloatToInt (height * 0.3f));
  48779. thumb.setBounds (thumbStartPosition, y + 1,
  48780. thumbSize, height - 2);
  48781. }
  48782. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  48783. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  48784. g.fillRect (thumb);
  48785. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  48786. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  48787. if (thumbSize > 16)
  48788. {
  48789. for (int i = 3; --i >= 0;)
  48790. {
  48791. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  48792. g.setColour (Colours::black.withAlpha (0.15f));
  48793. if (isScrollbarVertical)
  48794. {
  48795. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  48796. g.setColour (Colours::white.withAlpha (0.15f));
  48797. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  48798. }
  48799. else
  48800. {
  48801. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  48802. g.setColour (Colours::white.withAlpha (0.15f));
  48803. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  48804. }
  48805. }
  48806. }
  48807. }
  48808. }
  48809. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  48810. {
  48811. return &scrollbarShadow;
  48812. }
  48813. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  48814. {
  48815. g.fillAll (findColour (PopupMenu::backgroundColourId));
  48816. g.setColour (Colours::black.withAlpha (0.6f));
  48817. g.drawRect (0, 0, width, height);
  48818. }
  48819. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  48820. bool, MenuBarComponent& menuBar)
  48821. {
  48822. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  48823. }
  48824. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  48825. {
  48826. if (textEditor.isEnabled())
  48827. {
  48828. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  48829. g.drawRect (0, 0, width, height);
  48830. }
  48831. }
  48832. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  48833. const bool isButtonDown,
  48834. int buttonX, int buttonY,
  48835. int buttonW, int buttonH,
  48836. ComboBox& box)
  48837. {
  48838. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  48839. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  48840. : ComboBox::backgroundColourId));
  48841. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  48842. g.setColour (box.findColour (ComboBox::outlineColourId));
  48843. g.drawRect (0, 0, width, height);
  48844. const float arrowX = 0.2f;
  48845. const float arrowH = 0.3f;
  48846. if (box.isEnabled())
  48847. {
  48848. Path p;
  48849. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  48850. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  48851. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  48852. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  48853. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  48854. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  48855. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  48856. : ComboBox::buttonColourId));
  48857. g.fillPath (p);
  48858. }
  48859. }
  48860. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  48861. {
  48862. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  48863. f.setHorizontalScale (0.9f);
  48864. return f;
  48865. }
  48866. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  48867. {
  48868. Path p;
  48869. p.addTriangle (x1, y1, x2, y2, x3, y3);
  48870. g.setColour (fill);
  48871. g.fillPath (p);
  48872. g.setColour (outline);
  48873. g.strokePath (p, PathStrokeType (0.3f));
  48874. }
  48875. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  48876. int x, int y,
  48877. int w, int h,
  48878. float sliderPos,
  48879. float minSliderPos,
  48880. float maxSliderPos,
  48881. const Slider::SliderStyle style,
  48882. Slider& slider)
  48883. {
  48884. g.fillAll (slider.findColour (Slider::backgroundColourId));
  48885. if (style == Slider::LinearBar)
  48886. {
  48887. g.setColour (slider.findColour (Slider::thumbColourId));
  48888. g.fillRect (x, y, (int) sliderPos - x, h);
  48889. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  48890. g.drawRect (x, y, (int) sliderPos - x, h);
  48891. }
  48892. else
  48893. {
  48894. g.setColour (slider.findColour (Slider::trackColourId)
  48895. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  48896. if (slider.isHorizontal())
  48897. {
  48898. g.fillRect (x, y + roundFloatToInt (h * 0.6f),
  48899. w, roundFloatToInt (h * 0.2f));
  48900. }
  48901. else
  48902. {
  48903. g.fillRect (x + roundFloatToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  48904. jmin (4, roundFloatToInt (w * 0.2f)), h);
  48905. }
  48906. float alpha = 0.35f;
  48907. if (slider.isEnabled())
  48908. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  48909. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  48910. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  48911. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  48912. {
  48913. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  48914. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  48915. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  48916. fill, outline);
  48917. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  48918. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  48919. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  48920. fill, outline);
  48921. }
  48922. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  48923. {
  48924. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  48925. minSliderPos - 7.0f, y + h * 0.9f ,
  48926. minSliderPos, y + h * 0.9f,
  48927. fill, outline);
  48928. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  48929. maxSliderPos, y + h * 0.9f,
  48930. maxSliderPos + 7.0f, y + h * 0.9f,
  48931. fill, outline);
  48932. }
  48933. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  48934. {
  48935. drawTriangle (g, sliderPos, y + h * 0.9f,
  48936. sliderPos - 7.0f, y + h * 0.2f,
  48937. sliderPos + 7.0f, y + h * 0.2f,
  48938. fill, outline);
  48939. }
  48940. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  48941. {
  48942. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  48943. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  48944. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  48945. fill, outline);
  48946. }
  48947. }
  48948. }
  48949. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  48950. {
  48951. if (isIncrement)
  48952. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  48953. else
  48954. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  48955. }
  48956. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  48957. {
  48958. return &scrollbarShadow;
  48959. }
  48960. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  48961. {
  48962. return 8;
  48963. }
  48964. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  48965. int w, int h,
  48966. bool isMouseOver,
  48967. bool isMouseDragging)
  48968. {
  48969. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  48970. : Colours::darkgrey);
  48971. const float lineThickness = jmin (w, h) * 0.1f;
  48972. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  48973. {
  48974. g.drawLine (w * i,
  48975. h + 1.0f,
  48976. w + 1.0f,
  48977. h * i,
  48978. lineThickness);
  48979. }
  48980. }
  48981. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  48982. {
  48983. Path shape;
  48984. if (buttonType == DocumentWindow::closeButton)
  48985. {
  48986. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, 0.35f);
  48987. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, 0.35f);
  48988. ShapeButton* const b = new ShapeButton ("close",
  48989. Colour (0x7fff3333),
  48990. Colour (0xd7ff3333),
  48991. Colour (0xf7ff3333));
  48992. b->setShape (shape, true, true, true);
  48993. return b;
  48994. }
  48995. else if (buttonType == DocumentWindow::minimiseButton)
  48996. {
  48997. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  48998. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  48999. DrawablePath dp;
  49000. dp.setPath (shape);
  49001. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  49002. b->setImages (&dp);
  49003. return b;
  49004. }
  49005. else if (buttonType == DocumentWindow::maximiseButton)
  49006. {
  49007. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, 0.25f);
  49008. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  49009. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  49010. DrawablePath dp;
  49011. dp.setPath (shape);
  49012. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  49013. b->setImages (&dp);
  49014. return b;
  49015. }
  49016. jassertfalse
  49017. return 0;
  49018. }
  49019. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  49020. int titleBarX,
  49021. int titleBarY,
  49022. int titleBarW,
  49023. int titleBarH,
  49024. Button* minimiseButton,
  49025. Button* maximiseButton,
  49026. Button* closeButton,
  49027. bool positionTitleBarButtonsOnLeft)
  49028. {
  49029. titleBarY += titleBarH / 8;
  49030. titleBarH -= titleBarH / 4;
  49031. const int buttonW = titleBarH;
  49032. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  49033. : titleBarX + titleBarW - buttonW - 4;
  49034. if (closeButton != 0)
  49035. {
  49036. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  49037. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  49038. : -(buttonW + buttonW / 5);
  49039. }
  49040. if (positionTitleBarButtonsOnLeft)
  49041. swapVariables (minimiseButton, maximiseButton);
  49042. if (maximiseButton != 0)
  49043. {
  49044. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  49045. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  49046. }
  49047. if (minimiseButton != 0)
  49048. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  49049. }
  49050. END_JUCE_NAMESPACE
  49051. /********* End of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  49052. /********* Start of inlined file: juce_MenuBarComponent.cpp *********/
  49053. BEGIN_JUCE_NAMESPACE
  49054. class DummyMenuComponent : public Component
  49055. {
  49056. DummyMenuComponent (const DummyMenuComponent&);
  49057. const DummyMenuComponent& operator= (const DummyMenuComponent&);
  49058. public:
  49059. DummyMenuComponent() {}
  49060. ~DummyMenuComponent() {}
  49061. void inputAttemptWhenModal()
  49062. {
  49063. exitModalState (0);
  49064. }
  49065. };
  49066. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  49067. : model (0),
  49068. itemUnderMouse (-1),
  49069. currentPopupIndex (-1),
  49070. indexToShowAgain (-1),
  49071. lastMouseX (0),
  49072. lastMouseY (0),
  49073. inModalState (false),
  49074. currentPopup (0)
  49075. {
  49076. setRepaintsOnMouseActivity (true);
  49077. setWantsKeyboardFocus (false);
  49078. setMouseClickGrabsKeyboardFocus (false);
  49079. setModel (model_);
  49080. }
  49081. MenuBarComponent::~MenuBarComponent()
  49082. {
  49083. setModel (0);
  49084. Desktop::getInstance().removeGlobalMouseListener (this);
  49085. deleteAndZero (currentPopup);
  49086. }
  49087. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  49088. {
  49089. if (model != newModel)
  49090. {
  49091. if (model != 0)
  49092. model->removeListener (this);
  49093. model = newModel;
  49094. if (model != 0)
  49095. model->addListener (this);
  49096. repaint();
  49097. menuBarItemsChanged (0);
  49098. }
  49099. }
  49100. void MenuBarComponent::paint (Graphics& g)
  49101. {
  49102. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  49103. getLookAndFeel().drawMenuBarBackground (g,
  49104. getWidth(),
  49105. getHeight(),
  49106. isMouseOverBar,
  49107. *this);
  49108. if (model != 0)
  49109. {
  49110. for (int i = 0; i < menuNames.size(); ++i)
  49111. {
  49112. g.saveState();
  49113. g.setOrigin (xPositions [i], 0);
  49114. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  49115. getLookAndFeel().drawMenuBarItem (g,
  49116. xPositions[i + 1] - xPositions[i],
  49117. getHeight(),
  49118. i,
  49119. menuNames[i],
  49120. i == itemUnderMouse,
  49121. i == currentPopupIndex,
  49122. isMouseOverBar,
  49123. *this);
  49124. g.restoreState();
  49125. }
  49126. }
  49127. }
  49128. void MenuBarComponent::resized()
  49129. {
  49130. xPositions.clear();
  49131. int x = 2;
  49132. xPositions.add (x);
  49133. for (int i = 0; i < menuNames.size(); ++i)
  49134. {
  49135. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  49136. xPositions.add (x);
  49137. }
  49138. }
  49139. int MenuBarComponent::getItemAt (const int x, const int y)
  49140. {
  49141. for (int i = 0; i < xPositions.size(); ++i)
  49142. if (x >= xPositions[i] && x < xPositions[i + 1])
  49143. return reallyContains (x, y, true) ? i : -1;
  49144. return -1;
  49145. }
  49146. void MenuBarComponent::repaintMenuItem (int index)
  49147. {
  49148. if (((unsigned int) index) < (unsigned int) xPositions.size())
  49149. {
  49150. const int x1 = xPositions [index];
  49151. const int x2 = xPositions [index + 1];
  49152. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  49153. }
  49154. }
  49155. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  49156. {
  49157. const int newItem = getItemAt (x, y);
  49158. if (itemUnderMouse != newItem)
  49159. {
  49160. repaintMenuItem (itemUnderMouse);
  49161. itemUnderMouse = newItem;
  49162. repaintMenuItem (itemUnderMouse);
  49163. }
  49164. }
  49165. void MenuBarComponent::hideCurrentMenu()
  49166. {
  49167. deleteAndZero (currentPopup);
  49168. repaint();
  49169. }
  49170. void MenuBarComponent::showMenu (int index)
  49171. {
  49172. if (index != currentPopupIndex)
  49173. {
  49174. if (inModalState)
  49175. {
  49176. hideCurrentMenu();
  49177. indexToShowAgain = index;
  49178. return;
  49179. }
  49180. indexToShowAgain = -1;
  49181. currentPopupIndex = -1;
  49182. deleteAndZero (currentPopup);
  49183. menuBarItemsChanged (0);
  49184. Component* const prevFocused = getCurrentlyFocusedComponent();
  49185. ComponentDeletionWatcher* prevCompDeletionChecker = 0;
  49186. if (prevFocused != 0)
  49187. prevCompDeletionChecker = new ComponentDeletionWatcher (prevFocused);
  49188. ComponentDeletionWatcher deletionChecker (this);
  49189. enterModalState (false);
  49190. inModalState = true;
  49191. int result = 0;
  49192. ApplicationCommandManager* managerOfChosenCommand = 0;
  49193. Desktop::getInstance().addGlobalMouseListener (this);
  49194. for (;;)
  49195. {
  49196. const int x = getScreenX() + xPositions [itemUnderMouse];
  49197. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  49198. currentPopupIndex = itemUnderMouse;
  49199. indexToShowAgain = -1;
  49200. repaint();
  49201. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  49202. {
  49203. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  49204. menuNames [itemUnderMouse]));
  49205. currentPopup = m.createMenuComponent (x, getScreenY(),
  49206. w, getHeight(),
  49207. 0, w, 0, 0,
  49208. true, this,
  49209. &managerOfChosenCommand,
  49210. this);
  49211. }
  49212. if (currentPopup == 0)
  49213. {
  49214. currentPopup = new DummyMenuComponent();
  49215. addAndMakeVisible (currentPopup);
  49216. }
  49217. currentPopup->enterModalState (false);
  49218. currentPopup->toFront (false); // need to do this after making it modal, or it could
  49219. // be stuck behind other comps that are already modal..
  49220. result = currentPopup->runModalLoop();
  49221. if (deletionChecker.hasBeenDeleted())
  49222. {
  49223. delete prevCompDeletionChecker;
  49224. return;
  49225. }
  49226. const int lastPopupIndex = currentPopupIndex;
  49227. deleteAndZero (currentPopup);
  49228. currentPopupIndex = -1;
  49229. if (result != 0)
  49230. {
  49231. topLevelIndexClicked = lastPopupIndex;
  49232. break;
  49233. }
  49234. else if (indexToShowAgain >= 0)
  49235. {
  49236. menuBarItemsChanged (0);
  49237. repaint();
  49238. itemUnderMouse = indexToShowAgain;
  49239. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  49240. break;
  49241. }
  49242. else
  49243. {
  49244. break;
  49245. }
  49246. }
  49247. Desktop::getInstance().removeGlobalMouseListener (this);
  49248. inModalState = false;
  49249. exitModalState (0);
  49250. if (prevCompDeletionChecker != 0)
  49251. {
  49252. if (! prevCompDeletionChecker->hasBeenDeleted())
  49253. prevFocused->grabKeyboardFocus();
  49254. delete prevCompDeletionChecker;
  49255. }
  49256. int mx, my;
  49257. getMouseXYRelative (mx, my);
  49258. updateItemUnderMouse (mx, my);
  49259. repaint();
  49260. if (result != 0)
  49261. {
  49262. if (managerOfChosenCommand != 0)
  49263. {
  49264. ApplicationCommandTarget::InvocationInfo info (result);
  49265. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  49266. managerOfChosenCommand->invoke (info, true);
  49267. }
  49268. postCommandMessage (result);
  49269. }
  49270. }
  49271. }
  49272. void MenuBarComponent::handleCommandMessage (int commandId)
  49273. {
  49274. if (model != 0)
  49275. model->menuItemSelected (commandId, topLevelIndexClicked);
  49276. }
  49277. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  49278. {
  49279. if (e.eventComponent == this)
  49280. updateItemUnderMouse (e.x, e.y);
  49281. }
  49282. void MenuBarComponent::mouseExit (const MouseEvent& e)
  49283. {
  49284. if (e.eventComponent == this)
  49285. updateItemUnderMouse (e.x, e.y);
  49286. }
  49287. void MenuBarComponent::mouseDown (const MouseEvent& e)
  49288. {
  49289. const MouseEvent e2 (e.getEventRelativeTo (this));
  49290. if (currentPopupIndex < 0)
  49291. {
  49292. updateItemUnderMouse (e2.x, e2.y);
  49293. currentPopupIndex = -2;
  49294. showMenu (itemUnderMouse);
  49295. }
  49296. }
  49297. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  49298. {
  49299. const MouseEvent e2 (e.getEventRelativeTo (this));
  49300. const int item = getItemAt (e2.x, e2.y);
  49301. if (item >= 0)
  49302. showMenu (item);
  49303. }
  49304. void MenuBarComponent::mouseUp (const MouseEvent& e)
  49305. {
  49306. const MouseEvent e2 (e.getEventRelativeTo (this));
  49307. updateItemUnderMouse (e2.x, e2.y);
  49308. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (currentPopup) != 0)
  49309. hideCurrentMenu();
  49310. }
  49311. void MenuBarComponent::mouseMove (const MouseEvent& e)
  49312. {
  49313. const MouseEvent e2 (e.getEventRelativeTo (this));
  49314. if (lastMouseX != e2.x || lastMouseY != e2.y)
  49315. {
  49316. if (currentPopupIndex >= 0)
  49317. {
  49318. const int item = getItemAt (e2.x, e2.y);
  49319. if (item >= 0)
  49320. showMenu (item);
  49321. }
  49322. else
  49323. {
  49324. updateItemUnderMouse (e2.x, e2.y);
  49325. }
  49326. lastMouseX = e2.x;
  49327. lastMouseY = e2.y;
  49328. }
  49329. }
  49330. bool MenuBarComponent::keyPressed (const KeyPress& key)
  49331. {
  49332. bool used = false;
  49333. const int numMenus = menuNames.size();
  49334. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  49335. if (key.isKeyCode (KeyPress::leftKey))
  49336. {
  49337. showMenu ((currentIndex + numMenus - 1) % numMenus);
  49338. used = true;
  49339. }
  49340. else if (key.isKeyCode (KeyPress::rightKey))
  49341. {
  49342. showMenu ((currentIndex + 1) % numMenus);
  49343. used = true;
  49344. }
  49345. return used;
  49346. }
  49347. void MenuBarComponent::inputAttemptWhenModal()
  49348. {
  49349. hideCurrentMenu();
  49350. }
  49351. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  49352. {
  49353. StringArray newNames;
  49354. if (model != 0)
  49355. newNames = model->getMenuBarNames();
  49356. if (newNames != menuNames)
  49357. {
  49358. menuNames = newNames;
  49359. repaint();
  49360. resized();
  49361. }
  49362. }
  49363. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  49364. const ApplicationCommandTarget::InvocationInfo& info)
  49365. {
  49366. if (model == 0
  49367. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  49368. return;
  49369. for (int i = 0; i < menuNames.size(); ++i)
  49370. {
  49371. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  49372. if (menu.containsCommandItem (info.commandID))
  49373. {
  49374. itemUnderMouse = i;
  49375. repaintMenuItem (i);
  49376. startTimer (200);
  49377. break;
  49378. }
  49379. }
  49380. }
  49381. void MenuBarComponent::timerCallback()
  49382. {
  49383. stopTimer();
  49384. int mx, my;
  49385. getMouseXYRelative (mx, my);
  49386. updateItemUnderMouse (mx, my);
  49387. }
  49388. END_JUCE_NAMESPACE
  49389. /********* End of inlined file: juce_MenuBarComponent.cpp *********/
  49390. /********* Start of inlined file: juce_MenuBarModel.cpp *********/
  49391. BEGIN_JUCE_NAMESPACE
  49392. MenuBarModel::MenuBarModel() throw()
  49393. : manager (0)
  49394. {
  49395. }
  49396. MenuBarModel::~MenuBarModel()
  49397. {
  49398. setApplicationCommandManagerToWatch (0);
  49399. }
  49400. void MenuBarModel::menuItemsChanged()
  49401. {
  49402. triggerAsyncUpdate();
  49403. }
  49404. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  49405. {
  49406. if (manager != newManager)
  49407. {
  49408. if (manager != 0)
  49409. manager->removeListener (this);
  49410. manager = newManager;
  49411. if (manager != 0)
  49412. manager->addListener (this);
  49413. }
  49414. }
  49415. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  49416. {
  49417. jassert (newListener != 0);
  49418. jassert (! listeners.contains (newListener)); // trying to add a listener to the list twice!
  49419. if (newListener != 0)
  49420. listeners.add (newListener);
  49421. }
  49422. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  49423. {
  49424. // Trying to remove a listener that isn't on the list!
  49425. // If this assertion happens because this object is a dangling pointer, make sure you've not
  49426. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  49427. jassert (listeners.contains (listenerToRemove));
  49428. listeners.removeValue (listenerToRemove);
  49429. }
  49430. void MenuBarModel::handleAsyncUpdate()
  49431. {
  49432. for (int i = listeners.size(); --i >= 0;)
  49433. {
  49434. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuBarItemsChanged (this);
  49435. i = jmin (i, listeners.size());
  49436. }
  49437. }
  49438. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  49439. {
  49440. for (int i = listeners.size(); --i >= 0;)
  49441. {
  49442. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuCommandInvoked (this, info);
  49443. i = jmin (i, listeners.size());
  49444. }
  49445. }
  49446. void MenuBarModel::applicationCommandListChanged()
  49447. {
  49448. menuItemsChanged();
  49449. }
  49450. END_JUCE_NAMESPACE
  49451. /********* End of inlined file: juce_MenuBarModel.cpp *********/
  49452. /********* Start of inlined file: juce_PopupMenu.cpp *********/
  49453. BEGIN_JUCE_NAMESPACE
  49454. static VoidArray activeMenuWindows;
  49455. class MenuItemInfo
  49456. {
  49457. public:
  49458. const int itemId;
  49459. String text;
  49460. const Colour textColour;
  49461. const bool active, isSeparator, isTicked, usesColour;
  49462. Image* image;
  49463. PopupMenuCustomComponent* const customComp;
  49464. PopupMenu* subMenu;
  49465. ApplicationCommandManager* const commandManager;
  49466. MenuItemInfo() throw()
  49467. : itemId (0),
  49468. active (true),
  49469. isSeparator (true),
  49470. isTicked (false),
  49471. usesColour (false),
  49472. image (0),
  49473. customComp (0),
  49474. subMenu (0),
  49475. commandManager (0)
  49476. {
  49477. }
  49478. MenuItemInfo (const int itemId_,
  49479. const String& text_,
  49480. const bool active_,
  49481. const bool isTicked_,
  49482. const Image* im,
  49483. const Colour& textColour_,
  49484. const bool usesColour_,
  49485. PopupMenuCustomComponent* const customComp_,
  49486. const PopupMenu* const subMenu_,
  49487. ApplicationCommandManager* const commandManager_) throw()
  49488. : itemId (itemId_),
  49489. text (text_),
  49490. textColour (textColour_),
  49491. active (active_),
  49492. isSeparator (false),
  49493. isTicked (isTicked_),
  49494. usesColour (usesColour_),
  49495. image (0),
  49496. customComp (customComp_),
  49497. commandManager (commandManager_)
  49498. {
  49499. subMenu = (subMenu_ != 0) ? new PopupMenu (*subMenu_) : 0;
  49500. if (customComp != 0)
  49501. customComp->refCount_++;
  49502. if (im != 0)
  49503. image = im->createCopy();
  49504. if (commandManager_ != 0 && itemId_ != 0)
  49505. {
  49506. String shortcutKey;
  49507. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  49508. ->getKeyPressesAssignedToCommand (itemId_));
  49509. for (int i = 0; i < keyPresses.size(); ++i)
  49510. {
  49511. const String key (keyPresses.getReference(i).getTextDescription());
  49512. if (shortcutKey.isNotEmpty())
  49513. shortcutKey << ", ";
  49514. if (key.length() == 1)
  49515. shortcutKey << "shortcut: '" << key << '\'';
  49516. else
  49517. shortcutKey << key;
  49518. }
  49519. shortcutKey = shortcutKey.trim();
  49520. if (shortcutKey.isNotEmpty())
  49521. text << "<end>" << shortcutKey;
  49522. }
  49523. }
  49524. MenuItemInfo (const MenuItemInfo& other) throw()
  49525. : itemId (other.itemId),
  49526. text (other.text),
  49527. textColour (other.textColour),
  49528. active (other.active),
  49529. isSeparator (other.isSeparator),
  49530. isTicked (other.isTicked),
  49531. usesColour (other.usesColour),
  49532. customComp (other.customComp),
  49533. commandManager (other.commandManager)
  49534. {
  49535. if (other.subMenu != 0)
  49536. subMenu = new PopupMenu (*(other.subMenu));
  49537. else
  49538. subMenu = 0;
  49539. if (other.image != 0)
  49540. image = other.image->createCopy();
  49541. else
  49542. image = 0;
  49543. if (customComp != 0)
  49544. customComp->refCount_++;
  49545. }
  49546. ~MenuItemInfo() throw()
  49547. {
  49548. delete subMenu;
  49549. delete image;
  49550. if (customComp != 0 && --(customComp->refCount_) == 0)
  49551. delete customComp;
  49552. }
  49553. bool canBeTriggered() const throw()
  49554. {
  49555. return active && ! (isSeparator || (subMenu != 0));
  49556. }
  49557. bool hasActiveSubMenu() const throw()
  49558. {
  49559. return active && (subMenu != 0);
  49560. }
  49561. juce_UseDebuggingNewOperator
  49562. private:
  49563. const MenuItemInfo& operator= (const MenuItemInfo&);
  49564. };
  49565. class MenuItemComponent : public Component
  49566. {
  49567. bool isHighlighted;
  49568. public:
  49569. MenuItemInfo itemInfo;
  49570. MenuItemComponent (const MenuItemInfo& itemInfo_)
  49571. : isHighlighted (false),
  49572. itemInfo (itemInfo_)
  49573. {
  49574. if (itemInfo.customComp != 0)
  49575. addAndMakeVisible (itemInfo.customComp);
  49576. }
  49577. ~MenuItemComponent()
  49578. {
  49579. if (itemInfo.customComp != 0)
  49580. removeChildComponent (itemInfo.customComp);
  49581. }
  49582. void getIdealSize (int& idealWidth,
  49583. int& idealHeight,
  49584. const int standardItemHeight)
  49585. {
  49586. if (itemInfo.customComp != 0)
  49587. {
  49588. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  49589. }
  49590. else
  49591. {
  49592. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  49593. itemInfo.isSeparator,
  49594. standardItemHeight,
  49595. idealWidth,
  49596. idealHeight);
  49597. }
  49598. }
  49599. void paint (Graphics& g)
  49600. {
  49601. if (itemInfo.customComp == 0)
  49602. {
  49603. String mainText (itemInfo.text);
  49604. String endText;
  49605. const int endIndex = mainText.indexOf (T("<end>"));
  49606. if (endIndex >= 0)
  49607. {
  49608. endText = mainText.substring (endIndex + 5).trim();
  49609. mainText = mainText.substring (0, endIndex);
  49610. }
  49611. getLookAndFeel()
  49612. .drawPopupMenuItem (g, getWidth(), getHeight(),
  49613. itemInfo.isSeparator,
  49614. itemInfo.active,
  49615. isHighlighted,
  49616. itemInfo.isTicked,
  49617. itemInfo.subMenu != 0,
  49618. mainText, endText,
  49619. itemInfo.image,
  49620. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  49621. }
  49622. }
  49623. void resized()
  49624. {
  49625. if (getNumChildComponents() > 0)
  49626. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  49627. }
  49628. void setHighlighted (bool shouldBeHighlighted)
  49629. {
  49630. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  49631. if (isHighlighted != shouldBeHighlighted)
  49632. {
  49633. isHighlighted = shouldBeHighlighted;
  49634. if (itemInfo.customComp != 0)
  49635. {
  49636. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  49637. itemInfo.customComp->repaint();
  49638. }
  49639. repaint();
  49640. }
  49641. }
  49642. private:
  49643. MenuItemComponent (const MenuItemComponent&);
  49644. const MenuItemComponent& operator= (const MenuItemComponent&);
  49645. };
  49646. static const int scrollZone = 24;
  49647. static const int borderSize = 2;
  49648. static const int timerInterval = 50;
  49649. static const int dismissCommandId = 0x6287345f;
  49650. static bool wasHiddenBecauseOfAppChange = false;
  49651. class PopupMenuWindow : public Component,
  49652. private Timer
  49653. {
  49654. public:
  49655. PopupMenuWindow() throw()
  49656. : Component (T("menu")),
  49657. owner (0),
  49658. currentChild (0),
  49659. activeSubMenu (0),
  49660. menuBarComponent (0),
  49661. managerOfChosenCommand (0),
  49662. componentAttachedTo (0),
  49663. attachedCompWatcher (0),
  49664. lastMouseX (0),
  49665. lastMouseY (0),
  49666. minimumWidth (0),
  49667. maximumNumColumns (7),
  49668. standardItemHeight (0),
  49669. isOver (false),
  49670. hasBeenOver (false),
  49671. isDown (false),
  49672. needsToScroll (false),
  49673. hideOnExit (false),
  49674. disableMouseMoves (false),
  49675. hasAnyJuceCompHadFocus (false),
  49676. numColumns (0),
  49677. contentHeight (0),
  49678. childYOffset (0),
  49679. timeEnteredCurrentChildComp (0),
  49680. scrollAcceleration (1.0)
  49681. {
  49682. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  49683. setWantsKeyboardFocus (true);
  49684. setOpaque (true);
  49685. setAlwaysOnTop (true);
  49686. Desktop::getInstance().addGlobalMouseListener (this);
  49687. activeMenuWindows.add (this);
  49688. }
  49689. ~PopupMenuWindow()
  49690. {
  49691. activeMenuWindows.removeValue (this);
  49692. Desktop::getInstance().removeGlobalMouseListener (this);
  49693. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  49694. delete activeSubMenu;
  49695. deleteAllChildren();
  49696. delete attachedCompWatcher;
  49697. }
  49698. static PopupMenuWindow* create (const PopupMenu& menu,
  49699. const bool dismissOnMouseUp,
  49700. PopupMenuWindow* const owner_,
  49701. const int minX, const int maxX,
  49702. const int minY, const int maxY,
  49703. const int minimumWidth,
  49704. const int maximumNumColumns,
  49705. const int standardItemHeight,
  49706. const bool alignToRectangle,
  49707. const int itemIdThatMustBeVisible,
  49708. Component* const menuBarComponent,
  49709. ApplicationCommandManager** managerOfChosenCommand,
  49710. Component* const componentAttachedTo) throw()
  49711. {
  49712. if (menu.items.size() > 0)
  49713. {
  49714. int totalItems = 0;
  49715. PopupMenuWindow* const mw = new PopupMenuWindow();
  49716. mw->setLookAndFeel (menu.lookAndFeel);
  49717. mw->setWantsKeyboardFocus (false);
  49718. mw->minimumWidth = minimumWidth;
  49719. mw->maximumNumColumns = maximumNumColumns;
  49720. mw->standardItemHeight = standardItemHeight;
  49721. mw->dismissOnMouseUp = dismissOnMouseUp;
  49722. for (int i = 0; i < menu.items.size(); ++i)
  49723. {
  49724. MenuItemInfo* const item = (MenuItemInfo*) menu.items.getUnchecked(i);
  49725. mw->addItem (*item);
  49726. ++totalItems;
  49727. }
  49728. if (totalItems == 0)
  49729. {
  49730. delete mw;
  49731. }
  49732. else
  49733. {
  49734. mw->owner = owner_;
  49735. mw->menuBarComponent = menuBarComponent;
  49736. mw->managerOfChosenCommand = managerOfChosenCommand;
  49737. mw->componentAttachedTo = componentAttachedTo;
  49738. delete mw->attachedCompWatcher;
  49739. mw->attachedCompWatcher = componentAttachedTo != 0 ? new ComponentDeletionWatcher (componentAttachedTo) : 0;
  49740. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  49741. mw->setTopLeftPosition (mw->windowPos.getX(),
  49742. mw->windowPos.getY());
  49743. mw->updateYPositions();
  49744. if (itemIdThatMustBeVisible != 0)
  49745. {
  49746. const int y = minY - mw->windowPos.getY();
  49747. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  49748. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  49749. }
  49750. mw->resizeToBestWindowPos();
  49751. mw->addToDesktop (ComponentPeer::windowIsTemporary
  49752. | mw->getLookAndFeel().getMenuWindowFlags());
  49753. return mw;
  49754. }
  49755. }
  49756. return 0;
  49757. }
  49758. void paint (Graphics& g)
  49759. {
  49760. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  49761. }
  49762. void paintOverChildren (Graphics& g)
  49763. {
  49764. if (isScrolling())
  49765. {
  49766. LookAndFeel& lf = getLookAndFeel();
  49767. if (isScrollZoneActive (false))
  49768. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, true);
  49769. if (isScrollZoneActive (true))
  49770. {
  49771. g.setOrigin (0, getHeight() - scrollZone);
  49772. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, false);
  49773. }
  49774. }
  49775. }
  49776. bool isScrollZoneActive (bool bottomOne) const
  49777. {
  49778. return isScrolling()
  49779. && (bottomOne
  49780. ? childYOffset < contentHeight - windowPos.getHeight()
  49781. : childYOffset > 0);
  49782. }
  49783. void addItem (const MenuItemInfo& item) throw()
  49784. {
  49785. MenuItemComponent* const mic = new MenuItemComponent (item);
  49786. addAndMakeVisible (mic);
  49787. int itemW = 80;
  49788. int itemH = 16;
  49789. mic->getIdealSize (itemW, itemH, standardItemHeight);
  49790. mic->setSize (itemW, jlimit (10, 600, itemH));
  49791. mic->addMouseListener (this, false);
  49792. }
  49793. // hide this and all sub-comps
  49794. void hide (const MenuItemInfo* const item) throw()
  49795. {
  49796. if (isVisible())
  49797. {
  49798. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  49799. deleteAndZero (activeSubMenu);
  49800. currentChild = 0;
  49801. exitModalState (item != 0 ? item->itemId : 0);
  49802. setVisible (false);
  49803. if (item != 0
  49804. && item->commandManager != 0
  49805. && item->itemId != 0)
  49806. {
  49807. *managerOfChosenCommand = item->commandManager;
  49808. }
  49809. }
  49810. }
  49811. void dismissMenu (const MenuItemInfo* const item) throw()
  49812. {
  49813. if (owner != 0)
  49814. {
  49815. owner->dismissMenu (item);
  49816. }
  49817. else
  49818. {
  49819. if (item != 0)
  49820. {
  49821. // need a copy of this on the stack as the one passed in will get deleted during this call
  49822. const MenuItemInfo mi (*item);
  49823. hide (&mi);
  49824. }
  49825. else
  49826. {
  49827. hide (0);
  49828. }
  49829. }
  49830. }
  49831. void mouseMove (const MouseEvent&)
  49832. {
  49833. timerCallback();
  49834. }
  49835. void mouseDown (const MouseEvent&)
  49836. {
  49837. timerCallback();
  49838. }
  49839. void mouseDrag (const MouseEvent&)
  49840. {
  49841. timerCallback();
  49842. }
  49843. void mouseUp (const MouseEvent&)
  49844. {
  49845. timerCallback();
  49846. }
  49847. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  49848. {
  49849. alterChildYPos (roundFloatToInt (-10.0f * amountY * scrollZone));
  49850. lastMouseX = -1;
  49851. }
  49852. bool keyPressed (const KeyPress& key)
  49853. {
  49854. if (key.isKeyCode (KeyPress::downKey))
  49855. {
  49856. selectNextItem (1);
  49857. }
  49858. else if (key.isKeyCode (KeyPress::upKey))
  49859. {
  49860. selectNextItem (-1);
  49861. }
  49862. else if (key.isKeyCode (KeyPress::leftKey))
  49863. {
  49864. PopupMenuWindow* parentWindow = owner;
  49865. if (parentWindow != 0)
  49866. {
  49867. MenuItemComponent* currentChildOfParent
  49868. = (parentWindow != 0) ? parentWindow->currentChild : 0;
  49869. hide (0);
  49870. if (parentWindow->isValidComponent())
  49871. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  49872. disableTimerUntilMouseMoves();
  49873. }
  49874. else if (menuBarComponent != 0)
  49875. {
  49876. menuBarComponent->keyPressed (key);
  49877. }
  49878. }
  49879. else if (key.isKeyCode (KeyPress::rightKey))
  49880. {
  49881. disableTimerUntilMouseMoves();
  49882. if (showSubMenuFor (currentChild))
  49883. {
  49884. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  49885. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  49886. activeSubMenu->selectNextItem (1);
  49887. }
  49888. else if (menuBarComponent != 0)
  49889. {
  49890. menuBarComponent->keyPressed (key);
  49891. }
  49892. }
  49893. else if (key.isKeyCode (KeyPress::returnKey))
  49894. {
  49895. triggerCurrentlyHighlightedItem();
  49896. }
  49897. else if (key.isKeyCode (KeyPress::escapeKey))
  49898. {
  49899. dismissMenu (0);
  49900. }
  49901. else
  49902. {
  49903. return false;
  49904. }
  49905. return true;
  49906. }
  49907. void inputAttemptWhenModal()
  49908. {
  49909. timerCallback();
  49910. if (! isOverAnyMenu())
  49911. {
  49912. if (componentAttachedTo != 0 && ! attachedCompWatcher->hasBeenDeleted())
  49913. {
  49914. // we want to dismiss the menu, but if we do it synchronously, then
  49915. // the mouse-click will be allowed to pass through. That's good, except
  49916. // when the user clicks on the button that orginally popped the menu up,
  49917. // as they'll expect the menu to go away, and in fact it'll just
  49918. // come back. So only dismiss synchronously if they're not on the original
  49919. // comp that we're attached to.
  49920. int mx, my;
  49921. componentAttachedTo->getMouseXYRelative (mx, my);
  49922. if (componentAttachedTo->reallyContains (mx, my, true))
  49923. {
  49924. postCommandMessage (dismissCommandId); // dismiss asynchrounously
  49925. return;
  49926. }
  49927. }
  49928. dismissMenu (0);
  49929. }
  49930. }
  49931. void handleCommandMessage (int commandId)
  49932. {
  49933. Component::handleCommandMessage (commandId);
  49934. if (commandId == dismissCommandId)
  49935. dismissMenu (0);
  49936. }
  49937. void timerCallback()
  49938. {
  49939. if (! isVisible())
  49940. return;
  49941. if (attachedCompWatcher != 0 && attachedCompWatcher->hasBeenDeleted())
  49942. {
  49943. dismissMenu (0);
  49944. return;
  49945. }
  49946. PopupMenuWindow* currentlyModalWindow = dynamic_cast <PopupMenuWindow*> (Component::getCurrentlyModalComponent());
  49947. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  49948. return;
  49949. startTimer (timerInterval); // do this in case it was called from a mouse
  49950. // move rather than a real timer callback
  49951. int mx, my;
  49952. Desktop::getMousePosition (mx, my);
  49953. int x = mx, y = my;
  49954. globalPositionToRelative (x, y);
  49955. const uint32 now = Time::getMillisecondCounter();
  49956. if (now > timeEnteredCurrentChildComp + 100
  49957. && reallyContains (x, y, true)
  49958. && currentChild->isValidComponent()
  49959. && (! disableMouseMoves)
  49960. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  49961. {
  49962. showSubMenuFor (currentChild);
  49963. }
  49964. if (mx != lastMouseX || my != lastMouseY || now > lastMouseMoveTime + 350)
  49965. {
  49966. highlightItemUnderMouse (mx, my, x, y);
  49967. }
  49968. bool overScrollArea = false;
  49969. if (isScrolling()
  49970. && (isOver || (isDown && ((unsigned int) x) < (unsigned int) getWidth()))
  49971. && ((isScrollZoneActive (false) && y < scrollZone)
  49972. || (isScrollZoneActive (true) && y > getHeight() - scrollZone)))
  49973. {
  49974. if (now > lastScroll + 20)
  49975. {
  49976. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  49977. int amount = 0;
  49978. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  49979. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  49980. alterChildYPos (y < scrollZone ? -amount : amount);
  49981. lastScroll = now;
  49982. }
  49983. overScrollArea = true;
  49984. lastMouseX = -1; // trigger a mouse-move
  49985. }
  49986. else
  49987. {
  49988. scrollAcceleration = 1.0;
  49989. }
  49990. const bool wasDown = isDown;
  49991. bool isOverAny = isOverAnyMenu();
  49992. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  49993. {
  49994. activeSubMenu->updateMouseOverStatus (mx, my);
  49995. isOverAny = isOverAnyMenu();
  49996. }
  49997. if (hideOnExit && hasBeenOver && ! isOverAny)
  49998. {
  49999. hide (0);
  50000. }
  50001. else
  50002. {
  50003. isDown = hasBeenOver
  50004. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  50005. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  50006. bool anyFocused = Process::isForegroundProcess();
  50007. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  50008. {
  50009. // because no component at all may have focus, our test here will
  50010. // only be triggered when something has focus and then loses it.
  50011. anyFocused = ! hasAnyJuceCompHadFocus;
  50012. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  50013. {
  50014. if (ComponentPeer::getPeer (i)->isFocused())
  50015. {
  50016. anyFocused = true;
  50017. hasAnyJuceCompHadFocus = true;
  50018. break;
  50019. }
  50020. }
  50021. }
  50022. if (! anyFocused)
  50023. {
  50024. if (now > lastFocused + 10)
  50025. {
  50026. wasHiddenBecauseOfAppChange = true;
  50027. dismissMenu (0);
  50028. return; // may have been deleted by the previous call..
  50029. }
  50030. }
  50031. else if (wasDown && now > menuCreationTime + 250
  50032. && ! (isDown || overScrollArea))
  50033. {
  50034. isOver = reallyContains (x, y, true);
  50035. if (isOver)
  50036. {
  50037. triggerCurrentlyHighlightedItem();
  50038. }
  50039. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  50040. {
  50041. dismissMenu (0);
  50042. }
  50043. return; // may have been deleted by the previous calls..
  50044. }
  50045. else
  50046. {
  50047. lastFocused = now;
  50048. }
  50049. }
  50050. }
  50051. juce_UseDebuggingNewOperator
  50052. private:
  50053. PopupMenuWindow* owner;
  50054. MenuItemComponent* currentChild;
  50055. PopupMenuWindow* activeSubMenu;
  50056. Component* menuBarComponent;
  50057. ApplicationCommandManager** managerOfChosenCommand;
  50058. Component* componentAttachedTo;
  50059. ComponentDeletionWatcher* attachedCompWatcher;
  50060. Rectangle windowPos;
  50061. int lastMouseX, lastMouseY;
  50062. int minimumWidth, maximumNumColumns, standardItemHeight;
  50063. bool isOver, hasBeenOver, isDown, needsToScroll;
  50064. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  50065. int numColumns, contentHeight, childYOffset;
  50066. Array <int> columnWidths;
  50067. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  50068. double scrollAcceleration;
  50069. bool overlaps (const Rectangle& r) const throw()
  50070. {
  50071. return r.intersects (getBounds())
  50072. || (owner != 0 && owner->overlaps (r));
  50073. }
  50074. bool isOverAnyMenu() const throw()
  50075. {
  50076. return (owner != 0) ? owner->isOverAnyMenu()
  50077. : isOverChildren();
  50078. }
  50079. bool isOverChildren() const throw()
  50080. {
  50081. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  50082. return isVisible()
  50083. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  50084. }
  50085. void updateMouseOverStatus (const int mx, const int my) throw()
  50086. {
  50087. int rx = mx, ry = my;
  50088. globalPositionToRelative (rx, ry);
  50089. isOver = reallyContains (rx, ry, true);
  50090. if (activeSubMenu != 0)
  50091. activeSubMenu->updateMouseOverStatus (mx, my);
  50092. }
  50093. bool treeContains (const PopupMenuWindow* const window) const throw()
  50094. {
  50095. const PopupMenuWindow* mw = this;
  50096. while (mw->owner != 0)
  50097. mw = mw->owner;
  50098. while (mw != 0)
  50099. {
  50100. if (mw == window)
  50101. return true;
  50102. mw = mw->activeSubMenu;
  50103. }
  50104. return false;
  50105. }
  50106. void calculateWindowPos (const int minX, const int maxX,
  50107. const int minY, const int maxY,
  50108. const bool alignToRectangle)
  50109. {
  50110. const Rectangle mon (Desktop::getInstance()
  50111. .getMonitorAreaContaining ((minX + maxX) / 2,
  50112. (minY + maxY) / 2,
  50113. true));
  50114. int x, y, widthToUse, heightToUse;
  50115. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  50116. if (alignToRectangle)
  50117. {
  50118. x = minX;
  50119. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  50120. const int spaceOver = minY - mon.getY();
  50121. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  50122. y = maxY;
  50123. else
  50124. y = minY - heightToUse;
  50125. }
  50126. else
  50127. {
  50128. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  50129. if (owner != 0)
  50130. {
  50131. if (owner->owner != 0)
  50132. {
  50133. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  50134. > owner->owner->getX() + owner->owner->getWidth() / 2);
  50135. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  50136. tendTowardsRight = true;
  50137. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  50138. tendTowardsRight = false;
  50139. }
  50140. else if (maxX + widthToUse < mon.getRight() - 32)
  50141. {
  50142. tendTowardsRight = true;
  50143. }
  50144. }
  50145. const int biggestSpace = jmax (mon.getRight() - maxX,
  50146. minX - mon.getX()) - 32;
  50147. if (biggestSpace < widthToUse)
  50148. {
  50149. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  50150. if (numColumns > 1)
  50151. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  50152. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  50153. }
  50154. if (tendTowardsRight)
  50155. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  50156. else
  50157. x = jmax (mon.getX() + 4, minX - widthToUse);
  50158. y = minY;
  50159. if ((minY + maxY) / 2 > mon.getCentreY())
  50160. y = jmax (mon.getY(), maxY - heightToUse);
  50161. }
  50162. x = jlimit (mon.getX() + 1, mon.getRight() - (widthToUse + 6), x);
  50163. y = jlimit (mon.getY() + 1, mon.getBottom() - (heightToUse + 6), y);
  50164. windowPos.setBounds (x, y, widthToUse, heightToUse);
  50165. // sets this flag if it's big enough to obscure any of its parent menus
  50166. hideOnExit = (owner != 0)
  50167. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  50168. }
  50169. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  50170. {
  50171. numColumns = 0;
  50172. contentHeight = 0;
  50173. const int maxMenuH = getParentHeight() - 24;
  50174. int totalW;
  50175. do
  50176. {
  50177. ++numColumns;
  50178. totalW = workOutBestSize (numColumns, maxMenuW);
  50179. if (totalW > maxMenuW)
  50180. {
  50181. numColumns = jmax (1, numColumns - 1);
  50182. totalW = workOutBestSize (numColumns, maxMenuW); // to update col widths
  50183. break;
  50184. }
  50185. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  50186. {
  50187. break;
  50188. }
  50189. } while (numColumns < maximumNumColumns);
  50190. const int actualH = jmin (contentHeight, maxMenuH);
  50191. needsToScroll = contentHeight > actualH;
  50192. width = updateYPositions();
  50193. height = actualH + borderSize * 2;
  50194. }
  50195. int workOutBestSize (const int numColumns, const int maxMenuW)
  50196. {
  50197. int totalW = 0;
  50198. contentHeight = 0;
  50199. int childNum = 0;
  50200. for (int col = 0; col < numColumns; ++col)
  50201. {
  50202. int i, colW = 50, colH = 0;
  50203. const int numChildren = jmin (getNumChildComponents() - childNum,
  50204. (getNumChildComponents() + numColumns - 1) / numColumns);
  50205. for (i = numChildren; --i >= 0;)
  50206. {
  50207. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  50208. colH += getChildComponent (childNum + i)->getHeight();
  50209. }
  50210. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + borderSize * 2);
  50211. columnWidths.set (col, colW);
  50212. totalW += colW;
  50213. contentHeight = jmax (contentHeight, colH);
  50214. childNum += numChildren;
  50215. }
  50216. if (totalW < minimumWidth)
  50217. {
  50218. totalW = minimumWidth;
  50219. for (int col = 0; col < numColumns; ++col)
  50220. columnWidths.set (0, totalW / numColumns);
  50221. }
  50222. return totalW;
  50223. }
  50224. void ensureItemIsVisible (const int itemId, int wantedY)
  50225. {
  50226. jassert (itemId != 0)
  50227. for (int i = getNumChildComponents(); --i >= 0;)
  50228. {
  50229. MenuItemComponent* const m = (MenuItemComponent*) getChildComponent (i);
  50230. if (m != 0
  50231. && m->itemInfo.itemId == itemId
  50232. && windowPos.getHeight() > scrollZone * 4)
  50233. {
  50234. const int currentY = m->getY();
  50235. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  50236. {
  50237. if (wantedY < 0)
  50238. wantedY = jlimit (scrollZone,
  50239. jmax (scrollZone, windowPos.getHeight() - (scrollZone + m->getHeight())),
  50240. currentY);
  50241. const Rectangle mon (Desktop::getInstance()
  50242. .getMonitorAreaContaining (windowPos.getX(),
  50243. windowPos.getY(),
  50244. true));
  50245. int deltaY = wantedY - currentY;
  50246. const int newY = jlimit (mon.getY(),
  50247. mon.getBottom() - windowPos.getHeight(),
  50248. windowPos.getY() + deltaY);
  50249. deltaY -= newY - windowPos.getY();
  50250. childYOffset -= deltaY;
  50251. windowPos.setPosition (windowPos.getX(), newY);
  50252. updateYPositions();
  50253. }
  50254. break;
  50255. }
  50256. }
  50257. }
  50258. void resizeToBestWindowPos()
  50259. {
  50260. Rectangle r (windowPos);
  50261. if (childYOffset < 0)
  50262. {
  50263. r.setBounds (r.getX(), r.getY() - childYOffset,
  50264. r.getWidth(), r.getHeight() + childYOffset);
  50265. }
  50266. else if (childYOffset > 0)
  50267. {
  50268. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  50269. if (spaceAtBottom > 0)
  50270. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  50271. }
  50272. setBounds (r);
  50273. updateYPositions();
  50274. }
  50275. void alterChildYPos (const int delta)
  50276. {
  50277. if (isScrolling())
  50278. {
  50279. childYOffset += delta;
  50280. if (delta < 0)
  50281. {
  50282. childYOffset = jmax (childYOffset, 0);
  50283. }
  50284. else if (delta > 0)
  50285. {
  50286. childYOffset = jmin (childYOffset,
  50287. contentHeight - windowPos.getHeight() + borderSize);
  50288. }
  50289. updateYPositions();
  50290. }
  50291. else
  50292. {
  50293. childYOffset = 0;
  50294. }
  50295. resizeToBestWindowPos();
  50296. repaint();
  50297. }
  50298. int updateYPositions()
  50299. {
  50300. int x = 0;
  50301. int childNum = 0;
  50302. for (int col = 0; col < numColumns; ++col)
  50303. {
  50304. const int numChildren = jmin (getNumChildComponents() - childNum,
  50305. (getNumChildComponents() + numColumns - 1) / numColumns);
  50306. const int colW = columnWidths [col];
  50307. int y = borderSize - (childYOffset + (getY() - windowPos.getY()));
  50308. for (int i = 0; i < numChildren; ++i)
  50309. {
  50310. Component* const c = getChildComponent (childNum + i);
  50311. c->setBounds (x, y, colW, c->getHeight());
  50312. y += c->getHeight();
  50313. }
  50314. x += colW;
  50315. childNum += numChildren;
  50316. }
  50317. return x;
  50318. }
  50319. bool isScrolling() const throw()
  50320. {
  50321. return childYOffset != 0 || needsToScroll;
  50322. }
  50323. void setCurrentlyHighlightedChild (MenuItemComponent* const child) throw()
  50324. {
  50325. if (currentChild->isValidComponent())
  50326. currentChild->setHighlighted (false);
  50327. currentChild = child;
  50328. if (currentChild != 0)
  50329. {
  50330. currentChild->setHighlighted (true);
  50331. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  50332. }
  50333. }
  50334. bool showSubMenuFor (MenuItemComponent* const childComp)
  50335. {
  50336. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  50337. deleteAndZero (activeSubMenu);
  50338. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  50339. {
  50340. int left = 0, top = 0;
  50341. childComp->relativePositionToGlobal (left, top);
  50342. int right = childComp->getWidth(), bottom = childComp->getHeight();
  50343. childComp->relativePositionToGlobal (right, bottom);
  50344. activeSubMenu = PopupMenuWindow::create (*(childComp->itemInfo.subMenu),
  50345. dismissOnMouseUp,
  50346. this,
  50347. left, right, top, bottom,
  50348. 0, maximumNumColumns,
  50349. standardItemHeight,
  50350. false, 0, menuBarComponent,
  50351. managerOfChosenCommand,
  50352. componentAttachedTo);
  50353. if (activeSubMenu != 0)
  50354. {
  50355. activeSubMenu->setVisible (true);
  50356. activeSubMenu->enterModalState (false);
  50357. activeSubMenu->toFront (false);
  50358. return true;
  50359. }
  50360. }
  50361. return false;
  50362. }
  50363. void highlightItemUnderMouse (const int mx, const int my, const int x, const int y)
  50364. {
  50365. isOver = reallyContains (x, y, true);
  50366. if (isOver)
  50367. hasBeenOver = true;
  50368. if (abs (lastMouseX - mx) > 2 || abs (lastMouseY - my) > 2)
  50369. {
  50370. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  50371. if (disableMouseMoves && isOver)
  50372. disableMouseMoves = false;
  50373. }
  50374. if (disableMouseMoves)
  50375. return;
  50376. bool isMovingTowardsMenu = false;
  50377. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  50378. if (isOver && (activeSubMenu != 0) && (mx != lastMouseX || my != lastMouseY))
  50379. {
  50380. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  50381. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  50382. // extends from the last mouse pos to the submenu's rectangle..
  50383. float subX = (float) activeSubMenu->getScreenX();
  50384. if (activeSubMenu->getX() > getX())
  50385. {
  50386. lastMouseX -= 2; // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  50387. }
  50388. else
  50389. {
  50390. lastMouseX += 2;
  50391. subX += activeSubMenu->getWidth();
  50392. }
  50393. Path areaTowardsSubMenu;
  50394. areaTowardsSubMenu.addTriangle ((float) lastMouseX,
  50395. (float) lastMouseY,
  50396. subX,
  50397. (float) activeSubMenu->getScreenY(),
  50398. subX,
  50399. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  50400. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) mx, (float) my);
  50401. }
  50402. lastMouseX = mx;
  50403. lastMouseY = my;
  50404. if (! isMovingTowardsMenu)
  50405. {
  50406. Component* c = getComponentAt (x, y);
  50407. if (c == this)
  50408. c = 0;
  50409. MenuItemComponent* mic = dynamic_cast <MenuItemComponent*> (c);
  50410. if (mic == 0 && c != 0)
  50411. mic = c->findParentComponentOfClass ((MenuItemComponent*) 0);
  50412. if (mic != currentChild
  50413. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  50414. {
  50415. if (isOver && (c != 0) && (activeSubMenu != 0))
  50416. {
  50417. activeSubMenu->hide (0);
  50418. }
  50419. if (! isOver)
  50420. mic = 0;
  50421. setCurrentlyHighlightedChild (mic);
  50422. }
  50423. }
  50424. }
  50425. void triggerCurrentlyHighlightedItem()
  50426. {
  50427. if (currentChild->isValidComponent()
  50428. && currentChild->itemInfo.canBeTriggered()
  50429. && (currentChild->itemInfo.customComp == 0
  50430. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  50431. {
  50432. dismissMenu (&currentChild->itemInfo);
  50433. }
  50434. }
  50435. void selectNextItem (const int delta)
  50436. {
  50437. disableTimerUntilMouseMoves();
  50438. MenuItemComponent* mic = 0;
  50439. bool wasLastOne = (currentChild == 0);
  50440. const int numItems = getNumChildComponents();
  50441. for (int i = 0; i < numItems + 1; ++i)
  50442. {
  50443. int index = (delta > 0) ? i : (numItems - 1 - i);
  50444. index = (index + numItems) % numItems;
  50445. mic = dynamic_cast <MenuItemComponent*> (getChildComponent (index));
  50446. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  50447. && wasLastOne)
  50448. break;
  50449. if (mic == currentChild)
  50450. wasLastOne = true;
  50451. }
  50452. setCurrentlyHighlightedChild (mic);
  50453. }
  50454. void disableTimerUntilMouseMoves() throw()
  50455. {
  50456. disableMouseMoves = true;
  50457. if (owner != 0)
  50458. owner->disableTimerUntilMouseMoves();
  50459. }
  50460. PopupMenuWindow (const PopupMenuWindow&);
  50461. const PopupMenuWindow& operator= (const PopupMenuWindow&);
  50462. };
  50463. PopupMenu::PopupMenu() throw()
  50464. : items (8),
  50465. lookAndFeel (0),
  50466. separatorPending (false)
  50467. {
  50468. }
  50469. PopupMenu::PopupMenu (const PopupMenu& other) throw()
  50470. : items (8),
  50471. lookAndFeel (other.lookAndFeel),
  50472. separatorPending (false)
  50473. {
  50474. items.ensureStorageAllocated (other.items.size());
  50475. for (int i = 0; i < other.items.size(); ++i)
  50476. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  50477. }
  50478. const PopupMenu& PopupMenu::operator= (const PopupMenu& other) throw()
  50479. {
  50480. if (this != &other)
  50481. {
  50482. lookAndFeel = other.lookAndFeel;
  50483. clear();
  50484. items.ensureStorageAllocated (other.items.size());
  50485. for (int i = 0; i < other.items.size(); ++i)
  50486. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  50487. }
  50488. return *this;
  50489. }
  50490. PopupMenu::~PopupMenu() throw()
  50491. {
  50492. clear();
  50493. }
  50494. void PopupMenu::clear() throw()
  50495. {
  50496. for (int i = items.size(); --i >= 0;)
  50497. {
  50498. MenuItemInfo* const mi = (MenuItemInfo*) items.getUnchecked(i);
  50499. delete mi;
  50500. }
  50501. items.clear();
  50502. separatorPending = false;
  50503. }
  50504. void PopupMenu::addSeparatorIfPending()
  50505. {
  50506. if (separatorPending)
  50507. {
  50508. separatorPending = false;
  50509. if (items.size() > 0)
  50510. items.add (new MenuItemInfo());
  50511. }
  50512. }
  50513. void PopupMenu::addItem (const int itemResultId,
  50514. const String& itemText,
  50515. const bool isActive,
  50516. const bool isTicked,
  50517. const Image* const iconToUse) throw()
  50518. {
  50519. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  50520. // didn't pick anything, so you shouldn't use it as the id
  50521. // for an item..
  50522. addSeparatorIfPending();
  50523. items.add (new MenuItemInfo (itemResultId,
  50524. itemText,
  50525. isActive,
  50526. isTicked,
  50527. iconToUse,
  50528. Colours::black,
  50529. false,
  50530. 0, 0, 0));
  50531. }
  50532. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  50533. const int commandID,
  50534. const String& displayName) throw()
  50535. {
  50536. jassert (commandManager != 0 && commandID != 0);
  50537. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  50538. if (registeredInfo != 0)
  50539. {
  50540. ApplicationCommandInfo info (*registeredInfo);
  50541. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  50542. addSeparatorIfPending();
  50543. items.add (new MenuItemInfo (commandID,
  50544. displayName.isNotEmpty() ? displayName
  50545. : info.shortName,
  50546. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  50547. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  50548. 0,
  50549. Colours::black,
  50550. false,
  50551. 0, 0,
  50552. commandManager));
  50553. }
  50554. }
  50555. void PopupMenu::addColouredItem (const int itemResultId,
  50556. const String& itemText,
  50557. const Colour& itemTextColour,
  50558. const bool isActive,
  50559. const bool isTicked,
  50560. const Image* const iconToUse) throw()
  50561. {
  50562. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  50563. // didn't pick anything, so you shouldn't use it as the id
  50564. // for an item..
  50565. addSeparatorIfPending();
  50566. items.add (new MenuItemInfo (itemResultId,
  50567. itemText,
  50568. isActive,
  50569. isTicked,
  50570. iconToUse,
  50571. itemTextColour,
  50572. true,
  50573. 0, 0, 0));
  50574. }
  50575. void PopupMenu::addCustomItem (const int itemResultId,
  50576. PopupMenuCustomComponent* const customComponent) throw()
  50577. {
  50578. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  50579. // didn't pick anything, so you shouldn't use it as the id
  50580. // for an item..
  50581. addSeparatorIfPending();
  50582. items.add (new MenuItemInfo (itemResultId,
  50583. String::empty,
  50584. true,
  50585. false,
  50586. 0,
  50587. Colours::black,
  50588. false,
  50589. customComponent,
  50590. 0, 0));
  50591. }
  50592. class NormalComponentWrapper : public PopupMenuCustomComponent
  50593. {
  50594. public:
  50595. NormalComponentWrapper (Component* const comp,
  50596. const int w, const int h,
  50597. const bool triggerMenuItemAutomaticallyWhenClicked)
  50598. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  50599. width (w),
  50600. height (h)
  50601. {
  50602. addAndMakeVisible (comp);
  50603. }
  50604. ~NormalComponentWrapper() {}
  50605. void getIdealSize (int& idealWidth, int& idealHeight)
  50606. {
  50607. idealWidth = width;
  50608. idealHeight = height;
  50609. }
  50610. void resized()
  50611. {
  50612. if (getChildComponent(0) != 0)
  50613. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  50614. }
  50615. juce_UseDebuggingNewOperator
  50616. private:
  50617. const int width, height;
  50618. NormalComponentWrapper (const NormalComponentWrapper&);
  50619. const NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  50620. };
  50621. void PopupMenu::addCustomItem (const int itemResultId,
  50622. Component* customComponent,
  50623. int idealWidth, int idealHeight,
  50624. const bool triggerMenuItemAutomaticallyWhenClicked) throw()
  50625. {
  50626. addCustomItem (itemResultId,
  50627. new NormalComponentWrapper (customComponent,
  50628. idealWidth, idealHeight,
  50629. triggerMenuItemAutomaticallyWhenClicked));
  50630. }
  50631. void PopupMenu::addSubMenu (const String& subMenuName,
  50632. const PopupMenu& subMenu,
  50633. const bool isActive,
  50634. Image* const iconToUse) throw()
  50635. {
  50636. addSeparatorIfPending();
  50637. items.add (new MenuItemInfo (0,
  50638. subMenuName,
  50639. isActive && (subMenu.getNumItems() > 0),
  50640. false,
  50641. iconToUse,
  50642. Colours::black,
  50643. false,
  50644. 0,
  50645. &subMenu,
  50646. 0));
  50647. }
  50648. void PopupMenu::addSeparator() throw()
  50649. {
  50650. separatorPending = true;
  50651. }
  50652. class HeaderItemComponent : public PopupMenuCustomComponent
  50653. {
  50654. public:
  50655. HeaderItemComponent (const String& name)
  50656. : PopupMenuCustomComponent (false)
  50657. {
  50658. setName (name);
  50659. }
  50660. ~HeaderItemComponent()
  50661. {
  50662. }
  50663. void paint (Graphics& g)
  50664. {
  50665. Font f (getLookAndFeel().getPopupMenuFont());
  50666. f.setBold (true);
  50667. g.setFont (f);
  50668. g.setColour (findColour (PopupMenu::headerTextColourId));
  50669. g.drawFittedText (getName(),
  50670. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  50671. Justification::bottomLeft, 1);
  50672. }
  50673. void getIdealSize (int& idealWidth,
  50674. int& idealHeight)
  50675. {
  50676. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  50677. idealHeight += idealHeight / 2;
  50678. idealWidth += idealWidth / 4;
  50679. }
  50680. juce_UseDebuggingNewOperator
  50681. };
  50682. void PopupMenu::addSectionHeader (const String& title) throw()
  50683. {
  50684. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  50685. }
  50686. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  50687. const int itemIdThatMustBeVisible,
  50688. const int minimumWidth,
  50689. const int maximumNumColumns,
  50690. const int standardItemHeight,
  50691. const bool alignToRectangle,
  50692. Component* menuBarComponent,
  50693. ApplicationCommandManager** managerOfChosenCommand,
  50694. Component* const componentAttachedTo) throw()
  50695. {
  50696. PopupMenuWindow* const pw
  50697. = PopupMenuWindow::create (*this,
  50698. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  50699. 0,
  50700. x, x + w,
  50701. y, y + h,
  50702. minimumWidth,
  50703. maximumNumColumns,
  50704. standardItemHeight,
  50705. alignToRectangle,
  50706. itemIdThatMustBeVisible,
  50707. menuBarComponent,
  50708. managerOfChosenCommand,
  50709. componentAttachedTo);
  50710. if (pw != 0)
  50711. pw->setVisible (true);
  50712. return pw;
  50713. }
  50714. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  50715. const int itemIdThatMustBeVisible,
  50716. const int minimumWidth,
  50717. const int maximumNumColumns,
  50718. const int standardItemHeight,
  50719. const bool alignToRectangle,
  50720. Component* const componentAttachedTo) throw()
  50721. {
  50722. Component* const prevFocused = Component::getCurrentlyFocusedComponent();
  50723. ComponentDeletionWatcher* deletionChecker1 = 0;
  50724. if (prevFocused != 0)
  50725. deletionChecker1 = new ComponentDeletionWatcher (prevFocused);
  50726. Component* const prevTopLevel = (prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0;
  50727. ComponentDeletionWatcher* deletionChecker2 = 0;
  50728. if (prevTopLevel != 0)
  50729. deletionChecker2 = new ComponentDeletionWatcher (prevTopLevel);
  50730. wasHiddenBecauseOfAppChange = false;
  50731. int result = 0;
  50732. ApplicationCommandManager* managerOfChosenCommand = 0;
  50733. Component* const popupComp = createMenuComponent (x, y, w, h,
  50734. itemIdThatMustBeVisible,
  50735. minimumWidth,
  50736. maximumNumColumns > 0 ? maximumNumColumns : 7,
  50737. standardItemHeight,
  50738. alignToRectangle, 0,
  50739. &managerOfChosenCommand,
  50740. componentAttachedTo);
  50741. if (popupComp != 0)
  50742. {
  50743. popupComp->enterModalState (false);
  50744. popupComp->toFront (false); // need to do this after making it modal, or it could
  50745. // be stuck behind other comps that are already modal..
  50746. result = popupComp->runModalLoop();
  50747. delete popupComp;
  50748. if (! wasHiddenBecauseOfAppChange)
  50749. {
  50750. if (deletionChecker2 != 0 && ! deletionChecker2->hasBeenDeleted())
  50751. prevTopLevel->toFront (true);
  50752. if (deletionChecker1 != 0 && ! deletionChecker1->hasBeenDeleted())
  50753. prevFocused->grabKeyboardFocus();
  50754. }
  50755. }
  50756. delete deletionChecker1;
  50757. delete deletionChecker2;
  50758. if (managerOfChosenCommand != 0 && result != 0)
  50759. {
  50760. ApplicationCommandTarget::InvocationInfo info (result);
  50761. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  50762. managerOfChosenCommand->invoke (info, true);
  50763. }
  50764. return result;
  50765. }
  50766. int PopupMenu::show (const int itemIdThatMustBeVisible,
  50767. const int minimumWidth,
  50768. const int maximumNumColumns,
  50769. const int standardItemHeight)
  50770. {
  50771. int x, y;
  50772. Desktop::getMousePosition (x, y);
  50773. return showAt (x, y,
  50774. itemIdThatMustBeVisible,
  50775. minimumWidth,
  50776. maximumNumColumns,
  50777. standardItemHeight);
  50778. }
  50779. int PopupMenu::showAt (const int screenX,
  50780. const int screenY,
  50781. const int itemIdThatMustBeVisible,
  50782. const int minimumWidth,
  50783. const int maximumNumColumns,
  50784. const int standardItemHeight)
  50785. {
  50786. return showMenu (screenX, screenY, 1, 1,
  50787. itemIdThatMustBeVisible,
  50788. minimumWidth, maximumNumColumns,
  50789. standardItemHeight,
  50790. false, 0);
  50791. }
  50792. int PopupMenu::showAt (Component* componentToAttachTo,
  50793. const int itemIdThatMustBeVisible,
  50794. const int minimumWidth,
  50795. const int maximumNumColumns,
  50796. const int standardItemHeight)
  50797. {
  50798. if (componentToAttachTo != 0)
  50799. {
  50800. return showMenu (componentToAttachTo->getScreenX(),
  50801. componentToAttachTo->getScreenY(),
  50802. componentToAttachTo->getWidth(),
  50803. componentToAttachTo->getHeight(),
  50804. itemIdThatMustBeVisible,
  50805. minimumWidth,
  50806. maximumNumColumns,
  50807. standardItemHeight,
  50808. true, componentToAttachTo);
  50809. }
  50810. else
  50811. {
  50812. return show (itemIdThatMustBeVisible,
  50813. minimumWidth,
  50814. maximumNumColumns,
  50815. standardItemHeight);
  50816. }
  50817. }
  50818. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus() throw()
  50819. {
  50820. for (int i = activeMenuWindows.size(); --i >= 0;)
  50821. {
  50822. PopupMenuWindow* const pmw = (PopupMenuWindow*) activeMenuWindows[i];
  50823. if (pmw != 0)
  50824. pmw->dismissMenu (0);
  50825. }
  50826. }
  50827. int PopupMenu::getNumItems() const throw()
  50828. {
  50829. int num = 0;
  50830. for (int i = items.size(); --i >= 0;)
  50831. if (! ((MenuItemInfo*) items.getUnchecked(i))->isSeparator)
  50832. ++num;
  50833. return num;
  50834. }
  50835. bool PopupMenu::containsCommandItem (const int commandID) const throw()
  50836. {
  50837. for (int i = items.size(); --i >= 0;)
  50838. {
  50839. const MenuItemInfo* mi = (const MenuItemInfo*) items.getUnchecked (i);
  50840. if ((mi->itemId == commandID && mi->commandManager != 0)
  50841. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  50842. {
  50843. return true;
  50844. }
  50845. }
  50846. return false;
  50847. }
  50848. bool PopupMenu::containsAnyActiveItems() const throw()
  50849. {
  50850. for (int i = items.size(); --i >= 0;)
  50851. {
  50852. const MenuItemInfo* const mi = (const MenuItemInfo*) items.getUnchecked (i);
  50853. if (mi->subMenu != 0)
  50854. {
  50855. if (mi->subMenu->containsAnyActiveItems())
  50856. return true;
  50857. }
  50858. else if (mi->active)
  50859. {
  50860. return true;
  50861. }
  50862. }
  50863. return false;
  50864. }
  50865. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel) throw()
  50866. {
  50867. lookAndFeel = newLookAndFeel;
  50868. }
  50869. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  50870. : refCount_ (0),
  50871. isHighlighted (false),
  50872. isTriggeredAutomatically (isTriggeredAutomatically_)
  50873. {
  50874. }
  50875. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  50876. {
  50877. jassert (refCount_ == 0); // should be deleted only by the menu component, as they keep a ref-count.
  50878. }
  50879. void PopupMenuCustomComponent::triggerMenuItem()
  50880. {
  50881. MenuItemComponent* const mic = dynamic_cast<MenuItemComponent*> (getParentComponent());
  50882. if (mic != 0)
  50883. {
  50884. PopupMenuWindow* const pmw = dynamic_cast<PopupMenuWindow*> (mic->getParentComponent());
  50885. if (pmw != 0)
  50886. {
  50887. pmw->dismissMenu (&mic->itemInfo);
  50888. }
  50889. else
  50890. {
  50891. // something must have gone wrong with the component hierarchy if this happens..
  50892. jassertfalse
  50893. }
  50894. }
  50895. else
  50896. {
  50897. // why isn't this component inside a menu? Not much point triggering the item if
  50898. // there's no menu.
  50899. jassertfalse
  50900. }
  50901. }
  50902. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_) throw()
  50903. : subMenu (0),
  50904. itemId (0),
  50905. isSeparator (false),
  50906. isTicked (false),
  50907. isEnabled (false),
  50908. isCustomComponent (false),
  50909. isSectionHeader (false),
  50910. customColour (0),
  50911. customImage (0),
  50912. menu (menu_),
  50913. index (0)
  50914. {
  50915. }
  50916. PopupMenu::MenuItemIterator::~MenuItemIterator() throw()
  50917. {
  50918. }
  50919. bool PopupMenu::MenuItemIterator::next() throw()
  50920. {
  50921. if (index >= menu.items.size())
  50922. return false;
  50923. const MenuItemInfo* const item = (const MenuItemInfo*) menu.items.getUnchecked (index);
  50924. ++index;
  50925. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  50926. subMenu = item->subMenu;
  50927. itemId = item->itemId;
  50928. isSeparator = item->isSeparator;
  50929. isTicked = item->isTicked;
  50930. isEnabled = item->active;
  50931. isSectionHeader = dynamic_cast <HeaderItemComponent*> (item->customComp) != 0;
  50932. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  50933. customColour = item->usesColour ? &(item->textColour) : 0;
  50934. customImage = item->image;
  50935. commandManager = item->commandManager;
  50936. return true;
  50937. }
  50938. END_JUCE_NAMESPACE
  50939. /********* End of inlined file: juce_PopupMenu.cpp *********/
  50940. /********* Start of inlined file: juce_ComponentDragger.cpp *********/
  50941. BEGIN_JUCE_NAMESPACE
  50942. ComponentDragger::ComponentDragger()
  50943. : constrainer (0),
  50944. originalX (0),
  50945. originalY (0)
  50946. {
  50947. }
  50948. ComponentDragger::~ComponentDragger()
  50949. {
  50950. }
  50951. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  50952. ComponentBoundsConstrainer* const constrainer_)
  50953. {
  50954. jassert (componentToDrag->isValidComponent());
  50955. if (componentToDrag->isValidComponent())
  50956. {
  50957. constrainer = constrainer_;
  50958. originalX = 0;
  50959. originalY = 0;
  50960. componentToDrag->relativePositionToGlobal (originalX, originalY);
  50961. }
  50962. }
  50963. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  50964. {
  50965. jassert (componentToDrag->isValidComponent());
  50966. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  50967. if (componentToDrag->isValidComponent())
  50968. {
  50969. int x = originalX + e.getDistanceFromDragStartX();
  50970. int y = originalY + e.getDistanceFromDragStartY();
  50971. int w = componentToDrag->getWidth();
  50972. int h = componentToDrag->getHeight();
  50973. const Component* const parentComp = componentToDrag->getParentComponent();
  50974. if (parentComp != 0)
  50975. parentComp->globalPositionToRelative (x, y);
  50976. if (constrainer != 0)
  50977. constrainer->setBoundsForComponent (componentToDrag, x, y, w, h,
  50978. false, false, false, false);
  50979. else
  50980. componentToDrag->setBounds (x, y, w, h);
  50981. }
  50982. }
  50983. END_JUCE_NAMESPACE
  50984. /********* End of inlined file: juce_ComponentDragger.cpp *********/
  50985. /********* Start of inlined file: juce_DragAndDropContainer.cpp *********/
  50986. BEGIN_JUCE_NAMESPACE
  50987. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  50988. bool juce_performDragDropText (const String& text, bool& shouldStop);
  50989. class DragImageComponent : public Component,
  50990. public Timer
  50991. {
  50992. private:
  50993. Image* image;
  50994. Component* const source;
  50995. DragAndDropContainer* const owner;
  50996. ComponentDeletionWatcher* sourceWatcher;
  50997. Component* mouseDragSource;
  50998. ComponentDeletionWatcher* mouseDragSourceWatcher;
  50999. DragAndDropTarget* currentlyOver;
  51000. String dragDesc;
  51001. int xOff, yOff;
  51002. bool hasCheckedForExternalDrag, drawImage;
  51003. DragImageComponent (const DragImageComponent&);
  51004. const DragImageComponent& operator= (const DragImageComponent&);
  51005. public:
  51006. DragImageComponent (Image* const im,
  51007. const String& desc,
  51008. Component* const s,
  51009. DragAndDropContainer* const o)
  51010. : image (im),
  51011. source (s),
  51012. owner (o),
  51013. currentlyOver (0),
  51014. dragDesc (desc),
  51015. hasCheckedForExternalDrag (false),
  51016. drawImage (true)
  51017. {
  51018. setSize (im->getWidth(), im->getHeight());
  51019. sourceWatcher = new ComponentDeletionWatcher (source);
  51020. mouseDragSource = Component::getComponentUnderMouse();
  51021. if (mouseDragSource == 0)
  51022. mouseDragSource = source;
  51023. mouseDragSourceWatcher = new ComponentDeletionWatcher (mouseDragSource);
  51024. mouseDragSource->addMouseListener (this, false);
  51025. int mx, my;
  51026. Desktop::getLastMouseDownPosition (mx, my);
  51027. source->globalPositionToRelative (mx, my);
  51028. xOff = jlimit (0, im->getWidth(), mx);
  51029. yOff = jlimit (0, im->getHeight(), my);
  51030. startTimer (200);
  51031. setInterceptsMouseClicks (false, false);
  51032. setAlwaysOnTop (true);
  51033. }
  51034. ~DragImageComponent()
  51035. {
  51036. if (owner->dragImageComponent == this)
  51037. owner->dragImageComponent = 0;
  51038. if (((Component*) currentlyOver)->isValidComponent())
  51039. {
  51040. Component* const over = dynamic_cast <Component*> (currentlyOver);
  51041. if (over != 0
  51042. && over->isValidComponent()
  51043. && source->isValidComponent()
  51044. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  51045. {
  51046. currentlyOver->itemDragExit (dragDesc, source);
  51047. }
  51048. }
  51049. if (! mouseDragSourceWatcher->hasBeenDeleted())
  51050. mouseDragSource->removeMouseListener (this);
  51051. delete mouseDragSourceWatcher;
  51052. delete sourceWatcher;
  51053. delete image;
  51054. }
  51055. void paint (Graphics& g)
  51056. {
  51057. if (isOpaque())
  51058. g.fillAll (Colours::white);
  51059. if (drawImage)
  51060. {
  51061. g.setOpacity (1.0f);
  51062. g.drawImageAt (image, 0, 0);
  51063. }
  51064. }
  51065. DragAndDropTarget* findTarget (const int screenX, const int screenY,
  51066. int& relX, int& relY) const throw()
  51067. {
  51068. Component* hit = getParentComponent();
  51069. if (hit == 0)
  51070. {
  51071. hit = Desktop::getInstance().findComponentAt (screenX, screenY);
  51072. }
  51073. else
  51074. {
  51075. int rx = screenX, ry = screenY;
  51076. hit->globalPositionToRelative (rx, ry);
  51077. hit = hit->getComponentAt (rx, ry);
  51078. }
  51079. while (hit != 0)
  51080. {
  51081. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  51082. if (ddt != 0 && ddt->isInterestedInDragSource (dragDesc, source))
  51083. {
  51084. relX = screenX;
  51085. relY = screenY;
  51086. hit->globalPositionToRelative (relX, relY);
  51087. return ddt;
  51088. }
  51089. hit = hit->getParentComponent();
  51090. }
  51091. return 0;
  51092. }
  51093. void mouseUp (const MouseEvent& e)
  51094. {
  51095. if (e.originalComponent != this)
  51096. {
  51097. if (! mouseDragSourceWatcher->hasBeenDeleted())
  51098. mouseDragSource->removeMouseListener (this);
  51099. bool dropAccepted = false;
  51100. DragAndDropTarget* ddt = 0;
  51101. int relX = 0, relY = 0;
  51102. if (isVisible())
  51103. {
  51104. setVisible (false);
  51105. ddt = findTarget (e.getScreenX(),
  51106. e.getScreenY(),
  51107. relX, relY);
  51108. // fade this component and remove it - it'll be deleted later by the timer callback
  51109. dropAccepted = ddt != 0;
  51110. setVisible (true);
  51111. if (dropAccepted || sourceWatcher->hasBeenDeleted())
  51112. {
  51113. fadeOutComponent (120);
  51114. }
  51115. else
  51116. {
  51117. int targetX = source->getWidth() / 2;
  51118. int targetY = source->getHeight() / 2;
  51119. source->relativePositionToGlobal (targetX, targetY);
  51120. int ourCentreX = getWidth() / 2;
  51121. int ourCentreY = getHeight() / 2;
  51122. relativePositionToGlobal (ourCentreX, ourCentreY);
  51123. fadeOutComponent (120,
  51124. targetX - ourCentreX,
  51125. targetY - ourCentreY);
  51126. }
  51127. }
  51128. if (getParentComponent() != 0)
  51129. getParentComponent()->removeChildComponent (this);
  51130. if (dropAccepted && ddt != 0)
  51131. ddt->itemDropped (dragDesc, source, relX, relY);
  51132. // careful - this object could now be deleted..
  51133. }
  51134. }
  51135. void updateLocation (const bool canDoExternalDrag, int x, int y)
  51136. {
  51137. int newX = x - xOff;
  51138. int newY = y - yOff;
  51139. if (getParentComponent() != 0)
  51140. getParentComponent()->globalPositionToRelative (newX, newY);
  51141. if (newX != getX() || newY != getY())
  51142. {
  51143. setTopLeftPosition (newX, newY);
  51144. int relX = 0, relY = 0;
  51145. DragAndDropTarget* const ddt = findTarget (x, y, relX, relY);
  51146. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  51147. if (ddt != currentlyOver)
  51148. {
  51149. Component* const over = dynamic_cast <Component*> (currentlyOver);
  51150. if (over != 0
  51151. && over->isValidComponent()
  51152. && ! (sourceWatcher->hasBeenDeleted())
  51153. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  51154. {
  51155. currentlyOver->itemDragExit (dragDesc, source);
  51156. }
  51157. currentlyOver = ddt;
  51158. if (currentlyOver != 0
  51159. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  51160. currentlyOver->itemDragEnter (dragDesc, source, relX, relY);
  51161. }
  51162. if (currentlyOver != 0
  51163. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  51164. currentlyOver->itemDragMove (dragDesc, source, relX, relY);
  51165. if (currentlyOver == 0
  51166. && canDoExternalDrag
  51167. && ! hasCheckedForExternalDrag)
  51168. {
  51169. if (Desktop::getInstance().findComponentAt (x, y) == 0)
  51170. {
  51171. hasCheckedForExternalDrag = true;
  51172. StringArray files;
  51173. bool canMoveFiles = false;
  51174. if (owner->shouldDropFilesWhenDraggedExternally (dragDesc, source, files, canMoveFiles)
  51175. && files.size() > 0)
  51176. {
  51177. ComponentDeletionWatcher cdw (this);
  51178. setVisible (false);
  51179. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  51180. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  51181. if (! cdw.hasBeenDeleted())
  51182. delete this;
  51183. return;
  51184. }
  51185. }
  51186. }
  51187. }
  51188. }
  51189. void mouseDrag (const MouseEvent& e)
  51190. {
  51191. if (e.originalComponent != this)
  51192. updateLocation (true, e.getScreenX(), e.getScreenY());
  51193. }
  51194. void timerCallback()
  51195. {
  51196. if (sourceWatcher->hasBeenDeleted())
  51197. {
  51198. delete this;
  51199. }
  51200. else if (! isMouseButtonDownAnywhere())
  51201. {
  51202. if (! mouseDragSourceWatcher->hasBeenDeleted())
  51203. mouseDragSource->removeMouseListener (this);
  51204. delete this;
  51205. }
  51206. }
  51207. };
  51208. DragAndDropContainer::DragAndDropContainer()
  51209. : dragImageComponent (0)
  51210. {
  51211. }
  51212. DragAndDropContainer::~DragAndDropContainer()
  51213. {
  51214. if (dragImageComponent != 0)
  51215. delete dragImageComponent;
  51216. }
  51217. void DragAndDropContainer::startDragging (const String& sourceDescription,
  51218. Component* sourceComponent,
  51219. Image* im,
  51220. const bool allowDraggingToExternalWindows)
  51221. {
  51222. if (dragImageComponent != 0)
  51223. {
  51224. if (im != 0)
  51225. delete im;
  51226. }
  51227. else
  51228. {
  51229. Component* const thisComp = dynamic_cast <Component*> (this);
  51230. if (thisComp != 0)
  51231. {
  51232. int mx, my;
  51233. Desktop::getLastMouseDownPosition (mx, my);
  51234. if (im == 0)
  51235. {
  51236. im = sourceComponent->createComponentSnapshot (Rectangle (0, 0, sourceComponent->getWidth(), sourceComponent->getHeight()));
  51237. if (im->getFormat() != Image::ARGB)
  51238. {
  51239. Image* newIm = new Image (Image::ARGB, im->getWidth(), im->getHeight(), true);
  51240. Graphics g2 (*newIm);
  51241. g2.drawImageAt (im, 0, 0);
  51242. delete im;
  51243. im = newIm;
  51244. }
  51245. im->multiplyAllAlphas (0.6f);
  51246. const int lo = 150;
  51247. const int hi = 400;
  51248. int rx = mx, ry = my;
  51249. sourceComponent->globalPositionToRelative (rx, ry);
  51250. const int cx = jlimit (0, im->getWidth(), rx);
  51251. const int cy = jlimit (0, im->getHeight(), ry);
  51252. for (int y = im->getHeight(); --y >= 0;)
  51253. {
  51254. const double dy = (y - cy) * (y - cy);
  51255. for (int x = im->getWidth(); --x >= 0;)
  51256. {
  51257. const int dx = x - cx;
  51258. const int distance = roundDoubleToInt (sqrt (dx * dx + dy));
  51259. if (distance > lo)
  51260. {
  51261. const float alpha = (distance > hi) ? 0
  51262. : (hi - distance) / (float) (hi - lo)
  51263. + Random::getSystemRandom().nextFloat() * 0.008f;
  51264. im->multiplyAlphaAt (x, y, alpha);
  51265. }
  51266. }
  51267. }
  51268. }
  51269. DragImageComponent* const dic
  51270. = new DragImageComponent (im,
  51271. sourceDescription,
  51272. sourceComponent,
  51273. this);
  51274. dragImageComponent = dic;
  51275. currentDragDesc = sourceDescription;
  51276. if (allowDraggingToExternalWindows)
  51277. {
  51278. if (! Desktop::canUseSemiTransparentWindows())
  51279. dic->setOpaque (true);
  51280. dic->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  51281. | ComponentPeer::windowIsTemporary);
  51282. }
  51283. else
  51284. thisComp->addChildComponent (dic);
  51285. dic->updateLocation (false, mx, my);
  51286. dic->setVisible (true);
  51287. }
  51288. else
  51289. {
  51290. // this class must only be implemented by an object that
  51291. // is also a Component.
  51292. jassertfalse
  51293. if (im != 0)
  51294. delete im;
  51295. }
  51296. }
  51297. }
  51298. bool DragAndDropContainer::isDragAndDropActive() const
  51299. {
  51300. return dragImageComponent != 0;
  51301. }
  51302. const String DragAndDropContainer::getCurrentDragDescription() const
  51303. {
  51304. return (dragImageComponent != 0) ? currentDragDesc
  51305. : String::empty;
  51306. }
  51307. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  51308. {
  51309. if (c == 0)
  51310. return 0;
  51311. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  51312. return c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  51313. }
  51314. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  51315. {
  51316. return false;
  51317. }
  51318. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  51319. {
  51320. }
  51321. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  51322. {
  51323. }
  51324. void DragAndDropTarget::itemDragExit (const String&, Component*)
  51325. {
  51326. }
  51327. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  51328. {
  51329. return true;
  51330. }
  51331. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  51332. {
  51333. }
  51334. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  51335. {
  51336. }
  51337. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  51338. {
  51339. }
  51340. END_JUCE_NAMESPACE
  51341. /********* End of inlined file: juce_DragAndDropContainer.cpp *********/
  51342. /********* Start of inlined file: juce_MouseCursor.cpp *********/
  51343. BEGIN_JUCE_NAMESPACE
  51344. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw();
  51345. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw();
  51346. // isStandard set depending on which interface was used to create the cursor
  51347. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw();
  51348. static CriticalSection mouseCursorLock;
  51349. static VoidArray standardCursors (2);
  51350. class RefCountedMouseCursor
  51351. {
  51352. public:
  51353. RefCountedMouseCursor (const MouseCursor::StandardCursorType t) throw()
  51354. : refCount (1),
  51355. standardType (t),
  51356. isStandard (true)
  51357. {
  51358. handle = juce_createStandardMouseCursor (standardType);
  51359. standardCursors.add (this);
  51360. }
  51361. RefCountedMouseCursor (Image& image,
  51362. const int hotSpotX,
  51363. const int hotSpotY) throw()
  51364. : refCount (1),
  51365. standardType (MouseCursor::NormalCursor),
  51366. isStandard (false)
  51367. {
  51368. handle = juce_createMouseCursorFromImage (image, hotSpotX, hotSpotY);
  51369. }
  51370. ~RefCountedMouseCursor() throw()
  51371. {
  51372. juce_deleteMouseCursor (handle, isStandard);
  51373. standardCursors.removeValue (this);
  51374. }
  51375. void decRef() throw()
  51376. {
  51377. if (--refCount == 0)
  51378. delete this;
  51379. }
  51380. void incRef() throw()
  51381. {
  51382. ++refCount;
  51383. }
  51384. void* getHandle() const throw()
  51385. {
  51386. return handle;
  51387. }
  51388. static RefCountedMouseCursor* findInstance (MouseCursor::StandardCursorType type) throw()
  51389. {
  51390. const ScopedLock sl (mouseCursorLock);
  51391. for (int i = 0; i < standardCursors.size(); i++)
  51392. {
  51393. RefCountedMouseCursor* const r = (RefCountedMouseCursor*) standardCursors.getUnchecked(i);
  51394. if (r->standardType == type)
  51395. {
  51396. r->incRef();
  51397. return r;
  51398. }
  51399. }
  51400. return new RefCountedMouseCursor (type);
  51401. }
  51402. juce_UseDebuggingNewOperator
  51403. private:
  51404. void* handle;
  51405. int refCount;
  51406. const MouseCursor::StandardCursorType standardType;
  51407. const bool isStandard;
  51408. const RefCountedMouseCursor& operator= (const RefCountedMouseCursor&);
  51409. };
  51410. MouseCursor::MouseCursor() throw()
  51411. {
  51412. cursorHandle = RefCountedMouseCursor::findInstance (NormalCursor);
  51413. }
  51414. MouseCursor::MouseCursor (const StandardCursorType type) throw()
  51415. {
  51416. cursorHandle = RefCountedMouseCursor::findInstance (type);
  51417. }
  51418. MouseCursor::MouseCursor (Image& image,
  51419. const int hotSpotX,
  51420. const int hotSpotY) throw()
  51421. {
  51422. cursorHandle = new RefCountedMouseCursor (image, hotSpotX, hotSpotY);
  51423. }
  51424. MouseCursor::MouseCursor (const MouseCursor& other) throw()
  51425. : cursorHandle (other.cursorHandle)
  51426. {
  51427. const ScopedLock sl (mouseCursorLock);
  51428. cursorHandle->incRef();
  51429. }
  51430. MouseCursor::~MouseCursor() throw()
  51431. {
  51432. const ScopedLock sl (mouseCursorLock);
  51433. cursorHandle->decRef();
  51434. }
  51435. const MouseCursor& MouseCursor::operator= (const MouseCursor& other) throw()
  51436. {
  51437. if (this != &other)
  51438. {
  51439. const ScopedLock sl (mouseCursorLock);
  51440. cursorHandle->decRef();
  51441. cursorHandle = other.cursorHandle;
  51442. cursorHandle->incRef();
  51443. }
  51444. return *this;
  51445. }
  51446. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  51447. {
  51448. return cursorHandle == other.cursorHandle;
  51449. }
  51450. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  51451. {
  51452. return cursorHandle != other.cursorHandle;
  51453. }
  51454. void* MouseCursor::getHandle() const throw()
  51455. {
  51456. return cursorHandle->getHandle();
  51457. }
  51458. void MouseCursor::showWaitCursor() throw()
  51459. {
  51460. const MouseCursor mc (MouseCursor::WaitCursor);
  51461. mc.showInAllWindows();
  51462. }
  51463. void MouseCursor::hideWaitCursor() throw()
  51464. {
  51465. if (Component::getComponentUnderMouse()->isValidComponent())
  51466. {
  51467. Component::getComponentUnderMouse()->getMouseCursor().showInAllWindows();
  51468. }
  51469. else
  51470. {
  51471. const MouseCursor mc (MouseCursor::NormalCursor);
  51472. mc.showInAllWindows();
  51473. }
  51474. }
  51475. END_JUCE_NAMESPACE
  51476. /********* End of inlined file: juce_MouseCursor.cpp *********/
  51477. /********* Start of inlined file: juce_MouseEvent.cpp *********/
  51478. BEGIN_JUCE_NAMESPACE
  51479. MouseEvent::MouseEvent (const int x_,
  51480. const int y_,
  51481. const ModifierKeys& mods_,
  51482. Component* const originator,
  51483. const Time& eventTime_,
  51484. const int mouseDownX_,
  51485. const int mouseDownY_,
  51486. const Time& mouseDownTime_,
  51487. const int numberOfClicks_,
  51488. const bool mouseWasDragged) throw()
  51489. : x (x_),
  51490. y (y_),
  51491. mods (mods_),
  51492. eventComponent (originator),
  51493. originalComponent (originator),
  51494. eventTime (eventTime_),
  51495. mouseDownX (mouseDownX_),
  51496. mouseDownY (mouseDownY_),
  51497. mouseDownTime (mouseDownTime_),
  51498. numberOfClicks (numberOfClicks_),
  51499. wasMovedSinceMouseDown (mouseWasDragged)
  51500. {
  51501. }
  51502. MouseEvent::~MouseEvent() throw()
  51503. {
  51504. }
  51505. bool MouseEvent::mouseWasClicked() const throw()
  51506. {
  51507. return ! wasMovedSinceMouseDown;
  51508. }
  51509. int MouseEvent::getMouseDownX() const throw()
  51510. {
  51511. return mouseDownX;
  51512. }
  51513. int MouseEvent::getMouseDownY() const throw()
  51514. {
  51515. return mouseDownY;
  51516. }
  51517. int MouseEvent::getDistanceFromDragStartX() const throw()
  51518. {
  51519. return x - mouseDownX;
  51520. }
  51521. int MouseEvent::getDistanceFromDragStartY() const throw()
  51522. {
  51523. return y - mouseDownY;
  51524. }
  51525. int MouseEvent::getDistanceFromDragStart() const throw()
  51526. {
  51527. return roundDoubleToInt (juce_hypot (getDistanceFromDragStartX(),
  51528. getDistanceFromDragStartY()));
  51529. }
  51530. int MouseEvent::getLengthOfMousePress() const throw()
  51531. {
  51532. if (mouseDownTime.toMilliseconds() > 0)
  51533. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  51534. return 0;
  51535. }
  51536. int MouseEvent::getScreenX() const throw()
  51537. {
  51538. int sx = x, sy = y;
  51539. eventComponent->relativePositionToGlobal (sx, sy);
  51540. return sx;
  51541. }
  51542. int MouseEvent::getScreenY() const throw()
  51543. {
  51544. int sx = x, sy = y;
  51545. eventComponent->relativePositionToGlobal (sx, sy);
  51546. return sy;
  51547. }
  51548. int MouseEvent::getMouseDownScreenX() const throw()
  51549. {
  51550. int sx = mouseDownX, sy = mouseDownY;
  51551. eventComponent->relativePositionToGlobal (sx, sy);
  51552. return sx;
  51553. }
  51554. int MouseEvent::getMouseDownScreenY() const throw()
  51555. {
  51556. int sx = mouseDownX, sy = mouseDownY;
  51557. eventComponent->relativePositionToGlobal (sx, sy);
  51558. return sy;
  51559. }
  51560. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  51561. {
  51562. if (otherComponent == 0)
  51563. {
  51564. jassertfalse
  51565. return *this;
  51566. }
  51567. MouseEvent me (*this);
  51568. eventComponent->relativePositionToOtherComponent (otherComponent, me.x, me.y);
  51569. eventComponent->relativePositionToOtherComponent (otherComponent, me.mouseDownX, me.mouseDownY);
  51570. me.eventComponent = otherComponent;
  51571. return me;
  51572. }
  51573. static int doubleClickTimeOutMs = 400;
  51574. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  51575. {
  51576. doubleClickTimeOutMs = newTime;
  51577. }
  51578. int MouseEvent::getDoubleClickTimeout() throw()
  51579. {
  51580. return doubleClickTimeOutMs;
  51581. }
  51582. END_JUCE_NAMESPACE
  51583. /********* End of inlined file: juce_MouseEvent.cpp *********/
  51584. /********* Start of inlined file: juce_MouseHoverDetector.cpp *********/
  51585. BEGIN_JUCE_NAMESPACE
  51586. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  51587. : source (0),
  51588. hoverTimeMillisecs (hoverTimeMillisecs_),
  51589. hasJustHovered (false)
  51590. {
  51591. internalTimer.owner = this;
  51592. }
  51593. MouseHoverDetector::~MouseHoverDetector()
  51594. {
  51595. setHoverComponent (0);
  51596. }
  51597. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  51598. {
  51599. hoverTimeMillisecs = newTimeInMillisecs;
  51600. }
  51601. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  51602. {
  51603. if (source != newSourceComponent)
  51604. {
  51605. internalTimer.stopTimer();
  51606. hasJustHovered = false;
  51607. if (source != 0)
  51608. {
  51609. // ! you need to delete the hover detector before deleting its component
  51610. jassert (source->isValidComponent());
  51611. source->removeMouseListener (&internalTimer);
  51612. }
  51613. source = newSourceComponent;
  51614. if (newSourceComponent != 0)
  51615. newSourceComponent->addMouseListener (&internalTimer, false);
  51616. }
  51617. }
  51618. void MouseHoverDetector::hoverTimerCallback()
  51619. {
  51620. internalTimer.stopTimer();
  51621. if (source != 0)
  51622. {
  51623. int mx, my;
  51624. source->getMouseXYRelative (mx, my);
  51625. if (source->reallyContains (mx, my, false))
  51626. {
  51627. hasJustHovered = true;
  51628. mouseHovered (mx, my);
  51629. }
  51630. }
  51631. }
  51632. void MouseHoverDetector::checkJustHoveredCallback()
  51633. {
  51634. if (hasJustHovered)
  51635. {
  51636. hasJustHovered = false;
  51637. mouseMovedAfterHover();
  51638. }
  51639. }
  51640. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  51641. {
  51642. owner->hoverTimerCallback();
  51643. }
  51644. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  51645. {
  51646. stopTimer();
  51647. owner->checkJustHoveredCallback();
  51648. }
  51649. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  51650. {
  51651. stopTimer();
  51652. owner->checkJustHoveredCallback();
  51653. }
  51654. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  51655. {
  51656. stopTimer();
  51657. owner->checkJustHoveredCallback();
  51658. }
  51659. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  51660. {
  51661. stopTimer();
  51662. owner->checkJustHoveredCallback();
  51663. }
  51664. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  51665. {
  51666. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  51667. {
  51668. lastX = e.x;
  51669. lastY = e.y;
  51670. if (owner->source != 0)
  51671. startTimer (owner->hoverTimeMillisecs);
  51672. owner->checkJustHoveredCallback();
  51673. }
  51674. }
  51675. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  51676. {
  51677. stopTimer();
  51678. owner->checkJustHoveredCallback();
  51679. }
  51680. END_JUCE_NAMESPACE
  51681. /********* End of inlined file: juce_MouseHoverDetector.cpp *********/
  51682. /********* Start of inlined file: juce_MouseListener.cpp *********/
  51683. BEGIN_JUCE_NAMESPACE
  51684. void MouseListener::mouseEnter (const MouseEvent&)
  51685. {
  51686. }
  51687. void MouseListener::mouseExit (const MouseEvent&)
  51688. {
  51689. }
  51690. void MouseListener::mouseDown (const MouseEvent&)
  51691. {
  51692. }
  51693. void MouseListener::mouseUp (const MouseEvent&)
  51694. {
  51695. }
  51696. void MouseListener::mouseDrag (const MouseEvent&)
  51697. {
  51698. }
  51699. void MouseListener::mouseMove (const MouseEvent&)
  51700. {
  51701. }
  51702. void MouseListener::mouseDoubleClick (const MouseEvent&)
  51703. {
  51704. }
  51705. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  51706. {
  51707. }
  51708. END_JUCE_NAMESPACE
  51709. /********* End of inlined file: juce_MouseListener.cpp *********/
  51710. /********* Start of inlined file: juce_BooleanPropertyComponent.cpp *********/
  51711. BEGIN_JUCE_NAMESPACE
  51712. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  51713. const String& buttonTextWhenTrue,
  51714. const String& buttonTextWhenFalse)
  51715. : PropertyComponent (name),
  51716. onText (buttonTextWhenTrue),
  51717. offText (buttonTextWhenFalse)
  51718. {
  51719. addAndMakeVisible (button = new ToggleButton (String::empty));
  51720. button->setClickingTogglesState (false);
  51721. button->addButtonListener (this);
  51722. }
  51723. BooleanPropertyComponent::~BooleanPropertyComponent()
  51724. {
  51725. deleteAllChildren();
  51726. }
  51727. void BooleanPropertyComponent::paint (Graphics& g)
  51728. {
  51729. PropertyComponent::paint (g);
  51730. const Rectangle r (button->getBounds());
  51731. g.setColour (Colours::white);
  51732. g.fillRect (r);
  51733. g.setColour (findColour (ComboBox::outlineColourId));
  51734. g.drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  51735. }
  51736. void BooleanPropertyComponent::refresh()
  51737. {
  51738. button->setToggleState (getState(), false);
  51739. button->setButtonText (button->getToggleState() ? onText : offText);
  51740. }
  51741. void BooleanPropertyComponent::buttonClicked (Button*)
  51742. {
  51743. setState (! getState());
  51744. }
  51745. END_JUCE_NAMESPACE
  51746. /********* End of inlined file: juce_BooleanPropertyComponent.cpp *********/
  51747. /********* Start of inlined file: juce_ButtonPropertyComponent.cpp *********/
  51748. BEGIN_JUCE_NAMESPACE
  51749. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  51750. const bool triggerOnMouseDown)
  51751. : PropertyComponent (name)
  51752. {
  51753. addAndMakeVisible (button = new TextButton (String::empty));
  51754. button->setTriggeredOnMouseDown (triggerOnMouseDown);
  51755. button->addButtonListener (this);
  51756. }
  51757. ButtonPropertyComponent::~ButtonPropertyComponent()
  51758. {
  51759. deleteAllChildren();
  51760. }
  51761. void ButtonPropertyComponent::refresh()
  51762. {
  51763. button->setButtonText (getButtonText());
  51764. }
  51765. void ButtonPropertyComponent::buttonClicked (Button*)
  51766. {
  51767. buttonClicked();
  51768. }
  51769. END_JUCE_NAMESPACE
  51770. /********* End of inlined file: juce_ButtonPropertyComponent.cpp *********/
  51771. /********* Start of inlined file: juce_ChoicePropertyComponent.cpp *********/
  51772. BEGIN_JUCE_NAMESPACE
  51773. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  51774. : PropertyComponent (name),
  51775. comboBox (0)
  51776. {
  51777. }
  51778. ChoicePropertyComponent::~ChoicePropertyComponent()
  51779. {
  51780. deleteAllChildren();
  51781. }
  51782. const StringArray& ChoicePropertyComponent::getChoices() const throw()
  51783. {
  51784. return choices;
  51785. }
  51786. void ChoicePropertyComponent::refresh()
  51787. {
  51788. if (comboBox == 0)
  51789. {
  51790. addAndMakeVisible (comboBox = new ComboBox (String::empty));
  51791. for (int i = 0; i < choices.size(); ++i)
  51792. {
  51793. if (choices[i].isNotEmpty())
  51794. comboBox->addItem (choices[i], i + 1);
  51795. else
  51796. comboBox->addSeparator();
  51797. }
  51798. comboBox->setEditableText (false);
  51799. comboBox->addListener (this);
  51800. }
  51801. comboBox->setSelectedId (getIndex() + 1, true);
  51802. }
  51803. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  51804. {
  51805. const int newIndex = comboBox->getSelectedId() - 1;
  51806. if (newIndex != getIndex())
  51807. setIndex (newIndex);
  51808. }
  51809. END_JUCE_NAMESPACE
  51810. /********* End of inlined file: juce_ChoicePropertyComponent.cpp *********/
  51811. /********* Start of inlined file: juce_PropertyComponent.cpp *********/
  51812. BEGIN_JUCE_NAMESPACE
  51813. PropertyComponent::PropertyComponent (const String& name,
  51814. const int preferredHeight_)
  51815. : Component (name),
  51816. preferredHeight (preferredHeight_)
  51817. {
  51818. jassert (name.isNotEmpty());
  51819. }
  51820. PropertyComponent::~PropertyComponent()
  51821. {
  51822. }
  51823. void PropertyComponent::paint (Graphics& g)
  51824. {
  51825. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  51826. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  51827. }
  51828. void PropertyComponent::resized()
  51829. {
  51830. if (getNumChildComponents() > 0)
  51831. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  51832. }
  51833. void PropertyComponent::enablementChanged()
  51834. {
  51835. repaint();
  51836. }
  51837. END_JUCE_NAMESPACE
  51838. /********* End of inlined file: juce_PropertyComponent.cpp *********/
  51839. /********* Start of inlined file: juce_PropertyPanel.cpp *********/
  51840. BEGIN_JUCE_NAMESPACE
  51841. class PropertyHolderComponent : public Component
  51842. {
  51843. public:
  51844. PropertyHolderComponent()
  51845. {
  51846. }
  51847. ~PropertyHolderComponent()
  51848. {
  51849. deleteAllChildren();
  51850. }
  51851. void paint (Graphics&)
  51852. {
  51853. }
  51854. void updateLayout (const int width);
  51855. void refreshAll() const;
  51856. };
  51857. class PropertySectionComponent : public Component
  51858. {
  51859. public:
  51860. PropertySectionComponent (const String& sectionTitle,
  51861. const Array <PropertyComponent*>& newProperties,
  51862. const bool open)
  51863. : Component (sectionTitle),
  51864. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  51865. isOpen_ (open)
  51866. {
  51867. for (int i = newProperties.size(); --i >= 0;)
  51868. {
  51869. addAndMakeVisible (newProperties.getUnchecked(i));
  51870. newProperties.getUnchecked(i)->refresh();
  51871. }
  51872. }
  51873. ~PropertySectionComponent()
  51874. {
  51875. deleteAllChildren();
  51876. }
  51877. void paint (Graphics& g)
  51878. {
  51879. if (titleHeight > 0)
  51880. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  51881. }
  51882. void resized()
  51883. {
  51884. int y = titleHeight;
  51885. for (int i = getNumChildComponents(); --i >= 0;)
  51886. {
  51887. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51888. if (pec != 0)
  51889. {
  51890. const int prefH = pec->getPreferredHeight();
  51891. pec->setBounds (1, y, getWidth() - 2, prefH);
  51892. y += prefH;
  51893. }
  51894. }
  51895. }
  51896. int getPreferredHeight() const
  51897. {
  51898. int y = titleHeight;
  51899. if (isOpen())
  51900. {
  51901. for (int i = 0; i < getNumChildComponents(); ++i)
  51902. {
  51903. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51904. if (pec != 0)
  51905. y += pec->getPreferredHeight();
  51906. }
  51907. }
  51908. return y;
  51909. }
  51910. void setOpen (const bool open)
  51911. {
  51912. if (isOpen_ != open)
  51913. {
  51914. isOpen_ = open;
  51915. for (int i = 0; i < getNumChildComponents(); ++i)
  51916. {
  51917. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51918. if (pec != 0)
  51919. pec->setVisible (open);
  51920. }
  51921. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  51922. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  51923. if (pp != 0)
  51924. pp->resized();
  51925. }
  51926. }
  51927. bool isOpen() const throw()
  51928. {
  51929. return isOpen_;
  51930. }
  51931. void refreshAll() const
  51932. {
  51933. for (int i = 0; i < getNumChildComponents(); ++i)
  51934. {
  51935. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51936. if (pec != 0)
  51937. pec->refresh();
  51938. }
  51939. }
  51940. void mouseDown (const MouseEvent&)
  51941. {
  51942. }
  51943. void mouseUp (const MouseEvent& e)
  51944. {
  51945. if (e.getMouseDownX() < titleHeight
  51946. && e.x < titleHeight
  51947. && e.y < titleHeight
  51948. && e.getNumberOfClicks() != 2)
  51949. {
  51950. setOpen (! isOpen());
  51951. }
  51952. }
  51953. void mouseDoubleClick (const MouseEvent& e)
  51954. {
  51955. if (e.y < titleHeight)
  51956. setOpen (! isOpen());
  51957. }
  51958. private:
  51959. int titleHeight;
  51960. bool isOpen_;
  51961. };
  51962. void PropertyHolderComponent::updateLayout (const int width)
  51963. {
  51964. int y = 0;
  51965. for (int i = getNumChildComponents(); --i >= 0;)
  51966. {
  51967. PropertySectionComponent* const section
  51968. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  51969. if (section != 0)
  51970. {
  51971. const int prefH = section->getPreferredHeight();
  51972. section->setBounds (0, y, width, prefH);
  51973. y += prefH;
  51974. }
  51975. }
  51976. setSize (width, y);
  51977. repaint();
  51978. }
  51979. void PropertyHolderComponent::refreshAll() const
  51980. {
  51981. for (int i = getNumChildComponents(); --i >= 0;)
  51982. {
  51983. PropertySectionComponent* const section
  51984. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  51985. if (section != 0)
  51986. section->refreshAll();
  51987. }
  51988. }
  51989. PropertyPanel::PropertyPanel()
  51990. {
  51991. messageWhenEmpty = TRANS("(nothing selected)");
  51992. addAndMakeVisible (viewport = new Viewport());
  51993. viewport->setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  51994. viewport->setFocusContainer (true);
  51995. }
  51996. PropertyPanel::~PropertyPanel()
  51997. {
  51998. clear();
  51999. deleteAllChildren();
  52000. }
  52001. void PropertyPanel::paint (Graphics& g)
  52002. {
  52003. if (propertyHolderComponent->getNumChildComponents() == 0)
  52004. {
  52005. g.setColour (Colours::black.withAlpha (0.5f));
  52006. g.setFont (14.0f);
  52007. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  52008. Justification::centred, true);
  52009. }
  52010. }
  52011. void PropertyPanel::resized()
  52012. {
  52013. viewport->setBounds (0, 0, getWidth(), getHeight());
  52014. updatePropHolderLayout();
  52015. }
  52016. void PropertyPanel::clear()
  52017. {
  52018. if (propertyHolderComponent->getNumChildComponents() > 0)
  52019. {
  52020. propertyHolderComponent->deleteAllChildren();
  52021. repaint();
  52022. }
  52023. }
  52024. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  52025. {
  52026. if (propertyHolderComponent->getNumChildComponents() == 0)
  52027. repaint();
  52028. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  52029. newProperties,
  52030. true), 0);
  52031. updatePropHolderLayout();
  52032. }
  52033. void PropertyPanel::addSection (const String& sectionTitle,
  52034. const Array <PropertyComponent*>& newProperties,
  52035. const bool shouldBeOpen)
  52036. {
  52037. jassert (sectionTitle.isNotEmpty());
  52038. if (propertyHolderComponent->getNumChildComponents() == 0)
  52039. repaint();
  52040. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  52041. newProperties,
  52042. shouldBeOpen), 0);
  52043. updatePropHolderLayout();
  52044. }
  52045. void PropertyPanel::updatePropHolderLayout() const
  52046. {
  52047. const int maxWidth = viewport->getMaximumVisibleWidth();
  52048. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (maxWidth);
  52049. const int newMaxWidth = viewport->getMaximumVisibleWidth();
  52050. if (maxWidth != newMaxWidth)
  52051. {
  52052. // need to do this twice because of scrollbars changing the size, etc.
  52053. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (newMaxWidth);
  52054. }
  52055. }
  52056. void PropertyPanel::refreshAll() const
  52057. {
  52058. ((PropertyHolderComponent*) propertyHolderComponent)->refreshAll();
  52059. }
  52060. const StringArray PropertyPanel::getSectionNames() const
  52061. {
  52062. StringArray s;
  52063. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  52064. {
  52065. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  52066. if (section != 0 && section->getName().isNotEmpty())
  52067. s.add (section->getName());
  52068. }
  52069. return s;
  52070. }
  52071. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  52072. {
  52073. int index = 0;
  52074. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  52075. {
  52076. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  52077. if (section != 0 && section->getName().isNotEmpty())
  52078. {
  52079. if (index == sectionIndex)
  52080. return section->isOpen();
  52081. ++index;
  52082. }
  52083. }
  52084. return false;
  52085. }
  52086. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  52087. {
  52088. int index = 0;
  52089. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  52090. {
  52091. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  52092. if (section != 0 && section->getName().isNotEmpty())
  52093. {
  52094. if (index == sectionIndex)
  52095. {
  52096. section->setOpen (shouldBeOpen);
  52097. break;
  52098. }
  52099. ++index;
  52100. }
  52101. }
  52102. }
  52103. XmlElement* PropertyPanel::getOpennessState() const
  52104. {
  52105. XmlElement* const xml = new XmlElement (T("PROPERTYPANELSTATE"));
  52106. const StringArray sections (getSectionNames());
  52107. for (int i = 0; i < sections.size(); ++i)
  52108. {
  52109. if (sections[i].isNotEmpty())
  52110. {
  52111. XmlElement* const e = new XmlElement (T("SECTION"));
  52112. e->setAttribute (T("name"), sections[i]);
  52113. e->setAttribute (T("open"), isSectionOpen (i) ? 1 : 0);
  52114. xml->addChildElement (e);
  52115. }
  52116. }
  52117. return xml;
  52118. }
  52119. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  52120. {
  52121. if (xml.hasTagName (T("PROPERTYPANELSTATE")))
  52122. {
  52123. const StringArray sections (getSectionNames());
  52124. forEachXmlChildElementWithTagName (xml, e, T("SECTION"))
  52125. {
  52126. setSectionOpen (sections.indexOf (e->getStringAttribute (T("name"))),
  52127. e->getBoolAttribute (T("open")));
  52128. }
  52129. }
  52130. }
  52131. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  52132. {
  52133. if (messageWhenEmpty != newMessage)
  52134. {
  52135. messageWhenEmpty = newMessage;
  52136. repaint();
  52137. }
  52138. }
  52139. const String& PropertyPanel::getMessageWhenEmpty() const throw()
  52140. {
  52141. return messageWhenEmpty;
  52142. }
  52143. END_JUCE_NAMESPACE
  52144. /********* End of inlined file: juce_PropertyPanel.cpp *********/
  52145. /********* Start of inlined file: juce_SliderPropertyComponent.cpp *********/
  52146. BEGIN_JUCE_NAMESPACE
  52147. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  52148. const double rangeMin,
  52149. const double rangeMax,
  52150. const double interval,
  52151. const double skewFactor)
  52152. : PropertyComponent (name)
  52153. {
  52154. addAndMakeVisible (slider = new Slider (name));
  52155. slider->setRange (rangeMin, rangeMax, interval);
  52156. slider->setSkewFactor (skewFactor);
  52157. slider->setSliderStyle (Slider::LinearBar);
  52158. slider->addListener (this);
  52159. }
  52160. SliderPropertyComponent::~SliderPropertyComponent()
  52161. {
  52162. deleteAllChildren();
  52163. }
  52164. void SliderPropertyComponent::refresh()
  52165. {
  52166. slider->setValue (getValue(), false);
  52167. }
  52168. void SliderPropertyComponent::sliderValueChanged (Slider*)
  52169. {
  52170. if (getValue() != slider->getValue())
  52171. setValue (slider->getValue());
  52172. }
  52173. END_JUCE_NAMESPACE
  52174. /********* End of inlined file: juce_SliderPropertyComponent.cpp *********/
  52175. /********* Start of inlined file: juce_TextPropertyComponent.cpp *********/
  52176. BEGIN_JUCE_NAMESPACE
  52177. class TextPropLabel : public Label
  52178. {
  52179. TextPropertyComponent& owner;
  52180. int maxChars;
  52181. bool isMultiline;
  52182. public:
  52183. TextPropLabel (TextPropertyComponent& owner_,
  52184. const int maxChars_, const bool isMultiline_)
  52185. : Label (String::empty, String::empty),
  52186. owner (owner_),
  52187. maxChars (maxChars_),
  52188. isMultiline (isMultiline_)
  52189. {
  52190. setEditable (true, true, false);
  52191. setColour (backgroundColourId, Colours::white);
  52192. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  52193. }
  52194. ~TextPropLabel()
  52195. {
  52196. }
  52197. TextEditor* createEditorComponent()
  52198. {
  52199. TextEditor* const textEditor = Label::createEditorComponent();
  52200. textEditor->setInputRestrictions (maxChars);
  52201. if (isMultiline)
  52202. {
  52203. textEditor->setMultiLine (true, true);
  52204. textEditor->setReturnKeyStartsNewLine (true);
  52205. }
  52206. return textEditor;
  52207. }
  52208. void textWasEdited()
  52209. {
  52210. owner.textWasEdited();
  52211. }
  52212. };
  52213. TextPropertyComponent::TextPropertyComponent (const String& name,
  52214. const int maxNumChars,
  52215. const bool isMultiLine)
  52216. : PropertyComponent (name)
  52217. {
  52218. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  52219. if (isMultiLine)
  52220. {
  52221. textEditor->setJustificationType (Justification::topLeft);
  52222. preferredHeight = 120;
  52223. }
  52224. }
  52225. TextPropertyComponent::~TextPropertyComponent()
  52226. {
  52227. deleteAllChildren();
  52228. }
  52229. void TextPropertyComponent::refresh()
  52230. {
  52231. textEditor->setText (getText(), false);
  52232. }
  52233. void TextPropertyComponent::textWasEdited()
  52234. {
  52235. const String newText (textEditor->getText());
  52236. if (getText() != newText)
  52237. setText (newText);
  52238. }
  52239. END_JUCE_NAMESPACE
  52240. /********* End of inlined file: juce_TextPropertyComponent.cpp *********/
  52241. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  52242. BEGIN_JUCE_NAMESPACE
  52243. class SimpleDeviceManagerInputLevelMeter : public Component,
  52244. public Timer
  52245. {
  52246. public:
  52247. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  52248. : manager (manager_),
  52249. level (0)
  52250. {
  52251. startTimer (50);
  52252. manager->enableInputLevelMeasurement (true);
  52253. }
  52254. ~SimpleDeviceManagerInputLevelMeter()
  52255. {
  52256. manager->enableInputLevelMeasurement (false);
  52257. }
  52258. void timerCallback()
  52259. {
  52260. const float newLevel = (float) manager->getCurrentInputLevel();
  52261. if (fabsf (level - newLevel) > 0.005f)
  52262. {
  52263. level = newLevel;
  52264. repaint();
  52265. }
  52266. }
  52267. void paint (Graphics& g)
  52268. {
  52269. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(), level);
  52270. }
  52271. private:
  52272. AudioDeviceManager* const manager;
  52273. float level;
  52274. };
  52275. class MidiInputSelectorComponentListBox : public ListBox,
  52276. public ListBoxModel
  52277. {
  52278. public:
  52279. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  52280. const String& noItemsMessage_,
  52281. const int minNumber_,
  52282. const int maxNumber_)
  52283. : ListBox (String::empty, 0),
  52284. deviceManager (deviceManager_),
  52285. noItemsMessage (noItemsMessage_),
  52286. minNumber (minNumber_),
  52287. maxNumber (maxNumber_)
  52288. {
  52289. items = MidiInput::getDevices();
  52290. setModel (this);
  52291. setOutlineThickness (1);
  52292. }
  52293. ~MidiInputSelectorComponentListBox()
  52294. {
  52295. }
  52296. int getNumRows()
  52297. {
  52298. return items.size();
  52299. }
  52300. void paintListBoxItem (int row,
  52301. Graphics& g,
  52302. int width, int height,
  52303. bool rowIsSelected)
  52304. {
  52305. if (((unsigned int) row) < (unsigned int) items.size())
  52306. {
  52307. if (rowIsSelected)
  52308. g.fillAll (findColour (TextEditor::highlightColourId)
  52309. .withMultipliedAlpha (0.3f));
  52310. const String item (items [row]);
  52311. bool enabled = deviceManager.isMidiInputEnabled (item);
  52312. const int x = getTickX();
  52313. const int tickW = height - height / 4;
  52314. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  52315. enabled, true, true, false);
  52316. g.setFont (height * 0.6f);
  52317. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  52318. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  52319. }
  52320. }
  52321. void listBoxItemClicked (int row, const MouseEvent& e)
  52322. {
  52323. selectRow (row);
  52324. if (e.x < getTickX())
  52325. flipEnablement (row);
  52326. }
  52327. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  52328. {
  52329. flipEnablement (row);
  52330. }
  52331. void returnKeyPressed (int row)
  52332. {
  52333. flipEnablement (row);
  52334. }
  52335. void paint (Graphics& g)
  52336. {
  52337. ListBox::paint (g);
  52338. if (items.size() == 0)
  52339. {
  52340. g.setColour (Colours::grey);
  52341. g.setFont (13.0f);
  52342. g.drawText (noItemsMessage,
  52343. 0, 0, getWidth(), getHeight() / 2,
  52344. Justification::centred, true);
  52345. }
  52346. }
  52347. int getBestHeight (const int preferredHeight)
  52348. {
  52349. const int extra = getOutlineThickness() * 2;
  52350. return jmax (getRowHeight() * 2 + extra,
  52351. jmin (getRowHeight() * getNumRows() + extra,
  52352. preferredHeight));
  52353. }
  52354. juce_UseDebuggingNewOperator
  52355. private:
  52356. AudioDeviceManager& deviceManager;
  52357. const String noItemsMessage;
  52358. StringArray items;
  52359. int minNumber, maxNumber;
  52360. void flipEnablement (const int row)
  52361. {
  52362. if (((unsigned int) row) < (unsigned int) items.size())
  52363. {
  52364. const String item (items [row]);
  52365. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  52366. }
  52367. }
  52368. int getTickX() const throw()
  52369. {
  52370. return getRowHeight() + 5;
  52371. }
  52372. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  52373. const MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  52374. };
  52375. class AudioDeviceSettingsPanel : public Component,
  52376. public ComboBoxListener,
  52377. public ChangeListener,
  52378. public ButtonListener
  52379. {
  52380. public:
  52381. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  52382. AudioIODeviceType::DeviceSetupDetails& setup_,
  52383. const bool hideAdvancedOptionsWithButton)
  52384. : type (type_),
  52385. setup (setup_)
  52386. {
  52387. sampleRateDropDown = 0;
  52388. sampleRateLabel = 0;
  52389. bufferSizeDropDown = 0;
  52390. bufferSizeLabel = 0;
  52391. outputDeviceDropDown = 0;
  52392. outputDeviceLabel = 0;
  52393. inputDeviceDropDown = 0;
  52394. inputDeviceLabel = 0;
  52395. testButton = 0;
  52396. inputLevelMeter = 0;
  52397. showUIButton = 0;
  52398. inputChanList = 0;
  52399. outputChanList = 0;
  52400. inputChanLabel = 0;
  52401. outputChanLabel = 0;
  52402. showAdvancedSettingsButton = 0;
  52403. if (hideAdvancedOptionsWithButton)
  52404. {
  52405. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  52406. showAdvancedSettingsButton->addButtonListener (this);
  52407. }
  52408. type->scanForDevices();
  52409. setup.manager->addChangeListener (this);
  52410. changeListenerCallback (0);
  52411. }
  52412. ~AudioDeviceSettingsPanel()
  52413. {
  52414. setup.manager->removeChangeListener (this);
  52415. deleteAndZero (outputDeviceLabel);
  52416. deleteAndZero (inputDeviceLabel);
  52417. deleteAndZero (sampleRateLabel);
  52418. deleteAndZero (bufferSizeLabel);
  52419. deleteAndZero (showUIButton);
  52420. deleteAndZero (inputChanLabel);
  52421. deleteAndZero (outputChanLabel);
  52422. deleteAndZero (showAdvancedSettingsButton);
  52423. deleteAllChildren();
  52424. }
  52425. void resized()
  52426. {
  52427. const int lx = proportionOfWidth (0.35f);
  52428. const int w = proportionOfWidth (0.4f);
  52429. const int h = 24;
  52430. const int space = 6;
  52431. const int dh = h + space;
  52432. int y = 0;
  52433. if (outputDeviceDropDown != 0)
  52434. {
  52435. outputDeviceDropDown->setBounds (lx, y, w, h);
  52436. testButton->setBounds (proportionOfWidth (0.77f),
  52437. outputDeviceDropDown->getY(),
  52438. proportionOfWidth (0.18f),
  52439. h);
  52440. y += dh;
  52441. }
  52442. if (inputDeviceDropDown != 0)
  52443. {
  52444. inputDeviceDropDown->setBounds (lx, y, w, h);
  52445. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  52446. inputDeviceDropDown->getY(),
  52447. proportionOfWidth (0.18f),
  52448. h);
  52449. y += dh;
  52450. }
  52451. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  52452. if (outputChanList != 0)
  52453. {
  52454. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  52455. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  52456. y += bh + space;
  52457. }
  52458. if (inputChanList != 0)
  52459. {
  52460. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  52461. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  52462. y += bh + space;
  52463. }
  52464. y += space * 2;
  52465. if (showAdvancedSettingsButton != 0)
  52466. {
  52467. showAdvancedSettingsButton->changeWidthToFitText (h);
  52468. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  52469. }
  52470. if (sampleRateDropDown != 0)
  52471. {
  52472. sampleRateDropDown->setVisible (! showAdvancedSettingsButton->isVisible());
  52473. sampleRateDropDown->setBounds (lx, y, w, h);
  52474. y += dh;
  52475. }
  52476. if (bufferSizeDropDown != 0)
  52477. {
  52478. bufferSizeDropDown->setVisible (! showAdvancedSettingsButton->isVisible());
  52479. bufferSizeDropDown->setBounds (lx, y, w, h);
  52480. y += dh;
  52481. }
  52482. if (showUIButton != 0)
  52483. {
  52484. showUIButton->setVisible (! showAdvancedSettingsButton->isVisible());
  52485. showUIButton->changeWidthToFitText (h);
  52486. showUIButton->setTopLeftPosition (lx, y);
  52487. }
  52488. }
  52489. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  52490. {
  52491. if (comboBoxThatHasChanged == 0)
  52492. return;
  52493. AudioDeviceManager::AudioDeviceSetup config;
  52494. setup.manager->getAudioDeviceSetup (config);
  52495. String error;
  52496. if (comboBoxThatHasChanged == outputDeviceDropDown
  52497. || comboBoxThatHasChanged == inputDeviceDropDown)
  52498. {
  52499. if (outputDeviceDropDown != 0)
  52500. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  52501. : outputDeviceDropDown->getText();
  52502. if (inputDeviceDropDown != 0)
  52503. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  52504. : inputDeviceDropDown->getText();
  52505. if (! type->hasSeparateInputsAndOutputs())
  52506. config.inputDeviceName = config.outputDeviceName;
  52507. if (comboBoxThatHasChanged == inputDeviceDropDown)
  52508. config.useDefaultInputChannels = true;
  52509. else
  52510. config.useDefaultOutputChannels = true;
  52511. error = setup.manager->setAudioDeviceSetup (config, true);
  52512. showCorrectDeviceName (inputDeviceDropDown, true);
  52513. showCorrectDeviceName (outputDeviceDropDown, false);
  52514. updateControlPanelButton();
  52515. resized();
  52516. }
  52517. else if (comboBoxThatHasChanged == sampleRateDropDown)
  52518. {
  52519. if (sampleRateDropDown->getSelectedId() > 0)
  52520. {
  52521. config.sampleRate = sampleRateDropDown->getSelectedId();
  52522. error = setup.manager->setAudioDeviceSetup (config, true);
  52523. }
  52524. }
  52525. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  52526. {
  52527. if (bufferSizeDropDown->getSelectedId() > 0)
  52528. {
  52529. config.bufferSize = bufferSizeDropDown->getSelectedId();
  52530. error = setup.manager->setAudioDeviceSetup (config, true);
  52531. }
  52532. }
  52533. if (error.isNotEmpty())
  52534. {
  52535. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  52536. T("Error when trying to open audio device!"),
  52537. error);
  52538. }
  52539. }
  52540. void buttonClicked (Button* button)
  52541. {
  52542. if (button == showAdvancedSettingsButton)
  52543. {
  52544. showAdvancedSettingsButton->setVisible (false);
  52545. resized();
  52546. }
  52547. else if (button == showUIButton)
  52548. {
  52549. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  52550. if (device != 0 && device->showControlPanel())
  52551. {
  52552. setup.manager->closeAudioDevice();
  52553. setup.manager->restartLastAudioDevice();
  52554. getTopLevelComponent()->toFront (true);
  52555. }
  52556. }
  52557. else if (button == testButton)
  52558. {
  52559. setup.manager->playTestSound();
  52560. }
  52561. }
  52562. void updateControlPanelButton()
  52563. {
  52564. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  52565. deleteAndZero (showUIButton);
  52566. if (currentDevice != 0 && currentDevice->hasControlPanel())
  52567. {
  52568. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  52569. TRANS ("opens the device's own control panel")));
  52570. showUIButton->addButtonListener (this);
  52571. }
  52572. resized();
  52573. }
  52574. void changeListenerCallback (void*)
  52575. {
  52576. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  52577. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  52578. {
  52579. if (outputDeviceDropDown == 0)
  52580. {
  52581. outputDeviceDropDown = new ComboBox (String::empty);
  52582. outputDeviceDropDown->addListener (this);
  52583. addAndMakeVisible (outputDeviceDropDown);
  52584. outputDeviceLabel = new Label (String::empty,
  52585. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  52586. : TRANS ("device:"));
  52587. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  52588. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  52589. testButton->addButtonListener (this);
  52590. }
  52591. addNamesToDeviceBox (*outputDeviceDropDown, false);
  52592. }
  52593. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  52594. {
  52595. if (inputDeviceDropDown == 0)
  52596. {
  52597. inputDeviceDropDown = new ComboBox (String::empty);
  52598. inputDeviceDropDown->addListener (this);
  52599. addAndMakeVisible (inputDeviceDropDown);
  52600. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  52601. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  52602. addAndMakeVisible (inputLevelMeter
  52603. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  52604. }
  52605. addNamesToDeviceBox (*inputDeviceDropDown, true);
  52606. }
  52607. updateControlPanelButton();
  52608. showCorrectDeviceName (inputDeviceDropDown, true);
  52609. showCorrectDeviceName (outputDeviceDropDown, false);
  52610. if (currentDevice != 0)
  52611. {
  52612. if (setup.maxNumOutputChannels > 0
  52613. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  52614. {
  52615. if (outputChanList == 0)
  52616. {
  52617. addAndMakeVisible (outputChanList
  52618. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  52619. TRANS ("(no audio output channels found)")));
  52620. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  52621. outputChanLabel->attachToComponent (outputChanList, true);
  52622. }
  52623. outputChanList->refresh();
  52624. }
  52625. else
  52626. {
  52627. deleteAndZero (outputChanLabel);
  52628. deleteAndZero (outputChanList);
  52629. }
  52630. if (setup.maxNumInputChannels > 0
  52631. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  52632. {
  52633. if (inputChanList == 0)
  52634. {
  52635. addAndMakeVisible (inputChanList
  52636. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  52637. TRANS ("(no audio input channels found)")));
  52638. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  52639. inputChanLabel->attachToComponent (inputChanList, true);
  52640. }
  52641. inputChanList->refresh();
  52642. }
  52643. else
  52644. {
  52645. deleteAndZero (inputChanLabel);
  52646. deleteAndZero (inputChanList);
  52647. }
  52648. // sample rate..
  52649. {
  52650. if (sampleRateDropDown == 0)
  52651. {
  52652. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  52653. sampleRateDropDown->addListener (this);
  52654. delete sampleRateLabel;
  52655. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  52656. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  52657. }
  52658. else
  52659. {
  52660. sampleRateDropDown->clear();
  52661. sampleRateDropDown->removeListener (this);
  52662. }
  52663. const int numRates = currentDevice->getNumSampleRates();
  52664. for (int i = 0; i < numRates; ++i)
  52665. {
  52666. const int rate = roundDoubleToInt (currentDevice->getSampleRate (i));
  52667. sampleRateDropDown->addItem (String (rate) + T(" Hz"), rate);
  52668. }
  52669. sampleRateDropDown->setSelectedId (roundDoubleToInt (currentDevice->getCurrentSampleRate()), true);
  52670. sampleRateDropDown->addListener (this);
  52671. }
  52672. // buffer size
  52673. {
  52674. if (bufferSizeDropDown == 0)
  52675. {
  52676. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  52677. bufferSizeDropDown->addListener (this);
  52678. delete bufferSizeLabel;
  52679. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  52680. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  52681. }
  52682. else
  52683. {
  52684. bufferSizeDropDown->clear();
  52685. }
  52686. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  52687. double currentRate = currentDevice->getCurrentSampleRate();
  52688. if (currentRate == 0)
  52689. currentRate = 48000.0;
  52690. for (int i = 0; i < numBufferSizes; ++i)
  52691. {
  52692. const int bs = currentDevice->getBufferSizeSamples (i);
  52693. bufferSizeDropDown->addItem (String (bs)
  52694. + T(" samples (")
  52695. + String (bs * 1000.0 / currentRate, 1)
  52696. + T(" ms)"),
  52697. bs);
  52698. }
  52699. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  52700. }
  52701. }
  52702. else
  52703. {
  52704. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  52705. deleteAndZero (sampleRateLabel);
  52706. deleteAndZero (bufferSizeLabel);
  52707. deleteAndZero (sampleRateDropDown);
  52708. deleteAndZero (bufferSizeDropDown);
  52709. if (outputDeviceDropDown != 0)
  52710. outputDeviceDropDown->setSelectedId (-1, true);
  52711. if (inputDeviceDropDown != 0)
  52712. inputDeviceDropDown->setSelectedId (-1, true);
  52713. }
  52714. resized();
  52715. setSize (getWidth(), getLowestY() + 4);
  52716. }
  52717. private:
  52718. AudioIODeviceType* const type;
  52719. const AudioIODeviceType::DeviceSetupDetails setup;
  52720. ComboBox* outputDeviceDropDown;
  52721. ComboBox* inputDeviceDropDown;
  52722. ComboBox* sampleRateDropDown;
  52723. ComboBox* bufferSizeDropDown;
  52724. Label* outputDeviceLabel;
  52725. Label* inputDeviceLabel;
  52726. Label* sampleRateLabel;
  52727. Label* bufferSizeLabel;
  52728. Label* inputChanLabel;
  52729. Label* outputChanLabel;
  52730. TextButton* testButton;
  52731. Component* inputLevelMeter;
  52732. TextButton* showUIButton;
  52733. TextButton* showAdvancedSettingsButton;
  52734. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  52735. {
  52736. if (box != 0)
  52737. {
  52738. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  52739. const int index = type->getIndexOfDevice (currentDevice, isInput);
  52740. box->setSelectedId (index + 1, true);
  52741. if (! isInput)
  52742. testButton->setEnabled (index >= 0);
  52743. }
  52744. }
  52745. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  52746. {
  52747. const StringArray devs (type->getDeviceNames (isInputs));
  52748. combo.clear (true);
  52749. for (int i = 0; i < devs.size(); ++i)
  52750. combo.addItem (devs[i], i + 1);
  52751. combo.addItem (TRANS("<< none >>"), -1);
  52752. combo.setSelectedId (-1, true);
  52753. }
  52754. int getLowestY() const
  52755. {
  52756. int y = 0;
  52757. for (int i = getNumChildComponents(); --i >= 0;)
  52758. y = jmax (y, getChildComponent (i)->getBottom());
  52759. return y;
  52760. }
  52761. class ChannelSelectorListBox : public ListBox,
  52762. public ListBoxModel
  52763. {
  52764. public:
  52765. enum BoxType
  52766. {
  52767. audioInputType,
  52768. audioOutputType
  52769. };
  52770. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  52771. const BoxType type_,
  52772. const String& noItemsMessage_)
  52773. : ListBox (String::empty, 0),
  52774. setup (setup_),
  52775. type (type_),
  52776. noItemsMessage (noItemsMessage_)
  52777. {
  52778. refresh();
  52779. setModel (this);
  52780. setOutlineThickness (1);
  52781. }
  52782. ~ChannelSelectorListBox()
  52783. {
  52784. }
  52785. void refresh()
  52786. {
  52787. items.clear();
  52788. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  52789. if (currentDevice != 0)
  52790. {
  52791. if (type == audioInputType)
  52792. items = currentDevice->getInputChannelNames();
  52793. else if (type == audioOutputType)
  52794. items = currentDevice->getOutputChannelNames();
  52795. if (setup.useStereoPairs)
  52796. {
  52797. StringArray pairs;
  52798. for (int i = 0; i < items.size(); i += 2)
  52799. {
  52800. String name (items[i]);
  52801. String name2 (items[i + 1]);
  52802. String commonBit;
  52803. for (int j = 0; j < name.length(); ++j)
  52804. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  52805. commonBit = name.substring (0, j);
  52806. pairs.add (name.trim()
  52807. + " + "
  52808. + name2.substring (commonBit.length()).trim());
  52809. }
  52810. items = pairs;
  52811. }
  52812. }
  52813. updateContent();
  52814. repaint();
  52815. }
  52816. int getNumRows()
  52817. {
  52818. return items.size();
  52819. }
  52820. void paintListBoxItem (int row,
  52821. Graphics& g,
  52822. int width, int height,
  52823. bool rowIsSelected)
  52824. {
  52825. if (((unsigned int) row) < (unsigned int) items.size())
  52826. {
  52827. if (rowIsSelected)
  52828. g.fillAll (findColour (TextEditor::highlightColourId)
  52829. .withMultipliedAlpha (0.3f));
  52830. const String item (items [row]);
  52831. bool enabled = false;
  52832. AudioDeviceManager::AudioDeviceSetup config;
  52833. setup.manager->getAudioDeviceSetup (config);
  52834. if (setup.useStereoPairs)
  52835. {
  52836. if (type == audioInputType)
  52837. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  52838. else if (type == audioOutputType)
  52839. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  52840. }
  52841. else
  52842. {
  52843. if (type == audioInputType)
  52844. enabled = config.inputChannels [row];
  52845. else if (type == audioOutputType)
  52846. enabled = config.outputChannels [row];
  52847. }
  52848. const int x = getTickX();
  52849. const int tickW = height - height / 4;
  52850. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  52851. enabled, true, true, false);
  52852. g.setFont (height * 0.6f);
  52853. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  52854. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  52855. }
  52856. }
  52857. void listBoxItemClicked (int row, const MouseEvent& e)
  52858. {
  52859. selectRow (row);
  52860. if (e.x < getTickX())
  52861. flipEnablement (row);
  52862. }
  52863. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  52864. {
  52865. flipEnablement (row);
  52866. }
  52867. void returnKeyPressed (int row)
  52868. {
  52869. flipEnablement (row);
  52870. }
  52871. void paint (Graphics& g)
  52872. {
  52873. ListBox::paint (g);
  52874. if (items.size() == 0)
  52875. {
  52876. g.setColour (Colours::grey);
  52877. g.setFont (13.0f);
  52878. g.drawText (noItemsMessage,
  52879. 0, 0, getWidth(), getHeight() / 2,
  52880. Justification::centred, true);
  52881. }
  52882. }
  52883. int getBestHeight (int maxHeight)
  52884. {
  52885. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  52886. getNumRows())
  52887. + getOutlineThickness() * 2;
  52888. }
  52889. juce_UseDebuggingNewOperator
  52890. private:
  52891. const AudioIODeviceType::DeviceSetupDetails setup;
  52892. const BoxType type;
  52893. const String noItemsMessage;
  52894. StringArray items;
  52895. void flipEnablement (const int row)
  52896. {
  52897. jassert (type == audioInputType || type == audioOutputType);
  52898. if (((unsigned int) row) < (unsigned int) items.size())
  52899. {
  52900. AudioDeviceManager::AudioDeviceSetup config;
  52901. setup.manager->getAudioDeviceSetup (config);
  52902. if (setup.useStereoPairs)
  52903. {
  52904. BitArray bits;
  52905. BitArray& original = (type == audioInputType ? config.inputChannels
  52906. : config.outputChannels);
  52907. int i;
  52908. for (i = 0; i < 256; i += 2)
  52909. bits.setBit (i / 2, original [i] || original [i + 1]);
  52910. if (type == audioInputType)
  52911. {
  52912. config.useDefaultInputChannels = false;
  52913. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  52914. }
  52915. else
  52916. {
  52917. config.useDefaultOutputChannels = false;
  52918. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  52919. }
  52920. for (i = 0; i < 256; ++i)
  52921. original.setBit (i, bits [i / 2]);
  52922. }
  52923. else
  52924. {
  52925. if (type == audioInputType)
  52926. {
  52927. config.useDefaultInputChannels = false;
  52928. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  52929. }
  52930. else
  52931. {
  52932. config.useDefaultOutputChannels = false;
  52933. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  52934. }
  52935. }
  52936. String error (setup.manager->setAudioDeviceSetup (config, true));
  52937. if (! error.isEmpty())
  52938. {
  52939. //xxx
  52940. }
  52941. }
  52942. }
  52943. static void flipBit (BitArray& chans, int index, int minNumber, int maxNumber)
  52944. {
  52945. const int numActive = chans.countNumberOfSetBits();
  52946. if (chans [index])
  52947. {
  52948. if (numActive > minNumber)
  52949. chans.setBit (index, false);
  52950. }
  52951. else
  52952. {
  52953. if (numActive >= maxNumber)
  52954. {
  52955. const int firstActiveChan = chans.findNextSetBit();
  52956. chans.setBit (index > firstActiveChan
  52957. ? firstActiveChan : chans.getHighestBit(),
  52958. false);
  52959. }
  52960. chans.setBit (index, true);
  52961. }
  52962. }
  52963. int getTickX() const throw()
  52964. {
  52965. return getRowHeight() + 5;
  52966. }
  52967. ChannelSelectorListBox (const ChannelSelectorListBox&);
  52968. const ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  52969. };
  52970. ChannelSelectorListBox* inputChanList;
  52971. ChannelSelectorListBox* outputChanList;
  52972. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  52973. const AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  52974. };
  52975. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  52976. const int minInputChannels_,
  52977. const int maxInputChannels_,
  52978. const int minOutputChannels_,
  52979. const int maxOutputChannels_,
  52980. const bool showMidiInputOptions,
  52981. const bool showMidiOutputSelector,
  52982. const bool showChannelsAsStereoPairs_,
  52983. const bool hideAdvancedOptionsWithButton_)
  52984. : deviceManager (deviceManager_),
  52985. minOutputChannels (minOutputChannels_),
  52986. maxOutputChannels (maxOutputChannels_),
  52987. minInputChannels (minInputChannels_),
  52988. maxInputChannels (maxInputChannels_),
  52989. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  52990. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_),
  52991. deviceTypeDropDown (0),
  52992. deviceTypeDropDownLabel (0),
  52993. audioDeviceSettingsComp (0)
  52994. {
  52995. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  52996. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  52997. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  52998. {
  52999. deviceTypeDropDown = new ComboBox (String::empty);
  53000. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  53001. {
  53002. deviceTypeDropDown
  53003. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  53004. i + 1);
  53005. }
  53006. addAndMakeVisible (deviceTypeDropDown);
  53007. deviceTypeDropDown->addListener (this);
  53008. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  53009. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  53010. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  53011. }
  53012. if (showMidiInputOptions)
  53013. {
  53014. addAndMakeVisible (midiInputsList
  53015. = new MidiInputSelectorComponentListBox (deviceManager,
  53016. TRANS("(no midi inputs available)"),
  53017. 0, 0));
  53018. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  53019. midiInputsLabel->setJustificationType (Justification::topRight);
  53020. midiInputsLabel->attachToComponent (midiInputsList, true);
  53021. }
  53022. else
  53023. {
  53024. midiInputsList = 0;
  53025. midiInputsLabel = 0;
  53026. }
  53027. if (showMidiOutputSelector)
  53028. {
  53029. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  53030. midiOutputSelector->addListener (this);
  53031. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  53032. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  53033. }
  53034. else
  53035. {
  53036. midiOutputSelector = 0;
  53037. midiOutputLabel = 0;
  53038. }
  53039. deviceManager_.addChangeListener (this);
  53040. changeListenerCallback (0);
  53041. }
  53042. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  53043. {
  53044. deviceManager.removeChangeListener (this);
  53045. deleteAllChildren();
  53046. }
  53047. void AudioDeviceSelectorComponent::resized()
  53048. {
  53049. const int lx = proportionOfWidth (0.35f);
  53050. const int w = proportionOfWidth (0.4f);
  53051. const int h = 24;
  53052. const int space = 6;
  53053. const int dh = h + space;
  53054. int y = 15;
  53055. if (deviceTypeDropDown != 0)
  53056. {
  53057. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  53058. y += dh + space * 2;
  53059. }
  53060. if (audioDeviceSettingsComp != 0)
  53061. {
  53062. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  53063. y += audioDeviceSettingsComp->getHeight() + space;
  53064. }
  53065. if (midiInputsList != 0)
  53066. {
  53067. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space));
  53068. midiInputsList->setBounds (lx, y, w, bh);
  53069. y += bh + space;
  53070. }
  53071. if (midiOutputSelector != 0)
  53072. midiOutputSelector->setBounds (lx, y, w, h);
  53073. }
  53074. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  53075. {
  53076. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  53077. if (device != 0 && device->hasControlPanel())
  53078. {
  53079. if (device->showControlPanel())
  53080. deviceManager.restartLastAudioDevice();
  53081. getTopLevelComponent()->toFront (true);
  53082. }
  53083. }
  53084. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  53085. {
  53086. if (comboBoxThatHasChanged == deviceTypeDropDown)
  53087. {
  53088. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  53089. if (type != 0)
  53090. {
  53091. deleteAndZero (audioDeviceSettingsComp);
  53092. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  53093. changeListenerCallback (0); // needed in case the type hasn't actally changed
  53094. }
  53095. }
  53096. else if (comboBoxThatHasChanged == midiOutputSelector)
  53097. {
  53098. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  53099. }
  53100. }
  53101. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  53102. {
  53103. if (deviceTypeDropDown != 0)
  53104. {
  53105. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  53106. }
  53107. if (audioDeviceSettingsComp == 0
  53108. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  53109. {
  53110. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  53111. deleteAndZero (audioDeviceSettingsComp);
  53112. AudioIODeviceType* const type
  53113. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  53114. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  53115. if (type != 0)
  53116. {
  53117. AudioIODeviceType::DeviceSetupDetails details;
  53118. details.manager = &deviceManager;
  53119. details.minNumInputChannels = minInputChannels;
  53120. details.maxNumInputChannels = maxInputChannels;
  53121. details.minNumOutputChannels = minOutputChannels;
  53122. details.maxNumOutputChannels = maxOutputChannels;
  53123. details.useStereoPairs = showChannelsAsStereoPairs;
  53124. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  53125. if (audioDeviceSettingsComp != 0)
  53126. {
  53127. addAndMakeVisible (audioDeviceSettingsComp);
  53128. audioDeviceSettingsComp->resized();
  53129. }
  53130. }
  53131. }
  53132. if (midiInputsList != 0)
  53133. {
  53134. midiInputsList->updateContent();
  53135. midiInputsList->repaint();
  53136. }
  53137. if (midiOutputSelector != 0)
  53138. {
  53139. midiOutputSelector->clear();
  53140. const StringArray midiOuts (MidiOutput::getDevices());
  53141. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  53142. midiOutputSelector->addSeparator();
  53143. for (int i = 0; i < midiOuts.size(); ++i)
  53144. midiOutputSelector->addItem (midiOuts[i], i + 1);
  53145. int current = -1;
  53146. if (deviceManager.getDefaultMidiOutput() != 0)
  53147. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  53148. midiOutputSelector->setSelectedId (current, true);
  53149. }
  53150. resized();
  53151. }
  53152. END_JUCE_NAMESPACE
  53153. /********* End of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  53154. /********* Start of inlined file: juce_BubbleComponent.cpp *********/
  53155. BEGIN_JUCE_NAMESPACE
  53156. BubbleComponent::BubbleComponent()
  53157. : side (0),
  53158. allowablePlacements (above | below | left | right),
  53159. arrowTipX (0.0f),
  53160. arrowTipY (0.0f)
  53161. {
  53162. setInterceptsMouseClicks (false, false);
  53163. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  53164. setComponentEffect (&shadow);
  53165. }
  53166. BubbleComponent::~BubbleComponent()
  53167. {
  53168. }
  53169. void BubbleComponent::paint (Graphics& g)
  53170. {
  53171. int x = content.getX();
  53172. int y = content.getY();
  53173. int w = content.getWidth();
  53174. int h = content.getHeight();
  53175. int cw, ch;
  53176. getContentSize (cw, ch);
  53177. if (side == 3)
  53178. x += w - cw;
  53179. else if (side != 1)
  53180. x += (w - cw) / 2;
  53181. w = cw;
  53182. if (side == 2)
  53183. y += h - ch;
  53184. else if (side != 0)
  53185. y += (h - ch) / 2;
  53186. h = ch;
  53187. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  53188. (float) x, (float) y,
  53189. (float) w, (float) h);
  53190. const int cx = x + (w - cw) / 2;
  53191. const int cy = y + (h - ch) / 2;
  53192. const int indent = 3;
  53193. g.setOrigin (cx + indent, cy + indent);
  53194. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  53195. paintContent (g, cw - indent * 2, ch - indent * 2);
  53196. }
  53197. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  53198. {
  53199. allowablePlacements = newPlacement;
  53200. }
  53201. void BubbleComponent::setPosition (Component* componentToPointTo)
  53202. {
  53203. jassert (componentToPointTo->isValidComponent());
  53204. int tx = 0;
  53205. int ty = 0;
  53206. if (getParentComponent() != 0)
  53207. componentToPointTo->relativePositionToOtherComponent (getParentComponent(), tx, ty);
  53208. else
  53209. componentToPointTo->relativePositionToGlobal (tx, ty);
  53210. setPosition (Rectangle (tx, ty, componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  53211. }
  53212. void BubbleComponent::setPosition (const int arrowTipX,
  53213. const int arrowTipY)
  53214. {
  53215. setPosition (Rectangle (arrowTipX, arrowTipY, 1, 1));
  53216. }
  53217. void BubbleComponent::setPosition (const Rectangle& rectangleToPointTo)
  53218. {
  53219. Rectangle availableSpace;
  53220. if (getParentComponent() != 0)
  53221. {
  53222. availableSpace.setSize (getParentComponent()->getWidth(),
  53223. getParentComponent()->getHeight());
  53224. }
  53225. else
  53226. {
  53227. availableSpace = getParentMonitorArea();
  53228. }
  53229. int x = 0;
  53230. int y = 0;
  53231. int w = 150;
  53232. int h = 30;
  53233. getContentSize (w, h);
  53234. w += 30;
  53235. h += 30;
  53236. const float edgeIndent = 2.0f;
  53237. const int arrowLength = jmin (10, h / 3, w / 3);
  53238. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  53239. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  53240. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  53241. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  53242. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  53243. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  53244. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  53245. {
  53246. spaceLeft = spaceRight = 0;
  53247. }
  53248. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  53249. && (spaceLeft > w + 20 || spaceRight > w + 20))
  53250. {
  53251. spaceAbove = spaceBelow = 0;
  53252. }
  53253. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  53254. {
  53255. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  53256. arrowTipX = w * 0.5f;
  53257. content.setSize (w, h - arrowLength);
  53258. if (spaceAbove >= spaceBelow)
  53259. {
  53260. // above
  53261. y = rectangleToPointTo.getY() - h;
  53262. content.setPosition (0, 0);
  53263. arrowTipY = h - edgeIndent;
  53264. side = 2;
  53265. }
  53266. else
  53267. {
  53268. // below
  53269. y = rectangleToPointTo.getBottom();
  53270. content.setPosition (0, arrowLength);
  53271. arrowTipY = edgeIndent;
  53272. side = 0;
  53273. }
  53274. }
  53275. else
  53276. {
  53277. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  53278. arrowTipY = h * 0.5f;
  53279. content.setSize (w - arrowLength, h);
  53280. if (spaceLeft > spaceRight)
  53281. {
  53282. // on the left
  53283. x = rectangleToPointTo.getX() - w;
  53284. content.setPosition (0, 0);
  53285. arrowTipX = w - edgeIndent;
  53286. side = 3;
  53287. }
  53288. else
  53289. {
  53290. // on the right
  53291. x = rectangleToPointTo.getRight();
  53292. content.setPosition (arrowLength, 0);
  53293. arrowTipX = edgeIndent;
  53294. side = 1;
  53295. }
  53296. }
  53297. setBounds (x, y, w, h);
  53298. }
  53299. END_JUCE_NAMESPACE
  53300. /********* End of inlined file: juce_BubbleComponent.cpp *********/
  53301. /********* Start of inlined file: juce_BubbleMessageComponent.cpp *********/
  53302. BEGIN_JUCE_NAMESPACE
  53303. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  53304. : fadeOutLength (fadeOutLengthMs),
  53305. deleteAfterUse (false)
  53306. {
  53307. }
  53308. BubbleMessageComponent::~BubbleMessageComponent()
  53309. {
  53310. fadeOutComponent (fadeOutLength);
  53311. }
  53312. void BubbleMessageComponent::showAt (int x, int y,
  53313. const String& text,
  53314. const int numMillisecondsBeforeRemoving,
  53315. const bool removeWhenMouseClicked,
  53316. const bool deleteSelfAfterUse)
  53317. {
  53318. textLayout.clear();
  53319. textLayout.setText (text, Font (14.0f));
  53320. textLayout.layout (256, Justification::centredLeft, true);
  53321. setPosition (x, y);
  53322. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  53323. }
  53324. void BubbleMessageComponent::showAt (Component* const component,
  53325. const String& text,
  53326. const int numMillisecondsBeforeRemoving,
  53327. const bool removeWhenMouseClicked,
  53328. const bool deleteSelfAfterUse)
  53329. {
  53330. textLayout.clear();
  53331. textLayout.setText (text, Font (14.0f));
  53332. textLayout.layout (256, Justification::centredLeft, true);
  53333. setPosition (component);
  53334. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  53335. }
  53336. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  53337. const bool removeWhenMouseClicked,
  53338. const bool deleteSelfAfterUse)
  53339. {
  53340. setVisible (true);
  53341. deleteAfterUse = deleteSelfAfterUse;
  53342. if (numMillisecondsBeforeRemoving > 0)
  53343. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  53344. else
  53345. expiryTime = 0;
  53346. startTimer (77);
  53347. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  53348. if (! (removeWhenMouseClicked && isShowing()))
  53349. mouseClickCounter += 0xfffff;
  53350. repaint();
  53351. }
  53352. void BubbleMessageComponent::getContentSize (int& w, int& h)
  53353. {
  53354. w = textLayout.getWidth() + 16;
  53355. h = textLayout.getHeight() + 16;
  53356. }
  53357. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  53358. {
  53359. g.setColour (findColour (TooltipWindow::textColourId));
  53360. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  53361. }
  53362. void BubbleMessageComponent::timerCallback()
  53363. {
  53364. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  53365. {
  53366. stopTimer();
  53367. setVisible (false);
  53368. if (deleteAfterUse)
  53369. delete this;
  53370. }
  53371. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  53372. {
  53373. stopTimer();
  53374. fadeOutComponent (fadeOutLength);
  53375. if (deleteAfterUse)
  53376. delete this;
  53377. }
  53378. }
  53379. END_JUCE_NAMESPACE
  53380. /********* End of inlined file: juce_BubbleMessageComponent.cpp *********/
  53381. /********* Start of inlined file: juce_ColourSelector.cpp *********/
  53382. BEGIN_JUCE_NAMESPACE
  53383. static const int swatchesPerRow = 8;
  53384. static const int swatchHeight = 22;
  53385. class ColourComponentSlider : public Slider
  53386. {
  53387. public:
  53388. ColourComponentSlider (const String& name)
  53389. : Slider (name)
  53390. {
  53391. setRange (0.0, 255.0, 1.0);
  53392. }
  53393. ~ColourComponentSlider()
  53394. {
  53395. }
  53396. const String getTextFromValue (double currentValue)
  53397. {
  53398. return String::formatted (T("%02X"), (int)currentValue);
  53399. }
  53400. double getValueFromText (const String& text)
  53401. {
  53402. return (double) text.getHexValue32();
  53403. }
  53404. private:
  53405. ColourComponentSlider (const ColourComponentSlider&);
  53406. const ColourComponentSlider& operator= (const ColourComponentSlider&);
  53407. };
  53408. class ColourSpaceMarker : public Component
  53409. {
  53410. public:
  53411. ColourSpaceMarker()
  53412. {
  53413. setInterceptsMouseClicks (false, false);
  53414. }
  53415. ~ColourSpaceMarker()
  53416. {
  53417. }
  53418. void paint (Graphics& g)
  53419. {
  53420. g.setColour (Colour::greyLevel (0.1f));
  53421. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  53422. g.setColour (Colour::greyLevel (0.9f));
  53423. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  53424. }
  53425. private:
  53426. ColourSpaceMarker (const ColourSpaceMarker&);
  53427. const ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  53428. };
  53429. class ColourSpaceView : public Component
  53430. {
  53431. ColourSelector* const owner;
  53432. float& h;
  53433. float& s;
  53434. float& v;
  53435. float lastHue;
  53436. ColourSpaceMarker* marker;
  53437. const int edge;
  53438. public:
  53439. ColourSpaceView (ColourSelector* owner_,
  53440. float& h_, float& s_, float& v_,
  53441. const int edgeSize)
  53442. : owner (owner_),
  53443. h (h_), s (s_), v (v_),
  53444. lastHue (0.0f),
  53445. edge (edgeSize)
  53446. {
  53447. addAndMakeVisible (marker = new ColourSpaceMarker());
  53448. setMouseCursor (MouseCursor::CrosshairCursor);
  53449. }
  53450. ~ColourSpaceView()
  53451. {
  53452. deleteAllChildren();
  53453. }
  53454. void paint (Graphics& g)
  53455. {
  53456. const float hue = h;
  53457. const float xScale = 1.0f / (getWidth() - edge * 2);
  53458. const float yScale = 1.0f / (getHeight() - edge * 2);
  53459. const Rectangle clip (g.getClipBounds());
  53460. const int x1 = jmax (clip.getX(), edge) & ~1;
  53461. const int x2 = jmin (clip.getRight(), getWidth() - edge) | 1;
  53462. const int y1 = jmax (clip.getY(), edge) & ~1;
  53463. const int y2 = jmin (clip.getBottom(), getHeight() - edge) | 1;
  53464. for (int y = y1; y < y2; y += 2)
  53465. {
  53466. const float v = jlimit (0.0f, 1.0f, 1.0f - (y - edge) * yScale);
  53467. for (int x = x1; x < x2; x += 2)
  53468. {
  53469. const float s = jlimit (0.0f, 1.0f, (x - edge) * xScale);
  53470. g.setColour (Colour (hue, s, v, 1.0f));
  53471. g.fillRect (x, y, 2, 2);
  53472. }
  53473. }
  53474. }
  53475. void mouseDown (const MouseEvent& e)
  53476. {
  53477. mouseDrag (e);
  53478. }
  53479. void mouseDrag (const MouseEvent& e)
  53480. {
  53481. const float s = (e.x - edge) / (float) (getWidth() - edge * 2);
  53482. const float v = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  53483. owner->setSV (s, v);
  53484. }
  53485. void updateIfNeeded()
  53486. {
  53487. if (lastHue != h)
  53488. {
  53489. lastHue = h;
  53490. repaint();
  53491. }
  53492. resized();
  53493. }
  53494. void resized()
  53495. {
  53496. marker->setBounds (roundFloatToInt ((getWidth() - edge * 2) * s),
  53497. roundFloatToInt ((getHeight() - edge * 2) * (1.0f - v)),
  53498. edge * 2, edge * 2);
  53499. }
  53500. private:
  53501. ColourSpaceView (const ColourSpaceView&);
  53502. const ColourSpaceView& operator= (const ColourSpaceView&);
  53503. };
  53504. class HueSelectorMarker : public Component
  53505. {
  53506. public:
  53507. HueSelectorMarker()
  53508. {
  53509. setInterceptsMouseClicks (false, false);
  53510. }
  53511. ~HueSelectorMarker()
  53512. {
  53513. }
  53514. void paint (Graphics& g)
  53515. {
  53516. Path p;
  53517. p.addTriangle (1.0f, 1.0f,
  53518. getWidth() * 0.3f, getHeight() * 0.5f,
  53519. 1.0f, getHeight() - 1.0f);
  53520. p.addTriangle (getWidth() - 1.0f, 1.0f,
  53521. getWidth() * 0.7f, getHeight() * 0.5f,
  53522. getWidth() - 1.0f, getHeight() - 1.0f);
  53523. g.setColour (Colours::white.withAlpha (0.75f));
  53524. g.fillPath (p);
  53525. g.setColour (Colours::black.withAlpha (0.75f));
  53526. g.strokePath (p, PathStrokeType (1.2f));
  53527. }
  53528. private:
  53529. HueSelectorMarker (const HueSelectorMarker&);
  53530. const HueSelectorMarker& operator= (const HueSelectorMarker&);
  53531. };
  53532. class HueSelectorComp : public Component
  53533. {
  53534. public:
  53535. HueSelectorComp (ColourSelector* owner_,
  53536. float& h_, float& s_, float& v_,
  53537. const int edgeSize)
  53538. : owner (owner_),
  53539. h (h_), s (s_), v (v_),
  53540. lastHue (0.0f),
  53541. edge (edgeSize)
  53542. {
  53543. addAndMakeVisible (marker = new HueSelectorMarker());
  53544. }
  53545. ~HueSelectorComp()
  53546. {
  53547. deleteAllChildren();
  53548. }
  53549. void paint (Graphics& g)
  53550. {
  53551. const float yScale = 1.0f / (getHeight() - edge * 2);
  53552. const Rectangle clip (g.getClipBounds());
  53553. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  53554. {
  53555. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  53556. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  53557. }
  53558. }
  53559. void resized()
  53560. {
  53561. marker->setBounds (0, roundFloatToInt ((getHeight() - edge * 2) * h),
  53562. getWidth(), edge * 2);
  53563. }
  53564. void mouseDown (const MouseEvent& e)
  53565. {
  53566. mouseDrag (e);
  53567. }
  53568. void mouseDrag (const MouseEvent& e)
  53569. {
  53570. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  53571. owner->setHue (hue);
  53572. }
  53573. void updateIfNeeded()
  53574. {
  53575. resized();
  53576. }
  53577. private:
  53578. ColourSelector* const owner;
  53579. float& h;
  53580. float& s;
  53581. float& v;
  53582. float lastHue;
  53583. HueSelectorMarker* marker;
  53584. const int edge;
  53585. HueSelectorComp (const HueSelectorComp&);
  53586. const HueSelectorComp& operator= (const HueSelectorComp&);
  53587. };
  53588. class SwatchComponent : public Component
  53589. {
  53590. public:
  53591. SwatchComponent (ColourSelector* owner_, int index_)
  53592. : owner (owner_),
  53593. index (index_)
  53594. {
  53595. }
  53596. ~SwatchComponent()
  53597. {
  53598. }
  53599. void paint (Graphics& g)
  53600. {
  53601. const Colour colour (owner->getSwatchColour (index));
  53602. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  53603. 6, 6,
  53604. Colour (0xffdddddd).overlaidWith (colour),
  53605. Colour (0xffffffff).overlaidWith (colour));
  53606. }
  53607. void mouseDown (const MouseEvent&)
  53608. {
  53609. PopupMenu m;
  53610. m.addItem (1, TRANS("Use this swatch as the current colour"));
  53611. m.addSeparator();
  53612. m.addItem (2, TRANS("Set this swatch to the current colour"));
  53613. const int r = m.showAt (this);
  53614. if (r == 1)
  53615. {
  53616. owner->setCurrentColour (owner->getSwatchColour (index));
  53617. }
  53618. else if (r == 2)
  53619. {
  53620. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  53621. {
  53622. owner->setSwatchColour (index, owner->getCurrentColour());
  53623. repaint();
  53624. }
  53625. }
  53626. }
  53627. private:
  53628. ColourSelector* const owner;
  53629. const int index;
  53630. SwatchComponent (const SwatchComponent&);
  53631. const SwatchComponent& operator= (const SwatchComponent&);
  53632. };
  53633. ColourSelector::ColourSelector (const int flags_,
  53634. const int edgeGap_,
  53635. const int gapAroundColourSpaceComponent)
  53636. : colour (Colours::white),
  53637. flags (flags_),
  53638. topSpace (0),
  53639. edgeGap (edgeGap_)
  53640. {
  53641. // not much point having a selector with no components in it!
  53642. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  53643. updateHSV();
  53644. if ((flags & showSliders) != 0)
  53645. {
  53646. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  53647. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  53648. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  53649. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  53650. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  53651. for (int i = 4; --i >= 0;)
  53652. sliders[i]->addListener (this);
  53653. }
  53654. else
  53655. {
  53656. zeromem (sliders, sizeof (sliders));
  53657. }
  53658. if ((flags & showColourspace) != 0)
  53659. {
  53660. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  53661. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  53662. }
  53663. else
  53664. {
  53665. colourSpace = 0;
  53666. hueSelector = 0;
  53667. }
  53668. update();
  53669. }
  53670. ColourSelector::~ColourSelector()
  53671. {
  53672. dispatchPendingMessages();
  53673. deleteAllChildren();
  53674. }
  53675. const Colour ColourSelector::getCurrentColour() const
  53676. {
  53677. return ((flags & showAlphaChannel) != 0) ? colour
  53678. : colour.withAlpha ((uint8) 0xff);
  53679. }
  53680. void ColourSelector::setCurrentColour (const Colour& c)
  53681. {
  53682. if (c != colour)
  53683. {
  53684. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  53685. updateHSV();
  53686. update();
  53687. }
  53688. }
  53689. void ColourSelector::setHue (float newH)
  53690. {
  53691. newH = jlimit (0.0f, 1.0f, newH);
  53692. if (h != newH)
  53693. {
  53694. h = newH;
  53695. colour = Colour (h, s, v, colour.getFloatAlpha());
  53696. update();
  53697. }
  53698. }
  53699. void ColourSelector::setSV (float newS, float newV)
  53700. {
  53701. newS = jlimit (0.0f, 1.0f, newS);
  53702. newV = jlimit (0.0f, 1.0f, newV);
  53703. if (s != newS || v != newV)
  53704. {
  53705. s = newS;
  53706. v = newV;
  53707. colour = Colour (h, s, v, colour.getFloatAlpha());
  53708. update();
  53709. }
  53710. }
  53711. void ColourSelector::updateHSV()
  53712. {
  53713. colour.getHSB (h, s, v);
  53714. }
  53715. void ColourSelector::update()
  53716. {
  53717. if (sliders[0] != 0)
  53718. {
  53719. sliders[0]->setValue ((int) colour.getRed());
  53720. sliders[1]->setValue ((int) colour.getGreen());
  53721. sliders[2]->setValue ((int) colour.getBlue());
  53722. sliders[3]->setValue ((int) colour.getAlpha());
  53723. }
  53724. if (colourSpace != 0)
  53725. {
  53726. ((ColourSpaceView*) colourSpace)->updateIfNeeded();
  53727. ((HueSelectorComp*) hueSelector)->updateIfNeeded();
  53728. }
  53729. if ((flags & showColourAtTop) != 0)
  53730. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  53731. sendChangeMessage (this);
  53732. }
  53733. void ColourSelector::paint (Graphics& g)
  53734. {
  53735. g.fillAll (findColour (backgroundColourId));
  53736. if ((flags & showColourAtTop) != 0)
  53737. {
  53738. const Colour colour (getCurrentColour());
  53739. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  53740. 10, 10,
  53741. Colour (0xffdddddd).overlaidWith (colour),
  53742. Colour (0xffffffff).overlaidWith (colour));
  53743. g.setColour (Colours::white.overlaidWith (colour).contrasting());
  53744. g.setFont (14.0f, true);
  53745. g.drawText (((flags & showAlphaChannel) != 0)
  53746. ? String::formatted (T("#%02X%02X%02X%02X"),
  53747. (int) colour.getAlpha(),
  53748. (int) colour.getRed(),
  53749. (int) colour.getGreen(),
  53750. (int) colour.getBlue())
  53751. : String::formatted (T("#%02X%02X%02X"),
  53752. (int) colour.getRed(),
  53753. (int) colour.getGreen(),
  53754. (int) colour.getBlue()),
  53755. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  53756. Justification::centred, false);
  53757. }
  53758. if ((flags & showSliders) != 0)
  53759. {
  53760. g.setColour (findColour (labelTextColourId));
  53761. g.setFont (11.0f);
  53762. for (int i = 4; --i >= 0;)
  53763. {
  53764. if (sliders[i]->isVisible())
  53765. g.drawText (sliders[i]->getName() + T(":"),
  53766. 0, sliders[i]->getY(),
  53767. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  53768. Justification::centredRight, false);
  53769. }
  53770. }
  53771. }
  53772. void ColourSelector::resized()
  53773. {
  53774. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  53775. const int numSwatches = getNumSwatches();
  53776. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  53777. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  53778. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  53779. int y = topSpace;
  53780. if ((flags & showColourspace) != 0)
  53781. {
  53782. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  53783. colourSpace->setBounds (edgeGap, y,
  53784. getWidth() - hueWidth - edgeGap - 4,
  53785. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  53786. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  53787. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  53788. colourSpace->getHeight());
  53789. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  53790. }
  53791. if ((flags & showSliders) != 0)
  53792. {
  53793. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  53794. for (int i = 0; i < numSliders; ++i)
  53795. {
  53796. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  53797. proportionOfWidth (0.72f), sliderHeight - 2);
  53798. y += sliderHeight;
  53799. }
  53800. }
  53801. if (numSwatches > 0)
  53802. {
  53803. const int startX = 8;
  53804. const int xGap = 4;
  53805. const int yGap = 4;
  53806. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  53807. y += edgeGap;
  53808. if (swatchComponents.size() != numSwatches)
  53809. {
  53810. int i;
  53811. for (i = swatchComponents.size(); --i >= 0;)
  53812. {
  53813. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  53814. delete sc;
  53815. }
  53816. for (i = 0; i < numSwatches; ++i)
  53817. {
  53818. SwatchComponent* const sc = new SwatchComponent (this, i);
  53819. swatchComponents.add (sc);
  53820. addAndMakeVisible (sc);
  53821. }
  53822. }
  53823. int x = startX;
  53824. for (int i = 0; i < swatchComponents.size(); ++i)
  53825. {
  53826. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  53827. sc->setBounds (x + xGap / 2,
  53828. y + yGap / 2,
  53829. swatchWidth - xGap,
  53830. swatchHeight - yGap);
  53831. if (((i + 1) % swatchesPerRow) == 0)
  53832. {
  53833. x = startX;
  53834. y += swatchHeight;
  53835. }
  53836. else
  53837. {
  53838. x += swatchWidth;
  53839. }
  53840. }
  53841. }
  53842. }
  53843. void ColourSelector::sliderValueChanged (Slider*)
  53844. {
  53845. if (sliders[0] != 0)
  53846. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  53847. (uint8) sliders[1]->getValue(),
  53848. (uint8) sliders[2]->getValue(),
  53849. (uint8) sliders[3]->getValue()));
  53850. }
  53851. int ColourSelector::getNumSwatches() const
  53852. {
  53853. return 0;
  53854. }
  53855. const Colour ColourSelector::getSwatchColour (const int) const
  53856. {
  53857. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  53858. return Colours::black;
  53859. }
  53860. void ColourSelector::setSwatchColour (const int, const Colour&) const
  53861. {
  53862. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  53863. }
  53864. END_JUCE_NAMESPACE
  53865. /********* End of inlined file: juce_ColourSelector.cpp *********/
  53866. /********* Start of inlined file: juce_DropShadower.cpp *********/
  53867. BEGIN_JUCE_NAMESPACE
  53868. class ShadowWindow : public Component
  53869. {
  53870. Component* owner;
  53871. Image** shadowImageSections;
  53872. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  53873. public:
  53874. ShadowWindow (Component* const owner_,
  53875. const int type_,
  53876. Image** const shadowImageSections_)
  53877. : owner (owner_),
  53878. shadowImageSections (shadowImageSections_),
  53879. type (type_)
  53880. {
  53881. setInterceptsMouseClicks (false, false);
  53882. if (owner_->isOnDesktop())
  53883. {
  53884. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  53885. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  53886. | ComponentPeer::windowIsTemporary);
  53887. }
  53888. else if (owner_->getParentComponent() != 0)
  53889. {
  53890. owner_->getParentComponent()->addChildComponent (this);
  53891. }
  53892. }
  53893. ~ShadowWindow()
  53894. {
  53895. }
  53896. void paint (Graphics& g)
  53897. {
  53898. Image* const topLeft = shadowImageSections [type * 3];
  53899. Image* const bottomRight = shadowImageSections [type * 3 + 1];
  53900. Image* const filler = shadowImageSections [type * 3 + 2];
  53901. ImageBrush fillBrush (filler, 0, 0, 1.0f);
  53902. g.setOpacity (1.0f);
  53903. if (type < 2)
  53904. {
  53905. int imH = jmin (topLeft->getHeight(), getHeight() / 2);
  53906. g.drawImage (topLeft,
  53907. 0, 0, topLeft->getWidth(), imH,
  53908. 0, 0, topLeft->getWidth(), imH);
  53909. imH = jmin (bottomRight->getHeight(), getHeight() - getHeight() / 2);
  53910. g.drawImage (bottomRight,
  53911. 0, getHeight() - imH, bottomRight->getWidth(), imH,
  53912. 0, bottomRight->getHeight() - imH, bottomRight->getWidth(), imH);
  53913. g.setBrush (&fillBrush);
  53914. g.fillRect (0, topLeft->getHeight(), getWidth(), getHeight() - (topLeft->getHeight() + bottomRight->getHeight()));
  53915. }
  53916. else
  53917. {
  53918. int imW = jmin (topLeft->getWidth(), getWidth() / 2);
  53919. g.drawImage (topLeft,
  53920. 0, 0, imW, topLeft->getHeight(),
  53921. 0, 0, imW, topLeft->getHeight());
  53922. imW = jmin (bottomRight->getWidth(), getWidth() - getWidth() / 2);
  53923. g.drawImage (bottomRight,
  53924. getWidth() - imW, 0, imW, bottomRight->getHeight(),
  53925. bottomRight->getWidth() - imW, 0, imW, bottomRight->getHeight());
  53926. g.setBrush (&fillBrush);
  53927. g.fillRect (topLeft->getWidth(), 0, getWidth() - (topLeft->getWidth() + bottomRight->getWidth()), getHeight());
  53928. }
  53929. }
  53930. void resized()
  53931. {
  53932. repaint(); // (needed for correct repainting)
  53933. }
  53934. private:
  53935. ShadowWindow (const ShadowWindow&);
  53936. const ShadowWindow& operator= (const ShadowWindow&);
  53937. };
  53938. DropShadower::DropShadower (const float alpha_,
  53939. const int xOffset_,
  53940. const int yOffset_,
  53941. const float blurRadius_)
  53942. : owner (0),
  53943. numShadows (0),
  53944. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  53945. xOffset (xOffset_),
  53946. yOffset (yOffset_),
  53947. alpha (alpha_),
  53948. blurRadius (blurRadius_),
  53949. inDestructor (false),
  53950. reentrant (false)
  53951. {
  53952. }
  53953. DropShadower::~DropShadower()
  53954. {
  53955. if (owner != 0)
  53956. owner->removeComponentListener (this);
  53957. inDestructor = true;
  53958. deleteShadowWindows();
  53959. }
  53960. void DropShadower::deleteShadowWindows()
  53961. {
  53962. if (numShadows > 0)
  53963. {
  53964. int i;
  53965. for (i = numShadows; --i >= 0;)
  53966. delete shadowWindows[i];
  53967. for (i = 12; --i >= 0;)
  53968. delete shadowImageSections[i];
  53969. numShadows = 0;
  53970. }
  53971. }
  53972. void DropShadower::setOwner (Component* componentToFollow)
  53973. {
  53974. if (componentToFollow != owner)
  53975. {
  53976. if (owner != 0)
  53977. owner->removeComponentListener (this);
  53978. // (the component can't be null)
  53979. jassert (componentToFollow != 0);
  53980. owner = componentToFollow;
  53981. jassert (owner != 0);
  53982. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  53983. owner->addComponentListener (this);
  53984. updateShadows();
  53985. }
  53986. }
  53987. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  53988. {
  53989. updateShadows();
  53990. }
  53991. void DropShadower::componentBroughtToFront (Component&)
  53992. {
  53993. bringShadowWindowsToFront();
  53994. }
  53995. void DropShadower::componentChildrenChanged (Component&)
  53996. {
  53997. }
  53998. void DropShadower::componentParentHierarchyChanged (Component&)
  53999. {
  54000. deleteShadowWindows();
  54001. updateShadows();
  54002. }
  54003. void DropShadower::componentVisibilityChanged (Component&)
  54004. {
  54005. updateShadows();
  54006. }
  54007. void DropShadower::updateShadows()
  54008. {
  54009. if (reentrant || inDestructor || (owner == 0))
  54010. return;
  54011. reentrant = true;
  54012. ComponentPeer* const nw = owner->getPeer();
  54013. const bool isOwnerVisible = owner->isVisible()
  54014. && (nw == 0 || ! nw->isMinimised());
  54015. const bool createShadowWindows = numShadows == 0
  54016. && owner->getWidth() > 0
  54017. && owner->getHeight() > 0
  54018. && isOwnerVisible
  54019. && (Desktop::canUseSemiTransparentWindows()
  54020. || owner->getParentComponent() != 0);
  54021. if (createShadowWindows)
  54022. {
  54023. // keep a cached version of the image to save doing the gaussian too often
  54024. String imageId;
  54025. imageId << shadowEdge << T(',')
  54026. << xOffset << T(',')
  54027. << yOffset << T(',')
  54028. << alpha;
  54029. const int hash = imageId.hashCode();
  54030. Image* bigIm = ImageCache::getFromHashCode (hash);
  54031. if (bigIm == 0)
  54032. {
  54033. bigIm = new Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true);
  54034. Graphics bigG (*bigIm);
  54035. bigG.setColour (Colours::black.withAlpha (alpha));
  54036. bigG.fillRect (shadowEdge + xOffset,
  54037. shadowEdge + yOffset,
  54038. bigIm->getWidth() - (shadowEdge * 2),
  54039. bigIm->getHeight() - (shadowEdge * 2));
  54040. ImageConvolutionKernel blurKernel (roundFloatToInt (blurRadius * 2.0f));
  54041. blurKernel.createGaussianBlur (blurRadius);
  54042. blurKernel.applyToImage (*bigIm, 0,
  54043. xOffset,
  54044. yOffset,
  54045. bigIm->getWidth(),
  54046. bigIm->getHeight());
  54047. ImageCache::addImageToCache (bigIm, hash);
  54048. }
  54049. const int iw = bigIm->getWidth();
  54050. const int ih = bigIm->getHeight();
  54051. const int shadowEdge2 = shadowEdge * 2;
  54052. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  54053. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  54054. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  54055. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  54056. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  54057. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  54058. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  54059. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  54060. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  54061. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  54062. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  54063. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  54064. ImageCache::release (bigIm);
  54065. for (int i = 0; i < 4; ++i)
  54066. {
  54067. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  54068. ++numShadows;
  54069. }
  54070. }
  54071. if (numShadows > 0)
  54072. {
  54073. for (int i = numShadows; --i >= 0;)
  54074. {
  54075. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  54076. shadowWindows[i]->setVisible (isOwnerVisible);
  54077. }
  54078. const int x = owner->getX();
  54079. const int y = owner->getY() - shadowEdge;
  54080. const int w = owner->getWidth();
  54081. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  54082. shadowWindows[0]->setBounds (x - shadowEdge,
  54083. y,
  54084. shadowEdge,
  54085. h);
  54086. shadowWindows[1]->setBounds (x + w,
  54087. y,
  54088. shadowEdge,
  54089. h);
  54090. shadowWindows[2]->setBounds (x,
  54091. y,
  54092. w,
  54093. shadowEdge);
  54094. shadowWindows[3]->setBounds (x,
  54095. owner->getBottom(),
  54096. w,
  54097. shadowEdge);
  54098. }
  54099. reentrant = false;
  54100. if (createShadowWindows)
  54101. bringShadowWindowsToFront();
  54102. }
  54103. void DropShadower::setShadowImage (Image* const src,
  54104. const int num,
  54105. const int w,
  54106. const int h,
  54107. const int sx,
  54108. const int sy) throw()
  54109. {
  54110. shadowImageSections[num] = new Image (Image::ARGB, w, h, true);
  54111. Graphics g (*shadowImageSections[num]);
  54112. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  54113. }
  54114. void DropShadower::bringShadowWindowsToFront()
  54115. {
  54116. if (! (inDestructor || reentrant))
  54117. {
  54118. updateShadows();
  54119. reentrant = true;
  54120. for (int i = numShadows; --i >= 0;)
  54121. shadowWindows[i]->toBehind (owner);
  54122. reentrant = false;
  54123. }
  54124. }
  54125. END_JUCE_NAMESPACE
  54126. /********* End of inlined file: juce_DropShadower.cpp *********/
  54127. /********* Start of inlined file: juce_MagnifierComponent.cpp *********/
  54128. BEGIN_JUCE_NAMESPACE
  54129. class MagnifyingPeer : public ComponentPeer
  54130. {
  54131. public:
  54132. MagnifyingPeer (Component* const component,
  54133. MagnifierComponent* const magnifierComp_)
  54134. : ComponentPeer (component, 0),
  54135. magnifierComp (magnifierComp_)
  54136. {
  54137. }
  54138. ~MagnifyingPeer()
  54139. {
  54140. }
  54141. void* getNativeHandle() const { return 0; }
  54142. void setVisible (bool) {}
  54143. void setTitle (const String&) {}
  54144. void setPosition (int, int) {}
  54145. void setSize (int, int) {}
  54146. void setBounds (int, int, int, int, const bool) {}
  54147. void setMinimised (bool) {}
  54148. bool isMinimised() const { return false; }
  54149. void setFullScreen (bool) {}
  54150. bool isFullScreen() const { return false; }
  54151. const BorderSize getFrameSize() const { return BorderSize (0); }
  54152. bool setAlwaysOnTop (bool) { return true; }
  54153. void toFront (bool) {}
  54154. void toBehind (ComponentPeer*) {}
  54155. void setIcon (const Image&) {}
  54156. bool isFocused() const
  54157. {
  54158. return magnifierComp->hasKeyboardFocus (true);
  54159. }
  54160. void grabFocus()
  54161. {
  54162. ComponentPeer* peer = magnifierComp->getPeer();
  54163. if (peer != 0)
  54164. peer->grabFocus();
  54165. }
  54166. void textInputRequired (int x, int y)
  54167. {
  54168. ComponentPeer* peer = magnifierComp->getPeer();
  54169. if (peer != 0)
  54170. peer->textInputRequired (x, y);
  54171. }
  54172. void getBounds (int& x, int& y, int& w, int& h) const
  54173. {
  54174. x = magnifierComp->getScreenX();
  54175. y = magnifierComp->getScreenY();
  54176. w = component->getWidth();
  54177. h = component->getHeight();
  54178. }
  54179. int getScreenX() const { return magnifierComp->getScreenX(); }
  54180. int getScreenY() const { return magnifierComp->getScreenY(); }
  54181. void relativePositionToGlobal (int& x, int& y)
  54182. {
  54183. const double zoom = magnifierComp->getScaleFactor();
  54184. x = roundDoubleToInt (x * zoom);
  54185. y = roundDoubleToInt (y * zoom);
  54186. magnifierComp->relativePositionToGlobal (x, y);
  54187. }
  54188. void globalPositionToRelative (int& x, int& y)
  54189. {
  54190. magnifierComp->globalPositionToRelative (x, y);
  54191. const double zoom = magnifierComp->getScaleFactor();
  54192. x = roundDoubleToInt (x / zoom);
  54193. y = roundDoubleToInt (y / zoom);
  54194. }
  54195. bool contains (int x, int y, bool) const
  54196. {
  54197. return ((unsigned int) x) < (unsigned int) magnifierComp->getWidth()
  54198. && ((unsigned int) y) < (unsigned int) magnifierComp->getHeight();
  54199. }
  54200. void repaint (int x, int y, int w, int h)
  54201. {
  54202. const double zoom = magnifierComp->getScaleFactor();
  54203. magnifierComp->repaint ((int) (x * zoom),
  54204. (int) (y * zoom),
  54205. roundDoubleToInt (w * zoom) + 1,
  54206. roundDoubleToInt (h * zoom) + 1);
  54207. }
  54208. void performAnyPendingRepaintsNow()
  54209. {
  54210. }
  54211. juce_UseDebuggingNewOperator
  54212. private:
  54213. MagnifierComponent* const magnifierComp;
  54214. MagnifyingPeer (const MagnifyingPeer&);
  54215. const MagnifyingPeer& operator= (const MagnifyingPeer&);
  54216. };
  54217. class PeerHolderComp : public Component
  54218. {
  54219. public:
  54220. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  54221. : magnifierComp (magnifierComp_)
  54222. {
  54223. setVisible (true);
  54224. }
  54225. ~PeerHolderComp()
  54226. {
  54227. }
  54228. ComponentPeer* createNewPeer (int, void*)
  54229. {
  54230. return new MagnifyingPeer (this, magnifierComp);
  54231. }
  54232. void childBoundsChanged (Component* c)
  54233. {
  54234. if (c != 0)
  54235. {
  54236. setSize (c->getWidth(), c->getHeight());
  54237. magnifierComp->childBoundsChanged (this);
  54238. }
  54239. }
  54240. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  54241. {
  54242. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  54243. Component* const p = magnifierComp->getParentComponent();
  54244. if (p != 0)
  54245. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  54246. }
  54247. private:
  54248. MagnifierComponent* const magnifierComp;
  54249. PeerHolderComp (const PeerHolderComp&);
  54250. const PeerHolderComp& operator= (const PeerHolderComp&);
  54251. };
  54252. MagnifierComponent::MagnifierComponent (Component* const content_,
  54253. const bool deleteContentCompWhenNoLongerNeeded)
  54254. : content (content_),
  54255. scaleFactor (0.0),
  54256. peer (0),
  54257. deleteContent (deleteContentCompWhenNoLongerNeeded)
  54258. {
  54259. holderComp = new PeerHolderComp (this);
  54260. setScaleFactor (1.0);
  54261. }
  54262. MagnifierComponent::~MagnifierComponent()
  54263. {
  54264. delete holderComp;
  54265. if (deleteContent)
  54266. delete content;
  54267. }
  54268. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  54269. {
  54270. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  54271. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  54272. if (scaleFactor != newScaleFactor)
  54273. {
  54274. scaleFactor = newScaleFactor;
  54275. if (scaleFactor == 1.0)
  54276. {
  54277. holderComp->removeFromDesktop();
  54278. peer = 0;
  54279. addChildComponent (content);
  54280. childBoundsChanged (content);
  54281. }
  54282. else
  54283. {
  54284. holderComp->addAndMakeVisible (content);
  54285. holderComp->childBoundsChanged (content);
  54286. childBoundsChanged (holderComp);
  54287. holderComp->addToDesktop (0);
  54288. peer = holderComp->getPeer();
  54289. }
  54290. repaint();
  54291. }
  54292. }
  54293. void MagnifierComponent::paint (Graphics& g)
  54294. {
  54295. const int w = holderComp->getWidth();
  54296. const int h = holderComp->getHeight();
  54297. if (w == 0 || h == 0)
  54298. return;
  54299. const Rectangle r (g.getClipBounds());
  54300. const int srcX = (int) (r.getX() / scaleFactor);
  54301. const int srcY = (int) (r.getY() / scaleFactor);
  54302. int srcW = roundDoubleToInt (r.getRight() / scaleFactor) - srcX;
  54303. int srcH = roundDoubleToInt (r.getBottom() / scaleFactor) - srcY;
  54304. if (scaleFactor >= 1.0)
  54305. {
  54306. ++srcW;
  54307. ++srcH;
  54308. }
  54309. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  54310. temp.clear (srcX, srcY, srcW, srcH);
  54311. Graphics g2 (temp);
  54312. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  54313. holderComp->paintEntireComponent (g2);
  54314. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  54315. g.drawImage (&temp,
  54316. 0, 0, (int) (w * scaleFactor), (int) (h * scaleFactor),
  54317. 0, 0, w, h,
  54318. false);
  54319. }
  54320. void MagnifierComponent::childBoundsChanged (Component* c)
  54321. {
  54322. if (c != 0)
  54323. setSize (roundDoubleToInt (c->getWidth() * scaleFactor),
  54324. roundDoubleToInt (c->getHeight() * scaleFactor));
  54325. }
  54326. void MagnifierComponent::mouseDown (const MouseEvent& e)
  54327. {
  54328. if (peer != 0)
  54329. peer->handleMouseDown (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54330. }
  54331. void MagnifierComponent::mouseUp (const MouseEvent& e)
  54332. {
  54333. if (peer != 0)
  54334. peer->handleMouseUp (e.mods.getRawFlags(), scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54335. }
  54336. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  54337. {
  54338. if (peer != 0)
  54339. peer->handleMouseDrag (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54340. }
  54341. void MagnifierComponent::mouseMove (const MouseEvent& e)
  54342. {
  54343. if (peer != 0)
  54344. peer->handleMouseMove (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54345. }
  54346. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  54347. {
  54348. if (peer != 0)
  54349. peer->handleMouseEnter (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54350. }
  54351. void MagnifierComponent::mouseExit (const MouseEvent& e)
  54352. {
  54353. if (peer != 0)
  54354. peer->handleMouseExit (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54355. }
  54356. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  54357. {
  54358. if (peer != 0)
  54359. peer->handleMouseWheel (roundFloatToInt (ix * 256.0f),
  54360. roundFloatToInt (iy * 256.0f),
  54361. e.eventTime.toMilliseconds());
  54362. else
  54363. Component::mouseWheelMove (e, ix, iy);
  54364. }
  54365. int MagnifierComponent::scaleInt (const int n) const throw()
  54366. {
  54367. return roundDoubleToInt (n / scaleFactor);
  54368. }
  54369. END_JUCE_NAMESPACE
  54370. /********* End of inlined file: juce_MagnifierComponent.cpp *********/
  54371. /********* Start of inlined file: juce_MidiKeyboardComponent.cpp *********/
  54372. BEGIN_JUCE_NAMESPACE
  54373. class MidiKeyboardUpDownButton : public Button
  54374. {
  54375. public:
  54376. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  54377. const int delta_)
  54378. : Button (String::empty),
  54379. owner (owner_),
  54380. delta (delta_)
  54381. {
  54382. setOpaque (true);
  54383. }
  54384. ~MidiKeyboardUpDownButton()
  54385. {
  54386. }
  54387. void clicked()
  54388. {
  54389. int note = owner->getLowestVisibleKey();
  54390. if (delta < 0)
  54391. note = (note - 1) / 12;
  54392. else
  54393. note = note / 12 + 1;
  54394. owner->setLowestVisibleKey (note * 12);
  54395. }
  54396. void paintButton (Graphics& g,
  54397. bool isMouseOverButton,
  54398. bool isButtonDown)
  54399. {
  54400. owner->drawUpDownButton (g, getWidth(), getHeight(),
  54401. isMouseOverButton, isButtonDown,
  54402. delta > 0);
  54403. }
  54404. private:
  54405. MidiKeyboardComponent* const owner;
  54406. const int delta;
  54407. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  54408. const MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  54409. };
  54410. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  54411. const Orientation orientation_)
  54412. : state (state_),
  54413. xOffset (0),
  54414. blackNoteLength (1),
  54415. keyWidth (16.0f),
  54416. orientation (orientation_),
  54417. midiChannel (1),
  54418. midiInChannelMask (0xffff),
  54419. velocity (1.0f),
  54420. noteUnderMouse (-1),
  54421. mouseDownNote (-1),
  54422. rangeStart (0),
  54423. rangeEnd (127),
  54424. firstKey (12 * 4),
  54425. canScroll (true),
  54426. mouseDragging (false),
  54427. keyPresses (4),
  54428. keyPressNotes (16),
  54429. keyMappingOctave (6),
  54430. octaveNumForMiddleC (3)
  54431. {
  54432. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  54433. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  54434. // initialise with a default set of querty key-mappings..
  54435. const char* const keymap = "awsedftgyhujkolp;";
  54436. for (int i = String (keymap).length(); --i >= 0;)
  54437. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  54438. setOpaque (true);
  54439. setWantsKeyboardFocus (true);
  54440. state.addListener (this);
  54441. }
  54442. MidiKeyboardComponent::~MidiKeyboardComponent()
  54443. {
  54444. state.removeListener (this);
  54445. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  54446. deleteAllChildren();
  54447. }
  54448. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  54449. {
  54450. keyWidth = widthInPixels;
  54451. resized();
  54452. }
  54453. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  54454. {
  54455. if (orientation != newOrientation)
  54456. {
  54457. orientation = newOrientation;
  54458. resized();
  54459. }
  54460. }
  54461. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  54462. const int highestNote)
  54463. {
  54464. jassert (lowestNote >= 0 && lowestNote <= 127);
  54465. jassert (highestNote >= 0 && highestNote <= 127);
  54466. jassert (lowestNote <= highestNote);
  54467. if (rangeStart != lowestNote || rangeEnd != highestNote)
  54468. {
  54469. rangeStart = jlimit (0, 127, lowestNote);
  54470. rangeEnd = jlimit (0, 127, highestNote);
  54471. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  54472. resized();
  54473. }
  54474. }
  54475. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  54476. {
  54477. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  54478. if (noteNumber != firstKey)
  54479. {
  54480. firstKey = noteNumber;
  54481. sendChangeMessage (this);
  54482. resized();
  54483. }
  54484. }
  54485. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  54486. {
  54487. if (canScroll != canScroll_)
  54488. {
  54489. canScroll = canScroll_;
  54490. resized();
  54491. }
  54492. }
  54493. void MidiKeyboardComponent::colourChanged()
  54494. {
  54495. repaint();
  54496. }
  54497. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  54498. {
  54499. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  54500. if (midiChannel != midiChannelNumber)
  54501. {
  54502. resetAnyKeysInUse();
  54503. midiChannel = jlimit (1, 16, midiChannelNumber);
  54504. }
  54505. }
  54506. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  54507. {
  54508. midiInChannelMask = midiChannelMask;
  54509. triggerAsyncUpdate();
  54510. }
  54511. void MidiKeyboardComponent::setVelocity (const float velocity_)
  54512. {
  54513. velocity = jlimit (0.0f, 1.0f, velocity_);
  54514. }
  54515. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth, int& x, int& w) const
  54516. {
  54517. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  54518. static const float blackNoteWidth = 0.7f;
  54519. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  54520. 1.0f, 2 - blackNoteWidth * 0.4f,
  54521. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  54522. 4.0f, 5 - blackNoteWidth * 0.5f,
  54523. 5.0f, 6 - blackNoteWidth * 0.3f,
  54524. 6.0f };
  54525. static const float widths[] = { 1.0f, blackNoteWidth,
  54526. 1.0f, blackNoteWidth,
  54527. 1.0f, 1.0f, blackNoteWidth,
  54528. 1.0f, blackNoteWidth,
  54529. 1.0f, blackNoteWidth,
  54530. 1.0f };
  54531. const int octave = midiNoteNumber / 12;
  54532. const int note = midiNoteNumber % 12;
  54533. x = roundFloatToInt (octave * 7.0f * keyWidth + notePos [note] * keyWidth);
  54534. w = roundFloatToInt (widths [note] * keyWidth);
  54535. }
  54536. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  54537. {
  54538. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  54539. int rx, rw;
  54540. getKeyPosition (rangeStart, keyWidth, rx, rw);
  54541. x -= xOffset + rx;
  54542. }
  54543. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  54544. {
  54545. int x, y;
  54546. getKeyPos (midiNoteNumber, x, y);
  54547. return x;
  54548. }
  54549. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  54550. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  54551. int MidiKeyboardComponent::xyToNote (int x, int y)
  54552. {
  54553. if (! reallyContains (x, y, false))
  54554. return -1;
  54555. if (orientation != horizontalKeyboard)
  54556. {
  54557. swapVariables (x, y);
  54558. if (orientation == verticalKeyboardFacingLeft)
  54559. y = getWidth() - y;
  54560. else
  54561. x = getHeight() - x;
  54562. }
  54563. return remappedXYToNote (x + xOffset, y);
  54564. }
  54565. int MidiKeyboardComponent::remappedXYToNote (int x, int y) const
  54566. {
  54567. if (y < blackNoteLength)
  54568. {
  54569. for (int octaveStart = 12 * (rangeStart / 12); octaveStart < rangeEnd; octaveStart += 12)
  54570. {
  54571. for (int i = 0; i < 5; ++i)
  54572. {
  54573. const int note = octaveStart + blackNotes [i];
  54574. if (note >= rangeStart && note <= rangeEnd)
  54575. {
  54576. int kx, kw;
  54577. getKeyPos (note, kx, kw);
  54578. kx += xOffset;
  54579. if (x >= kx && x < kx + kw)
  54580. return note;
  54581. }
  54582. }
  54583. }
  54584. }
  54585. for (int octaveStart = 12 * (rangeStart / 12); octaveStart < rangeEnd; octaveStart += 12)
  54586. {
  54587. for (int i = 0; i < 7; ++i)
  54588. {
  54589. const int note = octaveStart + whiteNotes [i];
  54590. if (note >= rangeStart && note <= rangeEnd)
  54591. {
  54592. int kx, kw;
  54593. getKeyPos (note, kx, kw);
  54594. kx += xOffset;
  54595. if (x >= kx && x < kx + kw)
  54596. return note;
  54597. }
  54598. }
  54599. }
  54600. return -1;
  54601. }
  54602. void MidiKeyboardComponent::repaintNote (const int noteNum)
  54603. {
  54604. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  54605. {
  54606. int x, w;
  54607. getKeyPos (noteNum, x, w);
  54608. if (orientation == horizontalKeyboard)
  54609. repaint (x, 0, w, getHeight());
  54610. else if (orientation == verticalKeyboardFacingLeft)
  54611. repaint (0, x, getWidth(), w);
  54612. else if (orientation == verticalKeyboardFacingRight)
  54613. repaint (0, getHeight() - x - w, getWidth(), w);
  54614. }
  54615. }
  54616. void MidiKeyboardComponent::paint (Graphics& g)
  54617. {
  54618. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  54619. const Colour lineColour (findColour (keySeparatorLineColourId));
  54620. const Colour textColour (findColour (textLabelColourId));
  54621. int x, w, octave;
  54622. for (octave = 0; octave < 128; octave += 12)
  54623. {
  54624. for (int white = 0; white < 7; ++white)
  54625. {
  54626. const int noteNum = octave + whiteNotes [white];
  54627. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  54628. {
  54629. getKeyPos (noteNum, x, w);
  54630. if (orientation == horizontalKeyboard)
  54631. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  54632. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54633. noteUnderMouse == noteNum,
  54634. lineColour, textColour);
  54635. else if (orientation == verticalKeyboardFacingLeft)
  54636. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  54637. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54638. noteUnderMouse == noteNum,
  54639. lineColour, textColour);
  54640. else if (orientation == verticalKeyboardFacingRight)
  54641. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  54642. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54643. noteUnderMouse == noteNum,
  54644. lineColour, textColour);
  54645. }
  54646. }
  54647. }
  54648. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54649. if (orientation == verticalKeyboardFacingLeft)
  54650. {
  54651. x1 = getWidth() - 1.0f;
  54652. x2 = getWidth() - 5.0f;
  54653. }
  54654. else if (orientation == verticalKeyboardFacingRight)
  54655. x2 = 5.0f;
  54656. else
  54657. y2 = 5.0f;
  54658. GradientBrush gb (Colours::black.withAlpha (0.3f), x1, y1,
  54659. Colours::transparentBlack, x2, y2, false);
  54660. g.setBrush (&gb);
  54661. getKeyPos (rangeEnd, x, w);
  54662. x += w;
  54663. if (orientation == verticalKeyboardFacingLeft)
  54664. g.fillRect (getWidth() - 5, 0, 5, x);
  54665. else if (orientation == verticalKeyboardFacingRight)
  54666. g.fillRect (0, 0, 5, x);
  54667. else
  54668. g.fillRect (0, 0, x, 5);
  54669. g.setColour (lineColour);
  54670. if (orientation == verticalKeyboardFacingLeft)
  54671. g.fillRect (0, 0, 1, x);
  54672. else if (orientation == verticalKeyboardFacingRight)
  54673. g.fillRect (getWidth() - 1, 0, 1, x);
  54674. else
  54675. g.fillRect (0, getHeight() - 1, x, 1);
  54676. const Colour blackNoteColour (findColour (blackNoteColourId));
  54677. for (octave = 0; octave < 128; octave += 12)
  54678. {
  54679. for (int black = 0; black < 5; ++black)
  54680. {
  54681. const int noteNum = octave + blackNotes [black];
  54682. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  54683. {
  54684. getKeyPos (noteNum, x, w);
  54685. if (orientation == horizontalKeyboard)
  54686. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  54687. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54688. noteUnderMouse == noteNum,
  54689. blackNoteColour);
  54690. else if (orientation == verticalKeyboardFacingLeft)
  54691. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  54692. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54693. noteUnderMouse == noteNum,
  54694. blackNoteColour);
  54695. else if (orientation == verticalKeyboardFacingRight)
  54696. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  54697. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54698. noteUnderMouse == noteNum,
  54699. blackNoteColour);
  54700. }
  54701. }
  54702. }
  54703. }
  54704. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  54705. Graphics& g, int x, int y, int w, int h,
  54706. bool isDown, bool isOver,
  54707. const Colour& lineColour,
  54708. const Colour& textColour)
  54709. {
  54710. Colour c (Colours::transparentWhite);
  54711. if (isDown)
  54712. c = findColour (keyDownOverlayColourId);
  54713. if (isOver)
  54714. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  54715. g.setColour (c);
  54716. g.fillRect (x, y, w, h);
  54717. const String text (getWhiteNoteText (midiNoteNumber));
  54718. if (! text.isEmpty())
  54719. {
  54720. g.setColour (textColour);
  54721. Font f (jmin (12.0f, keyWidth * 0.9f));
  54722. f.setHorizontalScale (0.8f);
  54723. g.setFont (f);
  54724. Justification justification (Justification::centredBottom);
  54725. if (orientation == verticalKeyboardFacingLeft)
  54726. justification = Justification::centredLeft;
  54727. else if (orientation == verticalKeyboardFacingRight)
  54728. justification = Justification::centredRight;
  54729. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  54730. }
  54731. g.setColour (lineColour);
  54732. if (orientation == horizontalKeyboard)
  54733. g.fillRect (x, y, 1, h);
  54734. else if (orientation == verticalKeyboardFacingLeft)
  54735. g.fillRect (x, y, w, 1);
  54736. else if (orientation == verticalKeyboardFacingRight)
  54737. g.fillRect (x, y + h - 1, w, 1);
  54738. if (midiNoteNumber == rangeEnd)
  54739. {
  54740. if (orientation == horizontalKeyboard)
  54741. g.fillRect (x + w, y, 1, h);
  54742. else if (orientation == verticalKeyboardFacingLeft)
  54743. g.fillRect (x, y + h, w, 1);
  54744. else if (orientation == verticalKeyboardFacingRight)
  54745. g.fillRect (x, y - 1, w, 1);
  54746. }
  54747. }
  54748. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  54749. Graphics& g, int x, int y, int w, int h,
  54750. bool isDown, bool isOver,
  54751. const Colour& noteFillColour)
  54752. {
  54753. Colour c (noteFillColour);
  54754. if (isDown)
  54755. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  54756. if (isOver)
  54757. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  54758. g.setColour (c);
  54759. g.fillRect (x, y, w, h);
  54760. if (isDown)
  54761. {
  54762. g.setColour (noteFillColour);
  54763. g.drawRect (x, y, w, h);
  54764. }
  54765. else
  54766. {
  54767. const int xIndent = jmax (1, jmin (w, h) / 8);
  54768. g.setColour (c.brighter());
  54769. if (orientation == horizontalKeyboard)
  54770. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  54771. else if (orientation == verticalKeyboardFacingLeft)
  54772. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  54773. else if (orientation == verticalKeyboardFacingRight)
  54774. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  54775. }
  54776. }
  54777. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_) throw()
  54778. {
  54779. octaveNumForMiddleC = octaveNumForMiddleC_;
  54780. repaint();
  54781. }
  54782. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  54783. {
  54784. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  54785. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  54786. return String::empty;
  54787. }
  54788. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  54789. const bool isMouseOver,
  54790. const bool isButtonDown,
  54791. const bool movesOctavesUp)
  54792. {
  54793. g.fillAll (findColour (upDownButtonBackgroundColourId));
  54794. float angle;
  54795. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  54796. angle = movesOctavesUp ? 0.0f : 0.5f;
  54797. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  54798. angle = movesOctavesUp ? 0.25f : 0.75f;
  54799. else
  54800. angle = movesOctavesUp ? 0.75f : 0.25f;
  54801. Path path;
  54802. path.lineTo (0.0f, 1.0f);
  54803. path.lineTo (1.0f, 0.5f);
  54804. path.closeSubPath();
  54805. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  54806. g.setColour (findColour (upDownButtonArrowColourId)
  54807. .withAlpha (isButtonDown ? 1.0f : (isMouseOver ? 0.6f : 0.4f)));
  54808. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  54809. w - 2.0f,
  54810. h - 2.0f,
  54811. true));
  54812. }
  54813. void MidiKeyboardComponent::resized()
  54814. {
  54815. int w = getWidth();
  54816. int h = getHeight();
  54817. if (w > 0 && h > 0)
  54818. {
  54819. if (orientation != horizontalKeyboard)
  54820. swapVariables (w, h);
  54821. blackNoteLength = roundFloatToInt (h * 0.7f);
  54822. int kx2, kw2;
  54823. getKeyPos (rangeEnd, kx2, kw2);
  54824. kx2 += kw2;
  54825. if (firstKey != rangeStart)
  54826. {
  54827. int kx1, kw1;
  54828. getKeyPos (rangeStart, kx1, kw1);
  54829. if (kx2 - kx1 <= w)
  54830. {
  54831. firstKey = rangeStart;
  54832. sendChangeMessage (this);
  54833. repaint();
  54834. }
  54835. }
  54836. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  54837. scrollDown->setVisible (showScrollButtons);
  54838. scrollUp->setVisible (showScrollButtons);
  54839. xOffset = 0;
  54840. if (showScrollButtons)
  54841. {
  54842. const int scrollButtonW = jmin (12, w / 2);
  54843. if (orientation == horizontalKeyboard)
  54844. {
  54845. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  54846. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  54847. }
  54848. else if (orientation == verticalKeyboardFacingLeft)
  54849. {
  54850. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  54851. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  54852. }
  54853. else if (orientation == verticalKeyboardFacingRight)
  54854. {
  54855. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  54856. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  54857. }
  54858. int endOfLastKey, kw;
  54859. getKeyPos (rangeEnd, endOfLastKey, kw);
  54860. endOfLastKey += kw;
  54861. const int spaceAvailable = w - scrollButtonW * 2;
  54862. const int lastStartKey = remappedXYToNote (endOfLastKey - spaceAvailable, 0) + 1;
  54863. if (lastStartKey >= 0 && firstKey > lastStartKey)
  54864. {
  54865. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  54866. sendChangeMessage (this);
  54867. }
  54868. int newOffset = 0;
  54869. getKeyPos (firstKey, newOffset, kw);
  54870. xOffset = newOffset - scrollButtonW;
  54871. }
  54872. else
  54873. {
  54874. firstKey = rangeStart;
  54875. }
  54876. timerCallback();
  54877. repaint();
  54878. }
  54879. }
  54880. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  54881. {
  54882. triggerAsyncUpdate();
  54883. }
  54884. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  54885. {
  54886. triggerAsyncUpdate();
  54887. }
  54888. void MidiKeyboardComponent::handleAsyncUpdate()
  54889. {
  54890. for (int i = rangeStart; i <= rangeEnd; ++i)
  54891. {
  54892. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  54893. {
  54894. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  54895. repaintNote (i);
  54896. }
  54897. }
  54898. }
  54899. void MidiKeyboardComponent::resetAnyKeysInUse()
  54900. {
  54901. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  54902. {
  54903. state.allNotesOff (midiChannel);
  54904. keysPressed.clear();
  54905. mouseDownNote = -1;
  54906. }
  54907. }
  54908. void MidiKeyboardComponent::updateNoteUnderMouse (int x, int y)
  54909. {
  54910. const int newNote = (mouseDragging || isMouseOver())
  54911. ? xyToNote (x, y) : -1;
  54912. if (noteUnderMouse != newNote)
  54913. {
  54914. if (mouseDownNote >= 0)
  54915. {
  54916. state.noteOff (midiChannel, mouseDownNote);
  54917. mouseDownNote = -1;
  54918. }
  54919. if (mouseDragging && newNote >= 0)
  54920. {
  54921. state.noteOn (midiChannel, newNote, velocity);
  54922. mouseDownNote = newNote;
  54923. }
  54924. repaintNote (noteUnderMouse);
  54925. noteUnderMouse = newNote;
  54926. repaintNote (noteUnderMouse);
  54927. }
  54928. else if (mouseDownNote >= 0 && ! mouseDragging)
  54929. {
  54930. state.noteOff (midiChannel, mouseDownNote);
  54931. mouseDownNote = -1;
  54932. }
  54933. }
  54934. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  54935. {
  54936. updateNoteUnderMouse (e.x, e.y);
  54937. stopTimer();
  54938. }
  54939. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  54940. {
  54941. const int newNote = xyToNote (e.x, e.y);
  54942. if (newNote >= 0)
  54943. mouseDraggedToKey (newNote, e);
  54944. updateNoteUnderMouse (e.x, e.y);
  54945. }
  54946. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  54947. {
  54948. return true;
  54949. }
  54950. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  54951. {
  54952. }
  54953. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  54954. {
  54955. const int newNote = xyToNote (e.x, e.y);
  54956. mouseDragging = false;
  54957. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  54958. {
  54959. repaintNote (noteUnderMouse);
  54960. noteUnderMouse = -1;
  54961. mouseDragging = true;
  54962. updateNoteUnderMouse (e.x, e.y);
  54963. startTimer (500);
  54964. }
  54965. }
  54966. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  54967. {
  54968. mouseDragging = false;
  54969. updateNoteUnderMouse (e.x, e.y);
  54970. stopTimer();
  54971. }
  54972. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  54973. {
  54974. updateNoteUnderMouse (e.x, e.y);
  54975. }
  54976. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  54977. {
  54978. updateNoteUnderMouse (e.x, e.y);
  54979. }
  54980. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  54981. {
  54982. setLowestVisibleKey (getLowestVisibleKey() + roundFloatToInt ((ix != 0 ? ix : iy) * 5.0f));
  54983. }
  54984. void MidiKeyboardComponent::timerCallback()
  54985. {
  54986. int mx, my;
  54987. getMouseXYRelative (mx, my);
  54988. updateNoteUnderMouse (mx, my);
  54989. }
  54990. void MidiKeyboardComponent::clearKeyMappings()
  54991. {
  54992. resetAnyKeysInUse();
  54993. keyPressNotes.clear();
  54994. keyPresses.clear();
  54995. }
  54996. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  54997. const int midiNoteOffsetFromC)
  54998. {
  54999. removeKeyPressForNote (midiNoteOffsetFromC);
  55000. keyPressNotes.add (midiNoteOffsetFromC);
  55001. keyPresses.add (key);
  55002. }
  55003. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  55004. {
  55005. for (int i = keyPressNotes.size(); --i >= 0;)
  55006. {
  55007. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  55008. {
  55009. keyPressNotes.remove (i);
  55010. keyPresses.remove (i);
  55011. }
  55012. }
  55013. }
  55014. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  55015. {
  55016. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  55017. keyMappingOctave = newOctaveNumber;
  55018. }
  55019. bool MidiKeyboardComponent::keyStateChanged()
  55020. {
  55021. bool keyPressUsed = false;
  55022. for (int i = keyPresses.size(); --i >= 0;)
  55023. {
  55024. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  55025. if (keyPresses.getReference(i).isCurrentlyDown())
  55026. {
  55027. if (! keysPressed [note])
  55028. {
  55029. keysPressed.setBit (note);
  55030. state.noteOn (midiChannel, note, velocity);
  55031. keyPressUsed = true;
  55032. }
  55033. }
  55034. else
  55035. {
  55036. if (keysPressed [note])
  55037. {
  55038. keysPressed.clearBit (note);
  55039. state.noteOff (midiChannel, note);
  55040. keyPressUsed = true;
  55041. }
  55042. }
  55043. }
  55044. return keyPressUsed;
  55045. }
  55046. void MidiKeyboardComponent::focusLost (FocusChangeType)
  55047. {
  55048. resetAnyKeysInUse();
  55049. }
  55050. END_JUCE_NAMESPACE
  55051. /********* End of inlined file: juce_MidiKeyboardComponent.cpp *********/
  55052. /********* Start of inlined file: juce_OpenGLComponent.cpp *********/
  55053. #if JUCE_OPENGL
  55054. BEGIN_JUCE_NAMESPACE
  55055. extern void juce_glViewport (const int w, const int h);
  55056. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  55057. const int alphaBits_,
  55058. const int depthBufferBits_,
  55059. const int stencilBufferBits_) throw()
  55060. : redBits (bitsPerRGBComponent),
  55061. greenBits (bitsPerRGBComponent),
  55062. blueBits (bitsPerRGBComponent),
  55063. alphaBits (alphaBits_),
  55064. depthBufferBits (depthBufferBits_),
  55065. stencilBufferBits (stencilBufferBits_),
  55066. accumulationBufferRedBits (0),
  55067. accumulationBufferGreenBits (0),
  55068. accumulationBufferBlueBits (0),
  55069. accumulationBufferAlphaBits (0),
  55070. fullSceneAntiAliasingNumSamples (0)
  55071. {
  55072. }
  55073. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const throw()
  55074. {
  55075. return memcmp (this, &other, sizeof (other)) == 0;
  55076. }
  55077. static VoidArray knownContexts;
  55078. OpenGLContext::OpenGLContext() throw()
  55079. {
  55080. knownContexts.add (this);
  55081. }
  55082. OpenGLContext::~OpenGLContext()
  55083. {
  55084. knownContexts.removeValue (this);
  55085. }
  55086. OpenGLContext* OpenGLContext::getCurrentContext()
  55087. {
  55088. for (int i = knownContexts.size(); --i >= 0;)
  55089. {
  55090. OpenGLContext* const oglc = (OpenGLContext*) knownContexts.getUnchecked(i);
  55091. if (oglc->isActive())
  55092. return oglc;
  55093. }
  55094. return 0;
  55095. }
  55096. class OpenGLComponentWatcher : public ComponentMovementWatcher
  55097. {
  55098. public:
  55099. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  55100. : ComponentMovementWatcher (owner_),
  55101. owner (owner_),
  55102. wasShowing (false)
  55103. {
  55104. }
  55105. ~OpenGLComponentWatcher() {}
  55106. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  55107. {
  55108. owner->updateContextPosition();
  55109. }
  55110. void componentPeerChanged()
  55111. {
  55112. const ScopedLock sl (owner->getContextLock());
  55113. owner->deleteContext();
  55114. }
  55115. void componentVisibilityChanged (Component&)
  55116. {
  55117. const bool isShowingNow = owner->isShowing();
  55118. if (wasShowing != isShowingNow)
  55119. {
  55120. wasShowing = isShowingNow;
  55121. owner->updateContextPosition();
  55122. }
  55123. }
  55124. juce_UseDebuggingNewOperator
  55125. private:
  55126. OpenGLComponent* const owner;
  55127. bool wasShowing;
  55128. };
  55129. OpenGLComponent::OpenGLComponent()
  55130. : context (0),
  55131. contextToShareListsWith (0),
  55132. needToUpdateViewport (true)
  55133. {
  55134. setOpaque (true);
  55135. componentWatcher = new OpenGLComponentWatcher (this);
  55136. }
  55137. OpenGLComponent::~OpenGLComponent()
  55138. {
  55139. deleteContext();
  55140. delete componentWatcher;
  55141. }
  55142. void OpenGLComponent::deleteContext()
  55143. {
  55144. const ScopedLock sl (contextLock);
  55145. deleteAndZero (context);
  55146. }
  55147. void OpenGLComponent::updateContextPosition()
  55148. {
  55149. needToUpdateViewport = true;
  55150. if (getWidth() > 0 && getHeight() > 0)
  55151. {
  55152. Component* const topComp = getTopLevelComponent();
  55153. if (topComp->getPeer() != 0)
  55154. {
  55155. const ScopedLock sl (contextLock);
  55156. if (context != 0)
  55157. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  55158. getScreenY() - topComp->getScreenY(),
  55159. getWidth(),
  55160. getHeight(),
  55161. topComp->getHeight());
  55162. }
  55163. }
  55164. }
  55165. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  55166. {
  55167. OpenGLPixelFormat pf;
  55168. const ScopedLock sl (contextLock);
  55169. if (context != 0)
  55170. pf = context->getPixelFormat();
  55171. return pf;
  55172. }
  55173. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  55174. {
  55175. if (! (preferredPixelFormat == formatToUse))
  55176. {
  55177. const ScopedLock sl (contextLock);
  55178. deleteContext();
  55179. preferredPixelFormat = formatToUse;
  55180. }
  55181. }
  55182. void OpenGLComponent::shareWith (OpenGLContext* context)
  55183. {
  55184. if (contextToShareListsWith != context)
  55185. {
  55186. const ScopedLock sl (contextLock);
  55187. deleteContext();
  55188. contextToShareListsWith = context;
  55189. }
  55190. }
  55191. bool OpenGLComponent::makeCurrentContextActive()
  55192. {
  55193. if (context == 0)
  55194. {
  55195. const ScopedLock sl (contextLock);
  55196. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  55197. {
  55198. context = OpenGLContext::createContextForWindow (this,
  55199. preferredPixelFormat,
  55200. contextToShareListsWith);
  55201. if (context != 0)
  55202. {
  55203. updateContextPosition();
  55204. if (context->makeActive())
  55205. newOpenGLContextCreated();
  55206. }
  55207. }
  55208. }
  55209. return context != 0 && context->makeActive();
  55210. }
  55211. void OpenGLComponent::makeCurrentContextInactive()
  55212. {
  55213. if (context != 0)
  55214. context->makeInactive();
  55215. }
  55216. bool OpenGLComponent::isActiveContext() const throw()
  55217. {
  55218. return context != 0 && context->isActive();
  55219. }
  55220. void OpenGLComponent::swapBuffers()
  55221. {
  55222. if (context != 0)
  55223. context->swapBuffers();
  55224. }
  55225. void OpenGLComponent::paint (Graphics&)
  55226. {
  55227. if (renderAndSwapBuffers())
  55228. {
  55229. ComponentPeer* const peer = getPeer();
  55230. if (peer != 0)
  55231. {
  55232. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  55233. getScreenY() - peer->getScreenY(),
  55234. getWidth(), getHeight());
  55235. }
  55236. }
  55237. }
  55238. bool OpenGLComponent::renderAndSwapBuffers()
  55239. {
  55240. const ScopedLock sl (contextLock);
  55241. if (! makeCurrentContextActive())
  55242. return false;
  55243. if (needToUpdateViewport)
  55244. {
  55245. needToUpdateViewport = false;
  55246. juce_glViewport (getWidth(), getHeight());
  55247. }
  55248. renderOpenGL();
  55249. swapBuffers();
  55250. return true;
  55251. }
  55252. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  55253. {
  55254. Component::internalRepaint (x, y, w, h);
  55255. if (context != 0)
  55256. context->repaint();
  55257. }
  55258. END_JUCE_NAMESPACE
  55259. #endif
  55260. /********* End of inlined file: juce_OpenGLComponent.cpp *********/
  55261. /********* Start of inlined file: juce_PreferencesPanel.cpp *********/
  55262. BEGIN_JUCE_NAMESPACE
  55263. PreferencesPanel::PreferencesPanel()
  55264. : currentPage (0),
  55265. buttonSize (70)
  55266. {
  55267. }
  55268. PreferencesPanel::~PreferencesPanel()
  55269. {
  55270. deleteAllChildren();
  55271. }
  55272. void PreferencesPanel::addSettingsPage (const String& title,
  55273. const Drawable* icon,
  55274. const Drawable* overIcon,
  55275. const Drawable* downIcon)
  55276. {
  55277. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  55278. button->setImages (icon, overIcon, downIcon);
  55279. button->setRadioGroupId (1);
  55280. button->addButtonListener (this);
  55281. button->setClickingTogglesState (true);
  55282. button->setWantsKeyboardFocus (false);
  55283. addAndMakeVisible (button);
  55284. resized();
  55285. }
  55286. void PreferencesPanel::addSettingsPage (const String& title,
  55287. const char* imageData,
  55288. const int imageDataSize)
  55289. {
  55290. DrawableImage icon, iconOver, iconDown;
  55291. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  55292. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  55293. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  55294. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  55295. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  55296. addSettingsPage (title, &icon, &iconOver, &iconDown);
  55297. if (currentPage == 0)
  55298. setCurrentPage (title);
  55299. }
  55300. class PrefsDialogWindow : public DialogWindow
  55301. {
  55302. public:
  55303. PrefsDialogWindow (const String& dialogtitle,
  55304. const Colour& backgroundColour)
  55305. : DialogWindow (dialogtitle, backgroundColour, true)
  55306. {
  55307. }
  55308. ~PrefsDialogWindow()
  55309. {
  55310. }
  55311. void closeButtonPressed()
  55312. {
  55313. exitModalState (0);
  55314. }
  55315. private:
  55316. PrefsDialogWindow (const PrefsDialogWindow&);
  55317. const PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  55318. };
  55319. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  55320. int dialogWidth,
  55321. int dialogHeight,
  55322. const Colour& backgroundColour)
  55323. {
  55324. setSize (dialogWidth, dialogHeight);
  55325. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  55326. dw.setContentComponent (this, true, true);
  55327. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  55328. dw.runModalLoop();
  55329. }
  55330. void PreferencesPanel::resized()
  55331. {
  55332. int x = 0;
  55333. for (int i = 0; i < getNumChildComponents(); ++i)
  55334. {
  55335. Component* c = getChildComponent (i);
  55336. if (dynamic_cast <DrawableButton*> (c) == 0)
  55337. {
  55338. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  55339. }
  55340. else
  55341. {
  55342. c->setBounds (x, 0, buttonSize, buttonSize);
  55343. x += buttonSize;
  55344. }
  55345. }
  55346. }
  55347. void PreferencesPanel::paint (Graphics& g)
  55348. {
  55349. g.setColour (Colours::grey);
  55350. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  55351. }
  55352. void PreferencesPanel::setCurrentPage (const String& pageName)
  55353. {
  55354. if (currentPageName != pageName)
  55355. {
  55356. currentPageName = pageName;
  55357. deleteAndZero (currentPage);
  55358. currentPage = createComponentForPage (pageName);
  55359. if (currentPage != 0)
  55360. {
  55361. addAndMakeVisible (currentPage);
  55362. currentPage->toBack();
  55363. resized();
  55364. }
  55365. for (int i = 0; i < getNumChildComponents(); ++i)
  55366. {
  55367. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  55368. if (db != 0 && db->getName() == pageName)
  55369. {
  55370. db->setToggleState (true, false);
  55371. break;
  55372. }
  55373. }
  55374. }
  55375. }
  55376. void PreferencesPanel::buttonClicked (Button*)
  55377. {
  55378. for (int i = 0; i < getNumChildComponents(); ++i)
  55379. {
  55380. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  55381. if (db != 0 && db->getToggleState())
  55382. {
  55383. setCurrentPage (db->getName());
  55384. break;
  55385. }
  55386. }
  55387. }
  55388. END_JUCE_NAMESPACE
  55389. /********* End of inlined file: juce_PreferencesPanel.cpp *********/
  55390. /********* Start of inlined file: juce_QuickTimeMovieComponent.cpp *********/
  55391. #if JUCE_QUICKTIME
  55392. #ifdef _MSC_VER
  55393. #pragma warning (disable: 4514)
  55394. #endif
  55395. #ifdef _WIN32
  55396. #include <windows.h>
  55397. #ifdef _MSC_VER
  55398. #pragma warning (push)
  55399. #pragma warning (disable : 4100)
  55400. #endif
  55401. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  55402. add its header directory to your include path.
  55403. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  55404. flag in juce_Config.h
  55405. */
  55406. #include <Movies.h>
  55407. #include <QTML.h>
  55408. #include <QuickTimeComponents.h>
  55409. #include <MediaHandlers.h>
  55410. #include <ImageCodec.h>
  55411. #ifdef _MSC_VER
  55412. #pragma warning (pop)
  55413. #endif
  55414. // If you've got QuickTime 7 installed, then these COM objects should be found in
  55415. // the "\Program Files\Quicktime" directory. You'll need to add this directory to
  55416. // your include search path to make these import statements work.
  55417. #import <QTOLibrary.dll>
  55418. #import <QTOControl.dll>
  55419. using namespace QTOLibrary;
  55420. using namespace QTOControlLib;
  55421. #else
  55422. #include <Carbon/Carbon.h>
  55423. #include <QuickTime/Movies.h>
  55424. #include <QuickTime/QuickTimeComponents.h>
  55425. #include <QuickTime/MediaHandlers.h>
  55426. #endif
  55427. BEGIN_JUCE_NAMESPACE
  55428. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  55429. static bool hasLoadedQT = false;
  55430. static bool isQTAvailable = false;
  55431. struct QTMovieCompInternal
  55432. {
  55433. QTMovieCompInternal()
  55434. : dataHandle (0)
  55435. {
  55436. #if JUCE_MAC
  55437. movie = 0;
  55438. controller = 0;
  55439. #endif
  55440. }
  55441. ~QTMovieCompInternal()
  55442. {
  55443. clearHandle();
  55444. }
  55445. #if JUCE_MAC
  55446. Movie movie;
  55447. MovieController controller;
  55448. #else
  55449. IQTControlPtr qtControlInternal;
  55450. IQTMoviePtr qtMovieInternal;
  55451. #endif
  55452. Handle dataHandle;
  55453. void clearHandle()
  55454. {
  55455. if (dataHandle != 0)
  55456. {
  55457. DisposeHandle (dataHandle);
  55458. dataHandle = 0;
  55459. }
  55460. }
  55461. };
  55462. #if JUCE_WIN32
  55463. #define qtControl (((QTMovieCompInternal*) internal)->qtControlInternal)
  55464. #define qtMovie (((QTMovieCompInternal*) internal)->qtMovieInternal)
  55465. QuickTimeMovieComponent::QuickTimeMovieComponent()
  55466. : movieLoaded (false),
  55467. controllerVisible (true)
  55468. {
  55469. internal = new QTMovieCompInternal();
  55470. setMouseEventsAllowed (false);
  55471. }
  55472. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  55473. {
  55474. closeMovie();
  55475. qtControl = 0;
  55476. deleteControl();
  55477. delete internal;
  55478. internal = 0;
  55479. }
  55480. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  55481. {
  55482. if (! hasLoadedQT)
  55483. {
  55484. hasLoadedQT = true;
  55485. isQTAvailable = (InitializeQTML (0) == noErr)
  55486. && (EnterMovies() == noErr);
  55487. }
  55488. return isQTAvailable;
  55489. }
  55490. void QuickTimeMovieComponent::createControlIfNeeded()
  55491. {
  55492. if (isShowing() && ! isControlCreated())
  55493. {
  55494. const IID qtIID = __uuidof (QTControl);
  55495. if (createControl (&qtIID))
  55496. {
  55497. const IID qtInterfaceIID = __uuidof (IQTControl);
  55498. qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  55499. if (qtControl != 0)
  55500. {
  55501. qtControl->Release(); // it has one ref too many at this point
  55502. qtControl->QuickTimeInitialize();
  55503. qtControl->PutSizing (qtMovieFitsControl);
  55504. if (movieFile != File::nonexistent)
  55505. loadMovie (movieFile, controllerVisible);
  55506. }
  55507. }
  55508. }
  55509. }
  55510. bool QuickTimeMovieComponent::isControlCreated() const
  55511. {
  55512. return isControlOpen();
  55513. }
  55514. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  55515. const bool isControllerVisible)
  55516. {
  55517. movieFile = File::nonexistent;
  55518. movieLoaded = false;
  55519. qtMovie = 0;
  55520. controllerVisible = isControllerVisible;
  55521. createControlIfNeeded();
  55522. if (isControlCreated())
  55523. {
  55524. if (qtControl != 0)
  55525. {
  55526. qtControl->Put_MovieHandle (0);
  55527. ((QTMovieCompInternal*) internal)->clearHandle();
  55528. Movie movie;
  55529. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, ((QTMovieCompInternal*) internal)->dataHandle))
  55530. {
  55531. qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  55532. qtMovie = qtControl->GetMovie();
  55533. if (qtMovie != 0)
  55534. qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  55535. : qtMovieControllerTypeNone);
  55536. }
  55537. if (movie == 0)
  55538. ((QTMovieCompInternal*) internal)->clearHandle();
  55539. }
  55540. movieLoaded = (qtMovie != 0);
  55541. }
  55542. else
  55543. {
  55544. // You're trying to open a movie when the control hasn't yet been created, probably because
  55545. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  55546. jassertfalse
  55547. }
  55548. delete movieStream;
  55549. return movieLoaded;
  55550. }
  55551. void QuickTimeMovieComponent::closeMovie()
  55552. {
  55553. stop();
  55554. movieFile = File::nonexistent;
  55555. movieLoaded = false;
  55556. qtMovie = 0;
  55557. if (qtControl != 0)
  55558. qtControl->Put_MovieHandle (0);
  55559. ((QTMovieCompInternal*) internal)->clearHandle();
  55560. }
  55561. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  55562. {
  55563. return movieFile;
  55564. }
  55565. bool QuickTimeMovieComponent::isMovieOpen() const
  55566. {
  55567. return movieLoaded;
  55568. }
  55569. double QuickTimeMovieComponent::getMovieDuration() const
  55570. {
  55571. if (qtMovie != 0)
  55572. return qtMovie->GetDuration() / (double) qtMovie->GetTimeScale();
  55573. return 0.0;
  55574. }
  55575. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  55576. {
  55577. if (qtMovie != 0)
  55578. {
  55579. struct QTRECT r = qtMovie->GetNaturalRect();
  55580. width = r.right - r.left;
  55581. height = r.bottom - r.top;
  55582. }
  55583. else
  55584. {
  55585. width = height = 0;
  55586. }
  55587. }
  55588. void QuickTimeMovieComponent::play()
  55589. {
  55590. if (qtMovie != 0)
  55591. qtMovie->Play();
  55592. }
  55593. void QuickTimeMovieComponent::stop()
  55594. {
  55595. if (qtMovie != 0)
  55596. qtMovie->Stop();
  55597. }
  55598. bool QuickTimeMovieComponent::isPlaying() const
  55599. {
  55600. return qtMovie != 0 && qtMovie->GetRate() != 0.0f;
  55601. }
  55602. void QuickTimeMovieComponent::setPosition (const double seconds)
  55603. {
  55604. if (qtMovie != 0)
  55605. qtMovie->PutTime ((long) (seconds * qtMovie->GetTimeScale()));
  55606. }
  55607. double QuickTimeMovieComponent::getPosition() const
  55608. {
  55609. if (qtMovie != 0)
  55610. return qtMovie->GetTime() / (double) qtMovie->GetTimeScale();
  55611. return 0.0;
  55612. }
  55613. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  55614. {
  55615. if (qtMovie != 0)
  55616. qtMovie->PutRate (newSpeed);
  55617. }
  55618. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  55619. {
  55620. if (qtMovie != 0)
  55621. {
  55622. qtMovie->PutAudioVolume (newVolume);
  55623. qtMovie->PutAudioMute (newVolume <= 0);
  55624. }
  55625. }
  55626. float QuickTimeMovieComponent::getMovieVolume() const
  55627. {
  55628. if (qtMovie != 0)
  55629. return qtMovie->GetAudioVolume();
  55630. return 0.0f;
  55631. }
  55632. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  55633. {
  55634. if (qtMovie != 0)
  55635. qtMovie->PutLoop (shouldLoop);
  55636. }
  55637. bool QuickTimeMovieComponent::isLooping() const
  55638. {
  55639. return qtMovie != 0 && qtMovie->GetLoop();
  55640. }
  55641. bool QuickTimeMovieComponent::isControllerVisible() const
  55642. {
  55643. return controllerVisible;
  55644. }
  55645. void QuickTimeMovieComponent::parentHierarchyChanged()
  55646. {
  55647. createControlIfNeeded();
  55648. QTWinBaseClass::parentHierarchyChanged();
  55649. }
  55650. void QuickTimeMovieComponent::visibilityChanged()
  55651. {
  55652. createControlIfNeeded();
  55653. QTWinBaseClass::visibilityChanged();
  55654. }
  55655. void QuickTimeMovieComponent::paint (Graphics& g)
  55656. {
  55657. if (! isControlCreated())
  55658. g.fillAll (Colours::black);
  55659. }
  55660. #endif
  55661. #if JUCE_MAC
  55662. static VoidArray activeQTWindows (2);
  55663. struct MacClickEventData
  55664. {
  55665. ::Point where;
  55666. long when;
  55667. long modifiers;
  55668. };
  55669. void OfferMouseClickToQuickTime (WindowRef window,
  55670. ::Point where, long when, long modifiers,
  55671. Component* topLevelComp)
  55672. {
  55673. if (hasLoadedQT)
  55674. {
  55675. for (int i = activeQTWindows.size(); --i >= 0;)
  55676. {
  55677. QuickTimeMovieComponent* const qtw = (QuickTimeMovieComponent*) activeQTWindows[i];
  55678. if (qtw->isVisible() && topLevelComp->isParentOf (qtw))
  55679. {
  55680. MacClickEventData data;
  55681. data.where = where;
  55682. data.when = when;
  55683. data.modifiers = modifiers;
  55684. qtw->handleMCEvent (&data);
  55685. }
  55686. }
  55687. }
  55688. }
  55689. QuickTimeMovieComponent::QuickTimeMovieComponent()
  55690. : internal (new QTMovieCompInternal()),
  55691. associatedWindow (0),
  55692. controllerVisible (false),
  55693. controllerAssignedToWindow (false),
  55694. reentrant (false)
  55695. {
  55696. if (! hasLoadedQT)
  55697. {
  55698. hasLoadedQT = true;
  55699. isQTAvailable = EnterMovies() == noErr;
  55700. }
  55701. setOpaque (true);
  55702. setVisible (true);
  55703. activeQTWindows.add (this);
  55704. }
  55705. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  55706. {
  55707. closeMovie();
  55708. activeQTWindows.removeValue ((void*) this);
  55709. QTMovieCompInternal* const i = (QTMovieCompInternal*) internal;
  55710. delete i;
  55711. if (activeQTWindows.size() == 0 && isQTAvailable)
  55712. {
  55713. isQTAvailable = false;
  55714. hasLoadedQT = false;
  55715. ExitMovies();
  55716. }
  55717. }
  55718. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  55719. {
  55720. if (! hasLoadedQT)
  55721. {
  55722. hasLoadedQT = true;
  55723. isQTAvailable = EnterMovies() == noErr;
  55724. }
  55725. return isQTAvailable;
  55726. }
  55727. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  55728. const bool controllerVisible_)
  55729. {
  55730. if (! isQTAvailable)
  55731. return false;
  55732. closeMovie();
  55733. movieFile = File::nonexistent;
  55734. if (getPeer() == 0)
  55735. {
  55736. // To open a movie, this component must be visible inside a functioning window, so that
  55737. // the QT control can be assigned to the window.
  55738. jassertfalse
  55739. return false;
  55740. }
  55741. controllerVisible = controllerVisible_;
  55742. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55743. GrafPtr savedPort;
  55744. GetPort (&savedPort);
  55745. bool result = false;
  55746. if (juce_OpenQuickTimeMovieFromStream (movieStream, qmci->movie, qmci->dataHandle))
  55747. {
  55748. qmci->controller = 0;
  55749. void* window = getWindowHandle();
  55750. if (window != associatedWindow && window != 0)
  55751. associatedWindow = window;
  55752. assignMovieToWindow();
  55753. SetMovieActive (qmci->movie, true);
  55754. SetMovieProgressProc (qmci->movie, (MovieProgressUPP) -1, 0);
  55755. startTimer (1000 / 50); // this needs to be quite a high frequency for smooth playback
  55756. result = true;
  55757. repaint();
  55758. }
  55759. MacSetPort (savedPort);
  55760. return result;
  55761. }
  55762. void QuickTimeMovieComponent::closeMovie()
  55763. {
  55764. stop();
  55765. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55766. if (qmci->controller != 0)
  55767. {
  55768. DisposeMovieController (qmci->controller);
  55769. qmci->controller = 0;
  55770. }
  55771. if (qmci->movie != 0)
  55772. {
  55773. DisposeMovie (qmci->movie);
  55774. qmci->movie = 0;
  55775. }
  55776. qmci->clearHandle();
  55777. stopTimer();
  55778. movieFile = File::nonexistent;
  55779. }
  55780. bool QuickTimeMovieComponent::isMovieOpen() const
  55781. {
  55782. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55783. return qmci->movie != 0 && qmci->controller != 0;
  55784. }
  55785. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  55786. {
  55787. return movieFile;
  55788. }
  55789. static GrafPtr getPortForWindow (void* window)
  55790. {
  55791. if (window == 0)
  55792. return 0;
  55793. return (GrafPtr) GetWindowPort ((WindowRef) window);
  55794. }
  55795. void QuickTimeMovieComponent::assignMovieToWindow()
  55796. {
  55797. if (reentrant)
  55798. return;
  55799. reentrant = true;
  55800. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55801. if (qmci->controller != 0)
  55802. {
  55803. DisposeMovieController (qmci->controller);
  55804. qmci->controller = 0;
  55805. }
  55806. controllerAssignedToWindow = false;
  55807. void* window = getWindowHandle();
  55808. GrafPtr port = getPortForWindow (window);
  55809. if (port != 0)
  55810. {
  55811. GrafPtr savedPort;
  55812. GetPort (&savedPort);
  55813. SetMovieGWorld (qmci->movie, (CGrafPtr) port, 0);
  55814. MacSetPort (port);
  55815. Rect r;
  55816. r.top = 0;
  55817. r.left = 0;
  55818. r.right = (short) jmax (1, getWidth());
  55819. r.bottom = (short) jmax (1, getHeight());
  55820. SetMovieBox (qmci->movie, &r);
  55821. // create the movie controller
  55822. qmci->controller = NewMovieController (qmci->movie, &r,
  55823. controllerVisible ? mcTopLeftMovie
  55824. : mcNotVisible);
  55825. if (qmci->controller != 0)
  55826. {
  55827. MCEnableEditing (qmci->controller, true);
  55828. MCDoAction (qmci->controller, mcActionSetUseBadge, (void*) false);
  55829. MCDoAction (qmci->controller, mcActionSetLoopIsPalindrome, (void*) false);
  55830. setLooping (looping);
  55831. MCDoAction (qmci->controller, mcActionSetFlags,
  55832. (void*) (pointer_sized_int) (mcFlagSuppressMovieFrame | (controllerVisible ? 0 : (mcFlagSuppressStepButtons | mcFlagSuppressSpeakerButton))));
  55833. MCSetControllerBoundsRect (qmci->controller, &r);
  55834. controllerAssignedToWindow = true;
  55835. resized();
  55836. }
  55837. MacSetPort (savedPort);
  55838. }
  55839. else
  55840. {
  55841. SetMovieGWorld (qmci->movie, 0, 0);
  55842. }
  55843. reentrant = false;
  55844. }
  55845. void QuickTimeMovieComponent::play()
  55846. {
  55847. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55848. if (qmci->movie != 0)
  55849. StartMovie (qmci->movie);
  55850. }
  55851. void QuickTimeMovieComponent::stop()
  55852. {
  55853. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55854. if (qmci->movie != 0)
  55855. StopMovie (qmci->movie);
  55856. }
  55857. bool QuickTimeMovieComponent::isPlaying() const
  55858. {
  55859. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55860. return qmci->movie != 0 && GetMovieRate (qmci->movie) != 0;
  55861. }
  55862. void QuickTimeMovieComponent::setPosition (const double seconds)
  55863. {
  55864. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55865. if (qmci->controller != 0)
  55866. {
  55867. TimeRecord time;
  55868. time.base = GetMovieTimeBase (qmci->movie);
  55869. time.scale = 100000;
  55870. const uint64 t = (uint64) (100000.0 * seconds);
  55871. time.value.lo = (UInt32) (t & 0xffffffff);
  55872. time.value.hi = (UInt32) (t >> 32);
  55873. SetMovieTime (qmci->movie, &time);
  55874. timerCallback(); // to call MCIdle
  55875. }
  55876. else
  55877. {
  55878. jassertfalse // no movie is open, so can't set the position.
  55879. }
  55880. }
  55881. double QuickTimeMovieComponent::getPosition() const
  55882. {
  55883. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55884. if (qmci->movie != 0)
  55885. {
  55886. TimeRecord time;
  55887. GetMovieTime (qmci->movie, &time);
  55888. return ((int64) (((uint64) time.value.hi << 32) | (uint64) time.value.lo))
  55889. / (double) time.scale;
  55890. }
  55891. return 0.0;
  55892. }
  55893. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  55894. {
  55895. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55896. if (qmci->movie != 0)
  55897. SetMovieRate (qmci->movie, (Fixed) (newSpeed * (Fixed) 0x00010000L));
  55898. }
  55899. double QuickTimeMovieComponent::getMovieDuration() const
  55900. {
  55901. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55902. if (qmci->movie != 0)
  55903. return GetMovieDuration (qmci->movie) / (double) GetMovieTimeScale (qmci->movie);
  55904. return 0.0;
  55905. }
  55906. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  55907. {
  55908. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55909. looping = shouldLoop;
  55910. if (qmci->controller != 0)
  55911. MCDoAction (qmci->controller, mcActionSetLooping, (void*) shouldLoop);
  55912. }
  55913. bool QuickTimeMovieComponent::isLooping() const
  55914. {
  55915. return looping;
  55916. }
  55917. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  55918. {
  55919. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55920. if (qmci->movie != 0)
  55921. SetMovieVolume (qmci->movie, jlimit ((short) 0, (short) 0x100, (short) (newVolume * 0x0100)));
  55922. }
  55923. float QuickTimeMovieComponent::getMovieVolume() const
  55924. {
  55925. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55926. if (qmci->movie != 0)
  55927. return jmax (0.0f, GetMovieVolume (qmci->movie) / (float) 0x0100);
  55928. return 0.0f;
  55929. }
  55930. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  55931. {
  55932. width = 0;
  55933. height = 0;
  55934. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55935. if (qmci->movie != 0)
  55936. {
  55937. Rect r;
  55938. GetMovieNaturalBoundsRect (qmci->movie, &r);
  55939. width = r.right - r.left;
  55940. height = r.bottom - r.top;
  55941. }
  55942. }
  55943. void QuickTimeMovieComponent::paint (Graphics& g)
  55944. {
  55945. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55946. if (qmci->movie == 0 || qmci->controller == 0)
  55947. {
  55948. g.fillAll (Colours::black);
  55949. return;
  55950. }
  55951. GrafPtr savedPort;
  55952. GetPort (&savedPort);
  55953. MacSetPort (getPortForWindow (getWindowHandle()));
  55954. MCDraw (qmci->controller, (WindowRef) getWindowHandle());
  55955. MacSetPort (savedPort);
  55956. ComponentPeer* const peer = getPeer();
  55957. if (peer != 0)
  55958. {
  55959. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  55960. getScreenY() - peer->getScreenY(),
  55961. getWidth(), getHeight());
  55962. }
  55963. timerCallback();
  55964. }
  55965. static const Rectangle getMoviePos (Component* const c)
  55966. {
  55967. return Rectangle (c->getScreenX() - c->getTopLevelComponent()->getScreenX(),
  55968. c->getScreenY() - c->getTopLevelComponent()->getScreenY(),
  55969. jmax (1, c->getWidth()),
  55970. jmax (1, c->getHeight()));
  55971. }
  55972. void QuickTimeMovieComponent::moved()
  55973. {
  55974. resized();
  55975. }
  55976. void QuickTimeMovieComponent::resized()
  55977. {
  55978. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55979. if (qmci->controller != 0 && isShowing())
  55980. {
  55981. checkWindowAssociation();
  55982. GrafPtr port = getPortForWindow (getWindowHandle());
  55983. if (port != 0)
  55984. {
  55985. GrafPtr savedPort;
  55986. GetPort (&savedPort);
  55987. SetMovieGWorld (qmci->movie, (CGrafPtr) port, 0);
  55988. MacSetPort (port);
  55989. lastPositionApplied = getMoviePos (this);
  55990. Rect r;
  55991. r.left = (short) lastPositionApplied.getX();
  55992. r.top = (short) lastPositionApplied.getY();
  55993. r.right = (short) lastPositionApplied.getRight();
  55994. r.bottom = (short) lastPositionApplied.getBottom();
  55995. if (MCGetVisible (qmci->controller))
  55996. MCSetControllerBoundsRect (qmci->controller, &r);
  55997. else
  55998. SetMovieBox (qmci->movie, &r);
  55999. if (! isPlaying())
  56000. timerCallback();
  56001. MacSetPort (savedPort);
  56002. repaint();
  56003. }
  56004. }
  56005. }
  56006. void QuickTimeMovieComponent::visibilityChanged()
  56007. {
  56008. checkWindowAssociation();
  56009. QTWinBaseClass::visibilityChanged();
  56010. }
  56011. void QuickTimeMovieComponent::timerCallback()
  56012. {
  56013. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  56014. if (qmci->controller != 0)
  56015. {
  56016. if (isTimerRunning())
  56017. startTimer (getTimerInterval());
  56018. MCIdle (qmci->controller);
  56019. if (lastPositionApplied != getMoviePos (this))
  56020. resized();
  56021. }
  56022. }
  56023. void QuickTimeMovieComponent::checkWindowAssociation()
  56024. {
  56025. void* const window = getWindowHandle();
  56026. if (window != associatedWindow
  56027. || (window != 0 && ! controllerAssignedToWindow))
  56028. {
  56029. associatedWindow = window;
  56030. assignMovieToWindow();
  56031. }
  56032. }
  56033. void QuickTimeMovieComponent::parentHierarchyChanged()
  56034. {
  56035. checkWindowAssociation();
  56036. }
  56037. void QuickTimeMovieComponent::handleMCEvent (void* ev)
  56038. {
  56039. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  56040. if (qmci->controller != 0 && isShowing())
  56041. {
  56042. MacClickEventData* data = (MacClickEventData*) ev;
  56043. data->where.h -= getTopLevelComponent()->getScreenX();
  56044. data->where.v -= getTopLevelComponent()->getScreenY();
  56045. Boolean b = false;
  56046. MCPtInController (qmci->controller, data->where, &b);
  56047. if (b)
  56048. {
  56049. const int oldTimeBeforeWaitCursor = MessageManager::getInstance()->getTimeBeforeShowingWaitCursor();
  56050. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (0);
  56051. MCClick (qmci->controller,
  56052. (WindowRef) getWindowHandle(),
  56053. data->where,
  56054. data->when,
  56055. data->modifiers);
  56056. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (oldTimeBeforeWaitCursor);
  56057. }
  56058. }
  56059. }
  56060. #endif
  56061. // (methods common to both platforms..)
  56062. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  56063. {
  56064. Handle dataRef = 0;
  56065. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  56066. if (err == noErr)
  56067. {
  56068. Str255 suffix;
  56069. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  56070. StringPtr name = suffix;
  56071. err = PtrAndHand (name, dataRef, name[0] + 1);
  56072. if (err == noErr)
  56073. {
  56074. long atoms[3];
  56075. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  56076. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  56077. atoms[2] = EndianU32_NtoB (MovieFileType);
  56078. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  56079. if (err == noErr)
  56080. return dataRef;
  56081. }
  56082. DisposeHandle (dataRef);
  56083. }
  56084. return 0;
  56085. }
  56086. static CFStringRef juceStringToCFString (const String& s)
  56087. {
  56088. const int len = s.length();
  56089. const juce_wchar* const t = (const juce_wchar*) s;
  56090. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  56091. for (int i = 0; i <= len; ++i)
  56092. temp[i] = t[i];
  56093. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  56094. juce_free (temp);
  56095. return result;
  56096. }
  56097. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  56098. {
  56099. Boolean trueBool = true;
  56100. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  56101. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  56102. props[prop].propValueSize = sizeof (trueBool);
  56103. props[prop].propValueAddress = &trueBool;
  56104. ++prop;
  56105. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  56106. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  56107. props[prop].propValueSize = sizeof (trueBool);
  56108. props[prop].propValueAddress = &trueBool;
  56109. ++prop;
  56110. Boolean isActive = true;
  56111. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  56112. props[prop].propID = kQTNewMoviePropertyID_Active;
  56113. props[prop].propValueSize = sizeof (isActive);
  56114. props[prop].propValueAddress = &isActive;
  56115. ++prop;
  56116. #if JUCE_MAC
  56117. SetPort (0);
  56118. #else
  56119. MacSetPort (0);
  56120. #endif
  56121. jassert (prop <= 5);
  56122. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  56123. return err == noErr;
  56124. }
  56125. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  56126. {
  56127. if (input == 0)
  56128. return false;
  56129. dataHandle = 0;
  56130. bool ok = false;
  56131. QTNewMoviePropertyElement props[5];
  56132. zeromem (props, sizeof (props));
  56133. int prop = 0;
  56134. DataReferenceRecord dr;
  56135. props[prop].propClass = kQTPropertyClass_DataLocation;
  56136. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  56137. props[prop].propValueSize = sizeof (dr);
  56138. props[prop].propValueAddress = (void*) &dr;
  56139. ++prop;
  56140. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  56141. if (fin != 0)
  56142. {
  56143. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  56144. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  56145. &dr.dataRef, &dr.dataRefType);
  56146. ok = openMovie (props, prop, movie);
  56147. DisposeHandle (dr.dataRef);
  56148. CFRelease (filePath);
  56149. }
  56150. else
  56151. {
  56152. // sanity-check because this currently needs to load the whole stream into memory..
  56153. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  56154. dataHandle = NewHandle ((Size) input->getTotalLength());
  56155. HLock (dataHandle);
  56156. // read the entire stream into memory - this is a pain, but can't get it to work
  56157. // properly using a custom callback to supply the data.
  56158. input->read (*dataHandle, (int) input->getTotalLength());
  56159. HUnlock (dataHandle);
  56160. // different types to get QT to try. (We should really be a bit smarter here by
  56161. // working out in advance which one the stream contains, rather than just trying
  56162. // each one)
  56163. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  56164. "\04.avi", "\04.m4a" };
  56165. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  56166. {
  56167. /* // this fails for some bizarre reason - it can be bodged to work with
  56168. // movies, but can't seem to do it for other file types..
  56169. QTNewMovieUserProcRecord procInfo;
  56170. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  56171. procInfo.getMovieUserProcRefcon = this;
  56172. procInfo.defaultDataRef.dataRef = dataRef;
  56173. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  56174. props[prop].propClass = kQTPropertyClass_DataLocation;
  56175. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  56176. props[prop].propValueSize = sizeof (procInfo);
  56177. props[prop].propValueAddress = (void*) &procInfo;
  56178. ++prop; */
  56179. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  56180. dr.dataRefType = HandleDataHandlerSubType;
  56181. ok = openMovie (props, prop, movie);
  56182. DisposeHandle (dr.dataRef);
  56183. }
  56184. }
  56185. return ok;
  56186. }
  56187. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  56188. const bool isControllerVisible)
  56189. {
  56190. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  56191. movieFile = movieFile_;
  56192. return ok;
  56193. }
  56194. void QuickTimeMovieComponent::goToStart()
  56195. {
  56196. setPosition (0.0);
  56197. }
  56198. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  56199. const RectanglePlacement& placement)
  56200. {
  56201. int normalWidth, normalHeight;
  56202. getMovieNormalSize (normalWidth, normalHeight);
  56203. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  56204. {
  56205. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  56206. placement.applyTo (x, y, w, h,
  56207. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  56208. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  56209. if (w > 0 && h > 0)
  56210. {
  56211. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  56212. roundDoubleToInt (w), roundDoubleToInt (h));
  56213. }
  56214. }
  56215. else
  56216. {
  56217. setBounds (spaceToFitWithin);
  56218. }
  56219. }
  56220. END_JUCE_NAMESPACE
  56221. #endif
  56222. /********* End of inlined file: juce_QuickTimeMovieComponent.cpp *********/
  56223. /********* Start of inlined file: juce_SystemTrayIconComponent.cpp *********/
  56224. #if JUCE_WIN32 || JUCE_LINUX
  56225. BEGIN_JUCE_NAMESPACE
  56226. SystemTrayIconComponent::SystemTrayIconComponent()
  56227. {
  56228. addToDesktop (0);
  56229. }
  56230. SystemTrayIconComponent::~SystemTrayIconComponent()
  56231. {
  56232. }
  56233. END_JUCE_NAMESPACE
  56234. #endif
  56235. /********* End of inlined file: juce_SystemTrayIconComponent.cpp *********/
  56236. /********* Start of inlined file: juce_AlertWindow.cpp *********/
  56237. BEGIN_JUCE_NAMESPACE
  56238. static const int titleH = 24;
  56239. static const int iconWidth = 80;
  56240. class AlertWindowTextEditor : public TextEditor
  56241. {
  56242. public:
  56243. #if JUCE_LINUX
  56244. #define PASSWORD_CHAR 0x2022
  56245. #else
  56246. #define PASSWORD_CHAR 0x25cf
  56247. #endif
  56248. AlertWindowTextEditor (const String& name,
  56249. const bool isPasswordBox)
  56250. : TextEditor (name,
  56251. isPasswordBox ? (const tchar) PASSWORD_CHAR
  56252. : (const tchar) 0)
  56253. {
  56254. setSelectAllWhenFocused (true);
  56255. }
  56256. ~AlertWindowTextEditor()
  56257. {
  56258. }
  56259. void returnPressed()
  56260. {
  56261. // pass these up the component hierarchy to be trigger the buttons
  56262. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, T('\n')));
  56263. }
  56264. void escapePressed()
  56265. {
  56266. // pass these up the component hierarchy to be trigger the buttons
  56267. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  56268. }
  56269. private:
  56270. AlertWindowTextEditor (const AlertWindowTextEditor&);
  56271. const AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  56272. };
  56273. AlertWindow::AlertWindow (const String& title,
  56274. const String& message,
  56275. AlertIconType iconType)
  56276. : TopLevelWindow (title, true),
  56277. alertIconType (iconType)
  56278. {
  56279. if (message.isEmpty())
  56280. text = T(" "); // to force an update if the message is empty
  56281. setMessage (message);
  56282. #if JUCE_MAC
  56283. setAlwaysOnTop (true);
  56284. #else
  56285. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  56286. {
  56287. Component* const c = Desktop::getInstance().getComponent (i);
  56288. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  56289. {
  56290. setAlwaysOnTop (true);
  56291. break;
  56292. }
  56293. }
  56294. #endif
  56295. lookAndFeelChanged();
  56296. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  56297. }
  56298. AlertWindow::~AlertWindow()
  56299. {
  56300. for (int i = customComps.size(); --i >= 0;)
  56301. removeChildComponent ((Component*) customComps[i]);
  56302. deleteAllChildren();
  56303. }
  56304. void AlertWindow::setMessage (const String& message)
  56305. {
  56306. const String newMessage (message.substring (0, 2048));
  56307. if (text != newMessage)
  56308. {
  56309. text = newMessage;
  56310. font.setHeight (15.0f);
  56311. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  56312. textLayout.setText (getName() + T("\n\n"), titleFont);
  56313. textLayout.appendText (text, font);
  56314. updateLayout (true);
  56315. repaint();
  56316. }
  56317. }
  56318. void AlertWindow::buttonClicked (Button* button)
  56319. {
  56320. for (int i = 0; i < buttons.size(); i++)
  56321. {
  56322. TextButton* const c = (TextButton*) buttons[i];
  56323. if (button->getName() == c->getName())
  56324. {
  56325. if (c->getParentComponent() != 0)
  56326. c->getParentComponent()->exitModalState (c->getCommandID());
  56327. break;
  56328. }
  56329. }
  56330. }
  56331. void AlertWindow::addButton (const String& name,
  56332. const int returnValue,
  56333. const KeyPress& shortcutKey1,
  56334. const KeyPress& shortcutKey2)
  56335. {
  56336. TextButton* const b = new TextButton (name, String::empty);
  56337. b->setWantsKeyboardFocus (true);
  56338. b->setMouseClickGrabsKeyboardFocus (false);
  56339. b->setCommandToTrigger (0, returnValue, false);
  56340. b->addShortcut (shortcutKey1);
  56341. b->addShortcut (shortcutKey2);
  56342. b->addButtonListener (this);
  56343. b->changeWidthToFitText (28);
  56344. addAndMakeVisible (b, 0);
  56345. buttons.add (b);
  56346. updateLayout (false);
  56347. }
  56348. int AlertWindow::getNumButtons() const
  56349. {
  56350. return buttons.size();
  56351. }
  56352. void AlertWindow::addTextEditor (const String& name,
  56353. const String& initialContents,
  56354. const String& onScreenLabel,
  56355. const bool isPasswordBox)
  56356. {
  56357. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  56358. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  56359. tc->setFont (font);
  56360. tc->setText (initialContents);
  56361. tc->setCaretPosition (initialContents.length());
  56362. addAndMakeVisible (tc);
  56363. textBoxes.add (tc);
  56364. allComps.add (tc);
  56365. textboxNames.add (onScreenLabel);
  56366. updateLayout (false);
  56367. }
  56368. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  56369. {
  56370. for (int i = textBoxes.size(); --i >= 0;)
  56371. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  56372. return ((TextEditor*)textBoxes[i])->getText();
  56373. return String::empty;
  56374. }
  56375. void AlertWindow::addComboBox (const String& name,
  56376. const StringArray& items,
  56377. const String& onScreenLabel)
  56378. {
  56379. ComboBox* const cb = new ComboBox (name);
  56380. for (int i = 0; i < items.size(); ++i)
  56381. cb->addItem (items[i], i + 1);
  56382. addAndMakeVisible (cb);
  56383. cb->setSelectedItemIndex (0);
  56384. comboBoxes.add (cb);
  56385. allComps.add (cb);
  56386. comboBoxNames.add (onScreenLabel);
  56387. updateLayout (false);
  56388. }
  56389. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  56390. {
  56391. for (int i = comboBoxes.size(); --i >= 0;)
  56392. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  56393. return (ComboBox*) comboBoxes[i];
  56394. return 0;
  56395. }
  56396. class AlertTextComp : public TextEditor
  56397. {
  56398. AlertTextComp (const AlertTextComp&);
  56399. const AlertTextComp& operator= (const AlertTextComp&);
  56400. int bestWidth;
  56401. public:
  56402. AlertTextComp (const String& message,
  56403. const Font& font)
  56404. {
  56405. setReadOnly (true);
  56406. setMultiLine (true, true);
  56407. setCaretVisible (false);
  56408. setScrollbarsShown (true);
  56409. lookAndFeelChanged();
  56410. setWantsKeyboardFocus (false);
  56411. setFont (font);
  56412. setText (message, false);
  56413. bestWidth = 2 * (int) sqrt (font.getHeight() * font.getStringWidth (message));
  56414. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  56415. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  56416. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  56417. }
  56418. ~AlertTextComp()
  56419. {
  56420. }
  56421. int getPreferredWidth() const throw() { return bestWidth; }
  56422. void updateLayout (const int width)
  56423. {
  56424. TextLayout text;
  56425. text.appendText (getText(), getFont());
  56426. text.layout (width - 8, Justification::topLeft, true);
  56427. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  56428. }
  56429. };
  56430. void AlertWindow::addTextBlock (const String& text)
  56431. {
  56432. AlertTextComp* const c = new AlertTextComp (text, font);
  56433. textBlocks.add (c);
  56434. allComps.add (c);
  56435. addAndMakeVisible (c);
  56436. updateLayout (false);
  56437. }
  56438. void AlertWindow::addProgressBarComponent (double& progressValue)
  56439. {
  56440. ProgressBar* const pb = new ProgressBar (progressValue);
  56441. progressBars.add (pb);
  56442. allComps.add (pb);
  56443. addAndMakeVisible (pb);
  56444. updateLayout (false);
  56445. }
  56446. void AlertWindow::addCustomComponent (Component* const component)
  56447. {
  56448. customComps.add (component);
  56449. allComps.add (component);
  56450. addAndMakeVisible (component);
  56451. updateLayout (false);
  56452. }
  56453. int AlertWindow::getNumCustomComponents() const
  56454. {
  56455. return customComps.size();
  56456. }
  56457. Component* AlertWindow::getCustomComponent (const int index) const
  56458. {
  56459. return (Component*) customComps [index];
  56460. }
  56461. Component* AlertWindow::removeCustomComponent (const int index)
  56462. {
  56463. Component* const c = getCustomComponent (index);
  56464. if (c != 0)
  56465. {
  56466. customComps.removeValue (c);
  56467. allComps.removeValue (c);
  56468. removeChildComponent (c);
  56469. updateLayout (false);
  56470. }
  56471. return c;
  56472. }
  56473. void AlertWindow::paint (Graphics& g)
  56474. {
  56475. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  56476. g.setColour (Colours::black);
  56477. g.setFont (12.0f);
  56478. int i;
  56479. for (i = textBoxes.size(); --i >= 0;)
  56480. {
  56481. if (textboxNames[i].isNotEmpty())
  56482. {
  56483. const TextEditor* const te = (TextEditor*) textBoxes[i];
  56484. g.drawFittedText (textboxNames[i],
  56485. te->getX(), te->getY() - 14,
  56486. te->getWidth(), 14,
  56487. Justification::centredLeft, 1);
  56488. }
  56489. }
  56490. for (i = comboBoxNames.size(); --i >= 0;)
  56491. {
  56492. if (comboBoxNames[i].isNotEmpty())
  56493. {
  56494. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  56495. g.drawFittedText (comboBoxNames[i],
  56496. cb->getX(), cb->getY() - 14,
  56497. cb->getWidth(), 14,
  56498. Justification::centredLeft, 1);
  56499. }
  56500. }
  56501. }
  56502. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  56503. {
  56504. const int wid = jmax (font.getStringWidth (text),
  56505. font.getStringWidth (getName()));
  56506. const int sw = (int) sqrt (font.getHeight() * wid);
  56507. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  56508. const int edgeGap = 10;
  56509. int iconSpace;
  56510. if (alertIconType == NoIcon)
  56511. {
  56512. textLayout.layout (w, Justification::horizontallyCentred, true);
  56513. iconSpace = 0;
  56514. }
  56515. else
  56516. {
  56517. textLayout.layout (w, Justification::left, true);
  56518. iconSpace = iconWidth;
  56519. }
  56520. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  56521. w = jmin (w, (int) (getParentWidth() * 0.7f));
  56522. const int textLayoutH = textLayout.getHeight();
  56523. const int textBottom = 16 + titleH + textLayoutH;
  56524. int h = textBottom;
  56525. int buttonW = 40;
  56526. int i;
  56527. for (i = 0; i < buttons.size(); ++i)
  56528. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  56529. w = jmax (buttonW, w);
  56530. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  56531. if (buttons.size() > 0)
  56532. h += 20 + ((TextButton*) buttons[0])->getHeight();
  56533. for (i = customComps.size(); --i >= 0;)
  56534. {
  56535. w = jmax (w, ((Component*) customComps[i])->getWidth() + 40);
  56536. h += 10 + ((Component*) customComps[i])->getHeight();
  56537. }
  56538. for (i = textBlocks.size(); --i >= 0;)
  56539. {
  56540. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  56541. w = jmax (w, ac->getPreferredWidth());
  56542. }
  56543. w = jmin (w, (int) (getParentWidth() * 0.7f));
  56544. for (i = textBlocks.size(); --i >= 0;)
  56545. {
  56546. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  56547. ac->updateLayout ((int) (w * 0.8f));
  56548. h += ac->getHeight() + 10;
  56549. }
  56550. h = jmin (getParentHeight() - 50, h);
  56551. if (onlyIncreaseSize)
  56552. {
  56553. w = jmax (w, getWidth());
  56554. h = jmax (h, getHeight());
  56555. }
  56556. if (! isVisible())
  56557. {
  56558. centreAroundComponent (0, w, h);
  56559. }
  56560. else
  56561. {
  56562. const int cx = getX() + getWidth() / 2;
  56563. const int cy = getY() + getHeight() / 2;
  56564. setBounds (cx - w / 2,
  56565. cy - h / 2,
  56566. w, h);
  56567. }
  56568. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  56569. const int spacer = 16;
  56570. int totalWidth = -spacer;
  56571. for (i = buttons.size(); --i >= 0;)
  56572. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  56573. int x = (w - totalWidth) / 2;
  56574. int y = (int) (getHeight() * 0.95f);
  56575. for (i = 0; i < buttons.size(); ++i)
  56576. {
  56577. TextButton* const c = (TextButton*) buttons[i];
  56578. int ny = proportionOfHeight (0.95f) - c->getHeight();
  56579. c->setTopLeftPosition (x, ny);
  56580. if (ny < y)
  56581. y = ny;
  56582. x += c->getWidth() + spacer;
  56583. c->toFront (false);
  56584. }
  56585. y = textBottom;
  56586. for (i = 0; i < allComps.size(); ++i)
  56587. {
  56588. Component* const c = (Component*) allComps[i];
  56589. const int h = 22;
  56590. const int comboIndex = comboBoxes.indexOf (c);
  56591. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  56592. y += 18;
  56593. const int tbIndex = textBoxes.indexOf (c);
  56594. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  56595. y += 18;
  56596. if (customComps.contains (c) || textBlocks.contains (c))
  56597. {
  56598. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  56599. y += c->getHeight() + 10;
  56600. }
  56601. else
  56602. {
  56603. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  56604. y += h + 10;
  56605. }
  56606. }
  56607. setWantsKeyboardFocus (getNumChildComponents() == 0);
  56608. }
  56609. bool AlertWindow::containsAnyExtraComponents() const
  56610. {
  56611. return textBoxes.size()
  56612. + comboBoxes.size()
  56613. + progressBars.size()
  56614. + customComps.size() > 0;
  56615. }
  56616. void AlertWindow::mouseDown (const MouseEvent&)
  56617. {
  56618. dragger.startDraggingComponent (this, &constrainer);
  56619. }
  56620. void AlertWindow::mouseDrag (const MouseEvent& e)
  56621. {
  56622. dragger.dragComponent (this, e);
  56623. }
  56624. bool AlertWindow::keyPressed (const KeyPress& key)
  56625. {
  56626. for (int i = buttons.size(); --i >= 0;)
  56627. {
  56628. TextButton* const b = (TextButton*) buttons[i];
  56629. if (b->isRegisteredForShortcut (key))
  56630. {
  56631. b->triggerClick();
  56632. return true;
  56633. }
  56634. }
  56635. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  56636. {
  56637. exitModalState (0);
  56638. return true;
  56639. }
  56640. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  56641. {
  56642. ((TextButton*) buttons.getFirst())->triggerClick();
  56643. return true;
  56644. }
  56645. return false;
  56646. }
  56647. void AlertWindow::lookAndFeelChanged()
  56648. {
  56649. const int flags = getLookAndFeel().getAlertBoxWindowFlags();
  56650. setUsingNativeTitleBar ((flags & ComponentPeer::windowHasTitleBar) != 0);
  56651. setDropShadowEnabled ((flags & ComponentPeer::windowHasDropShadow) != 0);
  56652. }
  56653. struct AlertWindowInfo
  56654. {
  56655. String title, message, button1, button2, button3;
  56656. AlertWindow::AlertIconType iconType;
  56657. int numButtons;
  56658. int run() const
  56659. {
  56660. return (int) (pointer_sized_int)
  56661. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  56662. }
  56663. private:
  56664. int show() const
  56665. {
  56666. AlertWindow aw (title, message, iconType);
  56667. if (numButtons == 1)
  56668. {
  56669. aw.addButton (button1, 0,
  56670. KeyPress (KeyPress::escapeKey, 0, 0),
  56671. KeyPress (KeyPress::returnKey, 0, 0));
  56672. }
  56673. else
  56674. {
  56675. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  56676. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  56677. if (button1ShortCut == button2ShortCut)
  56678. button2ShortCut = KeyPress();
  56679. if (numButtons == 2)
  56680. {
  56681. aw.addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  56682. aw.addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  56683. }
  56684. else
  56685. {
  56686. jassert (numButtons == 3);
  56687. aw.addButton (button1, 1, button1ShortCut);
  56688. aw.addButton (button2, 2, button2ShortCut);
  56689. aw.addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  56690. }
  56691. }
  56692. return aw.runModalLoop();
  56693. }
  56694. static void* showCallback (void* userData)
  56695. {
  56696. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  56697. }
  56698. };
  56699. void AlertWindow::showMessageBox (AlertIconType iconType,
  56700. const String& title,
  56701. const String& message,
  56702. const String& buttonText)
  56703. {
  56704. AlertWindowInfo info;
  56705. info.title = title;
  56706. info.message = message;
  56707. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  56708. info.iconType = iconType;
  56709. info.numButtons = 1;
  56710. info.run();
  56711. }
  56712. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  56713. const String& title,
  56714. const String& message,
  56715. const String& button1Text,
  56716. const String& button2Text)
  56717. {
  56718. AlertWindowInfo info;
  56719. info.title = title;
  56720. info.message = message;
  56721. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  56722. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  56723. info.iconType = iconType;
  56724. info.numButtons = 2;
  56725. return info.run() != 0;
  56726. }
  56727. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  56728. const String& title,
  56729. const String& message,
  56730. const String& button1Text,
  56731. const String& button2Text,
  56732. const String& button3Text)
  56733. {
  56734. AlertWindowInfo info;
  56735. info.title = title;
  56736. info.message = message;
  56737. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  56738. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  56739. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  56740. info.iconType = iconType;
  56741. info.numButtons = 3;
  56742. return info.run();
  56743. }
  56744. END_JUCE_NAMESPACE
  56745. /********* End of inlined file: juce_AlertWindow.cpp *********/
  56746. /********* Start of inlined file: juce_ComponentPeer.cpp *********/
  56747. BEGIN_JUCE_NAMESPACE
  56748. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  56749. // these are over in juce_component.cpp
  56750. extern int64 juce_recentMouseDownTimes[4];
  56751. extern int juce_recentMouseDownX [4];
  56752. extern int juce_recentMouseDownY [4];
  56753. extern Component* juce_recentMouseDownComponent [4];
  56754. extern int juce_LastMousePosX;
  56755. extern int juce_LastMousePosY;
  56756. extern int juce_MouseClickCounter;
  56757. extern bool juce_MouseHasMovedSignificantlySincePressed;
  56758. static const int fakeMouseMoveMessage = 0x7fff00ff;
  56759. static VoidArray heavyweightPeers (4);
  56760. ComponentPeer::ComponentPeer (Component* const component_,
  56761. const int styleFlags_) throw()
  56762. : component (component_),
  56763. styleFlags (styleFlags_),
  56764. lastPaintTime (0),
  56765. constrainer (0),
  56766. lastFocusedComponent (0),
  56767. dragAndDropTargetComponent (0),
  56768. lastDragAndDropCompUnderMouse (0),
  56769. fakeMouseMessageSent (false),
  56770. isWindowMinimised (false)
  56771. {
  56772. heavyweightPeers.add (this);
  56773. }
  56774. ComponentPeer::~ComponentPeer()
  56775. {
  56776. heavyweightPeers.removeValue (this);
  56777. delete dragAndDropTargetComponent;
  56778. }
  56779. int ComponentPeer::getNumPeers() throw()
  56780. {
  56781. return heavyweightPeers.size();
  56782. }
  56783. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  56784. {
  56785. return (ComponentPeer*) heavyweightPeers [index];
  56786. }
  56787. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  56788. {
  56789. for (int i = heavyweightPeers.size(); --i >= 0;)
  56790. {
  56791. ComponentPeer* const peer = (ComponentPeer*) heavyweightPeers.getUnchecked(i);
  56792. if (peer->getComponent() == component)
  56793. return peer;
  56794. }
  56795. return 0;
  56796. }
  56797. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  56798. {
  56799. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  56800. }
  56801. void ComponentPeer::updateCurrentModifiers() throw()
  56802. {
  56803. ModifierKeys::updateCurrentModifiers();
  56804. }
  56805. void ComponentPeer::handleMouseEnter (int x, int y, const int64 time)
  56806. {
  56807. jassert (component->isValidComponent());
  56808. updateCurrentModifiers();
  56809. Component* c = component->getComponentAt (x, y);
  56810. const ComponentDeletionWatcher deletionChecker (component);
  56811. if (c != Component::componentUnderMouse && Component::componentUnderMouse != 0)
  56812. {
  56813. jassert (Component::componentUnderMouse->isValidComponent());
  56814. const int oldX = x;
  56815. const int oldY = y;
  56816. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56817. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56818. Component::componentUnderMouse = 0;
  56819. if (deletionChecker.hasBeenDeleted())
  56820. return;
  56821. c = component->getComponentAt (oldX, oldY);
  56822. }
  56823. Component::componentUnderMouse = c;
  56824. if (Component::componentUnderMouse != 0)
  56825. {
  56826. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56827. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  56828. }
  56829. }
  56830. void ComponentPeer::handleMouseMove (int x, int y, const int64 time)
  56831. {
  56832. jassert (component->isValidComponent());
  56833. updateCurrentModifiers();
  56834. fakeMouseMessageSent = false;
  56835. const ComponentDeletionWatcher deletionChecker (component);
  56836. Component* c = component->getComponentAt (x, y);
  56837. if (c != Component::componentUnderMouse)
  56838. {
  56839. const int oldX = x;
  56840. const int oldY = y;
  56841. if (Component::componentUnderMouse != 0)
  56842. {
  56843. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56844. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56845. x = oldX;
  56846. y = oldY;
  56847. Component::componentUnderMouse = 0;
  56848. if (deletionChecker.hasBeenDeleted())
  56849. return; // if this window has just been deleted..
  56850. c = component->getComponentAt (x, y);
  56851. }
  56852. Component::componentUnderMouse = c;
  56853. if (c != 0)
  56854. {
  56855. component->relativePositionToOtherComponent (c, x, y);
  56856. c->internalMouseEnter (x, y, time);
  56857. x = oldX;
  56858. y = oldY;
  56859. if (deletionChecker.hasBeenDeleted())
  56860. return; // if this window has just been deleted..
  56861. }
  56862. }
  56863. if (Component::componentUnderMouse != 0)
  56864. {
  56865. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56866. Component::componentUnderMouse->internalMouseMove (x, y, time);
  56867. }
  56868. }
  56869. void ComponentPeer::handleMouseDown (int x, int y, const int64 time)
  56870. {
  56871. ++juce_MouseClickCounter;
  56872. updateCurrentModifiers();
  56873. int numMouseButtonsDown = 0;
  56874. if (ModifierKeys::getCurrentModifiers().isLeftButtonDown())
  56875. ++numMouseButtonsDown;
  56876. if (ModifierKeys::getCurrentModifiers().isRightButtonDown())
  56877. ++numMouseButtonsDown;
  56878. if (ModifierKeys::getCurrentModifiers().isMiddleButtonDown())
  56879. ++numMouseButtonsDown;
  56880. if (numMouseButtonsDown == 1)
  56881. {
  56882. Component::componentUnderMouse = component->getComponentAt (x, y);
  56883. if (Component::componentUnderMouse != 0)
  56884. {
  56885. // can't set these in the mouseDownInt() method, because it's re-entrant, so do it here..
  56886. for (int i = numElementsInArray (juce_recentMouseDownTimes); --i > 0;)
  56887. {
  56888. juce_recentMouseDownTimes [i] = juce_recentMouseDownTimes [i - 1];
  56889. juce_recentMouseDownX [i] = juce_recentMouseDownX [i - 1];
  56890. juce_recentMouseDownY [i] = juce_recentMouseDownY [i - 1];
  56891. juce_recentMouseDownComponent [i] = juce_recentMouseDownComponent [i - 1];
  56892. }
  56893. juce_recentMouseDownTimes[0] = time;
  56894. juce_recentMouseDownX[0] = x;
  56895. juce_recentMouseDownY[0] = y;
  56896. juce_recentMouseDownComponent[0] = Component::componentUnderMouse;
  56897. relativePositionToGlobal (juce_recentMouseDownX[0], juce_recentMouseDownY[0]);
  56898. juce_MouseHasMovedSignificantlySincePressed = false;
  56899. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56900. Component::componentUnderMouse->internalMouseDown (x, y);
  56901. }
  56902. }
  56903. }
  56904. void ComponentPeer::handleMouseDrag (int x, int y, const int64 time)
  56905. {
  56906. updateCurrentModifiers();
  56907. if (Component::componentUnderMouse != 0)
  56908. {
  56909. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56910. Component::componentUnderMouse->internalMouseDrag (x, y, time);
  56911. }
  56912. }
  56913. void ComponentPeer::handleMouseUp (const int oldModifiers, int x, int y, const int64 time)
  56914. {
  56915. updateCurrentModifiers();
  56916. int numMouseButtonsDown = 0;
  56917. if ((oldModifiers & ModifierKeys::leftButtonModifier) != 0)
  56918. ++numMouseButtonsDown;
  56919. if ((oldModifiers & ModifierKeys::rightButtonModifier) != 0)
  56920. ++numMouseButtonsDown;
  56921. if ((oldModifiers & ModifierKeys::middleButtonModifier) != 0)
  56922. ++numMouseButtonsDown;
  56923. if (numMouseButtonsDown == 1)
  56924. {
  56925. const ComponentDeletionWatcher deletionChecker (component);
  56926. Component* c = component->getComponentAt (x, y);
  56927. if (c != Component::componentUnderMouse)
  56928. {
  56929. const int oldX = x;
  56930. const int oldY = y;
  56931. if (Component::componentUnderMouse != 0)
  56932. {
  56933. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56934. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  56935. x = oldX;
  56936. y = oldY;
  56937. if (Component::componentUnderMouse != 0)
  56938. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56939. if (deletionChecker.hasBeenDeleted())
  56940. return;
  56941. c = component->getComponentAt (oldX, oldY);
  56942. }
  56943. Component::componentUnderMouse = c;
  56944. if (Component::componentUnderMouse != 0)
  56945. {
  56946. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56947. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  56948. }
  56949. }
  56950. else
  56951. {
  56952. if (Component::componentUnderMouse != 0)
  56953. {
  56954. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56955. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  56956. }
  56957. }
  56958. }
  56959. }
  56960. void ComponentPeer::handleMouseExit (int x, int y, const int64 time)
  56961. {
  56962. jassert (component->isValidComponent());
  56963. updateCurrentModifiers();
  56964. if (Component::componentUnderMouse != 0)
  56965. {
  56966. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56967. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56968. Component::componentUnderMouse = 0;
  56969. }
  56970. }
  56971. void ComponentPeer::handleMouseWheel (const int amountX, const int amountY, const int64 time)
  56972. {
  56973. updateCurrentModifiers();
  56974. if (Component::componentUnderMouse != 0)
  56975. Component::componentUnderMouse->internalMouseWheel (amountX, amountY, time);
  56976. }
  56977. void ComponentPeer::sendFakeMouseMove() throw()
  56978. {
  56979. if ((! fakeMouseMessageSent)
  56980. && component->flags.hasHeavyweightPeerFlag
  56981. && ! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  56982. {
  56983. if (! isMinimised())
  56984. {
  56985. int realX, realY, realW, realH;
  56986. getBounds (realX, realY, realW, realH);
  56987. component->bounds_.setBounds (realX, realY, realW, realH);
  56988. }
  56989. int x, y;
  56990. component->getMouseXYRelative (x, y);
  56991. if (((unsigned int) x) < (unsigned int) component->getWidth()
  56992. && ((unsigned int) y) < (unsigned int) component->getHeight()
  56993. && contains (x, y, false))
  56994. {
  56995. postMessage (new Message (fakeMouseMoveMessage, x, y, 0));
  56996. }
  56997. fakeMouseMessageSent = true;
  56998. }
  56999. }
  57000. void ComponentPeer::handleMessage (const Message& message)
  57001. {
  57002. if (message.intParameter1 == fakeMouseMoveMessage)
  57003. {
  57004. handleMouseMove (message.intParameter2,
  57005. message.intParameter3,
  57006. Time::currentTimeMillis());
  57007. }
  57008. }
  57009. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  57010. {
  57011. Graphics g (&contextToPaintTo);
  57012. #if JUCE_ENABLE_REPAINT_DEBUGGING
  57013. g.saveState();
  57014. #endif
  57015. JUCE_TRY
  57016. {
  57017. component->paintEntireComponent (g);
  57018. }
  57019. JUCE_CATCH_EXCEPTION
  57020. #if JUCE_ENABLE_REPAINT_DEBUGGING
  57021. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  57022. // clearly when things are being repainted.
  57023. {
  57024. g.restoreState();
  57025. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  57026. (uint8) Random::getSystemRandom().nextInt (255),
  57027. (uint8) Random::getSystemRandom().nextInt (255),
  57028. (uint8) 0x50));
  57029. }
  57030. #endif
  57031. }
  57032. bool ComponentPeer::handleKeyPress (const int keyCode,
  57033. const juce_wchar textCharacter)
  57034. {
  57035. updateCurrentModifiers();
  57036. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  57037. ? Component::currentlyFocusedComponent
  57038. : component;
  57039. if (target->isCurrentlyBlockedByAnotherModalComponent())
  57040. {
  57041. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  57042. if (currentModalComp != 0)
  57043. target = currentModalComp;
  57044. }
  57045. const KeyPress keyInfo (keyCode,
  57046. ModifierKeys::getCurrentModifiers().getRawFlags()
  57047. & ModifierKeys::allKeyboardModifiers,
  57048. textCharacter);
  57049. bool keyWasUsed = false;
  57050. while (target != 0)
  57051. {
  57052. const ComponentDeletionWatcher deletionChecker (target);
  57053. if (target->keyListeners_ != 0)
  57054. {
  57055. for (int i = target->keyListeners_->size(); --i >= 0;)
  57056. {
  57057. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyPressed (keyInfo, target);
  57058. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  57059. return keyWasUsed;
  57060. i = jmin (i, target->keyListeners_->size());
  57061. }
  57062. }
  57063. keyWasUsed = target->keyPressed (keyInfo);
  57064. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  57065. break;
  57066. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  57067. {
  57068. Component::getCurrentlyFocusedComponent()
  57069. ->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  57070. keyWasUsed = true;
  57071. break;
  57072. }
  57073. target = target->parentComponent_;
  57074. }
  57075. return keyWasUsed;
  57076. }
  57077. bool ComponentPeer::handleKeyUpOrDown()
  57078. {
  57079. updateCurrentModifiers();
  57080. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  57081. ? Component::currentlyFocusedComponent
  57082. : component;
  57083. if (target->isCurrentlyBlockedByAnotherModalComponent())
  57084. {
  57085. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  57086. if (currentModalComp != 0)
  57087. target = currentModalComp;
  57088. }
  57089. bool keyWasUsed = false;
  57090. while (target != 0)
  57091. {
  57092. const ComponentDeletionWatcher deletionChecker (target);
  57093. keyWasUsed = target->keyStateChanged();
  57094. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  57095. break;
  57096. if (target->keyListeners_ != 0)
  57097. {
  57098. for (int i = target->keyListeners_->size(); --i >= 0;)
  57099. {
  57100. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyStateChanged (target);
  57101. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  57102. return keyWasUsed;
  57103. i = jmin (i, target->keyListeners_->size());
  57104. }
  57105. }
  57106. target = target->parentComponent_;
  57107. }
  57108. return keyWasUsed;
  57109. }
  57110. void ComponentPeer::handleModifierKeysChange()
  57111. {
  57112. updateCurrentModifiers();
  57113. Component* target = Component::getComponentUnderMouse();
  57114. if (target == 0)
  57115. target = Component::getCurrentlyFocusedComponent();
  57116. if (target == 0)
  57117. target = component;
  57118. if (target->isValidComponent())
  57119. target->internalModifierKeysChanged();
  57120. }
  57121. void ComponentPeer::handleBroughtToFront()
  57122. {
  57123. updateCurrentModifiers();
  57124. if (component != 0)
  57125. component->internalBroughtToFront();
  57126. }
  57127. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  57128. {
  57129. constrainer = newConstrainer;
  57130. }
  57131. void ComponentPeer::handleMovedOrResized()
  57132. {
  57133. jassert (component->isValidComponent());
  57134. updateCurrentModifiers();
  57135. const bool nowMinimised = isMinimised();
  57136. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  57137. {
  57138. const ComponentDeletionWatcher deletionChecker (component);
  57139. int realX, realY, realW, realH;
  57140. getBounds (realX, realY, realW, realH);
  57141. const bool wasMoved = (component->getX() != realX || component->getY() != realY);
  57142. const bool wasResized = (component->getWidth() != realW || component->getHeight() != realH);
  57143. if (wasMoved || wasResized)
  57144. {
  57145. component->bounds_.setBounds (realX, realY, realW, realH);
  57146. if (wasResized)
  57147. component->repaint();
  57148. component->sendMovedResizedMessages (wasMoved, wasResized);
  57149. if (deletionChecker.hasBeenDeleted())
  57150. return;
  57151. }
  57152. }
  57153. if (isWindowMinimised != nowMinimised)
  57154. {
  57155. isWindowMinimised = nowMinimised;
  57156. component->minimisationStateChanged (nowMinimised);
  57157. component->sendVisibilityChangeMessage();
  57158. }
  57159. if (! isFullScreen())
  57160. lastNonFullscreenBounds = component->getBounds();
  57161. }
  57162. void ComponentPeer::handleFocusGain()
  57163. {
  57164. updateCurrentModifiers();
  57165. if (component->isParentOf (lastFocusedComponent))
  57166. {
  57167. Component::currentlyFocusedComponent = lastFocusedComponent;
  57168. Desktop::getInstance().triggerFocusCallback();
  57169. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  57170. }
  57171. else
  57172. {
  57173. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  57174. {
  57175. component->grabKeyboardFocus();
  57176. }
  57177. else
  57178. {
  57179. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  57180. if (currentModalComp != 0)
  57181. currentModalComp->toFront (! currentModalComp->hasKeyboardFocus (true));
  57182. }
  57183. }
  57184. }
  57185. void ComponentPeer::handleFocusLoss()
  57186. {
  57187. updateCurrentModifiers();
  57188. if (component->hasKeyboardFocus (true))
  57189. {
  57190. lastFocusedComponent = Component::currentlyFocusedComponent;
  57191. if (lastFocusedComponent != 0)
  57192. {
  57193. Component::currentlyFocusedComponent = 0;
  57194. Desktop::getInstance().triggerFocusCallback();
  57195. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  57196. }
  57197. }
  57198. }
  57199. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  57200. {
  57201. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  57202. ? lastFocusedComponent
  57203. : component;
  57204. }
  57205. void ComponentPeer::handleScreenSizeChange()
  57206. {
  57207. updateCurrentModifiers();
  57208. component->parentSizeChanged();
  57209. handleMovedOrResized();
  57210. }
  57211. void ComponentPeer::setNonFullScreenBounds (const Rectangle& newBounds) throw()
  57212. {
  57213. lastNonFullscreenBounds = newBounds;
  57214. }
  57215. const Rectangle& ComponentPeer::getNonFullScreenBounds() const throw()
  57216. {
  57217. return lastNonFullscreenBounds;
  57218. }
  57219. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  57220. const StringArray& files,
  57221. FileDragAndDropTarget* const lastOne)
  57222. {
  57223. while (c != 0)
  57224. {
  57225. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  57226. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  57227. return t;
  57228. c = c->getParentComponent();
  57229. }
  57230. return 0;
  57231. }
  57232. void ComponentPeer::handleFileDragMove (const StringArray& files, int x, int y)
  57233. {
  57234. updateCurrentModifiers();
  57235. FileDragAndDropTarget* lastTarget = 0;
  57236. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  57237. lastTarget = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  57238. FileDragAndDropTarget* newTarget = 0;
  57239. Component* const compUnderMouse = component->getComponentAt (x, y);
  57240. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  57241. {
  57242. lastDragAndDropCompUnderMouse = compUnderMouse;
  57243. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  57244. if (newTarget != lastTarget)
  57245. {
  57246. if (lastTarget != 0)
  57247. lastTarget->fileDragExit (files);
  57248. deleteAndZero (dragAndDropTargetComponent);
  57249. if (newTarget != 0)
  57250. {
  57251. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  57252. int mx = x, my = y;
  57253. component->relativePositionToOtherComponent (targetComp, mx, my);
  57254. dragAndDropTargetComponent = new ComponentDeletionWatcher (dynamic_cast <Component*> (newTarget));
  57255. newTarget->fileDragEnter (files, mx, my);
  57256. }
  57257. }
  57258. }
  57259. else
  57260. {
  57261. newTarget = lastTarget;
  57262. }
  57263. if (newTarget != 0)
  57264. {
  57265. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  57266. component->relativePositionToOtherComponent (targetComp, x, y);
  57267. newTarget->fileDragMove (files, x, y);
  57268. }
  57269. }
  57270. void ComponentPeer::handleFileDragExit (const StringArray& files)
  57271. {
  57272. handleFileDragMove (files, -1, -1);
  57273. jassert (dragAndDropTargetComponent == 0);
  57274. lastDragAndDropCompUnderMouse = 0;
  57275. }
  57276. void ComponentPeer::handleFileDragDrop (const StringArray& files, int x, int y)
  57277. {
  57278. handleFileDragMove (files, x, y);
  57279. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  57280. {
  57281. FileDragAndDropTarget* const target = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  57282. deleteAndZero (dragAndDropTargetComponent);
  57283. lastDragAndDropCompUnderMouse = 0;
  57284. if (target != 0)
  57285. {
  57286. Component* const targetComp = dynamic_cast <Component*> (target);
  57287. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  57288. {
  57289. targetComp->internalModalInputAttempt();
  57290. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  57291. return;
  57292. }
  57293. component->relativePositionToOtherComponent (targetComp, x, y);
  57294. target->filesDropped (files, x, y);
  57295. }
  57296. }
  57297. }
  57298. void ComponentPeer::handleUserClosingWindow()
  57299. {
  57300. updateCurrentModifiers();
  57301. component->userTriedToCloseWindow();
  57302. }
  57303. void ComponentPeer::clearMaskedRegion() throw()
  57304. {
  57305. maskedRegion.clear();
  57306. }
  57307. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h) throw()
  57308. {
  57309. maskedRegion.add (x, y, w, h);
  57310. }
  57311. END_JUCE_NAMESPACE
  57312. /********* End of inlined file: juce_ComponentPeer.cpp *********/
  57313. /********* Start of inlined file: juce_DialogWindow.cpp *********/
  57314. BEGIN_JUCE_NAMESPACE
  57315. DialogWindow::DialogWindow (const String& name,
  57316. const Colour& backgroundColour_,
  57317. const bool escapeKeyTriggersCloseButton_,
  57318. const bool addToDesktop_)
  57319. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  57320. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  57321. {
  57322. }
  57323. DialogWindow::~DialogWindow()
  57324. {
  57325. }
  57326. void DialogWindow::resized()
  57327. {
  57328. DocumentWindow::resized();
  57329. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  57330. if (escapeKeyTriggersCloseButton
  57331. && getCloseButton() != 0
  57332. && ! getCloseButton()->isRegisteredForShortcut (esc))
  57333. {
  57334. getCloseButton()->addShortcut (esc);
  57335. }
  57336. }
  57337. class TempDialogWindow : public DialogWindow
  57338. {
  57339. public:
  57340. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  57341. : DialogWindow (title, colour, escapeCloses, true)
  57342. {
  57343. }
  57344. ~TempDialogWindow()
  57345. {
  57346. }
  57347. void closeButtonPressed()
  57348. {
  57349. setVisible (false);
  57350. }
  57351. private:
  57352. TempDialogWindow (const TempDialogWindow&);
  57353. const TempDialogWindow& operator= (const TempDialogWindow&);
  57354. };
  57355. int DialogWindow::showModalDialog (const String& dialogTitle,
  57356. Component* contentComponent,
  57357. Component* componentToCentreAround,
  57358. const Colour& colour,
  57359. const bool escapeKeyTriggersCloseButton,
  57360. const bool shouldBeResizable,
  57361. const bool useBottomRightCornerResizer)
  57362. {
  57363. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  57364. dw.setContentComponent (contentComponent, true, true);
  57365. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  57366. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  57367. const int result = dw.runModalLoop();
  57368. dw.setContentComponent (0, false);
  57369. return result;
  57370. }
  57371. END_JUCE_NAMESPACE
  57372. /********* End of inlined file: juce_DialogWindow.cpp *********/
  57373. /********* Start of inlined file: juce_DocumentWindow.cpp *********/
  57374. BEGIN_JUCE_NAMESPACE
  57375. DocumentWindow::DocumentWindow (const String& title,
  57376. const Colour& backgroundColour,
  57377. const int requiredButtons_,
  57378. const bool addToDesktop_)
  57379. : ResizableWindow (title, backgroundColour, addToDesktop_),
  57380. titleBarHeight (26),
  57381. menuBarHeight (24),
  57382. requiredButtons (requiredButtons_),
  57383. #if JUCE_MAC
  57384. positionTitleBarButtonsOnLeft (true),
  57385. #else
  57386. positionTitleBarButtonsOnLeft (false),
  57387. #endif
  57388. drawTitleTextCentred (true),
  57389. titleBarIcon (0),
  57390. menuBar (0),
  57391. menuBarModel (0)
  57392. {
  57393. zeromem (titleBarButtons, sizeof (titleBarButtons));
  57394. setResizeLimits (128, 128, 32768, 32768);
  57395. lookAndFeelChanged();
  57396. }
  57397. DocumentWindow::~DocumentWindow()
  57398. {
  57399. for (int i = 0; i < 3; ++i)
  57400. delete titleBarButtons[i];
  57401. delete titleBarIcon;
  57402. delete menuBar;
  57403. }
  57404. void DocumentWindow::repaintTitleBar()
  57405. {
  57406. const int border = getBorderSize();
  57407. repaint (border, border, getWidth() - border * 2, getTitleBarHeight());
  57408. }
  57409. void DocumentWindow::setName (const String& newName)
  57410. {
  57411. if (newName != getName())
  57412. {
  57413. Component::setName (newName);
  57414. repaintTitleBar();
  57415. }
  57416. }
  57417. void DocumentWindow::setIcon (const Image* imageToUse)
  57418. {
  57419. deleteAndZero (titleBarIcon);
  57420. if (imageToUse != 0)
  57421. titleBarIcon = imageToUse->createCopy();
  57422. repaintTitleBar();
  57423. }
  57424. void DocumentWindow::setTitleBarHeight (const int newHeight)
  57425. {
  57426. titleBarHeight = newHeight;
  57427. resized();
  57428. repaintTitleBar();
  57429. }
  57430. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  57431. const bool positionTitleBarButtonsOnLeft_)
  57432. {
  57433. requiredButtons = requiredButtons_;
  57434. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  57435. lookAndFeelChanged();
  57436. }
  57437. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  57438. {
  57439. drawTitleTextCentred = textShouldBeCentred;
  57440. repaintTitleBar();
  57441. }
  57442. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  57443. const int menuBarHeight_)
  57444. {
  57445. if (menuBarModel != menuBarModel_)
  57446. {
  57447. delete menuBar;
  57448. menuBar = 0;
  57449. menuBarModel = menuBarModel_;
  57450. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  57451. : getLookAndFeel().getDefaultMenuBarHeight();
  57452. if (menuBarModel != 0)
  57453. {
  57454. // (call the Component method directly to avoid the assertion in ResizableWindow)
  57455. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  57456. menuBar->setEnabled (isActiveWindow());
  57457. }
  57458. resized();
  57459. }
  57460. }
  57461. void DocumentWindow::closeButtonPressed()
  57462. {
  57463. /* If you've got a close button, you have to override this method to get
  57464. rid of your window!
  57465. If the window is just a pop-up, you should override this method and make
  57466. it delete the window in whatever way is appropriate for your app. E.g. you
  57467. might just want to call "delete this".
  57468. If your app is centred around this window such that the whole app should quit when
  57469. the window is closed, then you will probably want to use this method as an opportunity
  57470. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  57471. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  57472. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  57473. or closing it via the taskbar icon on Windows).
  57474. */
  57475. jassertfalse
  57476. }
  57477. void DocumentWindow::minimiseButtonPressed()
  57478. {
  57479. setMinimised (true);
  57480. }
  57481. void DocumentWindow::maximiseButtonPressed()
  57482. {
  57483. setFullScreen (! isFullScreen());
  57484. }
  57485. void DocumentWindow::paint (Graphics& g)
  57486. {
  57487. ResizableWindow::paint (g);
  57488. if (resizableBorder == 0 && getBorderSize() == 1)
  57489. {
  57490. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  57491. g.drawRect (0, 0, getWidth(), getHeight());
  57492. }
  57493. const int border = getBorderSize();
  57494. g.setOrigin (border, border);
  57495. g.reduceClipRegion (0, 0, getWidth() - border * 2, getTitleBarHeight());
  57496. int titleSpaceX1 = 6;
  57497. int titleSpaceX2 = getWidth() - 6;
  57498. for (int i = 0; i < 3; ++i)
  57499. {
  57500. if (titleBarButtons[i] != 0)
  57501. {
  57502. if (positionTitleBarButtonsOnLeft)
  57503. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  57504. else
  57505. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  57506. }
  57507. }
  57508. getLookAndFeel()
  57509. .drawDocumentWindowTitleBar (*this, g,
  57510. getWidth() - border * 2,
  57511. getTitleBarHeight(),
  57512. titleSpaceX1, jmax (1, titleSpaceX2 - titleSpaceX1),
  57513. titleBarIcon, ! drawTitleTextCentred);
  57514. }
  57515. void DocumentWindow::resized()
  57516. {
  57517. ResizableWindow::resized();
  57518. if (titleBarButtons[1] != 0)
  57519. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  57520. const int border = getBorderSize();
  57521. getLookAndFeel()
  57522. .positionDocumentWindowButtons (*this,
  57523. border, border,
  57524. getWidth() - border * 2, getTitleBarHeight(),
  57525. titleBarButtons[0],
  57526. titleBarButtons[1],
  57527. titleBarButtons[2],
  57528. positionTitleBarButtonsOnLeft);
  57529. if (menuBar != 0)
  57530. menuBar->setBounds (border, border + getTitleBarHeight(),
  57531. getWidth() - border * 2, menuBarHeight);
  57532. }
  57533. Button* DocumentWindow::getCloseButton() const throw()
  57534. {
  57535. return titleBarButtons[2];
  57536. }
  57537. Button* DocumentWindow::getMinimiseButton() const throw()
  57538. {
  57539. return titleBarButtons[0];
  57540. }
  57541. Button* DocumentWindow::getMaximiseButton() const throw()
  57542. {
  57543. return titleBarButtons[1];
  57544. }
  57545. int DocumentWindow::getDesktopWindowStyleFlags() const
  57546. {
  57547. int flags = ResizableWindow::getDesktopWindowStyleFlags();
  57548. if ((requiredButtons & minimiseButton) != 0)
  57549. flags |= ComponentPeer::windowHasMinimiseButton;
  57550. if ((requiredButtons & maximiseButton) != 0)
  57551. flags |= ComponentPeer::windowHasMaximiseButton;
  57552. if ((requiredButtons & closeButton) != 0)
  57553. flags |= ComponentPeer::windowHasCloseButton;
  57554. return flags;
  57555. }
  57556. void DocumentWindow::lookAndFeelChanged()
  57557. {
  57558. int i;
  57559. for (i = 0; i < 3; ++i)
  57560. deleteAndZero (titleBarButtons[i]);
  57561. if (! isUsingNativeTitleBar())
  57562. {
  57563. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  57564. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  57565. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  57566. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  57567. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  57568. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  57569. for (i = 0; i < 3; ++i)
  57570. {
  57571. if (titleBarButtons[i] != 0)
  57572. {
  57573. buttonListener.owner = this;
  57574. titleBarButtons[i]->addButtonListener (&buttonListener);
  57575. titleBarButtons[i]->setWantsKeyboardFocus (false);
  57576. // (call the Component method directly to avoid the assertion in ResizableWindow)
  57577. Component::addAndMakeVisible (titleBarButtons[i]);
  57578. }
  57579. }
  57580. if (getCloseButton() != 0)
  57581. {
  57582. #if JUCE_MAC
  57583. getCloseButton()->addShortcut (KeyPress (T('w'), ModifierKeys::commandModifier, 0));
  57584. #else
  57585. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  57586. #endif
  57587. }
  57588. }
  57589. activeWindowStatusChanged();
  57590. ResizableWindow::lookAndFeelChanged();
  57591. }
  57592. void DocumentWindow::parentHierarchyChanged()
  57593. {
  57594. lookAndFeelChanged();
  57595. }
  57596. void DocumentWindow::activeWindowStatusChanged()
  57597. {
  57598. ResizableWindow::activeWindowStatusChanged();
  57599. for (int i = 0; i < 3; ++i)
  57600. if (titleBarButtons[i] != 0)
  57601. titleBarButtons[i]->setEnabled (isActiveWindow());
  57602. if (menuBar != 0)
  57603. menuBar->setEnabled (isActiveWindow());
  57604. }
  57605. const BorderSize DocumentWindow::getBorderThickness()
  57606. {
  57607. return BorderSize (getBorderSize());
  57608. }
  57609. const BorderSize DocumentWindow::getContentComponentBorder()
  57610. {
  57611. const int size = getBorderSize();
  57612. return BorderSize (size
  57613. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  57614. + (menuBar != 0 ? menuBarHeight : 0),
  57615. size, size, size);
  57616. }
  57617. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  57618. {
  57619. const int border = getBorderSize();
  57620. if (e.x >= border
  57621. && e.y >= border
  57622. && e.x < getWidth() - border
  57623. && e.y < border + getTitleBarHeight()
  57624. && getMaximiseButton() != 0)
  57625. {
  57626. getMaximiseButton()->triggerClick();
  57627. }
  57628. }
  57629. void DocumentWindow::userTriedToCloseWindow()
  57630. {
  57631. closeButtonPressed();
  57632. }
  57633. int DocumentWindow::getTitleBarHeight() const
  57634. {
  57635. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  57636. }
  57637. int DocumentWindow::getBorderSize() const
  57638. {
  57639. return (isFullScreen() || isUsingNativeTitleBar()) ? 0 : (resizableBorder != 0 ? 4 : 1);
  57640. }
  57641. DocumentWindow::ButtonListenerProxy::ButtonListenerProxy()
  57642. {
  57643. }
  57644. void DocumentWindow::ButtonListenerProxy::buttonClicked (Button* button)
  57645. {
  57646. if (button == owner->getMinimiseButton())
  57647. {
  57648. owner->minimiseButtonPressed();
  57649. }
  57650. else if (button == owner->getMaximiseButton())
  57651. {
  57652. owner->maximiseButtonPressed();
  57653. }
  57654. else if (button == owner->getCloseButton())
  57655. {
  57656. owner->closeButtonPressed();
  57657. }
  57658. }
  57659. END_JUCE_NAMESPACE
  57660. /********* End of inlined file: juce_DocumentWindow.cpp *********/
  57661. /********* Start of inlined file: juce_ResizableWindow.cpp *********/
  57662. BEGIN_JUCE_NAMESPACE
  57663. ResizableWindow::ResizableWindow (const String& name,
  57664. const Colour& backgroundColour_,
  57665. const bool addToDesktop_)
  57666. : TopLevelWindow (name, addToDesktop_),
  57667. resizableCorner (0),
  57668. resizableBorder (0),
  57669. contentComponent (0),
  57670. resizeToFitContent (false),
  57671. fullscreen (false),
  57672. constrainer (0)
  57673. #ifdef JUCE_DEBUG
  57674. , hasBeenResized (false)
  57675. #endif
  57676. {
  57677. setBackgroundColour (backgroundColour_);
  57678. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  57679. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  57680. if (addToDesktop_)
  57681. Component::addToDesktop (getDesktopWindowStyleFlags());
  57682. }
  57683. ResizableWindow::~ResizableWindow()
  57684. {
  57685. deleteAndZero (resizableCorner);
  57686. deleteAndZero (resizableBorder);
  57687. deleteAndZero (contentComponent);
  57688. // have you been adding your own components directly to this window..? tut tut tut.
  57689. // Read the instructions for using a ResizableWindow!
  57690. jassert (getNumChildComponents() == 0);
  57691. }
  57692. int ResizableWindow::getDesktopWindowStyleFlags() const
  57693. {
  57694. int flags = TopLevelWindow::getDesktopWindowStyleFlags();
  57695. if (isResizable() && (flags & ComponentPeer::windowHasTitleBar) != 0)
  57696. flags |= ComponentPeer::windowIsResizable;
  57697. return flags;
  57698. }
  57699. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  57700. const bool deleteOldOne,
  57701. const bool resizeToFit)
  57702. {
  57703. resizeToFitContent = resizeToFit;
  57704. if (contentComponent != newContentComponent)
  57705. {
  57706. if (deleteOldOne)
  57707. delete contentComponent;
  57708. else
  57709. removeChildComponent (contentComponent);
  57710. contentComponent = newContentComponent;
  57711. Component::addAndMakeVisible (contentComponent);
  57712. }
  57713. if (resizeToFit)
  57714. childBoundsChanged (contentComponent);
  57715. resized(); // must always be called to position the new content comp
  57716. }
  57717. void ResizableWindow::setContentComponentSize (int width, int height)
  57718. {
  57719. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  57720. const BorderSize border (getContentComponentBorder());
  57721. setSize (width + border.getLeftAndRight(),
  57722. height + border.getTopAndBottom());
  57723. }
  57724. const BorderSize ResizableWindow::getBorderThickness()
  57725. {
  57726. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  57727. }
  57728. const BorderSize ResizableWindow::getContentComponentBorder()
  57729. {
  57730. return getBorderThickness();
  57731. }
  57732. void ResizableWindow::moved()
  57733. {
  57734. updateLastPos();
  57735. }
  57736. void ResizableWindow::visibilityChanged()
  57737. {
  57738. TopLevelWindow::visibilityChanged();
  57739. updateLastPos();
  57740. }
  57741. void ResizableWindow::resized()
  57742. {
  57743. if (resizableBorder != 0)
  57744. {
  57745. resizableBorder->setVisible (! isFullScreen());
  57746. resizableBorder->setBorderThickness (getBorderThickness());
  57747. resizableBorder->setSize (getWidth(), getHeight());
  57748. resizableBorder->toBack();
  57749. }
  57750. if (resizableCorner != 0)
  57751. {
  57752. resizableCorner->setVisible (! isFullScreen());
  57753. const int resizerSize = 18;
  57754. resizableCorner->setBounds (getWidth() - resizerSize,
  57755. getHeight() - resizerSize,
  57756. resizerSize, resizerSize);
  57757. }
  57758. if (contentComponent != 0)
  57759. contentComponent->setBoundsInset (getContentComponentBorder());
  57760. updateLastPos();
  57761. #ifdef JUCE_DEBUG
  57762. hasBeenResized = true;
  57763. #endif
  57764. }
  57765. void ResizableWindow::childBoundsChanged (Component* child)
  57766. {
  57767. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  57768. {
  57769. // not going to look very good if this component has a zero size..
  57770. jassert (child->getWidth() > 0);
  57771. jassert (child->getHeight() > 0);
  57772. const BorderSize borders (getContentComponentBorder());
  57773. setSize (child->getWidth() + borders.getLeftAndRight(),
  57774. child->getHeight() + borders.getTopAndBottom());
  57775. }
  57776. }
  57777. void ResizableWindow::activeWindowStatusChanged()
  57778. {
  57779. const BorderSize borders (getContentComponentBorder());
  57780. repaint (0, 0, getWidth(), borders.getTop());
  57781. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  57782. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  57783. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  57784. }
  57785. void ResizableWindow::setResizable (const bool shouldBeResizable,
  57786. const bool useBottomRightCornerResizer)
  57787. {
  57788. if (shouldBeResizable)
  57789. {
  57790. if (useBottomRightCornerResizer)
  57791. {
  57792. deleteAndZero (resizableBorder);
  57793. if (resizableCorner == 0)
  57794. {
  57795. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  57796. resizableCorner->setAlwaysOnTop (true);
  57797. }
  57798. }
  57799. else
  57800. {
  57801. deleteAndZero (resizableCorner);
  57802. if (resizableBorder == 0)
  57803. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  57804. }
  57805. }
  57806. else
  57807. {
  57808. deleteAndZero (resizableCorner);
  57809. deleteAndZero (resizableBorder);
  57810. }
  57811. if (isUsingNativeTitleBar())
  57812. recreateDesktopWindow();
  57813. childBoundsChanged (contentComponent);
  57814. resized();
  57815. }
  57816. bool ResizableWindow::isResizable() const throw()
  57817. {
  57818. return resizableCorner != 0
  57819. || resizableBorder != 0;
  57820. }
  57821. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  57822. const int newMinimumHeight,
  57823. const int newMaximumWidth,
  57824. const int newMaximumHeight) throw()
  57825. {
  57826. // if you've set up a custom constrainer then these settings won't have any effect..
  57827. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  57828. if (constrainer == 0)
  57829. setConstrainer (&defaultConstrainer);
  57830. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  57831. newMaximumWidth, newMaximumHeight);
  57832. setBoundsConstrained (getX(), getY(), getWidth(), getHeight());
  57833. }
  57834. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  57835. {
  57836. if (constrainer != newConstrainer)
  57837. {
  57838. constrainer = newConstrainer;
  57839. const bool useBottomRightCornerResizer = resizableCorner != 0;
  57840. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  57841. deleteAndZero (resizableCorner);
  57842. deleteAndZero (resizableBorder);
  57843. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  57844. ComponentPeer* const peer = getPeer();
  57845. if (peer != 0)
  57846. peer->setConstrainer (newConstrainer);
  57847. }
  57848. }
  57849. void ResizableWindow::setBoundsConstrained (int x, int y, int w, int h)
  57850. {
  57851. if (constrainer != 0)
  57852. constrainer->setBoundsForComponent (this, x, y, w, h, false, false, false, false);
  57853. else
  57854. setBounds (x, y, w, h);
  57855. }
  57856. void ResizableWindow::paint (Graphics& g)
  57857. {
  57858. g.fillAll (backgroundColour);
  57859. if (! isFullScreen())
  57860. {
  57861. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  57862. getBorderThickness(), *this);
  57863. }
  57864. #ifdef JUCE_DEBUG
  57865. /* If this fails, then you've probably written a subclass with a resized()
  57866. callback but forgotten to make it call its parent class's resized() method.
  57867. It's important when you override methods like resized(), moved(),
  57868. etc., that you make sure the base class methods also get called.
  57869. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  57870. because your content should all be inside the content component - and it's the
  57871. content component's resized() method that you should be using to do your
  57872. layout.
  57873. */
  57874. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  57875. #endif
  57876. }
  57877. void ResizableWindow::lookAndFeelChanged()
  57878. {
  57879. resized();
  57880. if (isOnDesktop())
  57881. {
  57882. Component::addToDesktop (getDesktopWindowStyleFlags());
  57883. ComponentPeer* const peer = getPeer();
  57884. if (peer != 0)
  57885. peer->setConstrainer (constrainer);
  57886. }
  57887. }
  57888. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  57889. {
  57890. if (Desktop::canUseSemiTransparentWindows())
  57891. backgroundColour = newColour;
  57892. else
  57893. backgroundColour = newColour.withAlpha (1.0f);
  57894. setOpaque (backgroundColour.isOpaque());
  57895. repaint();
  57896. }
  57897. bool ResizableWindow::isFullScreen() const
  57898. {
  57899. if (isOnDesktop())
  57900. {
  57901. ComponentPeer* const peer = getPeer();
  57902. return peer != 0 && peer->isFullScreen();
  57903. }
  57904. return fullscreen;
  57905. }
  57906. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  57907. {
  57908. if (shouldBeFullScreen != isFullScreen())
  57909. {
  57910. updateLastPos();
  57911. fullscreen = shouldBeFullScreen;
  57912. if (isOnDesktop())
  57913. {
  57914. ComponentPeer* const peer = getPeer();
  57915. if (peer != 0)
  57916. {
  57917. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  57918. const Rectangle lastPos (lastNonFullScreenPos);
  57919. peer->setFullScreen (shouldBeFullScreen);
  57920. if (! shouldBeFullScreen)
  57921. setBounds (lastPos);
  57922. }
  57923. else
  57924. {
  57925. jassertfalse
  57926. }
  57927. }
  57928. else
  57929. {
  57930. if (shouldBeFullScreen)
  57931. setBounds (0, 0, getParentWidth(), getParentHeight());
  57932. else
  57933. setBounds (lastNonFullScreenPos);
  57934. }
  57935. resized();
  57936. }
  57937. }
  57938. bool ResizableWindow::isMinimised() const
  57939. {
  57940. ComponentPeer* const peer = getPeer();
  57941. return (peer != 0) && peer->isMinimised();
  57942. }
  57943. void ResizableWindow::setMinimised (const bool shouldMinimise)
  57944. {
  57945. if (shouldMinimise != isMinimised())
  57946. {
  57947. ComponentPeer* const peer = getPeer();
  57948. if (peer != 0)
  57949. {
  57950. updateLastPos();
  57951. peer->setMinimised (shouldMinimise);
  57952. }
  57953. else
  57954. {
  57955. jassertfalse
  57956. }
  57957. }
  57958. }
  57959. void ResizableWindow::updateLastPos()
  57960. {
  57961. if (isShowing() && ! (isFullScreen() || isMinimised()))
  57962. {
  57963. lastNonFullScreenPos = getBounds();
  57964. }
  57965. }
  57966. void ResizableWindow::parentSizeChanged()
  57967. {
  57968. if (isFullScreen() && getParentComponent() != 0)
  57969. {
  57970. setBounds (0, 0, getParentWidth(), getParentHeight());
  57971. }
  57972. }
  57973. const String ResizableWindow::getWindowStateAsString()
  57974. {
  57975. updateLastPos();
  57976. String s;
  57977. if (isFullScreen())
  57978. s << "fs ";
  57979. s << lastNonFullScreenPos.getX() << T(' ')
  57980. << lastNonFullScreenPos.getY() << T(' ')
  57981. << lastNonFullScreenPos.getWidth() << T(' ')
  57982. << lastNonFullScreenPos.getHeight();
  57983. return s;
  57984. }
  57985. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  57986. {
  57987. StringArray tokens;
  57988. tokens.addTokens (s, false);
  57989. tokens.removeEmptyStrings();
  57990. tokens.trim();
  57991. const bool fs = tokens[0].startsWithIgnoreCase (T("fs"));
  57992. const int n = fs ? 1 : 0;
  57993. if (tokens.size() != 4 + n)
  57994. return false;
  57995. Rectangle r (tokens[n].getIntValue(),
  57996. tokens[n + 1].getIntValue(),
  57997. tokens[n + 2].getIntValue(),
  57998. tokens[n + 3].getIntValue());
  57999. if (r.isEmpty())
  58000. return false;
  58001. const Rectangle screen (Desktop::getInstance().getMonitorAreaContaining (r.getX(), r.getY()));
  58002. r = r.getIntersection (screen);
  58003. lastNonFullScreenPos = r;
  58004. if (isOnDesktop())
  58005. {
  58006. ComponentPeer* const peer = getPeer();
  58007. if (peer != 0)
  58008. peer->setNonFullScreenBounds (r);
  58009. }
  58010. setFullScreen (fs);
  58011. if (! fs)
  58012. setBoundsConstrained (r.getX(),
  58013. r.getY(),
  58014. r.getWidth(),
  58015. r.getHeight());
  58016. return true;
  58017. }
  58018. void ResizableWindow::mouseDown (const MouseEvent&)
  58019. {
  58020. if (! isFullScreen())
  58021. dragger.startDraggingComponent (this, constrainer);
  58022. }
  58023. void ResizableWindow::mouseDrag (const MouseEvent& e)
  58024. {
  58025. if (! isFullScreen())
  58026. dragger.dragComponent (this, e);
  58027. }
  58028. #ifdef JUCE_DEBUG
  58029. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  58030. {
  58031. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  58032. manages its child components automatically, and if you add your own it'll cause
  58033. trouble. Instead, use setContentComponent() to give it a component which
  58034. will be automatically resized and kept in the right place - then you can add
  58035. subcomponents to the content comp. See the notes for the ResizableWindow class
  58036. for more info.
  58037. If you really know what you're doing and want to avoid this assertion, just call
  58038. Component::addChildComponent directly.
  58039. */
  58040. jassertfalse
  58041. Component::addChildComponent (child, zOrder);
  58042. }
  58043. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  58044. {
  58045. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  58046. manages its child components automatically, and if you add your own it'll cause
  58047. trouble. Instead, use setContentComponent() to give it a component which
  58048. will be automatically resized and kept in the right place - then you can add
  58049. subcomponents to the content comp. See the notes for the ResizableWindow class
  58050. for more info.
  58051. If you really know what you're doing and want to avoid this assertion, just call
  58052. Component::addAndMakeVisible directly.
  58053. */
  58054. jassertfalse
  58055. Component::addAndMakeVisible (child, zOrder);
  58056. }
  58057. #endif
  58058. END_JUCE_NAMESPACE
  58059. /********* End of inlined file: juce_ResizableWindow.cpp *********/
  58060. /********* Start of inlined file: juce_SplashScreen.cpp *********/
  58061. BEGIN_JUCE_NAMESPACE
  58062. SplashScreen::SplashScreen()
  58063. : backgroundImage (0),
  58064. isImageInCache (false)
  58065. {
  58066. setOpaque (true);
  58067. }
  58068. SplashScreen::~SplashScreen()
  58069. {
  58070. if (isImageInCache)
  58071. ImageCache::release (backgroundImage);
  58072. else
  58073. delete backgroundImage;
  58074. }
  58075. void SplashScreen::show (const String& title,
  58076. Image* const backgroundImage_,
  58077. const int minimumTimeToDisplayFor,
  58078. const bool useDropShadow,
  58079. const bool removeOnMouseClick)
  58080. {
  58081. backgroundImage = backgroundImage_;
  58082. jassert (backgroundImage_ != 0);
  58083. if (backgroundImage_ != 0)
  58084. {
  58085. isImageInCache = ImageCache::isImageInCache (backgroundImage_);
  58086. setOpaque (! backgroundImage_->hasAlphaChannel());
  58087. show (title,
  58088. backgroundImage_->getWidth(),
  58089. backgroundImage_->getHeight(),
  58090. minimumTimeToDisplayFor,
  58091. useDropShadow,
  58092. removeOnMouseClick);
  58093. }
  58094. }
  58095. void SplashScreen::show (const String& title,
  58096. const int width,
  58097. const int height,
  58098. const int minimumTimeToDisplayFor,
  58099. const bool useDropShadow,
  58100. const bool removeOnMouseClick)
  58101. {
  58102. setName (title);
  58103. setAlwaysOnTop (true);
  58104. setVisible (true);
  58105. centreWithSize (width, height);
  58106. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  58107. toFront (false);
  58108. MessageManager::getInstance()->dispatchPendingMessages();
  58109. repaint();
  58110. originalClickCounter = removeOnMouseClick
  58111. ? Desktop::getMouseButtonClickCounter()
  58112. : INT_MAX;
  58113. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  58114. startTimer (50);
  58115. }
  58116. void SplashScreen::paint (Graphics& g)
  58117. {
  58118. if (backgroundImage != 0)
  58119. {
  58120. g.setOpacity (1.0f);
  58121. g.drawImage (backgroundImage,
  58122. 0, 0, getWidth(), getHeight(),
  58123. 0, 0, backgroundImage->getWidth(), backgroundImage->getHeight());
  58124. }
  58125. }
  58126. void SplashScreen::timerCallback()
  58127. {
  58128. if (Time::getCurrentTime() > earliestTimeToDelete
  58129. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  58130. {
  58131. delete this;
  58132. }
  58133. }
  58134. END_JUCE_NAMESPACE
  58135. /********* End of inlined file: juce_SplashScreen.cpp *********/
  58136. /********* Start of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  58137. BEGIN_JUCE_NAMESPACE
  58138. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  58139. const bool hasProgressBar,
  58140. const bool hasCancelButton,
  58141. const int timeOutMsWhenCancelling_,
  58142. const String& cancelButtonText)
  58143. : Thread ("Juce Progress Window"),
  58144. progress (0.0),
  58145. alertWindow (title, String::empty, AlertWindow::NoIcon),
  58146. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  58147. {
  58148. if (hasProgressBar)
  58149. alertWindow.addProgressBarComponent (progress);
  58150. if (hasCancelButton)
  58151. alertWindow.addButton (cancelButtonText, 1);
  58152. }
  58153. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  58154. {
  58155. stopThread (timeOutMsWhenCancelling);
  58156. }
  58157. bool ThreadWithProgressWindow::runThread (const int priority)
  58158. {
  58159. startThread (priority);
  58160. startTimer (100);
  58161. {
  58162. const ScopedLock sl (messageLock);
  58163. alertWindow.setMessage (message);
  58164. }
  58165. const bool wasCancelled = alertWindow.runModalLoop() != 0;
  58166. stopThread (timeOutMsWhenCancelling);
  58167. alertWindow.setVisible (false);
  58168. return ! wasCancelled;
  58169. }
  58170. void ThreadWithProgressWindow::setProgress (const double newProgress)
  58171. {
  58172. progress = newProgress;
  58173. }
  58174. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  58175. {
  58176. const ScopedLock sl (messageLock);
  58177. message = newStatusMessage;
  58178. }
  58179. void ThreadWithProgressWindow::timerCallback()
  58180. {
  58181. if (! isThreadRunning())
  58182. {
  58183. // thread has finished normally..
  58184. alertWindow.exitModalState (0);
  58185. alertWindow.setVisible (false);
  58186. }
  58187. else
  58188. {
  58189. const ScopedLock sl (messageLock);
  58190. alertWindow.setMessage (message);
  58191. }
  58192. }
  58193. END_JUCE_NAMESPACE
  58194. /********* End of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  58195. /********* Start of inlined file: juce_TooltipWindow.cpp *********/
  58196. BEGIN_JUCE_NAMESPACE
  58197. TooltipWindow::TooltipWindow (Component* const parentComponent,
  58198. const int millisecondsBeforeTipAppears_)
  58199. : Component ("tooltip"),
  58200. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  58201. mouseX (0),
  58202. mouseY (0),
  58203. lastMouseMoveTime (0),
  58204. lastHideTime (0),
  58205. lastComponentUnderMouse (0),
  58206. changedCompsSinceShown (true)
  58207. {
  58208. startTimer (123);
  58209. setAlwaysOnTop (true);
  58210. setOpaque (true);
  58211. if (parentComponent != 0)
  58212. {
  58213. parentComponent->addChildComponent (this);
  58214. }
  58215. else
  58216. {
  58217. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  58218. addToDesktop (ComponentPeer::windowHasDropShadow
  58219. | ComponentPeer::windowIsTemporary);
  58220. }
  58221. }
  58222. TooltipWindow::~TooltipWindow()
  58223. {
  58224. }
  58225. void TooltipWindow::paint (Graphics& g)
  58226. {
  58227. getLookAndFeel().drawTooltip (g, tip, getWidth(), getHeight());
  58228. }
  58229. void TooltipWindow::mouseEnter (const MouseEvent&)
  58230. {
  58231. setVisible (false);
  58232. }
  58233. void TooltipWindow::showFor (Component* const c)
  58234. {
  58235. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  58236. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  58237. tip = ttc->getTooltip();
  58238. else
  58239. tip = String::empty;
  58240. if (tip.isEmpty())
  58241. {
  58242. setVisible (false);
  58243. }
  58244. else
  58245. {
  58246. int mx, my;
  58247. Desktop::getMousePosition (mx, my);
  58248. if (getParentComponent() != 0)
  58249. getParentComponent()->globalPositionToRelative (mx, my);
  58250. int x, y, w, h;
  58251. getLookAndFeel().getTooltipSize (tip, w, h);
  58252. if (mx > getParentWidth() / 2)
  58253. x = mx - (w + 12);
  58254. else
  58255. x = mx + 24;
  58256. if (my > getParentHeight() / 2)
  58257. y = my - (h + 6);
  58258. else
  58259. y = my + 6;
  58260. setBounds (x, y, w, h);
  58261. setVisible (true);
  58262. toFront (false);
  58263. }
  58264. }
  58265. void TooltipWindow::timerCallback()
  58266. {
  58267. int mx, my;
  58268. Desktop::getMousePosition (mx, my);
  58269. const unsigned int now = Time::getApproximateMillisecondCounter();
  58270. Component* const underMouse = Component::getComponentUnderMouse();
  58271. const bool changedComp = (underMouse != lastComponentUnderMouse);
  58272. lastComponentUnderMouse = underMouse;
  58273. if (changedComp
  58274. || abs (mx - mouseX) > 4
  58275. || abs (my - mouseY) > 4
  58276. || Desktop::getInstance().getMouseButtonClickCounter() > mouseClicks)
  58277. {
  58278. lastMouseMoveTime = now;
  58279. if (isVisible())
  58280. {
  58281. lastHideTime = now;
  58282. setVisible (false);
  58283. }
  58284. changedCompsSinceShown = changedCompsSinceShown || changedComp;
  58285. tip = String::empty;
  58286. mouseX = mx;
  58287. mouseY = my;
  58288. }
  58289. if (changedCompsSinceShown)
  58290. {
  58291. if ((now > lastMouseMoveTime + millisecondsBeforeTipAppears
  58292. || now < lastHideTime + 500)
  58293. && ! isVisible())
  58294. {
  58295. if (underMouse->isValidComponent())
  58296. showFor (underMouse);
  58297. changedCompsSinceShown = false;
  58298. }
  58299. }
  58300. mouseClicks = Desktop::getInstance().getMouseButtonClickCounter();
  58301. }
  58302. END_JUCE_NAMESPACE
  58303. /********* End of inlined file: juce_TooltipWindow.cpp *********/
  58304. /********* Start of inlined file: juce_TopLevelWindow.cpp *********/
  58305. BEGIN_JUCE_NAMESPACE
  58306. /** Keeps track of the active top level window.
  58307. */
  58308. class TopLevelWindowManager : public Timer,
  58309. public DeletedAtShutdown
  58310. {
  58311. public:
  58312. TopLevelWindowManager()
  58313. : windows (8),
  58314. currentActive (0)
  58315. {
  58316. }
  58317. ~TopLevelWindowManager()
  58318. {
  58319. clearSingletonInstance();
  58320. }
  58321. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  58322. void timerCallback()
  58323. {
  58324. startTimer (1731);
  58325. TopLevelWindow* active = 0;
  58326. if (Process::isForegroundProcess())
  58327. {
  58328. active = currentActive;
  58329. Component* const c = Component::getCurrentlyFocusedComponent();
  58330. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  58331. if (tlw == 0 && c != 0)
  58332. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  58333. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  58334. if (tlw != 0)
  58335. active = tlw;
  58336. }
  58337. if (active != currentActive)
  58338. {
  58339. currentActive = active;
  58340. for (int i = windows.size(); --i >= 0;)
  58341. {
  58342. TopLevelWindow* const tlw = (TopLevelWindow*) windows.getUnchecked (i);
  58343. tlw->setWindowActive (isWindowActive (tlw));
  58344. i = jmin (i, windows.size() - 1);
  58345. }
  58346. Desktop::getInstance().triggerFocusCallback();
  58347. }
  58348. }
  58349. bool addWindow (TopLevelWindow* const w) throw()
  58350. {
  58351. windows.add (w);
  58352. startTimer (10);
  58353. return isWindowActive (w);
  58354. }
  58355. void removeWindow (TopLevelWindow* const w) throw()
  58356. {
  58357. startTimer (10);
  58358. if (currentActive == w)
  58359. currentActive = 0;
  58360. windows.removeValue (w);
  58361. if (windows.size() == 0)
  58362. deleteInstance();
  58363. }
  58364. VoidArray windows;
  58365. private:
  58366. TopLevelWindow* currentActive;
  58367. bool isWindowActive (TopLevelWindow* const tlw) const throw()
  58368. {
  58369. return (tlw == currentActive
  58370. || tlw->isParentOf (currentActive)
  58371. || tlw->hasKeyboardFocus (true))
  58372. && tlw->isShowing();
  58373. }
  58374. TopLevelWindowManager (const TopLevelWindowManager&);
  58375. const TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  58376. };
  58377. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  58378. void juce_CheckCurrentlyFocusedTopLevelWindow() throw()
  58379. {
  58380. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  58381. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  58382. }
  58383. TopLevelWindow::TopLevelWindow (const String& name,
  58384. const bool addToDesktop_)
  58385. : Component (name),
  58386. useDropShadow (true),
  58387. useNativeTitleBar (false),
  58388. windowIsActive_ (false),
  58389. shadower (0)
  58390. {
  58391. setOpaque (true);
  58392. if (addToDesktop_)
  58393. Component::addToDesktop (getDesktopWindowStyleFlags());
  58394. else
  58395. setDropShadowEnabled (true);
  58396. setWantsKeyboardFocus (true);
  58397. setBroughtToFrontOnMouseClick (true);
  58398. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  58399. }
  58400. TopLevelWindow::~TopLevelWindow()
  58401. {
  58402. deleteAndZero (shadower);
  58403. TopLevelWindowManager::getInstance()->removeWindow (this);
  58404. }
  58405. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  58406. {
  58407. if (hasKeyboardFocus (true))
  58408. TopLevelWindowManager::getInstance()->timerCallback();
  58409. else
  58410. TopLevelWindowManager::getInstance()->startTimer (10);
  58411. }
  58412. void TopLevelWindow::setWindowActive (const bool isNowActive) throw()
  58413. {
  58414. if (windowIsActive_ != isNowActive)
  58415. {
  58416. windowIsActive_ = isNowActive;
  58417. activeWindowStatusChanged();
  58418. }
  58419. }
  58420. void TopLevelWindow::activeWindowStatusChanged()
  58421. {
  58422. }
  58423. void TopLevelWindow::parentHierarchyChanged()
  58424. {
  58425. setDropShadowEnabled (useDropShadow);
  58426. }
  58427. void TopLevelWindow::visibilityChanged()
  58428. {
  58429. if (isShowing())
  58430. toFront (true);
  58431. }
  58432. int TopLevelWindow::getDesktopWindowStyleFlags() const
  58433. {
  58434. int flags = ComponentPeer::windowAppearsOnTaskbar;
  58435. if (useDropShadow)
  58436. flags |= ComponentPeer::windowHasDropShadow;
  58437. if (useNativeTitleBar)
  58438. flags |= ComponentPeer::windowHasTitleBar;
  58439. return flags;
  58440. }
  58441. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  58442. {
  58443. useDropShadow = useShadow;
  58444. if (isOnDesktop())
  58445. {
  58446. deleteAndZero (shadower);
  58447. Component::addToDesktop (getDesktopWindowStyleFlags());
  58448. }
  58449. else
  58450. {
  58451. if (useShadow && isOpaque())
  58452. {
  58453. if (shadower == 0)
  58454. {
  58455. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  58456. if (shadower != 0)
  58457. shadower->setOwner (this);
  58458. }
  58459. }
  58460. else
  58461. {
  58462. deleteAndZero (shadower);
  58463. }
  58464. }
  58465. }
  58466. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  58467. {
  58468. if (useNativeTitleBar != useNativeTitleBar_)
  58469. {
  58470. useNativeTitleBar = useNativeTitleBar_;
  58471. recreateDesktopWindow();
  58472. sendLookAndFeelChange();
  58473. }
  58474. }
  58475. void TopLevelWindow::recreateDesktopWindow()
  58476. {
  58477. if (isOnDesktop())
  58478. {
  58479. Component::addToDesktop (getDesktopWindowStyleFlags());
  58480. toFront (true);
  58481. }
  58482. }
  58483. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  58484. {
  58485. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  58486. because this class needs to make sure its layout corresponds with settings like whether
  58487. it's got a native title bar or not.
  58488. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  58489. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  58490. method, then add or remove whatever flags are necessary from this value before returning it.
  58491. */
  58492. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  58493. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  58494. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  58495. if (windowStyleFlags != getDesktopWindowStyleFlags())
  58496. sendLookAndFeelChange();
  58497. }
  58498. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  58499. {
  58500. if (c == 0)
  58501. c = TopLevelWindow::getActiveTopLevelWindow();
  58502. if (c == 0)
  58503. {
  58504. centreWithSize (width, height);
  58505. }
  58506. else
  58507. {
  58508. int x = (c->getWidth() - width) / 2;
  58509. int y = (c->getHeight() - height) / 2;
  58510. c->relativePositionToGlobal (x, y);
  58511. Rectangle parentArea (c->getParentMonitorArea());
  58512. if (getParentComponent() != 0)
  58513. {
  58514. getParentComponent()->globalPositionToRelative (x, y);
  58515. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  58516. }
  58517. parentArea.reduce (12, 12);
  58518. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), x),
  58519. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), y),
  58520. width, height);
  58521. }
  58522. }
  58523. int TopLevelWindow::getNumTopLevelWindows() throw()
  58524. {
  58525. return TopLevelWindowManager::getInstance()->windows.size();
  58526. }
  58527. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  58528. {
  58529. return (TopLevelWindow*) TopLevelWindowManager::getInstance()->windows [index];
  58530. }
  58531. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  58532. {
  58533. TopLevelWindow* best = 0;
  58534. int bestNumTWLParents = -1;
  58535. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  58536. {
  58537. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  58538. if (tlw->isActiveWindow())
  58539. {
  58540. int numTWLParents = 0;
  58541. const Component* c = tlw->getParentComponent();
  58542. while (c != 0)
  58543. {
  58544. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  58545. ++numTWLParents;
  58546. c = c->getParentComponent();
  58547. }
  58548. if (bestNumTWLParents < numTWLParents)
  58549. {
  58550. best = tlw;
  58551. bestNumTWLParents = numTWLParents;
  58552. }
  58553. }
  58554. }
  58555. return best;
  58556. }
  58557. END_JUCE_NAMESPACE
  58558. /********* End of inlined file: juce_TopLevelWindow.cpp *********/
  58559. /********* Start of inlined file: juce_Brush.cpp *********/
  58560. BEGIN_JUCE_NAMESPACE
  58561. Brush::Brush() throw()
  58562. {
  58563. }
  58564. Brush::~Brush() throw()
  58565. {
  58566. }
  58567. void Brush::paintVerticalLine (LowLevelGraphicsContext& context,
  58568. int x, float y1, float y2) throw()
  58569. {
  58570. Path p;
  58571. p.addRectangle ((float) x, y1, 1.0f, y2 - y1);
  58572. paintPath (context, p, AffineTransform::identity);
  58573. }
  58574. void Brush::paintHorizontalLine (LowLevelGraphicsContext& context,
  58575. int y, float x1, float x2) throw()
  58576. {
  58577. Path p;
  58578. p.addRectangle (x1, (float) y, x2 - x1, 1.0f);
  58579. paintPath (context, p, AffineTransform::identity);
  58580. }
  58581. void Brush::paintLine (LowLevelGraphicsContext& context,
  58582. float x1, float y1, float x2, float y2) throw()
  58583. {
  58584. Path p;
  58585. p.addLineSegment (x1, y1, x2, y2, 1.0f);
  58586. paintPath (context, p, AffineTransform::identity);
  58587. }
  58588. END_JUCE_NAMESPACE
  58589. /********* End of inlined file: juce_Brush.cpp *********/
  58590. /********* Start of inlined file: juce_GradientBrush.cpp *********/
  58591. BEGIN_JUCE_NAMESPACE
  58592. GradientBrush::GradientBrush (const Colour& colour1,
  58593. const float x1,
  58594. const float y1,
  58595. const Colour& colour2,
  58596. const float x2,
  58597. const float y2,
  58598. const bool isRadial) throw()
  58599. : gradient (colour1, x1, y1,
  58600. colour2, x2, y2,
  58601. isRadial)
  58602. {
  58603. }
  58604. GradientBrush::GradientBrush (const ColourGradient& gradient_) throw()
  58605. : gradient (gradient_)
  58606. {
  58607. }
  58608. GradientBrush::~GradientBrush() throw()
  58609. {
  58610. }
  58611. Brush* GradientBrush::createCopy() const throw()
  58612. {
  58613. return new GradientBrush (gradient);
  58614. }
  58615. void GradientBrush::applyTransform (const AffineTransform& transform) throw()
  58616. {
  58617. gradient.transform = gradient.transform.followedBy (transform);
  58618. }
  58619. void GradientBrush::multiplyOpacity (const float multiple) throw()
  58620. {
  58621. gradient.multiplyOpacity (multiple);
  58622. }
  58623. bool GradientBrush::isInvisible() const throw()
  58624. {
  58625. return gradient.isInvisible();
  58626. }
  58627. void GradientBrush::paintPath (LowLevelGraphicsContext& context,
  58628. const Path& path, const AffineTransform& transform) throw()
  58629. {
  58630. context.fillPathWithGradient (path, transform, gradient, EdgeTable::Oversampling_4times);
  58631. }
  58632. void GradientBrush::paintRectangle (LowLevelGraphicsContext& context,
  58633. int x, int y, int w, int h) throw()
  58634. {
  58635. context.fillRectWithGradient (x, y, w, h, gradient);
  58636. }
  58637. void GradientBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  58638. const Image& alphaChannelImage, int imageX, int imageY,
  58639. int x, int y, int w, int h) throw()
  58640. {
  58641. context.saveState();
  58642. if (context.reduceClipRegion (x, y, w, h))
  58643. context.fillAlphaChannelWithGradient (alphaChannelImage, imageX, imageY, gradient);
  58644. context.restoreState();
  58645. }
  58646. END_JUCE_NAMESPACE
  58647. /********* End of inlined file: juce_GradientBrush.cpp *********/
  58648. /********* Start of inlined file: juce_ImageBrush.cpp *********/
  58649. BEGIN_JUCE_NAMESPACE
  58650. ImageBrush::ImageBrush (Image* const image_,
  58651. const int anchorX_,
  58652. const int anchorY_,
  58653. const float opacity_) throw()
  58654. : image (image_),
  58655. anchorX (anchorX_),
  58656. anchorY (anchorY_),
  58657. opacity (opacity_)
  58658. {
  58659. jassert (image != 0); // not much point creating a brush without an image, is there?
  58660. if (image != 0)
  58661. {
  58662. if (image->getWidth() == 0 || image->getHeight() == 0)
  58663. {
  58664. jassertfalse // you've passed in an empty image - not exactly brilliant for tiling.
  58665. image = 0;
  58666. }
  58667. }
  58668. }
  58669. ImageBrush::~ImageBrush() throw()
  58670. {
  58671. }
  58672. Brush* ImageBrush::createCopy() const throw()
  58673. {
  58674. return new ImageBrush (image, anchorX, anchorY, opacity);
  58675. }
  58676. void ImageBrush::multiplyOpacity (const float multiple) throw()
  58677. {
  58678. opacity *= multiple;
  58679. }
  58680. bool ImageBrush::isInvisible() const throw()
  58681. {
  58682. return opacity == 0.0f;
  58683. }
  58684. void ImageBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  58685. {
  58686. //xxx should probably be smarter and warp the image
  58687. }
  58688. void ImageBrush::getStartXY (int& x, int& y) const throw()
  58689. {
  58690. x -= anchorX;
  58691. y -= anchorY;
  58692. const int iw = image->getWidth();
  58693. const int ih = image->getHeight();
  58694. if (x < 0)
  58695. x = ((x / iw) - 1) * iw;
  58696. else
  58697. x = (x / iw) * iw;
  58698. if (y < 0)
  58699. y = ((y / ih) - 1) * ih;
  58700. else
  58701. y = (y / ih) * ih;
  58702. x += anchorX;
  58703. y += anchorY;
  58704. }
  58705. void ImageBrush::paintRectangle (LowLevelGraphicsContext& context,
  58706. int x, int y, int w, int h) throw()
  58707. {
  58708. context.saveState();
  58709. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  58710. {
  58711. const int right = x + w;
  58712. const int bottom = y + h;
  58713. const int iw = image->getWidth();
  58714. const int ih = image->getHeight();
  58715. int startX = x;
  58716. getStartXY (startX, y);
  58717. while (y < bottom)
  58718. {
  58719. x = startX;
  58720. while (x < right)
  58721. {
  58722. context.blendImage (*image, x, y, iw, ih, 0, 0, opacity);
  58723. x += iw;
  58724. }
  58725. y += ih;
  58726. }
  58727. }
  58728. context.restoreState();
  58729. }
  58730. void ImageBrush::paintPath (LowLevelGraphicsContext& context,
  58731. const Path& path, const AffineTransform& transform) throw()
  58732. {
  58733. if (image != 0)
  58734. {
  58735. Rectangle clip (context.getClipBounds());
  58736. {
  58737. float x, y, w, h;
  58738. path.getBoundsTransformed (transform, x, y, w, h);
  58739. clip = clip.getIntersection (Rectangle ((int) floorf (x),
  58740. (int) floorf (y),
  58741. 2 + (int) floorf (w),
  58742. 2 + (int) floorf (h)));
  58743. }
  58744. int x = clip.getX();
  58745. int y = clip.getY();
  58746. const int right = clip.getRight();
  58747. const int bottom = clip.getBottom();
  58748. const int iw = image->getWidth();
  58749. const int ih = image->getHeight();
  58750. int startX = x;
  58751. getStartXY (startX, y);
  58752. while (y < bottom)
  58753. {
  58754. x = startX;
  58755. while (x < right)
  58756. {
  58757. context.fillPathWithImage (path, transform, *image, x, y, opacity, EdgeTable::Oversampling_4times);
  58758. x += iw;
  58759. }
  58760. y += ih;
  58761. }
  58762. }
  58763. }
  58764. void ImageBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  58765. const Image& alphaChannelImage, int imageX, int imageY,
  58766. int x, int y, int w, int h) throw()
  58767. {
  58768. context.saveState();
  58769. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  58770. {
  58771. const Rectangle clip (context.getClipBounds());
  58772. x = clip.getX();
  58773. y = clip.getY();
  58774. const int right = clip.getRight();
  58775. const int bottom = clip.getBottom();
  58776. const int iw = image->getWidth();
  58777. const int ih = image->getHeight();
  58778. int startX = x;
  58779. getStartXY (startX, y);
  58780. while (y < bottom)
  58781. {
  58782. x = startX;
  58783. while (x < right)
  58784. {
  58785. context.fillAlphaChannelWithImage (alphaChannelImage,
  58786. imageX, imageY, *image,
  58787. x, y, opacity);
  58788. x += iw;
  58789. }
  58790. y += ih;
  58791. }
  58792. }
  58793. context.restoreState();
  58794. }
  58795. END_JUCE_NAMESPACE
  58796. /********* End of inlined file: juce_ImageBrush.cpp *********/
  58797. /********* Start of inlined file: juce_SolidColourBrush.cpp *********/
  58798. BEGIN_JUCE_NAMESPACE
  58799. SolidColourBrush::SolidColourBrush() throw()
  58800. : colour (0xff000000)
  58801. {
  58802. }
  58803. SolidColourBrush::SolidColourBrush (const Colour& colour_) throw()
  58804. : colour (colour_)
  58805. {
  58806. }
  58807. SolidColourBrush::~SolidColourBrush() throw()
  58808. {
  58809. }
  58810. Brush* SolidColourBrush::createCopy() const throw()
  58811. {
  58812. return new SolidColourBrush (colour);
  58813. }
  58814. void SolidColourBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  58815. {
  58816. }
  58817. void SolidColourBrush::multiplyOpacity (const float multiple) throw()
  58818. {
  58819. colour = colour.withMultipliedAlpha (multiple);
  58820. }
  58821. bool SolidColourBrush::isInvisible() const throw()
  58822. {
  58823. return colour.isTransparent();
  58824. }
  58825. void SolidColourBrush::paintPath (LowLevelGraphicsContext& context,
  58826. const Path& path, const AffineTransform& transform) throw()
  58827. {
  58828. if (! colour.isTransparent())
  58829. context.fillPathWithColour (path, transform, colour, EdgeTable::Oversampling_4times);
  58830. }
  58831. void SolidColourBrush::paintRectangle (LowLevelGraphicsContext& context,
  58832. int x, int y, int w, int h) throw()
  58833. {
  58834. if (! colour.isTransparent())
  58835. context.fillRectWithColour (x, y, w, h, colour, false);
  58836. }
  58837. void SolidColourBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  58838. const Image& alphaChannelImage, int imageX, int imageY,
  58839. int x, int y, int w, int h) throw()
  58840. {
  58841. if (! colour.isTransparent())
  58842. {
  58843. context.saveState();
  58844. if (context.reduceClipRegion (x, y, w, h))
  58845. context.fillAlphaChannelWithColour (alphaChannelImage, imageX, imageY, colour);
  58846. context.restoreState();
  58847. }
  58848. }
  58849. void SolidColourBrush::paintVerticalLine (LowLevelGraphicsContext& context,
  58850. int x, float y1, float y2) throw()
  58851. {
  58852. context.drawVerticalLine (x, y1, y2, colour);
  58853. }
  58854. void SolidColourBrush::paintHorizontalLine (LowLevelGraphicsContext& context,
  58855. int y, float x1, float x2) throw()
  58856. {
  58857. context.drawHorizontalLine (y, x1, x2, colour);
  58858. }
  58859. void SolidColourBrush::paintLine (LowLevelGraphicsContext& context,
  58860. float x1, float y1, float x2, float y2) throw()
  58861. {
  58862. context.drawLine (x1, y1, x2, y2, colour);
  58863. }
  58864. END_JUCE_NAMESPACE
  58865. /********* End of inlined file: juce_SolidColourBrush.cpp *********/
  58866. /********* Start of inlined file: juce_Colour.cpp *********/
  58867. BEGIN_JUCE_NAMESPACE
  58868. static forcedinline uint8 floatAlphaToInt (const float alpha)
  58869. {
  58870. return (uint8) jlimit (0, 0xff, roundFloatToInt (alpha * 255.0f));
  58871. }
  58872. static const float oneOver255 = 1.0f / 255.0f;
  58873. Colour::Colour() throw()
  58874. : argb (0)
  58875. {
  58876. }
  58877. Colour::Colour (const Colour& other) throw()
  58878. : argb (other.argb)
  58879. {
  58880. }
  58881. const Colour& Colour::operator= (const Colour& other) throw()
  58882. {
  58883. argb = other.argb;
  58884. return *this;
  58885. }
  58886. bool Colour::operator== (const Colour& other) const throw()
  58887. {
  58888. return argb.getARGB() == other.argb.getARGB();
  58889. }
  58890. bool Colour::operator!= (const Colour& other) const throw()
  58891. {
  58892. return argb.getARGB() != other.argb.getARGB();
  58893. }
  58894. Colour::Colour (const uint32 argb_) throw()
  58895. : argb (argb_)
  58896. {
  58897. }
  58898. Colour::Colour (const uint8 red,
  58899. const uint8 green,
  58900. const uint8 blue) throw()
  58901. {
  58902. argb.setARGB (0xff, red, green, blue);
  58903. }
  58904. const Colour Colour::fromRGB (const uint8 red,
  58905. const uint8 green,
  58906. const uint8 blue) throw()
  58907. {
  58908. return Colour (red, green, blue);
  58909. }
  58910. Colour::Colour (const uint8 red,
  58911. const uint8 green,
  58912. const uint8 blue,
  58913. const uint8 alpha) throw()
  58914. {
  58915. argb.setARGB (alpha, red, green, blue);
  58916. }
  58917. const Colour Colour::fromRGBA (const uint8 red,
  58918. const uint8 green,
  58919. const uint8 blue,
  58920. const uint8 alpha) throw()
  58921. {
  58922. return Colour (red, green, blue, alpha);
  58923. }
  58924. Colour::Colour (const uint8 red,
  58925. const uint8 green,
  58926. const uint8 blue,
  58927. const float alpha) throw()
  58928. {
  58929. argb.setARGB (floatAlphaToInt (alpha), red, green, blue);
  58930. }
  58931. const Colour Colour::fromRGBAFloat (const uint8 red,
  58932. const uint8 green,
  58933. const uint8 blue,
  58934. const float alpha) throw()
  58935. {
  58936. return Colour (red, green, blue, alpha);
  58937. }
  58938. static void convertHSBtoRGB (float h, const float s, float v,
  58939. uint8& r, uint8& g, uint8& b) throw()
  58940. {
  58941. v *= 255.0f;
  58942. const uint8 intV = (uint8) roundFloatToInt (v);
  58943. if (s == 0)
  58944. {
  58945. r = intV;
  58946. g = intV;
  58947. b = intV;
  58948. }
  58949. else
  58950. {
  58951. h = (h - floorf (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  58952. const float f = h - floorf (h);
  58953. const uint8 x = (uint8) roundFloatToInt (v * (1.0f - s));
  58954. const float y = v * (1.0f - s * f);
  58955. const float z = v * (1.0f - (s * (1.0f - f)));
  58956. if (h < 1.0f)
  58957. {
  58958. r = intV;
  58959. g = (uint8) roundFloatToInt (z);
  58960. b = x;
  58961. }
  58962. else if (h < 2.0f)
  58963. {
  58964. r = (uint8) roundFloatToInt (y);
  58965. g = intV;
  58966. b = x;
  58967. }
  58968. else if (h < 3.0f)
  58969. {
  58970. r = x;
  58971. g = intV;
  58972. b = (uint8) roundFloatToInt (z);
  58973. }
  58974. else if (h < 4.0f)
  58975. {
  58976. r = x;
  58977. g = (uint8) roundFloatToInt (y);
  58978. b = intV;
  58979. }
  58980. else if (h < 5.0f)
  58981. {
  58982. r = (uint8) roundFloatToInt (z);
  58983. g = x;
  58984. b = intV;
  58985. }
  58986. else if (h < 6.0f)
  58987. {
  58988. r = intV;
  58989. g = x;
  58990. b = (uint8) roundFloatToInt (y);
  58991. }
  58992. else
  58993. {
  58994. r = 0;
  58995. g = 0;
  58996. b = 0;
  58997. }
  58998. }
  58999. }
  59000. Colour::Colour (const float hue,
  59001. const float saturation,
  59002. const float brightness,
  59003. const float alpha) throw()
  59004. {
  59005. uint8 r = getRed(), g = getGreen(), b = getBlue();
  59006. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  59007. argb.setARGB (floatAlphaToInt (alpha), r, g, b);
  59008. }
  59009. const Colour Colour::fromHSV (const float hue,
  59010. const float saturation,
  59011. const float brightness,
  59012. const float alpha) throw()
  59013. {
  59014. return Colour (hue, saturation, brightness, alpha);
  59015. }
  59016. Colour::Colour (const float hue,
  59017. const float saturation,
  59018. const float brightness,
  59019. const uint8 alpha) throw()
  59020. {
  59021. uint8 r = getRed(), g = getGreen(), b = getBlue();
  59022. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  59023. argb.setARGB (alpha, r, g, b);
  59024. }
  59025. Colour::~Colour() throw()
  59026. {
  59027. }
  59028. const PixelARGB Colour::getPixelARGB() const throw()
  59029. {
  59030. PixelARGB p (argb);
  59031. p.premultiply();
  59032. return p;
  59033. }
  59034. uint32 Colour::getARGB() const throw()
  59035. {
  59036. return argb.getARGB();
  59037. }
  59038. bool Colour::isTransparent() const throw()
  59039. {
  59040. return getAlpha() == 0;
  59041. }
  59042. bool Colour::isOpaque() const throw()
  59043. {
  59044. return getAlpha() == 0xff;
  59045. }
  59046. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  59047. {
  59048. PixelARGB newCol (argb);
  59049. newCol.setAlpha (newAlpha);
  59050. return Colour (newCol.getARGB());
  59051. }
  59052. const Colour Colour::withAlpha (const float newAlpha) const throw()
  59053. {
  59054. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  59055. PixelARGB newCol (argb);
  59056. newCol.setAlpha (floatAlphaToInt (newAlpha));
  59057. return Colour (newCol.getARGB());
  59058. }
  59059. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  59060. {
  59061. jassert (alphaMultiplier >= 0);
  59062. PixelARGB newCol (argb);
  59063. newCol.setAlpha ((uint8) jmin (0xff, roundFloatToInt (alphaMultiplier * newCol.getAlpha())));
  59064. return Colour (newCol.getARGB());
  59065. }
  59066. const Colour Colour::overlaidWith (const Colour& src) const throw()
  59067. {
  59068. const int destAlpha = getAlpha();
  59069. if (destAlpha > 0)
  59070. {
  59071. const int invA = 0xff - (int) src.getAlpha();
  59072. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  59073. if (resA > 0)
  59074. {
  59075. const int da = (invA * destAlpha) / resA;
  59076. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  59077. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  59078. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  59079. (uint8) resA);
  59080. }
  59081. return *this;
  59082. }
  59083. else
  59084. {
  59085. return src;
  59086. }
  59087. }
  59088. float Colour::getFloatRed() const throw()
  59089. {
  59090. return getRed() * oneOver255;
  59091. }
  59092. float Colour::getFloatGreen() const throw()
  59093. {
  59094. return getGreen() * oneOver255;
  59095. }
  59096. float Colour::getFloatBlue() const throw()
  59097. {
  59098. return getBlue() * oneOver255;
  59099. }
  59100. float Colour::getFloatAlpha() const throw()
  59101. {
  59102. return getAlpha() * oneOver255;
  59103. }
  59104. void Colour::getHSB (float& h, float& s, float& v) const throw()
  59105. {
  59106. const int r = getRed();
  59107. const int g = getGreen();
  59108. const int b = getBlue();
  59109. const int hi = jmax (r, g, b);
  59110. const int lo = jmin (r, g, b);
  59111. if (hi != 0)
  59112. {
  59113. s = (hi - lo) / (float) hi;
  59114. if (s != 0)
  59115. {
  59116. const float invDiff = 1.0f / (hi - lo);
  59117. const float red = (hi - r) * invDiff;
  59118. const float green = (hi - g) * invDiff;
  59119. const float blue = (hi - b) * invDiff;
  59120. if (r == hi)
  59121. h = blue - green;
  59122. else if (g == hi)
  59123. h = 2.0f + red - blue;
  59124. else
  59125. h = 4.0f + green - red;
  59126. h *= 1.0f / 6.0f;
  59127. if (h < 0)
  59128. ++h;
  59129. }
  59130. else
  59131. {
  59132. h = 0;
  59133. }
  59134. }
  59135. else
  59136. {
  59137. s = 0;
  59138. h = 0;
  59139. }
  59140. v = hi * oneOver255;
  59141. }
  59142. float Colour::getHue() const throw()
  59143. {
  59144. float h, s, b;
  59145. getHSB (h, s, b);
  59146. return h;
  59147. }
  59148. const Colour Colour::withHue (const float hue) const throw()
  59149. {
  59150. float h, s, b;
  59151. getHSB (h, s, b);
  59152. return Colour (hue, s, b, getAlpha());
  59153. }
  59154. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  59155. {
  59156. float h, s, b;
  59157. getHSB (h, s, b);
  59158. h += amountToRotate;
  59159. h -= floorf (h);
  59160. return Colour (h, s, b, getAlpha());
  59161. }
  59162. float Colour::getSaturation() const throw()
  59163. {
  59164. float h, s, b;
  59165. getHSB (h, s, b);
  59166. return s;
  59167. }
  59168. const Colour Colour::withSaturation (const float saturation) const throw()
  59169. {
  59170. float h, s, b;
  59171. getHSB (h, s, b);
  59172. return Colour (h, saturation, b, getAlpha());
  59173. }
  59174. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  59175. {
  59176. float h, s, b;
  59177. getHSB (h, s, b);
  59178. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  59179. }
  59180. float Colour::getBrightness() const throw()
  59181. {
  59182. float h, s, b;
  59183. getHSB (h, s, b);
  59184. return b;
  59185. }
  59186. const Colour Colour::withBrightness (const float brightness) const throw()
  59187. {
  59188. float h, s, b;
  59189. getHSB (h, s, b);
  59190. return Colour (h, s, brightness, getAlpha());
  59191. }
  59192. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  59193. {
  59194. float h, s, b;
  59195. getHSB (h, s, b);
  59196. b *= amount;
  59197. if (b > 1.0f)
  59198. b = 1.0f;
  59199. return Colour (h, s, b, getAlpha());
  59200. }
  59201. const Colour Colour::brighter (float amount) const throw()
  59202. {
  59203. amount = 1.0f / (1.0f + amount);
  59204. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  59205. (uint8) (255 - (amount * (255 - getGreen()))),
  59206. (uint8) (255 - (amount * (255 - getBlue()))),
  59207. getAlpha());
  59208. }
  59209. const Colour Colour::darker (float amount) const throw()
  59210. {
  59211. amount = 1.0f / (1.0f + amount);
  59212. return Colour ((uint8) (amount * getRed()),
  59213. (uint8) (amount * getGreen()),
  59214. (uint8) (amount * getBlue()),
  59215. getAlpha());
  59216. }
  59217. const Colour Colour::greyLevel (const float brightness) throw()
  59218. {
  59219. const uint8 level
  59220. = (uint8) jlimit (0x00, 0xff, roundFloatToInt (brightness * 255.0f));
  59221. return Colour (level, level, level);
  59222. }
  59223. const Colour Colour::contrasting (const float amount) const throw()
  59224. {
  59225. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  59226. ? Colours::black
  59227. : Colours::white).withAlpha (amount));
  59228. }
  59229. const Colour Colour::contrasting (const Colour& colour1,
  59230. const Colour& colour2) throw()
  59231. {
  59232. const float b1 = colour1.getBrightness();
  59233. const float b2 = colour2.getBrightness();
  59234. float best = 0.0f;
  59235. float bestDist = 0.0f;
  59236. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  59237. {
  59238. const float d1 = fabsf (i - b1);
  59239. const float d2 = fabsf (i - b2);
  59240. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  59241. if (dist > bestDist)
  59242. {
  59243. best = i;
  59244. bestDist = dist;
  59245. }
  59246. }
  59247. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  59248. .withBrightness (best);
  59249. }
  59250. const String Colour::toString() const throw()
  59251. {
  59252. return String::toHexString ((int) argb.getARGB());
  59253. }
  59254. const Colour Colour::fromString (const String& encodedColourString)
  59255. {
  59256. return Colour ((uint32) encodedColourString.getHexValue32());
  59257. }
  59258. END_JUCE_NAMESPACE
  59259. /********* End of inlined file: juce_Colour.cpp *********/
  59260. /********* Start of inlined file: juce_ColourGradient.cpp *********/
  59261. BEGIN_JUCE_NAMESPACE
  59262. ColourGradient::ColourGradient() throw()
  59263. : colours (4)
  59264. {
  59265. #ifdef JUCE_DEBUG
  59266. x1 = 987654.0f;
  59267. #endif
  59268. }
  59269. ColourGradient::ColourGradient (const Colour& colour1,
  59270. const float x1_,
  59271. const float y1_,
  59272. const Colour& colour2,
  59273. const float x2_,
  59274. const float y2_,
  59275. const bool isRadial_) throw()
  59276. : x1 (x1_),
  59277. y1 (y1_),
  59278. x2 (x2_),
  59279. y2 (y2_),
  59280. isRadial (isRadial_),
  59281. colours (4)
  59282. {
  59283. colours.add (0);
  59284. colours.add (colour1.getPixelARGB().getARGB());
  59285. colours.add (1 << 16);
  59286. colours.add (colour2.getPixelARGB().getARGB());
  59287. }
  59288. ColourGradient::~ColourGradient() throw()
  59289. {
  59290. }
  59291. void ColourGradient::clearColours() throw()
  59292. {
  59293. colours.clear();
  59294. }
  59295. void ColourGradient::addColour (const double proportionAlongGradient,
  59296. const Colour& colour) throw()
  59297. {
  59298. // must be within the two end-points
  59299. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  59300. const uint32 pos = jlimit (0, 65535, roundDoubleToInt (proportionAlongGradient * 65536.0));
  59301. int i;
  59302. for (i = 0; i < colours.size(); i += 2)
  59303. if (colours.getUnchecked(i) > pos)
  59304. break;
  59305. colours.insert (i, pos);
  59306. colours.insert (i + 1, colour.getPixelARGB().getARGB());
  59307. }
  59308. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  59309. {
  59310. for (int i = 1; i < colours.size(); i += 2)
  59311. {
  59312. PixelARGB pix (colours.getUnchecked(i));
  59313. pix.multiplyAlpha (multiplier);
  59314. colours.set (i, pix.getARGB());
  59315. }
  59316. }
  59317. int ColourGradient::getNumColours() const throw()
  59318. {
  59319. return colours.size() >> 1;
  59320. }
  59321. double ColourGradient::getColourPosition (const int index) const throw()
  59322. {
  59323. return colours [index << 1];
  59324. }
  59325. const Colour ColourGradient::getColour (const int index) const throw()
  59326. {
  59327. PixelARGB pix (colours [(index << 1) + 1]);
  59328. pix.unpremultiply();
  59329. return Colour (pix.getARGB());
  59330. }
  59331. PixelARGB* ColourGradient::createLookupTable (int& numEntries) const throw()
  59332. {
  59333. #ifdef JUCE_DEBUG
  59334. // trying to use the object without setting its co-ordinates? Have a careful read of
  59335. // the comments for the constructors.
  59336. jassert (x1 != 987654.0f);
  59337. #endif
  59338. const int numColours = colours.size() >> 1;
  59339. float tx1 = x1, ty1 = y1, tx2 = x2, ty2 = y2;
  59340. transform.transformPoint (tx1, ty1);
  59341. transform.transformPoint (tx2, ty2);
  59342. const double distance = juce_hypot (tx1 - tx2, ty1 - ty2);
  59343. numEntries = jlimit (1, (numColours - 1) << 8, 3 * (int) distance);
  59344. PixelARGB* const lookupTable = (PixelARGB*) juce_calloc (numEntries * sizeof (PixelARGB));
  59345. if (numColours >= 2)
  59346. {
  59347. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  59348. PixelARGB pix1 (colours.getUnchecked (1));
  59349. int index = 0;
  59350. for (int j = 2; j < colours.size(); j += 2)
  59351. {
  59352. const int numToDo = ((colours.getUnchecked (j) * numEntries) >> 16) - index;
  59353. const PixelARGB pix2 (colours.getUnchecked (j + 1));
  59354. for (int i = 0; i < numToDo; ++i)
  59355. {
  59356. jassert (index >= 0 && index < numEntries);
  59357. lookupTable[index] = pix1;
  59358. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  59359. ++index;
  59360. }
  59361. pix1 = pix2;
  59362. }
  59363. while (index < numEntries)
  59364. lookupTable [index++] = pix1;
  59365. }
  59366. else
  59367. {
  59368. jassertfalse // no colours specified!
  59369. }
  59370. return lookupTable;
  59371. }
  59372. bool ColourGradient::isOpaque() const throw()
  59373. {
  59374. for (int i = 1; i < colours.size(); i += 2)
  59375. if (PixelARGB (colours.getUnchecked(i)).getAlpha() < 0xff)
  59376. return false;
  59377. return true;
  59378. }
  59379. bool ColourGradient::isInvisible() const throw()
  59380. {
  59381. for (int i = 1; i < colours.size(); i += 2)
  59382. if (PixelARGB (colours.getUnchecked(i)).getAlpha() > 0)
  59383. return false;
  59384. return true;
  59385. }
  59386. END_JUCE_NAMESPACE
  59387. /********* End of inlined file: juce_ColourGradient.cpp *********/
  59388. /********* Start of inlined file: juce_Colours.cpp *********/
  59389. BEGIN_JUCE_NAMESPACE
  59390. const Colour Colours::transparentBlack (0);
  59391. const Colour Colours::transparentWhite (0x00ffffff);
  59392. const Colour Colours::aliceblue (0xfff0f8ff);
  59393. const Colour Colours::antiquewhite (0xfffaebd7);
  59394. const Colour Colours::aqua (0xff00ffff);
  59395. const Colour Colours::aquamarine (0xff7fffd4);
  59396. const Colour Colours::azure (0xfff0ffff);
  59397. const Colour Colours::beige (0xfff5f5dc);
  59398. const Colour Colours::bisque (0xffffe4c4);
  59399. const Colour Colours::black (0xff000000);
  59400. const Colour Colours::blanchedalmond (0xffffebcd);
  59401. const Colour Colours::blue (0xff0000ff);
  59402. const Colour Colours::blueviolet (0xff8a2be2);
  59403. const Colour Colours::brown (0xffa52a2a);
  59404. const Colour Colours::burlywood (0xffdeb887);
  59405. const Colour Colours::cadetblue (0xff5f9ea0);
  59406. const Colour Colours::chartreuse (0xff7fff00);
  59407. const Colour Colours::chocolate (0xffd2691e);
  59408. const Colour Colours::coral (0xffff7f50);
  59409. const Colour Colours::cornflowerblue (0xff6495ed);
  59410. const Colour Colours::cornsilk (0xfffff8dc);
  59411. const Colour Colours::crimson (0xffdc143c);
  59412. const Colour Colours::cyan (0xff00ffff);
  59413. const Colour Colours::darkblue (0xff00008b);
  59414. const Colour Colours::darkcyan (0xff008b8b);
  59415. const Colour Colours::darkgoldenrod (0xffb8860b);
  59416. const Colour Colours::darkgrey (0xff555555);
  59417. const Colour Colours::darkgreen (0xff006400);
  59418. const Colour Colours::darkkhaki (0xffbdb76b);
  59419. const Colour Colours::darkmagenta (0xff8b008b);
  59420. const Colour Colours::darkolivegreen (0xff556b2f);
  59421. const Colour Colours::darkorange (0xffff8c00);
  59422. const Colour Colours::darkorchid (0xff9932cc);
  59423. const Colour Colours::darkred (0xff8b0000);
  59424. const Colour Colours::darksalmon (0xffe9967a);
  59425. const Colour Colours::darkseagreen (0xff8fbc8f);
  59426. const Colour Colours::darkslateblue (0xff483d8b);
  59427. const Colour Colours::darkslategrey (0xff2f4f4f);
  59428. const Colour Colours::darkturquoise (0xff00ced1);
  59429. const Colour Colours::darkviolet (0xff9400d3);
  59430. const Colour Colours::deeppink (0xffff1493);
  59431. const Colour Colours::deepskyblue (0xff00bfff);
  59432. const Colour Colours::dimgrey (0xff696969);
  59433. const Colour Colours::dodgerblue (0xff1e90ff);
  59434. const Colour Colours::firebrick (0xffb22222);
  59435. const Colour Colours::floralwhite (0xfffffaf0);
  59436. const Colour Colours::forestgreen (0xff228b22);
  59437. const Colour Colours::fuchsia (0xffff00ff);
  59438. const Colour Colours::gainsboro (0xffdcdcdc);
  59439. const Colour Colours::gold (0xffffd700);
  59440. const Colour Colours::goldenrod (0xffdaa520);
  59441. const Colour Colours::grey (0xff808080);
  59442. const Colour Colours::green (0xff008000);
  59443. const Colour Colours::greenyellow (0xffadff2f);
  59444. const Colour Colours::honeydew (0xfff0fff0);
  59445. const Colour Colours::hotpink (0xffff69b4);
  59446. const Colour Colours::indianred (0xffcd5c5c);
  59447. const Colour Colours::indigo (0xff4b0082);
  59448. const Colour Colours::ivory (0xfffffff0);
  59449. const Colour Colours::khaki (0xfff0e68c);
  59450. const Colour Colours::lavender (0xffe6e6fa);
  59451. const Colour Colours::lavenderblush (0xfffff0f5);
  59452. const Colour Colours::lemonchiffon (0xfffffacd);
  59453. const Colour Colours::lightblue (0xffadd8e6);
  59454. const Colour Colours::lightcoral (0xfff08080);
  59455. const Colour Colours::lightcyan (0xffe0ffff);
  59456. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  59457. const Colour Colours::lightgreen (0xff90ee90);
  59458. const Colour Colours::lightgrey (0xffd3d3d3);
  59459. const Colour Colours::lightpink (0xffffb6c1);
  59460. const Colour Colours::lightsalmon (0xffffa07a);
  59461. const Colour Colours::lightseagreen (0xff20b2aa);
  59462. const Colour Colours::lightskyblue (0xff87cefa);
  59463. const Colour Colours::lightslategrey (0xff778899);
  59464. const Colour Colours::lightsteelblue (0xffb0c4de);
  59465. const Colour Colours::lightyellow (0xffffffe0);
  59466. const Colour Colours::lime (0xff00ff00);
  59467. const Colour Colours::limegreen (0xff32cd32);
  59468. const Colour Colours::linen (0xfffaf0e6);
  59469. const Colour Colours::magenta (0xffff00ff);
  59470. const Colour Colours::maroon (0xff800000);
  59471. const Colour Colours::mediumaquamarine (0xff66cdaa);
  59472. const Colour Colours::mediumblue (0xff0000cd);
  59473. const Colour Colours::mediumorchid (0xffba55d3);
  59474. const Colour Colours::mediumpurple (0xff9370db);
  59475. const Colour Colours::mediumseagreen (0xff3cb371);
  59476. const Colour Colours::mediumslateblue (0xff7b68ee);
  59477. const Colour Colours::mediumspringgreen (0xff00fa9a);
  59478. const Colour Colours::mediumturquoise (0xff48d1cc);
  59479. const Colour Colours::mediumvioletred (0xffc71585);
  59480. const Colour Colours::midnightblue (0xff191970);
  59481. const Colour Colours::mintcream (0xfff5fffa);
  59482. const Colour Colours::mistyrose (0xffffe4e1);
  59483. const Colour Colours::navajowhite (0xffffdead);
  59484. const Colour Colours::navy (0xff000080);
  59485. const Colour Colours::oldlace (0xfffdf5e6);
  59486. const Colour Colours::olive (0xff808000);
  59487. const Colour Colours::olivedrab (0xff6b8e23);
  59488. const Colour Colours::orange (0xffffa500);
  59489. const Colour Colours::orangered (0xffff4500);
  59490. const Colour Colours::orchid (0xffda70d6);
  59491. const Colour Colours::palegoldenrod (0xffeee8aa);
  59492. const Colour Colours::palegreen (0xff98fb98);
  59493. const Colour Colours::paleturquoise (0xffafeeee);
  59494. const Colour Colours::palevioletred (0xffdb7093);
  59495. const Colour Colours::papayawhip (0xffffefd5);
  59496. const Colour Colours::peachpuff (0xffffdab9);
  59497. const Colour Colours::peru (0xffcd853f);
  59498. const Colour Colours::pink (0xffffc0cb);
  59499. const Colour Colours::plum (0xffdda0dd);
  59500. const Colour Colours::powderblue (0xffb0e0e6);
  59501. const Colour Colours::purple (0xff800080);
  59502. const Colour Colours::red (0xffff0000);
  59503. const Colour Colours::rosybrown (0xffbc8f8f);
  59504. const Colour Colours::royalblue (0xff4169e1);
  59505. const Colour Colours::saddlebrown (0xff8b4513);
  59506. const Colour Colours::salmon (0xfffa8072);
  59507. const Colour Colours::sandybrown (0xfff4a460);
  59508. const Colour Colours::seagreen (0xff2e8b57);
  59509. const Colour Colours::seashell (0xfffff5ee);
  59510. const Colour Colours::sienna (0xffa0522d);
  59511. const Colour Colours::silver (0xffc0c0c0);
  59512. const Colour Colours::skyblue (0xff87ceeb);
  59513. const Colour Colours::slateblue (0xff6a5acd);
  59514. const Colour Colours::slategrey (0xff708090);
  59515. const Colour Colours::snow (0xfffffafa);
  59516. const Colour Colours::springgreen (0xff00ff7f);
  59517. const Colour Colours::steelblue (0xff4682b4);
  59518. const Colour Colours::tan (0xffd2b48c);
  59519. const Colour Colours::teal (0xff008080);
  59520. const Colour Colours::thistle (0xffd8bfd8);
  59521. const Colour Colours::tomato (0xffff6347);
  59522. const Colour Colours::turquoise (0xff40e0d0);
  59523. const Colour Colours::violet (0xffee82ee);
  59524. const Colour Colours::wheat (0xfff5deb3);
  59525. const Colour Colours::white (0xffffffff);
  59526. const Colour Colours::whitesmoke (0xfff5f5f5);
  59527. const Colour Colours::yellow (0xffffff00);
  59528. const Colour Colours::yellowgreen (0xff9acd32);
  59529. const Colour Colours::findColourForName (const String& colourName,
  59530. const Colour& defaultColour)
  59531. {
  59532. static const int presets[] =
  59533. {
  59534. // (first value is the string's hashcode, second is ARGB)
  59535. 0x05978fff, 0xff000000, /* black */
  59536. 0x06bdcc29, 0xffffffff, /* white */
  59537. 0x002e305a, 0xff0000ff, /* blue */
  59538. 0x00308adf, 0xff808080, /* grey */
  59539. 0x05e0cf03, 0xff008000, /* green */
  59540. 0x0001b891, 0xffff0000, /* red */
  59541. 0xd43c6474, 0xffffff00, /* yellow */
  59542. 0x620886da, 0xfff0f8ff, /* aliceblue */
  59543. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  59544. 0x002dcebc, 0xff00ffff, /* aqua */
  59545. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  59546. 0x0590228f, 0xfff0ffff, /* azure */
  59547. 0x05947fe4, 0xfff5f5dc, /* beige */
  59548. 0xad388e35, 0xffffe4c4, /* bisque */
  59549. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  59550. 0x39129959, 0xff8a2be2, /* blueviolet */
  59551. 0x059a8136, 0xffa52a2a, /* brown */
  59552. 0x89cea8f9, 0xffdeb887, /* burlywood */
  59553. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  59554. 0x6b748956, 0xff7fff00, /* chartreuse */
  59555. 0x2903623c, 0xffd2691e, /* chocolate */
  59556. 0x05a74431, 0xffff7f50, /* coral */
  59557. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  59558. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  59559. 0x3d8c4edf, 0xffdc143c, /* crimson */
  59560. 0x002ed323, 0xff00ffff, /* cyan */
  59561. 0x67cc74d0, 0xff00008b, /* darkblue */
  59562. 0x67cd1799, 0xff008b8b, /* darkcyan */
  59563. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  59564. 0x67cecf55, 0xff555555, /* darkgrey */
  59565. 0x920b194d, 0xff006400, /* darkgreen */
  59566. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  59567. 0x5c293873, 0xff8b008b, /* darkmagenta */
  59568. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  59569. 0xbcfd2524, 0xffff8c00, /* darkorange */
  59570. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  59571. 0x55ee0d5b, 0xff8b0000, /* darkred */
  59572. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  59573. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  59574. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  59575. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  59576. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  59577. 0xc8769375, 0xff9400d3, /* darkviolet */
  59578. 0x25832862, 0xffff1493, /* deeppink */
  59579. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  59580. 0x634c8b67, 0xff696969, /* dimgrey */
  59581. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  59582. 0xef19e3cb, 0xffb22222, /* firebrick */
  59583. 0xb852b195, 0xfffffaf0, /* floralwhite */
  59584. 0xd086fd06, 0xff228b22, /* forestgreen */
  59585. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  59586. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  59587. 0x00308060, 0xffffd700, /* gold */
  59588. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  59589. 0xbab8a537, 0xffadff2f, /* greenyellow */
  59590. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  59591. 0x41892743, 0xffff69b4, /* hotpink */
  59592. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  59593. 0xb969fed2, 0xff4b0082, /* indigo */
  59594. 0x05fef6a9, 0xfffffff0, /* ivory */
  59595. 0x06149302, 0xfff0e68c, /* khaki */
  59596. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  59597. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  59598. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  59599. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  59600. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  59601. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  59602. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  59603. 0xf40157ad, 0xff90ee90, /* lightgreen */
  59604. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  59605. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  59606. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  59607. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  59608. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  59609. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  59610. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  59611. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  59612. 0x0032afd5, 0xff00ff00, /* lime */
  59613. 0x607bbc4e, 0xff32cd32, /* limegreen */
  59614. 0x06234efa, 0xfffaf0e6, /* linen */
  59615. 0x316858a9, 0xffff00ff, /* magenta */
  59616. 0xbf8ca470, 0xff800000, /* maroon */
  59617. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  59618. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  59619. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  59620. 0x07556b71, 0xff9370db, /* mediumpurple */
  59621. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  59622. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  59623. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  59624. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  59625. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  59626. 0x168eb32a, 0xff191970, /* midnightblue */
  59627. 0x4306b960, 0xfff5fffa, /* mintcream */
  59628. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  59629. 0xe97218a6, 0xffffdead, /* navajowhite */
  59630. 0x00337bb6, 0xff000080, /* navy */
  59631. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  59632. 0x064ee1db, 0xff808000, /* olive */
  59633. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  59634. 0xc3de262e, 0xffffa500, /* orange */
  59635. 0x58bebba3, 0xffff4500, /* orangered */
  59636. 0xc3def8a3, 0xffda70d6, /* orchid */
  59637. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  59638. 0x3d9dd619, 0xff98fb98, /* palegreen */
  59639. 0x74022737, 0xffafeeee, /* paleturquoise */
  59640. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  59641. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  59642. 0x93e1b776, 0xffffdab9, /* peachpuff */
  59643. 0x003472f8, 0xffcd853f, /* peru */
  59644. 0x00348176, 0xffffc0cb, /* pink */
  59645. 0x00348d94, 0xffdda0dd, /* plum */
  59646. 0xd036be93, 0xffb0e0e6, /* powderblue */
  59647. 0xc5c507bc, 0xff800080, /* purple */
  59648. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  59649. 0xbd9413e1, 0xff4169e1, /* royalblue */
  59650. 0xf456044f, 0xff8b4513, /* saddlebrown */
  59651. 0xc9c6f66e, 0xfffa8072, /* salmon */
  59652. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  59653. 0x34636c14, 0xff2e8b57, /* seagreen */
  59654. 0x3507fb41, 0xfffff5ee, /* seashell */
  59655. 0xca348772, 0xffa0522d, /* sienna */
  59656. 0xca37d30d, 0xffc0c0c0, /* silver */
  59657. 0x80da74fb, 0xff87ceeb, /* skyblue */
  59658. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  59659. 0x44ab37f8, 0xff708090, /* slategrey */
  59660. 0x0035f183, 0xfffffafa, /* snow */
  59661. 0xd5440d16, 0xff00ff7f, /* springgreen */
  59662. 0x3e1524a5, 0xff4682b4, /* steelblue */
  59663. 0x0001bfa1, 0xffd2b48c, /* tan */
  59664. 0x0036425c, 0xff008080, /* teal */
  59665. 0xafc8858f, 0xffd8bfd8, /* thistle */
  59666. 0xcc41600a, 0xffff6347, /* tomato */
  59667. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  59668. 0xcf57947f, 0xffee82ee, /* violet */
  59669. 0x06bdbae7, 0xfff5deb3, /* wheat */
  59670. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  59671. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  59672. };
  59673. const int hash = colourName.trim().toLowerCase().hashCode();
  59674. for (int i = 0; i < numElementsInArray (presets); i += 2)
  59675. if (presets [i] == hash)
  59676. return Colour (presets [i + 1]);
  59677. return defaultColour;
  59678. }
  59679. END_JUCE_NAMESPACE
  59680. /********* End of inlined file: juce_Colours.cpp *********/
  59681. /********* Start of inlined file: juce_EdgeTable.cpp *********/
  59682. BEGIN_JUCE_NAMESPACE
  59683. EdgeTable::EdgeTable (const int top_,
  59684. const int height_,
  59685. const OversamplingLevel oversampling_,
  59686. const int expectedEdgesPerLine) throw()
  59687. : top (top_),
  59688. height (height_),
  59689. maxEdgesPerLine (expectedEdgesPerLine),
  59690. lineStrideElements ((expectedEdgesPerLine << 1) + 1),
  59691. oversampling (oversampling_)
  59692. {
  59693. table = (int*) juce_calloc ((height << (int)oversampling_)
  59694. * lineStrideElements * sizeof (int));
  59695. }
  59696. EdgeTable::EdgeTable (const EdgeTable& other) throw()
  59697. : table (0)
  59698. {
  59699. operator= (other);
  59700. }
  59701. const EdgeTable& EdgeTable::operator= (const EdgeTable& other) throw()
  59702. {
  59703. juce_free (table);
  59704. top = other.top;
  59705. height = other.height;
  59706. maxEdgesPerLine = other.maxEdgesPerLine;
  59707. lineStrideElements = other.lineStrideElements;
  59708. oversampling = other.oversampling;
  59709. const int tableSize = (height << (int)oversampling)
  59710. * lineStrideElements * sizeof (int);
  59711. table = (int*) juce_malloc (tableSize);
  59712. memcpy (table, other.table, tableSize);
  59713. return *this;
  59714. }
  59715. EdgeTable::~EdgeTable() throw()
  59716. {
  59717. juce_free (table);
  59718. }
  59719. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  59720. {
  59721. if (newNumEdgesPerLine != maxEdgesPerLine)
  59722. {
  59723. maxEdgesPerLine = newNumEdgesPerLine;
  59724. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  59725. int* const newTable = (int*) juce_malloc ((height << (int) oversampling)
  59726. * newLineStrideElements * sizeof (int));
  59727. for (int i = 0; i < (height << (int) oversampling); ++i)
  59728. {
  59729. const int* srcLine = table + lineStrideElements * i;
  59730. int* dstLine = newTable + newLineStrideElements * i;
  59731. int num = *srcLine++;
  59732. *dstLine++ = num;
  59733. num <<= 1;
  59734. while (--num >= 0)
  59735. *dstLine++ = *srcLine++;
  59736. }
  59737. juce_free (table);
  59738. table = newTable;
  59739. lineStrideElements = newLineStrideElements;
  59740. }
  59741. }
  59742. void EdgeTable::optimiseTable() throw()
  59743. {
  59744. int maxLineElements = 0;
  59745. for (int i = height; --i >= 0;)
  59746. maxLineElements = jmax (maxLineElements,
  59747. table [i * lineStrideElements]);
  59748. remapTableForNumEdges (maxLineElements);
  59749. }
  59750. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  59751. {
  59752. jassert (y >= 0 && y < (height << oversampling))
  59753. int* lineStart = table + lineStrideElements * y;
  59754. int n = lineStart[0];
  59755. if (n >= maxEdgesPerLine)
  59756. {
  59757. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  59758. lineStart = table + lineStrideElements * y;
  59759. }
  59760. n <<= 1;
  59761. int* const line = lineStart + 1;
  59762. while (n > 0)
  59763. {
  59764. const int cx = line [n - 2];
  59765. if (cx <= x)
  59766. break;
  59767. line [n] = cx;
  59768. line [n + 1] = line [n - 1];
  59769. n -= 2;
  59770. }
  59771. line [n] = x;
  59772. line [n + 1] = winding;
  59773. lineStart[0]++;
  59774. }
  59775. void EdgeTable::addPath (const Path& path,
  59776. const AffineTransform& transform) throw()
  59777. {
  59778. const int windingAmount = 256 / (1 << (int) oversampling);
  59779. const float timesOversampling = (float) (1 << (int) oversampling);
  59780. const int bottomLimit = (height << (int) oversampling);
  59781. PathFlatteningIterator iter (path, transform);
  59782. while (iter.next())
  59783. {
  59784. int y1 = roundFloatToInt (iter.y1 * timesOversampling) - (top << (int) oversampling);
  59785. int y2 = roundFloatToInt (iter.y2 * timesOversampling) - (top << (int) oversampling);
  59786. if (y1 != y2)
  59787. {
  59788. const double x1 = 256.0 * iter.x1;
  59789. const double x2 = 256.0 * iter.x2;
  59790. const double multiplier = (x2 - x1) / (y2 - y1);
  59791. const int oldY1 = y1;
  59792. int winding;
  59793. if (y1 > y2)
  59794. {
  59795. swapVariables (y1, y2);
  59796. winding = windingAmount;
  59797. }
  59798. else
  59799. {
  59800. winding = -windingAmount;
  59801. }
  59802. jassert (y1 < y2);
  59803. if (y1 < 0)
  59804. y1 = 0;
  59805. if (y2 > bottomLimit)
  59806. y2 = bottomLimit;
  59807. while (y1 < y2)
  59808. {
  59809. addEdgePoint (roundDoubleToInt (x1 + multiplier * (y1 - oldY1)),
  59810. y1,
  59811. winding);
  59812. ++y1;
  59813. }
  59814. }
  59815. }
  59816. if (! path.isUsingNonZeroWinding())
  59817. {
  59818. // if it's an alternate-winding path, we need to go through and
  59819. // make sure all the windings are alternating.
  59820. int* lineStart = table;
  59821. for (int i = height << (int) oversampling; --i >= 0;)
  59822. {
  59823. int* line = lineStart;
  59824. lineStart += lineStrideElements;
  59825. int num = *line;
  59826. while (--num >= 0)
  59827. {
  59828. line += 2;
  59829. *line = abs (*line);
  59830. if (--num >= 0)
  59831. {
  59832. line += 2;
  59833. *line = -abs (*line);
  59834. }
  59835. }
  59836. }
  59837. }
  59838. }
  59839. END_JUCE_NAMESPACE
  59840. /********* End of inlined file: juce_EdgeTable.cpp *********/
  59841. /********* Start of inlined file: juce_Graphics.cpp *********/
  59842. BEGIN_JUCE_NAMESPACE
  59843. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  59844. #define MINIMUM_COORD -0x3fffffff
  59845. #define MAXIMUM_COORD 0x3fffffff
  59846. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  59847. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  59848. jassert ((int) x >= MINIMUM_COORD \
  59849. && (int) x <= MAXIMUM_COORD \
  59850. && (int) y >= MINIMUM_COORD \
  59851. && (int) y <= MAXIMUM_COORD \
  59852. && (int) w >= MINIMUM_COORD \
  59853. && (int) w <= MAXIMUM_COORD \
  59854. && (int) h >= MINIMUM_COORD \
  59855. && (int) h <= MAXIMUM_COORD);
  59856. LowLevelGraphicsContext::LowLevelGraphicsContext()
  59857. {
  59858. }
  59859. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  59860. {
  59861. }
  59862. Graphics::Graphics (Image& imageToDrawOnto) throw()
  59863. : context (imageToDrawOnto.createLowLevelContext()),
  59864. ownsContext (true),
  59865. state (new GraphicsState()),
  59866. saveStatePending (false)
  59867. {
  59868. }
  59869. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  59870. : context (internalContext),
  59871. ownsContext (false),
  59872. state (new GraphicsState()),
  59873. saveStatePending (false)
  59874. {
  59875. }
  59876. Graphics::~Graphics() throw()
  59877. {
  59878. delete state;
  59879. if (ownsContext)
  59880. delete context;
  59881. }
  59882. void Graphics::resetToDefaultState() throw()
  59883. {
  59884. setColour (Colours::black);
  59885. state->font.resetToDefaultState();
  59886. state->quality = defaultQuality;
  59887. }
  59888. bool Graphics::isVectorDevice() const throw()
  59889. {
  59890. return context->isVectorDevice();
  59891. }
  59892. bool Graphics::reduceClipRegion (const int x, const int y,
  59893. const int w, const int h) throw()
  59894. {
  59895. saveStateIfPending();
  59896. return context->reduceClipRegion (x, y, w, h);
  59897. }
  59898. bool Graphics::reduceClipRegion (const RectangleList& clipRegion) throw()
  59899. {
  59900. saveStateIfPending();
  59901. return context->reduceClipRegion (clipRegion);
  59902. }
  59903. void Graphics::excludeClipRegion (const int x, const int y,
  59904. const int w, const int h) throw()
  59905. {
  59906. saveStateIfPending();
  59907. context->excludeClipRegion (x, y, w, h);
  59908. }
  59909. bool Graphics::isClipEmpty() const throw()
  59910. {
  59911. return context->isClipEmpty();
  59912. }
  59913. const Rectangle Graphics::getClipBounds() const throw()
  59914. {
  59915. return context->getClipBounds();
  59916. }
  59917. void Graphics::saveState() throw()
  59918. {
  59919. saveStateIfPending();
  59920. saveStatePending = true;
  59921. }
  59922. void Graphics::restoreState() throw()
  59923. {
  59924. if (saveStatePending)
  59925. {
  59926. saveStatePending = false;
  59927. }
  59928. else
  59929. {
  59930. const int stackSize = stateStack.size();
  59931. if (stackSize > 0)
  59932. {
  59933. context->restoreState();
  59934. delete state;
  59935. state = stateStack.getUnchecked (stackSize - 1);
  59936. stateStack.removeLast (1, false);
  59937. }
  59938. else
  59939. {
  59940. // Trying to call restoreState() more times than you've called saveState() !
  59941. // Be careful to correctly match each saveState() with exactly one call to restoreState().
  59942. jassertfalse
  59943. }
  59944. }
  59945. }
  59946. void Graphics::saveStateIfPending() throw()
  59947. {
  59948. if (saveStatePending)
  59949. {
  59950. saveStatePending = false;
  59951. context->saveState();
  59952. stateStack.add (new GraphicsState (*state));
  59953. }
  59954. }
  59955. void Graphics::setOrigin (const int newOriginX,
  59956. const int newOriginY) throw()
  59957. {
  59958. saveStateIfPending();
  59959. context->setOrigin (newOriginX, newOriginY);
  59960. }
  59961. bool Graphics::clipRegionIntersects (const int x, const int y,
  59962. const int w, const int h) const throw()
  59963. {
  59964. return context->clipRegionIntersects (x, y, w, h);
  59965. }
  59966. void Graphics::setColour (const Colour& newColour) throw()
  59967. {
  59968. saveStateIfPending();
  59969. state->colour = newColour;
  59970. deleteAndZero (state->brush);
  59971. }
  59972. const Colour& Graphics::getCurrentColour() const throw()
  59973. {
  59974. return state->colour;
  59975. }
  59976. void Graphics::setOpacity (const float newOpacity) throw()
  59977. {
  59978. saveStateIfPending();
  59979. state->colour = state->colour.withAlpha (newOpacity);
  59980. }
  59981. void Graphics::setBrush (const Brush* const newBrush) throw()
  59982. {
  59983. saveStateIfPending();
  59984. delete state->brush;
  59985. if (newBrush != 0)
  59986. state->brush = newBrush->createCopy();
  59987. else
  59988. state->brush = 0;
  59989. }
  59990. Graphics::GraphicsState::GraphicsState() throw()
  59991. : colour (Colours::black),
  59992. brush (0),
  59993. quality (defaultQuality)
  59994. {
  59995. }
  59996. Graphics::GraphicsState::GraphicsState (const GraphicsState& other) throw()
  59997. : colour (other.colour),
  59998. brush (other.brush != 0 ? other.brush->createCopy() : 0),
  59999. font (other.font),
  60000. quality (other.quality)
  60001. {
  60002. }
  60003. Graphics::GraphicsState::~GraphicsState() throw()
  60004. {
  60005. delete brush;
  60006. }
  60007. void Graphics::setFont (const Font& newFont) throw()
  60008. {
  60009. saveStateIfPending();
  60010. state->font = newFont;
  60011. }
  60012. void Graphics::setFont (const float newFontHeight,
  60013. const int newFontStyleFlags) throw()
  60014. {
  60015. saveStateIfPending();
  60016. state->font.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0.0f);
  60017. }
  60018. const Font& Graphics::getCurrentFont() const throw()
  60019. {
  60020. return state->font;
  60021. }
  60022. void Graphics::drawSingleLineText (const String& text,
  60023. const int startX,
  60024. const int baselineY) const throw()
  60025. {
  60026. if (text.isNotEmpty()
  60027. && startX < context->getClipBounds().getRight())
  60028. {
  60029. GlyphArrangement arr;
  60030. arr.addLineOfText (state->font, text, (float) startX, (float) baselineY);
  60031. arr.draw (*this);
  60032. }
  60033. }
  60034. void Graphics::drawTextAsPath (const String& text,
  60035. const AffineTransform& transform) const throw()
  60036. {
  60037. if (text.isNotEmpty())
  60038. {
  60039. GlyphArrangement arr;
  60040. arr.addLineOfText (state->font, text, 0.0f, 0.0f);
  60041. arr.draw (*this, transform);
  60042. }
  60043. }
  60044. void Graphics::drawMultiLineText (const String& text,
  60045. const int startX,
  60046. const int baselineY,
  60047. const int maximumLineWidth) const throw()
  60048. {
  60049. if (text.isNotEmpty()
  60050. && startX < context->getClipBounds().getRight())
  60051. {
  60052. GlyphArrangement arr;
  60053. arr.addJustifiedText (state->font, text,
  60054. (float) startX, (float) baselineY, (float) maximumLineWidth,
  60055. Justification::left);
  60056. arr.draw (*this);
  60057. }
  60058. }
  60059. void Graphics::drawText (const String& text,
  60060. const int x,
  60061. const int y,
  60062. const int width,
  60063. const int height,
  60064. const Justification& justificationType,
  60065. const bool useEllipsesIfTooBig) const throw()
  60066. {
  60067. if (text.isNotEmpty() && context->clipRegionIntersects (x, y, width, height))
  60068. {
  60069. GlyphArrangement arr;
  60070. arr.addCurtailedLineOfText (state->font, text,
  60071. 0.0f, 0.0f, (float)width,
  60072. useEllipsesIfTooBig);
  60073. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  60074. (float) x, (float) y,
  60075. (float) width, (float) height,
  60076. justificationType);
  60077. arr.draw (*this);
  60078. }
  60079. }
  60080. void Graphics::drawFittedText (const String& text,
  60081. const int x,
  60082. const int y,
  60083. const int width,
  60084. const int height,
  60085. const Justification& justification,
  60086. const int maximumNumberOfLines,
  60087. const float minimumHorizontalScale) const throw()
  60088. {
  60089. if (text.isNotEmpty()
  60090. && width > 0 && height > 0
  60091. && context->clipRegionIntersects (x, y, width, height))
  60092. {
  60093. GlyphArrangement arr;
  60094. arr.addFittedText (state->font, text,
  60095. (float) x, (float) y,
  60096. (float) width, (float) height,
  60097. justification,
  60098. maximumNumberOfLines,
  60099. minimumHorizontalScale);
  60100. arr.draw (*this);
  60101. }
  60102. }
  60103. void Graphics::fillRect (int x,
  60104. int y,
  60105. int width,
  60106. int height) const throw()
  60107. {
  60108. // passing in a silly number can cause maths problems in rendering!
  60109. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60110. SolidColourBrush colourBrush (state->colour);
  60111. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, width, height);
  60112. }
  60113. void Graphics::fillRect (const Rectangle& r) const throw()
  60114. {
  60115. fillRect (r.getX(),
  60116. r.getY(),
  60117. r.getWidth(),
  60118. r.getHeight());
  60119. }
  60120. void Graphics::fillRect (const float x,
  60121. const float y,
  60122. const float width,
  60123. const float height) const throw()
  60124. {
  60125. // passing in a silly number can cause maths problems in rendering!
  60126. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60127. Path p;
  60128. p.addRectangle (x, y, width, height);
  60129. fillPath (p);
  60130. }
  60131. void Graphics::setPixel (int x, int y) const throw()
  60132. {
  60133. if (context->clipRegionIntersects (x, y, 1, 1))
  60134. {
  60135. SolidColourBrush colourBrush (state->colour);
  60136. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, 1, 1);
  60137. }
  60138. }
  60139. void Graphics::fillAll() const throw()
  60140. {
  60141. fillRect (context->getClipBounds());
  60142. }
  60143. void Graphics::fillAll (const Colour& colourToUse) const throw()
  60144. {
  60145. if (! colourToUse.isTransparent())
  60146. {
  60147. const Rectangle clip (context->getClipBounds());
  60148. context->fillRectWithColour (clip.getX(), clip.getY(), clip.getWidth(), clip.getHeight(),
  60149. colourToUse, false);
  60150. }
  60151. }
  60152. void Graphics::fillPath (const Path& path,
  60153. const AffineTransform& transform) const throw()
  60154. {
  60155. if ((! context->isClipEmpty()) && ! path.isEmpty())
  60156. {
  60157. SolidColourBrush colourBrush (state->colour);
  60158. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintPath (*context, path, transform);
  60159. }
  60160. }
  60161. void Graphics::strokePath (const Path& path,
  60162. const PathStrokeType& strokeType,
  60163. const AffineTransform& transform) const throw()
  60164. {
  60165. if (! state->colour.isTransparent())
  60166. {
  60167. Path stroke;
  60168. strokeType.createStrokedPath (stroke, path, transform);
  60169. fillPath (stroke);
  60170. }
  60171. }
  60172. void Graphics::drawRect (const int x,
  60173. const int y,
  60174. const int width,
  60175. const int height,
  60176. const int lineThickness) const throw()
  60177. {
  60178. // passing in a silly number can cause maths problems in rendering!
  60179. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60180. SolidColourBrush colourBrush (state->colour);
  60181. Brush& b = (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush);
  60182. b.paintRectangle (*context, x, y, width, lineThickness);
  60183. b.paintRectangle (*context, x, y + lineThickness, lineThickness, height - lineThickness * 2);
  60184. b.paintRectangle (*context, x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2);
  60185. b.paintRectangle (*context, x, y + height - lineThickness, width, lineThickness);
  60186. }
  60187. void Graphics::drawRect (const float x,
  60188. const float y,
  60189. const float width,
  60190. const float height,
  60191. const float lineThickness) const throw()
  60192. {
  60193. // passing in a silly number can cause maths problems in rendering!
  60194. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60195. Path p;
  60196. p.addRectangle (x, y, width, lineThickness);
  60197. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  60198. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  60199. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  60200. fillPath (p);
  60201. }
  60202. void Graphics::drawRect (const Rectangle& r,
  60203. const int lineThickness) const throw()
  60204. {
  60205. drawRect (r.getX(), r.getY(),
  60206. r.getWidth(), r.getHeight(),
  60207. lineThickness);
  60208. }
  60209. void Graphics::drawBevel (const int x,
  60210. const int y,
  60211. const int width,
  60212. const int height,
  60213. const int bevelThickness,
  60214. const Colour& topLeftColour,
  60215. const Colour& bottomRightColour,
  60216. const bool useGradient) const throw()
  60217. {
  60218. // passing in a silly number can cause maths problems in rendering!
  60219. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60220. if (clipRegionIntersects (x, y, width, height))
  60221. {
  60222. const float oldOpacity = state->colour.getFloatAlpha();
  60223. const float ramp = oldOpacity / bevelThickness;
  60224. for (int i = bevelThickness; --i >= 0;)
  60225. {
  60226. const float op = useGradient ? ramp * (bevelThickness - i)
  60227. : oldOpacity;
  60228. context->fillRectWithColour (x + i, y + i, width - i * 2, 1, topLeftColour.withMultipliedAlpha (op), false);
  60229. context->fillRectWithColour (x + i, y + i + 1, 1, height - i * 2 - 2, topLeftColour.withMultipliedAlpha (op * 0.75f), false);
  60230. context->fillRectWithColour (x + i, y + height - i - 1, width - i * 2, 1, bottomRightColour.withMultipliedAlpha (op), false);
  60231. context->fillRectWithColour (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2, bottomRightColour.withMultipliedAlpha (op * 0.75f), false);
  60232. }
  60233. }
  60234. }
  60235. void Graphics::fillEllipse (const float x,
  60236. const float y,
  60237. const float width,
  60238. const float height) const throw()
  60239. {
  60240. // passing in a silly number can cause maths problems in rendering!
  60241. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60242. Path p;
  60243. p.addEllipse (x, y, width, height);
  60244. fillPath (p);
  60245. }
  60246. void Graphics::drawEllipse (const float x,
  60247. const float y,
  60248. const float width,
  60249. const float height,
  60250. const float lineThickness) const throw()
  60251. {
  60252. // passing in a silly number can cause maths problems in rendering!
  60253. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60254. Path p;
  60255. p.addEllipse (x, y, width, height);
  60256. strokePath (p, PathStrokeType (lineThickness));
  60257. }
  60258. void Graphics::fillRoundedRectangle (const float x,
  60259. const float y,
  60260. const float width,
  60261. const float height,
  60262. const float cornerSize) const throw()
  60263. {
  60264. // passing in a silly number can cause maths problems in rendering!
  60265. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60266. Path p;
  60267. p.addRoundedRectangle (x, y, width, height, cornerSize);
  60268. fillPath (p);
  60269. }
  60270. void Graphics::fillRoundedRectangle (const Rectangle& r,
  60271. const float cornerSize) const throw()
  60272. {
  60273. fillRoundedRectangle ((float) r.getX(),
  60274. (float) r.getY(),
  60275. (float) r.getWidth(),
  60276. (float) r.getHeight(),
  60277. cornerSize);
  60278. }
  60279. void Graphics::drawRoundedRectangle (const float x,
  60280. const float y,
  60281. const float width,
  60282. const float height,
  60283. const float cornerSize,
  60284. const float lineThickness) const throw()
  60285. {
  60286. // passing in a silly number can cause maths problems in rendering!
  60287. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60288. Path p;
  60289. p.addRoundedRectangle (x, y, width, height, cornerSize);
  60290. strokePath (p, PathStrokeType (lineThickness));
  60291. }
  60292. void Graphics::drawRoundedRectangle (const Rectangle& r,
  60293. const float cornerSize,
  60294. const float lineThickness) const throw()
  60295. {
  60296. drawRoundedRectangle ((float) r.getX(),
  60297. (float) r.getY(),
  60298. (float) r.getWidth(),
  60299. (float) r.getHeight(),
  60300. cornerSize, lineThickness);
  60301. }
  60302. void Graphics::drawArrow (const float startX,
  60303. const float startY,
  60304. const float endX,
  60305. const float endY,
  60306. const float lineThickness,
  60307. const float arrowheadWidth,
  60308. const float arrowheadLength) const throw()
  60309. {
  60310. Path p;
  60311. p.addArrow (startX, startY, endX, endY,
  60312. lineThickness, arrowheadWidth, arrowheadLength);
  60313. fillPath (p);
  60314. }
  60315. void Graphics::fillCheckerBoard (int x, int y,
  60316. int width, int height,
  60317. const int checkWidth,
  60318. const int checkHeight,
  60319. const Colour& colour1,
  60320. const Colour& colour2) const throw()
  60321. {
  60322. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  60323. if (checkWidth > 0 && checkHeight > 0)
  60324. {
  60325. if (colour1 == colour2)
  60326. {
  60327. context->fillRectWithColour (x, y, width, height, colour1, false);
  60328. }
  60329. else
  60330. {
  60331. const Rectangle clip (context->getClipBounds());
  60332. const int right = jmin (x + width, clip.getRight());
  60333. const int bottom = jmin (y + height, clip.getBottom());
  60334. int cy = 0;
  60335. while (y < bottom)
  60336. {
  60337. int cx = cy;
  60338. for (int xx = x; xx < right; xx += checkWidth)
  60339. context->fillRectWithColour (xx, y,
  60340. jmin (checkWidth, right - xx),
  60341. jmin (checkHeight, bottom - y),
  60342. ((cx++ & 1) == 0) ? colour1 : colour2,
  60343. false);
  60344. ++cy;
  60345. y += checkHeight;
  60346. }
  60347. }
  60348. }
  60349. }
  60350. void Graphics::drawVerticalLine (const int x, float top, float bottom) const throw()
  60351. {
  60352. SolidColourBrush colourBrush (state->colour);
  60353. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintVerticalLine (*context, x, top, bottom);
  60354. }
  60355. void Graphics::drawHorizontalLine (const int y, float left, float right) const throw()
  60356. {
  60357. SolidColourBrush colourBrush (state->colour);
  60358. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintHorizontalLine (*context, y, left, right);
  60359. }
  60360. void Graphics::drawLine (float x1, float y1,
  60361. float x2, float y2) const throw()
  60362. {
  60363. if (! context->isClipEmpty())
  60364. {
  60365. SolidColourBrush colourBrush (state->colour);
  60366. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintLine (*context, x1, y1, x2, y2);
  60367. }
  60368. }
  60369. void Graphics::drawLine (const float startX,
  60370. const float startY,
  60371. const float endX,
  60372. const float endY,
  60373. const float lineThickness) const throw()
  60374. {
  60375. Path p;
  60376. p.addLineSegment (startX, startY, endX, endY, lineThickness);
  60377. fillPath (p);
  60378. }
  60379. void Graphics::drawLine (const Line& line) const throw()
  60380. {
  60381. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  60382. }
  60383. void Graphics::drawLine (const Line& line,
  60384. const float lineThickness) const throw()
  60385. {
  60386. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), lineThickness);
  60387. }
  60388. void Graphics::drawDashedLine (const float startX,
  60389. const float startY,
  60390. const float endX,
  60391. const float endY,
  60392. const float* const dashLengths,
  60393. const int numDashLengths,
  60394. const float lineThickness) const throw()
  60395. {
  60396. const double dx = endX - startX;
  60397. const double dy = endY - startY;
  60398. const double totalLen = juce_hypot (dx, dy);
  60399. if (totalLen >= 0.5)
  60400. {
  60401. const double onePixAlpha = 1.0 / totalLen;
  60402. double alpha = 0.0;
  60403. float x = startX;
  60404. float y = startY;
  60405. int n = 0;
  60406. while (alpha < 1.0f)
  60407. {
  60408. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  60409. n = n % numDashLengths;
  60410. const float oldX = x;
  60411. const float oldY = y;
  60412. x = (float) (startX + dx * alpha);
  60413. y = (float) (startY + dy * alpha);
  60414. if ((n & 1) != 0)
  60415. {
  60416. if (lineThickness != 1.0f)
  60417. drawLine (oldX, oldY, x, y, lineThickness);
  60418. else
  60419. drawLine (oldX, oldY, x, y);
  60420. }
  60421. }
  60422. }
  60423. }
  60424. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality) throw()
  60425. {
  60426. saveStateIfPending();
  60427. state->quality = newQuality;
  60428. }
  60429. void Graphics::drawImageAt (const Image* const imageToDraw,
  60430. const int topLeftX,
  60431. const int topLeftY,
  60432. const bool fillAlphaChannelWithCurrentBrush) const throw()
  60433. {
  60434. if (imageToDraw != 0)
  60435. {
  60436. const int imageW = imageToDraw->getWidth();
  60437. const int imageH = imageToDraw->getHeight();
  60438. drawImage (imageToDraw,
  60439. topLeftX, topLeftY, imageW, imageH,
  60440. 0, 0, imageW, imageH,
  60441. fillAlphaChannelWithCurrentBrush);
  60442. }
  60443. }
  60444. void Graphics::drawImageWithin (const Image* const imageToDraw,
  60445. const int destX,
  60446. const int destY,
  60447. const int destW,
  60448. const int destH,
  60449. const RectanglePlacement& placementWithinTarget,
  60450. const bool fillAlphaChannelWithCurrentBrush) const throw()
  60451. {
  60452. // passing in a silly number can cause maths problems in rendering!
  60453. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (destX, destY, destW, destH);
  60454. if (imageToDraw != 0)
  60455. {
  60456. const int imageW = imageToDraw->getWidth();
  60457. const int imageH = imageToDraw->getHeight();
  60458. if (imageW > 0 && imageH > 0)
  60459. {
  60460. double newX = 0.0, newY = 0.0;
  60461. double newW = imageW;
  60462. double newH = imageH;
  60463. placementWithinTarget.applyTo (newX, newY, newW, newH,
  60464. destX, destY, destW, destH);
  60465. if (newW > 0 && newH > 0)
  60466. {
  60467. drawImage (imageToDraw,
  60468. roundDoubleToInt (newX), roundDoubleToInt (newY),
  60469. roundDoubleToInt (newW), roundDoubleToInt (newH),
  60470. 0, 0, imageW, imageH,
  60471. fillAlphaChannelWithCurrentBrush);
  60472. }
  60473. }
  60474. }
  60475. }
  60476. void Graphics::drawImage (const Image* const imageToDraw,
  60477. int dx, int dy, int dw, int dh,
  60478. int sx, int sy, int sw, int sh,
  60479. const bool fillAlphaChannelWithCurrentBrush) const throw()
  60480. {
  60481. // passing in a silly number can cause maths problems in rendering!
  60482. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (dx, dy, dw, dh);
  60483. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (sx, sy, sw, sh);
  60484. if (imageToDraw == 0 || ! context->clipRegionIntersects (dx, dy, dw, dh))
  60485. return;
  60486. if (sw == dw && sh == dh)
  60487. {
  60488. if (sx < 0)
  60489. {
  60490. dx -= sx;
  60491. dw += sx;
  60492. sw += sx;
  60493. sx = 0;
  60494. }
  60495. if (sx + sw > imageToDraw->getWidth())
  60496. {
  60497. const int amount = sx + sw - imageToDraw->getWidth();
  60498. dw -= amount;
  60499. sw -= amount;
  60500. }
  60501. if (sy < 0)
  60502. {
  60503. dy -= sy;
  60504. dh += sy;
  60505. sh += sy;
  60506. sy = 0;
  60507. }
  60508. if (sy + sh > imageToDraw->getHeight())
  60509. {
  60510. const int amount = sy + sh - imageToDraw->getHeight();
  60511. dh -= amount;
  60512. sh -= amount;
  60513. }
  60514. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  60515. return;
  60516. if (fillAlphaChannelWithCurrentBrush)
  60517. {
  60518. SolidColourBrush colourBrush (state->colour);
  60519. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  60520. .paintAlphaChannel (*context, *imageToDraw,
  60521. dx - sx, dy - sy,
  60522. dx, dy,
  60523. dw, dh);
  60524. }
  60525. else
  60526. {
  60527. context->blendImage (*imageToDraw,
  60528. dx, dy, dw, dh, sx, sy,
  60529. state->colour.getFloatAlpha());
  60530. }
  60531. }
  60532. else
  60533. {
  60534. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  60535. return;
  60536. if (fillAlphaChannelWithCurrentBrush)
  60537. {
  60538. if (imageToDraw->isRGB())
  60539. {
  60540. fillRect (dx, dy, dw, dh);
  60541. }
  60542. else
  60543. {
  60544. int tx = dx;
  60545. int ty = dy;
  60546. int tw = dw;
  60547. int th = dh;
  60548. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  60549. {
  60550. Image temp (imageToDraw->getFormat(), tw, th, true);
  60551. Graphics g (temp);
  60552. g.setImageResamplingQuality (state->quality);
  60553. g.setOrigin (dx - tx, dy - ty);
  60554. g.drawImage (imageToDraw,
  60555. 0, 0, dw, dh,
  60556. sx, sy, sw, sh,
  60557. false);
  60558. SolidColourBrush colourBrush (state->colour);
  60559. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  60560. .paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  60561. }
  60562. }
  60563. }
  60564. else
  60565. {
  60566. context->blendImageRescaling (*imageToDraw,
  60567. dx, dy, dw, dh,
  60568. sx, sy, sw, sh,
  60569. state->colour.getFloatAlpha(),
  60570. state->quality);
  60571. }
  60572. }
  60573. }
  60574. void Graphics::drawImageTransformed (const Image* const imageToDraw,
  60575. int sourceClipX,
  60576. int sourceClipY,
  60577. int sourceClipWidth,
  60578. int sourceClipHeight,
  60579. const AffineTransform& transform,
  60580. const bool fillAlphaChannelWithCurrentBrush) const throw()
  60581. {
  60582. if (imageToDraw != 0
  60583. && (! context->isClipEmpty())
  60584. && ! transform.isSingularity())
  60585. {
  60586. if (fillAlphaChannelWithCurrentBrush)
  60587. {
  60588. Path p;
  60589. p.addRectangle ((float) sourceClipX, (float) sourceClipY,
  60590. (float) sourceClipWidth, (float) sourceClipHeight);
  60591. p.applyTransform (transform);
  60592. float dx, dy, dw, dh;
  60593. p.getBounds (dx, dy, dw, dh);
  60594. int tx = (int) dx;
  60595. int ty = (int) dy;
  60596. int tw = roundFloatToInt (dw) + 2;
  60597. int th = roundFloatToInt (dh) + 2;
  60598. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  60599. {
  60600. Image temp (imageToDraw->getFormat(), tw, th, true);
  60601. Graphics g (temp);
  60602. g.setImageResamplingQuality (state->quality);
  60603. g.drawImageTransformed (imageToDraw,
  60604. sourceClipX,
  60605. sourceClipY,
  60606. sourceClipWidth,
  60607. sourceClipHeight,
  60608. transform.translated ((float) -tx, (float) -ty),
  60609. false);
  60610. SolidColourBrush colourBrush (state->colour);
  60611. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  60612. }
  60613. }
  60614. else
  60615. {
  60616. context->blendImageWarping (*imageToDraw,
  60617. sourceClipX,
  60618. sourceClipY,
  60619. sourceClipWidth,
  60620. sourceClipHeight,
  60621. transform,
  60622. state->colour.getFloatAlpha(),
  60623. state->quality);
  60624. }
  60625. }
  60626. }
  60627. END_JUCE_NAMESPACE
  60628. /********* End of inlined file: juce_Graphics.cpp *********/
  60629. /********* Start of inlined file: juce_Justification.cpp *********/
  60630. BEGIN_JUCE_NAMESPACE
  60631. Justification::Justification (const Justification& other) throw()
  60632. : flags (other.flags)
  60633. {
  60634. }
  60635. const Justification& Justification::operator= (const Justification& other) throw()
  60636. {
  60637. flags = other.flags;
  60638. return *this;
  60639. }
  60640. int Justification::getOnlyVerticalFlags() const throw()
  60641. {
  60642. return flags & (top | bottom | verticallyCentred);
  60643. }
  60644. int Justification::getOnlyHorizontalFlags() const throw()
  60645. {
  60646. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  60647. }
  60648. void Justification::applyToRectangle (int& x, int& y,
  60649. const int w, const int h,
  60650. const int spaceX, const int spaceY,
  60651. const int spaceW, const int spaceH) const throw()
  60652. {
  60653. if ((flags & horizontallyCentred) != 0)
  60654. {
  60655. x = spaceX + ((spaceW - w) >> 1);
  60656. }
  60657. else if ((flags & right) != 0)
  60658. {
  60659. x = spaceX + spaceW - w;
  60660. }
  60661. else
  60662. {
  60663. x = spaceX;
  60664. }
  60665. if ((flags & verticallyCentred) != 0)
  60666. {
  60667. y = spaceY + ((spaceH - h) >> 1);
  60668. }
  60669. else if ((flags & bottom) != 0)
  60670. {
  60671. y = spaceY + spaceH - h;
  60672. }
  60673. else
  60674. {
  60675. y = spaceY;
  60676. }
  60677. }
  60678. END_JUCE_NAMESPACE
  60679. /********* End of inlined file: juce_Justification.cpp *********/
  60680. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  60681. BEGIN_JUCE_NAMESPACE
  60682. #if JUCE_MSVC
  60683. #pragma warning (disable: 4996) // deprecated sprintf warning
  60684. #endif
  60685. // this will throw an assertion if you try to draw something that's not
  60686. // possible in postscript
  60687. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  60688. #if defined (JUCE_DEBUG) && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  60689. #define notPossibleInPostscriptAssert jassertfalse
  60690. #else
  60691. #define notPossibleInPostscriptAssert
  60692. #endif
  60693. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  60694. const String& documentTitle,
  60695. const int totalWidth_,
  60696. const int totalHeight_)
  60697. : out (resultingPostScript),
  60698. totalWidth (totalWidth_),
  60699. totalHeight (totalHeight_),
  60700. xOffset (0),
  60701. yOffset (0),
  60702. needToClip (true)
  60703. {
  60704. clip = new RectangleList (Rectangle (0, 0, totalWidth_, totalHeight_));
  60705. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  60706. out << "%!PS-Adobe-3.0 EPSF-3.0"
  60707. "\n%%BoundingBox: 0 0 600 824"
  60708. "\n%%Pages: 0"
  60709. "\n%%Creator: Raw Material Software JUCE"
  60710. "\n%%Title: " << documentTitle <<
  60711. "\n%%CreationDate: none"
  60712. "\n%%LanguageLevel: 2"
  60713. "\n%%EndComments"
  60714. "\n%%BeginProlog"
  60715. "\n%%BeginResource: JRes"
  60716. "\n/bd {bind def} bind def"
  60717. "\n/c {setrgbcolor} bd"
  60718. "\n/m {moveto} bd"
  60719. "\n/l {lineto} bd"
  60720. "\n/rl {rlineto} bd"
  60721. "\n/ct {curveto} bd"
  60722. "\n/cp {closepath} bd"
  60723. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  60724. "\n/doclip {initclip newpath} bd"
  60725. "\n/endclip {clip newpath} bd"
  60726. "\n%%EndResource"
  60727. "\n%%EndProlog"
  60728. "\n%%BeginSetup"
  60729. "\n%%EndSetup"
  60730. "\n%%Page: 1 1"
  60731. "\n%%BeginPageSetup"
  60732. "\n%%EndPageSetup\n\n"
  60733. << "40 800 translate\n"
  60734. << scale << ' ' << scale << " scale\n\n";
  60735. }
  60736. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  60737. {
  60738. delete clip;
  60739. }
  60740. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  60741. {
  60742. return true;
  60743. }
  60744. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  60745. {
  60746. if (x != 0 || y != 0)
  60747. {
  60748. xOffset += x;
  60749. yOffset += y;
  60750. needToClip = true;
  60751. }
  60752. }
  60753. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (int x, int y, int w, int h)
  60754. {
  60755. needToClip = true;
  60756. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  60757. }
  60758. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (const RectangleList& clipRegion)
  60759. {
  60760. needToClip = true;
  60761. return clip->clipTo (clipRegion);
  60762. }
  60763. void LowLevelGraphicsPostScriptRenderer::excludeClipRegion (int x, int y, int w, int h)
  60764. {
  60765. needToClip = true;
  60766. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  60767. }
  60768. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (int x, int y, int w, int h)
  60769. {
  60770. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  60771. }
  60772. const Rectangle LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  60773. {
  60774. return clip->getBounds().translated (-xOffset, -yOffset);
  60775. }
  60776. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  60777. {
  60778. return clip->isEmpty();
  60779. }
  60780. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState (RectangleList* const clip_,
  60781. const int xOffset_, const int yOffset_)
  60782. : clip (clip_),
  60783. xOffset (xOffset_),
  60784. yOffset (yOffset_)
  60785. {
  60786. }
  60787. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  60788. {
  60789. delete clip;
  60790. }
  60791. void LowLevelGraphicsPostScriptRenderer::saveState()
  60792. {
  60793. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  60794. }
  60795. void LowLevelGraphicsPostScriptRenderer::restoreState()
  60796. {
  60797. SavedState* const top = stateStack.getLast();
  60798. if (top != 0)
  60799. {
  60800. clip->swapWith (*top->clip);
  60801. xOffset = top->xOffset;
  60802. yOffset = top->yOffset;
  60803. stateStack.removeLast();
  60804. needToClip = true;
  60805. }
  60806. else
  60807. {
  60808. jassertfalse // trying to pop with an empty stack!
  60809. }
  60810. }
  60811. void LowLevelGraphicsPostScriptRenderer::writeClip()
  60812. {
  60813. if (needToClip)
  60814. {
  60815. needToClip = false;
  60816. out << "doclip ";
  60817. int itemsOnLine = 0;
  60818. for (RectangleList::Iterator i (*clip); i.next();)
  60819. {
  60820. if (++itemsOnLine == 6)
  60821. {
  60822. itemsOnLine = 0;
  60823. out << '\n';
  60824. }
  60825. const Rectangle& r = *i.getRectangle();
  60826. out << r.getX() << ' ' << -r.getY() << ' '
  60827. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  60828. }
  60829. out << "endclip\n";
  60830. }
  60831. }
  60832. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  60833. {
  60834. Colour c (Colours::white.overlaidWith (colour));
  60835. if (lastColour != c)
  60836. {
  60837. lastColour = c;
  60838. out << String (c.getFloatRed(), 3) << ' '
  60839. << String (c.getFloatGreen(), 3) << ' '
  60840. << String (c.getFloatBlue(), 3) << " c\n";
  60841. }
  60842. }
  60843. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  60844. {
  60845. out << String (x, 2) << ' '
  60846. << String (-y, 2) << ' ';
  60847. }
  60848. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  60849. {
  60850. out << "newpath ";
  60851. float lastX = 0.0f;
  60852. float lastY = 0.0f;
  60853. int itemsOnLine = 0;
  60854. Path::Iterator i (path);
  60855. while (i.next())
  60856. {
  60857. if (++itemsOnLine == 4)
  60858. {
  60859. itemsOnLine = 0;
  60860. out << '\n';
  60861. }
  60862. switch (i.elementType)
  60863. {
  60864. case Path::Iterator::startNewSubPath:
  60865. writeXY (i.x1, i.y1);
  60866. lastX = i.x1;
  60867. lastY = i.y1;
  60868. out << "m ";
  60869. break;
  60870. case Path::Iterator::lineTo:
  60871. writeXY (i.x1, i.y1);
  60872. lastX = i.x1;
  60873. lastY = i.y1;
  60874. out << "l ";
  60875. break;
  60876. case Path::Iterator::quadraticTo:
  60877. {
  60878. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  60879. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  60880. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  60881. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  60882. writeXY (cp1x, cp1y);
  60883. writeXY (cp2x, cp2y);
  60884. writeXY (i.x2, i.y2);
  60885. out << "ct ";
  60886. lastX = i.x2;
  60887. lastY = i.y2;
  60888. }
  60889. break;
  60890. case Path::Iterator::cubicTo:
  60891. writeXY (i.x1, i.y1);
  60892. writeXY (i.x2, i.y2);
  60893. writeXY (i.x3, i.y3);
  60894. out << "ct ";
  60895. lastX = i.x3;
  60896. lastY = i.y3;
  60897. break;
  60898. case Path::Iterator::closePath:
  60899. out << "cp ";
  60900. break;
  60901. default:
  60902. jassertfalse
  60903. break;
  60904. }
  60905. }
  60906. out << '\n';
  60907. }
  60908. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  60909. {
  60910. out << "[ "
  60911. << trans.mat00 << ' '
  60912. << trans.mat10 << ' '
  60913. << trans.mat01 << ' '
  60914. << trans.mat11 << ' '
  60915. << trans.mat02 << ' '
  60916. << trans.mat12 << " ] concat ";
  60917. }
  60918. void LowLevelGraphicsPostScriptRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool /*replaceExistingContents*/)
  60919. {
  60920. writeClip();
  60921. writeColour (colour);
  60922. x += xOffset;
  60923. y += yOffset;
  60924. out << x << ' ' << -(y + h) << ' ' << w << ' ' << h << " rectfill\n";
  60925. }
  60926. void LowLevelGraphicsPostScriptRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  60927. {
  60928. Path p;
  60929. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  60930. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_256times);
  60931. }
  60932. void LowLevelGraphicsPostScriptRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  60933. const Colour& colour, EdgeTable::OversamplingLevel /*quality*/)
  60934. {
  60935. writeClip();
  60936. Path p (path);
  60937. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  60938. writePath (p);
  60939. writeColour (colour);
  60940. out << "fill\n";
  60941. }
  60942. void LowLevelGraphicsPostScriptRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel /*quality*/)
  60943. {
  60944. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  60945. // postscript can't do semi-transparent ones.
  60946. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  60947. writeClip();
  60948. out << "gsave ";
  60949. {
  60950. Path p (path);
  60951. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  60952. writePath (p);
  60953. out << "clip\n";
  60954. }
  60955. int numColours = 256;
  60956. PixelARGB* const colours = gradient.createLookupTable (numColours);
  60957. for (int i = numColours; --i >= 0;)
  60958. colours[i].unpremultiply();
  60959. const Rectangle bounds (clip->getBounds());
  60960. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  60961. // time-being, this just fills it with the average colour..
  60962. writeColour (Colour (colours [numColours / 2].getARGB()));
  60963. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  60964. juce_free (colours);
  60965. out << "grestore\n";
  60966. }
  60967. void LowLevelGraphicsPostScriptRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  60968. const Image& sourceImage,
  60969. int imageX, int imageY,
  60970. float opacity, EdgeTable::OversamplingLevel /*quality*/)
  60971. {
  60972. writeClip();
  60973. out << "gsave ";
  60974. Path p (path);
  60975. p.applyTransform (transform.translated ((float) xOffset, (float) yOffset));
  60976. writePath (p);
  60977. out << "clip\n";
  60978. blendImage (sourceImage, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight(), 0, 0, opacity);
  60979. out << "grestore\n";
  60980. }
  60981. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithColour (const Image& /*clipImage*/, int x, int y, const Colour& colour)
  60982. {
  60983. x += xOffset;
  60984. y += yOffset;
  60985. writeClip();
  60986. writeColour (colour);
  60987. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  60988. }
  60989. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithGradient (const Image& /*alphaChannelImage*/, int imageX, int imageY, const ColourGradient& /*gradient*/)
  60990. {
  60991. imageX += xOffset;
  60992. imageY += yOffset;
  60993. writeClip();
  60994. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  60995. }
  60996. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithImage (const Image& /*alphaImage*/, int alphaImageX, int alphaImageY,
  60997. const Image& /*fillerImage*/, int fillerImageX, int fillerImageY, float /*opacity*/)
  60998. {
  60999. alphaImageX += xOffset;
  61000. alphaImageY += yOffset;
  61001. fillerImageX += xOffset;
  61002. fillerImageY += yOffset;
  61003. writeClip();
  61004. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  61005. }
  61006. void LowLevelGraphicsPostScriptRenderer::blendImageRescaling (const Image& sourceImage,
  61007. int dx, int dy, int dw, int dh,
  61008. int sx, int sy, int sw, int sh,
  61009. float alpha,
  61010. const Graphics::ResamplingQuality quality)
  61011. {
  61012. if (sw > 0 && sh > 0)
  61013. {
  61014. jassert (sx >= 0 && sx + sw <= sourceImage.getWidth());
  61015. jassert (sy >= 0 && sy + sh <= sourceImage.getHeight());
  61016. if (sw == dw && sh == dh)
  61017. {
  61018. blendImage (sourceImage,
  61019. dx, dy, dw, dh,
  61020. sx, sy, alpha);
  61021. }
  61022. else
  61023. {
  61024. blendImageWarping (sourceImage,
  61025. sx, sy, sw, sh,
  61026. AffineTransform::scale (dw / (float) sw,
  61027. dh / (float) sh)
  61028. .translated ((float) (dx - sx),
  61029. (float) (dy - sy)),
  61030. alpha,
  61031. quality);
  61032. }
  61033. }
  61034. }
  61035. void LowLevelGraphicsPostScriptRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  61036. {
  61037. blendImageWarping (sourceImage,
  61038. sx, sy, dw, dh,
  61039. AffineTransform::translation ((float) dx, (float) dy),
  61040. opacity, Graphics::highResamplingQuality);
  61041. }
  61042. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  61043. const int sx, const int sy,
  61044. const int maxW, const int maxH) const
  61045. {
  61046. out << "{<\n";
  61047. const int w = jmin (maxW, im.getWidth());
  61048. const int h = jmin (maxH, im.getHeight());
  61049. int charsOnLine = 0;
  61050. int lineStride, pixelStride;
  61051. const uint8* data = im.lockPixelDataReadOnly (0, 0, w, h, lineStride, pixelStride);
  61052. Colour pixel;
  61053. for (int y = h; --y >= 0;)
  61054. {
  61055. for (int x = 0; x < w; ++x)
  61056. {
  61057. const uint8* pixelData = data + lineStride * y + pixelStride * x;
  61058. if (x >= sx && y >= sy)
  61059. {
  61060. if (im.isARGB())
  61061. {
  61062. PixelARGB p (*(const PixelARGB*) pixelData);
  61063. p.unpremultiply();
  61064. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  61065. }
  61066. else if (im.isRGB())
  61067. {
  61068. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  61069. }
  61070. else
  61071. {
  61072. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  61073. }
  61074. }
  61075. else
  61076. {
  61077. pixel = Colours::transparentWhite;
  61078. }
  61079. char colourString [16];
  61080. sprintf (colourString, "%x%x%x", pixel.getRed(), pixel.getGreen(), pixel.getBlue());
  61081. out << (const char*) colourString;
  61082. charsOnLine += 3;
  61083. if (charsOnLine > 100)
  61084. {
  61085. out << '\n';
  61086. charsOnLine = 0;
  61087. }
  61088. }
  61089. }
  61090. im.releasePixelDataReadOnly (data);
  61091. out << "\n>}\n";
  61092. }
  61093. void LowLevelGraphicsPostScriptRenderer::blendImageWarping (const Image& sourceImage,
  61094. int srcClipX, int srcClipY,
  61095. int srcClipW, int srcClipH,
  61096. const AffineTransform& t,
  61097. float /*opacity*/,
  61098. const Graphics::ResamplingQuality /*quality*/)
  61099. {
  61100. const int w = jmin (sourceImage.getWidth(), srcClipX + srcClipW);
  61101. const int h = jmin (sourceImage.getHeight(), srcClipY + srcClipH);
  61102. writeClip();
  61103. out << "gsave ";
  61104. writeTransform (t.translated ((float) xOffset, (float) yOffset)
  61105. .scaled (1.0f, -1.0f));
  61106. RectangleList imageClip;
  61107. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  61108. imageClip.clipTo (Rectangle (srcClipX, srcClipY, srcClipW, srcClipH));
  61109. out << "newpath ";
  61110. int itemsOnLine = 0;
  61111. for (RectangleList::Iterator i (imageClip); i.next();)
  61112. {
  61113. if (++itemsOnLine == 6)
  61114. {
  61115. out << '\n';
  61116. itemsOnLine = 0;
  61117. }
  61118. const Rectangle& r = *i.getRectangle();
  61119. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  61120. }
  61121. out << " clip newpath\n";
  61122. out << w << ' ' << h << " scale\n";
  61123. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  61124. writeImage (sourceImage, srcClipX, srcClipY, srcClipW, srcClipH);
  61125. out << "false 3 colorimage grestore\n";
  61126. needToClip = true;
  61127. }
  61128. void LowLevelGraphicsPostScriptRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  61129. {
  61130. Path p;
  61131. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  61132. fillPathWithColour (p, AffineTransform::identity, colour, EdgeTable::Oversampling_256times);
  61133. }
  61134. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  61135. {
  61136. drawLine (x, top, x, bottom, col);
  61137. }
  61138. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  61139. {
  61140. drawLine (left, y, right, y, col);
  61141. }
  61142. END_JUCE_NAMESPACE
  61143. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  61144. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  61145. BEGIN_JUCE_NAMESPACE
  61146. #if ! (defined (JUCE_MAC) || (defined (JUCE_WIN32) && defined (JUCE_64BIT)))
  61147. #define JUCE_USE_SSE_INSTRUCTIONS 1
  61148. #endif
  61149. #if defined (JUCE_DEBUG) && JUCE_MSVC
  61150. #pragma warning (disable: 4714)
  61151. #endif
  61152. #define MINIMUM_COORD -0x3fffffff
  61153. #define MAXIMUM_COORD 0x3fffffff
  61154. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  61155. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  61156. jassert ((int) x >= MINIMUM_COORD \
  61157. && (int) x <= MAXIMUM_COORD \
  61158. && (int) y >= MINIMUM_COORD \
  61159. && (int) y <= MAXIMUM_COORD \
  61160. && (int) w >= 0 \
  61161. && (int) w < MAXIMUM_COORD \
  61162. && (int) h >= 0 \
  61163. && (int) h < MAXIMUM_COORD);
  61164. static void replaceRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  61165. {
  61166. const PixelARGB blendColour (colour.getPixelARGB());
  61167. if (w < 32)
  61168. {
  61169. while (--h >= 0)
  61170. {
  61171. PixelRGB* dest = (PixelRGB*) pixels;
  61172. for (int i = w; --i >= 0;)
  61173. (dest++)->set (blendColour);
  61174. pixels += stride;
  61175. }
  61176. }
  61177. else
  61178. {
  61179. // for wider fills, it's worth using some optimisations..
  61180. const uint8 r = blendColour.getRed();
  61181. const uint8 g = blendColour.getGreen();
  61182. const uint8 b = blendColour.getBlue();
  61183. if (r == g && r == b) // if all the component values are the same, we can cheat..
  61184. {
  61185. while (--h >= 0)
  61186. {
  61187. memset (pixels, r, w * 3);
  61188. pixels += stride;
  61189. }
  61190. }
  61191. else
  61192. {
  61193. PixelRGB filler [4];
  61194. filler[0].set (blendColour);
  61195. filler[1].set (blendColour);
  61196. filler[2].set (blendColour);
  61197. filler[3].set (blendColour);
  61198. const int* const intFiller = (const int*) filler;
  61199. while (--h >= 0)
  61200. {
  61201. uint8* dest = (uint8*) pixels;
  61202. int i = w;
  61203. while ((i > 8) && (((pointer_sized_int) dest & 7) != 0))
  61204. {
  61205. ((PixelRGB*) dest)->set (blendColour);
  61206. dest += 3;
  61207. --i;
  61208. }
  61209. while (i >= 4)
  61210. {
  61211. ((int*) dest) [0] = intFiller[0];
  61212. ((int*) dest) [1] = intFiller[1];
  61213. ((int*) dest) [2] = intFiller[2];
  61214. dest += 12;
  61215. i -= 4;
  61216. }
  61217. while (--i >= 0)
  61218. {
  61219. ((PixelRGB*) dest)->set (blendColour);
  61220. dest += 3;
  61221. }
  61222. pixels += stride;
  61223. }
  61224. }
  61225. }
  61226. }
  61227. static void replaceRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  61228. {
  61229. const PixelARGB blendColour (colour.getPixelARGB());
  61230. while (--h >= 0)
  61231. {
  61232. PixelARGB* const dest = (PixelARGB*) pixels;
  61233. for (int i = 0; i < w; ++i)
  61234. dest[i] = blendColour;
  61235. pixels += stride;
  61236. }
  61237. }
  61238. static void blendRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  61239. {
  61240. if (colour.isOpaque())
  61241. {
  61242. replaceRectRGB (pixels, w, h, stride, colour);
  61243. }
  61244. else
  61245. {
  61246. const PixelARGB blendColour (colour.getPixelARGB());
  61247. const int alpha = blendColour.getAlpha();
  61248. if (alpha <= 0)
  61249. return;
  61250. #if defined (JUCE_USE_SSE_INSTRUCTIONS) && ! JUCE_64BIT
  61251. if (SystemStats::hasSSE())
  61252. {
  61253. int64 rgb0 = (((int64) blendColour.getRed()) << 32)
  61254. | (int64) ((blendColour.getGreen() << 16)
  61255. | blendColour.getBlue());
  61256. const int invAlpha = 0xff - alpha;
  61257. int64 aaaa = (invAlpha << 16) | invAlpha;
  61258. aaaa = (aaaa << 16) | aaaa;
  61259. #ifndef JUCE_GCC
  61260. __asm
  61261. {
  61262. movq mm1, aaaa
  61263. movq mm2, rgb0
  61264. pxor mm7, mm7
  61265. }
  61266. while (--h >= 0)
  61267. {
  61268. __asm
  61269. {
  61270. mov edx, pixels
  61271. mov ebx, w
  61272. pixloop:
  61273. prefetchnta [edx]
  61274. mov ax, [edx + 1]
  61275. shl eax, 8
  61276. mov al, [edx]
  61277. movd mm0, eax
  61278. punpcklbw mm0, mm7
  61279. pmullw mm0, mm1
  61280. psrlw mm0, 8
  61281. paddw mm0, mm2
  61282. packuswb mm0, mm7
  61283. movd eax, mm0
  61284. mov [edx], al
  61285. inc edx
  61286. shr eax, 8
  61287. mov [edx], ax
  61288. add edx, 2
  61289. dec ebx
  61290. jg pixloop
  61291. }
  61292. pixels += stride;
  61293. }
  61294. __asm emms
  61295. #else
  61296. __asm__ __volatile__ (
  61297. "movq %[aaaa], %%mm1 \n"
  61298. "\tmovq %[rgb0], %%mm2 \n"
  61299. "\tpxor %%mm7, %%mm7 \n"
  61300. ".lineLoop2: \n"
  61301. "\tmovl %%esi,%%edx \n"
  61302. "\tmovl %[w], %%ebx \n"
  61303. ".pixLoop2: \n"
  61304. "\tprefetchnta (%%edx) \n"
  61305. "\tmov (%%edx), %%ax \n"
  61306. "\tshl $8, %%eax \n"
  61307. "\tmov 2(%%edx), %%al \n"
  61308. "\tmovd %%eax, %%mm0 \n"
  61309. "\tpunpcklbw %%mm7, %%mm0 \n"
  61310. "\tpmullw %%mm1, %%mm0 \n"
  61311. "\tpsrlw $8, %%mm0 \n"
  61312. "\tpaddw %%mm2, %%mm0 \n"
  61313. "\tpackuswb %%mm7, %%mm0 \n"
  61314. "\tmovd %%mm0, %%eax \n"
  61315. "\tmovb %%al, (%%edx) \n"
  61316. "\tinc %%edx \n"
  61317. "\tshr $8, %%eax \n"
  61318. "\tmovw %%ax, (%%edx) \n"
  61319. "\tadd $2, %%edx \n"
  61320. "\tdec %%ebx \n"
  61321. "\tjg .pixLoop2 \n"
  61322. "\tadd %%edi, %%esi \n"
  61323. "\tdec %%ecx \n"
  61324. "\tjg .lineLoop2 \n"
  61325. "\temms \n"
  61326. : /* No output registers */
  61327. : [aaaa] "m" (aaaa), /* Input registers */
  61328. [rgb0] "m" (rgb0),
  61329. [w] "m" (w),
  61330. "c" (h),
  61331. [stride] "D" (stride),
  61332. [pixels] "S" (pixels)
  61333. : "cc", "eax", "edx", "memory" /* Clobber list */
  61334. );
  61335. #endif
  61336. }
  61337. else
  61338. #endif
  61339. {
  61340. while (--h >= 0)
  61341. {
  61342. PixelRGB* dest = (PixelRGB*) pixels;
  61343. for (int i = w; --i >= 0;)
  61344. (dest++)->blend (blendColour);
  61345. pixels += stride;
  61346. }
  61347. }
  61348. }
  61349. }
  61350. static void blendRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  61351. {
  61352. if (colour.isOpaque())
  61353. {
  61354. replaceRectARGB (pixels, w, h, stride, colour);
  61355. }
  61356. else
  61357. {
  61358. const PixelARGB blendColour (colour.getPixelARGB());
  61359. const int alpha = blendColour.getAlpha();
  61360. if (alpha <= 0)
  61361. return;
  61362. while (--h >= 0)
  61363. {
  61364. PixelARGB* dest = (PixelARGB*) pixels;
  61365. for (int i = w; --i >= 0;)
  61366. (dest++)->blend (blendColour);
  61367. pixels += stride;
  61368. }
  61369. }
  61370. }
  61371. static void blendAlphaMapARGB (uint8* destPixel, const int imageStride,
  61372. const uint8* alphaValues, const int w, int h,
  61373. const int pixelStride, const int lineStride,
  61374. const Colour& colour) throw()
  61375. {
  61376. const PixelARGB srcPix (colour.getPixelARGB());
  61377. while (--h >= 0)
  61378. {
  61379. PixelARGB* dest = (PixelARGB*) destPixel;
  61380. const uint8* src = alphaValues;
  61381. int i = w;
  61382. while (--i >= 0)
  61383. {
  61384. unsigned int srcAlpha = *src;
  61385. src += pixelStride;
  61386. if (srcAlpha > 0)
  61387. dest->blend (srcPix, srcAlpha);
  61388. ++dest;
  61389. }
  61390. alphaValues += lineStride;
  61391. destPixel += imageStride;
  61392. }
  61393. }
  61394. static void blendAlphaMapRGB (uint8* destPixel, const int imageStride,
  61395. const uint8* alphaValues, int const width, int height,
  61396. const int pixelStride, const int lineStride,
  61397. const Colour& colour) throw()
  61398. {
  61399. const PixelARGB srcPix (colour.getPixelARGB());
  61400. while (--height >= 0)
  61401. {
  61402. PixelRGB* dest = (PixelRGB*) destPixel;
  61403. const uint8* src = alphaValues;
  61404. int i = width;
  61405. while (--i >= 0)
  61406. {
  61407. unsigned int srcAlpha = *src;
  61408. src += pixelStride;
  61409. if (srcAlpha > 0)
  61410. dest->blend (srcPix, srcAlpha);
  61411. ++dest;
  61412. }
  61413. alphaValues += lineStride;
  61414. destPixel += imageStride;
  61415. }
  61416. }
  61417. template <class PixelType>
  61418. class SolidColourEdgeTableRenderer
  61419. {
  61420. uint8* const data;
  61421. const int stride;
  61422. PixelType* linePixels;
  61423. PixelARGB sourceColour;
  61424. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  61425. const SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  61426. public:
  61427. SolidColourEdgeTableRenderer (uint8* const data_,
  61428. const int stride_,
  61429. const Colour& colour) throw()
  61430. : data (data_),
  61431. stride (stride_),
  61432. sourceColour (colour.getPixelARGB())
  61433. {
  61434. }
  61435. forcedinline void setEdgeTableYPos (const int y) throw()
  61436. {
  61437. linePixels = (PixelType*) (data + stride * y);
  61438. }
  61439. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  61440. {
  61441. linePixels[x].blend (sourceColour, alphaLevel);
  61442. }
  61443. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  61444. {
  61445. PixelARGB p (sourceColour);
  61446. p.multiplyAlpha (alphaLevel);
  61447. PixelType* dest = linePixels + x;
  61448. if (p.getAlpha() < 0xff)
  61449. {
  61450. do
  61451. {
  61452. dest->blend (p);
  61453. ++dest;
  61454. } while (--width > 0);
  61455. }
  61456. else
  61457. {
  61458. do
  61459. {
  61460. dest->set (p);
  61461. ++dest;
  61462. } while (--width > 0);
  61463. }
  61464. }
  61465. };
  61466. class AlphaBitmapRenderer
  61467. {
  61468. uint8* data;
  61469. int stride;
  61470. uint8* lineStart;
  61471. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  61472. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  61473. public:
  61474. AlphaBitmapRenderer (uint8* const data_,
  61475. const int stride_) throw()
  61476. : data (data_),
  61477. stride (stride_)
  61478. {
  61479. }
  61480. forcedinline void setEdgeTableYPos (const int y) throw()
  61481. {
  61482. lineStart = data + (stride * y);
  61483. }
  61484. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  61485. {
  61486. lineStart [x] = (uint8) alphaLevel;
  61487. }
  61488. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  61489. {
  61490. uint8* d = lineStart + x;
  61491. while (--width >= 0)
  61492. *d++ = (uint8) alphaLevel;
  61493. }
  61494. };
  61495. static const int numScaleBits = 12;
  61496. class LinearGradientPixelGenerator
  61497. {
  61498. const PixelARGB* const lookupTable;
  61499. const int numEntries;
  61500. PixelARGB linePix;
  61501. int start, scale;
  61502. double grad, yTerm;
  61503. bool vertical, horizontal;
  61504. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  61505. const LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  61506. public:
  61507. LinearGradientPixelGenerator (const ColourGradient& gradient,
  61508. const PixelARGB* const lookupTable_, const int numEntries_)
  61509. : lookupTable (lookupTable_),
  61510. numEntries (numEntries_)
  61511. {
  61512. jassert (numEntries_ >= 0);
  61513. float x1 = gradient.x1;
  61514. float y1 = gradient.y1;
  61515. float x2 = gradient.x2;
  61516. float y2 = gradient.y2;
  61517. if (! gradient.transform.isIdentity())
  61518. {
  61519. Line l (x2, y2, x1, y1);
  61520. const Point p3 = l.getPointAlongLine (0.0, 100.0f);
  61521. float x3 = p3.getX();
  61522. float y3 = p3.getY();
  61523. gradient.transform.transformPoint (x1, y1);
  61524. gradient.transform.transformPoint (x2, y2);
  61525. gradient.transform.transformPoint (x3, y3);
  61526. Line l2 (x2, y2, x3, y3);
  61527. float prop = l2.findNearestPointTo (x1, y1);
  61528. const Point newP2 (l2.getPointAlongLineProportionally (prop));
  61529. x2 = newP2.getX();
  61530. y2 = newP2.getY();
  61531. }
  61532. vertical = fabs (x1 - x2) < 0.001f;
  61533. horizontal = fabs (y1 - y2) < 0.001f;
  61534. if (vertical)
  61535. {
  61536. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (y2 - y1));
  61537. start = roundDoubleToInt (y1 * scale);
  61538. }
  61539. else if (horizontal)
  61540. {
  61541. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (x2 - x1));
  61542. start = roundDoubleToInt (x1 * scale);
  61543. }
  61544. else
  61545. {
  61546. grad = (y2 - y1) / (double) (x1 - x2);
  61547. yTerm = y1 - x1 / grad;
  61548. scale = roundDoubleToInt ((numEntries << numScaleBits) / (yTerm * grad - (y2 * grad - x2)));
  61549. grad *= scale;
  61550. }
  61551. }
  61552. forcedinline void setY (const int y) throw()
  61553. {
  61554. if (vertical)
  61555. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> numScaleBits)];
  61556. else if (! horizontal)
  61557. start = roundDoubleToInt ((y - yTerm) * grad);
  61558. }
  61559. forcedinline const PixelARGB getPixel (const int x) const throw()
  61560. {
  61561. if (vertical)
  61562. return linePix;
  61563. return lookupTable [jlimit (0, numEntries, (x * scale - start) >> numScaleBits)];
  61564. }
  61565. };
  61566. class RadialGradientPixelGenerator
  61567. {
  61568. protected:
  61569. const PixelARGB* const lookupTable;
  61570. const int numEntries;
  61571. const double gx1, gy1;
  61572. double maxDist, invScale;
  61573. double dy;
  61574. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  61575. const RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  61576. public:
  61577. RadialGradientPixelGenerator (const ColourGradient& gradient,
  61578. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  61579. : lookupTable (lookupTable_),
  61580. numEntries (numEntries_),
  61581. gx1 (gradient.x1),
  61582. gy1 (gradient.y1)
  61583. {
  61584. jassert (numEntries_ >= 0);
  61585. const float dx = gradient.x1 - gradient.x2;
  61586. const float dy = gradient.y1 - gradient.y2;
  61587. maxDist = dx * dx + dy * dy;
  61588. invScale = (numEntries + 1) / sqrt (maxDist);
  61589. }
  61590. forcedinline void setY (const int y) throw()
  61591. {
  61592. dy = y - gy1;
  61593. dy *= dy;
  61594. }
  61595. forcedinline const PixelARGB getPixel (const int px) const throw()
  61596. {
  61597. double x = px - gx1;
  61598. x *= x;
  61599. x += dy;
  61600. if (x >= maxDist)
  61601. return lookupTable [numEntries];
  61602. else
  61603. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  61604. }
  61605. };
  61606. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  61607. {
  61608. double tM10, tM00, lineYM01, lineYM11;
  61609. AffineTransform inverseTransform;
  61610. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  61611. const TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  61612. public:
  61613. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient,
  61614. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  61615. : RadialGradientPixelGenerator (gradient, lookupTable_, numEntries_),
  61616. inverseTransform (gradient.transform.inverted())
  61617. {
  61618. tM10 = inverseTransform.mat10;
  61619. tM00 = inverseTransform.mat00;
  61620. }
  61621. forcedinline void setY (const int y) throw()
  61622. {
  61623. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  61624. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  61625. }
  61626. forcedinline const PixelARGB getPixel (const int px) const throw()
  61627. {
  61628. double x = px;
  61629. const double y = tM10 * x + lineYM11;
  61630. x = tM00 * x + lineYM01;
  61631. x *= x;
  61632. x += y * y;
  61633. if (x >= maxDist)
  61634. return lookupTable [numEntries];
  61635. else
  61636. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  61637. }
  61638. };
  61639. template <class PixelType, class GradientType>
  61640. class GradientEdgeTableRenderer : public GradientType
  61641. {
  61642. uint8* const data;
  61643. const int stride;
  61644. PixelType* linePixels;
  61645. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  61646. const GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  61647. public:
  61648. GradientEdgeTableRenderer (uint8* const data_,
  61649. const int stride_,
  61650. const ColourGradient& gradient,
  61651. const PixelARGB* const lookupTable, const int numEntries) throw()
  61652. : GradientType (gradient, lookupTable, numEntries - 1),
  61653. data (data_),
  61654. stride (stride_)
  61655. {
  61656. }
  61657. forcedinline void setEdgeTableYPos (const int y) throw()
  61658. {
  61659. linePixels = (PixelType*) (data + stride * y);
  61660. GradientType::setY (y);
  61661. }
  61662. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  61663. {
  61664. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  61665. }
  61666. forcedinline void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  61667. {
  61668. PixelType* dest = linePixels + x;
  61669. if (alphaLevel < 0xff)
  61670. {
  61671. do
  61672. {
  61673. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  61674. } while (--width > 0);
  61675. }
  61676. else
  61677. {
  61678. do
  61679. {
  61680. (dest++)->blend (GradientType::getPixel (x++));
  61681. } while (--width > 0);
  61682. }
  61683. }
  61684. };
  61685. template <class DestPixelType, class SrcPixelType>
  61686. class ImageFillEdgeTableRenderer
  61687. {
  61688. uint8* const destImageData;
  61689. const uint8* srcImageData;
  61690. int stride, srcStride, extraAlpha;
  61691. DestPixelType* linePixels;
  61692. SrcPixelType* sourceLineStart;
  61693. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  61694. const ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  61695. public:
  61696. ImageFillEdgeTableRenderer (uint8* const destImageData_,
  61697. const int stride_,
  61698. const uint8* srcImageData_,
  61699. const int srcStride_,
  61700. int extraAlpha_,
  61701. SrcPixelType*) throw() // dummy param to avoid compiler error
  61702. : destImageData (destImageData_),
  61703. srcImageData (srcImageData_),
  61704. stride (stride_),
  61705. srcStride (srcStride_),
  61706. extraAlpha (extraAlpha_)
  61707. {
  61708. }
  61709. forcedinline void setEdgeTableYPos (int y) throw()
  61710. {
  61711. linePixels = (DestPixelType*) (destImageData + stride * y);
  61712. sourceLineStart = (SrcPixelType*) (srcImageData + srcStride * y);
  61713. }
  61714. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  61715. {
  61716. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  61717. linePixels[x].blend (sourceLineStart [x], alphaLevel);
  61718. }
  61719. forcedinline void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  61720. {
  61721. DestPixelType* dest = linePixels + x;
  61722. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  61723. if (alphaLevel < 0xfe)
  61724. {
  61725. do
  61726. {
  61727. dest++ ->blend (sourceLineStart [x++], alphaLevel);
  61728. } while (--width > 0);
  61729. }
  61730. else
  61731. {
  61732. do
  61733. {
  61734. dest++ ->blend (sourceLineStart [x++]);
  61735. } while (--width > 0);
  61736. }
  61737. }
  61738. };
  61739. static void blendRowOfPixels (PixelARGB* dst,
  61740. const PixelRGB* src,
  61741. int width) throw()
  61742. {
  61743. while (--width >= 0)
  61744. (dst++)->set (*src++);
  61745. }
  61746. static void blendRowOfPixels (PixelRGB* dst,
  61747. const PixelRGB* src,
  61748. int width) throw()
  61749. {
  61750. memcpy (dst, src, 3 * width);
  61751. }
  61752. static void blendRowOfPixels (PixelRGB* dst,
  61753. const PixelARGB* src,
  61754. int width) throw()
  61755. {
  61756. while (--width >= 0)
  61757. (dst++)->blend (*src++);
  61758. }
  61759. static void blendRowOfPixels (PixelARGB* dst,
  61760. const PixelARGB* src,
  61761. int width) throw()
  61762. {
  61763. while (--width >= 0)
  61764. (dst++)->blend (*src++);
  61765. }
  61766. static void blendRowOfPixels (PixelARGB* dst,
  61767. const PixelRGB* src,
  61768. int width,
  61769. const uint8 alpha) throw()
  61770. {
  61771. while (--width >= 0)
  61772. (dst++)->blend (*src++, alpha);
  61773. }
  61774. static void blendRowOfPixels (PixelRGB* dst,
  61775. const PixelRGB* src,
  61776. int width,
  61777. const uint8 alpha) throw()
  61778. {
  61779. uint8* d = (uint8*) dst;
  61780. const uint8* s = (const uint8*) src;
  61781. const int inverseAlpha = 0xff - alpha;
  61782. while (--width >= 0)
  61783. {
  61784. d[0] = (uint8) (s[0] + (((d[0] - s[0]) * inverseAlpha) >> 8));
  61785. d[1] = (uint8) (s[1] + (((d[1] - s[1]) * inverseAlpha) >> 8));
  61786. d[2] = (uint8) (s[2] + (((d[2] - s[2]) * inverseAlpha) >> 8));
  61787. d += 3;
  61788. s += 3;
  61789. }
  61790. }
  61791. static void blendRowOfPixels (PixelRGB* dst,
  61792. const PixelARGB* src,
  61793. int width,
  61794. const uint8 alpha) throw()
  61795. {
  61796. while (--width >= 0)
  61797. (dst++)->blend (*src++, alpha);
  61798. }
  61799. static void blendRowOfPixels (PixelARGB* dst,
  61800. const PixelARGB* src,
  61801. int width,
  61802. const uint8 alpha) throw()
  61803. {
  61804. while (--width >= 0)
  61805. (dst++)->blend (*src++, alpha);
  61806. }
  61807. template <class DestPixelType, class SrcPixelType>
  61808. static void overlayImage (DestPixelType* dest,
  61809. const int destStride,
  61810. const SrcPixelType* src,
  61811. const int srcStride,
  61812. const int width,
  61813. int height,
  61814. const uint8 alpha) throw()
  61815. {
  61816. if (alpha < 0xff)
  61817. {
  61818. while (--height >= 0)
  61819. {
  61820. blendRowOfPixels (dest, src, width, alpha);
  61821. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  61822. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  61823. }
  61824. }
  61825. else
  61826. {
  61827. while (--height >= 0)
  61828. {
  61829. blendRowOfPixels (dest, src, width);
  61830. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  61831. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  61832. }
  61833. }
  61834. }
  61835. template <class DestPixelType, class SrcPixelType>
  61836. static void transformedImageRender (Image& destImage,
  61837. const Image& sourceImage,
  61838. const int destClipX, const int destClipY,
  61839. const int destClipW, const int destClipH,
  61840. const int srcClipX, const int srcClipY,
  61841. const int srcClipWidth, const int srcClipHeight,
  61842. double srcX, double srcY,
  61843. const double lineDX, const double lineDY,
  61844. const double pixelDX, const double pixelDY,
  61845. const uint8 alpha,
  61846. const Graphics::ResamplingQuality quality,
  61847. DestPixelType*,
  61848. SrcPixelType*) throw() // forced by a compiler bug to include dummy
  61849. // parameters of the templated classes to
  61850. // make it use the correct instance of this function..
  61851. {
  61852. int destStride, destPixelStride;
  61853. uint8* const destPixels = destImage.lockPixelDataReadWrite (destClipX, destClipY, destClipW, destClipH, destStride, destPixelStride);
  61854. int srcStride, srcPixelStride;
  61855. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (srcClipX, srcClipY, srcClipWidth, srcClipHeight, srcStride, srcPixelStride);
  61856. if (quality == Graphics::lowResamplingQuality) // nearest-neighbour..
  61857. {
  61858. for (int y = 0; y < destClipH; ++y)
  61859. {
  61860. double sx = srcX;
  61861. double sy = srcY;
  61862. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  61863. for (int x = 0; x < destClipW; ++x)
  61864. {
  61865. const int ix = roundDoubleToInt (floor (sx)) - srcClipX;
  61866. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  61867. {
  61868. const int iy = roundDoubleToInt (floor (sy)) - srcClipY;
  61869. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  61870. {
  61871. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  61872. dest->blend (*src, alpha);
  61873. }
  61874. }
  61875. ++dest;
  61876. sx += pixelDX;
  61877. sy += pixelDY;
  61878. }
  61879. srcX += lineDX;
  61880. srcY += lineDY;
  61881. }
  61882. }
  61883. else
  61884. {
  61885. jassert (quality == Graphics::mediumResamplingQuality); // (only bilinear is implemented, so that's what you'll get here..)
  61886. for (int y = 0; y < destClipH; ++y)
  61887. {
  61888. double sx = srcX;
  61889. double sy = srcY;
  61890. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  61891. for (int x = 0; x < destClipW; ++x)
  61892. {
  61893. const double fx = floor (sx);
  61894. const double fy = floor (sy);
  61895. const int ix = roundDoubleToInt (fx) - srcClipX;
  61896. const int iy = roundDoubleToInt (fy) - srcClipY;
  61897. if (ix < srcClipWidth && iy < srcClipHeight)
  61898. {
  61899. PixelARGB p1 (0), p2 (0), p3 (0), p4 (0);
  61900. const SrcPixelType* src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  61901. if (iy >= 0)
  61902. {
  61903. if (ix >= 0)
  61904. p1.set (src[0]);
  61905. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  61906. p2.set (src[1]);
  61907. }
  61908. if (((unsigned int) (iy + 1)) < (unsigned int) srcClipHeight)
  61909. {
  61910. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  61911. if (ix >= 0)
  61912. p3.set (src[0]);
  61913. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  61914. p4.set (src[1]);
  61915. }
  61916. const int dx = roundDoubleToInt ((sx - fx) * 255.0);
  61917. p1.tween (p2, dx);
  61918. p3.tween (p4, dx);
  61919. p1.tween (p3, roundDoubleToInt ((sy - fy) * 255.0));
  61920. if (p1.getAlpha() > 0)
  61921. dest->blend (p1, alpha);
  61922. }
  61923. ++dest;
  61924. sx += pixelDX;
  61925. sy += pixelDY;
  61926. }
  61927. srcX += lineDX;
  61928. srcY += lineDY;
  61929. }
  61930. }
  61931. destImage.releasePixelDataReadWrite (destPixels);
  61932. sourceImage.releasePixelDataReadOnly (srcPixels);
  61933. }
  61934. template <class SrcPixelType, class DestPixelType>
  61935. static void renderAlphaMap (DestPixelType* destPixels,
  61936. int destStride,
  61937. SrcPixelType* srcPixels,
  61938. int srcStride,
  61939. const uint8* alphaValues,
  61940. const int lineStride, const int pixelStride,
  61941. int width, int height,
  61942. const int extraAlpha) throw()
  61943. {
  61944. while (--height >= 0)
  61945. {
  61946. SrcPixelType* srcPix = srcPixels;
  61947. srcPixels = (SrcPixelType*) (((const uint8*) srcPixels) + srcStride);
  61948. DestPixelType* destPix = destPixels;
  61949. destPixels = (DestPixelType*) (((uint8*) destPixels) + destStride);
  61950. const uint8* alpha = alphaValues;
  61951. alphaValues += lineStride;
  61952. if (extraAlpha < 0x100)
  61953. {
  61954. for (int i = width; --i >= 0;)
  61955. {
  61956. destPix++ ->blend (*srcPix++, (extraAlpha * *alpha) >> 8);
  61957. alpha += pixelStride;
  61958. }
  61959. }
  61960. else
  61961. {
  61962. for (int i = width; --i >= 0;)
  61963. {
  61964. destPix++ ->blend (*srcPix++, *alpha);
  61965. alpha += pixelStride;
  61966. }
  61967. }
  61968. }
  61969. }
  61970. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_)
  61971. : image (image_),
  61972. xOffset (0),
  61973. yOffset (0),
  61974. stateStack (20)
  61975. {
  61976. clip = new RectangleList (Rectangle (0, 0, image_.getWidth(), image_.getHeight()));
  61977. }
  61978. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  61979. {
  61980. delete clip;
  61981. }
  61982. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  61983. {
  61984. return false;
  61985. }
  61986. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  61987. {
  61988. xOffset += x;
  61989. yOffset += y;
  61990. }
  61991. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (int x, int y, int w, int h)
  61992. {
  61993. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  61994. }
  61995. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (const RectangleList& clipRegion)
  61996. {
  61997. RectangleList temp (clipRegion);
  61998. temp.offsetAll (xOffset, yOffset);
  61999. return clip->clipTo (temp);
  62000. }
  62001. void LowLevelGraphicsSoftwareRenderer::excludeClipRegion (int x, int y, int w, int h)
  62002. {
  62003. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  62004. }
  62005. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (int x, int y, int w, int h)
  62006. {
  62007. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  62008. }
  62009. const Rectangle LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  62010. {
  62011. return clip->getBounds().translated (-xOffset, -yOffset);
  62012. }
  62013. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  62014. {
  62015. return clip->isEmpty();
  62016. }
  62017. LowLevelGraphicsSoftwareRenderer::SavedState::SavedState (RectangleList* const clip_,
  62018. const int xOffset_, const int yOffset_)
  62019. : clip (clip_),
  62020. xOffset (xOffset_),
  62021. yOffset (yOffset_)
  62022. {
  62023. }
  62024. LowLevelGraphicsSoftwareRenderer::SavedState::~SavedState()
  62025. {
  62026. delete clip;
  62027. }
  62028. void LowLevelGraphicsSoftwareRenderer::saveState()
  62029. {
  62030. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  62031. }
  62032. void LowLevelGraphicsSoftwareRenderer::restoreState()
  62033. {
  62034. SavedState* const top = stateStack.getLast();
  62035. if (top != 0)
  62036. {
  62037. clip->swapWith (*top->clip);
  62038. xOffset = top->xOffset;
  62039. yOffset = top->yOffset;
  62040. stateStack.removeLast();
  62041. }
  62042. else
  62043. {
  62044. jassertfalse // trying to pop with an empty stack!
  62045. }
  62046. }
  62047. void LowLevelGraphicsSoftwareRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  62048. {
  62049. x += xOffset;
  62050. y += yOffset;
  62051. for (RectangleList::Iterator i (*clip); i.next();)
  62052. {
  62053. clippedFillRectWithColour (*i.getRectangle(), x, y, w, h, colour, replaceExistingContents);
  62054. }
  62055. }
  62056. void LowLevelGraphicsSoftwareRenderer::clippedFillRectWithColour (const Rectangle& clipRect,
  62057. int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  62058. {
  62059. if (clipRect.intersectRectangle (x, y, w, h))
  62060. {
  62061. int stride, pixelStride;
  62062. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  62063. if (image.getFormat() == Image::RGB)
  62064. {
  62065. if (replaceExistingContents)
  62066. replaceRectRGB (pixels, w, h, stride, colour);
  62067. else
  62068. blendRectRGB (pixels, w, h, stride, colour);
  62069. }
  62070. else if (image.getFormat() == Image::ARGB)
  62071. {
  62072. if (replaceExistingContents)
  62073. replaceRectARGB (pixels, w, h, stride, colour);
  62074. else
  62075. blendRectARGB (pixels, w, h, stride, colour);
  62076. }
  62077. else
  62078. {
  62079. jassertfalse // not done!
  62080. }
  62081. image.releasePixelDataReadWrite (pixels);
  62082. }
  62083. }
  62084. void LowLevelGraphicsSoftwareRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  62085. {
  62086. Path p;
  62087. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  62088. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_none);
  62089. }
  62090. bool LowLevelGraphicsSoftwareRenderer::getPathBounds (int clipX, int clipY, int clipW, int clipH,
  62091. const Path& path, const AffineTransform& transform,
  62092. int& x, int& y, int& w, int& h) const
  62093. {
  62094. float tx, ty, tw, th;
  62095. path.getBoundsTransformed (transform, tx, ty, tw, th);
  62096. x = roundDoubleToInt (tx) - 1;
  62097. y = roundDoubleToInt (ty) - 1;
  62098. w = roundDoubleToInt (tw) + 2;
  62099. h = roundDoubleToInt (th) + 2;
  62100. // seems like this operation is using some crazy out-of-range numbers..
  62101. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, w, h);
  62102. return Rectangle::intersectRectangles (x, y, w, h, clipX, clipY, clipW, clipH);
  62103. }
  62104. void LowLevelGraphicsSoftwareRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  62105. const Colour& colour, EdgeTable::OversamplingLevel quality)
  62106. {
  62107. for (RectangleList::Iterator i (*clip); i.next();)
  62108. {
  62109. const Rectangle& r = *i.getRectangle();
  62110. clippedFillPathWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(), path, t, colour, quality);
  62111. }
  62112. }
  62113. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  62114. const Colour& colour, EdgeTable::OversamplingLevel quality)
  62115. {
  62116. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  62117. int cx, cy, cw, ch;
  62118. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  62119. {
  62120. EdgeTable edgeTable (0, ch, quality);
  62121. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  62122. int stride, pixelStride;
  62123. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  62124. if (image.getFormat() == Image::RGB)
  62125. {
  62126. jassert (pixelStride == 3);
  62127. SolidColourEdgeTableRenderer <PixelRGB> renderer (pixels, stride, colour);
  62128. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62129. }
  62130. else if (image.getFormat() == Image::ARGB)
  62131. {
  62132. jassert (pixelStride == 4);
  62133. SolidColourEdgeTableRenderer <PixelARGB> renderer (pixels, stride, colour);
  62134. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62135. }
  62136. else if (image.getFormat() == Image::SingleChannel)
  62137. {
  62138. jassert (pixelStride == 1);
  62139. AlphaBitmapRenderer renderer (pixels, stride);
  62140. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62141. }
  62142. image.releasePixelDataReadWrite (pixels);
  62143. }
  62144. }
  62145. void LowLevelGraphicsSoftwareRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  62146. {
  62147. for (RectangleList::Iterator i (*clip); i.next();)
  62148. {
  62149. const Rectangle& r = *i.getRectangle();
  62150. clippedFillPathWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62151. path, t, gradient, quality);
  62152. }
  62153. }
  62154. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  62155. const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  62156. {
  62157. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  62158. int cx, cy, cw, ch;
  62159. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  62160. {
  62161. int stride, pixelStride;
  62162. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  62163. ColourGradient g2 (gradient);
  62164. const bool isIdentity = g2.transform.isIdentity();
  62165. if (isIdentity)
  62166. {
  62167. g2.x1 += xOffset - cx;
  62168. g2.x2 += xOffset - cx;
  62169. g2.y1 += yOffset - cy;
  62170. g2.y2 += yOffset - cy;
  62171. }
  62172. else
  62173. {
  62174. g2.transform = g2.transform.translated ((float) (xOffset - cx),
  62175. (float) (yOffset - cy));
  62176. }
  62177. int numLookupEntries;
  62178. PixelARGB* const lookupTable = g2.createLookupTable (numLookupEntries);
  62179. jassert (numLookupEntries > 0);
  62180. EdgeTable edgeTable (0, ch, quality);
  62181. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  62182. if (image.getFormat() == Image::RGB)
  62183. {
  62184. jassert (pixelStride == 3);
  62185. if (g2.isRadial)
  62186. {
  62187. if (isIdentity)
  62188. {
  62189. GradientEdgeTableRenderer <PixelRGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62190. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62191. }
  62192. else
  62193. {
  62194. GradientEdgeTableRenderer <PixelRGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62195. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62196. }
  62197. }
  62198. else
  62199. {
  62200. GradientEdgeTableRenderer <PixelRGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62201. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62202. }
  62203. }
  62204. else if (image.getFormat() == Image::ARGB)
  62205. {
  62206. jassert (pixelStride == 4);
  62207. if (g2.isRadial)
  62208. {
  62209. if (isIdentity)
  62210. {
  62211. GradientEdgeTableRenderer <PixelARGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62212. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62213. }
  62214. else
  62215. {
  62216. GradientEdgeTableRenderer <PixelARGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62217. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62218. }
  62219. }
  62220. else
  62221. {
  62222. GradientEdgeTableRenderer <PixelARGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62223. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62224. }
  62225. }
  62226. else if (image.getFormat() == Image::SingleChannel)
  62227. {
  62228. jassertfalse // not done!
  62229. }
  62230. juce_free (lookupTable);
  62231. image.releasePixelDataReadWrite (pixels);
  62232. }
  62233. }
  62234. void LowLevelGraphicsSoftwareRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  62235. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  62236. {
  62237. imageX += xOffset;
  62238. imageY += yOffset;
  62239. for (RectangleList::Iterator i (*clip); i.next();)
  62240. {
  62241. const Rectangle& r = *i.getRectangle();
  62242. clippedFillPathWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62243. path, transform, sourceImage, imageX, imageY, opacity, quality);
  62244. }
  62245. }
  62246. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithImage (int x, int y, int w, int h, const Path& path, const AffineTransform& transform,
  62247. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  62248. {
  62249. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight()))
  62250. {
  62251. EdgeTable edgeTable (0, h, quality);
  62252. edgeTable.addPath (path, transform.translated ((float) (xOffset - x), (float) (yOffset - y)));
  62253. int stride, pixelStride;
  62254. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  62255. int srcStride, srcPixelStride;
  62256. const uint8* const srcPix = (const uint8*) sourceImage.lockPixelDataReadOnly (x - imageX, y - imageY, w, h, srcStride, srcPixelStride);
  62257. const int alpha = jlimit (0, 255, roundDoubleToInt (opacity * 255.0f));
  62258. if (image.getFormat() == Image::RGB)
  62259. {
  62260. if (sourceImage.getFormat() == Image::RGB)
  62261. {
  62262. ImageFillEdgeTableRenderer <PixelRGB, PixelRGB> renderer (pixels, stride,
  62263. srcPix, srcStride,
  62264. alpha, (PixelRGB*) 0);
  62265. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  62266. }
  62267. else if (sourceImage.getFormat() == Image::ARGB)
  62268. {
  62269. ImageFillEdgeTableRenderer <PixelRGB, PixelARGB> renderer (pixels, stride,
  62270. srcPix, srcStride,
  62271. alpha, (PixelARGB*) 0);
  62272. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  62273. }
  62274. else
  62275. {
  62276. jassertfalse // not done!
  62277. }
  62278. }
  62279. else if (image.getFormat() == Image::ARGB)
  62280. {
  62281. if (sourceImage.getFormat() == Image::RGB)
  62282. {
  62283. ImageFillEdgeTableRenderer <PixelARGB, PixelRGB> renderer (pixels, stride,
  62284. srcPix, srcStride,
  62285. alpha, (PixelRGB*) 0);
  62286. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  62287. }
  62288. else if (sourceImage.getFormat() == Image::ARGB)
  62289. {
  62290. ImageFillEdgeTableRenderer <PixelARGB, PixelARGB> renderer (pixels, stride,
  62291. srcPix, srcStride,
  62292. alpha, (PixelARGB*) 0);
  62293. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  62294. }
  62295. else
  62296. {
  62297. jassertfalse // not done!
  62298. }
  62299. }
  62300. else
  62301. {
  62302. jassertfalse // not done!
  62303. }
  62304. sourceImage.releasePixelDataReadOnly (srcPix);
  62305. image.releasePixelDataReadWrite (pixels);
  62306. }
  62307. }
  62308. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithColour (const Image& clipImage, int x, int y, const Colour& colour)
  62309. {
  62310. x += xOffset;
  62311. y += yOffset;
  62312. for (RectangleList::Iterator i (*clip); i.next();)
  62313. {
  62314. const Rectangle& r = *i.getRectangle();
  62315. clippedFillAlphaChannelWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62316. clipImage, x, y, colour);
  62317. }
  62318. }
  62319. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& clipImage, int x, int y, const Colour& colour)
  62320. {
  62321. int w = clipImage.getWidth();
  62322. int h = clipImage.getHeight();
  62323. int sx = 0;
  62324. int sy = 0;
  62325. if (x < clipX)
  62326. {
  62327. sx = clipX - x;
  62328. w -= clipX - x;
  62329. x = clipX;
  62330. }
  62331. if (y < clipY)
  62332. {
  62333. sy = clipY - y;
  62334. h -= clipY - y;
  62335. y = clipY;
  62336. }
  62337. if (x + w > clipX + clipW)
  62338. w = clipX + clipW - x;
  62339. if (y + h > clipY + clipH)
  62340. h = clipY + clipH - y;
  62341. if (w > 0 && h > 0)
  62342. {
  62343. int stride, alphaStride, pixelStride;
  62344. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  62345. const uint8* const alphaValues
  62346. = clipImage.lockPixelDataReadOnly (sx, sy, w, h, alphaStride, pixelStride);
  62347. #if JUCE_MAC
  62348. const uint8* const alphas = alphaValues;
  62349. #else
  62350. const uint8* const alphas = alphaValues + (clipImage.getFormat() == Image::ARGB ? 3 : 0);
  62351. #endif
  62352. if (image.getFormat() == Image::RGB)
  62353. {
  62354. blendAlphaMapRGB (pixels, stride,
  62355. alphas, w, h,
  62356. pixelStride, alphaStride,
  62357. colour);
  62358. }
  62359. else if (image.getFormat() == Image::ARGB)
  62360. {
  62361. blendAlphaMapARGB (pixels, stride,
  62362. alphas, w, h,
  62363. pixelStride, alphaStride,
  62364. colour);
  62365. }
  62366. else
  62367. {
  62368. jassertfalse // not done!
  62369. }
  62370. clipImage.releasePixelDataReadOnly (alphaValues);
  62371. image.releasePixelDataReadWrite (pixels);
  62372. }
  62373. }
  62374. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithGradient (const Image& alphaChannelImage, int imageX, int imageY, const ColourGradient& gradient)
  62375. {
  62376. imageX += xOffset;
  62377. imageY += yOffset;
  62378. for (RectangleList::Iterator i (*clip); i.next();)
  62379. {
  62380. const Rectangle& r = *i.getRectangle();
  62381. clippedFillAlphaChannelWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62382. alphaChannelImage, imageX, imageY, gradient);
  62383. }
  62384. }
  62385. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithGradient (int x, int y, int w, int h,
  62386. const Image& alphaChannelImage,
  62387. int imageX, int imageY, const ColourGradient& gradient)
  62388. {
  62389. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, alphaChannelImage.getWidth(), alphaChannelImage.getHeight()))
  62390. {
  62391. ColourGradient g2 (gradient);
  62392. g2.x1 += xOffset - x;
  62393. g2.x2 += xOffset - x;
  62394. g2.y1 += yOffset - y;
  62395. g2.y2 += yOffset - y;
  62396. Image temp (g2.isOpaque() ? Image::RGB : Image::ARGB, w, h, true);
  62397. LowLevelGraphicsSoftwareRenderer tempG (temp);
  62398. tempG.fillRectWithGradient (0, 0, w, h, g2);
  62399. clippedFillAlphaChannelWithImage (x, y, w, h,
  62400. alphaChannelImage, imageX, imageY,
  62401. temp, x, y, 1.0f);
  62402. }
  62403. }
  62404. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  62405. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  62406. {
  62407. alphaImageX += xOffset;
  62408. alphaImageY += yOffset;
  62409. fillerImageX += xOffset;
  62410. fillerImageY += yOffset;
  62411. for (RectangleList::Iterator i (*clip); i.next();)
  62412. {
  62413. const Rectangle& r = *i.getRectangle();
  62414. clippedFillAlphaChannelWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62415. alphaImage, alphaImageX, alphaImageY,
  62416. fillerImage, fillerImageX, fillerImageY, opacity);
  62417. }
  62418. }
  62419. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithImage (int x, int y, int w, int h, const Image& alphaImage, int alphaImageX, int alphaImageY,
  62420. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  62421. {
  62422. if (Rectangle::intersectRectangles (x, y, w, h, alphaImageX, alphaImageY, alphaImage.getWidth(), alphaImage.getHeight())
  62423. && Rectangle::intersectRectangles (x, y, w, h, fillerImageX, fillerImageY, fillerImage.getWidth(), fillerImage.getHeight()))
  62424. {
  62425. int dstStride, dstPixStride;
  62426. uint8* const dstPix = image.lockPixelDataReadWrite (x, y, w, h, dstStride, dstPixStride);
  62427. int srcStride, srcPixStride;
  62428. const uint8* const srcPix = fillerImage.lockPixelDataReadOnly (x - fillerImageX, y - fillerImageY, w, h, srcStride, srcPixStride);
  62429. int maskStride, maskPixStride;
  62430. const uint8* const alpha
  62431. = alphaImage.lockPixelDataReadOnly (x - alphaImageX, y - alphaImageY, w, h, maskStride, maskPixStride);
  62432. #if JUCE_MAC
  62433. const uint8* const alphaValues = alpha;
  62434. #else
  62435. const uint8* const alphaValues = alpha + (alphaImage.getFormat() == Image::ARGB ? 3 : 0);
  62436. #endif
  62437. const int extraAlpha = jlimit (0, 0x100, roundDoubleToInt (opacity * 256.0f));
  62438. if (image.getFormat() == Image::RGB)
  62439. {
  62440. if (fillerImage.getFormat() == Image::RGB)
  62441. {
  62442. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  62443. }
  62444. else if (fillerImage.getFormat() == Image::ARGB)
  62445. {
  62446. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  62447. }
  62448. else
  62449. {
  62450. jassertfalse // not done!
  62451. }
  62452. }
  62453. else if (image.getFormat() == Image::ARGB)
  62454. {
  62455. if (fillerImage.getFormat() == Image::RGB)
  62456. {
  62457. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  62458. }
  62459. else if (fillerImage.getFormat() == Image::ARGB)
  62460. {
  62461. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  62462. }
  62463. else
  62464. {
  62465. jassertfalse // not done!
  62466. }
  62467. }
  62468. else
  62469. {
  62470. jassertfalse // not done!
  62471. }
  62472. alphaImage.releasePixelDataReadOnly (alphaValues);
  62473. fillerImage.releasePixelDataReadOnly (srcPix);
  62474. image.releasePixelDataReadWrite (dstPix);
  62475. }
  62476. }
  62477. void LowLevelGraphicsSoftwareRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  62478. {
  62479. dx += xOffset;
  62480. dy += yOffset;
  62481. for (RectangleList::Iterator i (*clip); i.next();)
  62482. {
  62483. const Rectangle& r = *i.getRectangle();
  62484. clippedBlendImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62485. sourceImage, dx, dy, dw, dh, sx, sy, opacity);
  62486. }
  62487. }
  62488. void LowLevelGraphicsSoftwareRenderer::clippedBlendImage (int clipX, int clipY, int clipW, int clipH,
  62489. const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  62490. {
  62491. if (dx < clipX)
  62492. {
  62493. sx += clipX - dx;
  62494. dw -= clipX - dx;
  62495. dx = clipX;
  62496. }
  62497. if (dy < clipY)
  62498. {
  62499. sy += clipY - dy;
  62500. dh -= clipY - dy;
  62501. dy = clipY;
  62502. }
  62503. if (dx + dw > clipX + clipW)
  62504. dw = clipX + clipW - dx;
  62505. if (dy + dh > clipY + clipH)
  62506. dh = clipY + clipH - dy;
  62507. if (dw <= 0 || dh <= 0)
  62508. return;
  62509. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  62510. if (alpha == 0)
  62511. return;
  62512. int dstStride, dstPixelStride;
  62513. uint8* const dstPixels = image.lockPixelDataReadWrite (dx, dy, dw, dh, dstStride, dstPixelStride);
  62514. int srcStride, srcPixelStride;
  62515. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (sx, sy, dw, dh, srcStride, srcPixelStride);
  62516. if (image.getFormat() == Image::ARGB)
  62517. {
  62518. if (sourceImage.getFormat() == Image::ARGB)
  62519. {
  62520. overlayImage ((PixelARGB*) dstPixels, dstStride,
  62521. (PixelARGB*) srcPixels, srcStride,
  62522. dw, dh, alpha);
  62523. }
  62524. else if (sourceImage.getFormat() == Image::RGB)
  62525. {
  62526. overlayImage ((PixelARGB*) dstPixels, dstStride,
  62527. (PixelRGB*) srcPixels, srcStride,
  62528. dw, dh, alpha);
  62529. }
  62530. else
  62531. {
  62532. jassertfalse
  62533. }
  62534. }
  62535. else if (image.getFormat() == Image::RGB)
  62536. {
  62537. if (sourceImage.getFormat() == Image::ARGB)
  62538. {
  62539. overlayImage ((PixelRGB*) dstPixels, dstStride,
  62540. (PixelARGB*) srcPixels, srcStride,
  62541. dw, dh, alpha);
  62542. }
  62543. else if (sourceImage.getFormat() == Image::RGB)
  62544. {
  62545. overlayImage ((PixelRGB*) dstPixels, dstStride,
  62546. (PixelRGB*) srcPixels, srcStride,
  62547. dw, dh, alpha);
  62548. }
  62549. else
  62550. {
  62551. jassertfalse
  62552. }
  62553. }
  62554. else
  62555. {
  62556. jassertfalse
  62557. }
  62558. image.releasePixelDataReadWrite (dstPixels);
  62559. sourceImage.releasePixelDataReadOnly (srcPixels);
  62560. }
  62561. void LowLevelGraphicsSoftwareRenderer::blendImageRescaling (const Image& sourceImage,
  62562. int dx, int dy, int dw, int dh,
  62563. int sx, int sy, int sw, int sh,
  62564. float alpha,
  62565. const Graphics::ResamplingQuality quality)
  62566. {
  62567. if (sw > 0 && sh > 0)
  62568. {
  62569. if (sw == dw && sh == dh)
  62570. {
  62571. blendImage (sourceImage,
  62572. dx, dy, dw, dh,
  62573. sx, sy, alpha);
  62574. }
  62575. else
  62576. {
  62577. blendImageWarping (sourceImage,
  62578. sx, sy, sw, sh,
  62579. AffineTransform::translation ((float) -sx,
  62580. (float) -sy)
  62581. .scaled (dw / (float) sw,
  62582. dh / (float) sh)
  62583. .translated ((float) dx,
  62584. (float) dy),
  62585. alpha,
  62586. quality);
  62587. }
  62588. }
  62589. }
  62590. void LowLevelGraphicsSoftwareRenderer::blendImageWarping (const Image& sourceImage,
  62591. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  62592. const AffineTransform& t,
  62593. float opacity,
  62594. const Graphics::ResamplingQuality quality)
  62595. {
  62596. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  62597. for (RectangleList::Iterator i (*clip); i.next();)
  62598. {
  62599. const Rectangle& r = *i.getRectangle();
  62600. clippedBlendImageWarping (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62601. sourceImage, srcClipX, srcClipY, srcClipW, srcClipH,
  62602. transform, opacity, quality);
  62603. }
  62604. }
  62605. void LowLevelGraphicsSoftwareRenderer::clippedBlendImageWarping (int destClipX, int destClipY, int destClipW, int destClipH,
  62606. const Image& sourceImage,
  62607. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  62608. const AffineTransform& transform,
  62609. float opacity,
  62610. const Graphics::ResamplingQuality quality)
  62611. {
  62612. if (opacity > 0 && destClipW > 0 && destClipH > 0 && ! transform.isSingularity())
  62613. {
  62614. Rectangle::intersectRectangles (srcClipX, srcClipY, srcClipW, srcClipH,
  62615. 0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  62616. if (srcClipW <= 0 || srcClipH <= 0)
  62617. return;
  62618. jassert (srcClipX >= 0 && srcClipY >= 0);
  62619. Path imageBounds;
  62620. imageBounds.addRectangle ((float) srcClipX, (float) srcClipY, (float) srcClipW, (float) srcClipH);
  62621. imageBounds.applyTransform (transform);
  62622. float imX, imY, imW, imH;
  62623. imageBounds.getBounds (imX, imY, imW, imH);
  62624. if (Rectangle::intersectRectangles (destClipX, destClipY, destClipW, destClipH,
  62625. (int) floorf (imX),
  62626. (int) floorf (imY),
  62627. 1 + roundDoubleToInt (imW),
  62628. 1 + roundDoubleToInt (imH)))
  62629. {
  62630. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  62631. float srcX1 = (float) destClipX;
  62632. float srcY1 = (float) destClipY;
  62633. float srcX2 = (float) (destClipX + destClipW);
  62634. float srcY2 = srcY1;
  62635. float srcX3 = srcX1;
  62636. float srcY3 = (float) (destClipY + destClipH);
  62637. AffineTransform inverse (transform.inverted());
  62638. inverse.transformPoint (srcX1, srcY1);
  62639. inverse.transformPoint (srcX2, srcY2);
  62640. inverse.transformPoint (srcX3, srcY3);
  62641. const double lineDX = (double) (srcX3 - srcX1) / destClipH;
  62642. const double lineDY = (double) (srcY3 - srcY1) / destClipH;
  62643. const double pixelDX = (double) (srcX2 - srcX1) / destClipW;
  62644. const double pixelDY = (double) (srcY2 - srcY1) / destClipW;
  62645. if (image.getFormat() == Image::ARGB)
  62646. {
  62647. if (sourceImage.getFormat() == Image::ARGB)
  62648. {
  62649. transformedImageRender (image, sourceImage,
  62650. destClipX, destClipY, destClipW, destClipH,
  62651. srcClipX, srcClipY, srcClipW, srcClipH,
  62652. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  62653. alpha, quality, (PixelARGB*)0, (PixelARGB*)0);
  62654. }
  62655. else if (sourceImage.getFormat() == Image::RGB)
  62656. {
  62657. transformedImageRender (image, sourceImage,
  62658. destClipX, destClipY, destClipW, destClipH,
  62659. srcClipX, srcClipY, srcClipW, srcClipH,
  62660. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  62661. alpha, quality, (PixelARGB*)0, (PixelRGB*)0);
  62662. }
  62663. else
  62664. {
  62665. jassertfalse
  62666. }
  62667. }
  62668. else if (image.getFormat() == Image::RGB)
  62669. {
  62670. if (sourceImage.getFormat() == Image::ARGB)
  62671. {
  62672. transformedImageRender (image, sourceImage,
  62673. destClipX, destClipY, destClipW, destClipH,
  62674. srcClipX, srcClipY, srcClipW, srcClipH,
  62675. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  62676. alpha, quality, (PixelRGB*)0, (PixelARGB*)0);
  62677. }
  62678. else if (sourceImage.getFormat() == Image::RGB)
  62679. {
  62680. transformedImageRender (image, sourceImage,
  62681. destClipX, destClipY, destClipW, destClipH,
  62682. srcClipX, srcClipY, srcClipW, srcClipH,
  62683. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  62684. alpha, quality, (PixelRGB*)0, (PixelRGB*)0);
  62685. }
  62686. else
  62687. {
  62688. jassertfalse
  62689. }
  62690. }
  62691. else
  62692. {
  62693. jassertfalse
  62694. }
  62695. }
  62696. }
  62697. }
  62698. void LowLevelGraphicsSoftwareRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  62699. {
  62700. x1 += xOffset;
  62701. y1 += yOffset;
  62702. x2 += xOffset;
  62703. y2 += yOffset;
  62704. for (RectangleList::Iterator i (*clip); i.next();)
  62705. {
  62706. const Rectangle& r = *i.getRectangle();
  62707. clippedDrawLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62708. x1, y1, x2, y2, colour);
  62709. }
  62710. }
  62711. void LowLevelGraphicsSoftwareRenderer::clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour)
  62712. {
  62713. if (clipW > 0 && clipH > 0)
  62714. {
  62715. if (x1 == x2)
  62716. {
  62717. if (y2 < y1)
  62718. swapVariables (y1, y2);
  62719. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (x1), y1, y2, colour);
  62720. }
  62721. else if (y1 == y2)
  62722. {
  62723. if (x2 < x1)
  62724. swapVariables (x1, x2);
  62725. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (y1), x1, x2, colour);
  62726. }
  62727. else
  62728. {
  62729. double gradient = (y2 - y1) / (x2 - x1);
  62730. if (fabs (gradient) > 1.0)
  62731. {
  62732. gradient = 1.0 / gradient;
  62733. int y = roundDoubleToInt (y1);
  62734. const int startY = y;
  62735. int endY = roundDoubleToInt (y2);
  62736. if (y > endY)
  62737. swapVariables (y, endY);
  62738. while (y < endY)
  62739. {
  62740. const double x = x1 + gradient * (y - startY);
  62741. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, y, x, x + 1.0, colour);
  62742. ++y;
  62743. }
  62744. }
  62745. else
  62746. {
  62747. int x = roundDoubleToInt (x1);
  62748. const int startX = x;
  62749. int endX = roundDoubleToInt (x2);
  62750. if (x > endX)
  62751. swapVariables (x, endX);
  62752. while (x < endX)
  62753. {
  62754. const double y = y1 + gradient * (x - startX);
  62755. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, x, y, y + 1.0, colour);
  62756. ++x;
  62757. }
  62758. }
  62759. }
  62760. }
  62761. }
  62762. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  62763. {
  62764. for (RectangleList::Iterator i (*clip); i.next();)
  62765. {
  62766. const Rectangle& r = *i.getRectangle();
  62767. clippedDrawVerticalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62768. x + xOffset, top + yOffset, bottom + yOffset, col);
  62769. }
  62770. }
  62771. void LowLevelGraphicsSoftwareRenderer::clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH,
  62772. const int x, double top, double bottom, const Colour& col)
  62773. {
  62774. jassert (top <= bottom);
  62775. if (((unsigned int) (x - clipX)) < (unsigned int) clipW
  62776. && top < clipY + clipH
  62777. && bottom > clipY
  62778. && clipW > 0)
  62779. {
  62780. if (top < clipY)
  62781. top = clipY;
  62782. if (bottom > clipY + clipH)
  62783. bottom = clipY + clipH;
  62784. if (bottom > top)
  62785. drawVertical (x, top, bottom, col);
  62786. }
  62787. }
  62788. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  62789. {
  62790. for (RectangleList::Iterator i (*clip); i.next();)
  62791. {
  62792. const Rectangle& r = *i.getRectangle();
  62793. clippedDrawHorizontalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62794. y + yOffset, left + xOffset, right + xOffset, col);
  62795. }
  62796. }
  62797. void LowLevelGraphicsSoftwareRenderer::clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH,
  62798. const int y, double left, double right, const Colour& col)
  62799. {
  62800. jassert (left <= right);
  62801. if (((unsigned int) (y - clipY)) < (unsigned int) clipH
  62802. && left < clipX + clipW
  62803. && right > clipX
  62804. && clipW > 0)
  62805. {
  62806. if (left < clipX)
  62807. left = clipX;
  62808. if (right > clipX + clipW)
  62809. right = clipX + clipW;
  62810. if (right > left)
  62811. drawHorizontal (y, left, right, col);
  62812. }
  62813. }
  62814. void LowLevelGraphicsSoftwareRenderer::drawVertical (const int x,
  62815. const double top,
  62816. const double bottom,
  62817. const Colour& col)
  62818. {
  62819. int wholeStart = (int) top;
  62820. const int wholeEnd = (int) bottom;
  62821. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  62822. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  62823. if (totalPixels <= 0)
  62824. return;
  62825. int lineStride, dstPixelStride;
  62826. uint8* const dstPixels = image.lockPixelDataReadWrite (x, wholeStart, 1, totalPixels, lineStride, dstPixelStride);
  62827. uint8* dest = dstPixels;
  62828. PixelARGB colour (col.getPixelARGB());
  62829. if (wholeEnd == wholeStart)
  62830. {
  62831. if (image.getFormat() == Image::ARGB)
  62832. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62833. else if (image.getFormat() == Image::RGB)
  62834. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62835. else
  62836. {
  62837. jassertfalse
  62838. }
  62839. }
  62840. else
  62841. {
  62842. if (image.getFormat() == Image::ARGB)
  62843. {
  62844. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62845. ++wholeStart;
  62846. dest += lineStride;
  62847. if (colour.getAlpha() == 0xff)
  62848. {
  62849. while (wholeEnd > wholeStart)
  62850. {
  62851. ((PixelARGB*) dest)->set (colour);
  62852. ++wholeStart;
  62853. dest += lineStride;
  62854. }
  62855. }
  62856. else
  62857. {
  62858. while (wholeEnd > wholeStart)
  62859. {
  62860. ((PixelARGB*) dest)->blend (colour);
  62861. ++wholeStart;
  62862. dest += lineStride;
  62863. }
  62864. }
  62865. if (lastAlpha > 0)
  62866. {
  62867. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  62868. }
  62869. }
  62870. else if (image.getFormat() == Image::RGB)
  62871. {
  62872. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62873. ++wholeStart;
  62874. dest += lineStride;
  62875. if (colour.getAlpha() == 0xff)
  62876. {
  62877. while (wholeEnd > wholeStart)
  62878. {
  62879. ((PixelRGB*) dest)->set (colour);
  62880. ++wholeStart;
  62881. dest += lineStride;
  62882. }
  62883. }
  62884. else
  62885. {
  62886. while (wholeEnd > wholeStart)
  62887. {
  62888. ((PixelRGB*) dest)->blend (colour);
  62889. ++wholeStart;
  62890. dest += lineStride;
  62891. }
  62892. }
  62893. if (lastAlpha > 0)
  62894. {
  62895. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  62896. }
  62897. }
  62898. else
  62899. {
  62900. jassertfalse
  62901. }
  62902. }
  62903. image.releasePixelDataReadWrite (dstPixels);
  62904. }
  62905. void LowLevelGraphicsSoftwareRenderer::drawHorizontal (const int y,
  62906. const double top,
  62907. const double bottom,
  62908. const Colour& col)
  62909. {
  62910. int wholeStart = (int) top;
  62911. const int wholeEnd = (int) bottom;
  62912. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  62913. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  62914. if (totalPixels <= 0)
  62915. return;
  62916. int lineStride, dstPixelStride;
  62917. uint8* const dstPixels = image.lockPixelDataReadWrite (wholeStart, y, totalPixels, 1, lineStride, dstPixelStride);
  62918. uint8* dest = dstPixels;
  62919. PixelARGB colour (col.getPixelARGB());
  62920. if (wholeEnd == wholeStart)
  62921. {
  62922. if (image.getFormat() == Image::ARGB)
  62923. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62924. else if (image.getFormat() == Image::RGB)
  62925. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62926. else
  62927. {
  62928. jassertfalse
  62929. }
  62930. }
  62931. else
  62932. {
  62933. if (image.getFormat() == Image::ARGB)
  62934. {
  62935. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62936. dest += dstPixelStride;
  62937. ++wholeStart;
  62938. if (colour.getAlpha() == 0xff)
  62939. {
  62940. while (wholeEnd > wholeStart)
  62941. {
  62942. ((PixelARGB*) dest)->set (colour);
  62943. dest += dstPixelStride;
  62944. ++wholeStart;
  62945. }
  62946. }
  62947. else
  62948. {
  62949. while (wholeEnd > wholeStart)
  62950. {
  62951. ((PixelARGB*) dest)->blend (colour);
  62952. dest += dstPixelStride;
  62953. ++wholeStart;
  62954. }
  62955. }
  62956. if (lastAlpha > 0)
  62957. {
  62958. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  62959. }
  62960. }
  62961. else if (image.getFormat() == Image::RGB)
  62962. {
  62963. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62964. dest += dstPixelStride;
  62965. ++wholeStart;
  62966. if (colour.getAlpha() == 0xff)
  62967. {
  62968. while (wholeEnd > wholeStart)
  62969. {
  62970. ((PixelRGB*) dest)->set (colour);
  62971. dest += dstPixelStride;
  62972. ++wholeStart;
  62973. }
  62974. }
  62975. else
  62976. {
  62977. while (wholeEnd > wholeStart)
  62978. {
  62979. ((PixelRGB*) dest)->blend (colour);
  62980. dest += dstPixelStride;
  62981. ++wholeStart;
  62982. }
  62983. }
  62984. if (lastAlpha > 0)
  62985. {
  62986. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  62987. }
  62988. }
  62989. else
  62990. {
  62991. jassertfalse
  62992. }
  62993. }
  62994. image.releasePixelDataReadWrite (dstPixels);
  62995. }
  62996. END_JUCE_NAMESPACE
  62997. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  62998. /********* Start of inlined file: juce_RectanglePlacement.cpp *********/
  62999. BEGIN_JUCE_NAMESPACE
  63000. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  63001. : flags (other.flags)
  63002. {
  63003. }
  63004. const RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  63005. {
  63006. flags = other.flags;
  63007. return *this;
  63008. }
  63009. void RectanglePlacement::applyTo (double& x, double& y,
  63010. double& w, double& h,
  63011. const double dx, const double dy,
  63012. const double dw, const double dh) const throw()
  63013. {
  63014. if (w == 0 || h == 0)
  63015. return;
  63016. if ((flags & stretchToFit) != 0)
  63017. {
  63018. x = dx;
  63019. y = dy;
  63020. w = dw;
  63021. h = dh;
  63022. }
  63023. else
  63024. {
  63025. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  63026. : jmin (dw / w, dh / h);
  63027. if ((flags & onlyReduceInSize) != 0)
  63028. scale = jmin (scale, 1.0);
  63029. if ((flags & onlyIncreaseInSize) != 0)
  63030. scale = jmax (scale, 1.0);
  63031. w *= scale;
  63032. h *= scale;
  63033. if ((flags & xLeft) != 0)
  63034. x = dx;
  63035. else if ((flags & xRight) != 0)
  63036. x = dx + dw - w;
  63037. else
  63038. x = dx + (dw - w) * 0.5;
  63039. if ((flags & yTop) != 0)
  63040. y = dy;
  63041. else if ((flags & yBottom) != 0)
  63042. y = dy + dh - h;
  63043. else
  63044. y = dy + (dh - h) * 0.5;
  63045. }
  63046. }
  63047. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  63048. float w, float h,
  63049. const float dx, const float dy,
  63050. const float dw, const float dh) const throw()
  63051. {
  63052. if (w == 0 || h == 0)
  63053. return AffineTransform::identity;
  63054. const float scaleX = dw / w;
  63055. const float scaleY = dh / h;
  63056. if ((flags & stretchToFit) != 0)
  63057. {
  63058. return AffineTransform::translation (-x, -y)
  63059. .scaled (scaleX, scaleY)
  63060. .translated (dx - x, dy - y);
  63061. }
  63062. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  63063. : jmin (scaleX, scaleY);
  63064. if ((flags & onlyReduceInSize) != 0)
  63065. scale = jmin (scale, 1.0f);
  63066. if ((flags & onlyIncreaseInSize) != 0)
  63067. scale = jmax (scale, 1.0f);
  63068. w *= scale;
  63069. h *= scale;
  63070. float newX = dx;
  63071. if ((flags & xRight) != 0)
  63072. newX += dw - w; // right
  63073. else if ((flags & xLeft) == 0)
  63074. newX += (dw - w) / 2.0f; // centre
  63075. float newY = dy;
  63076. if ((flags & yBottom) != 0)
  63077. newY += dh - h; // bottom
  63078. else if ((flags & yTop) == 0)
  63079. newY += (dh - h) / 2.0f; // centre
  63080. return AffineTransform::translation (-x, -y)
  63081. .scaled (scale, scale)
  63082. .translated (newX, newY);
  63083. }
  63084. END_JUCE_NAMESPACE
  63085. /********* End of inlined file: juce_RectanglePlacement.cpp *********/
  63086. /********* Start of inlined file: juce_Drawable.cpp *********/
  63087. BEGIN_JUCE_NAMESPACE
  63088. Drawable::Drawable()
  63089. {
  63090. }
  63091. Drawable::~Drawable()
  63092. {
  63093. }
  63094. void Drawable::drawAt (Graphics& g, const float x, const float y) const
  63095. {
  63096. draw (g, AffineTransform::translation (x, y));
  63097. }
  63098. void Drawable::drawWithin (Graphics& g,
  63099. const int destX,
  63100. const int destY,
  63101. const int destW,
  63102. const int destH,
  63103. const RectanglePlacement& placement) const
  63104. {
  63105. if (destW > 0 && destH > 0)
  63106. {
  63107. float x, y, w, h;
  63108. getBounds (x, y, w, h);
  63109. draw (g, placement.getTransformToFit (x, y, w, h,
  63110. (float) destX, (float) destY,
  63111. (float) destW, (float) destH));
  63112. }
  63113. }
  63114. Drawable* Drawable::createFromImageData (const void* data, const int numBytes)
  63115. {
  63116. Drawable* result = 0;
  63117. Image* const image = ImageFileFormat::loadFrom (data, numBytes);
  63118. if (image != 0)
  63119. {
  63120. DrawableImage* const di = new DrawableImage();
  63121. di->setImage (image, true);
  63122. result = di;
  63123. }
  63124. else
  63125. {
  63126. const String asString (String::createStringFromData (data, numBytes));
  63127. XmlDocument doc (asString);
  63128. XmlElement* const outer = doc.getDocumentElement (true);
  63129. if (outer != 0 && outer->hasTagName (T("svg")))
  63130. {
  63131. XmlElement* const svg = doc.getDocumentElement();
  63132. if (svg != 0)
  63133. {
  63134. result = Drawable::createFromSVG (*svg);
  63135. delete svg;
  63136. }
  63137. }
  63138. delete outer;
  63139. }
  63140. return result;
  63141. }
  63142. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  63143. {
  63144. MemoryBlock mb;
  63145. dataSource.readIntoMemoryBlock (mb);
  63146. return createFromImageData (mb.getData(), mb.getSize());
  63147. }
  63148. Drawable* Drawable::createFromImageFile (const File& file)
  63149. {
  63150. FileInputStream* fin = file.createInputStream();
  63151. if (fin == 0)
  63152. return 0;
  63153. Drawable* d = createFromImageDataStream (*fin);
  63154. delete fin;
  63155. return d;
  63156. }
  63157. END_JUCE_NAMESPACE
  63158. /********* End of inlined file: juce_Drawable.cpp *********/
  63159. /********* Start of inlined file: juce_DrawableComposite.cpp *********/
  63160. BEGIN_JUCE_NAMESPACE
  63161. DrawableComposite::DrawableComposite()
  63162. {
  63163. }
  63164. DrawableComposite::~DrawableComposite()
  63165. {
  63166. }
  63167. void DrawableComposite::insertDrawable (Drawable* drawable,
  63168. const AffineTransform& transform,
  63169. const int index)
  63170. {
  63171. if (drawable != 0)
  63172. {
  63173. if (! drawables.contains (drawable))
  63174. {
  63175. drawables.insert (index, drawable);
  63176. if (transform.isIdentity())
  63177. transforms.insert (index, 0);
  63178. else
  63179. transforms.insert (index, new AffineTransform (transform));
  63180. }
  63181. else
  63182. {
  63183. jassertfalse // trying to add a drawable that's already in here!
  63184. }
  63185. }
  63186. }
  63187. void DrawableComposite::insertDrawable (const Drawable& drawable,
  63188. const AffineTransform& transform,
  63189. const int index)
  63190. {
  63191. insertDrawable (drawable.createCopy(), transform, index);
  63192. }
  63193. void DrawableComposite::removeDrawable (const int index)
  63194. {
  63195. drawables.remove (index);
  63196. transforms.remove (index);
  63197. }
  63198. void DrawableComposite::bringToFront (const int index)
  63199. {
  63200. if (index >= 0 && index < drawables.size() - 1)
  63201. {
  63202. drawables.move (index, -1);
  63203. transforms.move (index, -1);
  63204. }
  63205. }
  63206. void DrawableComposite::draw (Graphics& g, const AffineTransform& transform) const
  63207. {
  63208. for (int i = 0; i < drawables.size(); ++i)
  63209. {
  63210. const AffineTransform* const t = transforms.getUnchecked(i);
  63211. drawables.getUnchecked(i)->draw (g, t == 0 ? transform
  63212. : t->followedBy (transform));
  63213. }
  63214. }
  63215. void DrawableComposite::getBounds (float& x, float& y, float& width, float& height) const
  63216. {
  63217. Path totalPath;
  63218. for (int i = 0; i < drawables.size(); ++i)
  63219. {
  63220. drawables.getUnchecked(i)->getBounds (x, y, width, height);
  63221. if (width > 0.0f && height > 0.0f)
  63222. {
  63223. Path outline;
  63224. outline.addRectangle (x, y, width, height);
  63225. const AffineTransform* const t = transforms.getUnchecked(i);
  63226. if (t == 0)
  63227. totalPath.addPath (outline);
  63228. else
  63229. totalPath.addPath (outline, *t);
  63230. }
  63231. }
  63232. totalPath.getBounds (x, y, width, height);
  63233. }
  63234. bool DrawableComposite::hitTest (float x, float y) const
  63235. {
  63236. for (int i = 0; i < drawables.size(); ++i)
  63237. {
  63238. float tx = x;
  63239. float ty = y;
  63240. const AffineTransform* const t = transforms.getUnchecked(i);
  63241. if (t != 0)
  63242. t->inverted().transformPoint (tx, ty);
  63243. if (drawables.getUnchecked(i)->hitTest (tx, ty))
  63244. return true;
  63245. }
  63246. return false;
  63247. }
  63248. Drawable* DrawableComposite::createCopy() const
  63249. {
  63250. DrawableComposite* const dc = new DrawableComposite();
  63251. for (int i = 0; i < drawables.size(); ++i)
  63252. {
  63253. dc->drawables.add (drawables.getUnchecked(i)->createCopy());
  63254. const AffineTransform* const t = transforms.getUnchecked(i);
  63255. dc->transforms.add (t != 0 ? new AffineTransform (*t) : 0);
  63256. }
  63257. return dc;
  63258. }
  63259. END_JUCE_NAMESPACE
  63260. /********* End of inlined file: juce_DrawableComposite.cpp *********/
  63261. /********* Start of inlined file: juce_DrawableImage.cpp *********/
  63262. BEGIN_JUCE_NAMESPACE
  63263. DrawableImage::DrawableImage()
  63264. : image (0),
  63265. canDeleteImage (false),
  63266. opacity (1.0f),
  63267. overlayColour (0x00000000)
  63268. {
  63269. }
  63270. DrawableImage::~DrawableImage()
  63271. {
  63272. clearImage();
  63273. }
  63274. void DrawableImage::clearImage()
  63275. {
  63276. if (canDeleteImage && image != 0)
  63277. {
  63278. if (ImageCache::isImageInCache (image))
  63279. ImageCache::release (image);
  63280. else
  63281. delete image;
  63282. }
  63283. image = 0;
  63284. }
  63285. void DrawableImage::setImage (const Image& imageToCopy)
  63286. {
  63287. clearImage();
  63288. image = new Image (imageToCopy);
  63289. canDeleteImage = true;
  63290. }
  63291. void DrawableImage::setImage (Image* imageToUse,
  63292. const bool releaseWhenNotNeeded)
  63293. {
  63294. clearImage();
  63295. image = imageToUse;
  63296. canDeleteImage = releaseWhenNotNeeded;
  63297. }
  63298. void DrawableImage::setOpacity (const float newOpacity)
  63299. {
  63300. opacity = newOpacity;
  63301. }
  63302. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  63303. {
  63304. overlayColour = newOverlayColour;
  63305. }
  63306. void DrawableImage::draw (Graphics& g, const AffineTransform& transform) const
  63307. {
  63308. if (image != 0)
  63309. {
  63310. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  63311. if (opacity > 0.0f && ! overlayColour.isOpaque())
  63312. {
  63313. g.setColour (oldColour.withMultipliedAlpha (opacity));
  63314. g.drawImageTransformed (image,
  63315. 0, 0, image->getWidth(), image->getHeight(),
  63316. transform, false);
  63317. }
  63318. if (! overlayColour.isTransparent())
  63319. {
  63320. g.setColour (overlayColour.withMultipliedAlpha (oldColour.getFloatAlpha()));
  63321. g.drawImageTransformed (image,
  63322. 0, 0, image->getWidth(), image->getHeight(),
  63323. transform, true);
  63324. }
  63325. g.setColour (oldColour);
  63326. }
  63327. }
  63328. void DrawableImage::getBounds (float& x, float& y, float& width, float& height) const
  63329. {
  63330. x = 0.0f;
  63331. y = 0.0f;
  63332. width = 0.0f;
  63333. height = 0.0f;
  63334. if (image != 0)
  63335. {
  63336. width = (float) image->getWidth();
  63337. height = (float) image->getHeight();
  63338. }
  63339. }
  63340. bool DrawableImage::hitTest (float x, float y) const
  63341. {
  63342. return image != 0
  63343. && x >= 0.0f
  63344. && y >= 0.0f
  63345. && x < image->getWidth()
  63346. && y < image->getHeight()
  63347. && image->getPixelAt (roundFloatToInt (x), roundFloatToInt (y)).getAlpha() >= 127;
  63348. }
  63349. Drawable* DrawableImage::createCopy() const
  63350. {
  63351. DrawableImage* const di = new DrawableImage();
  63352. di->opacity = opacity;
  63353. di->overlayColour = overlayColour;
  63354. if (image != 0)
  63355. {
  63356. if ((! canDeleteImage) || ! ImageCache::isImageInCache (image))
  63357. {
  63358. di->setImage (*image);
  63359. }
  63360. else
  63361. {
  63362. ImageCache::incReferenceCount (image);
  63363. di->setImage (image, true);
  63364. }
  63365. }
  63366. return di;
  63367. }
  63368. END_JUCE_NAMESPACE
  63369. /********* End of inlined file: juce_DrawableImage.cpp *********/
  63370. /********* Start of inlined file: juce_DrawablePath.cpp *********/
  63371. BEGIN_JUCE_NAMESPACE
  63372. DrawablePath::DrawablePath()
  63373. : fillBrush (new SolidColourBrush (Colours::black)),
  63374. strokeBrush (0),
  63375. strokeType (0.0f)
  63376. {
  63377. }
  63378. DrawablePath::~DrawablePath()
  63379. {
  63380. delete fillBrush;
  63381. delete strokeBrush;
  63382. }
  63383. void DrawablePath::setPath (const Path& newPath)
  63384. {
  63385. path = newPath;
  63386. updateOutline();
  63387. }
  63388. void DrawablePath::setSolidFill (const Colour& newColour)
  63389. {
  63390. delete fillBrush;
  63391. fillBrush = new SolidColourBrush (newColour);
  63392. }
  63393. void DrawablePath::setFillBrush (const Brush& newBrush)
  63394. {
  63395. delete fillBrush;
  63396. fillBrush = newBrush.createCopy();
  63397. }
  63398. void DrawablePath::setOutline (const float thickness, const Colour& colour)
  63399. {
  63400. strokeType = PathStrokeType (thickness);
  63401. delete strokeBrush;
  63402. strokeBrush = new SolidColourBrush (colour);
  63403. updateOutline();
  63404. }
  63405. void DrawablePath::setOutline (const PathStrokeType& strokeType_, const Brush& newStrokeBrush)
  63406. {
  63407. strokeType = strokeType_;
  63408. delete strokeBrush;
  63409. strokeBrush = newStrokeBrush.createCopy();
  63410. updateOutline();
  63411. }
  63412. void DrawablePath::draw (Graphics& g, const AffineTransform& transform) const
  63413. {
  63414. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  63415. const float currentOpacity = oldColour.getFloatAlpha();
  63416. {
  63417. Brush* const tempBrush = fillBrush->createCopy();
  63418. tempBrush->applyTransform (transform);
  63419. tempBrush->multiplyOpacity (currentOpacity);
  63420. g.setBrush (tempBrush);
  63421. g.fillPath (path, transform);
  63422. delete tempBrush;
  63423. }
  63424. if (strokeBrush != 0 && strokeType.getStrokeThickness() > 0.0f)
  63425. {
  63426. Brush* const tempBrush = strokeBrush->createCopy();
  63427. tempBrush->applyTransform (transform);
  63428. tempBrush->multiplyOpacity (currentOpacity);
  63429. g.setBrush (tempBrush);
  63430. g.fillPath (outline, transform);
  63431. delete tempBrush;
  63432. }
  63433. g.setColour (oldColour);
  63434. }
  63435. void DrawablePath::updateOutline()
  63436. {
  63437. outline.clear();
  63438. strokeType.createStrokedPath (outline, path, AffineTransform::identity, 4.0f);
  63439. }
  63440. void DrawablePath::getBounds (float& x, float& y, float& width, float& height) const
  63441. {
  63442. if (strokeType.getStrokeThickness() > 0.0f)
  63443. outline.getBounds (x, y, width, height);
  63444. else
  63445. path.getBounds (x, y, width, height);
  63446. }
  63447. bool DrawablePath::hitTest (float x, float y) const
  63448. {
  63449. return path.contains (x, y)
  63450. || outline.contains (x, y);
  63451. }
  63452. Drawable* DrawablePath::createCopy() const
  63453. {
  63454. DrawablePath* const dp = new DrawablePath();
  63455. dp->path = path;
  63456. dp->setFillBrush (*fillBrush);
  63457. if (strokeBrush != 0)
  63458. dp->setOutline (strokeType, *strokeBrush);
  63459. return dp;
  63460. }
  63461. END_JUCE_NAMESPACE
  63462. /********* End of inlined file: juce_DrawablePath.cpp *********/
  63463. /********* Start of inlined file: juce_DrawableText.cpp *********/
  63464. BEGIN_JUCE_NAMESPACE
  63465. DrawableText::DrawableText()
  63466. : colour (Colours::white)
  63467. {
  63468. }
  63469. DrawableText::~DrawableText()
  63470. {
  63471. }
  63472. void DrawableText::setText (const GlyphArrangement& newText)
  63473. {
  63474. text = newText;
  63475. }
  63476. void DrawableText::setText (const String& newText, const Font& fontToUse)
  63477. {
  63478. text.clear();
  63479. text.addLineOfText (fontToUse, newText, 0.0f, 0.0f);
  63480. }
  63481. void DrawableText::setColour (const Colour& newColour)
  63482. {
  63483. colour = newColour;
  63484. }
  63485. void DrawableText::draw (Graphics& g, const AffineTransform& transform) const
  63486. {
  63487. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  63488. g.setColour (colour.withMultipliedAlpha (oldColour.getFloatAlpha()));
  63489. text.draw (g, transform);
  63490. g.setColour (oldColour);
  63491. }
  63492. void DrawableText::getBounds (float& x, float& y, float& width, float& height) const
  63493. {
  63494. text.getBoundingBox (0, -1, x, y, width, height, false); // (really returns top, left, bottom, right)
  63495. width -= x;
  63496. height -= y;
  63497. }
  63498. bool DrawableText::hitTest (float x, float y) const
  63499. {
  63500. return text.findGlyphIndexAt (x, y) >= 0;
  63501. }
  63502. Drawable* DrawableText::createCopy() const
  63503. {
  63504. DrawableText* const dt = new DrawableText();
  63505. dt->text = text;
  63506. dt->colour = colour;
  63507. return dt;
  63508. }
  63509. END_JUCE_NAMESPACE
  63510. /********* End of inlined file: juce_DrawableText.cpp *********/
  63511. /********* Start of inlined file: juce_SVGParser.cpp *********/
  63512. BEGIN_JUCE_NAMESPACE
  63513. class SVGState
  63514. {
  63515. public:
  63516. SVGState (const XmlElement* const topLevel)
  63517. : topLevelXml (topLevel),
  63518. x (0), y (0),
  63519. width (512), height (512),
  63520. viewBoxW (0), viewBoxH (0)
  63521. {
  63522. }
  63523. ~SVGState()
  63524. {
  63525. }
  63526. Drawable* parseSVGElement (const XmlElement& xml)
  63527. {
  63528. if (! xml.hasTagName (T("svg")))
  63529. return 0;
  63530. DrawableComposite* const drawable = new DrawableComposite();
  63531. drawable->setName (xml.getStringAttribute (T("id")));
  63532. SVGState newState (*this);
  63533. if (xml.hasAttribute (T("transform")))
  63534. newState.addTransform (xml);
  63535. newState.x = getCoordLength (xml.getStringAttribute (T("x"), String (newState.x)), viewBoxW);
  63536. newState.y = getCoordLength (xml.getStringAttribute (T("y"), String (newState.y)), viewBoxH);
  63537. newState.width = getCoordLength (xml.getStringAttribute (T("width"), String (newState.width)), viewBoxW);
  63538. newState.height = getCoordLength (xml.getStringAttribute (T("height"), String (newState.height)), viewBoxH);
  63539. if (xml.hasAttribute (T("viewBox")))
  63540. {
  63541. const String viewParams (xml.getStringAttribute (T("viewBox")));
  63542. int i = 0;
  63543. float vx, vy, vw, vh;
  63544. if (parseCoords (viewParams, vx, vy, i, true)
  63545. && parseCoords (viewParams, vw, vh, i, true)
  63546. && vw > 0
  63547. && vh > 0)
  63548. {
  63549. newState.viewBoxW = vw;
  63550. newState.viewBoxH = vh;
  63551. int placementFlags = 0;
  63552. const String aspect (xml.getStringAttribute (T("preserveAspectRatio")));
  63553. if (aspect.containsIgnoreCase (T("none")))
  63554. {
  63555. placementFlags = RectanglePlacement::stretchToFit;
  63556. }
  63557. else
  63558. {
  63559. if (aspect.containsIgnoreCase (T("slice")))
  63560. placementFlags |= RectanglePlacement::fillDestination;
  63561. if (aspect.containsIgnoreCase (T("xMin")))
  63562. placementFlags |= RectanglePlacement::xLeft;
  63563. else if (aspect.containsIgnoreCase (T("xMax")))
  63564. placementFlags |= RectanglePlacement::xRight;
  63565. else
  63566. placementFlags |= RectanglePlacement::xMid;
  63567. if (aspect.containsIgnoreCase (T("yMin")))
  63568. placementFlags |= RectanglePlacement::yTop;
  63569. else if (aspect.containsIgnoreCase (T("yMax")))
  63570. placementFlags |= RectanglePlacement::yBottom;
  63571. else
  63572. placementFlags |= RectanglePlacement::yMid;
  63573. }
  63574. const RectanglePlacement placement (placementFlags);
  63575. newState.transform
  63576. = placement.getTransformToFit (vx, vy, vw, vh,
  63577. 0.0f, 0.0f, newState.width, newState.height)
  63578. .followedBy (newState.transform);
  63579. }
  63580. }
  63581. else
  63582. {
  63583. if (viewBoxW == 0)
  63584. newState.viewBoxW = newState.width;
  63585. if (viewBoxH == 0)
  63586. newState.viewBoxH = newState.height;
  63587. }
  63588. newState.parseSubElements (xml, drawable);
  63589. return drawable;
  63590. }
  63591. private:
  63592. const XmlElement* const topLevelXml;
  63593. float x, y, width, height, viewBoxW, viewBoxH;
  63594. AffineTransform transform;
  63595. String cssStyleText;
  63596. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  63597. {
  63598. forEachXmlChildElement (xml, e)
  63599. {
  63600. Drawable* d = 0;
  63601. if (e->hasTagName (T("g")))
  63602. d = parseGroupElement (*e);
  63603. else if (e->hasTagName (T("svg")))
  63604. d = parseSVGElement (*e);
  63605. else if (e->hasTagName (T("path")))
  63606. d = parsePath (*e);
  63607. else if (e->hasTagName (T("rect")))
  63608. d = parseRect (*e);
  63609. else if (e->hasTagName (T("circle")))
  63610. d = parseCircle (*e);
  63611. else if (e->hasTagName (T("ellipse")))
  63612. d = parseEllipse (*e);
  63613. else if (e->hasTagName (T("line")))
  63614. d = parseLine (*e);
  63615. else if (e->hasTagName (T("polyline")))
  63616. d = parsePolygon (*e, true);
  63617. else if (e->hasTagName (T("polygon")))
  63618. d = parsePolygon (*e, false);
  63619. else if (e->hasTagName (T("text")))
  63620. d = parseText (*e);
  63621. else if (e->hasTagName (T("switch")))
  63622. d = parseSwitch (*e);
  63623. else if (e->hasTagName (T("style")))
  63624. parseCSSStyle (*e);
  63625. parentDrawable->insertDrawable (d);
  63626. }
  63627. }
  63628. DrawableComposite* parseSwitch (const XmlElement& xml)
  63629. {
  63630. const XmlElement* const group = xml.getChildByName (T("g"));
  63631. if (group != 0)
  63632. return parseGroupElement (*group);
  63633. return 0;
  63634. }
  63635. DrawableComposite* parseGroupElement (const XmlElement& xml)
  63636. {
  63637. DrawableComposite* const drawable = new DrawableComposite();
  63638. drawable->setName (xml.getStringAttribute (T("id")));
  63639. if (xml.hasAttribute (T("transform")))
  63640. {
  63641. SVGState newState (*this);
  63642. newState.addTransform (xml);
  63643. newState.parseSubElements (xml, drawable);
  63644. }
  63645. else
  63646. {
  63647. parseSubElements (xml, drawable);
  63648. }
  63649. return drawable;
  63650. }
  63651. Drawable* parsePath (const XmlElement& xml) const
  63652. {
  63653. const String d (xml.getStringAttribute (T("d")).trimStart());
  63654. Path path;
  63655. if (getStyleAttribute (&xml, T("fill-rule")).trim().equalsIgnoreCase (T("evenodd")))
  63656. path.setUsingNonZeroWinding (false);
  63657. int index = 0;
  63658. float lastX = 0, lastY = 0;
  63659. float lastX2 = 0, lastY2 = 0;
  63660. tchar lastCommandChar = 0;
  63661. bool carryOn = true;
  63662. const String validCommandChars (T("MmLlHhVvCcSsQqTtAaZz"));
  63663. for (;;)
  63664. {
  63665. float x, y, x2, y2, x3, y3;
  63666. const bool isRelative = (d[index] >= 'a' && d[index] <= 'z');
  63667. if (validCommandChars.containsChar (d[index]))
  63668. lastCommandChar = d [index++];
  63669. switch (lastCommandChar)
  63670. {
  63671. case T('M'):
  63672. case T('m'):
  63673. case T('L'):
  63674. case T('l'):
  63675. if (parseCoords (d, x, y, index, false))
  63676. {
  63677. if (isRelative)
  63678. {
  63679. x += lastX;
  63680. y += lastY;
  63681. }
  63682. if (lastCommandChar == T('M') || lastCommandChar == T('m'))
  63683. path.startNewSubPath (x, y);
  63684. else
  63685. path.lineTo (x, y);
  63686. lastX2 = lastX;
  63687. lastY2 = lastY;
  63688. lastX = x;
  63689. lastY = y;
  63690. }
  63691. else
  63692. {
  63693. ++index;
  63694. }
  63695. break;
  63696. case T('H'):
  63697. case T('h'):
  63698. if (parseCoord (d, x, index, false, true))
  63699. {
  63700. if (isRelative)
  63701. x += lastX;
  63702. path.lineTo (x, lastY);
  63703. lastX2 = lastX;
  63704. lastX = x;
  63705. }
  63706. else
  63707. {
  63708. ++index;
  63709. }
  63710. break;
  63711. case T('V'):
  63712. case T('v'):
  63713. if (parseCoord (d, y, index, false, false))
  63714. {
  63715. if (isRelative)
  63716. y += lastY;
  63717. path.lineTo (lastX, y);
  63718. lastY2 = lastY;
  63719. lastY = y;
  63720. }
  63721. else
  63722. {
  63723. ++index;
  63724. }
  63725. break;
  63726. case T('C'):
  63727. case T('c'):
  63728. if (parseCoords (d, x, y, index, false)
  63729. && parseCoords (d, x2, y2, index, false)
  63730. && parseCoords (d, x3, y3, index, false))
  63731. {
  63732. if (isRelative)
  63733. {
  63734. x += lastX;
  63735. y += lastY;
  63736. x2 += lastX;
  63737. y2 += lastY;
  63738. x3 += lastX;
  63739. y3 += lastY;
  63740. }
  63741. path.cubicTo (x, y, x2, y2, x3, y3);
  63742. lastX2 = x2;
  63743. lastY2 = y2;
  63744. lastX = x3;
  63745. lastY = y3;
  63746. }
  63747. else
  63748. {
  63749. ++index;
  63750. }
  63751. break;
  63752. case T('S'):
  63753. case T('s'):
  63754. if (parseCoords (d, x, y, index, false)
  63755. && parseCoords (d, x3, y3, index, false))
  63756. {
  63757. if (isRelative)
  63758. {
  63759. x += lastX;
  63760. y += lastY;
  63761. x3 += lastX;
  63762. y3 += lastY;
  63763. }
  63764. x2 = lastX + (lastX - lastX2);
  63765. y2 = lastY + (lastY - lastY2);
  63766. path.cubicTo (x2, y2, x, y, x3, y3);
  63767. lastX2 = x2;
  63768. lastY2 = y2;
  63769. lastX = x3;
  63770. lastY = y3;
  63771. }
  63772. else
  63773. {
  63774. ++index;
  63775. }
  63776. break;
  63777. case T('Q'):
  63778. case T('q'):
  63779. if (parseCoords (d, x, y, index, false)
  63780. && parseCoords (d, x2, y2, index, false))
  63781. {
  63782. if (isRelative)
  63783. {
  63784. x += lastX;
  63785. y += lastY;
  63786. x2 += lastX;
  63787. y2 += lastY;
  63788. }
  63789. path.quadraticTo (x, y, x2, y2);
  63790. lastX2 = x;
  63791. lastY2 = y;
  63792. lastX = x2;
  63793. lastY = y2;
  63794. }
  63795. else
  63796. {
  63797. ++index;
  63798. }
  63799. break;
  63800. case T('T'):
  63801. case T('t'):
  63802. if (parseCoords (d, x, y, index, false))
  63803. {
  63804. if (isRelative)
  63805. {
  63806. x += lastX;
  63807. y += lastY;
  63808. }
  63809. x2 = lastX + (lastX - lastX2);
  63810. y2 = lastY + (lastY - lastY2);
  63811. path.quadraticTo (x2, y2, x, y);
  63812. lastX2 = x2;
  63813. lastY2 = y2;
  63814. lastX = x;
  63815. lastY = y;
  63816. }
  63817. else
  63818. {
  63819. ++index;
  63820. }
  63821. break;
  63822. case T('A'):
  63823. case T('a'):
  63824. if (parseCoords (d, x, y, index, false))
  63825. {
  63826. String num;
  63827. if (parseNextNumber (d, num, index, false))
  63828. {
  63829. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  63830. if (parseNextNumber (d, num, index, false))
  63831. {
  63832. const bool largeArc = num.getIntValue() != 0;
  63833. if (parseNextNumber (d, num, index, false))
  63834. {
  63835. const bool sweep = num.getIntValue() != 0;
  63836. if (parseCoords (d, x2, y2, index, false))
  63837. {
  63838. if (isRelative)
  63839. {
  63840. x2 += lastX;
  63841. y2 += lastY;
  63842. }
  63843. if (lastX != x2 || lastY != y2)
  63844. {
  63845. double centreX, centreY, startAngle, deltaAngle;
  63846. double rx = x, ry = y;
  63847. endpointToCentreParameters (lastX, lastY, x2, y2,
  63848. angle, largeArc, sweep,
  63849. rx, ry, centreX, centreY,
  63850. startAngle, deltaAngle);
  63851. path.addCentredArc ((float) centreX, (float) centreY,
  63852. (float) rx, (float) ry,
  63853. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  63854. false);
  63855. path.lineTo (x2, y2);
  63856. }
  63857. lastX2 = lastX;
  63858. lastY2 = lastY;
  63859. lastX = x2;
  63860. lastY = y2;
  63861. }
  63862. }
  63863. }
  63864. }
  63865. }
  63866. else
  63867. {
  63868. ++index;
  63869. }
  63870. break;
  63871. case T('Z'):
  63872. case T('z'):
  63873. path.closeSubPath();
  63874. while (CharacterFunctions::isWhitespace (d [index]))
  63875. ++index;
  63876. break;
  63877. default:
  63878. carryOn = false;
  63879. break;
  63880. }
  63881. if (! carryOn)
  63882. break;
  63883. }
  63884. return parseShape (xml, path);
  63885. }
  63886. Drawable* parseRect (const XmlElement& xml) const
  63887. {
  63888. Path rect;
  63889. const bool hasRX = xml.hasAttribute (T("rx"));
  63890. const bool hasRY = xml.hasAttribute (T("ry"));
  63891. if (hasRX || hasRY)
  63892. {
  63893. float rx = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  63894. float ry = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  63895. if (! hasRX)
  63896. rx = ry;
  63897. else if (! hasRY)
  63898. ry = rx;
  63899. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  63900. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  63901. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  63902. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH),
  63903. rx, ry);
  63904. }
  63905. else
  63906. {
  63907. rect.addRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  63908. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  63909. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  63910. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH));
  63911. }
  63912. return parseShape (xml, rect);
  63913. }
  63914. Drawable* parseCircle (const XmlElement& xml) const
  63915. {
  63916. Path circle;
  63917. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  63918. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  63919. const float radius = getCoordLength (xml.getStringAttribute (T("r")), viewBoxW);
  63920. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  63921. return parseShape (xml, circle);
  63922. }
  63923. Drawable* parseEllipse (const XmlElement& xml) const
  63924. {
  63925. Path ellipse;
  63926. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  63927. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  63928. const float radiusX = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  63929. const float radiusY = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  63930. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  63931. return parseShape (xml, ellipse);
  63932. }
  63933. Drawable* parseLine (const XmlElement& xml) const
  63934. {
  63935. Path line;
  63936. const float x1 = getCoordLength (xml.getStringAttribute (T("x1")), viewBoxW);
  63937. const float y1 = getCoordLength (xml.getStringAttribute (T("y1")), viewBoxH);
  63938. const float x2 = getCoordLength (xml.getStringAttribute (T("x2")), viewBoxW);
  63939. const float y2 = getCoordLength (xml.getStringAttribute (T("y2")), viewBoxH);
  63940. line.startNewSubPath (x1, y1);
  63941. line.lineTo (x2, y2);
  63942. return parseShape (xml, line);
  63943. }
  63944. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  63945. {
  63946. const String points (xml.getStringAttribute (T("points")));
  63947. Path path;
  63948. int index = 0;
  63949. float x, y;
  63950. if (parseCoords (points, x, y, index, true))
  63951. {
  63952. float firstX = x;
  63953. float firstY = y;
  63954. float lastX = 0, lastY = 0;
  63955. path.startNewSubPath (x, y);
  63956. while (parseCoords (points, x, y, index, true))
  63957. {
  63958. lastX = x;
  63959. lastY = y;
  63960. path.lineTo (x, y);
  63961. }
  63962. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  63963. path.closeSubPath();
  63964. }
  63965. return parseShape (xml, path);
  63966. }
  63967. Drawable* parseShape (const XmlElement& xml, Path& path,
  63968. const bool parseTransform = true) const
  63969. {
  63970. if (parseTransform && xml.hasAttribute (T("transform")))
  63971. {
  63972. SVGState newState (*this);
  63973. newState.addTransform (xml);
  63974. return newState.parseShape (xml, path, false);
  63975. }
  63976. DrawablePath* dp = new DrawablePath();
  63977. dp->setSolidFill (Colours::transparentBlack);
  63978. path.applyTransform (transform);
  63979. dp->setPath (path);
  63980. Path::Iterator iter (path);
  63981. bool containsClosedSubPath = false;
  63982. while (iter.next())
  63983. {
  63984. if (iter.elementType == Path::Iterator::closePath)
  63985. {
  63986. containsClosedSubPath = true;
  63987. break;
  63988. }
  63989. }
  63990. Brush* const fillBrush
  63991. = getBrushForFill (path,
  63992. getStyleAttribute (&xml, T("fill")),
  63993. getStyleAttribute (&xml, T("fill-opacity")),
  63994. getStyleAttribute (&xml, T("opacity")),
  63995. containsClosedSubPath ? Colours::black
  63996. : Colours::transparentBlack);
  63997. if (fillBrush != 0)
  63998. {
  63999. if (! fillBrush->isInvisible())
  64000. {
  64001. fillBrush->applyTransform (transform);
  64002. dp->setFillBrush (*fillBrush);
  64003. }
  64004. delete fillBrush;
  64005. }
  64006. const String strokeType (getStyleAttribute (&xml, T("stroke")));
  64007. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase (T("none")))
  64008. {
  64009. Brush* const strokeBrush
  64010. = getBrushForFill (path, strokeType,
  64011. getStyleAttribute (&xml, T("stroke-opacity")),
  64012. getStyleAttribute (&xml, T("opacity")),
  64013. Colours::transparentBlack);
  64014. if (strokeBrush != 0)
  64015. {
  64016. const PathStrokeType stroke (getStrokeFor (&xml));
  64017. if (! strokeBrush->isInvisible())
  64018. {
  64019. strokeBrush->applyTransform (transform);
  64020. dp->setOutline (stroke, *strokeBrush);
  64021. }
  64022. delete strokeBrush;
  64023. }
  64024. }
  64025. return dp;
  64026. }
  64027. const XmlElement* findLinkedElement (const XmlElement* e) const
  64028. {
  64029. const String id (e->getStringAttribute (T("xlink:href")));
  64030. if (! id.startsWithChar (T('#')))
  64031. return 0;
  64032. return findElementForId (topLevelXml, id.substring (1));
  64033. }
  64034. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  64035. {
  64036. if (fillXml == 0)
  64037. return;
  64038. forEachXmlChildElementWithTagName (*fillXml, e, T("stop"))
  64039. {
  64040. int index = 0;
  64041. Colour col (parseColour (getStyleAttribute (e, T("stop-color")), index, Colours::black));
  64042. const String opacity (getStyleAttribute (e, T("stop-opacity"), T("1")));
  64043. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  64044. double offset = e->getDoubleAttribute (T("offset"));
  64045. if (e->getStringAttribute (T("offset")).containsChar (T('%')))
  64046. offset *= 0.01;
  64047. cg.addColour (jlimit (0.0, 1.0, offset), col);
  64048. }
  64049. }
  64050. Brush* getBrushForFill (const Path& path,
  64051. const String& fill,
  64052. const String& fillOpacity,
  64053. const String& overallOpacity,
  64054. const Colour& defaultColour) const
  64055. {
  64056. float opacity = 1.0f;
  64057. if (overallOpacity.isNotEmpty())
  64058. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  64059. if (fillOpacity.isNotEmpty())
  64060. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  64061. if (fill.startsWithIgnoreCase (T("url")))
  64062. {
  64063. const String id (fill.fromFirstOccurrenceOf (T("#"), false, false)
  64064. .upToLastOccurrenceOf (T(")"), false, false).trim());
  64065. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  64066. if (fillXml != 0
  64067. && (fillXml->hasTagName (T("linearGradient"))
  64068. || fillXml->hasTagName (T("radialGradient"))))
  64069. {
  64070. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  64071. ColourGradient cg;
  64072. addGradientStopsIn (cg, inheritedFrom);
  64073. addGradientStopsIn (cg, fillXml);
  64074. if (cg.getNumColours() > 0)
  64075. {
  64076. cg.addColour (0.0, cg.getColour (0));
  64077. cg.addColour (1.0, cg.getColour (cg.getNumColours() - 1));
  64078. }
  64079. else
  64080. {
  64081. cg.addColour (0.0, Colours::black);
  64082. cg.addColour (1.0, Colours::black);
  64083. }
  64084. if (overallOpacity.isNotEmpty())
  64085. cg.multiplyOpacity (overallOpacity.getFloatValue());
  64086. jassert (cg.getNumColours() > 0);
  64087. cg.isRadial = fillXml->hasTagName (T("radialGradient"));
  64088. cg.transform = parseTransform (fillXml->getStringAttribute (T("gradientTransform")));
  64089. float width = viewBoxW;
  64090. float height = viewBoxH;
  64091. float dx = 0.0;
  64092. float dy = 0.0;
  64093. const bool userSpace = fillXml->getStringAttribute (T("gradientUnits")).equalsIgnoreCase (T("userSpaceOnUse"));
  64094. if (! userSpace)
  64095. path.getBounds (dx, dy, width, height);
  64096. if (cg.isRadial)
  64097. {
  64098. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("cx"), T("50%")), width);
  64099. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("cy"), T("50%")), height);
  64100. const float radius = getCoordLength (fillXml->getStringAttribute (T("r"), T("50%")), width);
  64101. cg.x2 = cg.x1 + radius;
  64102. cg.y2 = cg.y1;
  64103. //xxx (the fx, fy focal point isn't handled properly here..)
  64104. }
  64105. else
  64106. {
  64107. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("x1"), T("0%")), width);
  64108. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("y1"), T("0%")), height);
  64109. cg.x2 = dx + getCoordLength (fillXml->getStringAttribute (T("x2"), T("100%")), width);
  64110. cg.y2 = dy + getCoordLength (fillXml->getStringAttribute (T("y2"), T("0%")), height);
  64111. if (cg.x1 == cg.x2 && cg.y1 == cg.y2)
  64112. return new SolidColourBrush (cg.getColour (cg.getNumColours() - 1));
  64113. }
  64114. return new GradientBrush (cg);
  64115. }
  64116. }
  64117. if (fill.equalsIgnoreCase (T("none")))
  64118. return new SolidColourBrush (Colours::transparentBlack);
  64119. int i = 0;
  64120. Colour colour (parseColour (fill, i, defaultColour));
  64121. colour = colour.withMultipliedAlpha (opacity);
  64122. return new SolidColourBrush (colour);
  64123. }
  64124. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  64125. {
  64126. const String width (getStyleAttribute (xml, T("stroke-width")));
  64127. const String cap (getStyleAttribute (xml, T("stroke-linecap")));
  64128. const String join (getStyleAttribute (xml, T("stroke-linejoin")));
  64129. //const String mitreLimit (getStyleAttribute (xml, T("stroke-miterlimit")));
  64130. //const String dashArray (getStyleAttribute (xml, T("stroke-dasharray")));
  64131. //const String dashOffset (getStyleAttribute (xml, T("stroke-dashoffset")));
  64132. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  64133. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  64134. if (join.equalsIgnoreCase (T("round")))
  64135. joinStyle = PathStrokeType::curved;
  64136. else if (join.equalsIgnoreCase (T("bevel")))
  64137. joinStyle = PathStrokeType::beveled;
  64138. if (cap.equalsIgnoreCase (T("round")))
  64139. capStyle = PathStrokeType::rounded;
  64140. else if (cap.equalsIgnoreCase (T("square")))
  64141. capStyle = PathStrokeType::square;
  64142. float ox = 0.0f, oy = 0.0f;
  64143. transform.transformPoint (ox, oy);
  64144. float x = getCoordLength (width, viewBoxW), y = 0.0f;
  64145. transform.transformPoint (x, y);
  64146. return PathStrokeType (width.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  64147. joinStyle, capStyle);
  64148. }
  64149. Drawable* parseText (const XmlElement& xml)
  64150. {
  64151. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  64152. getCoordList (xCoords, getInheritedAttribute (&xml, T("x")), true, true);
  64153. getCoordList (yCoords, getInheritedAttribute (&xml, T("y")), true, false);
  64154. getCoordList (dxCoords, getInheritedAttribute (&xml, T("dx")), true, true);
  64155. getCoordList (dyCoords, getInheritedAttribute (&xml, T("dy")), true, false);
  64156. //xxx not done text yet!
  64157. forEachXmlChildElement (xml, e)
  64158. {
  64159. if (e->isTextElement())
  64160. {
  64161. const String text (e->getText());
  64162. Path path;
  64163. parseShape (*e, path);
  64164. }
  64165. else if (e->hasTagName (T("tspan")))
  64166. {
  64167. parseText (*e);
  64168. }
  64169. }
  64170. return 0;
  64171. }
  64172. void addTransform (const XmlElement& xml)
  64173. {
  64174. transform = parseTransform (xml.getStringAttribute (T("transform")))
  64175. .followedBy (transform);
  64176. }
  64177. bool parseCoord (const String& s, float& value, int& index,
  64178. const bool allowUnits, const bool isX) const
  64179. {
  64180. String number;
  64181. if (! parseNextNumber (s, number, index, allowUnits))
  64182. {
  64183. value = 0;
  64184. return false;
  64185. }
  64186. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  64187. return true;
  64188. }
  64189. bool parseCoords (const String& s, float& x, float& y,
  64190. int& index, const bool allowUnits) const
  64191. {
  64192. return parseCoord (s, x, index, allowUnits, true)
  64193. && parseCoord (s, y, index, allowUnits, false);
  64194. }
  64195. float getCoordLength (const String& s, const float sizeForProportions) const
  64196. {
  64197. float n = s.getFloatValue();
  64198. const int len = s.length();
  64199. if (len > 2)
  64200. {
  64201. const float dpi = 96.0f;
  64202. const tchar n1 = s [len - 2];
  64203. const tchar n2 = s [len - 1];
  64204. if (n1 == T('i') && n2 == T('n'))
  64205. n *= dpi;
  64206. else if (n1 == T('m') && n2 == T('m'))
  64207. n *= dpi / 25.4f;
  64208. else if (n1 == T('c') && n2 == T('m'))
  64209. n *= dpi / 2.54f;
  64210. else if (n1 == T('p') && n2 == T('c'))
  64211. n *= 15.0f;
  64212. else if (n2 == T('%'))
  64213. n *= 0.01f * sizeForProportions;
  64214. }
  64215. return n;
  64216. }
  64217. void getCoordList (Array <float>& coords, const String& list,
  64218. const bool allowUnits, const bool isX) const
  64219. {
  64220. int index = 0;
  64221. float value;
  64222. while (parseCoord (list, value, index, allowUnits, isX))
  64223. coords.add (value);
  64224. }
  64225. void parseCSSStyle (const XmlElement& xml)
  64226. {
  64227. cssStyleText = xml.getAllSubText() + T("\n") + cssStyleText;
  64228. }
  64229. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  64230. const String& defaultValue = String::empty) const
  64231. {
  64232. if (xml->hasAttribute (attributeName))
  64233. return xml->getStringAttribute (attributeName, defaultValue);
  64234. const String styleAtt (xml->getStringAttribute (T("style")));
  64235. if (styleAtt.isNotEmpty())
  64236. {
  64237. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  64238. if (value.isNotEmpty())
  64239. return value;
  64240. }
  64241. else if (xml->hasAttribute (T("class")))
  64242. {
  64243. const String className (T(".") + xml->getStringAttribute (T("class")));
  64244. int index = cssStyleText.indexOfIgnoreCase (className + T(" "));
  64245. if (index < 0)
  64246. index = cssStyleText.indexOfIgnoreCase (className + T("{"));
  64247. if (index >= 0)
  64248. {
  64249. const int openBracket = cssStyleText.indexOfChar (index, T('{'));
  64250. if (openBracket > index)
  64251. {
  64252. const int closeBracket = cssStyleText.indexOfChar (openBracket, T('}'));
  64253. if (closeBracket > openBracket)
  64254. {
  64255. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  64256. if (value.isNotEmpty())
  64257. return value;
  64258. }
  64259. }
  64260. }
  64261. }
  64262. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  64263. if (xml != 0)
  64264. return getStyleAttribute (xml, attributeName, defaultValue);
  64265. return defaultValue;
  64266. }
  64267. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  64268. {
  64269. if (xml->hasAttribute (attributeName))
  64270. return xml->getStringAttribute (attributeName);
  64271. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  64272. if (xml != 0)
  64273. return getInheritedAttribute (xml, attributeName);
  64274. return String::empty;
  64275. }
  64276. static bool isIdentifierChar (const tchar c)
  64277. {
  64278. return CharacterFunctions::isLetter (c) || c == T('-');
  64279. }
  64280. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  64281. {
  64282. int i = 0;
  64283. for (;;)
  64284. {
  64285. i = list.indexOf (i, attributeName);
  64286. if (i < 0)
  64287. break;
  64288. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  64289. && ! isIdentifierChar (list [i + attributeName.length()]))
  64290. {
  64291. i = list.indexOfChar (i, T(':'));
  64292. if (i < 0)
  64293. break;
  64294. int end = list.indexOfChar (i, T(';'));
  64295. if (end < 0)
  64296. end = 0x7ffff;
  64297. return list.substring (i + 1, end).trim();
  64298. }
  64299. ++i;
  64300. }
  64301. return defaultValue;
  64302. }
  64303. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  64304. {
  64305. const tchar* const s = (const tchar*) source;
  64306. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  64307. ++index;
  64308. int start = index;
  64309. if (CharacterFunctions::isDigit (s[index]) || s[index] == T('.') || s[index] == T('-'))
  64310. ++index;
  64311. while (CharacterFunctions::isDigit (s[index]) || s[index] == T('.'))
  64312. ++index;
  64313. if ((s[index] == T('e') || s[index] == T('E'))
  64314. && (CharacterFunctions::isDigit (s[index + 1])
  64315. || s[index + 1] == T('-')
  64316. || s[index + 1] == T('+')))
  64317. {
  64318. index += 2;
  64319. while (CharacterFunctions::isDigit (s[index]))
  64320. ++index;
  64321. }
  64322. if (allowUnits)
  64323. {
  64324. while (CharacterFunctions::isLetter (s[index]))
  64325. ++index;
  64326. }
  64327. if (index == start)
  64328. return false;
  64329. value = String (s + start, index - start);
  64330. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  64331. ++index;
  64332. return true;
  64333. }
  64334. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  64335. {
  64336. if (s [index] == T('#'))
  64337. {
  64338. uint32 hex [6];
  64339. zeromem (hex, sizeof (hex));
  64340. int numChars = 0;
  64341. for (int i = 6; --i >= 0;)
  64342. {
  64343. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  64344. if (hexValue >= 0)
  64345. hex [numChars++] = hexValue;
  64346. else
  64347. break;
  64348. }
  64349. if (numChars <= 3)
  64350. return Colour ((uint8) (hex [0] * 0x11),
  64351. (uint8) (hex [1] * 0x11),
  64352. (uint8) (hex [2] * 0x11));
  64353. else
  64354. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  64355. (uint8) ((hex [2] << 4) + hex [3]),
  64356. (uint8) ((hex [4] << 4) + hex [5]));
  64357. }
  64358. else if (s [index] == T('r')
  64359. && s [index + 1] == T('g')
  64360. && s [index + 2] == T('b'))
  64361. {
  64362. const int openBracket = s.indexOfChar (index, T('('));
  64363. const int closeBracket = s.indexOfChar (openBracket, T(')'));
  64364. if (openBracket >= 3 && closeBracket > openBracket)
  64365. {
  64366. index = closeBracket;
  64367. StringArray tokens;
  64368. tokens.addTokens (s.substring (openBracket + 1, closeBracket), T(","), T(""));
  64369. tokens.trim();
  64370. tokens.removeEmptyStrings();
  64371. if (tokens[0].containsChar T('%'))
  64372. return Colour ((uint8) roundDoubleToInt (2.55 * tokens[0].getDoubleValue()),
  64373. (uint8) roundDoubleToInt (2.55 * tokens[1].getDoubleValue()),
  64374. (uint8) roundDoubleToInt (2.55 * tokens[2].getDoubleValue()));
  64375. else
  64376. return Colour ((uint8) tokens[0].getIntValue(),
  64377. (uint8) tokens[1].getIntValue(),
  64378. (uint8) tokens[2].getIntValue());
  64379. }
  64380. }
  64381. return Colours::findColourForName (s, defaultColour);
  64382. }
  64383. static const AffineTransform parseTransform (String t)
  64384. {
  64385. AffineTransform result;
  64386. while (t.isNotEmpty())
  64387. {
  64388. StringArray tokens;
  64389. tokens.addTokens (t.fromFirstOccurrenceOf (T("("), false, false)
  64390. .upToFirstOccurrenceOf (T(")"), false, false),
  64391. T(", "), 0);
  64392. tokens.removeEmptyStrings (true);
  64393. float numbers [6];
  64394. for (int i = 0; i < 6; ++i)
  64395. numbers[i] = tokens[i].getFloatValue();
  64396. AffineTransform trans;
  64397. if (t.startsWithIgnoreCase (T("matrix")))
  64398. {
  64399. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  64400. numbers[1], numbers[3], numbers[5]);
  64401. }
  64402. else if (t.startsWithIgnoreCase (T("translate")))
  64403. {
  64404. trans = trans.translated (numbers[0], numbers[1]);
  64405. }
  64406. else if (t.startsWithIgnoreCase (T("scale")))
  64407. {
  64408. if (tokens.size() == 1)
  64409. trans = trans.scaled (numbers[0], numbers[0]);
  64410. else
  64411. trans = trans.scaled (numbers[0], numbers[1]);
  64412. }
  64413. else if (t.startsWithIgnoreCase (T("rotate")))
  64414. {
  64415. if (tokens.size() != 3)
  64416. trans = trans.rotated (numbers[0] / (180.0f / float_Pi));
  64417. else
  64418. trans = trans.rotated (numbers[0] / (180.0f / float_Pi),
  64419. numbers[1], numbers[2]);
  64420. }
  64421. else if (t.startsWithIgnoreCase (T("skewX")))
  64422. {
  64423. trans = AffineTransform (1.0f, tanf (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  64424. 0.0f, 1.0f, 0.0f);
  64425. }
  64426. else if (t.startsWithIgnoreCase (T("skewY")))
  64427. {
  64428. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  64429. tanf (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  64430. }
  64431. result = trans.followedBy (result);
  64432. t = t.fromFirstOccurrenceOf (T(")"), false, false).trimStart();
  64433. }
  64434. return result;
  64435. }
  64436. static void endpointToCentreParameters (const double x1, const double y1,
  64437. const double x2, const double y2,
  64438. const double angle,
  64439. const bool largeArc, const bool sweep,
  64440. double& rx, double& ry,
  64441. double& centreX, double& centreY,
  64442. double& startAngle, double& deltaAngle)
  64443. {
  64444. const double midX = (x1 - x2) * 0.5;
  64445. const double midY = (y1 - y2) * 0.5;
  64446. const double cosAngle = cos (angle);
  64447. const double sinAngle = sin (angle);
  64448. const double xp = cosAngle * midX + sinAngle * midY;
  64449. const double yp = cosAngle * midY - sinAngle * midX;
  64450. const double xp2 = xp * xp;
  64451. const double yp2 = yp * yp;
  64452. double rx2 = rx * rx;
  64453. double ry2 = ry * ry;
  64454. const double s = (xp2 / rx2) + (yp2 / ry2);
  64455. double c;
  64456. if (s <= 1.0)
  64457. {
  64458. c = sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  64459. / (( rx2 * yp2) + (ry2 * xp2))));
  64460. if (largeArc == sweep)
  64461. c = -c;
  64462. }
  64463. else
  64464. {
  64465. const double s2 = sqrt (s);
  64466. rx *= s2;
  64467. ry *= s2;
  64468. rx2 = rx * rx;
  64469. ry2 = ry * ry;
  64470. c = 0;
  64471. }
  64472. const double cpx = ((rx * yp) / ry) * c;
  64473. const double cpy = ((-ry * xp) / rx) * c;
  64474. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  64475. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  64476. const double ux = (xp - cpx) / rx;
  64477. const double uy = (yp - cpy) / ry;
  64478. const double vx = (-xp - cpx) / rx;
  64479. const double vy = (-yp - cpy) / ry;
  64480. const double length = juce_hypot (ux, uy);
  64481. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  64482. if (uy < 0)
  64483. startAngle = -startAngle;
  64484. startAngle += double_Pi * 0.5;
  64485. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  64486. / (length * juce_hypot (vx, vy))));
  64487. if ((ux * vy) - (uy * vx) < 0)
  64488. deltaAngle = -deltaAngle;
  64489. if (sweep)
  64490. {
  64491. if (deltaAngle < 0)
  64492. deltaAngle += double_Pi * 2.0;
  64493. }
  64494. else
  64495. {
  64496. if (deltaAngle > 0)
  64497. deltaAngle -= double_Pi * 2.0;
  64498. }
  64499. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  64500. }
  64501. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  64502. {
  64503. forEachXmlChildElement (*parent, e)
  64504. {
  64505. if (e->compareAttribute (T("id"), id))
  64506. return e;
  64507. const XmlElement* const found = findElementForId (e, id);
  64508. if (found != 0)
  64509. return found;
  64510. }
  64511. return 0;
  64512. }
  64513. const SVGState& operator= (const SVGState&);
  64514. };
  64515. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  64516. {
  64517. SVGState state (&svgDocument);
  64518. return state.parseSVGElement (svgDocument);
  64519. }
  64520. END_JUCE_NAMESPACE
  64521. /********* End of inlined file: juce_SVGParser.cpp *********/
  64522. /********* Start of inlined file: juce_DropShadowEffect.cpp *********/
  64523. BEGIN_JUCE_NAMESPACE
  64524. #if JUCE_MSVC
  64525. #pragma optimize ("t", on) // try to avoid slowing everything down in debug builds
  64526. #endif
  64527. DropShadowEffect::DropShadowEffect()
  64528. : offsetX (0),
  64529. offsetY (0),
  64530. radius (4),
  64531. opacity (0.6f)
  64532. {
  64533. }
  64534. DropShadowEffect::~DropShadowEffect()
  64535. {
  64536. }
  64537. void DropShadowEffect::setShadowProperties (const float newRadius,
  64538. const float newOpacity,
  64539. const int newShadowOffsetX,
  64540. const int newShadowOffsetY)
  64541. {
  64542. radius = jmax (1.1f, newRadius);
  64543. offsetX = newShadowOffsetX;
  64544. offsetY = newShadowOffsetY;
  64545. opacity = newOpacity;
  64546. }
  64547. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  64548. {
  64549. const int w = image.getWidth();
  64550. const int h = image.getHeight();
  64551. int lineStride, pixelStride;
  64552. const PixelARGB* srcPixels = (const PixelARGB*) image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(), lineStride, pixelStride);
  64553. Image shadowImage (Image::SingleChannel, w, h, false);
  64554. int destStride, destPixelStride;
  64555. uint8* const shadowChannel = (uint8*) shadowImage.lockPixelDataReadWrite (0, 0, w, h, destStride, destPixelStride);
  64556. const int filter = roundFloatToInt (63.0f / radius);
  64557. const int radiusMinus1 = roundFloatToInt ((radius - 1.0f) * 63.0f);
  64558. for (int x = w; --x >= 0;)
  64559. {
  64560. int shadowAlpha = 0;
  64561. const PixelARGB* src = srcPixels + x;
  64562. uint8* shadowPix = shadowChannel + x;
  64563. for (int y = h; --y >= 0;)
  64564. {
  64565. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  64566. *shadowPix = (uint8) shadowAlpha;
  64567. src = (const PixelARGB*) (((const uint8*) src) + lineStride);
  64568. shadowPix += destStride;
  64569. }
  64570. }
  64571. for (int y = h; --y >= 0;)
  64572. {
  64573. int shadowAlpha = 0;
  64574. uint8* shadowPix = shadowChannel + y * destStride;
  64575. for (int x = w; --x >= 0;)
  64576. {
  64577. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  64578. *shadowPix++ = (uint8) shadowAlpha;
  64579. }
  64580. }
  64581. image.releasePixelDataReadOnly (srcPixels);
  64582. shadowImage.releasePixelDataReadWrite (shadowChannel);
  64583. g.setColour (Colours::black.withAlpha (opacity));
  64584. g.drawImageAt (&shadowImage, offsetX, offsetY, true);
  64585. g.setOpacity (1.0f);
  64586. g.drawImageAt (&image, 0, 0);
  64587. }
  64588. END_JUCE_NAMESPACE
  64589. /********* End of inlined file: juce_DropShadowEffect.cpp *********/
  64590. /********* Start of inlined file: juce_GlowEffect.cpp *********/
  64591. BEGIN_JUCE_NAMESPACE
  64592. GlowEffect::GlowEffect()
  64593. : radius (2.0f),
  64594. colour (Colours::white)
  64595. {
  64596. }
  64597. GlowEffect::~GlowEffect()
  64598. {
  64599. }
  64600. void GlowEffect::setGlowProperties (const float newRadius,
  64601. const Colour& newColour)
  64602. {
  64603. radius = newRadius;
  64604. colour = newColour;
  64605. }
  64606. void GlowEffect::applyEffect (Image& image, Graphics& g)
  64607. {
  64608. const int w = image.getWidth();
  64609. const int h = image.getHeight();
  64610. Image temp (image.getFormat(), w, h, true);
  64611. ImageConvolutionKernel blurKernel (roundFloatToInt (radius * 2.0f));
  64612. blurKernel.createGaussianBlur (radius);
  64613. blurKernel.rescaleAllValues (radius);
  64614. blurKernel.applyToImage (temp, &image, 0, 0, w, h);
  64615. g.setColour (colour);
  64616. g.drawImageAt (&temp, 0, 0, true);
  64617. g.setOpacity (1.0f);
  64618. g.drawImageAt (&image, 0, 0, false);
  64619. }
  64620. END_JUCE_NAMESPACE
  64621. /********* End of inlined file: juce_GlowEffect.cpp *********/
  64622. /********* Start of inlined file: juce_ReduceOpacityEffect.cpp *********/
  64623. BEGIN_JUCE_NAMESPACE
  64624. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  64625. : opacity (opacity_)
  64626. {
  64627. }
  64628. ReduceOpacityEffect::~ReduceOpacityEffect()
  64629. {
  64630. }
  64631. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  64632. {
  64633. opacity = jlimit (0.0f, 1.0f, newOpacity);
  64634. }
  64635. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  64636. {
  64637. g.setOpacity (opacity);
  64638. g.drawImageAt (&image, 0, 0);
  64639. }
  64640. END_JUCE_NAMESPACE
  64641. /********* End of inlined file: juce_ReduceOpacityEffect.cpp *********/
  64642. /********* Start of inlined file: juce_Font.cpp *********/
  64643. BEGIN_JUCE_NAMESPACE
  64644. static const float minFontHeight = 0.1f;
  64645. static const float maxFontHeight = 10000.0f;
  64646. static const float defaultFontHeight = 14.0f;
  64647. static String defaultSans, defaultSerif, defaultFixed, fallbackFont;
  64648. Font::Font() throw()
  64649. : typefaceName (defaultSans),
  64650. height (defaultFontHeight),
  64651. horizontalScale (1.0f),
  64652. kerning (0),
  64653. ascent (0),
  64654. styleFlags (Font::plain)
  64655. {
  64656. }
  64657. void Font::resetToDefaultState() throw()
  64658. {
  64659. typefaceName = defaultSans;
  64660. height = defaultFontHeight;
  64661. horizontalScale = 1.0f;
  64662. kerning = 0;
  64663. ascent = 0;
  64664. styleFlags = Font::plain;
  64665. typeface = 0;
  64666. }
  64667. Font::Font (const float fontHeight,
  64668. const int styleFlags_) throw()
  64669. : typefaceName (defaultSans),
  64670. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  64671. horizontalScale (1.0f),
  64672. kerning (0),
  64673. ascent (0),
  64674. styleFlags (styleFlags_)
  64675. {
  64676. }
  64677. Font::Font (const String& typefaceName_,
  64678. const float fontHeight,
  64679. const int styleFlags_) throw()
  64680. : typefaceName (typefaceName_),
  64681. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  64682. horizontalScale (1.0f),
  64683. kerning (0),
  64684. ascent (0),
  64685. styleFlags (styleFlags_)
  64686. {
  64687. }
  64688. Font::Font (const Font& other) throw()
  64689. : typefaceName (other.typefaceName),
  64690. height (other.height),
  64691. horizontalScale (other.horizontalScale),
  64692. kerning (other.kerning),
  64693. ascent (other.ascent),
  64694. styleFlags (other.styleFlags),
  64695. typeface (other.typeface)
  64696. {
  64697. }
  64698. const Font& Font::operator= (const Font& other) throw()
  64699. {
  64700. if (this != &other)
  64701. {
  64702. typefaceName = other.typefaceName;
  64703. height = other.height;
  64704. styleFlags = other.styleFlags;
  64705. horizontalScale = other.horizontalScale;
  64706. kerning = other.kerning;
  64707. ascent = other.ascent;
  64708. typeface = other.typeface;
  64709. }
  64710. return *this;
  64711. }
  64712. Font::~Font() throw()
  64713. {
  64714. }
  64715. Font::Font (const Typeface& face) throw()
  64716. : height (11.0f),
  64717. horizontalScale (1.0f),
  64718. kerning (0),
  64719. ascent (0),
  64720. styleFlags (plain)
  64721. {
  64722. typefaceName = face.getName();
  64723. setBold (face.isBold());
  64724. setItalic (face.isItalic());
  64725. typeface = new Typeface (face);
  64726. }
  64727. bool Font::operator== (const Font& other) const throw()
  64728. {
  64729. return height == other.height
  64730. && horizontalScale == other.horizontalScale
  64731. && kerning == other.kerning
  64732. && styleFlags == other.styleFlags
  64733. && typefaceName == other.typefaceName;
  64734. }
  64735. bool Font::operator!= (const Font& other) const throw()
  64736. {
  64737. return ! operator== (other);
  64738. }
  64739. void Font::setTypefaceName (const String& faceName) throw()
  64740. {
  64741. typefaceName = faceName;
  64742. typeface = 0;
  64743. ascent = 0;
  64744. }
  64745. void Font::initialiseDefaultFontNames() throw()
  64746. {
  64747. Font::getDefaultFontNames (defaultSans,
  64748. defaultSerif,
  64749. defaultFixed);
  64750. }
  64751. void clearUpDefaultFontNames() throw() // called at shutdown by code in Typface
  64752. {
  64753. defaultSans = String::empty;
  64754. defaultSerif = String::empty;
  64755. defaultFixed = String::empty;
  64756. fallbackFont = String::empty;
  64757. }
  64758. const String Font::getDefaultSansSerifFontName() throw()
  64759. {
  64760. return defaultSans;
  64761. }
  64762. const String Font::getDefaultSerifFontName() throw()
  64763. {
  64764. return defaultSerif;
  64765. }
  64766. const String Font::getDefaultMonospacedFontName() throw()
  64767. {
  64768. return defaultFixed;
  64769. }
  64770. void Font::setDefaultSansSerifFontName (const String& name) throw()
  64771. {
  64772. defaultSans = name;
  64773. }
  64774. const String Font::getFallbackFontName() throw()
  64775. {
  64776. return fallbackFont;
  64777. }
  64778. void Font::setFallbackFontName (const String& name) throw()
  64779. {
  64780. fallbackFont = name;
  64781. }
  64782. void Font::setHeight (float newHeight) throw()
  64783. {
  64784. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  64785. }
  64786. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  64787. {
  64788. newHeight = jlimit (minFontHeight, maxFontHeight, newHeight);
  64789. horizontalScale *= (height / newHeight);
  64790. height = newHeight;
  64791. }
  64792. void Font::setStyleFlags (const int newFlags) throw()
  64793. {
  64794. if (styleFlags != newFlags)
  64795. {
  64796. styleFlags = newFlags;
  64797. typeface = 0;
  64798. ascent = 0;
  64799. }
  64800. }
  64801. void Font::setSizeAndStyle (const float newHeight,
  64802. const int newStyleFlags,
  64803. const float newHorizontalScale,
  64804. const float newKerningAmount) throw()
  64805. {
  64806. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  64807. horizontalScale = newHorizontalScale;
  64808. kerning = newKerningAmount;
  64809. setStyleFlags (newStyleFlags);
  64810. }
  64811. void Font::setHorizontalScale (const float scaleFactor) throw()
  64812. {
  64813. horizontalScale = scaleFactor;
  64814. }
  64815. void Font::setExtraKerningFactor (const float extraKerning) throw()
  64816. {
  64817. kerning = extraKerning;
  64818. }
  64819. void Font::setBold (const bool shouldBeBold) throw()
  64820. {
  64821. setStyleFlags (shouldBeBold ? (styleFlags | bold)
  64822. : (styleFlags & ~bold));
  64823. }
  64824. bool Font::isBold() const throw()
  64825. {
  64826. return (styleFlags & bold) != 0;
  64827. }
  64828. void Font::setItalic (const bool shouldBeItalic) throw()
  64829. {
  64830. setStyleFlags (shouldBeItalic ? (styleFlags | italic)
  64831. : (styleFlags & ~italic));
  64832. }
  64833. bool Font::isItalic() const throw()
  64834. {
  64835. return (styleFlags & italic) != 0;
  64836. }
  64837. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  64838. {
  64839. setStyleFlags (shouldBeUnderlined ? (styleFlags | underlined)
  64840. : (styleFlags & ~underlined));
  64841. }
  64842. bool Font::isUnderlined() const throw()
  64843. {
  64844. return (styleFlags & underlined) != 0;
  64845. }
  64846. float Font::getAscent() const throw()
  64847. {
  64848. if (ascent == 0)
  64849. ascent = getTypeface()->getAscent();
  64850. return height * ascent;
  64851. }
  64852. float Font::getDescent() const throw()
  64853. {
  64854. return height - getAscent();
  64855. }
  64856. int Font::getStringWidth (const String& text) const throw()
  64857. {
  64858. return roundFloatToInt (getStringWidthFloat (text));
  64859. }
  64860. float Font::getStringWidthFloat (const String& text) const throw()
  64861. {
  64862. float x = 0.0f;
  64863. if (text.isNotEmpty())
  64864. {
  64865. Typeface* const typeface = getTypeface();
  64866. const juce_wchar* t = (const juce_wchar*) text;
  64867. do
  64868. {
  64869. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (*t++);
  64870. if (glyph != 0)
  64871. x += kerning + glyph->getHorizontalSpacing (*t);
  64872. }
  64873. while (*t != 0);
  64874. x *= height;
  64875. x *= horizontalScale;
  64876. }
  64877. return x;
  64878. }
  64879. Typeface* Font::getTypeface() const throw()
  64880. {
  64881. if (typeface == 0)
  64882. typeface = Typeface::getTypefaceFor (*this);
  64883. return typeface;
  64884. }
  64885. void Font::findFonts (OwnedArray<Font>& destArray) throw()
  64886. {
  64887. const StringArray names (findAllTypefaceNames());
  64888. for (int i = 0; i < names.size(); ++i)
  64889. destArray.add (new Font (names[i], defaultFontHeight, Font::plain));
  64890. }
  64891. END_JUCE_NAMESPACE
  64892. /********* End of inlined file: juce_Font.cpp *********/
  64893. /********* Start of inlined file: juce_GlyphArrangement.cpp *********/
  64894. BEGIN_JUCE_NAMESPACE
  64895. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  64896. class FontGlyphAlphaMap
  64897. {
  64898. public:
  64899. bool draw (const Graphics& g, float x, const float y) const throw()
  64900. {
  64901. if (bitmap1 == 0)
  64902. return false;
  64903. x += xOrigin;
  64904. const float xFloor = floorf (x);
  64905. const int intX = (int) xFloor;
  64906. g.drawImageAt (((x - xFloor) >= 0.5f && bitmap2 != 0) ? bitmap2 : bitmap1,
  64907. intX, (int) floorf (y + yOrigin), true);
  64908. return true;
  64909. }
  64910. juce_UseDebuggingNewOperator
  64911. private:
  64912. Image* bitmap1;
  64913. Image* bitmap2;
  64914. float xOrigin, yOrigin;
  64915. int lastAccessCount;
  64916. Typeface::Ptr typeface;
  64917. float height, horizontalScale;
  64918. juce_wchar character;
  64919. friend class GlyphCache;
  64920. FontGlyphAlphaMap() throw()
  64921. : bitmap1 (0),
  64922. bitmap2 (0),
  64923. lastAccessCount (0),
  64924. height (0),
  64925. horizontalScale (0),
  64926. character (0)
  64927. {
  64928. }
  64929. ~FontGlyphAlphaMap() throw()
  64930. {
  64931. delete bitmap1;
  64932. delete bitmap2;
  64933. }
  64934. class AlphaBitmapRenderer
  64935. {
  64936. uint8* const data;
  64937. const int stride;
  64938. uint8* lineStart;
  64939. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  64940. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  64941. public:
  64942. AlphaBitmapRenderer (uint8* const data_,
  64943. const int stride_) throw()
  64944. : data (data_),
  64945. stride (stride_)
  64946. {
  64947. }
  64948. forcedinline void setEdgeTableYPos (const int y) throw()
  64949. {
  64950. lineStart = data + (stride * y);
  64951. }
  64952. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  64953. {
  64954. lineStart [x] = (uint8) alphaLevel;
  64955. }
  64956. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  64957. {
  64958. uint8* d = lineStart + x;
  64959. while (--width >= 0)
  64960. *d++ = (uint8) alphaLevel;
  64961. }
  64962. };
  64963. Image* createAlphaMapFromPath (const Path& path,
  64964. float& topLeftX, float& topLeftY,
  64965. float xScale, float yScale,
  64966. const float subPixelOffsetX) throw()
  64967. {
  64968. Image* im = 0;
  64969. float px, py, pw, ph;
  64970. path.getBounds (px, py, pw, ph);
  64971. topLeftX = floorf (px * xScale);
  64972. topLeftY = floorf (py * yScale);
  64973. int bitmapWidth = roundFloatToInt (pw * xScale) + 2;
  64974. int bitmapHeight = roundFloatToInt (ph * yScale) + 2;
  64975. im = new Image (Image::SingleChannel, bitmapWidth, bitmapHeight, true);
  64976. EdgeTable edgeTable (0, bitmapHeight, EdgeTable::Oversampling_16times);
  64977. edgeTable.addPath (path, AffineTransform::scale (xScale, yScale)
  64978. .translated (subPixelOffsetX - topLeftX, -topLeftY));
  64979. int stride, pixelStride;
  64980. uint8* const pixels = (uint8*) im->lockPixelDataReadWrite (0, 0, bitmapWidth, bitmapHeight, stride, pixelStride);
  64981. jassert (pixelStride == 1);
  64982. AlphaBitmapRenderer renderer (pixels, stride);
  64983. edgeTable.iterate (renderer, 0, 0, bitmapWidth, bitmapHeight, 0);
  64984. im->releasePixelDataReadWrite (pixels);
  64985. return im;
  64986. }
  64987. void generate (Typeface* const face,
  64988. const juce_wchar character_,
  64989. const float fontHeight,
  64990. const float fontHorizontalScale) throw()
  64991. {
  64992. character = character_;
  64993. typeface = face;
  64994. height = fontHeight;
  64995. horizontalScale = fontHorizontalScale;
  64996. const Path* const glyphPath = face->getOutlineForGlyph (character_);
  64997. deleteAndZero (bitmap1);
  64998. deleteAndZero (bitmap2);
  64999. const float fontHScale = fontHeight * fontHorizontalScale;
  65000. if (glyphPath != 0 && ! glyphPath->isEmpty())
  65001. {
  65002. bitmap1 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.0f);
  65003. if (fontHScale < 24.0f)
  65004. bitmap2 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.5f);
  65005. }
  65006. else
  65007. {
  65008. xOrigin = yOrigin = 0;
  65009. }
  65010. }
  65011. };
  65012. static const int defaultNumGlyphsToCache = 120;
  65013. class GlyphCache;
  65014. static GlyphCache* cacheInstance = 0;
  65015. class GlyphCache : private DeletedAtShutdown
  65016. {
  65017. public:
  65018. static GlyphCache* getInstance() throw()
  65019. {
  65020. if (cacheInstance == 0)
  65021. cacheInstance = new GlyphCache();
  65022. return cacheInstance;
  65023. }
  65024. const FontGlyphAlphaMap& getGlyphFor (Typeface* const typeface,
  65025. const float fontHeight,
  65026. const float fontHorizontalScale,
  65027. const juce_wchar character) throw()
  65028. {
  65029. ++accessCounter;
  65030. int oldestCounter = INT_MAX;
  65031. int oldestIndex = 0;
  65032. for (int i = numGlyphs; --i >= 0;)
  65033. {
  65034. FontGlyphAlphaMap& g = glyphs[i];
  65035. if (g.character == character
  65036. && g.height == fontHeight
  65037. && g.typeface->hashCode() == typeface->hashCode()
  65038. && g.horizontalScale == fontHorizontalScale)
  65039. {
  65040. g.lastAccessCount = accessCounter;
  65041. ++hits;
  65042. return g;
  65043. }
  65044. if (oldestCounter > g.lastAccessCount)
  65045. {
  65046. oldestCounter = g.lastAccessCount;
  65047. oldestIndex = i;
  65048. }
  65049. }
  65050. ++misses;
  65051. if (hits + misses > (numGlyphs << 4))
  65052. {
  65053. if (misses * 2 > hits)
  65054. setCacheSize (numGlyphs + 32);
  65055. hits = 0;
  65056. misses = 0;
  65057. oldestIndex = 0;
  65058. }
  65059. FontGlyphAlphaMap& oldest = glyphs [oldestIndex];
  65060. oldest.lastAccessCount = accessCounter;
  65061. oldest.generate (typeface,
  65062. character,
  65063. fontHeight,
  65064. fontHorizontalScale);
  65065. return oldest;
  65066. }
  65067. void setCacheSize (const int num) throw()
  65068. {
  65069. if (numGlyphs != num)
  65070. {
  65071. numGlyphs = num;
  65072. if (glyphs != 0)
  65073. delete[] glyphs;
  65074. glyphs = new FontGlyphAlphaMap [numGlyphs];
  65075. hits = 0;
  65076. misses = 0;
  65077. }
  65078. }
  65079. juce_UseDebuggingNewOperator
  65080. private:
  65081. FontGlyphAlphaMap* glyphs;
  65082. int numGlyphs, accessCounter;
  65083. int hits, misses;
  65084. GlyphCache() throw()
  65085. : glyphs (0),
  65086. numGlyphs (0),
  65087. accessCounter (0)
  65088. {
  65089. setCacheSize (defaultNumGlyphsToCache);
  65090. }
  65091. ~GlyphCache() throw()
  65092. {
  65093. delete[] glyphs;
  65094. jassert (cacheInstance == this);
  65095. cacheInstance = 0;
  65096. }
  65097. GlyphCache (const GlyphCache&);
  65098. const GlyphCache& operator= (const GlyphCache&);
  65099. };
  65100. PositionedGlyph::PositionedGlyph() throw()
  65101. {
  65102. }
  65103. void PositionedGlyph::draw (const Graphics& g) const throw()
  65104. {
  65105. if (! glyphInfo->isWhitespace())
  65106. {
  65107. if (fontHeight < 100.0f && fontHeight > 0.1f && ! g.isVectorDevice())
  65108. {
  65109. const FontGlyphAlphaMap& alphaMap
  65110. = GlyphCache::getInstance()->getGlyphFor (glyphInfo->getTypeface(),
  65111. fontHeight,
  65112. fontHorizontalScale,
  65113. getCharacter());
  65114. alphaMap.draw (g, x, y);
  65115. }
  65116. else
  65117. {
  65118. // that's a bit of a dodgy size, isn't it??
  65119. jassert (fontHeight > 0.0f && fontHeight < 4000.0f);
  65120. draw (g, AffineTransform::identity);
  65121. }
  65122. }
  65123. }
  65124. void PositionedGlyph::draw (const Graphics& g,
  65125. const AffineTransform& transform) const throw()
  65126. {
  65127. if (! glyphInfo->isWhitespace())
  65128. {
  65129. g.fillPath (glyphInfo->getPath(),
  65130. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  65131. .translated (x, y)
  65132. .followedBy (transform));
  65133. }
  65134. }
  65135. void PositionedGlyph::createPath (Path& path) const throw()
  65136. {
  65137. if (! glyphInfo->isWhitespace())
  65138. {
  65139. path.addPath (glyphInfo->getPath(),
  65140. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  65141. .translated (x, y));
  65142. }
  65143. }
  65144. bool PositionedGlyph::hitTest (float px, float py) const throw()
  65145. {
  65146. if (px >= getLeft() && px < getRight()
  65147. && py >= getTop() && py < getBottom()
  65148. && fontHeight > 0.0f
  65149. && ! glyphInfo->isWhitespace())
  65150. {
  65151. AffineTransform::translation (-x, -y)
  65152. .scaled (1.0f / (fontHeight * fontHorizontalScale), 1.0f / fontHeight)
  65153. .transformPoint (px, py);
  65154. return glyphInfo->getPath().contains (px, py);
  65155. }
  65156. return false;
  65157. }
  65158. void PositionedGlyph::moveBy (const float deltaX,
  65159. const float deltaY) throw()
  65160. {
  65161. x += deltaX;
  65162. y += deltaY;
  65163. }
  65164. GlyphArrangement::GlyphArrangement() throw()
  65165. : numGlyphs (0),
  65166. numAllocated (0),
  65167. glyphs (0)
  65168. {
  65169. }
  65170. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other) throw()
  65171. : numGlyphs (0),
  65172. numAllocated (0),
  65173. glyphs (0)
  65174. {
  65175. addGlyphArrangement (other);
  65176. }
  65177. const GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other) throw()
  65178. {
  65179. if (this != &other)
  65180. {
  65181. clear();
  65182. addGlyphArrangement (other);
  65183. }
  65184. return *this;
  65185. }
  65186. GlyphArrangement::~GlyphArrangement() throw()
  65187. {
  65188. clear();
  65189. juce_free (glyphs);
  65190. }
  65191. void GlyphArrangement::ensureNumGlyphsAllocated (const int minGlyphs) throw()
  65192. {
  65193. if (numAllocated <= minGlyphs)
  65194. {
  65195. numAllocated = minGlyphs + 2;
  65196. if (glyphs == 0)
  65197. glyphs = (PositionedGlyph*) juce_malloc (numAllocated * sizeof (PositionedGlyph));
  65198. else
  65199. glyphs = (PositionedGlyph*) juce_realloc (glyphs, numAllocated * sizeof (PositionedGlyph));
  65200. }
  65201. }
  65202. void GlyphArrangement::incGlyphRefCount (const int i) const throw()
  65203. {
  65204. jassert (((unsigned int) i) < (unsigned int) numGlyphs);
  65205. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  65206. glyphs[i].glyphInfo->getTypeface()->incReferenceCount();
  65207. }
  65208. void GlyphArrangement::decGlyphRefCount (const int i) const throw()
  65209. {
  65210. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  65211. glyphs[i].glyphInfo->getTypeface()->decReferenceCount();
  65212. }
  65213. void GlyphArrangement::clear() throw()
  65214. {
  65215. for (int i = numGlyphs; --i >= 0;)
  65216. decGlyphRefCount (i);
  65217. numGlyphs = 0;
  65218. }
  65219. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const throw()
  65220. {
  65221. jassert (((unsigned int) index) < (unsigned int) numGlyphs);
  65222. return glyphs [index];
  65223. }
  65224. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other) throw()
  65225. {
  65226. ensureNumGlyphsAllocated (numGlyphs + other.numGlyphs);
  65227. memcpy (glyphs + numGlyphs, other.glyphs,
  65228. other.numGlyphs * sizeof (PositionedGlyph));
  65229. for (int i = other.numGlyphs; --i >= 0;)
  65230. incGlyphRefCount (numGlyphs++);
  65231. }
  65232. void GlyphArrangement::removeLast() throw()
  65233. {
  65234. if (numGlyphs > 0)
  65235. decGlyphRefCount (--numGlyphs);
  65236. }
  65237. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num) throw()
  65238. {
  65239. jassert (startIndex >= 0);
  65240. if (startIndex < 0)
  65241. startIndex = 0;
  65242. if (num < 0 || startIndex + num >= numGlyphs)
  65243. {
  65244. while (numGlyphs > startIndex)
  65245. removeLast();
  65246. }
  65247. else if (num > 0)
  65248. {
  65249. int i;
  65250. for (i = startIndex; i < startIndex + num; ++i)
  65251. decGlyphRefCount (i);
  65252. for (i = numGlyphs - (startIndex + num); --i >= 0;)
  65253. {
  65254. glyphs [startIndex] = glyphs [startIndex + num];
  65255. ++startIndex;
  65256. }
  65257. numGlyphs -= num;
  65258. }
  65259. }
  65260. void GlyphArrangement::addLineOfText (const Font& font,
  65261. const String& text,
  65262. const float xOffset,
  65263. const float yOffset) throw()
  65264. {
  65265. addCurtailedLineOfText (font, text,
  65266. xOffset, yOffset,
  65267. 1.0e10f, false);
  65268. }
  65269. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  65270. const String& text,
  65271. float xOffset,
  65272. const float yOffset,
  65273. const float maxWidthPixels,
  65274. const bool useEllipsis) throw()
  65275. {
  65276. const int textLen = text.length();
  65277. if (textLen > 0)
  65278. {
  65279. ensureNumGlyphsAllocated (numGlyphs + textLen + 3); // extra chars for ellipsis
  65280. Typeface* const typeface = font.getTypeface();
  65281. const float fontHeight = font.getHeight();
  65282. const float ascent = font.getAscent();
  65283. const float fontHorizontalScale = font.getHorizontalScale();
  65284. const float heightTimesScale = fontHorizontalScale * fontHeight;
  65285. const float kerningFactor = font.getExtraKerningFactor();
  65286. const float startX = xOffset;
  65287. const juce_wchar* const unicodeText = (const juce_wchar*) text;
  65288. for (int i = 0; i < textLen; ++i)
  65289. {
  65290. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (unicodeText[i]);
  65291. if (glyph != 0)
  65292. {
  65293. jassert (numAllocated > numGlyphs);
  65294. ensureNumGlyphsAllocated (numGlyphs);
  65295. PositionedGlyph& pg = glyphs [numGlyphs];
  65296. pg.glyphInfo = glyph;
  65297. pg.x = xOffset;
  65298. pg.y = yOffset;
  65299. pg.w = heightTimesScale * glyph->getHorizontalSpacing (0);
  65300. pg.fontHeight = fontHeight;
  65301. pg.fontAscent = ascent;
  65302. pg.fontHorizontalScale = fontHorizontalScale;
  65303. pg.isUnderlined = font.isUnderlined();
  65304. xOffset += heightTimesScale * (kerningFactor + glyph->getHorizontalSpacing (unicodeText [i + 1]));
  65305. if (xOffset - startX > maxWidthPixels + 1.0f)
  65306. {
  65307. // curtail the string if it's too wide..
  65308. if (useEllipsis && textLen > 3 && numGlyphs >= 3)
  65309. appendEllipsis (font, startX + maxWidthPixels);
  65310. break;
  65311. }
  65312. else
  65313. {
  65314. if (glyph->getTypeface() != 0)
  65315. glyph->getTypeface()->incReferenceCount();
  65316. ++numGlyphs;
  65317. }
  65318. }
  65319. }
  65320. }
  65321. }
  65322. void GlyphArrangement::appendEllipsis (const Font& font, const float maxXPixels) throw()
  65323. {
  65324. const TypefaceGlyphInfo* const dotGlyph = font.getTypeface()->getGlyph (T('.'));
  65325. if (dotGlyph != 0)
  65326. {
  65327. if (numGlyphs > 0)
  65328. {
  65329. PositionedGlyph& glyph = glyphs [numGlyphs - 1];
  65330. const float fontHeight = glyph.fontHeight;
  65331. const float fontHorizontalScale = glyph.fontHorizontalScale;
  65332. const float fontAscent = glyph.fontAscent;
  65333. const float dx = fontHeight * fontHorizontalScale
  65334. * (font.getExtraKerningFactor() + dotGlyph->getHorizontalSpacing (T('.')));
  65335. float xOffset = 0.0f, yOffset = 0.0f;
  65336. for (int dotPos = 3; --dotPos >= 0 && numGlyphs > 0;)
  65337. {
  65338. removeLast();
  65339. jassert (numAllocated > numGlyphs);
  65340. PositionedGlyph& pg = glyphs [numGlyphs];
  65341. xOffset = pg.x;
  65342. yOffset = pg.y;
  65343. if (numGlyphs == 0 || xOffset + dx * 3 <= maxXPixels)
  65344. break;
  65345. }
  65346. for (int i = 3; --i >= 0;)
  65347. {
  65348. jassert (numAllocated > numGlyphs);
  65349. ensureNumGlyphsAllocated (numGlyphs);
  65350. PositionedGlyph& pg = glyphs [numGlyphs];
  65351. pg.glyphInfo = dotGlyph;
  65352. pg.x = xOffset;
  65353. pg.y = yOffset;
  65354. pg.w = dx;
  65355. pg.fontHeight = fontHeight;
  65356. pg.fontAscent = fontAscent;
  65357. pg.fontHorizontalScale = fontHorizontalScale;
  65358. pg.isUnderlined = font.isUnderlined();
  65359. xOffset += dx;
  65360. if (dotGlyph->getTypeface() != 0)
  65361. dotGlyph->getTypeface()->incReferenceCount();
  65362. ++numGlyphs;
  65363. }
  65364. }
  65365. }
  65366. }
  65367. void GlyphArrangement::addJustifiedText (const Font& font,
  65368. const String& text,
  65369. float x, float y,
  65370. const float maxLineWidth,
  65371. const Justification& horizontalLayout) throw()
  65372. {
  65373. int lineStartIndex = numGlyphs;
  65374. addLineOfText (font, text, x, y);
  65375. const float originalY = y;
  65376. while (lineStartIndex < numGlyphs)
  65377. {
  65378. int i = lineStartIndex;
  65379. if (glyphs[i].getCharacter() != T('\n') && glyphs[i].getCharacter() != T('\r'))
  65380. ++i;
  65381. const float lineMaxX = glyphs [lineStartIndex].getLeft() + maxLineWidth;
  65382. int lastWordBreakIndex = -1;
  65383. while (i < numGlyphs)
  65384. {
  65385. PositionedGlyph& pg = glyphs[i];
  65386. const juce_wchar c = pg.getCharacter();
  65387. if (c == T('\r') || c == T('\n'))
  65388. {
  65389. ++i;
  65390. if (c == T('\r') && i < numGlyphs && glyphs [i].getCharacter() == T('\n'))
  65391. ++i;
  65392. break;
  65393. }
  65394. else if (pg.isWhitespace())
  65395. {
  65396. lastWordBreakIndex = i + 1;
  65397. }
  65398. else if (SHOULD_WRAP (pg.getRight(), lineMaxX))
  65399. {
  65400. if (lastWordBreakIndex >= 0)
  65401. i = lastWordBreakIndex;
  65402. break;
  65403. }
  65404. ++i;
  65405. }
  65406. const float currentLineStartX = glyphs [lineStartIndex].getLeft();
  65407. float currentLineEndX = currentLineStartX;
  65408. for (int j = i; --j >= lineStartIndex;)
  65409. {
  65410. if (! glyphs[j].isWhitespace())
  65411. {
  65412. currentLineEndX = glyphs[j].getRight();
  65413. break;
  65414. }
  65415. }
  65416. float deltaX = 0.0f;
  65417. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  65418. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  65419. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  65420. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  65421. else if (horizontalLayout.testFlags (Justification::right))
  65422. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  65423. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  65424. x + deltaX - currentLineStartX, y - originalY);
  65425. lineStartIndex = i;
  65426. y += font.getHeight();
  65427. }
  65428. }
  65429. void GlyphArrangement::addFittedText (const Font& f,
  65430. const String& text,
  65431. float x, float y,
  65432. float width, float height,
  65433. const Justification& layout,
  65434. int maximumLines,
  65435. const float minimumHorizontalScale) throw()
  65436. {
  65437. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  65438. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  65439. if (text.containsAnyOf (T("\r\n")))
  65440. {
  65441. GlyphArrangement ga;
  65442. ga.addJustifiedText (f, text, x, y, width, layout);
  65443. float l, t, r, b;
  65444. ga.getBoundingBox (0, -1, l, t, r, b, false);
  65445. float dy = y - t;
  65446. if (layout.testFlags (Justification::verticallyCentred))
  65447. dy += (height - (b - t)) * 0.5f;
  65448. else if (layout.testFlags (Justification::bottom))
  65449. dy += height - (b - t);
  65450. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  65451. addGlyphArrangement (ga);
  65452. return;
  65453. }
  65454. int startIndex = numGlyphs;
  65455. addLineOfText (f, text.trim(), x, y);
  65456. if (numGlyphs > startIndex)
  65457. {
  65458. float lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  65459. if (lineWidth <= 0)
  65460. return;
  65461. if (lineWidth * minimumHorizontalScale < width)
  65462. {
  65463. if (lineWidth > width)
  65464. {
  65465. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex,
  65466. width / lineWidth);
  65467. }
  65468. justifyGlyphs (startIndex, numGlyphs - startIndex,
  65469. x, y, width, height, layout);
  65470. }
  65471. else if (maximumLines <= 1)
  65472. {
  65473. const float ratio = jmax (minimumHorizontalScale, width / lineWidth);
  65474. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex, ratio);
  65475. while (numGlyphs > 0 && glyphs [numGlyphs - 1].x + glyphs [numGlyphs - 1].w >= x + width)
  65476. removeLast();
  65477. appendEllipsis (f, x + width);
  65478. justifyGlyphs (startIndex, numGlyphs - startIndex,
  65479. x, y, width, height, layout);
  65480. }
  65481. else
  65482. {
  65483. Font font (f);
  65484. String txt (text.trim());
  65485. const int length = txt.length();
  65486. int numLines = 1;
  65487. const int originalStartIndex = startIndex;
  65488. if (length <= 12 && ! txt.containsAnyOf (T(" -\t\r\n")))
  65489. maximumLines = 1;
  65490. maximumLines = jmin (maximumLines, length);
  65491. while (numLines < maximumLines)
  65492. {
  65493. ++numLines;
  65494. const float newFontHeight = height / (float)numLines;
  65495. if (newFontHeight < 8.0f)
  65496. break;
  65497. if (newFontHeight < font.getHeight())
  65498. {
  65499. font.setHeight (newFontHeight);
  65500. while (numGlyphs > startIndex)
  65501. removeLast();
  65502. addLineOfText (font, txt, x, y);
  65503. lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  65504. }
  65505. if (numLines > lineWidth / width)
  65506. break;
  65507. }
  65508. if (numLines < 1)
  65509. numLines = 1;
  65510. float lineY = y;
  65511. float widthPerLine = lineWidth / numLines;
  65512. int lastLineStartIndex = 0;
  65513. for (int line = 0; line < numLines; ++line)
  65514. {
  65515. int i = startIndex;
  65516. lastLineStartIndex = i;
  65517. float lineStartX = glyphs[startIndex].getLeft();
  65518. while (i < numGlyphs)
  65519. {
  65520. lineWidth = (glyphs[i].getRight() - lineStartX);
  65521. if (lineWidth > widthPerLine)
  65522. {
  65523. // got to a point where the line's too long, so skip forward to find a
  65524. // good place to break it..
  65525. const int searchStartIndex = i;
  65526. while (i < numGlyphs)
  65527. {
  65528. if ((glyphs[i].getRight() - lineStartX) * minimumHorizontalScale < width)
  65529. {
  65530. if (glyphs[i].isWhitespace()
  65531. || glyphs[i].getCharacter() == T('-'))
  65532. {
  65533. ++i;
  65534. break;
  65535. }
  65536. }
  65537. else
  65538. {
  65539. // can't find a suitable break, so try looking backwards..
  65540. i = searchStartIndex;
  65541. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  65542. {
  65543. if (glyphs[i - back].isWhitespace()
  65544. || glyphs[i - back].getCharacter() == T('-'))
  65545. {
  65546. i -= back - 1;
  65547. break;
  65548. }
  65549. }
  65550. break;
  65551. }
  65552. ++i;
  65553. }
  65554. break;
  65555. }
  65556. ++i;
  65557. }
  65558. int wsStart = i;
  65559. while (wsStart > 0 && glyphs[wsStart - 1].isWhitespace())
  65560. --wsStart;
  65561. int wsEnd = i;
  65562. while (wsEnd < numGlyphs && glyphs[wsEnd].isWhitespace())
  65563. ++wsEnd;
  65564. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  65565. i = jmax (wsStart, startIndex + 1);
  65566. lineWidth = glyphs[i - 1].getRight() - lineStartX;
  65567. if (lineWidth > width)
  65568. {
  65569. stretchRangeOfGlyphs (startIndex, i - startIndex,
  65570. width / lineWidth);
  65571. }
  65572. justifyGlyphs (startIndex, i - startIndex,
  65573. x, lineY, width, font.getHeight(),
  65574. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  65575. startIndex = i;
  65576. lineY += font.getHeight();
  65577. if (startIndex >= numGlyphs)
  65578. break;
  65579. }
  65580. if (startIndex < numGlyphs)
  65581. {
  65582. while (numGlyphs > startIndex)
  65583. removeLast();
  65584. if (startIndex - originalStartIndex > 4)
  65585. {
  65586. const float lineStartX = glyphs[lastLineStartIndex].getLeft();
  65587. appendEllipsis (font, lineStartX + width);
  65588. lineWidth = glyphs[startIndex - 1].getRight() - lineStartX;
  65589. if (lineWidth > width)
  65590. {
  65591. stretchRangeOfGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  65592. width / lineWidth);
  65593. }
  65594. justifyGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  65595. x, lineY - font.getHeight(), width, font.getHeight(),
  65596. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  65597. }
  65598. startIndex = numGlyphs;
  65599. }
  65600. justifyGlyphs (originalStartIndex, startIndex - originalStartIndex,
  65601. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  65602. }
  65603. }
  65604. }
  65605. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  65606. const float dx, const float dy) throw()
  65607. {
  65608. jassert (startIndex >= 0);
  65609. if (dx != 0.0f || dy != 0.0f)
  65610. {
  65611. if (num < 0 || startIndex + num > numGlyphs)
  65612. num = numGlyphs - startIndex;
  65613. while (--num >= 0)
  65614. {
  65615. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  65616. glyphs [startIndex++].moveBy (dx, dy);
  65617. }
  65618. }
  65619. }
  65620. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  65621. const float horizontalScaleFactor) throw()
  65622. {
  65623. jassert (startIndex >= 0);
  65624. if (num < 0 || startIndex + num > numGlyphs)
  65625. num = numGlyphs - startIndex;
  65626. if (num > 0)
  65627. {
  65628. const float xAnchor = glyphs[startIndex].getLeft();
  65629. while (--num >= 0)
  65630. {
  65631. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  65632. PositionedGlyph& pg = glyphs[startIndex++];
  65633. pg.x = xAnchor + (pg.x - xAnchor) * horizontalScaleFactor;
  65634. pg.fontHorizontalScale *= horizontalScaleFactor;
  65635. pg.w *= horizontalScaleFactor;
  65636. }
  65637. }
  65638. }
  65639. void GlyphArrangement::getBoundingBox (int startIndex, int num,
  65640. float& left,
  65641. float& top,
  65642. float& right,
  65643. float& bottom,
  65644. const bool includeWhitespace) const throw()
  65645. {
  65646. jassert (startIndex >= 0);
  65647. if (num < 0 || startIndex + num > numGlyphs)
  65648. num = numGlyphs - startIndex;
  65649. left = 0.0f;
  65650. top = 0.0f;
  65651. right = 0.0f;
  65652. bottom = 0.0f;
  65653. bool isFirst = true;
  65654. while (--num >= 0)
  65655. {
  65656. const PositionedGlyph& pg = glyphs [startIndex++];
  65657. if (includeWhitespace || ! pg.isWhitespace())
  65658. {
  65659. if (isFirst)
  65660. {
  65661. isFirst = false;
  65662. left = pg.getLeft();
  65663. top = pg.getTop();
  65664. right = pg.getRight();
  65665. bottom = pg.getBottom();
  65666. }
  65667. else
  65668. {
  65669. left = jmin (left, pg.getLeft());
  65670. top = jmin (top, pg.getTop());
  65671. right = jmax (right, pg.getRight());
  65672. bottom = jmax (bottom, pg.getBottom());
  65673. }
  65674. }
  65675. }
  65676. }
  65677. void GlyphArrangement::justifyGlyphs (const int startIndex,
  65678. const int num,
  65679. const float x, const float y,
  65680. const float width, const float height,
  65681. const Justification& justification) throw()
  65682. {
  65683. jassert (num >= 0 && startIndex >= 0);
  65684. if (numGlyphs > 0 && num > 0)
  65685. {
  65686. float left, top, right, bottom;
  65687. getBoundingBox (startIndex, num, left, top, right, bottom,
  65688. ! justification.testFlags (Justification::horizontallyJustified
  65689. | Justification::horizontallyCentred));
  65690. float deltaX = 0.0f;
  65691. if (justification.testFlags (Justification::horizontallyJustified))
  65692. deltaX = x - left;
  65693. else if (justification.testFlags (Justification::horizontallyCentred))
  65694. deltaX = x + (width - (right - left)) * 0.5f - left;
  65695. else if (justification.testFlags (Justification::right))
  65696. deltaX = (x + width) - right;
  65697. else
  65698. deltaX = x - left;
  65699. float deltaY = 0.0f;
  65700. if (justification.testFlags (Justification::top))
  65701. deltaY = y - top;
  65702. else if (justification.testFlags (Justification::bottom))
  65703. deltaY = (y + height) - bottom;
  65704. else
  65705. deltaY = y + (height - (bottom - top)) * 0.5f - top;
  65706. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  65707. if (justification.testFlags (Justification::horizontallyJustified))
  65708. {
  65709. int lineStart = 0;
  65710. float baseY = glyphs [startIndex].getBaselineY();
  65711. int i;
  65712. for (i = 0; i < num; ++i)
  65713. {
  65714. const float glyphY = glyphs [startIndex + i].getBaselineY();
  65715. if (glyphY != baseY)
  65716. {
  65717. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  65718. lineStart = i;
  65719. baseY = glyphY;
  65720. }
  65721. }
  65722. if (i > lineStart)
  65723. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  65724. }
  65725. }
  65726. }
  65727. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth) throw()
  65728. {
  65729. if (start + num < numGlyphs
  65730. && glyphs [start + num - 1].getCharacter() != T('\r')
  65731. && glyphs [start + num - 1].getCharacter() != T('\n'))
  65732. {
  65733. int numSpaces = 0;
  65734. int spacesAtEnd = 0;
  65735. for (int i = 0; i < num; ++i)
  65736. {
  65737. if (glyphs [start + i].isWhitespace())
  65738. {
  65739. ++spacesAtEnd;
  65740. ++numSpaces;
  65741. }
  65742. else
  65743. {
  65744. spacesAtEnd = 0;
  65745. }
  65746. }
  65747. numSpaces -= spacesAtEnd;
  65748. if (numSpaces > 0)
  65749. {
  65750. const float startX = glyphs [start].getLeft();
  65751. const float endX = glyphs [start + num - 1 - spacesAtEnd].getRight();
  65752. const float extraPaddingBetweenWords
  65753. = (targetWidth - (endX - startX)) / (float) numSpaces;
  65754. float deltaX = 0.0f;
  65755. for (int i = 0; i < num; ++i)
  65756. {
  65757. glyphs [start + i].moveBy (deltaX, 0.0);
  65758. if (glyphs [start + i].isWhitespace())
  65759. deltaX += extraPaddingBetweenWords;
  65760. }
  65761. }
  65762. }
  65763. }
  65764. void GlyphArrangement::draw (const Graphics& g) const throw()
  65765. {
  65766. for (int i = 0; i < numGlyphs; ++i)
  65767. {
  65768. glyphs[i].draw (g);
  65769. if (glyphs[i].isUnderlined)
  65770. {
  65771. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  65772. juce_wchar nextChar = 0;
  65773. if (i < numGlyphs - 1
  65774. && glyphs[i + 1].y == glyphs[i].y)
  65775. {
  65776. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  65777. }
  65778. g.fillRect (glyphs[i].x,
  65779. glyphs[i].y + lineThickness * 2.0f,
  65780. glyphs[i].fontHeight
  65781. * glyphs[i].fontHorizontalScale
  65782. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  65783. lineThickness);
  65784. }
  65785. }
  65786. }
  65787. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const throw()
  65788. {
  65789. for (int i = 0; i < numGlyphs; ++i)
  65790. {
  65791. glyphs[i].draw (g, transform);
  65792. if (glyphs[i].isUnderlined)
  65793. {
  65794. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  65795. juce_wchar nextChar = 0;
  65796. if (i < numGlyphs - 1
  65797. && glyphs[i + 1].y == glyphs[i].y)
  65798. {
  65799. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  65800. }
  65801. Path p;
  65802. p.addLineSegment (glyphs[i].x,
  65803. glyphs[i].y + lineThickness * 2.5f,
  65804. glyphs[i].x + glyphs[i].fontHeight
  65805. * glyphs[i].fontHorizontalScale
  65806. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  65807. glyphs[i].y + lineThickness * 2.5f,
  65808. lineThickness);
  65809. g.fillPath (p, transform);
  65810. }
  65811. }
  65812. }
  65813. void GlyphArrangement::createPath (Path& path) const throw()
  65814. {
  65815. for (int i = 0; i < numGlyphs; ++i)
  65816. glyphs[i].createPath (path);
  65817. }
  65818. int GlyphArrangement::findGlyphIndexAt (float x, float y) const throw()
  65819. {
  65820. for (int i = 0; i < numGlyphs; ++i)
  65821. if (glyphs[i].hitTest (x, y))
  65822. return i;
  65823. return -1;
  65824. }
  65825. END_JUCE_NAMESPACE
  65826. /********* End of inlined file: juce_GlyphArrangement.cpp *********/
  65827. /********* Start of inlined file: juce_TextLayout.cpp *********/
  65828. BEGIN_JUCE_NAMESPACE
  65829. class TextLayoutToken
  65830. {
  65831. public:
  65832. String text;
  65833. Font font;
  65834. int x, y, w, h;
  65835. int line, lineHeight;
  65836. bool isWhitespace, isNewLine;
  65837. TextLayoutToken (const String& t,
  65838. const Font& f,
  65839. const bool isWhitespace_) throw()
  65840. : text (t),
  65841. font (f),
  65842. x(0),
  65843. y(0),
  65844. isWhitespace (isWhitespace_)
  65845. {
  65846. w = font.getStringWidth (t);
  65847. h = roundFloatToInt (f.getHeight());
  65848. isNewLine = t.containsAnyOf (T("\r\n"));
  65849. }
  65850. TextLayoutToken (const TextLayoutToken& other) throw()
  65851. : text (other.text),
  65852. font (other.font),
  65853. x (other.x),
  65854. y (other.y),
  65855. w (other.w),
  65856. h (other.h),
  65857. line (other.line),
  65858. lineHeight (other.lineHeight),
  65859. isWhitespace (other.isWhitespace),
  65860. isNewLine (other.isNewLine)
  65861. {
  65862. }
  65863. ~TextLayoutToken() throw()
  65864. {
  65865. }
  65866. void draw (Graphics& g,
  65867. const int xOffset,
  65868. const int yOffset) throw()
  65869. {
  65870. if (! isWhitespace)
  65871. {
  65872. g.setFont (font);
  65873. g.drawSingleLineText (text.trimEnd(),
  65874. xOffset + x,
  65875. yOffset + y + (lineHeight - h)
  65876. + roundFloatToInt (font.getAscent()));
  65877. }
  65878. }
  65879. juce_UseDebuggingNewOperator
  65880. };
  65881. TextLayout::TextLayout() throw()
  65882. : tokens (64),
  65883. totalLines (0)
  65884. {
  65885. }
  65886. TextLayout::TextLayout (const String& text,
  65887. const Font& font) throw()
  65888. : tokens (64),
  65889. totalLines (0)
  65890. {
  65891. appendText (text, font);
  65892. }
  65893. TextLayout::TextLayout (const TextLayout& other) throw()
  65894. : tokens (64),
  65895. totalLines (0)
  65896. {
  65897. *this = other;
  65898. }
  65899. const TextLayout& TextLayout::operator= (const TextLayout& other) throw()
  65900. {
  65901. if (this != &other)
  65902. {
  65903. clear();
  65904. totalLines = other.totalLines;
  65905. for (int i = 0; i < other.tokens.size(); ++i)
  65906. tokens.add (new TextLayoutToken (*(const TextLayoutToken*)(other.tokens.getUnchecked(i))));
  65907. }
  65908. return *this;
  65909. }
  65910. TextLayout::~TextLayout() throw()
  65911. {
  65912. clear();
  65913. }
  65914. void TextLayout::clear() throw()
  65915. {
  65916. for (int i = tokens.size(); --i >= 0;)
  65917. {
  65918. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  65919. delete t;
  65920. }
  65921. tokens.clear();
  65922. totalLines = 0;
  65923. }
  65924. void TextLayout::appendText (const String& text,
  65925. const Font& font) throw()
  65926. {
  65927. const tchar* t = text;
  65928. String currentString;
  65929. int lastCharType = 0;
  65930. for (;;)
  65931. {
  65932. const tchar c = *t++;
  65933. if (c == 0)
  65934. break;
  65935. int charType;
  65936. if (c == T('\r') || c == T('\n'))
  65937. {
  65938. charType = 0;
  65939. }
  65940. else if (CharacterFunctions::isWhitespace (c))
  65941. {
  65942. charType = 2;
  65943. }
  65944. else
  65945. {
  65946. charType = 1;
  65947. }
  65948. if (charType == 0 || charType != lastCharType)
  65949. {
  65950. if (currentString.isNotEmpty())
  65951. {
  65952. tokens.add (new TextLayoutToken (currentString, font,
  65953. lastCharType == 2 || lastCharType == 0));
  65954. }
  65955. currentString = String::charToString (c);
  65956. if (c == T('\r') && *t == T('\n'))
  65957. currentString += *t++;
  65958. }
  65959. else
  65960. {
  65961. currentString += c;
  65962. }
  65963. lastCharType = charType;
  65964. }
  65965. if (currentString.isNotEmpty())
  65966. tokens.add (new TextLayoutToken (currentString,
  65967. font,
  65968. lastCharType == 2));
  65969. }
  65970. void TextLayout::setText (const String& text, const Font& font) throw()
  65971. {
  65972. clear();
  65973. appendText (text, font);
  65974. }
  65975. void TextLayout::layout (int maxWidth,
  65976. const Justification& justification,
  65977. const bool attemptToBalanceLineLengths) throw()
  65978. {
  65979. if (attemptToBalanceLineLengths)
  65980. {
  65981. const int originalW = maxWidth;
  65982. int bestWidth = maxWidth;
  65983. float bestLineProportion = 0.0f;
  65984. while (maxWidth > originalW / 2)
  65985. {
  65986. layout (maxWidth, justification, false);
  65987. if (getNumLines() <= 1)
  65988. return;
  65989. const int lastLineW = getLineWidth (getNumLines() - 1);
  65990. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  65991. const float prop = lastLineW / (float) lastButOneLineW;
  65992. if (prop > 0.9f)
  65993. return;
  65994. if (prop > bestLineProportion)
  65995. {
  65996. bestLineProportion = prop;
  65997. bestWidth = maxWidth;
  65998. }
  65999. maxWidth -= 10;
  66000. }
  66001. layout (bestWidth, justification, false);
  66002. }
  66003. else
  66004. {
  66005. int x = 0;
  66006. int y = 0;
  66007. int h = 0;
  66008. totalLines = 0;
  66009. int i;
  66010. for (i = 0; i < tokens.size(); ++i)
  66011. {
  66012. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  66013. t->x = x;
  66014. t->y = y;
  66015. t->line = totalLines;
  66016. x += t->w;
  66017. h = jmax (h, t->h);
  66018. const TextLayoutToken* nextTok = (TextLayoutToken*) tokens [i + 1];
  66019. if (nextTok == 0)
  66020. break;
  66021. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  66022. {
  66023. // finished a line, so go back and update the heights of the things on it
  66024. for (int j = i; j >= 0; --j)
  66025. {
  66026. TextLayoutToken* const tok = (TextLayoutToken*)tokens.getUnchecked(j);
  66027. if (tok->line == totalLines)
  66028. tok->lineHeight = h;
  66029. else
  66030. break;
  66031. }
  66032. x = 0;
  66033. y += h;
  66034. h = 0;
  66035. ++totalLines;
  66036. }
  66037. }
  66038. // finished a line, so go back and update the heights of the things on it
  66039. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  66040. {
  66041. TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(j);
  66042. if (t->line == totalLines)
  66043. t->lineHeight = h;
  66044. else
  66045. break;
  66046. }
  66047. ++totalLines;
  66048. if (! justification.testFlags (Justification::left))
  66049. {
  66050. int totalW = getWidth();
  66051. for (i = totalLines; --i >= 0;)
  66052. {
  66053. const int lineW = getLineWidth (i);
  66054. int dx = 0;
  66055. if (justification.testFlags (Justification::horizontallyCentred))
  66056. dx = (totalW - lineW) / 2;
  66057. else if (justification.testFlags (Justification::right))
  66058. dx = totalW - lineW;
  66059. for (int j = tokens.size(); --j >= 0;)
  66060. {
  66061. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(j);
  66062. if (t->line == i)
  66063. t->x += dx;
  66064. }
  66065. }
  66066. }
  66067. }
  66068. }
  66069. int TextLayout::getLineWidth (const int lineNumber) const throw()
  66070. {
  66071. int maxW = 0;
  66072. for (int i = tokens.size(); --i >= 0;)
  66073. {
  66074. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  66075. if (t->line == lineNumber && ! t->isWhitespace)
  66076. maxW = jmax (maxW, t->x + t->w);
  66077. }
  66078. return maxW;
  66079. }
  66080. int TextLayout::getWidth() const throw()
  66081. {
  66082. int maxW = 0;
  66083. for (int i = tokens.size(); --i >= 0;)
  66084. {
  66085. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  66086. if (! t->isWhitespace)
  66087. maxW = jmax (maxW, t->x + t->w);
  66088. }
  66089. return maxW;
  66090. }
  66091. int TextLayout::getHeight() const throw()
  66092. {
  66093. int maxH = 0;
  66094. for (int i = tokens.size(); --i >= 0;)
  66095. {
  66096. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  66097. if (! t->isWhitespace)
  66098. maxH = jmax (maxH, t->y + t->h);
  66099. }
  66100. return maxH;
  66101. }
  66102. void TextLayout::draw (Graphics& g,
  66103. const int xOffset,
  66104. const int yOffset) const throw()
  66105. {
  66106. for (int i = tokens.size(); --i >= 0;)
  66107. ((TextLayoutToken*) tokens.getUnchecked(i))->draw (g, xOffset, yOffset);
  66108. }
  66109. void TextLayout::drawWithin (Graphics& g,
  66110. int x, int y, int w, int h,
  66111. const Justification& justification) const throw()
  66112. {
  66113. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  66114. x, y, w, h);
  66115. draw (g, x, y);
  66116. }
  66117. END_JUCE_NAMESPACE
  66118. /********* End of inlined file: juce_TextLayout.cpp *********/
  66119. /********* Start of inlined file: juce_Typeface.cpp *********/
  66120. BEGIN_JUCE_NAMESPACE
  66121. TypefaceGlyphInfo::TypefaceGlyphInfo (const juce_wchar character_,
  66122. const Path& shape,
  66123. const float horizontalSeparation,
  66124. Typeface* const typeface_) throw()
  66125. : character (character_),
  66126. path (shape),
  66127. width (horizontalSeparation),
  66128. typeface (typeface_)
  66129. {
  66130. }
  66131. TypefaceGlyphInfo::~TypefaceGlyphInfo() throw()
  66132. {
  66133. }
  66134. float TypefaceGlyphInfo::getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  66135. {
  66136. if (subsequentCharacter != 0)
  66137. {
  66138. const KerningPair* const pairs = (const KerningPair*) kerningPairs.getData();
  66139. const int numPairs = getNumKerningPairs();
  66140. for (int i = 0; i < numPairs; ++i)
  66141. if (pairs [i].character2 == subsequentCharacter)
  66142. return width + pairs [i].kerningAmount;
  66143. }
  66144. return width;
  66145. }
  66146. void TypefaceGlyphInfo::addKerningPair (const juce_wchar subsequentCharacter,
  66147. const float extraKerningAmount) throw()
  66148. {
  66149. const int numPairs = getNumKerningPairs();
  66150. kerningPairs.setSize ((numPairs + 1) * sizeof (KerningPair));
  66151. KerningPair& p = getKerningPair (numPairs);
  66152. p.character2 = subsequentCharacter;
  66153. p.kerningAmount = extraKerningAmount;
  66154. }
  66155. TypefaceGlyphInfo::KerningPair& TypefaceGlyphInfo::getKerningPair (const int index) const throw()
  66156. {
  66157. return ((KerningPair*) kerningPairs.getData()) [index];
  66158. }
  66159. int TypefaceGlyphInfo::getNumKerningPairs() const throw()
  66160. {
  66161. return kerningPairs.getSize() / sizeof (KerningPair);
  66162. }
  66163. Typeface::Typeface() throw()
  66164. : hash (0),
  66165. isFullyPopulated (false)
  66166. {
  66167. zeromem (lookupTable, sizeof (lookupTable));
  66168. }
  66169. Typeface::Typeface (const Typeface& other)
  66170. : typefaceName (other.typefaceName),
  66171. ascent (other.ascent),
  66172. bold (other.bold),
  66173. italic (other.italic),
  66174. isFullyPopulated (other.isFullyPopulated),
  66175. defaultCharacter (other.defaultCharacter)
  66176. {
  66177. zeromem (lookupTable, sizeof (lookupTable));
  66178. for (int i = 0; i < other.glyphs.size(); ++i)
  66179. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  66180. updateHashCode();
  66181. }
  66182. Typeface::Typeface (const String& faceName,
  66183. const bool bold,
  66184. const bool italic)
  66185. : isFullyPopulated (false)
  66186. {
  66187. zeromem (lookupTable, sizeof (lookupTable));
  66188. initialiseTypefaceCharacteristics (faceName, bold, italic, false);
  66189. updateHashCode();
  66190. }
  66191. Typeface::~Typeface()
  66192. {
  66193. clear();
  66194. }
  66195. const Typeface& Typeface::operator= (const Typeface& other) throw()
  66196. {
  66197. if (this != &other)
  66198. {
  66199. clear();
  66200. typefaceName = other.typefaceName;
  66201. ascent = other.ascent;
  66202. bold = other.bold;
  66203. italic = other.italic;
  66204. isFullyPopulated = other.isFullyPopulated;
  66205. defaultCharacter = other.defaultCharacter;
  66206. for (int i = 0; i < other.glyphs.size(); ++i)
  66207. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  66208. updateHashCode();
  66209. }
  66210. return *this;
  66211. }
  66212. void Typeface::updateHashCode() throw()
  66213. {
  66214. hash = typefaceName.hashCode();
  66215. if (bold)
  66216. hash ^= 0xffff;
  66217. if (italic)
  66218. hash ^= 0xffff0000;
  66219. }
  66220. void Typeface::clear() throw()
  66221. {
  66222. zeromem (lookupTable, sizeof (lookupTable));
  66223. typefaceName = String::empty;
  66224. bold = false;
  66225. italic = false;
  66226. for (int i = glyphs.size(); --i >= 0;)
  66227. {
  66228. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) (glyphs.getUnchecked(i));
  66229. delete g;
  66230. }
  66231. glyphs.clear();
  66232. updateHashCode();
  66233. }
  66234. Typeface::Typeface (InputStream& serialisedTypefaceStream)
  66235. {
  66236. zeromem (lookupTable, sizeof (lookupTable));
  66237. isFullyPopulated = true;
  66238. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  66239. BufferedInputStream in (&gzin, 32768, false);
  66240. typefaceName = in.readString();
  66241. bold = in.readBool();
  66242. italic = in.readBool();
  66243. ascent = in.readFloat();
  66244. defaultCharacter = (juce_wchar) in.readShort();
  66245. int i, numChars = in.readInt();
  66246. for (i = 0; i < numChars; ++i)
  66247. {
  66248. const juce_wchar c = (juce_wchar) in.readShort();
  66249. const float width = in.readFloat();
  66250. Path p;
  66251. p.loadPathFromStream (in);
  66252. addGlyph (c, p, width);
  66253. }
  66254. const int numKerningPairs = in.readInt();
  66255. for (i = 0; i < numKerningPairs; ++i)
  66256. {
  66257. const juce_wchar char1 = (juce_wchar) in.readShort();
  66258. const juce_wchar char2 = (juce_wchar) in.readShort();
  66259. addKerningPair (char1, char2, in.readFloat());
  66260. }
  66261. updateHashCode();
  66262. }
  66263. void Typeface::serialise (OutputStream& outputStream)
  66264. {
  66265. GZIPCompressorOutputStream out (&outputStream);
  66266. out.writeString (typefaceName);
  66267. out.writeBool (bold);
  66268. out.writeBool (italic);
  66269. out.writeFloat (ascent);
  66270. out.writeShort ((short) (unsigned short) defaultCharacter);
  66271. out.writeInt (glyphs.size());
  66272. int i, numKerningPairs = 0;
  66273. for (i = 0; i < glyphs.size(); ++i)
  66274. {
  66275. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  66276. out.writeShort ((short) (unsigned short) g.character);
  66277. out.writeFloat (g.width);
  66278. g.path.writePathToStream (out);
  66279. numKerningPairs += g.getNumKerningPairs();
  66280. }
  66281. out.writeInt (numKerningPairs);
  66282. for (i = 0; i < glyphs.size(); ++i)
  66283. {
  66284. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  66285. for (int j = 0; j < g.getNumKerningPairs(); ++j)
  66286. {
  66287. const TypefaceGlyphInfo::KerningPair& p = g.getKerningPair (j);
  66288. out.writeShort ((short) (unsigned short) g.character);
  66289. out.writeShort ((short) (unsigned short) p.character2);
  66290. out.writeFloat (p.kerningAmount);
  66291. }
  66292. }
  66293. }
  66294. const Path* Typeface::getOutlineForGlyph (const juce_wchar character) throw()
  66295. {
  66296. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) getGlyph (character);
  66297. if (g != 0)
  66298. return &(g->path);
  66299. else
  66300. return 0;
  66301. }
  66302. const TypefaceGlyphInfo* Typeface::getGlyph (const juce_wchar character) throw()
  66303. {
  66304. if (((unsigned int) character) < 128 && lookupTable [character] > 0)
  66305. return (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  66306. for (int i = 0; i < glyphs.size(); ++i)
  66307. {
  66308. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  66309. if (g->character == character)
  66310. return g;
  66311. }
  66312. if ((! isFullyPopulated)
  66313. && findAndAddSystemGlyph (character))
  66314. {
  66315. for (int i = 0; i < glyphs.size(); ++i)
  66316. {
  66317. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  66318. if (g->character == character)
  66319. return g;
  66320. }
  66321. }
  66322. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  66323. {
  66324. const TypefaceGlyphInfo* spaceGlyph = getGlyph (L' ');
  66325. if (spaceGlyph != 0)
  66326. {
  66327. // Add a copy of the empty glyph, mapped onto this character
  66328. addGlyph (character, spaceGlyph->getPath(), spaceGlyph->getHorizontalSpacing (0));
  66329. spaceGlyph = (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  66330. }
  66331. return spaceGlyph;
  66332. }
  66333. else if (character != defaultCharacter)
  66334. {
  66335. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  66336. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  66337. if (fallbackTypeface != 0 && fallbackTypeface != this)
  66338. return fallbackTypeface->getGlyph (character);
  66339. return getGlyph (defaultCharacter);
  66340. }
  66341. return 0;
  66342. }
  66343. void Typeface::addGlyph (const juce_wchar character,
  66344. const Path& path,
  66345. const float horizontalSpacing) throw()
  66346. {
  66347. #ifdef JUCE_DEBUG
  66348. for (int i = 0; i < glyphs.size(); ++i)
  66349. {
  66350. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  66351. if (g->character == character)
  66352. jassertfalse;
  66353. }
  66354. #endif
  66355. if (((unsigned int) character) < 128)
  66356. lookupTable [character] = (short) glyphs.size();
  66357. glyphs.add (new TypefaceGlyphInfo (character,
  66358. path,
  66359. horizontalSpacing,
  66360. this));
  66361. }
  66362. void Typeface::addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw()
  66363. {
  66364. if (glyphInfoToCopy != 0)
  66365. {
  66366. if (glyphInfoToCopy->character > 0 && glyphInfoToCopy->character < 128)
  66367. lookupTable [glyphInfoToCopy->character] = (short) glyphs.size();
  66368. TypefaceGlyphInfo* const newOne
  66369. = new TypefaceGlyphInfo (glyphInfoToCopy->character,
  66370. glyphInfoToCopy->path,
  66371. glyphInfoToCopy->width,
  66372. this);
  66373. newOne->kerningPairs = glyphInfoToCopy->kerningPairs;
  66374. glyphs.add (newOne);
  66375. }
  66376. }
  66377. void Typeface::addKerningPair (const juce_wchar char1,
  66378. const juce_wchar char2,
  66379. const float extraAmount) throw()
  66380. {
  66381. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) getGlyph (char1);
  66382. if (g != 0)
  66383. g->addKerningPair (char2, extraAmount);
  66384. }
  66385. void Typeface::setName (const String& name) throw()
  66386. {
  66387. typefaceName = name;
  66388. updateHashCode();
  66389. }
  66390. void Typeface::setAscent (const float newAscent) throw()
  66391. {
  66392. ascent = newAscent;
  66393. }
  66394. void Typeface::setDefaultCharacter (const juce_wchar newDefaultCharacter) throw()
  66395. {
  66396. defaultCharacter = newDefaultCharacter;
  66397. }
  66398. void Typeface::setBold (const bool shouldBeBold) throw()
  66399. {
  66400. bold = shouldBeBold;
  66401. updateHashCode();
  66402. }
  66403. void Typeface::setItalic (const bool shouldBeItalic) throw()
  66404. {
  66405. italic = shouldBeItalic;
  66406. updateHashCode();
  66407. }
  66408. class TypefaceCache;
  66409. static TypefaceCache* typefaceCacheInstance = 0;
  66410. void clearUpDefaultFontNames() throw(); // in juce_Font.cpp
  66411. class TypefaceCache : private DeletedAtShutdown
  66412. {
  66413. private:
  66414. struct CachedFace
  66415. {
  66416. CachedFace() throw()
  66417. : lastUsageCount (0),
  66418. flags (0)
  66419. {
  66420. }
  66421. String typefaceName;
  66422. int lastUsageCount;
  66423. int flags;
  66424. Typeface::Ptr typeFace;
  66425. };
  66426. int counter;
  66427. OwnedArray <CachedFace> faces;
  66428. TypefaceCache (const TypefaceCache&);
  66429. const TypefaceCache& operator= (const TypefaceCache&);
  66430. public:
  66431. TypefaceCache (int numToCache = 10)
  66432. : counter (1),
  66433. faces (2)
  66434. {
  66435. while (--numToCache >= 0)
  66436. {
  66437. CachedFace* const face = new CachedFace();
  66438. face->typeFace = new Typeface();
  66439. faces.add (face);
  66440. }
  66441. }
  66442. ~TypefaceCache()
  66443. {
  66444. faces.clear();
  66445. jassert (typefaceCacheInstance == this);
  66446. typefaceCacheInstance = 0;
  66447. // just a courtesy call to get avoid leaking these strings at shutdown
  66448. clearUpDefaultFontNames();
  66449. }
  66450. static TypefaceCache* getInstance() throw()
  66451. {
  66452. if (typefaceCacheInstance == 0)
  66453. typefaceCacheInstance = new TypefaceCache();
  66454. return typefaceCacheInstance;
  66455. }
  66456. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  66457. {
  66458. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  66459. int i;
  66460. for (i = faces.size(); --i >= 0;)
  66461. {
  66462. CachedFace* const face = faces.getUnchecked(i);
  66463. if (face->flags == flags
  66464. && face->typefaceName == font.getTypefaceName())
  66465. {
  66466. face->lastUsageCount = ++counter;
  66467. return face->typeFace;
  66468. }
  66469. }
  66470. int replaceIndex = 0;
  66471. int bestLastUsageCount = INT_MAX;
  66472. for (i = faces.size(); --i >= 0;)
  66473. {
  66474. const int lu = faces.getUnchecked(i)->lastUsageCount;
  66475. if (bestLastUsageCount > lu)
  66476. {
  66477. bestLastUsageCount = lu;
  66478. replaceIndex = i;
  66479. }
  66480. }
  66481. CachedFace* const face = faces.getUnchecked (replaceIndex);
  66482. face->typefaceName = font.getTypefaceName();
  66483. face->flags = flags;
  66484. face->lastUsageCount = ++counter;
  66485. face->typeFace = new Typeface (font.getTypefaceName(),
  66486. font.isBold(),
  66487. font.isItalic());
  66488. return face->typeFace;
  66489. }
  66490. };
  66491. const Typeface::Ptr Typeface::getTypefaceFor (const Font& font) throw()
  66492. {
  66493. return TypefaceCache::getInstance()->findTypefaceFor (font);
  66494. }
  66495. END_JUCE_NAMESPACE
  66496. /********* End of inlined file: juce_Typeface.cpp *********/
  66497. /********* Start of inlined file: juce_AffineTransform.cpp *********/
  66498. BEGIN_JUCE_NAMESPACE
  66499. AffineTransform::AffineTransform() throw()
  66500. : mat00 (1.0f),
  66501. mat01 (0),
  66502. mat02 (0),
  66503. mat10 (0),
  66504. mat11 (1.0f),
  66505. mat12 (0)
  66506. {
  66507. }
  66508. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  66509. : mat00 (other.mat00),
  66510. mat01 (other.mat01),
  66511. mat02 (other.mat02),
  66512. mat10 (other.mat10),
  66513. mat11 (other.mat11),
  66514. mat12 (other.mat12)
  66515. {
  66516. }
  66517. AffineTransform::AffineTransform (const float mat00_,
  66518. const float mat01_,
  66519. const float mat02_,
  66520. const float mat10_,
  66521. const float mat11_,
  66522. const float mat12_) throw()
  66523. : mat00 (mat00_),
  66524. mat01 (mat01_),
  66525. mat02 (mat02_),
  66526. mat10 (mat10_),
  66527. mat11 (mat11_),
  66528. mat12 (mat12_)
  66529. {
  66530. }
  66531. const AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  66532. {
  66533. mat00 = other.mat00;
  66534. mat01 = other.mat01;
  66535. mat02 = other.mat02;
  66536. mat10 = other.mat10;
  66537. mat11 = other.mat11;
  66538. mat12 = other.mat12;
  66539. return *this;
  66540. }
  66541. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  66542. {
  66543. return mat00 == other.mat00
  66544. && mat01 == other.mat01
  66545. && mat02 == other.mat02
  66546. && mat10 == other.mat10
  66547. && mat11 == other.mat11
  66548. && mat12 == other.mat12;
  66549. }
  66550. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  66551. {
  66552. return ! operator== (other);
  66553. }
  66554. bool AffineTransform::isIdentity() const throw()
  66555. {
  66556. return (mat01 == 0)
  66557. && (mat02 == 0)
  66558. && (mat10 == 0)
  66559. && (mat12 == 0)
  66560. && (mat00 == 1.0f)
  66561. && (mat11 == 1.0f);
  66562. }
  66563. const AffineTransform AffineTransform::identity;
  66564. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  66565. {
  66566. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  66567. other.mat00 * mat01 + other.mat01 * mat11,
  66568. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  66569. other.mat10 * mat00 + other.mat11 * mat10,
  66570. other.mat10 * mat01 + other.mat11 * mat11,
  66571. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  66572. }
  66573. const AffineTransform AffineTransform::followedBy (const float omat00,
  66574. const float omat01,
  66575. const float omat02,
  66576. const float omat10,
  66577. const float omat11,
  66578. const float omat12) const throw()
  66579. {
  66580. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  66581. omat00 * mat01 + omat01 * mat11,
  66582. omat00 * mat02 + omat01 * mat12 + omat02,
  66583. omat10 * mat00 + omat11 * mat10,
  66584. omat10 * mat01 + omat11 * mat11,
  66585. omat10 * mat02 + omat11 * mat12 + omat12);
  66586. }
  66587. const AffineTransform AffineTransform::translated (const float dx,
  66588. const float dy) const throw()
  66589. {
  66590. return followedBy (1.0f, 0, dx,
  66591. 0, 1.0f, dy);
  66592. }
  66593. const AffineTransform AffineTransform::translation (const float dx,
  66594. const float dy) throw()
  66595. {
  66596. return AffineTransform (1.0f, 0, dx,
  66597. 0, 1.0f, dy);
  66598. }
  66599. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  66600. {
  66601. const float cosRad = cosf (rad);
  66602. const float sinRad = sinf (rad);
  66603. return followedBy (cosRad, -sinRad, 0,
  66604. sinRad, cosRad, 0);
  66605. }
  66606. const AffineTransform AffineTransform::rotation (const float rad) throw()
  66607. {
  66608. const float cosRad = cosf (rad);
  66609. const float sinRad = sinf (rad);
  66610. return AffineTransform (cosRad, -sinRad, 0,
  66611. sinRad, cosRad, 0);
  66612. }
  66613. const AffineTransform AffineTransform::rotated (const float angle,
  66614. const float pivotX,
  66615. const float pivotY) const throw()
  66616. {
  66617. return translated (-pivotX, -pivotY)
  66618. .rotated (angle)
  66619. .translated (pivotX, pivotY);
  66620. }
  66621. const AffineTransform AffineTransform::rotation (const float angle,
  66622. const float pivotX,
  66623. const float pivotY) throw()
  66624. {
  66625. return translation (-pivotX, -pivotY)
  66626. .rotated (angle)
  66627. .translated (pivotX, pivotY);
  66628. }
  66629. const AffineTransform AffineTransform::scaled (const float factorX,
  66630. const float factorY) const throw()
  66631. {
  66632. return followedBy (factorX, 0, 0,
  66633. 0, factorY, 0);
  66634. }
  66635. const AffineTransform AffineTransform::scale (const float factorX,
  66636. const float factorY) throw()
  66637. {
  66638. return AffineTransform (factorX, 0, 0,
  66639. 0, factorY, 0);
  66640. }
  66641. const AffineTransform AffineTransform::sheared (const float shearX,
  66642. const float shearY) const throw()
  66643. {
  66644. return followedBy (1.0f, shearX, 0,
  66645. shearY, 1.0f, 0);
  66646. }
  66647. const AffineTransform AffineTransform::inverted() const throw()
  66648. {
  66649. double determinant = (mat00 * mat11 - mat10 * mat01);
  66650. if (determinant != 0.0)
  66651. {
  66652. determinant = 1.0 / determinant;
  66653. const float dst00 = (float) (mat11 * determinant);
  66654. const float dst10 = (float) (-mat10 * determinant);
  66655. const float dst01 = (float) (-mat01 * determinant);
  66656. const float dst11 = (float) (mat00 * determinant);
  66657. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  66658. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  66659. }
  66660. else
  66661. {
  66662. // singularity..
  66663. return *this;
  66664. }
  66665. }
  66666. bool AffineTransform::isSingularity() const throw()
  66667. {
  66668. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  66669. }
  66670. void AffineTransform::transformPoint (float& x,
  66671. float& y) const throw()
  66672. {
  66673. const float oldX = x;
  66674. x = mat00 * oldX + mat01 * y + mat02;
  66675. y = mat10 * oldX + mat11 * y + mat12;
  66676. }
  66677. void AffineTransform::transformPoint (double& x,
  66678. double& y) const throw()
  66679. {
  66680. const double oldX = x;
  66681. x = mat00 * oldX + mat01 * y + mat02;
  66682. y = mat10 * oldX + mat11 * y + mat12;
  66683. }
  66684. END_JUCE_NAMESPACE
  66685. /********* End of inlined file: juce_AffineTransform.cpp *********/
  66686. /********* Start of inlined file: juce_BorderSize.cpp *********/
  66687. BEGIN_JUCE_NAMESPACE
  66688. BorderSize::BorderSize() throw()
  66689. : top (0),
  66690. left (0),
  66691. bottom (0),
  66692. right (0)
  66693. {
  66694. }
  66695. BorderSize::BorderSize (const BorderSize& other) throw()
  66696. : top (other.top),
  66697. left (other.left),
  66698. bottom (other.bottom),
  66699. right (other.right)
  66700. {
  66701. }
  66702. BorderSize::BorderSize (const int topGap,
  66703. const int leftGap,
  66704. const int bottomGap,
  66705. const int rightGap) throw()
  66706. : top (topGap),
  66707. left (leftGap),
  66708. bottom (bottomGap),
  66709. right (rightGap)
  66710. {
  66711. }
  66712. BorderSize::BorderSize (const int allGaps) throw()
  66713. : top (allGaps),
  66714. left (allGaps),
  66715. bottom (allGaps),
  66716. right (allGaps)
  66717. {
  66718. }
  66719. BorderSize::~BorderSize() throw()
  66720. {
  66721. }
  66722. void BorderSize::setTop (const int newTopGap) throw()
  66723. {
  66724. top = newTopGap;
  66725. }
  66726. void BorderSize::setLeft (const int newLeftGap) throw()
  66727. {
  66728. left = newLeftGap;
  66729. }
  66730. void BorderSize::setBottom (const int newBottomGap) throw()
  66731. {
  66732. bottom = newBottomGap;
  66733. }
  66734. void BorderSize::setRight (const int newRightGap) throw()
  66735. {
  66736. right = newRightGap;
  66737. }
  66738. const Rectangle BorderSize::subtractedFrom (const Rectangle& r) const throw()
  66739. {
  66740. return Rectangle (r.getX() + left,
  66741. r.getY() + top,
  66742. r.getWidth() - (left + right),
  66743. r.getHeight() - (top + bottom));
  66744. }
  66745. void BorderSize::subtractFrom (Rectangle& r) const throw()
  66746. {
  66747. r.setBounds (r.getX() + left,
  66748. r.getY() + top,
  66749. r.getWidth() - (left + right),
  66750. r.getHeight() - (top + bottom));
  66751. }
  66752. const Rectangle BorderSize::addedTo (const Rectangle& r) const throw()
  66753. {
  66754. return Rectangle (r.getX() - left,
  66755. r.getY() - top,
  66756. r.getWidth() + (left + right),
  66757. r.getHeight() + (top + bottom));
  66758. }
  66759. void BorderSize::addTo (Rectangle& r) const throw()
  66760. {
  66761. r.setBounds (r.getX() - left,
  66762. r.getY() - top,
  66763. r.getWidth() + (left + right),
  66764. r.getHeight() + (top + bottom));
  66765. }
  66766. bool BorderSize::operator== (const BorderSize& other) const throw()
  66767. {
  66768. return top == other.top
  66769. && left == other.left
  66770. && bottom == other.bottom
  66771. && right == other.right;
  66772. }
  66773. bool BorderSize::operator!= (const BorderSize& other) const throw()
  66774. {
  66775. return ! operator== (other);
  66776. }
  66777. END_JUCE_NAMESPACE
  66778. /********* End of inlined file: juce_BorderSize.cpp *********/
  66779. /********* Start of inlined file: juce_Line.cpp *********/
  66780. BEGIN_JUCE_NAMESPACE
  66781. static bool juce_lineIntersection (const float x1, const float y1,
  66782. const float x2, const float y2,
  66783. const float x3, const float y3,
  66784. const float x4, const float y4,
  66785. float& intersectionX,
  66786. float& intersectionY) throw()
  66787. {
  66788. if (x2 != x3 || y2 != y3)
  66789. {
  66790. const float dx1 = x2 - x1;
  66791. const float dy1 = y2 - y1;
  66792. const float dx2 = x4 - x3;
  66793. const float dy2 = y4 - y3;
  66794. const float divisor = dx1 * dy2 - dx2 * dy1;
  66795. if (divisor == 0)
  66796. {
  66797. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  66798. {
  66799. if (dy1 == 0 && dy2 != 0)
  66800. {
  66801. const float along = (y1 - y3) / dy2;
  66802. intersectionX = x3 + along * dx2;
  66803. intersectionY = y1;
  66804. return along >= 0 && along <= 1.0f;
  66805. }
  66806. else if (dy2 == 0 && dy1 != 0)
  66807. {
  66808. const float along = (y3 - y1) / dy1;
  66809. intersectionX = x1 + along * dx1;
  66810. intersectionY = y3;
  66811. return along >= 0 && along <= 1.0f;
  66812. }
  66813. else if (dx1 == 0 && dx2 != 0)
  66814. {
  66815. const float along = (x1 - x3) / dx2;
  66816. intersectionX = x1;
  66817. intersectionY = y3 + along * dy2;
  66818. return along >= 0 && along <= 1.0f;
  66819. }
  66820. else if (dx2 == 0 && dx1 != 0)
  66821. {
  66822. const float along = (x3 - x1) / dx1;
  66823. intersectionX = x3;
  66824. intersectionY = y1 + along * dy1;
  66825. return along >= 0 && along <= 1.0f;
  66826. }
  66827. }
  66828. intersectionX = 0.5f * (x2 + x3);
  66829. intersectionY = 0.5f * (y2 + y3);
  66830. return false;
  66831. }
  66832. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  66833. intersectionX = x1 + along1 * dx1;
  66834. intersectionY = y1 + along1 * dy1;
  66835. if (along1 < 0 || along1 > 1.0f)
  66836. return false;
  66837. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1) / divisor;
  66838. return along2 >= 0 && along2 <= 1.0f;
  66839. }
  66840. intersectionX = x2;
  66841. intersectionY = y2;
  66842. return true;
  66843. }
  66844. Line::Line() throw()
  66845. : startX (0.0f),
  66846. startY (0.0f),
  66847. endX (0.0f),
  66848. endY (0.0f)
  66849. {
  66850. }
  66851. Line::Line (const Line& other) throw()
  66852. : startX (other.startX),
  66853. startY (other.startY),
  66854. endX (other.endX),
  66855. endY (other.endY)
  66856. {
  66857. }
  66858. Line::Line (const float startX_, const float startY_,
  66859. const float endX_, const float endY_) throw()
  66860. : startX (startX_),
  66861. startY (startY_),
  66862. endX (endX_),
  66863. endY (endY_)
  66864. {
  66865. }
  66866. Line::Line (const Point& start,
  66867. const Point& end) throw()
  66868. : startX (start.getX()),
  66869. startY (start.getY()),
  66870. endX (end.getX()),
  66871. endY (end.getY())
  66872. {
  66873. }
  66874. const Line& Line::operator= (const Line& other) throw()
  66875. {
  66876. startX = other.startX;
  66877. startY = other.startY;
  66878. endX = other.endX;
  66879. endY = other.endY;
  66880. return *this;
  66881. }
  66882. Line::~Line() throw()
  66883. {
  66884. }
  66885. const Point Line::getStart() const throw()
  66886. {
  66887. return Point (startX, startY);
  66888. }
  66889. const Point Line::getEnd() const throw()
  66890. {
  66891. return Point (endX, endY);
  66892. }
  66893. void Line::setStart (const float newStartX,
  66894. const float newStartY) throw()
  66895. {
  66896. startX = newStartX;
  66897. startY = newStartY;
  66898. }
  66899. void Line::setStart (const Point& newStart) throw()
  66900. {
  66901. startX = newStart.getX();
  66902. startY = newStart.getY();
  66903. }
  66904. void Line::setEnd (const float newEndX,
  66905. const float newEndY) throw()
  66906. {
  66907. endX = newEndX;
  66908. endY = newEndY;
  66909. }
  66910. void Line::setEnd (const Point& newEnd) throw()
  66911. {
  66912. endX = newEnd.getX();
  66913. endY = newEnd.getY();
  66914. }
  66915. bool Line::operator== (const Line& other) const throw()
  66916. {
  66917. return startX == other.startX
  66918. && startY == other.startY
  66919. && endX == other.endX
  66920. && endY == other.endY;
  66921. }
  66922. bool Line::operator!= (const Line& other) const throw()
  66923. {
  66924. return startX != other.startX
  66925. || startY != other.startY
  66926. || endX != other.endX
  66927. || endY != other.endY;
  66928. }
  66929. void Line::applyTransform (const AffineTransform& transform) throw()
  66930. {
  66931. transform.transformPoint (startX, startY);
  66932. transform.transformPoint (endX, endY);
  66933. }
  66934. float Line::getLength() const throw()
  66935. {
  66936. return (float) juce_hypot (startX - endX,
  66937. startY - endY);
  66938. }
  66939. float Line::getAngle() const throw()
  66940. {
  66941. return atan2f (endX - startX,
  66942. endY - startY);
  66943. }
  66944. const Point Line::getPointAlongLine (const float distanceFromStart) const throw()
  66945. {
  66946. const float alpha = distanceFromStart / getLength();
  66947. return Point (startX + (endX - startX) * alpha,
  66948. startY + (endY - startY) * alpha);
  66949. }
  66950. const Point Line::getPointAlongLine (const float offsetX,
  66951. const float offsetY) const throw()
  66952. {
  66953. const float dx = endX - startX;
  66954. const float dy = endY - startY;
  66955. const double length = juce_hypot (dx, dy);
  66956. if (length == 0)
  66957. return Point (startX, startY);
  66958. else
  66959. return Point (startX + (float) (((dx * offsetX) - (dy * offsetY)) / length),
  66960. startY + (float) (((dy * offsetX) + (dx * offsetY)) / length));
  66961. }
  66962. const Point Line::getPointAlongLineProportionally (const float alpha) const throw()
  66963. {
  66964. return Point (startX + (endX - startX) * alpha,
  66965. startY + (endY - startY) * alpha);
  66966. }
  66967. float Line::getDistanceFromLine (const float x,
  66968. const float y) const throw()
  66969. {
  66970. const double dx = endX - startX;
  66971. const double dy = endY - startY;
  66972. const double length = dx * dx + dy * dy;
  66973. if (length > 0)
  66974. {
  66975. const double prop = ((x - startX) * dx + (y - startY) * dy) / length;
  66976. if (prop >= 0.0f && prop < 1.0f)
  66977. {
  66978. return (float) juce_hypot (x - (startX + prop * dx),
  66979. y - (startY + prop * dy));
  66980. }
  66981. }
  66982. return (float) jmin (juce_hypot (x - startX, y - startY),
  66983. juce_hypot (x - endX, y - endY));
  66984. }
  66985. float Line::findNearestPointTo (const float x,
  66986. const float y) const throw()
  66987. {
  66988. const double dx = endX - startX;
  66989. const double dy = endY - startY;
  66990. const double length = dx * dx + dy * dy;
  66991. if (length <= 0.0)
  66992. return 0.0f;
  66993. return jlimit (0.0f, 1.0f,
  66994. (float) (((x - startX) * dx + (y - startY) * dy) / length));
  66995. }
  66996. const Line Line::withShortenedStart (const float distanceToShortenBy) const throw()
  66997. {
  66998. const float length = getLength();
  66999. return Line (getPointAlongLine (jmin (distanceToShortenBy, length)),
  67000. getEnd());
  67001. }
  67002. const Line Line::withShortenedEnd (const float distanceToShortenBy) const throw()
  67003. {
  67004. const float length = getLength();
  67005. return Line (getStart(),
  67006. getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  67007. }
  67008. bool Line::clipToPath (const Path& path,
  67009. const bool keepSectionOutsidePath) throw()
  67010. {
  67011. const bool startInside = path.contains (startX, startY);
  67012. const bool endInside = path.contains (endX, endY);
  67013. if (startInside == endInside)
  67014. {
  67015. if (keepSectionOutsidePath != startInside)
  67016. {
  67017. // entirely outside the path
  67018. return false;
  67019. }
  67020. else
  67021. {
  67022. // entirely inside the path
  67023. startX = 0.0f;
  67024. startY = 0.0f;
  67025. endX = 0.0f;
  67026. endY = 0.0f;
  67027. return true;
  67028. }
  67029. }
  67030. else
  67031. {
  67032. bool changed = false;
  67033. PathFlatteningIterator iter (path, AffineTransform::identity);
  67034. while (iter.next())
  67035. {
  67036. float ix, iy;
  67037. if (intersects (Line (iter.x1, iter.y1,
  67038. iter.x2, iter.y2),
  67039. ix, iy))
  67040. {
  67041. if ((startInside && keepSectionOutsidePath)
  67042. || (endInside && ! keepSectionOutsidePath))
  67043. {
  67044. setStart (ix, iy);
  67045. }
  67046. else
  67047. {
  67048. setEnd (ix, iy);
  67049. }
  67050. changed = true;
  67051. }
  67052. }
  67053. return changed;
  67054. }
  67055. }
  67056. bool Line::intersects (const Line& line,
  67057. float& intersectionX,
  67058. float& intersectionY) const throw()
  67059. {
  67060. return juce_lineIntersection (startX, startY,
  67061. endX, endY,
  67062. line.startX, line.startY,
  67063. line.endX, line.endY,
  67064. intersectionX,
  67065. intersectionY);
  67066. }
  67067. bool Line::isVertical() const throw()
  67068. {
  67069. return startX == endX;
  67070. }
  67071. bool Line::isHorizontal() const throw()
  67072. {
  67073. return startY == endY;
  67074. }
  67075. bool Line::isPointAbove (const float x, const float y) const throw()
  67076. {
  67077. return startX != endX
  67078. && y < ((endY - startY) * (x - startX)) / (endX - startX) + startY;
  67079. }
  67080. END_JUCE_NAMESPACE
  67081. /********* End of inlined file: juce_Line.cpp *********/
  67082. /********* Start of inlined file: juce_Path.cpp *********/
  67083. BEGIN_JUCE_NAMESPACE
  67084. // tests that some co-ords aren't NaNs
  67085. #define CHECK_COORDS_ARE_VALID(x, y) \
  67086. jassert (x == x && y == y);
  67087. const float Path::lineMarker = 100001.0f;
  67088. const float Path::moveMarker = 100002.0f;
  67089. const float Path::quadMarker = 100003.0f;
  67090. const float Path::cubicMarker = 100004.0f;
  67091. const float Path::closeSubPathMarker = 100005.0f;
  67092. static const int defaultGranularity = 32;
  67093. Path::Path() throw()
  67094. : ArrayAllocationBase <float> (defaultGranularity),
  67095. numElements (0),
  67096. pathXMin (0),
  67097. pathXMax (0),
  67098. pathYMin (0),
  67099. pathYMax (0),
  67100. useNonZeroWinding (true)
  67101. {
  67102. }
  67103. Path::~Path() throw()
  67104. {
  67105. }
  67106. Path::Path (const Path& other) throw()
  67107. : ArrayAllocationBase <float> (defaultGranularity),
  67108. numElements (other.numElements),
  67109. pathXMin (other.pathXMin),
  67110. pathXMax (other.pathXMax),
  67111. pathYMin (other.pathYMin),
  67112. pathYMax (other.pathYMax),
  67113. useNonZeroWinding (other.useNonZeroWinding)
  67114. {
  67115. if (numElements > 0)
  67116. {
  67117. setAllocatedSize (numElements);
  67118. memcpy (elements, other.elements, numElements * sizeof (float));
  67119. }
  67120. }
  67121. const Path& Path::operator= (const Path& other) throw()
  67122. {
  67123. if (this != &other)
  67124. {
  67125. ensureAllocatedSize (other.numElements);
  67126. numElements = other.numElements;
  67127. pathXMin = other.pathXMin;
  67128. pathXMax = other.pathXMax;
  67129. pathYMin = other.pathYMin;
  67130. pathYMax = other.pathYMax;
  67131. useNonZeroWinding = other.useNonZeroWinding;
  67132. if (numElements > 0)
  67133. memcpy (elements, other.elements, numElements * sizeof (float));
  67134. }
  67135. return *this;
  67136. }
  67137. void Path::clear() throw()
  67138. {
  67139. numElements = 0;
  67140. pathXMin = 0;
  67141. pathYMin = 0;
  67142. pathYMax = 0;
  67143. pathXMax = 0;
  67144. }
  67145. void Path::swapWithPath (Path& other)
  67146. {
  67147. swapVariables <int> (this->numAllocated, other.numAllocated);
  67148. swapVariables <float*> (this->elements, other.elements);
  67149. swapVariables <int> (this->numElements, other.numElements);
  67150. swapVariables <float> (this->pathXMin, other.pathXMin);
  67151. swapVariables <float> (this->pathXMax, other.pathXMax);
  67152. swapVariables <float> (this->pathYMin, other.pathYMin);
  67153. swapVariables <float> (this->pathYMax, other.pathYMax);
  67154. swapVariables <bool> (this->useNonZeroWinding, other.useNonZeroWinding);
  67155. }
  67156. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  67157. {
  67158. useNonZeroWinding = isNonZero;
  67159. }
  67160. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  67161. const bool preserveProportions) throw()
  67162. {
  67163. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  67164. }
  67165. bool Path::isEmpty() const throw()
  67166. {
  67167. int i = 0;
  67168. while (i < numElements)
  67169. {
  67170. const float type = elements [i++];
  67171. if (type == moveMarker)
  67172. {
  67173. i += 2;
  67174. }
  67175. else if (type == lineMarker
  67176. || type == quadMarker
  67177. || type == cubicMarker)
  67178. {
  67179. return false;
  67180. }
  67181. }
  67182. return true;
  67183. }
  67184. void Path::getBounds (float& x, float& y,
  67185. float& w, float& h) const throw()
  67186. {
  67187. x = pathXMin;
  67188. y = pathYMin;
  67189. w = pathXMax - pathXMin;
  67190. h = pathYMax - pathYMin;
  67191. }
  67192. void Path::getBoundsTransformed (const AffineTransform& transform,
  67193. float& x, float& y,
  67194. float& w, float& h) const throw()
  67195. {
  67196. float x1 = pathXMin;
  67197. float y1 = pathYMin;
  67198. transform.transformPoint (x1, y1);
  67199. float x2 = pathXMax;
  67200. float y2 = pathYMin;
  67201. transform.transformPoint (x2, y2);
  67202. float x3 = pathXMin;
  67203. float y3 = pathYMax;
  67204. transform.transformPoint (x3, y3);
  67205. float x4 = pathXMax;
  67206. float y4 = pathYMax;
  67207. transform.transformPoint (x4, y4);
  67208. x = jmin (x1, x2, x3, x4);
  67209. y = jmin (y1, y2, y3, y4);
  67210. w = jmax (x1, x2, x3, x4) - x;
  67211. h = jmax (y1, y2, y3, y4) - y;
  67212. }
  67213. void Path::startNewSubPath (const float x,
  67214. const float y) throw()
  67215. {
  67216. CHECK_COORDS_ARE_VALID (x, y);
  67217. if (numElements == 0)
  67218. {
  67219. pathXMin = pathXMax = x;
  67220. pathYMin = pathYMax = y;
  67221. }
  67222. else
  67223. {
  67224. pathXMin = jmin (pathXMin, x);
  67225. pathXMax = jmax (pathXMax, x);
  67226. pathYMin = jmin (pathYMin, y);
  67227. pathYMax = jmax (pathYMax, y);
  67228. }
  67229. ensureAllocatedSize (numElements + 3);
  67230. elements [numElements++] = moveMarker;
  67231. elements [numElements++] = x;
  67232. elements [numElements++] = y;
  67233. }
  67234. void Path::lineTo (const float x, const float y) throw()
  67235. {
  67236. CHECK_COORDS_ARE_VALID (x, y);
  67237. if (numElements == 0)
  67238. startNewSubPath (0, 0);
  67239. ensureAllocatedSize (numElements + 3);
  67240. elements [numElements++] = lineMarker;
  67241. elements [numElements++] = x;
  67242. elements [numElements++] = y;
  67243. pathXMin = jmin (pathXMin, x);
  67244. pathXMax = jmax (pathXMax, x);
  67245. pathYMin = jmin (pathYMin, y);
  67246. pathYMax = jmax (pathYMax, y);
  67247. }
  67248. void Path::quadraticTo (const float x1, const float y1,
  67249. const float x2, const float y2) throw()
  67250. {
  67251. CHECK_COORDS_ARE_VALID (x1, y1);
  67252. CHECK_COORDS_ARE_VALID (x2, y2);
  67253. if (numElements == 0)
  67254. startNewSubPath (0, 0);
  67255. ensureAllocatedSize (numElements + 5);
  67256. elements [numElements++] = quadMarker;
  67257. elements [numElements++] = x1;
  67258. elements [numElements++] = y1;
  67259. elements [numElements++] = x2;
  67260. elements [numElements++] = y2;
  67261. pathXMin = jmin (pathXMin, x1, x2);
  67262. pathXMax = jmax (pathXMax, x1, x2);
  67263. pathYMin = jmin (pathYMin, y1, y2);
  67264. pathYMax = jmax (pathYMax, y1, y2);
  67265. }
  67266. void Path::cubicTo (const float x1, const float y1,
  67267. const float x2, const float y2,
  67268. const float x3, const float y3) throw()
  67269. {
  67270. CHECK_COORDS_ARE_VALID (x1, y1);
  67271. CHECK_COORDS_ARE_VALID (x2, y2);
  67272. CHECK_COORDS_ARE_VALID (x3, y3);
  67273. if (numElements == 0)
  67274. startNewSubPath (0, 0);
  67275. ensureAllocatedSize (numElements + 7);
  67276. elements [numElements++] = cubicMarker;
  67277. elements [numElements++] = x1;
  67278. elements [numElements++] = y1;
  67279. elements [numElements++] = x2;
  67280. elements [numElements++] = y2;
  67281. elements [numElements++] = x3;
  67282. elements [numElements++] = y3;
  67283. pathXMin = jmin (pathXMin, x1, x2, x3);
  67284. pathXMax = jmax (pathXMax, x1, x2, x3);
  67285. pathYMin = jmin (pathYMin, y1, y2, y3);
  67286. pathYMax = jmax (pathYMax, y1, y2, y3);
  67287. }
  67288. void Path::closeSubPath() throw()
  67289. {
  67290. if (numElements > 0
  67291. && elements [numElements - 1] != closeSubPathMarker)
  67292. {
  67293. ensureAllocatedSize (numElements + 1);
  67294. elements [numElements++] = closeSubPathMarker;
  67295. }
  67296. }
  67297. const Point Path::getCurrentPosition() const
  67298. {
  67299. int i = numElements - 1;
  67300. if (i > 0 && elements[i] == closeSubPathMarker)
  67301. {
  67302. while (i >= 0)
  67303. {
  67304. if (elements[i] == moveMarker)
  67305. {
  67306. i += 2;
  67307. break;
  67308. }
  67309. --i;
  67310. }
  67311. }
  67312. if (i > 0)
  67313. return Point (elements [i - 1], elements [i]);
  67314. return Point (0.0f, 0.0f);
  67315. }
  67316. void Path::addRectangle (const float x, const float y,
  67317. const float w, const float h) throw()
  67318. {
  67319. startNewSubPath (x, y + h);
  67320. lineTo (x, y);
  67321. lineTo (x + w, y);
  67322. lineTo (x + w, y + h);
  67323. closeSubPath();
  67324. }
  67325. void Path::addRoundedRectangle (const float x, const float y,
  67326. const float w, const float h,
  67327. float csx,
  67328. float csy) throw()
  67329. {
  67330. csx = jmin (csx, w * 0.5f);
  67331. csy = jmin (csy, h * 0.5f);
  67332. const float cs45x = csx * 0.45f;
  67333. const float cs45y = csy * 0.45f;
  67334. const float x2 = x + w;
  67335. const float y2 = y + h;
  67336. startNewSubPath (x + csx, y);
  67337. lineTo (x2 - csx, y);
  67338. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  67339. lineTo (x2, y2 - csy);
  67340. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  67341. lineTo (x + csx, y2);
  67342. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  67343. lineTo (x, y + csy);
  67344. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  67345. closeSubPath();
  67346. }
  67347. void Path::addRoundedRectangle (const float x, const float y,
  67348. const float w, const float h,
  67349. float cs) throw()
  67350. {
  67351. addRoundedRectangle (x, y, w, h, cs, cs);
  67352. }
  67353. void Path::addTriangle (const float x1, const float y1,
  67354. const float x2, const float y2,
  67355. const float x3, const float y3) throw()
  67356. {
  67357. startNewSubPath (x1, y1);
  67358. lineTo (x2, y2);
  67359. lineTo (x3, y3);
  67360. closeSubPath();
  67361. }
  67362. void Path::addQuadrilateral (const float x1, const float y1,
  67363. const float x2, const float y2,
  67364. const float x3, const float y3,
  67365. const float x4, const float y4) throw()
  67366. {
  67367. startNewSubPath (x1, y1);
  67368. lineTo (x2, y2);
  67369. lineTo (x3, y3);
  67370. lineTo (x4, y4);
  67371. closeSubPath();
  67372. }
  67373. void Path::addEllipse (const float x, const float y,
  67374. const float w, const float h) throw()
  67375. {
  67376. const float hw = w * 0.5f;
  67377. const float hw55 = hw * 0.55f;
  67378. const float hh = h * 0.5f;
  67379. const float hh45 = hh * 0.55f;
  67380. const float cx = x + hw;
  67381. const float cy = y + hh;
  67382. startNewSubPath (cx, cy - hh);
  67383. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  67384. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  67385. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  67386. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  67387. closeSubPath();
  67388. }
  67389. void Path::addArc (const float x, const float y,
  67390. const float w, const float h,
  67391. const float fromRadians,
  67392. const float toRadians,
  67393. const bool startAsNewSubPath) throw()
  67394. {
  67395. const float radiusX = w / 2.0f;
  67396. const float radiusY = h / 2.0f;
  67397. addCentredArc (x + radiusX,
  67398. y + radiusY,
  67399. radiusX, radiusY,
  67400. 0.0f,
  67401. fromRadians, toRadians,
  67402. startAsNewSubPath);
  67403. }
  67404. static const float ellipseAngularIncrement = 0.05f;
  67405. void Path::addCentredArc (const float centreX, const float centreY,
  67406. const float radiusX, const float radiusY,
  67407. const float rotationOfEllipse,
  67408. const float fromRadians,
  67409. const float toRadians,
  67410. const bool startAsNewSubPath) throw()
  67411. {
  67412. if (radiusX > 0.0f && radiusY > 0.0f)
  67413. {
  67414. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  67415. float angle = fromRadians;
  67416. if (startAsNewSubPath)
  67417. {
  67418. float x = centreX + radiusX * sinf (angle);
  67419. float y = centreY - radiusY * cosf (angle);
  67420. if (rotationOfEllipse != 0)
  67421. rotation.transformPoint (x, y);
  67422. startNewSubPath (x, y);
  67423. }
  67424. if (fromRadians < toRadians)
  67425. {
  67426. if (startAsNewSubPath)
  67427. angle += ellipseAngularIncrement;
  67428. while (angle < toRadians)
  67429. {
  67430. float x = centreX + radiusX * sinf (angle);
  67431. float y = centreY - radiusY * cosf (angle);
  67432. if (rotationOfEllipse != 0)
  67433. rotation.transformPoint (x, y);
  67434. lineTo (x, y);
  67435. angle += ellipseAngularIncrement;
  67436. }
  67437. }
  67438. else
  67439. {
  67440. if (startAsNewSubPath)
  67441. angle -= ellipseAngularIncrement;
  67442. while (angle > toRadians)
  67443. {
  67444. float x = centreX + radiusX * sinf (angle);
  67445. float y = centreY - radiusY * cosf (angle);
  67446. if (rotationOfEllipse != 0)
  67447. rotation.transformPoint (x, y);
  67448. lineTo (x, y);
  67449. angle -= ellipseAngularIncrement;
  67450. }
  67451. }
  67452. float x = centreX + radiusX * sinf (toRadians);
  67453. float y = centreY - radiusY * cosf (toRadians);
  67454. if (rotationOfEllipse != 0)
  67455. rotation.transformPoint (x, y);
  67456. lineTo (x, y);
  67457. }
  67458. }
  67459. void Path::addPieSegment (const float x, const float y,
  67460. const float width, const float height,
  67461. const float fromRadians,
  67462. const float toRadians,
  67463. const float innerCircleProportionalSize)
  67464. {
  67465. float hw = width * 0.5f;
  67466. float hh = height * 0.5f;
  67467. const float centreX = x + hw;
  67468. const float centreY = y + hh;
  67469. startNewSubPath (centreX + hw * sinf (fromRadians),
  67470. centreY - hh * cosf (fromRadians));
  67471. addArc (x, y, width, height, fromRadians, toRadians);
  67472. if (fabs (fromRadians - toRadians) > float_Pi * 1.999f)
  67473. {
  67474. closeSubPath();
  67475. if (innerCircleProportionalSize > 0)
  67476. {
  67477. hw *= innerCircleProportionalSize;
  67478. hh *= innerCircleProportionalSize;
  67479. startNewSubPath (centreX + hw * sinf (toRadians),
  67480. centreY - hh * cosf (toRadians));
  67481. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  67482. toRadians, fromRadians);
  67483. }
  67484. }
  67485. else
  67486. {
  67487. if (innerCircleProportionalSize > 0)
  67488. {
  67489. hw *= innerCircleProportionalSize;
  67490. hh *= innerCircleProportionalSize;
  67491. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  67492. toRadians, fromRadians);
  67493. }
  67494. else
  67495. {
  67496. lineTo (centreX, centreY);
  67497. }
  67498. }
  67499. closeSubPath();
  67500. }
  67501. static void perpendicularOffset (const float x1, const float y1,
  67502. const float x2, const float y2,
  67503. const float offsetX, const float offsetY,
  67504. float& resultX, float& resultY) throw()
  67505. {
  67506. const float dx = x2 - x1;
  67507. const float dy = y2 - y1;
  67508. const float len = juce_hypotf (dx, dy);
  67509. if (len == 0)
  67510. {
  67511. resultX = x1;
  67512. resultY = y1;
  67513. }
  67514. else
  67515. {
  67516. resultX = x1 + ((dx * offsetX) - (dy * offsetY)) / len;
  67517. resultY = y1 + ((dy * offsetX) + (dx * offsetY)) / len;
  67518. }
  67519. }
  67520. void Path::addLineSegment (const float startX, const float startY,
  67521. const float endX, const float endY,
  67522. float lineThickness) throw()
  67523. {
  67524. lineThickness *= 0.5f;
  67525. float x, y;
  67526. perpendicularOffset (startX, startY, endX, endY,
  67527. 0, lineThickness, x, y);
  67528. startNewSubPath (x, y);
  67529. perpendicularOffset (startX, startY, endX, endY,
  67530. 0, -lineThickness, x, y);
  67531. lineTo (x, y);
  67532. perpendicularOffset (endX, endY, startX, startY,
  67533. 0, lineThickness, x, y);
  67534. lineTo (x, y);
  67535. perpendicularOffset (endX, endY, startX, startY,
  67536. 0, -lineThickness, x, y);
  67537. lineTo (x, y);
  67538. closeSubPath();
  67539. }
  67540. void Path::addArrow (const float startX, const float startY,
  67541. const float endX, const float endY,
  67542. float lineThickness,
  67543. float arrowheadWidth,
  67544. float arrowheadLength) throw()
  67545. {
  67546. lineThickness *= 0.5f;
  67547. arrowheadWidth *= 0.5f;
  67548. arrowheadLength = jmin (arrowheadLength, 0.8f * juce_hypotf (startX - endX,
  67549. startY - endY));
  67550. float x, y;
  67551. perpendicularOffset (startX, startY, endX, endY,
  67552. 0, lineThickness, x, y);
  67553. startNewSubPath (x, y);
  67554. perpendicularOffset (startX, startY, endX, endY,
  67555. 0, -lineThickness, x, y);
  67556. lineTo (x, y);
  67557. perpendicularOffset (endX, endY, startX, startY,
  67558. arrowheadLength, lineThickness, x, y);
  67559. lineTo (x, y);
  67560. perpendicularOffset (endX, endY, startX, startY,
  67561. arrowheadLength, arrowheadWidth, x, y);
  67562. lineTo (x, y);
  67563. perpendicularOffset (endX, endY, startX, startY,
  67564. 0, 0, x, y);
  67565. lineTo (x, y);
  67566. perpendicularOffset (endX, endY, startX, startY,
  67567. arrowheadLength, -arrowheadWidth, x, y);
  67568. lineTo (x, y);
  67569. perpendicularOffset (endX, endY, startX, startY,
  67570. arrowheadLength, -lineThickness, x, y);
  67571. lineTo (x, y);
  67572. closeSubPath();
  67573. }
  67574. void Path::addStar (const float centreX,
  67575. const float centreY,
  67576. const int numberOfPoints,
  67577. const float innerRadius,
  67578. const float outerRadius,
  67579. const float startAngle)
  67580. {
  67581. jassert (numberOfPoints > 1); // this would be silly.
  67582. if (numberOfPoints > 1)
  67583. {
  67584. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  67585. for (int i = 0; i < numberOfPoints; ++i)
  67586. {
  67587. float angle = startAngle + i * angleBetweenPoints;
  67588. const float x = centreX + outerRadius * sinf (angle);
  67589. const float y = centreY - outerRadius * cosf (angle);
  67590. if (i == 0)
  67591. startNewSubPath (x, y);
  67592. else
  67593. lineTo (x, y);
  67594. angle += angleBetweenPoints * 0.5f;
  67595. lineTo (centreX + innerRadius * sinf (angle),
  67596. centreY - innerRadius * cosf (angle));
  67597. }
  67598. closeSubPath();
  67599. }
  67600. }
  67601. void Path::addBubble (float x, float y,
  67602. float w, float h,
  67603. float cs,
  67604. float tipX,
  67605. float tipY,
  67606. int whichSide,
  67607. float arrowPos,
  67608. float arrowWidth)
  67609. {
  67610. if (w > 1.0f && h > 1.0f)
  67611. {
  67612. cs = jmin (cs, w * 0.5f, h * 0.5f);
  67613. const float cs2 = 2.0f * cs;
  67614. startNewSubPath (x + cs, y);
  67615. if (whichSide == 0)
  67616. {
  67617. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  67618. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  67619. lineTo (arrowX1, y);
  67620. lineTo (tipX, tipY);
  67621. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  67622. }
  67623. lineTo (x + w - cs, y);
  67624. if (cs > 0.0f)
  67625. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  67626. if (whichSide == 3)
  67627. {
  67628. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  67629. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  67630. lineTo (x + w, arrowY1);
  67631. lineTo (tipX, tipY);
  67632. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  67633. }
  67634. lineTo (x + w, y + h - cs);
  67635. if (cs > 0.0f)
  67636. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  67637. if (whichSide == 2)
  67638. {
  67639. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  67640. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  67641. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  67642. lineTo (tipX, tipY);
  67643. lineTo (arrowX1, y + h);
  67644. }
  67645. lineTo (x + cs, y + h);
  67646. if (cs > 0.0f)
  67647. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  67648. if (whichSide == 1)
  67649. {
  67650. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  67651. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  67652. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  67653. lineTo (tipX, tipY);
  67654. lineTo (x, arrowY1);
  67655. }
  67656. lineTo (x, y + cs);
  67657. if (cs > 0.0f)
  67658. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - ellipseAngularIncrement);
  67659. closeSubPath();
  67660. }
  67661. }
  67662. void Path::addPath (const Path& other) throw()
  67663. {
  67664. int i = 0;
  67665. while (i < other.numElements)
  67666. {
  67667. const float type = other.elements [i++];
  67668. if (type == moveMarker)
  67669. {
  67670. startNewSubPath (other.elements [i],
  67671. other.elements [i + 1]);
  67672. i += 2;
  67673. }
  67674. else if (type == lineMarker)
  67675. {
  67676. lineTo (other.elements [i],
  67677. other.elements [i + 1]);
  67678. i += 2;
  67679. }
  67680. else if (type == quadMarker)
  67681. {
  67682. quadraticTo (other.elements [i],
  67683. other.elements [i + 1],
  67684. other.elements [i + 2],
  67685. other.elements [i + 3]);
  67686. i += 4;
  67687. }
  67688. else if (type == cubicMarker)
  67689. {
  67690. cubicTo (other.elements [i],
  67691. other.elements [i + 1],
  67692. other.elements [i + 2],
  67693. other.elements [i + 3],
  67694. other.elements [i + 4],
  67695. other.elements [i + 5]);
  67696. i += 6;
  67697. }
  67698. else if (type == closeSubPathMarker)
  67699. {
  67700. closeSubPath();
  67701. }
  67702. else
  67703. {
  67704. // something's gone wrong with the element list!
  67705. jassertfalse
  67706. }
  67707. }
  67708. }
  67709. void Path::addPath (const Path& other,
  67710. const AffineTransform& transformToApply) throw()
  67711. {
  67712. int i = 0;
  67713. while (i < other.numElements)
  67714. {
  67715. const float type = other.elements [i++];
  67716. if (type == closeSubPathMarker)
  67717. {
  67718. closeSubPath();
  67719. }
  67720. else
  67721. {
  67722. float x = other.elements [i++];
  67723. float y = other.elements [i++];
  67724. transformToApply.transformPoint (x, y);
  67725. if (type == moveMarker)
  67726. {
  67727. startNewSubPath (x, y);
  67728. }
  67729. else if (type == lineMarker)
  67730. {
  67731. lineTo (x, y);
  67732. }
  67733. else if (type == quadMarker)
  67734. {
  67735. float x2 = other.elements [i++];
  67736. float y2 = other.elements [i++];
  67737. transformToApply.transformPoint (x2, y2);
  67738. quadraticTo (x, y, x2, y2);
  67739. }
  67740. else if (type == cubicMarker)
  67741. {
  67742. float x2 = other.elements [i++];
  67743. float y2 = other.elements [i++];
  67744. float x3 = other.elements [i++];
  67745. float y3 = other.elements [i++];
  67746. transformToApply.transformPoint (x2, y2);
  67747. transformToApply.transformPoint (x3, y3);
  67748. cubicTo (x, y, x2, y2, x3, y3);
  67749. }
  67750. else
  67751. {
  67752. // something's gone wrong with the element list!
  67753. jassertfalse
  67754. }
  67755. }
  67756. }
  67757. }
  67758. void Path::applyTransform (const AffineTransform& transform) throw()
  67759. {
  67760. int i = 0;
  67761. pathYMin = pathXMin = 0;
  67762. pathYMax = pathXMax = 0;
  67763. bool setMaxMin = false;
  67764. while (i < numElements)
  67765. {
  67766. const float type = elements [i++];
  67767. if (type == moveMarker)
  67768. {
  67769. transform.transformPoint (elements [i],
  67770. elements [i + 1]);
  67771. if (setMaxMin)
  67772. {
  67773. pathXMin = jmin (pathXMin, elements [i]);
  67774. pathXMax = jmax (pathXMax, elements [i]);
  67775. pathYMin = jmin (pathYMin, elements [i + 1]);
  67776. pathYMax = jmax (pathYMax, elements [i + 1]);
  67777. }
  67778. else
  67779. {
  67780. pathXMin = pathXMax = elements [i];
  67781. pathYMin = pathYMax = elements [i + 1];
  67782. setMaxMin = true;
  67783. }
  67784. i += 2;
  67785. }
  67786. else if (type == lineMarker)
  67787. {
  67788. transform.transformPoint (elements [i],
  67789. elements [i + 1]);
  67790. pathXMin = jmin (pathXMin, elements [i]);
  67791. pathXMax = jmax (pathXMax, elements [i]);
  67792. pathYMin = jmin (pathYMin, elements [i + 1]);
  67793. pathYMax = jmax (pathYMax, elements [i + 1]);
  67794. i += 2;
  67795. }
  67796. else if (type == quadMarker)
  67797. {
  67798. transform.transformPoint (elements [i],
  67799. elements [i + 1]);
  67800. transform.transformPoint (elements [i + 2],
  67801. elements [i + 3]);
  67802. pathXMin = jmin (pathXMin, elements [i], elements [i + 2]);
  67803. pathXMax = jmax (pathXMax, elements [i], elements [i + 2]);
  67804. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3]);
  67805. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3]);
  67806. i += 4;
  67807. }
  67808. else if (type == cubicMarker)
  67809. {
  67810. transform.transformPoint (elements [i],
  67811. elements [i + 1]);
  67812. transform.transformPoint (elements [i + 2],
  67813. elements [i + 3]);
  67814. transform.transformPoint (elements [i + 4],
  67815. elements [i + 5]);
  67816. pathXMin = jmin (pathXMin, elements [i], elements [i + 2], elements [i + 4]);
  67817. pathXMax = jmax (pathXMax, elements [i], elements [i + 2], elements [i + 4]);
  67818. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3], elements [i + 5]);
  67819. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3], elements [i + 5]);
  67820. i += 6;
  67821. }
  67822. }
  67823. }
  67824. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  67825. const float w, const float h,
  67826. const bool preserveProportions,
  67827. const Justification& justification) const throw()
  67828. {
  67829. float sx, sy, sw, sh;
  67830. getBounds (sx, sy, sw, sh);
  67831. if (preserveProportions)
  67832. {
  67833. if (w <= 0 || h <= 0 || sw <= 0 || sh <= 0)
  67834. return AffineTransform::identity;
  67835. float newW, newH;
  67836. const float srcRatio = sh / sw;
  67837. if (srcRatio > h / w)
  67838. {
  67839. newW = h / srcRatio;
  67840. newH = h;
  67841. }
  67842. else
  67843. {
  67844. newW = w;
  67845. newH = w * srcRatio;
  67846. }
  67847. float newXCentre = x;
  67848. float newYCentre = y;
  67849. if (justification.testFlags (Justification::left))
  67850. newXCentre += newW * 0.5f;
  67851. else if (justification.testFlags (Justification::right))
  67852. newXCentre += w - newW * 0.5f;
  67853. else
  67854. newXCentre += w * 0.5f;
  67855. if (justification.testFlags (Justification::top))
  67856. newYCentre += newH * 0.5f;
  67857. else if (justification.testFlags (Justification::bottom))
  67858. newYCentre += h - newH * 0.5f;
  67859. else
  67860. newYCentre += h * 0.5f;
  67861. return AffineTransform::translation (sw * -0.5f - sx, sh * -0.5f - sy)
  67862. .scaled (newW / sw, newH / sh)
  67863. .translated (newXCentre, newYCentre);
  67864. }
  67865. else
  67866. {
  67867. return AffineTransform::translation (-sx, -sy)
  67868. .scaled (w / sw, h / sh)
  67869. .translated (x, y);
  67870. }
  67871. }
  67872. static const float collisionDetectionTolerence = 20.0f;
  67873. bool Path::contains (const float x, const float y) const throw()
  67874. {
  67875. if (x <= pathXMin || x >= pathXMax
  67876. || y <= pathYMin || y >= pathYMax)
  67877. return false;
  67878. PathFlatteningIterator i (*this, AffineTransform::identity, collisionDetectionTolerence);
  67879. int positiveCrossings = 0;
  67880. int negativeCrossings = 0;
  67881. while (i.next())
  67882. {
  67883. if ((i.y1 <= y && i.y2 > y)
  67884. || (i.y2 <= y && i.y1 > y))
  67885. {
  67886. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  67887. if (intersectX <= x)
  67888. {
  67889. if (i.y1 < i.y2)
  67890. ++positiveCrossings;
  67891. else
  67892. ++negativeCrossings;
  67893. }
  67894. }
  67895. }
  67896. return (useNonZeroWinding) ? (negativeCrossings != positiveCrossings)
  67897. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  67898. }
  67899. bool Path::intersectsLine (const float x1, const float y1,
  67900. const float x2, const float y2) throw()
  67901. {
  67902. PathFlatteningIterator i (*this, AffineTransform::identity, collisionDetectionTolerence);
  67903. const Line line1 (x1, y1, x2, y2);
  67904. while (i.next())
  67905. {
  67906. const Line line2 (i.x1, i.y1, i.x2, i.y2);
  67907. float ix, iy;
  67908. if (line1.intersects (line2, ix, iy))
  67909. return true;
  67910. }
  67911. return false;
  67912. }
  67913. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const throw()
  67914. {
  67915. if (cornerRadius <= 0.01f)
  67916. return *this;
  67917. int indexOfPathStart = 0, indexOfPathStartThis = 0;
  67918. int n = 0;
  67919. bool lastWasLine = false, firstWasLine = false;
  67920. Path p;
  67921. while (n < numElements)
  67922. {
  67923. const float type = elements [n++];
  67924. if (type == moveMarker)
  67925. {
  67926. indexOfPathStart = p.numElements;
  67927. indexOfPathStartThis = n - 1;
  67928. const float x = elements [n++];
  67929. const float y = elements [n++];
  67930. p.startNewSubPath (x, y);
  67931. lastWasLine = false;
  67932. firstWasLine = (elements [n] == lineMarker);
  67933. }
  67934. else if (type == lineMarker || type == closeSubPathMarker)
  67935. {
  67936. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  67937. if (type == lineMarker)
  67938. {
  67939. endX = elements [n++];
  67940. endY = elements [n++];
  67941. if (n > 8)
  67942. {
  67943. startX = elements [n - 8];
  67944. startY = elements [n - 7];
  67945. joinX = elements [n - 5];
  67946. joinY = elements [n - 4];
  67947. }
  67948. }
  67949. else
  67950. {
  67951. endX = elements [indexOfPathStartThis + 1];
  67952. endY = elements [indexOfPathStartThis + 2];
  67953. if (n > 6)
  67954. {
  67955. startX = elements [n - 6];
  67956. startY = elements [n - 5];
  67957. joinX = elements [n - 3];
  67958. joinY = elements [n - 2];
  67959. }
  67960. }
  67961. if (lastWasLine)
  67962. {
  67963. const double len1 = juce_hypot (startX - joinX,
  67964. startY - joinY);
  67965. if (len1 > 0)
  67966. {
  67967. const double propNeeded = jmin (0.5, cornerRadius / len1);
  67968. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  67969. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  67970. }
  67971. const double len2 = juce_hypot (endX - joinX,
  67972. endY - joinY);
  67973. if (len2 > 0)
  67974. {
  67975. const double propNeeded = jmin (0.5, cornerRadius / len2);
  67976. p.quadraticTo (joinX, joinY,
  67977. (float) (joinX + (endX - joinX) * propNeeded),
  67978. (float) (joinY + (endY - joinY) * propNeeded));
  67979. }
  67980. p.lineTo (endX, endY);
  67981. }
  67982. else if (type == lineMarker)
  67983. {
  67984. p.lineTo (endX, endY);
  67985. lastWasLine = true;
  67986. }
  67987. if (type == closeSubPathMarker)
  67988. {
  67989. if (firstWasLine)
  67990. {
  67991. startX = elements [n - 3];
  67992. startY = elements [n - 2];
  67993. joinX = endX;
  67994. joinY = endY;
  67995. endX = elements [indexOfPathStartThis + 4];
  67996. endY = elements [indexOfPathStartThis + 5];
  67997. const double len1 = juce_hypot (startX - joinX,
  67998. startY - joinY);
  67999. if (len1 > 0)
  68000. {
  68001. const double propNeeded = jmin (0.5, cornerRadius / len1);
  68002. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  68003. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  68004. }
  68005. const double len2 = juce_hypot (endX - joinX,
  68006. endY - joinY);
  68007. if (len2 > 0)
  68008. {
  68009. const double propNeeded = jmin (0.5, cornerRadius / len2);
  68010. endX = (float) (joinX + (endX - joinX) * propNeeded);
  68011. endY = (float) (joinY + (endY - joinY) * propNeeded);
  68012. p.quadraticTo (joinX, joinY, endX, endY);
  68013. p.elements [indexOfPathStart + 1] = endX;
  68014. p.elements [indexOfPathStart + 2] = endY;
  68015. }
  68016. }
  68017. p.closeSubPath();
  68018. }
  68019. }
  68020. else if (type == quadMarker)
  68021. {
  68022. lastWasLine = false;
  68023. const float x1 = elements [n++];
  68024. const float y1 = elements [n++];
  68025. const float x2 = elements [n++];
  68026. const float y2 = elements [n++];
  68027. p.quadraticTo (x1, y1, x2, y2);
  68028. }
  68029. else if (type == cubicMarker)
  68030. {
  68031. lastWasLine = false;
  68032. const float x1 = elements [n++];
  68033. const float y1 = elements [n++];
  68034. const float x2 = elements [n++];
  68035. const float y2 = elements [n++];
  68036. const float x3 = elements [n++];
  68037. const float y3 = elements [n++];
  68038. p.cubicTo (x1, y1, x2, y2, x3, y3);
  68039. }
  68040. }
  68041. return p;
  68042. }
  68043. void Path::loadPathFromStream (InputStream& source)
  68044. {
  68045. while (! source.isExhausted())
  68046. {
  68047. switch (source.readByte())
  68048. {
  68049. case 'm':
  68050. {
  68051. const float x = source.readFloat();
  68052. const float y = source.readFloat();
  68053. startNewSubPath (x, y);
  68054. break;
  68055. }
  68056. case 'l':
  68057. {
  68058. const float x = source.readFloat();
  68059. const float y = source.readFloat();
  68060. lineTo (x, y);
  68061. break;
  68062. }
  68063. case 'q':
  68064. {
  68065. const float x1 = source.readFloat();
  68066. const float y1 = source.readFloat();
  68067. const float x2 = source.readFloat();
  68068. const float y2 = source.readFloat();
  68069. quadraticTo (x1, y1, x2, y2);
  68070. break;
  68071. }
  68072. case 'b':
  68073. {
  68074. const float x1 = source.readFloat();
  68075. const float y1 = source.readFloat();
  68076. const float x2 = source.readFloat();
  68077. const float y2 = source.readFloat();
  68078. const float x3 = source.readFloat();
  68079. const float y3 = source.readFloat();
  68080. cubicTo (x1, y1, x2, y2, x3, y3);
  68081. break;
  68082. }
  68083. case 'c':
  68084. closeSubPath();
  68085. break;
  68086. case 'n':
  68087. useNonZeroWinding = true;
  68088. break;
  68089. case 'z':
  68090. useNonZeroWinding = false;
  68091. break;
  68092. case 'e':
  68093. return; // end of path marker
  68094. default:
  68095. jassertfalse // illegal char in the stream
  68096. break;
  68097. }
  68098. }
  68099. }
  68100. void Path::loadPathFromData (const unsigned char* const data,
  68101. const int numberOfBytes) throw()
  68102. {
  68103. MemoryInputStream in ((const char*) data, numberOfBytes, false);
  68104. loadPathFromStream (in);
  68105. }
  68106. void Path::writePathToStream (OutputStream& dest) const
  68107. {
  68108. dest.writeByte ((useNonZeroWinding) ? 'n' : 'z');
  68109. int i = 0;
  68110. while (i < numElements)
  68111. {
  68112. const float type = elements [i++];
  68113. if (type == moveMarker)
  68114. {
  68115. dest.writeByte ('m');
  68116. dest.writeFloat (elements [i++]);
  68117. dest.writeFloat (elements [i++]);
  68118. }
  68119. else if (type == lineMarker)
  68120. {
  68121. dest.writeByte ('l');
  68122. dest.writeFloat (elements [i++]);
  68123. dest.writeFloat (elements [i++]);
  68124. }
  68125. else if (type == quadMarker)
  68126. {
  68127. dest.writeByte ('q');
  68128. dest.writeFloat (elements [i++]);
  68129. dest.writeFloat (elements [i++]);
  68130. dest.writeFloat (elements [i++]);
  68131. dest.writeFloat (elements [i++]);
  68132. }
  68133. else if (type == cubicMarker)
  68134. {
  68135. dest.writeByte ('b');
  68136. dest.writeFloat (elements [i++]);
  68137. dest.writeFloat (elements [i++]);
  68138. dest.writeFloat (elements [i++]);
  68139. dest.writeFloat (elements [i++]);
  68140. dest.writeFloat (elements [i++]);
  68141. dest.writeFloat (elements [i++]);
  68142. }
  68143. else if (type == closeSubPathMarker)
  68144. {
  68145. dest.writeByte ('c');
  68146. }
  68147. }
  68148. dest.writeByte ('e'); // marks the end-of-path
  68149. }
  68150. const String Path::toString() const
  68151. {
  68152. String s;
  68153. s.preallocateStorage (numElements * 4);
  68154. if (! useNonZeroWinding)
  68155. s << T("a ");
  68156. int i = 0;
  68157. float lastMarker = 0.0f;
  68158. while (i < numElements)
  68159. {
  68160. const float marker = elements [i++];
  68161. tchar markerChar = 0;
  68162. int numCoords = 0;
  68163. if (marker == moveMarker)
  68164. {
  68165. markerChar = T('m');
  68166. numCoords = 2;
  68167. }
  68168. else if (marker == lineMarker)
  68169. {
  68170. markerChar = T('l');
  68171. numCoords = 2;
  68172. }
  68173. else if (marker == quadMarker)
  68174. {
  68175. markerChar = T('q');
  68176. numCoords = 4;
  68177. }
  68178. else if (marker == cubicMarker)
  68179. {
  68180. markerChar = T('c');
  68181. numCoords = 6;
  68182. }
  68183. else
  68184. {
  68185. jassert (marker == closeSubPathMarker);
  68186. markerChar = T('z');
  68187. }
  68188. if (marker != lastMarker)
  68189. {
  68190. s << markerChar << T(' ');
  68191. lastMarker = marker;
  68192. }
  68193. while (--numCoords >= 0 && i < numElements)
  68194. {
  68195. String n (elements [i++], 3);
  68196. while (n.endsWithChar (T('0')))
  68197. n = n.dropLastCharacters (1);
  68198. if (n.endsWithChar (T('.')))
  68199. n = n.dropLastCharacters (1);
  68200. s << n << T(' ');
  68201. }
  68202. }
  68203. return s.trimEnd();
  68204. }
  68205. static const String nextToken (const tchar*& t)
  68206. {
  68207. while (*t == T(' '))
  68208. ++t;
  68209. const tchar* const start = t;
  68210. while (*t != 0 && *t != T(' '))
  68211. ++t;
  68212. const int length = (int) (t - start);
  68213. while (*t == T(' '))
  68214. ++t;
  68215. return String (start, length);
  68216. }
  68217. void Path::restoreFromString (const String& stringVersion)
  68218. {
  68219. clear();
  68220. setUsingNonZeroWinding (true);
  68221. const tchar* t = stringVersion;
  68222. tchar marker = T('m');
  68223. int numValues = 2;
  68224. float values [6];
  68225. while (*t != 0)
  68226. {
  68227. const String token (nextToken (t));
  68228. const tchar firstChar = token[0];
  68229. int startNum = 0;
  68230. if (firstChar == T('m') || firstChar == T('l'))
  68231. {
  68232. marker = firstChar;
  68233. numValues = 2;
  68234. }
  68235. else if (firstChar == T('q'))
  68236. {
  68237. marker = firstChar;
  68238. numValues = 4;
  68239. }
  68240. else if (firstChar == T('c'))
  68241. {
  68242. marker = firstChar;
  68243. numValues = 6;
  68244. }
  68245. else if (firstChar == T('z'))
  68246. {
  68247. marker = firstChar;
  68248. numValues = 0;
  68249. }
  68250. else if (firstChar == T('a'))
  68251. {
  68252. setUsingNonZeroWinding (false);
  68253. continue;
  68254. }
  68255. else
  68256. {
  68257. ++startNum;
  68258. values [0] = token.getFloatValue();
  68259. }
  68260. for (int i = startNum; i < numValues; ++i)
  68261. values [i] = nextToken (t).getFloatValue();
  68262. switch (marker)
  68263. {
  68264. case T('m'):
  68265. startNewSubPath (values[0], values[1]);
  68266. break;
  68267. case T('l'):
  68268. lineTo (values[0], values[1]);
  68269. break;
  68270. case T('q'):
  68271. quadraticTo (values[0], values[1],
  68272. values[2], values[3]);
  68273. break;
  68274. case T('c'):
  68275. cubicTo (values[0], values[1],
  68276. values[2], values[3],
  68277. values[4], values[5]);
  68278. break;
  68279. case T('z'):
  68280. closeSubPath();
  68281. break;
  68282. default:
  68283. jassertfalse // illegal string format?
  68284. break;
  68285. }
  68286. }
  68287. }
  68288. Path::Iterator::Iterator (const Path& path_)
  68289. : path (path_),
  68290. index (0)
  68291. {
  68292. }
  68293. Path::Iterator::~Iterator()
  68294. {
  68295. }
  68296. bool Path::Iterator::next()
  68297. {
  68298. const float* const elements = path.elements;
  68299. if (index < path.numElements)
  68300. {
  68301. const float type = elements [index++];
  68302. if (type == moveMarker)
  68303. {
  68304. elementType = startNewSubPath;
  68305. x1 = elements [index++];
  68306. y1 = elements [index++];
  68307. }
  68308. else if (type == lineMarker)
  68309. {
  68310. elementType = lineTo;
  68311. x1 = elements [index++];
  68312. y1 = elements [index++];
  68313. }
  68314. else if (type == quadMarker)
  68315. {
  68316. elementType = quadraticTo;
  68317. x1 = elements [index++];
  68318. y1 = elements [index++];
  68319. x2 = elements [index++];
  68320. y2 = elements [index++];
  68321. }
  68322. else if (type == cubicMarker)
  68323. {
  68324. elementType = cubicTo;
  68325. x1 = elements [index++];
  68326. y1 = elements [index++];
  68327. x2 = elements [index++];
  68328. y2 = elements [index++];
  68329. x3 = elements [index++];
  68330. y3 = elements [index++];
  68331. }
  68332. else if (type == closeSubPathMarker)
  68333. {
  68334. elementType = closePath;
  68335. }
  68336. return true;
  68337. }
  68338. return false;
  68339. }
  68340. END_JUCE_NAMESPACE
  68341. /********* End of inlined file: juce_Path.cpp *********/
  68342. /********* Start of inlined file: juce_PathIterator.cpp *********/
  68343. BEGIN_JUCE_NAMESPACE
  68344. #if JUCE_MSVC
  68345. #pragma optimize ("t", on)
  68346. #endif
  68347. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  68348. const AffineTransform& transform_,
  68349. float tolerence_) throw()
  68350. : x2 (0),
  68351. y2 (0),
  68352. closesSubPath (false),
  68353. subPathIndex (-1),
  68354. path (path_),
  68355. transform (transform_),
  68356. points (path_.elements),
  68357. tolerence (tolerence_ * tolerence_),
  68358. subPathCloseX (0),
  68359. subPathCloseY (0),
  68360. index (0),
  68361. stackSize (32)
  68362. {
  68363. stackBase = (float*) juce_malloc (stackSize * sizeof (float));
  68364. isIdentityTransform = transform.isIdentity();
  68365. stackPos = stackBase;
  68366. }
  68367. PathFlatteningIterator::~PathFlatteningIterator() throw()
  68368. {
  68369. juce_free (stackBase);
  68370. }
  68371. bool PathFlatteningIterator::next() throw()
  68372. {
  68373. x1 = x2;
  68374. y1 = y2;
  68375. float x3 = 0;
  68376. float y3 = 0;
  68377. float x4 = 0;
  68378. float y4 = 0;
  68379. float type;
  68380. for (;;)
  68381. {
  68382. if (stackPos == stackBase)
  68383. {
  68384. if (index >= path.numElements)
  68385. {
  68386. return false;
  68387. }
  68388. else
  68389. {
  68390. type = points [index++];
  68391. if (type != Path::closeSubPathMarker)
  68392. {
  68393. x2 = points [index++];
  68394. y2 = points [index++];
  68395. if (! isIdentityTransform)
  68396. transform.transformPoint (x2, y2);
  68397. if (type == Path::quadMarker)
  68398. {
  68399. x3 = points [index++];
  68400. y3 = points [index++];
  68401. if (! isIdentityTransform)
  68402. transform.transformPoint (x3, y3);
  68403. }
  68404. else if (type == Path::cubicMarker)
  68405. {
  68406. x3 = points [index++];
  68407. y3 = points [index++];
  68408. x4 = points [index++];
  68409. y4 = points [index++];
  68410. if (! isIdentityTransform)
  68411. {
  68412. transform.transformPoint (x3, y3);
  68413. transform.transformPoint (x4, y4);
  68414. }
  68415. }
  68416. }
  68417. }
  68418. }
  68419. else
  68420. {
  68421. type = *--stackPos;
  68422. if (type != Path::closeSubPathMarker)
  68423. {
  68424. x2 = *--stackPos;
  68425. y2 = *--stackPos;
  68426. if (type == Path::quadMarker)
  68427. {
  68428. x3 = *--stackPos;
  68429. y3 = *--stackPos;
  68430. }
  68431. else if (type == Path::cubicMarker)
  68432. {
  68433. x3 = *--stackPos;
  68434. y3 = *--stackPos;
  68435. x4 = *--stackPos;
  68436. y4 = *--stackPos;
  68437. }
  68438. }
  68439. }
  68440. if (type == Path::lineMarker)
  68441. {
  68442. ++subPathIndex;
  68443. closesSubPath = (stackPos == stackBase)
  68444. && (index < path.numElements)
  68445. && (points [index] == Path::closeSubPathMarker)
  68446. && x2 == subPathCloseX
  68447. && y2 == subPathCloseY;
  68448. return true;
  68449. }
  68450. else if (type == Path::quadMarker)
  68451. {
  68452. const int offset = (int) (stackPos - stackBase);
  68453. if (offset >= stackSize - 10)
  68454. {
  68455. stackSize <<= 1;
  68456. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  68457. stackPos = stackBase + offset;
  68458. }
  68459. const float dx1 = x1 - x2;
  68460. const float dy1 = y1 - y2;
  68461. const float dx2 = x2 - x3;
  68462. const float dy2 = y2 - y3;
  68463. const float m1x = (x1 + x2) * 0.5f;
  68464. const float m1y = (y1 + y2) * 0.5f;
  68465. const float m2x = (x2 + x3) * 0.5f;
  68466. const float m2y = (y2 + y3) * 0.5f;
  68467. const float m3x = (m1x + m2x) * 0.5f;
  68468. const float m3y = (m1y + m2y) * 0.5f;
  68469. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  68470. {
  68471. *stackPos++ = y3;
  68472. *stackPos++ = x3;
  68473. *stackPos++ = m2y;
  68474. *stackPos++ = m2x;
  68475. *stackPos++ = Path::quadMarker;
  68476. *stackPos++ = m3y;
  68477. *stackPos++ = m3x;
  68478. *stackPos++ = m1y;
  68479. *stackPos++ = m1x;
  68480. *stackPos++ = Path::quadMarker;
  68481. }
  68482. else
  68483. {
  68484. *stackPos++ = y3;
  68485. *stackPos++ = x3;
  68486. *stackPos++ = Path::lineMarker;
  68487. *stackPos++ = m3y;
  68488. *stackPos++ = m3x;
  68489. *stackPos++ = Path::lineMarker;
  68490. }
  68491. jassert (stackPos < stackBase + stackSize);
  68492. }
  68493. else if (type == Path::cubicMarker)
  68494. {
  68495. const int offset = (int) (stackPos - stackBase);
  68496. if (offset >= stackSize - 16)
  68497. {
  68498. stackSize <<= 1;
  68499. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  68500. stackPos = stackBase + offset;
  68501. }
  68502. const float dx1 = x1 - x2;
  68503. const float dy1 = y1 - y2;
  68504. const float dx2 = x2 - x3;
  68505. const float dy2 = y2 - y3;
  68506. const float dx3 = x3 - x4;
  68507. const float dy3 = y3 - y4;
  68508. const float m1x = (x1 + x2) * 0.5f;
  68509. const float m1y = (y1 + y2) * 0.5f;
  68510. const float m2x = (x3 + x2) * 0.5f;
  68511. const float m2y = (y3 + y2) * 0.5f;
  68512. const float m3x = (x3 + x4) * 0.5f;
  68513. const float m3y = (y3 + y4) * 0.5f;
  68514. const float m4x = (m1x + m2x) * 0.5f;
  68515. const float m4y = (m1y + m2y) * 0.5f;
  68516. const float m5x = (m3x + m2x) * 0.5f;
  68517. const float m5y = (m3y + m2y) * 0.5f;
  68518. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  68519. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  68520. {
  68521. *stackPos++ = y4;
  68522. *stackPos++ = x4;
  68523. *stackPos++ = m3y;
  68524. *stackPos++ = m3x;
  68525. *stackPos++ = m5y;
  68526. *stackPos++ = m5x;
  68527. *stackPos++ = Path::cubicMarker;
  68528. *stackPos++ = (m4y + m5y) * 0.5f;
  68529. *stackPos++ = (m4x + m5x) * 0.5f;
  68530. *stackPos++ = m4y;
  68531. *stackPos++ = m4x;
  68532. *stackPos++ = m1y;
  68533. *stackPos++ = m1x;
  68534. *stackPos++ = Path::cubicMarker;
  68535. }
  68536. else
  68537. {
  68538. *stackPos++ = y4;
  68539. *stackPos++ = x4;
  68540. *stackPos++ = Path::lineMarker;
  68541. *stackPos++ = m5y;
  68542. *stackPos++ = m5x;
  68543. *stackPos++ = Path::lineMarker;
  68544. *stackPos++ = m4y;
  68545. *stackPos++ = m4x;
  68546. *stackPos++ = Path::lineMarker;
  68547. }
  68548. }
  68549. else if (type == Path::closeSubPathMarker)
  68550. {
  68551. if (x2 != subPathCloseX || y2 != subPathCloseY)
  68552. {
  68553. x1 = x2;
  68554. y1 = y2;
  68555. x2 = subPathCloseX;
  68556. y2 = subPathCloseY;
  68557. closesSubPath = true;
  68558. return true;
  68559. }
  68560. }
  68561. else
  68562. {
  68563. subPathIndex = -1;
  68564. subPathCloseX = x1 = x2;
  68565. subPathCloseY = y1 = y2;
  68566. }
  68567. }
  68568. }
  68569. END_JUCE_NAMESPACE
  68570. /********* End of inlined file: juce_PathIterator.cpp *********/
  68571. /********* Start of inlined file: juce_PathStrokeType.cpp *********/
  68572. BEGIN_JUCE_NAMESPACE
  68573. PathStrokeType::PathStrokeType (const float strokeThickness,
  68574. const JointStyle jointStyle_,
  68575. const EndCapStyle endStyle_) throw()
  68576. : thickness (strokeThickness),
  68577. jointStyle (jointStyle_),
  68578. endStyle (endStyle_)
  68579. {
  68580. }
  68581. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  68582. : thickness (other.thickness),
  68583. jointStyle (other.jointStyle),
  68584. endStyle (other.endStyle)
  68585. {
  68586. }
  68587. const PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  68588. {
  68589. thickness = other.thickness;
  68590. jointStyle = other.jointStyle;
  68591. endStyle = other.endStyle;
  68592. return *this;
  68593. }
  68594. PathStrokeType::~PathStrokeType() throw()
  68595. {
  68596. }
  68597. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  68598. {
  68599. return thickness == other.thickness
  68600. && jointStyle == other.jointStyle
  68601. && endStyle == other.endStyle;
  68602. }
  68603. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  68604. {
  68605. return ! operator== (other);
  68606. }
  68607. static bool lineIntersection (const float x1, const float y1,
  68608. const float x2, const float y2,
  68609. const float x3, const float y3,
  68610. const float x4, const float y4,
  68611. float& intersectionX,
  68612. float& intersectionY,
  68613. float& distanceBeyondLine1EndSquared) throw()
  68614. {
  68615. if (x2 != x3 || y2 != y3)
  68616. {
  68617. const float dx1 = x2 - x1;
  68618. const float dy1 = y2 - y1;
  68619. const float dx2 = x4 - x3;
  68620. const float dy2 = y4 - y3;
  68621. const float divisor = dx1 * dy2 - dx2 * dy1;
  68622. if (divisor == 0)
  68623. {
  68624. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  68625. {
  68626. if (dy1 == 0 && dy2 != 0)
  68627. {
  68628. const float along = (y1 - y3) / dy2;
  68629. intersectionX = x3 + along * dx2;
  68630. intersectionY = y1;
  68631. distanceBeyondLine1EndSquared = intersectionX - x2;
  68632. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68633. if ((x2 > x1) == (intersectionX < x2))
  68634. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68635. return along >= 0 && along <= 1.0f;
  68636. }
  68637. else if (dy2 == 0 && dy1 != 0)
  68638. {
  68639. const float along = (y3 - y1) / dy1;
  68640. intersectionX = x1 + along * dx1;
  68641. intersectionY = y3;
  68642. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  68643. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68644. if (along < 1.0f)
  68645. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68646. return along >= 0 && along <= 1.0f;
  68647. }
  68648. else if (dx1 == 0 && dx2 != 0)
  68649. {
  68650. const float along = (x1 - x3) / dx2;
  68651. intersectionX = x1;
  68652. intersectionY = y3 + along * dy2;
  68653. distanceBeyondLine1EndSquared = intersectionY - y2;
  68654. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68655. if ((y2 > y1) == (intersectionY < y2))
  68656. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68657. return along >= 0 && along <= 1.0f;
  68658. }
  68659. else if (dx2 == 0 && dx1 != 0)
  68660. {
  68661. const float along = (x3 - x1) / dx1;
  68662. intersectionX = x3;
  68663. intersectionY = y1 + along * dy1;
  68664. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  68665. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68666. if (along < 1.0f)
  68667. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68668. return along >= 0 && along <= 1.0f;
  68669. }
  68670. }
  68671. intersectionX = 0.5f * (x2 + x3);
  68672. intersectionY = 0.5f * (y2 + y3);
  68673. distanceBeyondLine1EndSquared = 0.0f;
  68674. return false;
  68675. }
  68676. else
  68677. {
  68678. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  68679. intersectionX = x1 + along1 * dx1;
  68680. intersectionY = y1 + along1 * dy1;
  68681. if (along1 >= 0 && along1 <= 1.0f)
  68682. {
  68683. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  68684. if (along2 >= 0 && along2 <= divisor)
  68685. {
  68686. distanceBeyondLine1EndSquared = 0.0f;
  68687. return true;
  68688. }
  68689. }
  68690. distanceBeyondLine1EndSquared = along1 - 1.0f;
  68691. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68692. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  68693. if (along1 < 1.0f)
  68694. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68695. return false;
  68696. }
  68697. }
  68698. intersectionX = x2;
  68699. intersectionY = y2;
  68700. distanceBeyondLine1EndSquared = 0.0f;
  68701. return true;
  68702. }
  68703. // part of stroke drawing stuff
  68704. static void addEdgeAndJoint (Path& destPath,
  68705. const PathStrokeType::JointStyle style,
  68706. const float maxMiterExtensionSquared, const float width,
  68707. const float x1, const float y1,
  68708. const float x2, const float y2,
  68709. const float x3, const float y3,
  68710. const float x4, const float y4,
  68711. const float midX, const float midY) throw()
  68712. {
  68713. if (style == PathStrokeType::beveled
  68714. || (x3 == x4 && y3 == y4)
  68715. || (x1 == x2 && y1 == y2))
  68716. {
  68717. destPath.lineTo (x2, y2);
  68718. destPath.lineTo (x3, y3);
  68719. }
  68720. else
  68721. {
  68722. float jx, jy, distanceBeyondLine1EndSquared;
  68723. // if they intersect, use this point..
  68724. if (lineIntersection (x1, y1, x2, y2,
  68725. x3, y3, x4, y4,
  68726. jx, jy, distanceBeyondLine1EndSquared))
  68727. {
  68728. destPath.lineTo (jx, jy);
  68729. }
  68730. else
  68731. {
  68732. if (style == PathStrokeType::mitered)
  68733. {
  68734. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  68735. && distanceBeyondLine1EndSquared > 0.0f)
  68736. {
  68737. destPath.lineTo (jx, jy);
  68738. }
  68739. else
  68740. {
  68741. // the end sticks out too far, so just use a blunt joint
  68742. destPath.lineTo (x2, y2);
  68743. destPath.lineTo (x3, y3);
  68744. }
  68745. }
  68746. else
  68747. {
  68748. // curved joints
  68749. float angle = atan2f (x2 - midX, y2 - midY);
  68750. float angle2 = atan2f (x3 - midX, y3 - midY);
  68751. while (angle < angle2 - 0.01f)
  68752. angle2 -= float_Pi * 2.0f;
  68753. destPath.lineTo (x2, y2);
  68754. while (angle > angle2)
  68755. {
  68756. destPath.lineTo (midX + width * sinf (angle),
  68757. midY + width * cosf (angle));
  68758. angle -= 0.1f;
  68759. }
  68760. destPath.lineTo (x3, y3);
  68761. }
  68762. }
  68763. }
  68764. }
  68765. static inline void addLineEnd (Path& destPath,
  68766. const PathStrokeType::EndCapStyle style,
  68767. const float x1, const float y1,
  68768. const float x2, const float y2,
  68769. const float width) throw()
  68770. {
  68771. if (style == PathStrokeType::butt)
  68772. {
  68773. destPath.lineTo (x2, y2);
  68774. }
  68775. else
  68776. {
  68777. float offx1, offy1, offx2, offy2;
  68778. float dx = x2 - x1;
  68779. float dy = y2 - y1;
  68780. const float len = juce_hypotf (dx, dy);
  68781. if (len == 0)
  68782. {
  68783. offx1 = offx2 = x1;
  68784. offy1 = offy2 = y1;
  68785. }
  68786. else
  68787. {
  68788. const float offset = width / len;
  68789. dx *= offset;
  68790. dy *= offset;
  68791. offx1 = x1 + dy;
  68792. offy1 = y1 - dx;
  68793. offx2 = x2 + dy;
  68794. offy2 = y2 - dx;
  68795. }
  68796. if (style == PathStrokeType::square)
  68797. {
  68798. // sqaure ends
  68799. destPath.lineTo (offx1, offy1);
  68800. destPath.lineTo (offx2, offy2);
  68801. destPath.lineTo (x2, y2);
  68802. }
  68803. else
  68804. {
  68805. // rounded ends
  68806. const float midx = (offx1 + offx2) * 0.5f;
  68807. const float midy = (offy1 + offy2) * 0.5f;
  68808. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  68809. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  68810. midx, midy);
  68811. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  68812. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  68813. x2, y2);
  68814. }
  68815. }
  68816. }
  68817. struct LineSection
  68818. {
  68819. LineSection() throw() {}
  68820. LineSection (int) throw() {}
  68821. float x1, y1, x2, y2; // original line
  68822. float lx1, ly1, lx2, ly2; // the left-hand stroke
  68823. float rx1, ry1, rx2, ry2; // the right-hand stroke
  68824. };
  68825. static void addSubPath (Path& destPath, const Array <LineSection>& subPath,
  68826. const bool isClosed,
  68827. const float width, const float maxMiterExtensionSquared,
  68828. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle) throw()
  68829. {
  68830. jassert (subPath.size() > 0);
  68831. const LineSection& firstLine = subPath.getReference (0);
  68832. float lastX1 = firstLine.lx1;
  68833. float lastY1 = firstLine.ly1;
  68834. float lastX2 = firstLine.lx2;
  68835. float lastY2 = firstLine.ly2;
  68836. if (isClosed)
  68837. {
  68838. destPath.startNewSubPath (lastX1, lastY1);
  68839. }
  68840. else
  68841. {
  68842. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  68843. addLineEnd (destPath, endStyle,
  68844. firstLine.rx2, firstLine.ry2,
  68845. lastX1, lastY1,
  68846. width);
  68847. }
  68848. int i;
  68849. for (i = 1; i < subPath.size(); ++i)
  68850. {
  68851. const LineSection& l = subPath.getReference (i);
  68852. addEdgeAndJoint (destPath, jointStyle,
  68853. maxMiterExtensionSquared, width,
  68854. lastX1, lastY1, lastX2, lastY2,
  68855. l.lx1, l.ly1, l.lx2, l.ly2,
  68856. l.x1, l.y1);
  68857. lastX1 = l.lx1;
  68858. lastY1 = l.ly1;
  68859. lastX2 = l.lx2;
  68860. lastY2 = l.ly2;
  68861. }
  68862. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  68863. if (isClosed)
  68864. {
  68865. const LineSection& l = subPath.getReference (0);
  68866. addEdgeAndJoint (destPath, jointStyle,
  68867. maxMiterExtensionSquared, width,
  68868. lastX1, lastY1, lastX2, lastY2,
  68869. l.lx1, l.ly1, l.lx2, l.ly2,
  68870. l.x1, l.y1);
  68871. destPath.closeSubPath();
  68872. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  68873. }
  68874. else
  68875. {
  68876. destPath.lineTo (lastX2, lastY2);
  68877. addLineEnd (destPath, endStyle,
  68878. lastX2, lastY2,
  68879. lastLine.rx1, lastLine.ry1,
  68880. width);
  68881. }
  68882. lastX1 = lastLine.rx1;
  68883. lastY1 = lastLine.ry1;
  68884. lastX2 = lastLine.rx2;
  68885. lastY2 = lastLine.ry2;
  68886. for (i = subPath.size() - 1; --i >= 0;)
  68887. {
  68888. const LineSection& l = subPath.getReference (i);
  68889. addEdgeAndJoint (destPath, jointStyle,
  68890. maxMiterExtensionSquared, width,
  68891. lastX1, lastY1, lastX2, lastY2,
  68892. l.rx1, l.ry1, l.rx2, l.ry2,
  68893. l.x2, l.y2);
  68894. lastX1 = l.rx1;
  68895. lastY1 = l.ry1;
  68896. lastX2 = l.rx2;
  68897. lastY2 = l.ry2;
  68898. }
  68899. if (isClosed)
  68900. {
  68901. addEdgeAndJoint (destPath, jointStyle,
  68902. maxMiterExtensionSquared, width,
  68903. lastX1, lastY1, lastX2, lastY2,
  68904. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  68905. lastLine.x2, lastLine.y2);
  68906. }
  68907. else
  68908. {
  68909. // do the last line
  68910. destPath.lineTo (lastX2, lastY2);
  68911. }
  68912. destPath.closeSubPath();
  68913. }
  68914. void PathStrokeType::createStrokedPath (Path& destPath,
  68915. const Path& source,
  68916. const AffineTransform& transform,
  68917. const float extraAccuracy) const throw()
  68918. {
  68919. if (thickness <= 0)
  68920. {
  68921. destPath.clear();
  68922. return;
  68923. }
  68924. const Path* sourcePath = &source;
  68925. Path temp;
  68926. if (sourcePath == &destPath)
  68927. {
  68928. destPath.swapWithPath (temp);
  68929. sourcePath = &temp;
  68930. }
  68931. else
  68932. {
  68933. destPath.clear();
  68934. }
  68935. destPath.setUsingNonZeroWinding (true);
  68936. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  68937. const float width = 0.5f * thickness;
  68938. // Iterate the path, creating a list of the
  68939. // left/right-hand lines along either side of it...
  68940. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  68941. Array <LineSection> subPath;
  68942. LineSection l;
  68943. l.x1 = 0;
  68944. l.y1 = 0;
  68945. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  68946. while (it.next())
  68947. {
  68948. if (it.subPathIndex == 0)
  68949. {
  68950. if (subPath.size() > 0)
  68951. {
  68952. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  68953. subPath.clearQuick();
  68954. }
  68955. l.x1 = it.x1;
  68956. l.y1 = it.y1;
  68957. }
  68958. l.x2 = it.x2;
  68959. l.y2 = it.y2;
  68960. float dx = l.x2 - l.x1;
  68961. float dy = l.y2 - l.y1;
  68962. const float hypotSquared = dx*dx + dy*dy;
  68963. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  68964. {
  68965. const float len = sqrtf (hypotSquared);
  68966. if (len == 0)
  68967. {
  68968. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  68969. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  68970. }
  68971. else
  68972. {
  68973. const float offset = width / len;
  68974. dx *= offset;
  68975. dy *= offset;
  68976. l.rx2 = l.x1 - dy;
  68977. l.ry2 = l.y1 + dx;
  68978. l.lx1 = l.x1 + dy;
  68979. l.ly1 = l.y1 - dx;
  68980. l.lx2 = l.x2 + dy;
  68981. l.ly2 = l.y2 - dx;
  68982. l.rx1 = l.x2 - dy;
  68983. l.ry1 = l.y2 + dx;
  68984. }
  68985. subPath.add (l);
  68986. if (it.closesSubPath)
  68987. {
  68988. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle);
  68989. subPath.clearQuick();
  68990. }
  68991. else
  68992. {
  68993. l.x1 = it.x2;
  68994. l.y1 = it.y2;
  68995. }
  68996. }
  68997. }
  68998. if (subPath.size() > 0)
  68999. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  69000. }
  69001. void PathStrokeType::createDashedStroke (Path& destPath,
  69002. const Path& sourcePath,
  69003. const float* dashLengths,
  69004. int numDashLengths,
  69005. const AffineTransform& transform,
  69006. const float extraAccuracy) const throw()
  69007. {
  69008. if (thickness <= 0)
  69009. return;
  69010. // this should really be an even number..
  69011. jassert ((numDashLengths & 1) == 0);
  69012. Path newDestPath;
  69013. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  69014. bool first = true;
  69015. int dashNum = 0;
  69016. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  69017. float dx = 0.0f, dy = 0.0f;
  69018. for (;;)
  69019. {
  69020. const bool isSolid = ((dashNum & 1) == 0);
  69021. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  69022. jassert (dashLen > 0); // must be a positive increment!
  69023. if (dashLen <= 0)
  69024. break;
  69025. pos += dashLen;
  69026. while (pos > lineEndPos)
  69027. {
  69028. if (! it.next())
  69029. {
  69030. if (isSolid && ! first)
  69031. newDestPath.lineTo (it.x2, it.y2);
  69032. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  69033. return;
  69034. }
  69035. if (isSolid && ! first)
  69036. {
  69037. newDestPath.lineTo (it.x1, it.y1);
  69038. }
  69039. else
  69040. {
  69041. newDestPath.startNewSubPath (it.x1, it.y1);
  69042. first = false;
  69043. }
  69044. dx = it.x2 - it.x1;
  69045. dy = it.y2 - it.y1;
  69046. lineLen = juce_hypotf (dx, dy);
  69047. lineEndPos += lineLen;
  69048. }
  69049. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  69050. if (isSolid)
  69051. newDestPath.lineTo (it.x1 + dx * alpha,
  69052. it.y1 + dy * alpha);
  69053. else
  69054. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  69055. it.y1 + dy * alpha);
  69056. }
  69057. }
  69058. END_JUCE_NAMESPACE
  69059. /********* End of inlined file: juce_PathStrokeType.cpp *********/
  69060. /********* Start of inlined file: juce_Point.cpp *********/
  69061. BEGIN_JUCE_NAMESPACE
  69062. Point::Point() throw()
  69063. : x (0.0f),
  69064. y (0.0f)
  69065. {
  69066. }
  69067. Point::Point (const Point& other) throw()
  69068. : x (other.x),
  69069. y (other.y)
  69070. {
  69071. }
  69072. const Point& Point::operator= (const Point& other) throw()
  69073. {
  69074. x = other.x;
  69075. y = other.y;
  69076. return *this;
  69077. }
  69078. Point::Point (const float x_,
  69079. const float y_) throw()
  69080. : x (x_),
  69081. y (y_)
  69082. {
  69083. }
  69084. Point::~Point() throw()
  69085. {
  69086. }
  69087. void Point::setXY (const float x_,
  69088. const float y_) throw()
  69089. {
  69090. x = x_;
  69091. y = y_;
  69092. }
  69093. void Point::applyTransform (const AffineTransform& transform) throw()
  69094. {
  69095. transform.transformPoint (x, y);
  69096. }
  69097. END_JUCE_NAMESPACE
  69098. /********* End of inlined file: juce_Point.cpp *********/
  69099. /********* Start of inlined file: juce_PositionedRectangle.cpp *********/
  69100. BEGIN_JUCE_NAMESPACE
  69101. PositionedRectangle::PositionedRectangle() throw()
  69102. : x (0.0),
  69103. y (0.0),
  69104. w (0.0),
  69105. h (0.0),
  69106. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  69107. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  69108. wMode (absoluteSize),
  69109. hMode (absoluteSize)
  69110. {
  69111. }
  69112. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  69113. : x (other.x),
  69114. y (other.y),
  69115. w (other.w),
  69116. h (other.h),
  69117. xMode (other.xMode),
  69118. yMode (other.yMode),
  69119. wMode (other.wMode),
  69120. hMode (other.hMode)
  69121. {
  69122. }
  69123. const PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  69124. {
  69125. if (this != &other)
  69126. {
  69127. x = other.x;
  69128. y = other.y;
  69129. w = other.w;
  69130. h = other.h;
  69131. xMode = other.xMode;
  69132. yMode = other.yMode;
  69133. wMode = other.wMode;
  69134. hMode = other.hMode;
  69135. }
  69136. return *this;
  69137. }
  69138. PositionedRectangle::~PositionedRectangle() throw()
  69139. {
  69140. }
  69141. const bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  69142. {
  69143. return x == other.x
  69144. && y == other.y
  69145. && w == other.w
  69146. && h == other.h
  69147. && xMode == other.xMode
  69148. && yMode == other.yMode
  69149. && wMode == other.wMode
  69150. && hMode == other.hMode;
  69151. }
  69152. const bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  69153. {
  69154. return ! operator== (other);
  69155. }
  69156. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  69157. {
  69158. StringArray tokens;
  69159. tokens.addTokens (stringVersion, false);
  69160. decodePosString (tokens [0], xMode, x);
  69161. decodePosString (tokens [1], yMode, y);
  69162. decodeSizeString (tokens [2], wMode, w);
  69163. decodeSizeString (tokens [3], hMode, h);
  69164. }
  69165. const String PositionedRectangle::toString() const throw()
  69166. {
  69167. String s;
  69168. s.preallocateStorage (12);
  69169. addPosDescription (s, xMode, x);
  69170. s << T(' ');
  69171. addPosDescription (s, yMode, y);
  69172. s << T(' ');
  69173. addSizeDescription (s, wMode, w);
  69174. s << T(' ');
  69175. addSizeDescription (s, hMode, h);
  69176. return s;
  69177. }
  69178. const Rectangle PositionedRectangle::getRectangle (const Rectangle& target) const throw()
  69179. {
  69180. jassert (! target.isEmpty());
  69181. double x_, y_, w_, h_;
  69182. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  69183. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  69184. return Rectangle (roundDoubleToInt (x_), roundDoubleToInt (y_),
  69185. roundDoubleToInt (w_), roundDoubleToInt (h_));
  69186. }
  69187. void PositionedRectangle::getRectangleDouble (const Rectangle& target,
  69188. double& x_, double& y_,
  69189. double& w_, double& h_) const throw()
  69190. {
  69191. jassert (! target.isEmpty());
  69192. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  69193. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  69194. }
  69195. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  69196. {
  69197. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  69198. }
  69199. void PositionedRectangle::updateFrom (const Rectangle& rectangle,
  69200. const Rectangle& target) throw()
  69201. {
  69202. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  69203. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  69204. }
  69205. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  69206. const double newW, const double newH,
  69207. const Rectangle& target) throw()
  69208. {
  69209. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  69210. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  69211. }
  69212. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  69213. {
  69214. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  69215. updateFrom (comp.getBounds(), Rectangle());
  69216. else
  69217. updateFrom (comp.getBounds(), Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  69218. }
  69219. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  69220. {
  69221. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  69222. }
  69223. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  69224. {
  69225. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  69226. | absoluteFromParentBottomRight
  69227. | absoluteFromParentCentre
  69228. | proportionOfParentSize));
  69229. }
  69230. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  69231. {
  69232. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  69233. }
  69234. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  69235. {
  69236. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  69237. | absoluteFromParentBottomRight
  69238. | absoluteFromParentCentre
  69239. | proportionOfParentSize));
  69240. }
  69241. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  69242. {
  69243. return (SizeMode) wMode;
  69244. }
  69245. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  69246. {
  69247. return (SizeMode) hMode;
  69248. }
  69249. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  69250. const PositionMode xMode_,
  69251. const AnchorPoint yAnchor,
  69252. const PositionMode yMode_,
  69253. const SizeMode widthMode,
  69254. const SizeMode heightMode,
  69255. const Rectangle& target) throw()
  69256. {
  69257. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  69258. {
  69259. double tx, tw;
  69260. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  69261. xMode = (uint8) (xAnchor | xMode_);
  69262. wMode = (uint8) widthMode;
  69263. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  69264. }
  69265. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  69266. {
  69267. double ty, th;
  69268. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  69269. yMode = (uint8) (yAnchor | yMode_);
  69270. hMode = (uint8) heightMode;
  69271. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  69272. }
  69273. }
  69274. bool PositionedRectangle::isPositionAbsolute() const throw()
  69275. {
  69276. return xMode == absoluteFromParentTopLeft
  69277. && yMode == absoluteFromParentTopLeft
  69278. && wMode == absoluteSize
  69279. && hMode == absoluteSize;
  69280. }
  69281. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  69282. {
  69283. if ((mode & proportionOfParentSize) != 0)
  69284. {
  69285. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  69286. }
  69287. else
  69288. {
  69289. s << (roundDoubleToInt (value * 100.0) / 100.0);
  69290. if ((mode & absoluteFromParentBottomRight) != 0)
  69291. s << T('R');
  69292. else if ((mode & absoluteFromParentCentre) != 0)
  69293. s << T('C');
  69294. }
  69295. if ((mode & anchorAtRightOrBottom) != 0)
  69296. s << T('r');
  69297. else if ((mode & anchorAtCentre) != 0)
  69298. s << T('c');
  69299. }
  69300. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  69301. {
  69302. if (mode == proportionalSize)
  69303. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  69304. else if (mode == parentSizeMinusAbsolute)
  69305. s << (roundDoubleToInt (value * 100.0) / 100.0) << T('M');
  69306. else
  69307. s << (roundDoubleToInt (value * 100.0) / 100.0);
  69308. }
  69309. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  69310. {
  69311. if (s.containsChar (T('r')))
  69312. mode = anchorAtRightOrBottom;
  69313. else if (s.containsChar (T('c')))
  69314. mode = anchorAtCentre;
  69315. else
  69316. mode = anchorAtLeftOrTop;
  69317. if (s.containsChar (T('%')))
  69318. {
  69319. mode |= proportionOfParentSize;
  69320. value = s.removeCharacters (T("%rcRC")).getDoubleValue() / 100.0;
  69321. }
  69322. else
  69323. {
  69324. if (s.containsChar (T('R')))
  69325. mode |= absoluteFromParentBottomRight;
  69326. else if (s.containsChar (T('C')))
  69327. mode |= absoluteFromParentCentre;
  69328. else
  69329. mode |= absoluteFromParentTopLeft;
  69330. value = s.removeCharacters (T("rcRC")).getDoubleValue();
  69331. }
  69332. }
  69333. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  69334. {
  69335. if (s.containsChar (T('%')))
  69336. {
  69337. mode = proportionalSize;
  69338. value = s.upToFirstOccurrenceOf (T("%"), false, false).getDoubleValue() / 100.0;
  69339. }
  69340. else if (s.containsChar (T('M')))
  69341. {
  69342. mode = parentSizeMinusAbsolute;
  69343. value = s.getDoubleValue();
  69344. }
  69345. else
  69346. {
  69347. mode = absoluteSize;
  69348. value = s.getDoubleValue();
  69349. }
  69350. }
  69351. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  69352. const double x, const double w,
  69353. const uint8 xMode, const uint8 wMode,
  69354. const int parentPos,
  69355. const int parentSize) const throw()
  69356. {
  69357. if (wMode == proportionalSize)
  69358. wOut = roundDoubleToInt (w * parentSize);
  69359. else if (wMode == parentSizeMinusAbsolute)
  69360. wOut = jmax (0, parentSize - roundDoubleToInt (w));
  69361. else
  69362. wOut = roundDoubleToInt (w);
  69363. if ((xMode & proportionOfParentSize) != 0)
  69364. xOut = parentPos + x * parentSize;
  69365. else if ((xMode & absoluteFromParentBottomRight) != 0)
  69366. xOut = (parentPos + parentSize) - x;
  69367. else if ((xMode & absoluteFromParentCentre) != 0)
  69368. xOut = x + (parentPos + parentSize / 2);
  69369. else
  69370. xOut = x + parentPos;
  69371. if ((xMode & anchorAtRightOrBottom) != 0)
  69372. xOut -= wOut;
  69373. else if ((xMode & anchorAtCentre) != 0)
  69374. xOut -= wOut / 2;
  69375. }
  69376. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  69377. double x, const double w,
  69378. const uint8 xMode, const uint8 wMode,
  69379. const int parentPos,
  69380. const int parentSize) const throw()
  69381. {
  69382. if (wMode == proportionalSize)
  69383. {
  69384. if (parentSize > 0)
  69385. wOut = w / parentSize;
  69386. }
  69387. else if (wMode == parentSizeMinusAbsolute)
  69388. wOut = parentSize - w;
  69389. else
  69390. wOut = w;
  69391. if ((xMode & anchorAtRightOrBottom) != 0)
  69392. x += w;
  69393. else if ((xMode & anchorAtCentre) != 0)
  69394. x += w / 2;
  69395. if ((xMode & proportionOfParentSize) != 0)
  69396. {
  69397. if (parentSize > 0)
  69398. xOut = (x - parentPos) / parentSize;
  69399. }
  69400. else if ((xMode & absoluteFromParentBottomRight) != 0)
  69401. xOut = (parentPos + parentSize) - x;
  69402. else if ((xMode & absoluteFromParentCentre) != 0)
  69403. xOut = x - (parentPos + parentSize / 2);
  69404. else
  69405. xOut = x - parentPos;
  69406. }
  69407. END_JUCE_NAMESPACE
  69408. /********* End of inlined file: juce_PositionedRectangle.cpp *********/
  69409. /********* Start of inlined file: juce_Rectangle.cpp *********/
  69410. BEGIN_JUCE_NAMESPACE
  69411. Rectangle::Rectangle() throw()
  69412. : x (0),
  69413. y (0),
  69414. w (0),
  69415. h (0)
  69416. {
  69417. }
  69418. Rectangle::Rectangle (const int x_, const int y_,
  69419. const int w_, const int h_) throw()
  69420. : x (x_),
  69421. y (y_),
  69422. w (w_),
  69423. h (h_)
  69424. {
  69425. }
  69426. Rectangle::Rectangle (const int w_, const int h_) throw()
  69427. : x (0),
  69428. y (0),
  69429. w (w_),
  69430. h (h_)
  69431. {
  69432. }
  69433. Rectangle::Rectangle (const Rectangle& other) throw()
  69434. : x (other.x),
  69435. y (other.y),
  69436. w (other.w),
  69437. h (other.h)
  69438. {
  69439. }
  69440. Rectangle::~Rectangle() throw()
  69441. {
  69442. }
  69443. bool Rectangle::isEmpty() const throw()
  69444. {
  69445. return w <= 0 || h <= 0;
  69446. }
  69447. void Rectangle::setBounds (const int x_,
  69448. const int y_,
  69449. const int w_,
  69450. const int h_) throw()
  69451. {
  69452. x = x_;
  69453. y = y_;
  69454. w = w_;
  69455. h = h_;
  69456. }
  69457. void Rectangle::setPosition (const int x_,
  69458. const int y_) throw()
  69459. {
  69460. x = x_;
  69461. y = y_;
  69462. }
  69463. void Rectangle::setSize (const int w_,
  69464. const int h_) throw()
  69465. {
  69466. w = w_;
  69467. h = h_;
  69468. }
  69469. void Rectangle::translate (const int dx,
  69470. const int dy) throw()
  69471. {
  69472. x += dx;
  69473. y += dy;
  69474. }
  69475. const Rectangle Rectangle::translated (const int dx,
  69476. const int dy) const throw()
  69477. {
  69478. return Rectangle (x + dx, y + dy, w, h);
  69479. }
  69480. void Rectangle::expand (const int deltaX,
  69481. const int deltaY) throw()
  69482. {
  69483. const int nw = jmax (0, w + deltaX + deltaX);
  69484. const int nh = jmax (0, h + deltaY + deltaY);
  69485. setBounds (x - deltaX,
  69486. y - deltaY,
  69487. nw, nh);
  69488. }
  69489. const Rectangle Rectangle::expanded (const int deltaX,
  69490. const int deltaY) const throw()
  69491. {
  69492. const int nw = jmax (0, w + deltaX + deltaX);
  69493. const int nh = jmax (0, h + deltaY + deltaY);
  69494. return Rectangle (x - deltaX,
  69495. y - deltaY,
  69496. nw, nh);
  69497. }
  69498. void Rectangle::reduce (const int deltaX,
  69499. const int deltaY) throw()
  69500. {
  69501. expand (-deltaX, -deltaY);
  69502. }
  69503. const Rectangle Rectangle::reduced (const int deltaX,
  69504. const int deltaY) const throw()
  69505. {
  69506. return expanded (-deltaX, -deltaY);
  69507. }
  69508. bool Rectangle::operator== (const Rectangle& other) const throw()
  69509. {
  69510. return x == other.x
  69511. && y == other.y
  69512. && w == other.w
  69513. && h == other.h;
  69514. }
  69515. bool Rectangle::operator!= (const Rectangle& other) const throw()
  69516. {
  69517. return x != other.x
  69518. || y != other.y
  69519. || w != other.w
  69520. || h != other.h;
  69521. }
  69522. bool Rectangle::contains (const int px,
  69523. const int py) const throw()
  69524. {
  69525. return px >= x
  69526. && py >= y
  69527. && px < x + w
  69528. && py < y + h;
  69529. }
  69530. bool Rectangle::contains (const Rectangle& other) const throw()
  69531. {
  69532. return x <= other.x
  69533. && y <= other.y
  69534. && x + w >= other.x + other.w
  69535. && y + h >= other.y + other.h;
  69536. }
  69537. bool Rectangle::intersects (const Rectangle& other) const throw()
  69538. {
  69539. return x + w > other.x
  69540. && y + h > other.y
  69541. && x < other.x + other.w
  69542. && y < other.y + other.h
  69543. && w > 0
  69544. && h > 0;
  69545. }
  69546. const Rectangle Rectangle::getIntersection (const Rectangle& other) const throw()
  69547. {
  69548. const int nx = jmax (x, other.x);
  69549. const int ny = jmax (y, other.y);
  69550. const int nw = jmin (x + w, other.x + other.w) - nx;
  69551. const int nh = jmin (y + h, other.y + other.h) - ny;
  69552. if (nw >= 0 && nh >= 0)
  69553. return Rectangle (nx, ny, nw, nh);
  69554. else
  69555. return Rectangle();
  69556. }
  69557. bool Rectangle::intersectRectangle (int& x1, int& y1, int& w1, int& h1) const throw()
  69558. {
  69559. const int maxX = jmax (x1, x);
  69560. w1 = jmin (x1 + w1, x + w) - maxX;
  69561. if (w1 > 0)
  69562. {
  69563. const int maxY = jmax (y1, y);
  69564. h1 = jmin (y1 + h1, y + h) - maxY;
  69565. if (h1 > 0)
  69566. {
  69567. x1 = maxX;
  69568. y1 = maxY;
  69569. return true;
  69570. }
  69571. }
  69572. return false;
  69573. }
  69574. bool Rectangle::intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  69575. int x2, int y2, int w2, int h2) throw()
  69576. {
  69577. const int x = jmax (x1, x2);
  69578. w1 = jmin (x1 + w1, x2 + w2) - x;
  69579. if (w1 > 0)
  69580. {
  69581. const int y = jmax (y1, y2);
  69582. h1 = jmin (y1 + h1, y2 + h2) - y;
  69583. if (h1 > 0)
  69584. {
  69585. x1 = x;
  69586. y1 = y;
  69587. return true;
  69588. }
  69589. }
  69590. return false;
  69591. }
  69592. const Rectangle Rectangle::getUnion (const Rectangle& other) const throw()
  69593. {
  69594. const int newX = jmin (x, other.x);
  69595. const int newY = jmin (y, other.y);
  69596. return Rectangle (newX, newY,
  69597. jmax (x + w, other.x + other.w) - newX,
  69598. jmax (y + h, other.y + other.h) - newY);
  69599. }
  69600. bool Rectangle::enlargeIfAdjacent (const Rectangle& other) throw()
  69601. {
  69602. if (x == other.x && getRight() == other.getRight()
  69603. && (other.getBottom() >= y && other.y <= getBottom()))
  69604. {
  69605. const int newY = jmin (y, other.y);
  69606. h = jmax (getBottom(), other.getBottom()) - newY;
  69607. y = newY;
  69608. return true;
  69609. }
  69610. else if (y == other.y && getBottom() == other.getBottom()
  69611. && (other.getRight() >= x && other.x <= getRight()))
  69612. {
  69613. const int newX = jmin (x, other.x);
  69614. w = jmax (getRight(), other.getRight()) - newX;
  69615. x = newX;
  69616. return true;
  69617. }
  69618. return false;
  69619. }
  69620. bool Rectangle::reduceIfPartlyContainedIn (const Rectangle& other) throw()
  69621. {
  69622. int inside = 0;
  69623. const int otherR = other.getRight();
  69624. if (x >= other.x && x < otherR)
  69625. inside = 1;
  69626. const int otherB = other.getBottom();
  69627. if (y >= other.y && y < otherB)
  69628. inside |= 2;
  69629. const int r = x + w;
  69630. if (r >= other.x && r < otherR)
  69631. inside |= 4;
  69632. const int b = y + h;
  69633. if (b >= other.y && b < otherB)
  69634. inside |= 8;
  69635. switch (inside)
  69636. {
  69637. case 1 + 2 + 8:
  69638. w = r - otherR;
  69639. x = otherR;
  69640. return true;
  69641. case 1 + 2 + 4:
  69642. h = b - otherB;
  69643. y = otherB;
  69644. return true;
  69645. case 2 + 4 + 8:
  69646. w = other.x - x;
  69647. return true;
  69648. case 1 + 4 + 8:
  69649. h = other.y - y;
  69650. return true;
  69651. }
  69652. return false;
  69653. }
  69654. const String Rectangle::toString() const throw()
  69655. {
  69656. String s;
  69657. s.preallocateStorage (16);
  69658. s << x << T(' ')
  69659. << y << T(' ')
  69660. << w << T(' ')
  69661. << h;
  69662. return s;
  69663. }
  69664. const Rectangle Rectangle::fromString (const String& stringVersion)
  69665. {
  69666. StringArray toks;
  69667. toks.addTokens (stringVersion.trim(), T(",; \t\r\n"), 0);
  69668. return Rectangle (toks[0].trim().getIntValue(),
  69669. toks[1].trim().getIntValue(),
  69670. toks[2].trim().getIntValue(),
  69671. toks[3].trim().getIntValue());
  69672. }
  69673. END_JUCE_NAMESPACE
  69674. /********* End of inlined file: juce_Rectangle.cpp *********/
  69675. /********* Start of inlined file: juce_RectangleList.cpp *********/
  69676. BEGIN_JUCE_NAMESPACE
  69677. RectangleList::RectangleList() throw()
  69678. {
  69679. }
  69680. RectangleList::RectangleList (const Rectangle& rect) throw()
  69681. {
  69682. if (! rect.isEmpty())
  69683. rects.add (rect);
  69684. }
  69685. RectangleList::RectangleList (const RectangleList& other) throw()
  69686. : rects (other.rects)
  69687. {
  69688. }
  69689. const RectangleList& RectangleList::operator= (const RectangleList& other) throw()
  69690. {
  69691. if (this != &other)
  69692. rects = other.rects;
  69693. return *this;
  69694. }
  69695. RectangleList::~RectangleList() throw()
  69696. {
  69697. }
  69698. void RectangleList::clear() throw()
  69699. {
  69700. rects.clearQuick();
  69701. }
  69702. const Rectangle RectangleList::getRectangle (const int index) const throw()
  69703. {
  69704. if (((unsigned int) index) < (unsigned int) rects.size())
  69705. return rects.getReference (index);
  69706. return Rectangle();
  69707. }
  69708. bool RectangleList::isEmpty() const throw()
  69709. {
  69710. return rects.size() == 0;
  69711. }
  69712. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  69713. : current (0),
  69714. owner (list),
  69715. index (list.rects.size())
  69716. {
  69717. }
  69718. RectangleList::Iterator::~Iterator() throw()
  69719. {
  69720. }
  69721. bool RectangleList::Iterator::next() throw()
  69722. {
  69723. if (--index >= 0)
  69724. {
  69725. current = & (owner.rects.getReference (index));
  69726. return true;
  69727. }
  69728. return false;
  69729. }
  69730. void RectangleList::add (const Rectangle& rect) throw()
  69731. {
  69732. if (! rect.isEmpty())
  69733. {
  69734. if (rects.size() == 0)
  69735. {
  69736. rects.add (rect);
  69737. }
  69738. else
  69739. {
  69740. bool anyOverlaps = false;
  69741. int i;
  69742. for (i = rects.size(); --i >= 0;)
  69743. {
  69744. Rectangle& ourRect = rects.getReference (i);
  69745. if (rect.intersects (ourRect))
  69746. {
  69747. if (rect.contains (ourRect))
  69748. rects.remove (i);
  69749. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  69750. anyOverlaps = true;
  69751. }
  69752. }
  69753. if (anyOverlaps && rects.size() > 0)
  69754. {
  69755. RectangleList r (rect);
  69756. for (i = rects.size(); --i >= 0;)
  69757. {
  69758. const Rectangle& ourRect = rects.getReference (i);
  69759. if (rect.intersects (ourRect))
  69760. {
  69761. r.subtract (ourRect);
  69762. if (r.rects.size() == 0)
  69763. return;
  69764. }
  69765. }
  69766. for (i = r.getNumRectangles(); --i >= 0;)
  69767. rects.add (r.rects.getReference (i));
  69768. }
  69769. else
  69770. {
  69771. rects.add (rect);
  69772. }
  69773. }
  69774. }
  69775. }
  69776. void RectangleList::addWithoutMerging (const Rectangle& rect) throw()
  69777. {
  69778. rects.add (rect);
  69779. }
  69780. void RectangleList::add (const int x, const int y, const int w, const int h) throw()
  69781. {
  69782. if (rects.size() == 0)
  69783. {
  69784. if (w > 0 && h > 0)
  69785. rects.add (Rectangle (x, y, w, h));
  69786. }
  69787. else
  69788. {
  69789. add (Rectangle (x, y, w, h));
  69790. }
  69791. }
  69792. void RectangleList::add (const RectangleList& other) throw()
  69793. {
  69794. for (int i = 0; i < other.rects.size(); ++i)
  69795. add (other.rects.getReference (i));
  69796. }
  69797. void RectangleList::subtract (const Rectangle& rect) throw()
  69798. {
  69799. const int originalNumRects = rects.size();
  69800. if (originalNumRects > 0)
  69801. {
  69802. const int x1 = rect.x;
  69803. const int y1 = rect.y;
  69804. const int x2 = x1 + rect.w;
  69805. const int y2 = y1 + rect.h;
  69806. for (int i = getNumRectangles(); --i >= 0;)
  69807. {
  69808. Rectangle& r = rects.getReference (i);
  69809. const int rx1 = r.x;
  69810. const int ry1 = r.y;
  69811. const int rx2 = rx1 + r.w;
  69812. const int ry2 = ry1 + r.h;
  69813. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  69814. {
  69815. if (x1 > rx1 && x1 < rx2)
  69816. {
  69817. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  69818. {
  69819. r.w = x1 - rx1;
  69820. }
  69821. else
  69822. {
  69823. r.x = x1;
  69824. r.w = rx2 - x1;
  69825. rects.insert (i + 1, Rectangle (rx1, ry1, x1 - rx1, ry2 - ry1));
  69826. i += 2;
  69827. }
  69828. }
  69829. else if (x2 > rx1 && x2 < rx2)
  69830. {
  69831. r.x = x2;
  69832. r.w = rx2 - x2;
  69833. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  69834. {
  69835. rects.insert (i + 1, Rectangle (rx1, ry1, x2 - rx1, ry2 - ry1));
  69836. i += 2;
  69837. }
  69838. }
  69839. else if (y1 > ry1 && y1 < ry2)
  69840. {
  69841. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  69842. {
  69843. r.h = y1 - ry1;
  69844. }
  69845. else
  69846. {
  69847. r.y = y1;
  69848. r.h = ry2 - y1;
  69849. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y1 - ry1));
  69850. i += 2;
  69851. }
  69852. }
  69853. else if (y2 > ry1 && y2 < ry2)
  69854. {
  69855. r.y = y2;
  69856. r.h = ry2 - y2;
  69857. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  69858. {
  69859. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y2 - ry1));
  69860. i += 2;
  69861. }
  69862. }
  69863. else
  69864. {
  69865. rects.remove (i);
  69866. }
  69867. }
  69868. }
  69869. if (rects.size() > originalNumRects + 10)
  69870. consolidate();
  69871. }
  69872. }
  69873. void RectangleList::subtract (const RectangleList& otherList) throw()
  69874. {
  69875. for (int i = otherList.rects.size(); --i >= 0;)
  69876. subtract (otherList.rects.getReference (i));
  69877. }
  69878. bool RectangleList::clipTo (const Rectangle& rect) throw()
  69879. {
  69880. bool notEmpty = false;
  69881. if (rect.isEmpty())
  69882. {
  69883. clear();
  69884. }
  69885. else
  69886. {
  69887. for (int i = rects.size(); --i >= 0;)
  69888. {
  69889. Rectangle& r = rects.getReference (i);
  69890. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  69891. rects.remove (i);
  69892. else
  69893. notEmpty = true;
  69894. }
  69895. }
  69896. return notEmpty;
  69897. }
  69898. bool RectangleList::clipTo (const RectangleList& other) throw()
  69899. {
  69900. if (rects.size() == 0)
  69901. return false;
  69902. RectangleList result;
  69903. for (int j = 0; j < rects.size(); ++j)
  69904. {
  69905. const Rectangle& rect = rects.getReference (j);
  69906. for (int i = other.rects.size(); --i >= 0;)
  69907. {
  69908. Rectangle r (other.rects.getReference (i));
  69909. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  69910. result.rects.add (r);
  69911. }
  69912. }
  69913. swapWith (result);
  69914. return ! isEmpty();
  69915. }
  69916. bool RectangleList::getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw()
  69917. {
  69918. destRegion.clear();
  69919. if (! rect.isEmpty())
  69920. {
  69921. for (int i = rects.size(); --i >= 0;)
  69922. {
  69923. Rectangle r (rects.getReference (i));
  69924. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  69925. destRegion.rects.add (r);
  69926. }
  69927. }
  69928. return destRegion.rects.size() > 0;
  69929. }
  69930. void RectangleList::swapWith (RectangleList& otherList) throw()
  69931. {
  69932. rects.swapWithArray (otherList.rects);
  69933. }
  69934. void RectangleList::consolidate() throw()
  69935. {
  69936. int i;
  69937. for (i = 0; i < getNumRectangles() - 1; ++i)
  69938. {
  69939. Rectangle& r = rects.getReference (i);
  69940. const int rx1 = r.x;
  69941. const int ry1 = r.y;
  69942. const int rx2 = rx1 + r.w;
  69943. const int ry2 = ry1 + r.h;
  69944. for (int j = rects.size(); --j > i;)
  69945. {
  69946. Rectangle& r2 = rects.getReference (j);
  69947. const int jrx1 = r2.x;
  69948. const int jry1 = r2.y;
  69949. const int jrx2 = jrx1 + r2.w;
  69950. const int jry2 = jry1 + r2.h;
  69951. // if the vertical edges of any blocks are touching and their horizontals don't
  69952. // line up, split them horizontally..
  69953. if (jrx1 == rx2 || jrx2 == rx1)
  69954. {
  69955. if (jry1 > ry1 && jry1 < ry2)
  69956. {
  69957. r.h = jry1 - ry1;
  69958. rects.add (Rectangle (rx1, jry1, rx2 - rx1, ry2 - jry1));
  69959. i = -1;
  69960. break;
  69961. }
  69962. if (jry2 > ry1 && jry2 < ry2)
  69963. {
  69964. r.h = jry2 - ry1;
  69965. rects.add (Rectangle (rx1, jry2, rx2 - rx1, ry2 - jry2));
  69966. i = -1;
  69967. break;
  69968. }
  69969. else if (ry1 > jry1 && ry1 < jry2)
  69970. {
  69971. r2.h = ry1 - jry1;
  69972. rects.add (Rectangle (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  69973. i = -1;
  69974. break;
  69975. }
  69976. else if (ry2 > jry1 && ry2 < jry2)
  69977. {
  69978. r2.h = ry2 - jry1;
  69979. rects.add (Rectangle (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  69980. i = -1;
  69981. break;
  69982. }
  69983. }
  69984. }
  69985. }
  69986. for (i = 0; i < rects.size() - 1; ++i)
  69987. {
  69988. Rectangle& r = rects.getReference (i);
  69989. for (int j = rects.size(); --j > i;)
  69990. {
  69991. if (r.enlargeIfAdjacent (rects.getReference (j)))
  69992. {
  69993. rects.remove (j);
  69994. i = -1;
  69995. break;
  69996. }
  69997. }
  69998. }
  69999. }
  70000. bool RectangleList::containsPoint (const int x, const int y) const throw()
  70001. {
  70002. for (int i = getNumRectangles(); --i >= 0;)
  70003. if (rects.getReference (i).contains (x, y))
  70004. return true;
  70005. return false;
  70006. }
  70007. bool RectangleList::containsRectangle (const Rectangle& rectangleToCheck) const throw()
  70008. {
  70009. if (rects.size() > 1)
  70010. {
  70011. RectangleList r (rectangleToCheck);
  70012. for (int i = rects.size(); --i >= 0;)
  70013. {
  70014. r.subtract (rects.getReference (i));
  70015. if (r.rects.size() == 0)
  70016. return true;
  70017. }
  70018. }
  70019. else if (rects.size() > 0)
  70020. {
  70021. return rects.getReference (0).contains (rectangleToCheck);
  70022. }
  70023. return false;
  70024. }
  70025. bool RectangleList::intersectsRectangle (const Rectangle& rectangleToCheck) const throw()
  70026. {
  70027. for (int i = rects.size(); --i >= 0;)
  70028. if (rects.getReference (i).intersects (rectangleToCheck))
  70029. return true;
  70030. return false;
  70031. }
  70032. bool RectangleList::intersects (const RectangleList& other) const throw()
  70033. {
  70034. for (int i = rects.size(); --i >= 0;)
  70035. if (other.intersectsRectangle (rects.getReference (i)))
  70036. return true;
  70037. return false;
  70038. }
  70039. const Rectangle RectangleList::getBounds() const throw()
  70040. {
  70041. if (rects.size() <= 1)
  70042. {
  70043. if (rects.size() == 0)
  70044. return Rectangle();
  70045. else
  70046. return rects.getReference (0);
  70047. }
  70048. else
  70049. {
  70050. const Rectangle& r = rects.getReference (0);
  70051. int minX = r.x;
  70052. int minY = r.y;
  70053. int maxX = minX + r.w;
  70054. int maxY = minY + r.h;
  70055. for (int i = rects.size(); --i > 0;)
  70056. {
  70057. const Rectangle& r2 = rects.getReference (i);
  70058. minX = jmin (minX, r2.x);
  70059. minY = jmin (minY, r2.y);
  70060. maxX = jmax (maxX, r2.getRight());
  70061. maxY = jmax (maxY, r2.getBottom());
  70062. }
  70063. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  70064. }
  70065. }
  70066. void RectangleList::offsetAll (const int dx, const int dy) throw()
  70067. {
  70068. for (int i = rects.size(); --i >= 0;)
  70069. {
  70070. Rectangle& r = rects.getReference (i);
  70071. r.x += dx;
  70072. r.y += dy;
  70073. }
  70074. }
  70075. const Path RectangleList::toPath() const throw()
  70076. {
  70077. Path p;
  70078. for (int i = rects.size(); --i >= 0;)
  70079. {
  70080. const Rectangle& r = rects.getReference (i);
  70081. p.addRectangle ((float) r.x,
  70082. (float) r.y,
  70083. (float) r.w,
  70084. (float) r.h);
  70085. }
  70086. return p;
  70087. }
  70088. END_JUCE_NAMESPACE
  70089. /********* End of inlined file: juce_RectangleList.cpp *********/
  70090. /********* Start of inlined file: juce_Image.cpp *********/
  70091. BEGIN_JUCE_NAMESPACE
  70092. static const int fullAlphaThreshold = 253;
  70093. Image::Image (const PixelFormat format_,
  70094. const int imageWidth_,
  70095. const int imageHeight_)
  70096. : format (format_),
  70097. imageWidth (imageWidth_),
  70098. imageHeight (imageHeight_),
  70099. imageData (0)
  70100. {
  70101. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  70102. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  70103. // actual image will be at least 1x1.
  70104. }
  70105. Image::Image (const PixelFormat format_,
  70106. const int imageWidth_,
  70107. const int imageHeight_,
  70108. const bool clearImage)
  70109. : format (format_),
  70110. imageWidth (imageWidth_),
  70111. imageHeight (imageHeight_)
  70112. {
  70113. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  70114. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  70115. // actual image will be at least 1x1.
  70116. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  70117. lineStride = (pixelStride * jmax (1, imageWidth_) + 3) & ~3;
  70118. const int dataSize = lineStride * jmax (1, imageHeight_);
  70119. imageData = (uint8*) (clearImage ? juce_calloc (dataSize)
  70120. : juce_malloc (dataSize));
  70121. }
  70122. Image::Image (const Image& other)
  70123. : format (other.format),
  70124. imageWidth (other.imageWidth),
  70125. imageHeight (other.imageHeight)
  70126. {
  70127. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  70128. lineStride = (pixelStride * jmax (1, imageWidth) + 3) & ~3;
  70129. const int dataSize = lineStride * jmax (1, imageHeight);
  70130. imageData = (uint8*) juce_malloc (dataSize);
  70131. int ls, ps;
  70132. const uint8* srcData = other.lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  70133. setPixelData (0, 0, imageWidth, imageHeight, srcData, ls);
  70134. other.releasePixelDataReadOnly (srcData);
  70135. }
  70136. Image::~Image()
  70137. {
  70138. juce_free (imageData);
  70139. }
  70140. LowLevelGraphicsContext* Image::createLowLevelContext()
  70141. {
  70142. return new LowLevelGraphicsSoftwareRenderer (*this);
  70143. }
  70144. uint8* Image::lockPixelDataReadWrite (int x, int y, int w, int h, int& ls, int& ps)
  70145. {
  70146. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  70147. w = w;
  70148. h = h;
  70149. ls = lineStride;
  70150. ps = pixelStride;
  70151. return imageData + x * pixelStride + y * lineStride;
  70152. }
  70153. void Image::releasePixelDataReadWrite (void*)
  70154. {
  70155. }
  70156. const uint8* Image::lockPixelDataReadOnly (int x, int y, int w, int h, int& ls, int& ps) const
  70157. {
  70158. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  70159. w = w;
  70160. h = h;
  70161. ls = lineStride;
  70162. ps = pixelStride;
  70163. return imageData + x * pixelStride + y * lineStride;
  70164. }
  70165. void Image::releasePixelDataReadOnly (const void*) const
  70166. {
  70167. }
  70168. void Image::setPixelData (int x, int y, int w, int h,
  70169. const uint8* sourcePixelData, int sourceLineStride)
  70170. {
  70171. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  70172. if (Rectangle::intersectRectangles (x, y, w, h, 0, 0, imageWidth, imageHeight))
  70173. {
  70174. int ls, ps;
  70175. uint8* dest = lockPixelDataReadWrite (x, y, w, h, ls, ps);
  70176. for (int i = 0; i < h; ++i)
  70177. {
  70178. memcpy (dest + ls * i,
  70179. sourcePixelData + sourceLineStride * i,
  70180. w * pixelStride);
  70181. }
  70182. releasePixelDataReadWrite (dest);
  70183. }
  70184. }
  70185. void Image::clear (int dx, int dy, int dw, int dh,
  70186. const Colour& colourToClearTo)
  70187. {
  70188. const PixelARGB col (colourToClearTo.getPixelARGB());
  70189. int ls, ps;
  70190. uint8* dstData = lockPixelDataReadWrite (dx, dy, dw, dh, ls, ps);
  70191. uint8* dest = dstData;
  70192. while (--dh >= 0)
  70193. {
  70194. uint8* line = dest;
  70195. dest += ls;
  70196. if (isARGB())
  70197. {
  70198. for (int x = dw; --x >= 0;)
  70199. {
  70200. ((PixelARGB*) line)->set (col);
  70201. line += ps;
  70202. }
  70203. }
  70204. else if (isRGB())
  70205. {
  70206. for (int x = dw; --x >= 0;)
  70207. {
  70208. ((PixelRGB*) line)->set (col);
  70209. line += ps;
  70210. }
  70211. }
  70212. else
  70213. {
  70214. for (int x = dw; --x >= 0;)
  70215. {
  70216. *line = col.getAlpha();
  70217. line += ps;
  70218. }
  70219. }
  70220. }
  70221. releasePixelDataReadWrite (dstData);
  70222. }
  70223. Image* Image::createCopy (int newWidth, int newHeight,
  70224. const Graphics::ResamplingQuality quality) const
  70225. {
  70226. if (newWidth < 0)
  70227. newWidth = imageWidth;
  70228. if (newHeight < 0)
  70229. newHeight = imageHeight;
  70230. Image* const newImage = new Image (format, newWidth, newHeight, true);
  70231. Graphics g (*newImage);
  70232. g.setImageResamplingQuality (quality);
  70233. g.drawImage (this,
  70234. 0, 0, newWidth, newHeight,
  70235. 0, 0, imageWidth, imageHeight,
  70236. false);
  70237. return newImage;
  70238. }
  70239. const Colour Image::getPixelAt (const int x, const int y) const
  70240. {
  70241. Colour c;
  70242. if (((unsigned int) x) < (unsigned int) imageWidth
  70243. && ((unsigned int) y) < (unsigned int) imageHeight)
  70244. {
  70245. int ls, ps;
  70246. const uint8* const pixels = lockPixelDataReadOnly (x, y, 1, 1, ls, ps);
  70247. if (isARGB())
  70248. {
  70249. PixelARGB p (*(const PixelARGB*) pixels);
  70250. p.unpremultiply();
  70251. c = Colour (p.getARGB());
  70252. }
  70253. else if (isRGB())
  70254. c = Colour (((const PixelRGB*) pixels)->getARGB());
  70255. else
  70256. c = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixels);
  70257. releasePixelDataReadOnly (pixels);
  70258. }
  70259. return c;
  70260. }
  70261. void Image::setPixelAt (const int x, const int y,
  70262. const Colour& colour)
  70263. {
  70264. if (((unsigned int) x) < (unsigned int) imageWidth
  70265. && ((unsigned int) y) < (unsigned int) imageHeight)
  70266. {
  70267. int ls, ps;
  70268. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  70269. const PixelARGB col (colour.getPixelARGB());
  70270. if (isARGB())
  70271. ((PixelARGB*) pixels)->set (col);
  70272. else if (isRGB())
  70273. ((PixelRGB*) pixels)->set (col);
  70274. else
  70275. *pixels = col.getAlpha();
  70276. releasePixelDataReadWrite (pixels);
  70277. }
  70278. }
  70279. void Image::multiplyAlphaAt (const int x, const int y,
  70280. const float multiplier)
  70281. {
  70282. if (((unsigned int) x) < (unsigned int) imageWidth
  70283. && ((unsigned int) y) < (unsigned int) imageHeight
  70284. && hasAlphaChannel())
  70285. {
  70286. int ls, ps;
  70287. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  70288. if (isARGB())
  70289. ((PixelARGB*) pixels)->multiplyAlpha (multiplier);
  70290. else
  70291. *pixels = (uint8) (*pixels * multiplier);
  70292. releasePixelDataReadWrite (pixels);
  70293. }
  70294. }
  70295. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  70296. {
  70297. if (hasAlphaChannel())
  70298. {
  70299. int ls, ps;
  70300. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  70301. if (isARGB())
  70302. {
  70303. for (int y = 0; y < imageHeight; ++y)
  70304. {
  70305. uint8* p = pixels + y * ls;
  70306. for (int x = 0; x < imageWidth; ++x)
  70307. {
  70308. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  70309. p += ps;
  70310. }
  70311. }
  70312. }
  70313. else
  70314. {
  70315. for (int y = 0; y < imageHeight; ++y)
  70316. {
  70317. uint8* p = pixels + y * ls;
  70318. for (int x = 0; x < imageWidth; ++x)
  70319. {
  70320. *p = (uint8) (*p * amountToMultiplyBy);
  70321. p += ps;
  70322. }
  70323. }
  70324. }
  70325. releasePixelDataReadWrite (pixels);
  70326. }
  70327. else
  70328. {
  70329. jassertfalse // can't do this without an alpha-channel!
  70330. }
  70331. }
  70332. void Image::desaturate()
  70333. {
  70334. if (isARGB() || isRGB())
  70335. {
  70336. int ls, ps;
  70337. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  70338. if (isARGB())
  70339. {
  70340. for (int y = 0; y < imageHeight; ++y)
  70341. {
  70342. uint8* p = pixels + y * ls;
  70343. for (int x = 0; x < imageWidth; ++x)
  70344. {
  70345. ((PixelARGB*) p)->desaturate();
  70346. p += ps;
  70347. }
  70348. }
  70349. }
  70350. else
  70351. {
  70352. for (int y = 0; y < imageHeight; ++y)
  70353. {
  70354. uint8* p = pixels + y * ls;
  70355. for (int x = 0; x < imageWidth; ++x)
  70356. {
  70357. ((PixelRGB*) p)->desaturate();
  70358. p += ps;
  70359. }
  70360. }
  70361. }
  70362. releasePixelDataReadWrite (pixels);
  70363. }
  70364. }
  70365. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  70366. {
  70367. if (hasAlphaChannel())
  70368. {
  70369. const uint8 threshold = (uint8) jlimit (0, 255, roundFloatToInt (alphaThreshold * 255.0f));
  70370. SparseSet <int> pixelsOnRow;
  70371. int ls, ps;
  70372. const uint8* const pixels = lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  70373. for (int y = 0; y < imageHeight; ++y)
  70374. {
  70375. pixelsOnRow.clear();
  70376. const uint8* lineData = pixels + ls * y;
  70377. if (isARGB())
  70378. {
  70379. for (int x = 0; x < imageWidth; ++x)
  70380. {
  70381. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  70382. pixelsOnRow.addRange (x, 1);
  70383. lineData += ps;
  70384. }
  70385. }
  70386. else
  70387. {
  70388. for (int x = 0; x < imageWidth; ++x)
  70389. {
  70390. if (*lineData >= threshold)
  70391. pixelsOnRow.addRange (x, 1);
  70392. lineData += ps;
  70393. }
  70394. }
  70395. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  70396. {
  70397. int x, w;
  70398. if (pixelsOnRow.getRange (i, x, w))
  70399. result.add (Rectangle (x, y, w, 1));
  70400. }
  70401. result.consolidate();
  70402. }
  70403. releasePixelDataReadOnly (pixels);
  70404. }
  70405. else
  70406. {
  70407. result.add (0, 0, imageWidth, imageHeight);
  70408. }
  70409. }
  70410. void Image::moveImageSection (int dx, int dy,
  70411. int sx, int sy,
  70412. int w, int h)
  70413. {
  70414. if (dx < 0)
  70415. {
  70416. w += dx;
  70417. sx -= dx;
  70418. dx = 0;
  70419. }
  70420. if (dy < 0)
  70421. {
  70422. h += dy;
  70423. sy -= dy;
  70424. dy = 0;
  70425. }
  70426. if (sx < 0)
  70427. {
  70428. w += sx;
  70429. dx -= sx;
  70430. sx = 0;
  70431. }
  70432. if (sy < 0)
  70433. {
  70434. h += sy;
  70435. dy -= sy;
  70436. sy = 0;
  70437. }
  70438. const int minX = jmin (dx, sx);
  70439. const int minY = jmin (dy, sy);
  70440. w = jmin (w, getWidth() - jmax (sx, dx));
  70441. h = jmin (h, getHeight() - jmax (sy, dy));
  70442. if (w > 0 && h > 0)
  70443. {
  70444. const int maxX = jmax (dx, sx) + w;
  70445. const int maxY = jmax (dy, sy) + h;
  70446. int ls, ps;
  70447. uint8* const pixels = lockPixelDataReadWrite (minX, minY, maxX - minX, maxY - minY, ls, ps);
  70448. uint8* dst = pixels + ls * (dy - minY) + ps * (dx - minX);
  70449. const uint8* src = pixels + ls * (sy - minY) + ps * (sx - minX);
  70450. const int lineSize = ps * w;
  70451. if (dy > sy)
  70452. {
  70453. while (--h >= 0)
  70454. {
  70455. const int offset = h * ls;
  70456. memmove (dst + offset, src + offset, lineSize);
  70457. }
  70458. }
  70459. else if (dst != src)
  70460. {
  70461. while (--h >= 0)
  70462. {
  70463. memmove (dst, src, lineSize);
  70464. dst += ls;
  70465. src += ls;
  70466. }
  70467. }
  70468. releasePixelDataReadWrite (pixels);
  70469. }
  70470. }
  70471. END_JUCE_NAMESPACE
  70472. /********* End of inlined file: juce_Image.cpp *********/
  70473. /********* Start of inlined file: juce_ImageCache.cpp *********/
  70474. BEGIN_JUCE_NAMESPACE
  70475. struct CachedImageInfo
  70476. {
  70477. Image* image;
  70478. int64 hashCode;
  70479. int refCount;
  70480. unsigned int releaseTime;
  70481. juce_UseDebuggingNewOperator
  70482. };
  70483. static ImageCache* instance = 0;
  70484. static int cacheTimeout = 5000;
  70485. ImageCache::ImageCache() throw()
  70486. : images (4)
  70487. {
  70488. }
  70489. ImageCache::~ImageCache()
  70490. {
  70491. const ScopedLock sl (lock);
  70492. for (int i = images.size(); --i >= 0;)
  70493. {
  70494. CachedImageInfo* const ci = (CachedImageInfo*)(images.getUnchecked(i));
  70495. delete ci->image;
  70496. delete ci;
  70497. }
  70498. images.clear();
  70499. jassert (instance == this);
  70500. instance = 0;
  70501. }
  70502. Image* ImageCache::getFromHashCode (const int64 hashCode)
  70503. {
  70504. if (instance != 0)
  70505. {
  70506. const ScopedLock sl (instance->lock);
  70507. for (int i = instance->images.size(); --i >= 0;)
  70508. {
  70509. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  70510. if (ci->hashCode == hashCode)
  70511. {
  70512. atomicIncrement (ci->refCount);
  70513. return ci->image;
  70514. }
  70515. }
  70516. }
  70517. return 0;
  70518. }
  70519. void ImageCache::addImageToCache (Image* const image,
  70520. const int64 hashCode)
  70521. {
  70522. if (image != 0)
  70523. {
  70524. if (instance == 0)
  70525. instance = new ImageCache();
  70526. CachedImageInfo* const newC = new CachedImageInfo();
  70527. newC->hashCode = hashCode;
  70528. newC->image = image;
  70529. newC->refCount = 1;
  70530. newC->releaseTime = 0;
  70531. const ScopedLock sl (instance->lock);
  70532. instance->images.add (newC);
  70533. }
  70534. }
  70535. void ImageCache::release (Image* const imageToRelease)
  70536. {
  70537. if (imageToRelease != 0 && instance != 0)
  70538. {
  70539. const ScopedLock sl (instance->lock);
  70540. for (int i = instance->images.size(); --i >= 0;)
  70541. {
  70542. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  70543. if (ci->image == imageToRelease)
  70544. {
  70545. if (--(ci->refCount) == 0)
  70546. ci->releaseTime = Time::getApproximateMillisecondCounter();
  70547. if (! instance->isTimerRunning())
  70548. instance->startTimer (999);
  70549. break;
  70550. }
  70551. }
  70552. }
  70553. }
  70554. bool ImageCache::isImageInCache (Image* const imageToLookFor)
  70555. {
  70556. if (instance != 0)
  70557. {
  70558. const ScopedLock sl (instance->lock);
  70559. for (int i = instance->images.size(); --i >= 0;)
  70560. if (((const CachedImageInfo*) instance->images.getUnchecked(i))->image == imageToLookFor)
  70561. return true;
  70562. }
  70563. return false;
  70564. }
  70565. void ImageCache::incReferenceCount (Image* const image)
  70566. {
  70567. if (instance != 0)
  70568. {
  70569. const ScopedLock sl (instance->lock);
  70570. for (int i = instance->images.size(); --i >= 0;)
  70571. {
  70572. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  70573. if (ci->image == image)
  70574. {
  70575. ci->refCount++;
  70576. return;
  70577. }
  70578. }
  70579. }
  70580. jassertfalse // (trying to inc the ref count of an image that's not in the cache)
  70581. }
  70582. void ImageCache::timerCallback()
  70583. {
  70584. int numberStillNeedingReleasing = 0;
  70585. const unsigned int now = Time::getApproximateMillisecondCounter();
  70586. const ScopedLock sl (lock);
  70587. for (int i = images.size(); --i >= 0;)
  70588. {
  70589. CachedImageInfo* const ci = (CachedImageInfo*) images.getUnchecked(i);
  70590. if (ci->refCount <= 0)
  70591. {
  70592. if (now > ci->releaseTime + cacheTimeout
  70593. || now < ci->releaseTime - 1000)
  70594. {
  70595. images.remove (i);
  70596. delete ci->image;
  70597. delete ci;
  70598. }
  70599. else
  70600. {
  70601. ++numberStillNeedingReleasing;
  70602. }
  70603. }
  70604. }
  70605. if (numberStillNeedingReleasing == 0)
  70606. stopTimer();
  70607. }
  70608. Image* ImageCache::getFromFile (const File& file)
  70609. {
  70610. const int64 hashCode = file.getFullPathName().hashCode64();
  70611. Image* image = getFromHashCode (hashCode);
  70612. if (image == 0)
  70613. {
  70614. image = ImageFileFormat::loadFrom (file);
  70615. addImageToCache (image, hashCode);
  70616. }
  70617. return image;
  70618. }
  70619. Image* ImageCache::getFromMemory (const void* imageData,
  70620. const int dataSize)
  70621. {
  70622. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  70623. Image* image = getFromHashCode (hashCode);
  70624. if (image == 0)
  70625. {
  70626. image = ImageFileFormat::loadFrom (imageData, dataSize);
  70627. addImageToCache (image, hashCode);
  70628. }
  70629. return image;
  70630. }
  70631. void ImageCache::setCacheTimeout (const int millisecs)
  70632. {
  70633. cacheTimeout = millisecs;
  70634. }
  70635. END_JUCE_NAMESPACE
  70636. /********* End of inlined file: juce_ImageCache.cpp *********/
  70637. /********* Start of inlined file: juce_ImageConvolutionKernel.cpp *********/
  70638. BEGIN_JUCE_NAMESPACE
  70639. ImageConvolutionKernel::ImageConvolutionKernel (const int size_) throw()
  70640. : size (size_)
  70641. {
  70642. values = new float* [size];
  70643. for (int i = size; --i >= 0;)
  70644. values[i] = new float [size];
  70645. clear();
  70646. }
  70647. ImageConvolutionKernel::~ImageConvolutionKernel() throw()
  70648. {
  70649. for (int i = size; --i >= 0;)
  70650. delete[] values[i];
  70651. delete[] values;
  70652. }
  70653. void ImageConvolutionKernel::setKernelValue (const int x,
  70654. const int y,
  70655. const float value) throw()
  70656. {
  70657. if (((unsigned int) x) < (unsigned int) size
  70658. && ((unsigned int) y) < (unsigned int) size)
  70659. {
  70660. values[x][y] = value;
  70661. }
  70662. else
  70663. {
  70664. jassertfalse
  70665. }
  70666. }
  70667. void ImageConvolutionKernel::clear() throw()
  70668. {
  70669. for (int y = size; --y >= 0;)
  70670. for (int x = size; --x >= 0;)
  70671. values[x][y] = 0;
  70672. }
  70673. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum) throw()
  70674. {
  70675. double currentTotal = 0.0;
  70676. for (int y = size; --y >= 0;)
  70677. for (int x = size; --x >= 0;)
  70678. currentTotal += values[x][y];
  70679. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  70680. }
  70681. void ImageConvolutionKernel::rescaleAllValues (const float multiplier) throw()
  70682. {
  70683. for (int y = size; --y >= 0;)
  70684. for (int x = size; --x >= 0;)
  70685. values[x][y] *= multiplier;
  70686. }
  70687. void ImageConvolutionKernel::createGaussianBlur (const float radius) throw()
  70688. {
  70689. const double radiusFactor = -1.0 / (radius * radius * 2);
  70690. const int centre = size >> 1;
  70691. for (int y = size; --y >= 0;)
  70692. {
  70693. for (int x = size; --x >= 0;)
  70694. {
  70695. const int cx = x - centre;
  70696. const int cy = y - centre;
  70697. values[x][y] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  70698. }
  70699. }
  70700. setOverallSum (1.0f);
  70701. }
  70702. void ImageConvolutionKernel::applyToImage (Image& destImage,
  70703. const Image* sourceImage,
  70704. int dx,
  70705. int dy,
  70706. int dw,
  70707. int dh) const
  70708. {
  70709. Image* imageCreated = 0;
  70710. if (sourceImage == 0)
  70711. {
  70712. sourceImage = imageCreated = destImage.createCopy();
  70713. }
  70714. else
  70715. {
  70716. jassert (sourceImage->getWidth() == destImage.getWidth()
  70717. && sourceImage->getHeight() == destImage.getHeight()
  70718. && sourceImage->getFormat() == destImage.getFormat());
  70719. if (sourceImage->getWidth() != destImage.getWidth()
  70720. || sourceImage->getHeight() != destImage.getHeight()
  70721. || sourceImage->getFormat() != destImage.getFormat())
  70722. return;
  70723. }
  70724. const int imageWidth = destImage.getWidth();
  70725. const int imageHeight = destImage.getHeight();
  70726. if (dx >= imageWidth || dy >= imageHeight)
  70727. return;
  70728. if (dx + dw > imageWidth)
  70729. dw = imageWidth - dx;
  70730. if (dy + dh > imageHeight)
  70731. dh = imageHeight - dy;
  70732. const int dx2 = dx + dw;
  70733. const int dy2 = dy + dh;
  70734. int lineStride, pixelStride;
  70735. uint8* pixels = destImage.lockPixelDataReadWrite (dx, dy, dw, dh, lineStride, pixelStride);
  70736. uint8* line = pixels;
  70737. int srcLineStride, srcPixelStride;
  70738. const uint8* srcPixels = sourceImage->lockPixelDataReadOnly (0, 0, sourceImage->getWidth(), sourceImage->getHeight(), srcLineStride, srcPixelStride);
  70739. if (pixelStride == 4)
  70740. {
  70741. for (int y = dy; y < dy2; ++y)
  70742. {
  70743. uint8* dest = line;
  70744. line += lineStride;
  70745. for (int x = dx; x < dx2; ++x)
  70746. {
  70747. float c1 = 0;
  70748. float c2 = 0;
  70749. float c3 = 0;
  70750. float c4 = 0;
  70751. for (int yy = 0; yy < size; ++yy)
  70752. {
  70753. const int sy = y + yy - (size >> 1);
  70754. if (sy >= imageHeight)
  70755. break;
  70756. if (sy >= 0)
  70757. {
  70758. int sx = x - (size >> 1);
  70759. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  70760. for (int xx = 0; xx < size; ++xx)
  70761. {
  70762. if (sx >= imageWidth)
  70763. break;
  70764. if (sx >= 0)
  70765. {
  70766. const float kernelMult = values[xx][yy];
  70767. c1 += kernelMult * *src++;
  70768. c2 += kernelMult * *src++;
  70769. c3 += kernelMult * *src++;
  70770. c4 += kernelMult * *src++;
  70771. }
  70772. else
  70773. {
  70774. src += 4;
  70775. }
  70776. ++sx;
  70777. }
  70778. }
  70779. }
  70780. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c1));
  70781. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c2));
  70782. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c3));
  70783. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c4));
  70784. }
  70785. }
  70786. }
  70787. else if (pixelStride == 3)
  70788. {
  70789. for (int y = dy; y < dy2; ++y)
  70790. {
  70791. uint8* dest = line;
  70792. line += lineStride;
  70793. for (int x = dx; x < dx2; ++x)
  70794. {
  70795. float c1 = 0;
  70796. float c2 = 0;
  70797. float c3 = 0;
  70798. for (int yy = 0; yy < size; ++yy)
  70799. {
  70800. const int sy = y + yy - (size >> 1);
  70801. if (sy >= imageHeight)
  70802. break;
  70803. if (sy >= 0)
  70804. {
  70805. int sx = x - (size >> 1);
  70806. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  70807. for (int xx = 0; xx < size; ++xx)
  70808. {
  70809. if (sx >= imageWidth)
  70810. break;
  70811. if (sx >= 0)
  70812. {
  70813. const float kernelMult = values[xx][yy];
  70814. c1 += kernelMult * *src++;
  70815. c2 += kernelMult * *src++;
  70816. c3 += kernelMult * *src++;
  70817. }
  70818. else
  70819. {
  70820. src += 3;
  70821. }
  70822. ++sx;
  70823. }
  70824. }
  70825. }
  70826. *dest++ = (uint8) roundFloatToInt (c1);
  70827. *dest++ = (uint8) roundFloatToInt (c2);
  70828. *dest++ = (uint8) roundFloatToInt (c3);
  70829. }
  70830. }
  70831. }
  70832. sourceImage->releasePixelDataReadOnly (srcPixels);
  70833. destImage.releasePixelDataReadWrite (pixels);
  70834. if (imageCreated != 0)
  70835. delete imageCreated;
  70836. }
  70837. END_JUCE_NAMESPACE
  70838. /********* End of inlined file: juce_ImageConvolutionKernel.cpp *********/
  70839. /********* Start of inlined file: juce_ImageFileFormat.cpp *********/
  70840. BEGIN_JUCE_NAMESPACE
  70841. /********* Start of inlined file: juce_GIFLoader.h *********/
  70842. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  70843. #define __JUCE_GIFLOADER_JUCEHEADER__
  70844. #ifndef DOXYGEN
  70845. static const int maxGifCode = 1 << 12;
  70846. /**
  70847. Used internally by ImageFileFormat - don't use this class directly in your
  70848. application.
  70849. @see ImageFileFormat
  70850. */
  70851. class GIFLoader
  70852. {
  70853. public:
  70854. GIFLoader (InputStream& in);
  70855. ~GIFLoader() throw();
  70856. Image* getImage() const throw() { return image; }
  70857. private:
  70858. Image* image;
  70859. InputStream& input;
  70860. uint8 buffer [300];
  70861. uint8 palette [256][4];
  70862. bool dataBlockIsZero, fresh, finished;
  70863. int currentBit, lastBit, lastByteIndex;
  70864. int codeSize, setCodeSize;
  70865. int maxCode, maxCodeSize;
  70866. int firstcode, oldcode;
  70867. int clearCode, end_code;
  70868. int table [2] [maxGifCode];
  70869. int stack [2 * maxGifCode];
  70870. int *sp;
  70871. bool getSizeFromHeader (int& width, int& height);
  70872. bool readPalette (const int numCols);
  70873. int readDataBlock (unsigned char* dest);
  70874. int processExtension (int type, int& transparent);
  70875. int readLZWByte (bool initialise, int input_code_size);
  70876. int getCode (int code_size, bool initialise);
  70877. bool readImage (int width, int height,
  70878. int interlace, int transparent);
  70879. GIFLoader (const GIFLoader&);
  70880. const GIFLoader& operator= (const GIFLoader&);
  70881. };
  70882. #endif // DOXYGEN
  70883. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  70884. /********* End of inlined file: juce_GIFLoader.h *********/
  70885. Image* juce_loadPNGImageFromStream (InputStream& inputStream) throw();
  70886. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw();
  70887. PNGImageFormat::PNGImageFormat() throw() {}
  70888. PNGImageFormat::~PNGImageFormat() throw() {}
  70889. const String PNGImageFormat::getFormatName()
  70890. {
  70891. return T("PNG");
  70892. }
  70893. bool PNGImageFormat::canUnderstand (InputStream& in)
  70894. {
  70895. const int bytesNeeded = 4;
  70896. char header [bytesNeeded];
  70897. return in.read (header, bytesNeeded) == bytesNeeded
  70898. && header[1] == 'P'
  70899. && header[2] == 'N'
  70900. && header[3] == 'G';
  70901. }
  70902. Image* PNGImageFormat::decodeImage (InputStream& in)
  70903. {
  70904. return juce_loadPNGImageFromStream (in);
  70905. }
  70906. bool PNGImageFormat::writeImageToStream (const Image& sourceImage,
  70907. OutputStream& destStream)
  70908. {
  70909. return juce_writePNGImageToStream (sourceImage, destStream);
  70910. }
  70911. Image* juce_loadJPEGImageFromStream (InputStream& inputStream) throw();
  70912. bool juce_writeJPEGImageToStream (const Image& image, OutputStream& out, float quality) throw();
  70913. JPEGImageFormat::JPEGImageFormat() throw()
  70914. : quality (-1.0f)
  70915. {
  70916. }
  70917. JPEGImageFormat::~JPEGImageFormat() throw() {}
  70918. void JPEGImageFormat::setQuality (const float newQuality)
  70919. {
  70920. quality = newQuality;
  70921. }
  70922. const String JPEGImageFormat::getFormatName()
  70923. {
  70924. return T("JPEG");
  70925. }
  70926. bool JPEGImageFormat::canUnderstand (InputStream& in)
  70927. {
  70928. const int bytesNeeded = 10;
  70929. uint8 header [bytesNeeded];
  70930. if (in.read (header, bytesNeeded) == bytesNeeded)
  70931. {
  70932. return header[0] == 0xff
  70933. && header[1] == 0xd8
  70934. && header[2] == 0xff
  70935. && (header[3] == 0xe0 || header[3] == 0xe1);
  70936. }
  70937. return false;
  70938. }
  70939. Image* JPEGImageFormat::decodeImage (InputStream& in)
  70940. {
  70941. return juce_loadJPEGImageFromStream (in);
  70942. }
  70943. bool JPEGImageFormat::writeImageToStream (const Image& sourceImage,
  70944. OutputStream& destStream)
  70945. {
  70946. return juce_writeJPEGImageToStream (sourceImage, destStream, quality);
  70947. }
  70948. class GIFImageFormat : public ImageFileFormat
  70949. {
  70950. public:
  70951. GIFImageFormat() throw() {}
  70952. ~GIFImageFormat() throw() {}
  70953. const String getFormatName()
  70954. {
  70955. return T("GIF");
  70956. }
  70957. bool canUnderstand (InputStream& in)
  70958. {
  70959. const int bytesNeeded = 4;
  70960. char header [bytesNeeded];
  70961. return (in.read (header, bytesNeeded) == bytesNeeded)
  70962. && header[0] == 'G'
  70963. && header[1] == 'I'
  70964. && header[2] == 'F';
  70965. }
  70966. Image* decodeImage (InputStream& in)
  70967. {
  70968. GIFLoader* const loader = new GIFLoader (in);
  70969. Image* const im = loader->getImage();
  70970. delete loader;
  70971. return im;
  70972. }
  70973. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  70974. {
  70975. return false;
  70976. }
  70977. };
  70978. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  70979. {
  70980. static PNGImageFormat png;
  70981. static JPEGImageFormat jpg;
  70982. static GIFImageFormat gif;
  70983. ImageFileFormat* formats[4];
  70984. int numFormats = 0;
  70985. formats [numFormats++] = &png;
  70986. formats [numFormats++] = &jpg;
  70987. formats [numFormats++] = &gif;
  70988. const int64 streamPos = input.getPosition();
  70989. for (int i = 0; i < numFormats; ++i)
  70990. {
  70991. const bool found = formats[i]->canUnderstand (input);
  70992. input.setPosition (streamPos);
  70993. if (found)
  70994. return formats[i];
  70995. }
  70996. return 0;
  70997. }
  70998. Image* ImageFileFormat::loadFrom (InputStream& input)
  70999. {
  71000. ImageFileFormat* const format = findImageFormatForStream (input);
  71001. if (format != 0)
  71002. return format->decodeImage (input);
  71003. return 0;
  71004. }
  71005. Image* ImageFileFormat::loadFrom (const File& file)
  71006. {
  71007. InputStream* const in = file.createInputStream();
  71008. if (in != 0)
  71009. {
  71010. BufferedInputStream b (in, 8192, true);
  71011. return loadFrom (b);
  71012. }
  71013. return 0;
  71014. }
  71015. Image* ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  71016. {
  71017. if (rawData != 0 && numBytes > 4)
  71018. {
  71019. MemoryInputStream stream (rawData, numBytes, false);
  71020. return loadFrom (stream);
  71021. }
  71022. return 0;
  71023. }
  71024. END_JUCE_NAMESPACE
  71025. /********* End of inlined file: juce_ImageFileFormat.cpp *********/
  71026. /********* Start of inlined file: juce_GIFLoader.cpp *********/
  71027. BEGIN_JUCE_NAMESPACE
  71028. static inline int makeWord (const unsigned char a, const unsigned char b) throw()
  71029. {
  71030. return (b << 8) | a;
  71031. }
  71032. GIFLoader::GIFLoader (InputStream& in)
  71033. : image (0),
  71034. input (in),
  71035. dataBlockIsZero (false),
  71036. fresh (false),
  71037. finished (false)
  71038. {
  71039. currentBit = lastBit = lastByteIndex = 0;
  71040. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  71041. firstcode = oldcode = 0;
  71042. clearCode = end_code = 0;
  71043. int imageWidth, imageHeight;
  71044. int transparent = -1;
  71045. if (! getSizeFromHeader (imageWidth, imageHeight))
  71046. return;
  71047. if ((imageWidth <= 0) || (imageHeight <= 0))
  71048. return;
  71049. unsigned char buf [16];
  71050. if (in.read (buf, 3) != 3)
  71051. return;
  71052. int numColours = 2 << (buf[0] & 7);
  71053. if ((buf[0] & 0x80) != 0)
  71054. readPalette (numColours);
  71055. for (;;)
  71056. {
  71057. if (input.read (buf, 1) != 1)
  71058. break;
  71059. if (buf[0] == ';')
  71060. break;
  71061. if (buf[0] == '!')
  71062. {
  71063. if (input.read (buf, 1) != 1)
  71064. break;
  71065. if (processExtension (buf[0], transparent) < 0)
  71066. break;
  71067. continue;
  71068. }
  71069. if (buf[0] != ',')
  71070. continue;
  71071. if (input.read (buf, 9) != 9)
  71072. break;
  71073. imageWidth = makeWord (buf[4], buf[5]);
  71074. imageHeight = makeWord (buf[6], buf[7]);
  71075. numColours = 2 << (buf[8] & 7);
  71076. if ((buf[8] & 0x80) != 0)
  71077. if (! readPalette (numColours))
  71078. break;
  71079. image = new Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  71080. imageWidth, imageHeight, (transparent >= 0));
  71081. readImage (imageWidth, imageHeight,
  71082. (buf[8] & 0x40) != 0,
  71083. transparent);
  71084. break;
  71085. }
  71086. }
  71087. GIFLoader::~GIFLoader() throw()
  71088. {
  71089. }
  71090. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  71091. {
  71092. unsigned char b [8];
  71093. if (input.read (b, 6) == 6)
  71094. {
  71095. if ((strncmp ("GIF87a", (char*) b, 6) == 0)
  71096. || (strncmp ("GIF89a", (char*) b, 6) == 0))
  71097. {
  71098. if (input.read (b, 4) == 4)
  71099. {
  71100. w = makeWord (b[0], b[1]);
  71101. h = makeWord (b[2], b[3]);
  71102. return true;
  71103. }
  71104. }
  71105. }
  71106. return false;
  71107. }
  71108. bool GIFLoader::readPalette (const int numCols)
  71109. {
  71110. unsigned char rgb[4];
  71111. for (int i = 0; i < numCols; ++i)
  71112. {
  71113. input.read (rgb, 3);
  71114. palette [i][0] = rgb[0];
  71115. palette [i][1] = rgb[1];
  71116. palette [i][2] = rgb[2];
  71117. palette [i][3] = 0xff;
  71118. }
  71119. return true;
  71120. }
  71121. int GIFLoader::readDataBlock (unsigned char* const dest)
  71122. {
  71123. unsigned char n;
  71124. if (input.read (&n, 1) == 1)
  71125. {
  71126. dataBlockIsZero = (n == 0);
  71127. if (dataBlockIsZero || (input.read (dest, n) == n))
  71128. return n;
  71129. }
  71130. return -1;
  71131. }
  71132. int GIFLoader::processExtension (const int type, int& transparent)
  71133. {
  71134. unsigned char b [300];
  71135. int n = 0;
  71136. if (type == 0xf9)
  71137. {
  71138. n = readDataBlock (b);
  71139. if (n < 0)
  71140. return 1;
  71141. if ((b[0] & 0x1) != 0)
  71142. transparent = b[3];
  71143. }
  71144. do
  71145. {
  71146. n = readDataBlock (b);
  71147. }
  71148. while (n > 0);
  71149. return n;
  71150. }
  71151. int GIFLoader::getCode (const int codeSize, const bool initialise)
  71152. {
  71153. if (initialise)
  71154. {
  71155. currentBit = 0;
  71156. lastBit = 0;
  71157. finished = false;
  71158. return 0;
  71159. }
  71160. if ((currentBit + codeSize) >= lastBit)
  71161. {
  71162. if (finished)
  71163. return -1;
  71164. buffer[0] = buffer [lastByteIndex - 2];
  71165. buffer[1] = buffer [lastByteIndex - 1];
  71166. const int n = readDataBlock (&buffer[2]);
  71167. if (n == 0)
  71168. finished = true;
  71169. lastByteIndex = 2 + n;
  71170. currentBit = (currentBit - lastBit) + 16;
  71171. lastBit = (2 + n) * 8 ;
  71172. }
  71173. int result = 0;
  71174. int i = currentBit;
  71175. for (int j = 0; j < codeSize; ++j)
  71176. {
  71177. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  71178. ++i;
  71179. }
  71180. currentBit += codeSize;
  71181. return result;
  71182. }
  71183. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  71184. {
  71185. int code, incode, i;
  71186. if (initialise)
  71187. {
  71188. setCodeSize = inputCodeSize;
  71189. codeSize = setCodeSize + 1;
  71190. clearCode = 1 << setCodeSize;
  71191. end_code = clearCode + 1;
  71192. maxCodeSize = 2 * clearCode;
  71193. maxCode = clearCode + 2;
  71194. getCode (0, true);
  71195. fresh = true;
  71196. for (i = 0; i < clearCode; ++i)
  71197. {
  71198. table[0][i] = 0;
  71199. table[1][i] = i;
  71200. }
  71201. for (; i < maxGifCode; ++i)
  71202. {
  71203. table[0][i] = 0;
  71204. table[1][i] = 0;
  71205. }
  71206. sp = stack;
  71207. return 0;
  71208. }
  71209. else if (fresh)
  71210. {
  71211. fresh = false;
  71212. do
  71213. {
  71214. firstcode = oldcode
  71215. = getCode (codeSize, false);
  71216. }
  71217. while (firstcode == clearCode);
  71218. return firstcode;
  71219. }
  71220. if (sp > stack)
  71221. return *--sp;
  71222. while ((code = getCode (codeSize, false)) >= 0)
  71223. {
  71224. if (code == clearCode)
  71225. {
  71226. for (i = 0; i < clearCode; ++i)
  71227. {
  71228. table[0][i] = 0;
  71229. table[1][i] = i;
  71230. }
  71231. for (; i < maxGifCode; ++i)
  71232. {
  71233. table[0][i] = 0;
  71234. table[1][i] = 0;
  71235. }
  71236. codeSize = setCodeSize + 1;
  71237. maxCodeSize = 2 * clearCode;
  71238. maxCode = clearCode + 2;
  71239. sp = stack;
  71240. firstcode = oldcode = getCode (codeSize, false);
  71241. return firstcode;
  71242. }
  71243. else if (code == end_code)
  71244. {
  71245. if (dataBlockIsZero)
  71246. return -2;
  71247. unsigned char buf [260];
  71248. int n;
  71249. while ((n = readDataBlock (buf)) > 0)
  71250. {}
  71251. if (n != 0)
  71252. return -2;
  71253. }
  71254. incode = code;
  71255. if (code >= maxCode)
  71256. {
  71257. *sp++ = firstcode;
  71258. code = oldcode;
  71259. }
  71260. while (code >= clearCode)
  71261. {
  71262. *sp++ = table[1][code];
  71263. if (code == table[0][code])
  71264. return -2;
  71265. code = table[0][code];
  71266. }
  71267. *sp++ = firstcode = table[1][code];
  71268. if ((code = maxCode) < maxGifCode)
  71269. {
  71270. table[0][code] = oldcode;
  71271. table[1][code] = firstcode;
  71272. ++maxCode;
  71273. if ((maxCode >= maxCodeSize)
  71274. && (maxCodeSize < maxGifCode))
  71275. {
  71276. maxCodeSize <<= 1;
  71277. ++codeSize;
  71278. }
  71279. }
  71280. oldcode = incode;
  71281. if (sp > stack)
  71282. return *--sp;
  71283. }
  71284. return code;
  71285. }
  71286. bool GIFLoader::readImage (const int width, const int height,
  71287. const int interlace, const int transparent)
  71288. {
  71289. unsigned char c;
  71290. if (input.read (&c, 1) != 1
  71291. || readLZWByte (true, c) < 0)
  71292. return false;
  71293. if (transparent >= 0)
  71294. {
  71295. palette [transparent][0] = 0;
  71296. palette [transparent][1] = 0;
  71297. palette [transparent][2] = 0;
  71298. palette [transparent][3] = 0;
  71299. }
  71300. int index;
  71301. int xpos = 0, ypos = 0, pass = 0;
  71302. int stride, pixelStride;
  71303. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  71304. uint8* p = pixels;
  71305. const bool hasAlpha = image->hasAlphaChannel();
  71306. while ((index = readLZWByte (false, c)) >= 0)
  71307. {
  71308. const uint8* const paletteEntry = palette [index];
  71309. if (hasAlpha)
  71310. {
  71311. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  71312. paletteEntry[0],
  71313. paletteEntry[1],
  71314. paletteEntry[2]);
  71315. ((PixelARGB*) p)->premultiply();
  71316. p += pixelStride;
  71317. }
  71318. else
  71319. {
  71320. ((PixelRGB*) p)->setARGB (0,
  71321. paletteEntry[0],
  71322. paletteEntry[1],
  71323. paletteEntry[2]);
  71324. p += pixelStride;
  71325. }
  71326. ++xpos;
  71327. if (xpos == width)
  71328. {
  71329. xpos = 0;
  71330. if (interlace)
  71331. {
  71332. switch (pass)
  71333. {
  71334. case 0:
  71335. case 1:
  71336. ypos += 8;
  71337. break;
  71338. case 2:
  71339. ypos += 4;
  71340. break;
  71341. case 3:
  71342. ypos += 2;
  71343. break;
  71344. }
  71345. while (ypos >= height)
  71346. {
  71347. ++pass;
  71348. switch (pass)
  71349. {
  71350. case 1:
  71351. ypos = 4;
  71352. break;
  71353. case 2:
  71354. ypos = 2;
  71355. break;
  71356. case 3:
  71357. ypos = 1;
  71358. break;
  71359. default:
  71360. return true;
  71361. }
  71362. }
  71363. }
  71364. else
  71365. {
  71366. ++ypos;
  71367. }
  71368. p = pixels + xpos * pixelStride + ypos * stride;
  71369. }
  71370. if (ypos >= height)
  71371. break;
  71372. }
  71373. image->releasePixelDataReadWrite (pixels);
  71374. return true;
  71375. }
  71376. END_JUCE_NAMESPACE
  71377. /********* End of inlined file: juce_GIFLoader.cpp *********/
  71378. #endif
  71379. //==============================================================================
  71380. // some files include lots of library code, so leave them to the end to avoid cluttering
  71381. // up the build for the clean files.
  71382. /********* Start of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  71383. namespace zlibNamespace
  71384. {
  71385. #undef OS_CODE
  71386. #undef fdopen
  71387. /********* Start of inlined file: zlib.h *********/
  71388. #ifndef ZLIB_H
  71389. #define ZLIB_H
  71390. /********* Start of inlined file: zconf.h *********/
  71391. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  71392. #ifndef ZCONF_H
  71393. #define ZCONF_H
  71394. // *** Just a few hacks here to make it compile nicely with Juce..
  71395. #define Z_PREFIX 1
  71396. #undef __MACTYPES__
  71397. #ifdef _MSC_VER
  71398. #pragma warning (disable : 4131 4127 4244 4267)
  71399. #endif
  71400. /*
  71401. * If you *really* need a unique prefix for all types and library functions,
  71402. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  71403. */
  71404. #ifdef Z_PREFIX
  71405. # define deflateInit_ z_deflateInit_
  71406. # define deflate z_deflate
  71407. # define deflateEnd z_deflateEnd
  71408. # define inflateInit_ z_inflateInit_
  71409. # define inflate z_inflate
  71410. # define inflateEnd z_inflateEnd
  71411. # define deflateInit2_ z_deflateInit2_
  71412. # define deflateSetDictionary z_deflateSetDictionary
  71413. # define deflateCopy z_deflateCopy
  71414. # define deflateReset z_deflateReset
  71415. # define deflateParams z_deflateParams
  71416. # define deflateBound z_deflateBound
  71417. # define deflatePrime z_deflatePrime
  71418. # define inflateInit2_ z_inflateInit2_
  71419. # define inflateSetDictionary z_inflateSetDictionary
  71420. # define inflateSync z_inflateSync
  71421. # define inflateSyncPoint z_inflateSyncPoint
  71422. # define inflateCopy z_inflateCopy
  71423. # define inflateReset z_inflateReset
  71424. # define inflateBack z_inflateBack
  71425. # define inflateBackEnd z_inflateBackEnd
  71426. # define compress z_compress
  71427. # define compress2 z_compress2
  71428. # define compressBound z_compressBound
  71429. # define uncompress z_uncompress
  71430. # define adler32 z_adler32
  71431. # define crc32 z_crc32
  71432. # define get_crc_table z_get_crc_table
  71433. # define zError z_zError
  71434. # define alloc_func z_alloc_func
  71435. # define free_func z_free_func
  71436. # define in_func z_in_func
  71437. # define out_func z_out_func
  71438. # define Byte z_Byte
  71439. # define uInt z_uInt
  71440. # define uLong z_uLong
  71441. # define Bytef z_Bytef
  71442. # define charf z_charf
  71443. # define intf z_intf
  71444. # define uIntf z_uIntf
  71445. # define uLongf z_uLongf
  71446. # define voidpf z_voidpf
  71447. # define voidp z_voidp
  71448. #endif
  71449. #if defined(__MSDOS__) && !defined(MSDOS)
  71450. # define MSDOS
  71451. #endif
  71452. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  71453. # define OS2
  71454. #endif
  71455. #if defined(_WINDOWS) && !defined(WINDOWS)
  71456. # define WINDOWS
  71457. #endif
  71458. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  71459. # ifndef WIN32
  71460. # define WIN32
  71461. # endif
  71462. #endif
  71463. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  71464. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  71465. # ifndef SYS16BIT
  71466. # define SYS16BIT
  71467. # endif
  71468. # endif
  71469. #endif
  71470. /*
  71471. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  71472. * than 64k bytes at a time (needed on systems with 16-bit int).
  71473. */
  71474. #ifdef SYS16BIT
  71475. # define MAXSEG_64K
  71476. #endif
  71477. #ifdef MSDOS
  71478. # define UNALIGNED_OK
  71479. #endif
  71480. #ifdef __STDC_VERSION__
  71481. # ifndef STDC
  71482. # define STDC
  71483. # endif
  71484. # if __STDC_VERSION__ >= 199901L
  71485. # ifndef STDC99
  71486. # define STDC99
  71487. # endif
  71488. # endif
  71489. #endif
  71490. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  71491. # define STDC
  71492. #endif
  71493. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  71494. # define STDC
  71495. #endif
  71496. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  71497. # define STDC
  71498. #endif
  71499. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  71500. # define STDC
  71501. #endif
  71502. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  71503. # define STDC
  71504. #endif
  71505. #ifndef STDC
  71506. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  71507. # define const /* note: need a more gentle solution here */
  71508. # endif
  71509. #endif
  71510. /* Some Mac compilers merge all .h files incorrectly: */
  71511. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  71512. # define NO_DUMMY_DECL
  71513. #endif
  71514. /* Maximum value for memLevel in deflateInit2 */
  71515. #ifndef MAX_MEM_LEVEL
  71516. # ifdef MAXSEG_64K
  71517. # define MAX_MEM_LEVEL 8
  71518. # else
  71519. # define MAX_MEM_LEVEL 9
  71520. # endif
  71521. #endif
  71522. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  71523. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  71524. * created by gzip. (Files created by minigzip can still be extracted by
  71525. * gzip.)
  71526. */
  71527. #ifndef MAX_WBITS
  71528. # define MAX_WBITS 15 /* 32K LZ77 window */
  71529. #endif
  71530. /* The memory requirements for deflate are (in bytes):
  71531. (1 << (windowBits+2)) + (1 << (memLevel+9))
  71532. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  71533. plus a few kilobytes for small objects. For example, if you want to reduce
  71534. the default memory requirements from 256K to 128K, compile with
  71535. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  71536. Of course this will generally degrade compression (there's no free lunch).
  71537. The memory requirements for inflate are (in bytes) 1 << windowBits
  71538. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  71539. for small objects.
  71540. */
  71541. /* Type declarations */
  71542. #ifndef OF /* function prototypes */
  71543. # ifdef STDC
  71544. # define OF(args) args
  71545. # else
  71546. # define OF(args) ()
  71547. # endif
  71548. #endif
  71549. /* The following definitions for FAR are needed only for MSDOS mixed
  71550. * model programming (small or medium model with some far allocations).
  71551. * This was tested only with MSC; for other MSDOS compilers you may have
  71552. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  71553. * just define FAR to be empty.
  71554. */
  71555. #ifdef SYS16BIT
  71556. # if defined(M_I86SM) || defined(M_I86MM)
  71557. /* MSC small or medium model */
  71558. # define SMALL_MEDIUM
  71559. # ifdef _MSC_VER
  71560. # define FAR _far
  71561. # else
  71562. # define FAR far
  71563. # endif
  71564. # endif
  71565. # if (defined(__SMALL__) || defined(__MEDIUM__))
  71566. /* Turbo C small or medium model */
  71567. # define SMALL_MEDIUM
  71568. # ifdef __BORLANDC__
  71569. # define FAR _far
  71570. # else
  71571. # define FAR far
  71572. # endif
  71573. # endif
  71574. #endif
  71575. #if defined(WINDOWS) || defined(WIN32)
  71576. /* If building or using zlib as a DLL, define ZLIB_DLL.
  71577. * This is not mandatory, but it offers a little performance increase.
  71578. */
  71579. # ifdef ZLIB_DLL
  71580. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  71581. # ifdef ZLIB_INTERNAL
  71582. # define ZEXTERN extern __declspec(dllexport)
  71583. # else
  71584. # define ZEXTERN extern __declspec(dllimport)
  71585. # endif
  71586. # endif
  71587. # endif /* ZLIB_DLL */
  71588. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  71589. * define ZLIB_WINAPI.
  71590. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  71591. */
  71592. # ifdef ZLIB_WINAPI
  71593. # ifdef FAR
  71594. # undef FAR
  71595. # endif
  71596. # include <windows.h>
  71597. /* No need for _export, use ZLIB.DEF instead. */
  71598. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  71599. # define ZEXPORT WINAPI
  71600. # ifdef WIN32
  71601. # define ZEXPORTVA WINAPIV
  71602. # else
  71603. # define ZEXPORTVA FAR CDECL
  71604. # endif
  71605. # endif
  71606. #endif
  71607. #if defined (__BEOS__)
  71608. # ifdef ZLIB_DLL
  71609. # ifdef ZLIB_INTERNAL
  71610. # define ZEXPORT __declspec(dllexport)
  71611. # define ZEXPORTVA __declspec(dllexport)
  71612. # else
  71613. # define ZEXPORT __declspec(dllimport)
  71614. # define ZEXPORTVA __declspec(dllimport)
  71615. # endif
  71616. # endif
  71617. #endif
  71618. #ifndef ZEXTERN
  71619. # define ZEXTERN extern
  71620. #endif
  71621. #ifndef ZEXPORT
  71622. # define ZEXPORT
  71623. #endif
  71624. #ifndef ZEXPORTVA
  71625. # define ZEXPORTVA
  71626. #endif
  71627. #ifndef FAR
  71628. # define FAR
  71629. #endif
  71630. #if !defined(__MACTYPES__)
  71631. typedef unsigned char Byte; /* 8 bits */
  71632. #endif
  71633. typedef unsigned int uInt; /* 16 bits or more */
  71634. typedef unsigned long uLong; /* 32 bits or more */
  71635. #ifdef SMALL_MEDIUM
  71636. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  71637. # define Bytef Byte FAR
  71638. #else
  71639. typedef Byte FAR Bytef;
  71640. #endif
  71641. typedef char FAR charf;
  71642. typedef int FAR intf;
  71643. typedef uInt FAR uIntf;
  71644. typedef uLong FAR uLongf;
  71645. #ifdef STDC
  71646. typedef void const *voidpc;
  71647. typedef void FAR *voidpf;
  71648. typedef void *voidp;
  71649. #else
  71650. typedef Byte const *voidpc;
  71651. typedef Byte FAR *voidpf;
  71652. typedef Byte *voidp;
  71653. #endif
  71654. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  71655. # include <sys/types.h> /* for off_t */
  71656. # include <unistd.h> /* for SEEK_* and off_t */
  71657. # ifdef VMS
  71658. # include <unixio.h> /* for off_t */
  71659. # endif
  71660. # define z_off_t off_t
  71661. #endif
  71662. #ifndef SEEK_SET
  71663. # define SEEK_SET 0 /* Seek from beginning of file. */
  71664. # define SEEK_CUR 1 /* Seek from current position. */
  71665. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  71666. #endif
  71667. #ifndef z_off_t
  71668. # define z_off_t long
  71669. #endif
  71670. #if defined(__OS400__)
  71671. # define NO_vsnprintf
  71672. #endif
  71673. #if defined(__MVS__)
  71674. # define NO_vsnprintf
  71675. # ifdef FAR
  71676. # undef FAR
  71677. # endif
  71678. #endif
  71679. /* MVS linker does not support external names larger than 8 bytes */
  71680. #if defined(__MVS__)
  71681. # pragma map(deflateInit_,"DEIN")
  71682. # pragma map(deflateInit2_,"DEIN2")
  71683. # pragma map(deflateEnd,"DEEND")
  71684. # pragma map(deflateBound,"DEBND")
  71685. # pragma map(inflateInit_,"ININ")
  71686. # pragma map(inflateInit2_,"ININ2")
  71687. # pragma map(inflateEnd,"INEND")
  71688. # pragma map(inflateSync,"INSY")
  71689. # pragma map(inflateSetDictionary,"INSEDI")
  71690. # pragma map(compressBound,"CMBND")
  71691. # pragma map(inflate_table,"INTABL")
  71692. # pragma map(inflate_fast,"INFA")
  71693. # pragma map(inflate_copyright,"INCOPY")
  71694. #endif
  71695. #endif /* ZCONF_H */
  71696. /********* End of inlined file: zconf.h *********/
  71697. #ifdef __cplusplus
  71698. extern "C" {
  71699. #endif
  71700. #define ZLIB_VERSION "1.2.3"
  71701. #define ZLIB_VERNUM 0x1230
  71702. /*
  71703. The 'zlib' compression library provides in-memory compression and
  71704. decompression functions, including integrity checks of the uncompressed
  71705. data. This version of the library supports only one compression method
  71706. (deflation) but other algorithms will be added later and will have the same
  71707. stream interface.
  71708. Compression can be done in a single step if the buffers are large
  71709. enough (for example if an input file is mmap'ed), or can be done by
  71710. repeated calls of the compression function. In the latter case, the
  71711. application must provide more input and/or consume the output
  71712. (providing more output space) before each call.
  71713. The compressed data format used by default by the in-memory functions is
  71714. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  71715. around a deflate stream, which is itself documented in RFC 1951.
  71716. The library also supports reading and writing files in gzip (.gz) format
  71717. with an interface similar to that of stdio using the functions that start
  71718. with "gz". The gzip format is different from the zlib format. gzip is a
  71719. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  71720. This library can optionally read and write gzip streams in memory as well.
  71721. The zlib format was designed to be compact and fast for use in memory
  71722. and on communications channels. The gzip format was designed for single-
  71723. file compression on file systems, has a larger header than zlib to maintain
  71724. directory information, and uses a different, slower check method than zlib.
  71725. The library does not install any signal handler. The decoder checks
  71726. the consistency of the compressed data, so the library should never
  71727. crash even in case of corrupted input.
  71728. */
  71729. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  71730. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  71731. struct internal_state;
  71732. typedef struct z_stream_s {
  71733. Bytef *next_in; /* next input byte */
  71734. uInt avail_in; /* number of bytes available at next_in */
  71735. uLong total_in; /* total nb of input bytes read so far */
  71736. Bytef *next_out; /* next output byte should be put there */
  71737. uInt avail_out; /* remaining free space at next_out */
  71738. uLong total_out; /* total nb of bytes output so far */
  71739. char *msg; /* last error message, NULL if no error */
  71740. struct internal_state FAR *state; /* not visible by applications */
  71741. alloc_func zalloc; /* used to allocate the internal state */
  71742. free_func zfree; /* used to free the internal state */
  71743. voidpf opaque; /* private data object passed to zalloc and zfree */
  71744. int data_type; /* best guess about the data type: binary or text */
  71745. uLong adler; /* adler32 value of the uncompressed data */
  71746. uLong reserved; /* reserved for future use */
  71747. } z_stream;
  71748. typedef z_stream FAR *z_streamp;
  71749. /*
  71750. gzip header information passed to and from zlib routines. See RFC 1952
  71751. for more details on the meanings of these fields.
  71752. */
  71753. typedef struct gz_header_s {
  71754. int text; /* true if compressed data believed to be text */
  71755. uLong time; /* modification time */
  71756. int xflags; /* extra flags (not used when writing a gzip file) */
  71757. int os; /* operating system */
  71758. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  71759. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  71760. uInt extra_max; /* space at extra (only when reading header) */
  71761. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  71762. uInt name_max; /* space at name (only when reading header) */
  71763. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  71764. uInt comm_max; /* space at comment (only when reading header) */
  71765. int hcrc; /* true if there was or will be a header crc */
  71766. int done; /* true when done reading gzip header (not used
  71767. when writing a gzip file) */
  71768. } gz_header;
  71769. typedef gz_header FAR *gz_headerp;
  71770. /*
  71771. The application must update next_in and avail_in when avail_in has
  71772. dropped to zero. It must update next_out and avail_out when avail_out
  71773. has dropped to zero. The application must initialize zalloc, zfree and
  71774. opaque before calling the init function. All other fields are set by the
  71775. compression library and must not be updated by the application.
  71776. The opaque value provided by the application will be passed as the first
  71777. parameter for calls of zalloc and zfree. This can be useful for custom
  71778. memory management. The compression library attaches no meaning to the
  71779. opaque value.
  71780. zalloc must return Z_NULL if there is not enough memory for the object.
  71781. If zlib is used in a multi-threaded application, zalloc and zfree must be
  71782. thread safe.
  71783. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  71784. exactly 65536 bytes, but will not be required to allocate more than this
  71785. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  71786. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  71787. have their offset normalized to zero. The default allocation function
  71788. provided by this library ensures this (see zutil.c). To reduce memory
  71789. requirements and avoid any allocation of 64K objects, at the expense of
  71790. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  71791. The fields total_in and total_out can be used for statistics or
  71792. progress reports. After compression, total_in holds the total size of
  71793. the uncompressed data and may be saved for use in the decompressor
  71794. (particularly if the decompressor wants to decompress everything in
  71795. a single step).
  71796. */
  71797. /* constants */
  71798. #define Z_NO_FLUSH 0
  71799. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  71800. #define Z_SYNC_FLUSH 2
  71801. #define Z_FULL_FLUSH 3
  71802. #define Z_FINISH 4
  71803. #define Z_BLOCK 5
  71804. /* Allowed flush values; see deflate() and inflate() below for details */
  71805. #define Z_OK 0
  71806. #define Z_STREAM_END 1
  71807. #define Z_NEED_DICT 2
  71808. #define Z_ERRNO (-1)
  71809. #define Z_STREAM_ERROR (-2)
  71810. #define Z_DATA_ERROR (-3)
  71811. #define Z_MEM_ERROR (-4)
  71812. #define Z_BUF_ERROR (-5)
  71813. #define Z_VERSION_ERROR (-6)
  71814. /* Return codes for the compression/decompression functions. Negative
  71815. * values are errors, positive values are used for special but normal events.
  71816. */
  71817. #define Z_NO_COMPRESSION 0
  71818. #define Z_BEST_SPEED 1
  71819. #define Z_BEST_COMPRESSION 9
  71820. #define Z_DEFAULT_COMPRESSION (-1)
  71821. /* compression levels */
  71822. #define Z_FILTERED 1
  71823. #define Z_HUFFMAN_ONLY 2
  71824. #define Z_RLE 3
  71825. #define Z_FIXED 4
  71826. #define Z_DEFAULT_STRATEGY 0
  71827. /* compression strategy; see deflateInit2() below for details */
  71828. #define Z_BINARY 0
  71829. #define Z_TEXT 1
  71830. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  71831. #define Z_UNKNOWN 2
  71832. /* Possible values of the data_type field (though see inflate()) */
  71833. #define Z_DEFLATED 8
  71834. /* The deflate compression method (the only one supported in this version) */
  71835. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  71836. #define zlib_version zlibVersion()
  71837. /* for compatibility with versions < 1.0.2 */
  71838. /* basic functions */
  71839. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  71840. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  71841. If the first character differs, the library code actually used is
  71842. not compatible with the zlib.h header file used by the application.
  71843. This check is automatically made by deflateInit and inflateInit.
  71844. */
  71845. /*
  71846. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  71847. Initializes the internal stream state for compression. The fields
  71848. zalloc, zfree and opaque must be initialized before by the caller.
  71849. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  71850. use default allocation functions.
  71851. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  71852. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  71853. all (the input data is simply copied a block at a time).
  71854. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  71855. compression (currently equivalent to level 6).
  71856. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  71857. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  71858. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  71859. with the version assumed by the caller (ZLIB_VERSION).
  71860. msg is set to null if there is no error message. deflateInit does not
  71861. perform any compression: this will be done by deflate().
  71862. */
  71863. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  71864. /*
  71865. deflate compresses as much data as possible, and stops when the input
  71866. buffer becomes empty or the output buffer becomes full. It may introduce some
  71867. output latency (reading input without producing any output) except when
  71868. forced to flush.
  71869. The detailed semantics are as follows. deflate performs one or both of the
  71870. following actions:
  71871. - Compress more input starting at next_in and update next_in and avail_in
  71872. accordingly. If not all input can be processed (because there is not
  71873. enough room in the output buffer), next_in and avail_in are updated and
  71874. processing will resume at this point for the next call of deflate().
  71875. - Provide more output starting at next_out and update next_out and avail_out
  71876. accordingly. This action is forced if the parameter flush is non zero.
  71877. Forcing flush frequently degrades the compression ratio, so this parameter
  71878. should be set only when necessary (in interactive applications).
  71879. Some output may be provided even if flush is not set.
  71880. Before the call of deflate(), the application should ensure that at least
  71881. one of the actions is possible, by providing more input and/or consuming
  71882. more output, and updating avail_in or avail_out accordingly; avail_out
  71883. should never be zero before the call. The application can consume the
  71884. compressed output when it wants, for example when the output buffer is full
  71885. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  71886. and with zero avail_out, it must be called again after making room in the
  71887. output buffer because there might be more output pending.
  71888. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  71889. decide how much data to accumualte before producing output, in order to
  71890. maximize compression.
  71891. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  71892. flushed to the output buffer and the output is aligned on a byte boundary, so
  71893. that the decompressor can get all input data available so far. (In particular
  71894. avail_in is zero after the call if enough output space has been provided
  71895. before the call.) Flushing may degrade compression for some compression
  71896. algorithms and so it should be used only when necessary.
  71897. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  71898. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  71899. restart from this point if previous compressed data has been damaged or if
  71900. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  71901. compression.
  71902. If deflate returns with avail_out == 0, this function must be called again
  71903. with the same value of the flush parameter and more output space (updated
  71904. avail_out), until the flush is complete (deflate returns with non-zero
  71905. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  71906. avail_out is greater than six to avoid repeated flush markers due to
  71907. avail_out == 0 on return.
  71908. If the parameter flush is set to Z_FINISH, pending input is processed,
  71909. pending output is flushed and deflate returns with Z_STREAM_END if there
  71910. was enough output space; if deflate returns with Z_OK, this function must be
  71911. called again with Z_FINISH and more output space (updated avail_out) but no
  71912. more input data, until it returns with Z_STREAM_END or an error. After
  71913. deflate has returned Z_STREAM_END, the only possible operations on the
  71914. stream are deflateReset or deflateEnd.
  71915. Z_FINISH can be used immediately after deflateInit if all the compression
  71916. is to be done in a single step. In this case, avail_out must be at least
  71917. the value returned by deflateBound (see below). If deflate does not return
  71918. Z_STREAM_END, then it must be called again as described above.
  71919. deflate() sets strm->adler to the adler32 checksum of all input read
  71920. so far (that is, total_in bytes).
  71921. deflate() may update strm->data_type if it can make a good guess about
  71922. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  71923. binary. This field is only for information purposes and does not affect
  71924. the compression algorithm in any manner.
  71925. deflate() returns Z_OK if some progress has been made (more input
  71926. processed or more output produced), Z_STREAM_END if all input has been
  71927. consumed and all output has been produced (only when flush is set to
  71928. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  71929. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  71930. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  71931. fatal, and deflate() can be called again with more input and more output
  71932. space to continue compressing.
  71933. */
  71934. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  71935. /*
  71936. All dynamically allocated data structures for this stream are freed.
  71937. This function discards any unprocessed input and does not flush any
  71938. pending output.
  71939. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  71940. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  71941. prematurely (some input or output was discarded). In the error case,
  71942. msg may be set but then points to a static string (which must not be
  71943. deallocated).
  71944. */
  71945. /*
  71946. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  71947. Initializes the internal stream state for decompression. The fields
  71948. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  71949. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  71950. value depends on the compression method), inflateInit determines the
  71951. compression method from the zlib header and allocates all data structures
  71952. accordingly; otherwise the allocation will be deferred to the first call of
  71953. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  71954. use default allocation functions.
  71955. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  71956. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  71957. version assumed by the caller. msg is set to null if there is no error
  71958. message. inflateInit does not perform any decompression apart from reading
  71959. the zlib header if present: this will be done by inflate(). (So next_in and
  71960. avail_in may be modified, but next_out and avail_out are unchanged.)
  71961. */
  71962. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  71963. /*
  71964. inflate decompresses as much data as possible, and stops when the input
  71965. buffer becomes empty or the output buffer becomes full. It may introduce
  71966. some output latency (reading input without producing any output) except when
  71967. forced to flush.
  71968. The detailed semantics are as follows. inflate performs one or both of the
  71969. following actions:
  71970. - Decompress more input starting at next_in and update next_in and avail_in
  71971. accordingly. If not all input can be processed (because there is not
  71972. enough room in the output buffer), next_in is updated and processing
  71973. will resume at this point for the next call of inflate().
  71974. - Provide more output starting at next_out and update next_out and avail_out
  71975. accordingly. inflate() provides as much output as possible, until there
  71976. is no more input data or no more space in the output buffer (see below
  71977. about the flush parameter).
  71978. Before the call of inflate(), the application should ensure that at least
  71979. one of the actions is possible, by providing more input and/or consuming
  71980. more output, and updating the next_* and avail_* values accordingly.
  71981. The application can consume the uncompressed output when it wants, for
  71982. example when the output buffer is full (avail_out == 0), or after each
  71983. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  71984. must be called again after making room in the output buffer because there
  71985. might be more output pending.
  71986. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  71987. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  71988. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  71989. if and when it gets to the next deflate block boundary. When decoding the
  71990. zlib or gzip format, this will cause inflate() to return immediately after
  71991. the header and before the first block. When doing a raw inflate, inflate()
  71992. will go ahead and process the first block, and will return when it gets to
  71993. the end of that block, or when it runs out of data.
  71994. The Z_BLOCK option assists in appending to or combining deflate streams.
  71995. Also to assist in this, on return inflate() will set strm->data_type to the
  71996. number of unused bits in the last byte taken from strm->next_in, plus 64
  71997. if inflate() is currently decoding the last block in the deflate stream,
  71998. plus 128 if inflate() returned immediately after decoding an end-of-block
  71999. code or decoding the complete header up to just before the first byte of the
  72000. deflate stream. The end-of-block will not be indicated until all of the
  72001. uncompressed data from that block has been written to strm->next_out. The
  72002. number of unused bits may in general be greater than seven, except when
  72003. bit 7 of data_type is set, in which case the number of unused bits will be
  72004. less than eight.
  72005. inflate() should normally be called until it returns Z_STREAM_END or an
  72006. error. However if all decompression is to be performed in a single step
  72007. (a single call of inflate), the parameter flush should be set to
  72008. Z_FINISH. In this case all pending input is processed and all pending
  72009. output is flushed; avail_out must be large enough to hold all the
  72010. uncompressed data. (The size of the uncompressed data may have been saved
  72011. by the compressor for this purpose.) The next operation on this stream must
  72012. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  72013. is never required, but can be used to inform inflate that a faster approach
  72014. may be used for the single inflate() call.
  72015. In this implementation, inflate() always flushes as much output as
  72016. possible to the output buffer, and always uses the faster approach on the
  72017. first call. So the only effect of the flush parameter in this implementation
  72018. is on the return value of inflate(), as noted below, or when it returns early
  72019. because Z_BLOCK is used.
  72020. If a preset dictionary is needed after this call (see inflateSetDictionary
  72021. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  72022. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  72023. strm->adler to the adler32 checksum of all output produced so far (that is,
  72024. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  72025. below. At the end of the stream, inflate() checks that its computed adler32
  72026. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  72027. only if the checksum is correct.
  72028. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  72029. deflate data. The header type is detected automatically. Any information
  72030. contained in the gzip header is not retained, so applications that need that
  72031. information should instead use raw inflate, see inflateInit2() below, or
  72032. inflateBack() and perform their own processing of the gzip header and
  72033. trailer.
  72034. inflate() returns Z_OK if some progress has been made (more input processed
  72035. or more output produced), Z_STREAM_END if the end of the compressed data has
  72036. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  72037. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  72038. corrupted (input stream not conforming to the zlib format or incorrect check
  72039. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  72040. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  72041. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  72042. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  72043. inflate() can be called again with more input and more output space to
  72044. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  72045. call inflateSync() to look for a good compression block if a partial recovery
  72046. of the data is desired.
  72047. */
  72048. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  72049. /*
  72050. All dynamically allocated data structures for this stream are freed.
  72051. This function discards any unprocessed input and does not flush any
  72052. pending output.
  72053. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  72054. was inconsistent. In the error case, msg may be set but then points to a
  72055. static string (which must not be deallocated).
  72056. */
  72057. /* Advanced functions */
  72058. /*
  72059. The following functions are needed only in some special applications.
  72060. */
  72061. /*
  72062. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  72063. int level,
  72064. int method,
  72065. int windowBits,
  72066. int memLevel,
  72067. int strategy));
  72068. This is another version of deflateInit with more compression options. The
  72069. fields next_in, zalloc, zfree and opaque must be initialized before by
  72070. the caller.
  72071. The method parameter is the compression method. It must be Z_DEFLATED in
  72072. this version of the library.
  72073. The windowBits parameter is the base two logarithm of the window size
  72074. (the size of the history buffer). It should be in the range 8..15 for this
  72075. version of the library. Larger values of this parameter result in better
  72076. compression at the expense of memory usage. The default value is 15 if
  72077. deflateInit is used instead.
  72078. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  72079. determines the window size. deflate() will then generate raw deflate data
  72080. with no zlib header or trailer, and will not compute an adler32 check value.
  72081. windowBits can also be greater than 15 for optional gzip encoding. Add
  72082. 16 to windowBits to write a simple gzip header and trailer around the
  72083. compressed data instead of a zlib wrapper. The gzip header will have no
  72084. file name, no extra data, no comment, no modification time (set to zero),
  72085. no header crc, and the operating system will be set to 255 (unknown). If a
  72086. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  72087. The memLevel parameter specifies how much memory should be allocated
  72088. for the internal compression state. memLevel=1 uses minimum memory but
  72089. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  72090. for optimal speed. The default value is 8. See zconf.h for total memory
  72091. usage as a function of windowBits and memLevel.
  72092. The strategy parameter is used to tune the compression algorithm. Use the
  72093. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  72094. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  72095. string match), or Z_RLE to limit match distances to one (run-length
  72096. encoding). Filtered data consists mostly of small values with a somewhat
  72097. random distribution. In this case, the compression algorithm is tuned to
  72098. compress them better. The effect of Z_FILTERED is to force more Huffman
  72099. coding and less string matching; it is somewhat intermediate between
  72100. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  72101. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  72102. parameter only affects the compression ratio but not the correctness of the
  72103. compressed output even if it is not set appropriately. Z_FIXED prevents the
  72104. use of dynamic Huffman codes, allowing for a simpler decoder for special
  72105. applications.
  72106. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  72107. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  72108. method). msg is set to null if there is no error message. deflateInit2 does
  72109. not perform any compression: this will be done by deflate().
  72110. */
  72111. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  72112. const Bytef *dictionary,
  72113. uInt dictLength));
  72114. /*
  72115. Initializes the compression dictionary from the given byte sequence
  72116. without producing any compressed output. This function must be called
  72117. immediately after deflateInit, deflateInit2 or deflateReset, before any
  72118. call of deflate. The compressor and decompressor must use exactly the same
  72119. dictionary (see inflateSetDictionary).
  72120. The dictionary should consist of strings (byte sequences) that are likely
  72121. to be encountered later in the data to be compressed, with the most commonly
  72122. used strings preferably put towards the end of the dictionary. Using a
  72123. dictionary is most useful when the data to be compressed is short and can be
  72124. predicted with good accuracy; the data can then be compressed better than
  72125. with the default empty dictionary.
  72126. Depending on the size of the compression data structures selected by
  72127. deflateInit or deflateInit2, a part of the dictionary may in effect be
  72128. discarded, for example if the dictionary is larger than the window size in
  72129. deflate or deflate2. Thus the strings most likely to be useful should be
  72130. put at the end of the dictionary, not at the front. In addition, the
  72131. current implementation of deflate will use at most the window size minus
  72132. 262 bytes of the provided dictionary.
  72133. Upon return of this function, strm->adler is set to the adler32 value
  72134. of the dictionary; the decompressor may later use this value to determine
  72135. which dictionary has been used by the compressor. (The adler32 value
  72136. applies to the whole dictionary even if only a subset of the dictionary is
  72137. actually used by the compressor.) If a raw deflate was requested, then the
  72138. adler32 value is not computed and strm->adler is not set.
  72139. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  72140. parameter is invalid (such as NULL dictionary) or the stream state is
  72141. inconsistent (for example if deflate has already been called for this stream
  72142. or if the compression method is bsort). deflateSetDictionary does not
  72143. perform any compression: this will be done by deflate().
  72144. */
  72145. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  72146. z_streamp source));
  72147. /*
  72148. Sets the destination stream as a complete copy of the source stream.
  72149. This function can be useful when several compression strategies will be
  72150. tried, for example when there are several ways of pre-processing the input
  72151. data with a filter. The streams that will be discarded should then be freed
  72152. by calling deflateEnd. Note that deflateCopy duplicates the internal
  72153. compression state which can be quite large, so this strategy is slow and
  72154. can consume lots of memory.
  72155. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  72156. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  72157. (such as zalloc being NULL). msg is left unchanged in both source and
  72158. destination.
  72159. */
  72160. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  72161. /*
  72162. This function is equivalent to deflateEnd followed by deflateInit,
  72163. but does not free and reallocate all the internal compression state.
  72164. The stream will keep the same compression level and any other attributes
  72165. that may have been set by deflateInit2.
  72166. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  72167. stream state was inconsistent (such as zalloc or state being NULL).
  72168. */
  72169. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  72170. int level,
  72171. int strategy));
  72172. /*
  72173. Dynamically update the compression level and compression strategy. The
  72174. interpretation of level and strategy is as in deflateInit2. This can be
  72175. used to switch between compression and straight copy of the input data, or
  72176. to switch to a different kind of input data requiring a different
  72177. strategy. If the compression level is changed, the input available so far
  72178. is compressed with the old level (and may be flushed); the new level will
  72179. take effect only at the next call of deflate().
  72180. Before the call of deflateParams, the stream state must be set as for
  72181. a call of deflate(), since the currently available input may have to
  72182. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  72183. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  72184. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  72185. if strm->avail_out was zero.
  72186. */
  72187. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  72188. int good_length,
  72189. int max_lazy,
  72190. int nice_length,
  72191. int max_chain));
  72192. /*
  72193. Fine tune deflate's internal compression parameters. This should only be
  72194. used by someone who understands the algorithm used by zlib's deflate for
  72195. searching for the best matching string, and even then only by the most
  72196. fanatic optimizer trying to squeeze out the last compressed bit for their
  72197. specific input data. Read the deflate.c source code for the meaning of the
  72198. max_lazy, good_length, nice_length, and max_chain parameters.
  72199. deflateTune() can be called after deflateInit() or deflateInit2(), and
  72200. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  72201. */
  72202. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  72203. uLong sourceLen));
  72204. /*
  72205. deflateBound() returns an upper bound on the compressed size after
  72206. deflation of sourceLen bytes. It must be called after deflateInit()
  72207. or deflateInit2(). This would be used to allocate an output buffer
  72208. for deflation in a single pass, and so would be called before deflate().
  72209. */
  72210. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  72211. int bits,
  72212. int value));
  72213. /*
  72214. deflatePrime() inserts bits in the deflate output stream. The intent
  72215. is that this function is used to start off the deflate output with the
  72216. bits leftover from a previous deflate stream when appending to it. As such,
  72217. this function can only be used for raw deflate, and must be used before the
  72218. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  72219. less than or equal to 16, and that many of the least significant bits of
  72220. value will be inserted in the output.
  72221. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  72222. stream state was inconsistent.
  72223. */
  72224. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  72225. gz_headerp head));
  72226. /*
  72227. deflateSetHeader() provides gzip header information for when a gzip
  72228. stream is requested by deflateInit2(). deflateSetHeader() may be called
  72229. after deflateInit2() or deflateReset() and before the first call of
  72230. deflate(). The text, time, os, extra field, name, and comment information
  72231. in the provided gz_header structure are written to the gzip header (xflag is
  72232. ignored -- the extra flags are set according to the compression level). The
  72233. caller must assure that, if not Z_NULL, name and comment are terminated with
  72234. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  72235. available there. If hcrc is true, a gzip header crc is included. Note that
  72236. the current versions of the command-line version of gzip (up through version
  72237. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  72238. gzip file" and give up.
  72239. If deflateSetHeader is not used, the default gzip header has text false,
  72240. the time set to zero, and os set to 255, with no extra, name, or comment
  72241. fields. The gzip header is returned to the default state by deflateReset().
  72242. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  72243. stream state was inconsistent.
  72244. */
  72245. /*
  72246. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  72247. int windowBits));
  72248. This is another version of inflateInit with an extra parameter. The
  72249. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  72250. before by the caller.
  72251. The windowBits parameter is the base two logarithm of the maximum window
  72252. size (the size of the history buffer). It should be in the range 8..15 for
  72253. this version of the library. The default value is 15 if inflateInit is used
  72254. instead. windowBits must be greater than or equal to the windowBits value
  72255. provided to deflateInit2() while compressing, or it must be equal to 15 if
  72256. deflateInit2() was not used. If a compressed stream with a larger window
  72257. size is given as input, inflate() will return with the error code
  72258. Z_DATA_ERROR instead of trying to allocate a larger window.
  72259. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  72260. determines the window size. inflate() will then process raw deflate data,
  72261. not looking for a zlib or gzip header, not generating a check value, and not
  72262. looking for any check values for comparison at the end of the stream. This
  72263. is for use with other formats that use the deflate compressed data format
  72264. such as zip. Those formats provide their own check values. If a custom
  72265. format is developed using the raw deflate format for compressed data, it is
  72266. recommended that a check value such as an adler32 or a crc32 be applied to
  72267. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  72268. most applications, the zlib format should be used as is. Note that comments
  72269. above on the use in deflateInit2() applies to the magnitude of windowBits.
  72270. windowBits can also be greater than 15 for optional gzip decoding. Add
  72271. 32 to windowBits to enable zlib and gzip decoding with automatic header
  72272. detection, or add 16 to decode only the gzip format (the zlib format will
  72273. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  72274. a crc32 instead of an adler32.
  72275. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  72276. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  72277. is set to null if there is no error message. inflateInit2 does not perform
  72278. any decompression apart from reading the zlib header if present: this will
  72279. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  72280. and avail_out are unchanged.)
  72281. */
  72282. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  72283. const Bytef *dictionary,
  72284. uInt dictLength));
  72285. /*
  72286. Initializes the decompression dictionary from the given uncompressed byte
  72287. sequence. This function must be called immediately after a call of inflate,
  72288. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  72289. can be determined from the adler32 value returned by that call of inflate.
  72290. The compressor and decompressor must use exactly the same dictionary (see
  72291. deflateSetDictionary). For raw inflate, this function can be called
  72292. immediately after inflateInit2() or inflateReset() and before any call of
  72293. inflate() to set the dictionary. The application must insure that the
  72294. dictionary that was used for compression is provided.
  72295. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  72296. parameter is invalid (such as NULL dictionary) or the stream state is
  72297. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  72298. expected one (incorrect adler32 value). inflateSetDictionary does not
  72299. perform any decompression: this will be done by subsequent calls of
  72300. inflate().
  72301. */
  72302. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  72303. /*
  72304. Skips invalid compressed data until a full flush point (see above the
  72305. description of deflate with Z_FULL_FLUSH) can be found, or until all
  72306. available input is skipped. No output is provided.
  72307. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  72308. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  72309. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  72310. case, the application may save the current current value of total_in which
  72311. indicates where valid compressed data was found. In the error case, the
  72312. application may repeatedly call inflateSync, providing more input each time,
  72313. until success or end of the input data.
  72314. */
  72315. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  72316. z_streamp source));
  72317. /*
  72318. Sets the destination stream as a complete copy of the source stream.
  72319. This function can be useful when randomly accessing a large stream. The
  72320. first pass through the stream can periodically record the inflate state,
  72321. allowing restarting inflate at those points when randomly accessing the
  72322. stream.
  72323. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  72324. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  72325. (such as zalloc being NULL). msg is left unchanged in both source and
  72326. destination.
  72327. */
  72328. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  72329. /*
  72330. This function is equivalent to inflateEnd followed by inflateInit,
  72331. but does not free and reallocate all the internal decompression state.
  72332. The stream will keep attributes that may have been set by inflateInit2.
  72333. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  72334. stream state was inconsistent (such as zalloc or state being NULL).
  72335. */
  72336. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  72337. int bits,
  72338. int value));
  72339. /*
  72340. This function inserts bits in the inflate input stream. The intent is
  72341. that this function is used to start inflating at a bit position in the
  72342. middle of a byte. The provided bits will be used before any bytes are used
  72343. from next_in. This function should only be used with raw inflate, and
  72344. should be used before the first inflate() call after inflateInit2() or
  72345. inflateReset(). bits must be less than or equal to 16, and that many of the
  72346. least significant bits of value will be inserted in the input.
  72347. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  72348. stream state was inconsistent.
  72349. */
  72350. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  72351. gz_headerp head));
  72352. /*
  72353. inflateGetHeader() requests that gzip header information be stored in the
  72354. provided gz_header structure. inflateGetHeader() may be called after
  72355. inflateInit2() or inflateReset(), and before the first call of inflate().
  72356. As inflate() processes the gzip stream, head->done is zero until the header
  72357. is completed, at which time head->done is set to one. If a zlib stream is
  72358. being decoded, then head->done is set to -1 to indicate that there will be
  72359. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  72360. force inflate() to return immediately after header processing is complete
  72361. and before any actual data is decompressed.
  72362. The text, time, xflags, and os fields are filled in with the gzip header
  72363. contents. hcrc is set to true if there is a header CRC. (The header CRC
  72364. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  72365. contains the maximum number of bytes to write to extra. Once done is true,
  72366. extra_len contains the actual extra field length, and extra contains the
  72367. extra field, or that field truncated if extra_max is less than extra_len.
  72368. If name is not Z_NULL, then up to name_max characters are written there,
  72369. terminated with a zero unless the length is greater than name_max. If
  72370. comment is not Z_NULL, then up to comm_max characters are written there,
  72371. terminated with a zero unless the length is greater than comm_max. When
  72372. any of extra, name, or comment are not Z_NULL and the respective field is
  72373. not present in the header, then that field is set to Z_NULL to signal its
  72374. absence. This allows the use of deflateSetHeader() with the returned
  72375. structure to duplicate the header. However if those fields are set to
  72376. allocated memory, then the application will need to save those pointers
  72377. elsewhere so that they can be eventually freed.
  72378. If inflateGetHeader is not used, then the header information is simply
  72379. discarded. The header is always checked for validity, including the header
  72380. CRC if present. inflateReset() will reset the process to discard the header
  72381. information. The application would need to call inflateGetHeader() again to
  72382. retrieve the header from the next gzip stream.
  72383. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  72384. stream state was inconsistent.
  72385. */
  72386. /*
  72387. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  72388. unsigned char FAR *window));
  72389. Initialize the internal stream state for decompression using inflateBack()
  72390. calls. The fields zalloc, zfree and opaque in strm must be initialized
  72391. before the call. If zalloc and zfree are Z_NULL, then the default library-
  72392. derived memory allocation routines are used. windowBits is the base two
  72393. logarithm of the window size, in the range 8..15. window is a caller
  72394. supplied buffer of that size. Except for special applications where it is
  72395. assured that deflate was used with small window sizes, windowBits must be 15
  72396. and a 32K byte window must be supplied to be able to decompress general
  72397. deflate streams.
  72398. See inflateBack() for the usage of these routines.
  72399. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  72400. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  72401. be allocated, or Z_VERSION_ERROR if the version of the library does not
  72402. match the version of the header file.
  72403. */
  72404. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  72405. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  72406. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  72407. in_func in, void FAR *in_desc,
  72408. out_func out, void FAR *out_desc));
  72409. /*
  72410. inflateBack() does a raw inflate with a single call using a call-back
  72411. interface for input and output. This is more efficient than inflate() for
  72412. file i/o applications in that it avoids copying between the output and the
  72413. sliding window by simply making the window itself the output buffer. This
  72414. function trusts the application to not change the output buffer passed by
  72415. the output function, at least until inflateBack() returns.
  72416. inflateBackInit() must be called first to allocate the internal state
  72417. and to initialize the state with the user-provided window buffer.
  72418. inflateBack() may then be used multiple times to inflate a complete, raw
  72419. deflate stream with each call. inflateBackEnd() is then called to free
  72420. the allocated state.
  72421. A raw deflate stream is one with no zlib or gzip header or trailer.
  72422. This routine would normally be used in a utility that reads zip or gzip
  72423. files and writes out uncompressed files. The utility would decode the
  72424. header and process the trailer on its own, hence this routine expects
  72425. only the raw deflate stream to decompress. This is different from the
  72426. normal behavior of inflate(), which expects either a zlib or gzip header and
  72427. trailer around the deflate stream.
  72428. inflateBack() uses two subroutines supplied by the caller that are then
  72429. called by inflateBack() for input and output. inflateBack() calls those
  72430. routines until it reads a complete deflate stream and writes out all of the
  72431. uncompressed data, or until it encounters an error. The function's
  72432. parameters and return types are defined above in the in_func and out_func
  72433. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  72434. number of bytes of provided input, and a pointer to that input in buf. If
  72435. there is no input available, in() must return zero--buf is ignored in that
  72436. case--and inflateBack() will return a buffer error. inflateBack() will call
  72437. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  72438. should return zero on success, or non-zero on failure. If out() returns
  72439. non-zero, inflateBack() will return with an error. Neither in() nor out()
  72440. are permitted to change the contents of the window provided to
  72441. inflateBackInit(), which is also the buffer that out() uses to write from.
  72442. The length written by out() will be at most the window size. Any non-zero
  72443. amount of input may be provided by in().
  72444. For convenience, inflateBack() can be provided input on the first call by
  72445. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  72446. in() will be called. Therefore strm->next_in must be initialized before
  72447. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  72448. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  72449. must also be initialized, and then if strm->avail_in is not zero, input will
  72450. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  72451. The in_desc and out_desc parameters of inflateBack() is passed as the
  72452. first parameter of in() and out() respectively when they are called. These
  72453. descriptors can be optionally used to pass any information that the caller-
  72454. supplied in() and out() functions need to do their job.
  72455. On return, inflateBack() will set strm->next_in and strm->avail_in to
  72456. pass back any unused input that was provided by the last in() call. The
  72457. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  72458. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  72459. error in the deflate stream (in which case strm->msg is set to indicate the
  72460. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  72461. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  72462. distinguished using strm->next_in which will be Z_NULL only if in() returned
  72463. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  72464. out() returning non-zero. (in() will always be called before out(), so
  72465. strm->next_in is assured to be defined if out() returns non-zero.) Note
  72466. that inflateBack() cannot return Z_OK.
  72467. */
  72468. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  72469. /*
  72470. All memory allocated by inflateBackInit() is freed.
  72471. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  72472. state was inconsistent.
  72473. */
  72474. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  72475. /* Return flags indicating compile-time options.
  72476. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  72477. 1.0: size of uInt
  72478. 3.2: size of uLong
  72479. 5.4: size of voidpf (pointer)
  72480. 7.6: size of z_off_t
  72481. Compiler, assembler, and debug options:
  72482. 8: DEBUG
  72483. 9: ASMV or ASMINF -- use ASM code
  72484. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  72485. 11: 0 (reserved)
  72486. One-time table building (smaller code, but not thread-safe if true):
  72487. 12: BUILDFIXED -- build static block decoding tables when needed
  72488. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  72489. 14,15: 0 (reserved)
  72490. Library content (indicates missing functionality):
  72491. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  72492. deflate code when not needed)
  72493. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  72494. and decode gzip streams (to avoid linking crc code)
  72495. 18-19: 0 (reserved)
  72496. Operation variations (changes in library functionality):
  72497. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  72498. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  72499. 22,23: 0 (reserved)
  72500. The sprintf variant used by gzprintf (zero is best):
  72501. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  72502. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  72503. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  72504. Remainder:
  72505. 27-31: 0 (reserved)
  72506. */
  72507. /* utility functions */
  72508. /*
  72509. The following utility functions are implemented on top of the
  72510. basic stream-oriented functions. To simplify the interface, some
  72511. default options are assumed (compression level and memory usage,
  72512. standard memory allocation functions). The source code of these
  72513. utility functions can easily be modified if you need special options.
  72514. */
  72515. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  72516. const Bytef *source, uLong sourceLen));
  72517. /*
  72518. Compresses the source buffer into the destination buffer. sourceLen is
  72519. the byte length of the source buffer. Upon entry, destLen is the total
  72520. size of the destination buffer, which must be at least the value returned
  72521. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  72522. compressed buffer.
  72523. This function can be used to compress a whole file at once if the
  72524. input file is mmap'ed.
  72525. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  72526. enough memory, Z_BUF_ERROR if there was not enough room in the output
  72527. buffer.
  72528. */
  72529. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  72530. const Bytef *source, uLong sourceLen,
  72531. int level));
  72532. /*
  72533. Compresses the source buffer into the destination buffer. The level
  72534. parameter has the same meaning as in deflateInit. sourceLen is the byte
  72535. length of the source buffer. Upon entry, destLen is the total size of the
  72536. destination buffer, which must be at least the value returned by
  72537. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  72538. compressed buffer.
  72539. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  72540. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  72541. Z_STREAM_ERROR if the level parameter is invalid.
  72542. */
  72543. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  72544. /*
  72545. compressBound() returns an upper bound on the compressed size after
  72546. compress() or compress2() on sourceLen bytes. It would be used before
  72547. a compress() or compress2() call to allocate the destination buffer.
  72548. */
  72549. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  72550. const Bytef *source, uLong sourceLen));
  72551. /*
  72552. Decompresses the source buffer into the destination buffer. sourceLen is
  72553. the byte length of the source buffer. Upon entry, destLen is the total
  72554. size of the destination buffer, which must be large enough to hold the
  72555. entire uncompressed data. (The size of the uncompressed data must have
  72556. been saved previously by the compressor and transmitted to the decompressor
  72557. by some mechanism outside the scope of this compression library.)
  72558. Upon exit, destLen is the actual size of the compressed buffer.
  72559. This function can be used to decompress a whole file at once if the
  72560. input file is mmap'ed.
  72561. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  72562. enough memory, Z_BUF_ERROR if there was not enough room in the output
  72563. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  72564. */
  72565. typedef voidp gzFile;
  72566. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  72567. /*
  72568. Opens a gzip (.gz) file for reading or writing. The mode parameter
  72569. is as in fopen ("rb" or "wb") but can also include a compression level
  72570. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  72571. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  72572. as in "wb1R". (See the description of deflateInit2 for more information
  72573. about the strategy parameter.)
  72574. gzopen can be used to read a file which is not in gzip format; in this
  72575. case gzread will directly read from the file without decompression.
  72576. gzopen returns NULL if the file could not be opened or if there was
  72577. insufficient memory to allocate the (de)compression state; errno
  72578. can be checked to distinguish the two cases (if errno is zero, the
  72579. zlib error is Z_MEM_ERROR). */
  72580. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  72581. /*
  72582. gzdopen() associates a gzFile with the file descriptor fd. File
  72583. descriptors are obtained from calls like open, dup, creat, pipe or
  72584. fileno (in the file has been previously opened with fopen).
  72585. The mode parameter is as in gzopen.
  72586. The next call of gzclose on the returned gzFile will also close the
  72587. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  72588. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  72589. gzdopen returns NULL if there was insufficient memory to allocate
  72590. the (de)compression state.
  72591. */
  72592. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  72593. /*
  72594. Dynamically update the compression level or strategy. See the description
  72595. of deflateInit2 for the meaning of these parameters.
  72596. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  72597. opened for writing.
  72598. */
  72599. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  72600. /*
  72601. Reads the given number of uncompressed bytes from the compressed file.
  72602. If the input file was not in gzip format, gzread copies the given number
  72603. of bytes into the buffer.
  72604. gzread returns the number of uncompressed bytes actually read (0 for
  72605. end of file, -1 for error). */
  72606. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  72607. voidpc buf, unsigned len));
  72608. /*
  72609. Writes the given number of uncompressed bytes into the compressed file.
  72610. gzwrite returns the number of uncompressed bytes actually written
  72611. (0 in case of error).
  72612. */
  72613. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  72614. /*
  72615. Converts, formats, and writes the args to the compressed file under
  72616. control of the format string, as in fprintf. gzprintf returns the number of
  72617. uncompressed bytes actually written (0 in case of error). The number of
  72618. uncompressed bytes written is limited to 4095. The caller should assure that
  72619. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  72620. return an error (0) with nothing written. In this case, there may also be a
  72621. buffer overflow with unpredictable consequences, which is possible only if
  72622. zlib was compiled with the insecure functions sprintf() or vsprintf()
  72623. because the secure snprintf() or vsnprintf() functions were not available.
  72624. */
  72625. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  72626. /*
  72627. Writes the given null-terminated string to the compressed file, excluding
  72628. the terminating null character.
  72629. gzputs returns the number of characters written, or -1 in case of error.
  72630. */
  72631. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  72632. /*
  72633. Reads bytes from the compressed file until len-1 characters are read, or
  72634. a newline character is read and transferred to buf, or an end-of-file
  72635. condition is encountered. The string is then terminated with a null
  72636. character.
  72637. gzgets returns buf, or Z_NULL in case of error.
  72638. */
  72639. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  72640. /*
  72641. Writes c, converted to an unsigned char, into the compressed file.
  72642. gzputc returns the value that was written, or -1 in case of error.
  72643. */
  72644. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  72645. /*
  72646. Reads one byte from the compressed file. gzgetc returns this byte
  72647. or -1 in case of end of file or error.
  72648. */
  72649. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  72650. /*
  72651. Push one character back onto the stream to be read again later.
  72652. Only one character of push-back is allowed. gzungetc() returns the
  72653. character pushed, or -1 on failure. gzungetc() will fail if a
  72654. character has been pushed but not read yet, or if c is -1. The pushed
  72655. character will be discarded if the stream is repositioned with gzseek()
  72656. or gzrewind().
  72657. */
  72658. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  72659. /*
  72660. Flushes all pending output into the compressed file. The parameter
  72661. flush is as in the deflate() function. The return value is the zlib
  72662. error number (see function gzerror below). gzflush returns Z_OK if
  72663. the flush parameter is Z_FINISH and all output could be flushed.
  72664. gzflush should be called only when strictly necessary because it can
  72665. degrade compression.
  72666. */
  72667. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  72668. z_off_t offset, int whence));
  72669. /*
  72670. Sets the starting position for the next gzread or gzwrite on the
  72671. given compressed file. The offset represents a number of bytes in the
  72672. uncompressed data stream. The whence parameter is defined as in lseek(2);
  72673. the value SEEK_END is not supported.
  72674. If the file is opened for reading, this function is emulated but can be
  72675. extremely slow. If the file is opened for writing, only forward seeks are
  72676. supported; gzseek then compresses a sequence of zeroes up to the new
  72677. starting position.
  72678. gzseek returns the resulting offset location as measured in bytes from
  72679. the beginning of the uncompressed stream, or -1 in case of error, in
  72680. particular if the file is opened for writing and the new starting position
  72681. would be before the current position.
  72682. */
  72683. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  72684. /*
  72685. Rewinds the given file. This function is supported only for reading.
  72686. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  72687. */
  72688. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  72689. /*
  72690. Returns the starting position for the next gzread or gzwrite on the
  72691. given compressed file. This position represents a number of bytes in the
  72692. uncompressed data stream.
  72693. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  72694. */
  72695. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  72696. /*
  72697. Returns 1 when EOF has previously been detected reading the given
  72698. input stream, otherwise zero.
  72699. */
  72700. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  72701. /*
  72702. Returns 1 if file is being read directly without decompression, otherwise
  72703. zero.
  72704. */
  72705. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  72706. /*
  72707. Flushes all pending output if necessary, closes the compressed file
  72708. and deallocates all the (de)compression state. The return value is the zlib
  72709. error number (see function gzerror below).
  72710. */
  72711. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  72712. /*
  72713. Returns the error message for the last error which occurred on the
  72714. given compressed file. errnum is set to zlib error number. If an
  72715. error occurred in the file system and not in the compression library,
  72716. errnum is set to Z_ERRNO and the application may consult errno
  72717. to get the exact error code.
  72718. */
  72719. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  72720. /*
  72721. Clears the error and end-of-file flags for file. This is analogous to the
  72722. clearerr() function in stdio. This is useful for continuing to read a gzip
  72723. file that is being written concurrently.
  72724. */
  72725. /* checksum functions */
  72726. /*
  72727. These functions are not related to compression but are exported
  72728. anyway because they might be useful in applications using the
  72729. compression library.
  72730. */
  72731. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  72732. /*
  72733. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  72734. return the updated checksum. If buf is NULL, this function returns
  72735. the required initial value for the checksum.
  72736. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  72737. much faster. Usage example:
  72738. uLong adler = adler32(0L, Z_NULL, 0);
  72739. while (read_buffer(buffer, length) != EOF) {
  72740. adler = adler32(adler, buffer, length);
  72741. }
  72742. if (adler != original_adler) error();
  72743. */
  72744. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  72745. z_off_t len2));
  72746. /*
  72747. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  72748. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  72749. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  72750. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  72751. */
  72752. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  72753. /*
  72754. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  72755. updated CRC-32. If buf is NULL, this function returns the required initial
  72756. value for the for the crc. Pre- and post-conditioning (one's complement) is
  72757. performed within this function so it shouldn't be done by the application.
  72758. Usage example:
  72759. uLong crc = crc32(0L, Z_NULL, 0);
  72760. while (read_buffer(buffer, length) != EOF) {
  72761. crc = crc32(crc, buffer, length);
  72762. }
  72763. if (crc != original_crc) error();
  72764. */
  72765. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  72766. /*
  72767. Combine two CRC-32 check values into one. For two sequences of bytes,
  72768. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  72769. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  72770. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  72771. len2.
  72772. */
  72773. /* various hacks, don't look :) */
  72774. /* deflateInit and inflateInit are macros to allow checking the zlib version
  72775. * and the compiler's view of z_stream:
  72776. */
  72777. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  72778. const char *version, int stream_size));
  72779. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  72780. const char *version, int stream_size));
  72781. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  72782. int windowBits, int memLevel,
  72783. int strategy, const char *version,
  72784. int stream_size));
  72785. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  72786. const char *version, int stream_size));
  72787. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  72788. unsigned char FAR *window,
  72789. const char *version,
  72790. int stream_size));
  72791. #define deflateInit(strm, level) \
  72792. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  72793. #define inflateInit(strm) \
  72794. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  72795. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  72796. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  72797. (strategy), ZLIB_VERSION, sizeof(z_stream))
  72798. #define inflateInit2(strm, windowBits) \
  72799. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  72800. #define inflateBackInit(strm, windowBits, window) \
  72801. inflateBackInit_((strm), (windowBits), (window), \
  72802. ZLIB_VERSION, sizeof(z_stream))
  72803. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  72804. struct internal_state {int dummy;}; /* hack for buggy compilers */
  72805. #endif
  72806. ZEXTERN const char * ZEXPORT zError OF((int));
  72807. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  72808. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  72809. #ifdef __cplusplus
  72810. }
  72811. #endif
  72812. #endif /* ZLIB_H */
  72813. /********* End of inlined file: zlib.h *********/
  72814. #undef OS_CODE
  72815. }
  72816. BEGIN_JUCE_NAMESPACE
  72817. using namespace zlibNamespace;
  72818. // internal helper object that holds the zlib structures so they don't have to be
  72819. // included publicly.
  72820. class GZIPCompressorHelper
  72821. {
  72822. private:
  72823. z_stream* stream;
  72824. uint8* data;
  72825. int dataSize, compLevel, strategy;
  72826. bool setParams;
  72827. public:
  72828. bool finished, shouldFinish;
  72829. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  72830. : data (0),
  72831. dataSize (0),
  72832. compLevel (compressionLevel),
  72833. strategy (0),
  72834. setParams (true),
  72835. finished (false),
  72836. shouldFinish (false)
  72837. {
  72838. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  72839. if (deflateInit2 (stream,
  72840. compLevel,
  72841. Z_DEFLATED,
  72842. nowrap ? -MAX_WBITS : MAX_WBITS,
  72843. 8,
  72844. strategy) != Z_OK)
  72845. {
  72846. juce_free (stream);
  72847. stream = 0;
  72848. }
  72849. }
  72850. ~GZIPCompressorHelper()
  72851. {
  72852. if (stream != 0)
  72853. {
  72854. deflateEnd (stream);
  72855. juce_free (stream);
  72856. }
  72857. }
  72858. bool needsInput() const throw()
  72859. {
  72860. return dataSize <= 0;
  72861. }
  72862. void setInput (uint8* const newData, const int size) throw()
  72863. {
  72864. data = newData;
  72865. dataSize = size;
  72866. }
  72867. int doNextBlock (uint8* const dest, const int destSize) throw()
  72868. {
  72869. if (stream != 0)
  72870. {
  72871. stream->next_in = data;
  72872. stream->next_out = dest;
  72873. stream->avail_in = dataSize;
  72874. stream->avail_out = destSize;
  72875. const int result = setParams ? deflateParams (stream, compLevel, strategy)
  72876. : deflate (stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  72877. setParams = false;
  72878. switch (result)
  72879. {
  72880. case Z_STREAM_END:
  72881. finished = true;
  72882. case Z_OK:
  72883. data += dataSize - stream->avail_in;
  72884. dataSize = stream->avail_in;
  72885. return destSize - stream->avail_out;
  72886. default:
  72887. break;
  72888. }
  72889. }
  72890. return 0;
  72891. }
  72892. };
  72893. const int gzipCompBufferSize = 32768;
  72894. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  72895. int compressionLevel,
  72896. const bool deleteDestStream_,
  72897. const bool noWrap)
  72898. : destStream (destStream_),
  72899. deleteDestStream (deleteDestStream_)
  72900. {
  72901. if (compressionLevel < 1 || compressionLevel > 9)
  72902. compressionLevel = -1;
  72903. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  72904. buffer = (uint8*) juce_malloc (gzipCompBufferSize);
  72905. }
  72906. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  72907. {
  72908. flush();
  72909. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72910. delete h;
  72911. juce_free (buffer);
  72912. if (deleteDestStream)
  72913. delete destStream;
  72914. }
  72915. void GZIPCompressorOutputStream::flush()
  72916. {
  72917. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72918. if (! h->finished)
  72919. {
  72920. h->shouldFinish = true;
  72921. while (! h->finished)
  72922. doNextBlock();
  72923. }
  72924. destStream->flush();
  72925. }
  72926. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  72927. {
  72928. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72929. if (! h->finished)
  72930. {
  72931. h->setInput ((uint8*) destBuffer, howMany);
  72932. while (! h->needsInput())
  72933. {
  72934. if (! doNextBlock())
  72935. return false;
  72936. }
  72937. }
  72938. return true;
  72939. }
  72940. bool GZIPCompressorOutputStream::doNextBlock()
  72941. {
  72942. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72943. const int len = h->doNextBlock (buffer, gzipCompBufferSize);
  72944. if (len > 0)
  72945. return destStream->write (buffer, len);
  72946. else
  72947. return true;
  72948. }
  72949. int64 GZIPCompressorOutputStream::getPosition()
  72950. {
  72951. return destStream->getPosition();
  72952. }
  72953. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  72954. {
  72955. jassertfalse // can't do it!
  72956. return false;
  72957. }
  72958. END_JUCE_NAMESPACE
  72959. /********* End of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  72960. /********* Start of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  72961. #if JUCE_MSVC
  72962. #pragma warning (push)
  72963. #pragma warning (disable: 4309 4305)
  72964. #endif
  72965. namespace zlibNamespace
  72966. {
  72967. extern "C"
  72968. {
  72969. #undef OS_CODE
  72970. #undef fdopen
  72971. #define ZLIB_INTERNAL
  72972. #define NO_DUMMY_DECL
  72973. /********* Start of inlined file: adler32.c *********/
  72974. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  72975. #define ZLIB_INTERNAL
  72976. #define BASE 65521UL /* largest prime smaller than 65536 */
  72977. #define NMAX 5552
  72978. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  72979. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  72980. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  72981. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  72982. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  72983. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  72984. /* use NO_DIVIDE if your processor does not do division in hardware */
  72985. #ifdef NO_DIVIDE
  72986. # define MOD(a) \
  72987. do { \
  72988. if (a >= (BASE << 16)) a -= (BASE << 16); \
  72989. if (a >= (BASE << 15)) a -= (BASE << 15); \
  72990. if (a >= (BASE << 14)) a -= (BASE << 14); \
  72991. if (a >= (BASE << 13)) a -= (BASE << 13); \
  72992. if (a >= (BASE << 12)) a -= (BASE << 12); \
  72993. if (a >= (BASE << 11)) a -= (BASE << 11); \
  72994. if (a >= (BASE << 10)) a -= (BASE << 10); \
  72995. if (a >= (BASE << 9)) a -= (BASE << 9); \
  72996. if (a >= (BASE << 8)) a -= (BASE << 8); \
  72997. if (a >= (BASE << 7)) a -= (BASE << 7); \
  72998. if (a >= (BASE << 6)) a -= (BASE << 6); \
  72999. if (a >= (BASE << 5)) a -= (BASE << 5); \
  73000. if (a >= (BASE << 4)) a -= (BASE << 4); \
  73001. if (a >= (BASE << 3)) a -= (BASE << 3); \
  73002. if (a >= (BASE << 2)) a -= (BASE << 2); \
  73003. if (a >= (BASE << 1)) a -= (BASE << 1); \
  73004. if (a >= BASE) a -= BASE; \
  73005. } while (0)
  73006. # define MOD4(a) \
  73007. do { \
  73008. if (a >= (BASE << 4)) a -= (BASE << 4); \
  73009. if (a >= (BASE << 3)) a -= (BASE << 3); \
  73010. if (a >= (BASE << 2)) a -= (BASE << 2); \
  73011. if (a >= (BASE << 1)) a -= (BASE << 1); \
  73012. if (a >= BASE) a -= BASE; \
  73013. } while (0)
  73014. #else
  73015. # define MOD(a) a %= BASE
  73016. # define MOD4(a) a %= BASE
  73017. #endif
  73018. /* ========================================================================= */
  73019. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  73020. {
  73021. unsigned long sum2;
  73022. unsigned n;
  73023. /* split Adler-32 into component sums */
  73024. sum2 = (adler >> 16) & 0xffff;
  73025. adler &= 0xffff;
  73026. /* in case user likes doing a byte at a time, keep it fast */
  73027. if (len == 1) {
  73028. adler += buf[0];
  73029. if (adler >= BASE)
  73030. adler -= BASE;
  73031. sum2 += adler;
  73032. if (sum2 >= BASE)
  73033. sum2 -= BASE;
  73034. return adler | (sum2 << 16);
  73035. }
  73036. /* initial Adler-32 value (deferred check for len == 1 speed) */
  73037. if (buf == Z_NULL)
  73038. return 1L;
  73039. /* in case short lengths are provided, keep it somewhat fast */
  73040. if (len < 16) {
  73041. while (len--) {
  73042. adler += *buf++;
  73043. sum2 += adler;
  73044. }
  73045. if (adler >= BASE)
  73046. adler -= BASE;
  73047. MOD4(sum2); /* only added so many BASE's */
  73048. return adler | (sum2 << 16);
  73049. }
  73050. /* do length NMAX blocks -- requires just one modulo operation */
  73051. while (len >= NMAX) {
  73052. len -= NMAX;
  73053. n = NMAX / 16; /* NMAX is divisible by 16 */
  73054. do {
  73055. DO16(buf); /* 16 sums unrolled */
  73056. buf += 16;
  73057. } while (--n);
  73058. MOD(adler);
  73059. MOD(sum2);
  73060. }
  73061. /* do remaining bytes (less than NMAX, still just one modulo) */
  73062. if (len) { /* avoid modulos if none remaining */
  73063. while (len >= 16) {
  73064. len -= 16;
  73065. DO16(buf);
  73066. buf += 16;
  73067. }
  73068. while (len--) {
  73069. adler += *buf++;
  73070. sum2 += adler;
  73071. }
  73072. MOD(adler);
  73073. MOD(sum2);
  73074. }
  73075. /* return recombined sums */
  73076. return adler | (sum2 << 16);
  73077. }
  73078. /* ========================================================================= */
  73079. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  73080. {
  73081. unsigned long sum1;
  73082. unsigned long sum2;
  73083. unsigned rem;
  73084. /* the derivation of this formula is left as an exercise for the reader */
  73085. rem = (unsigned)(len2 % BASE);
  73086. sum1 = adler1 & 0xffff;
  73087. sum2 = rem * sum1;
  73088. MOD(sum2);
  73089. sum1 += (adler2 & 0xffff) + BASE - 1;
  73090. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  73091. if (sum1 > BASE) sum1 -= BASE;
  73092. if (sum1 > BASE) sum1 -= BASE;
  73093. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  73094. if (sum2 > BASE) sum2 -= BASE;
  73095. return sum1 | (sum2 << 16);
  73096. }
  73097. /********* End of inlined file: adler32.c *********/
  73098. /********* Start of inlined file: compress.c *********/
  73099. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73100. #define ZLIB_INTERNAL
  73101. /* ===========================================================================
  73102. Compresses the source buffer into the destination buffer. The level
  73103. parameter has the same meaning as in deflateInit. sourceLen is the byte
  73104. length of the source buffer. Upon entry, destLen is the total size of the
  73105. destination buffer, which must be at least 0.1% larger than sourceLen plus
  73106. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  73107. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  73108. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  73109. Z_STREAM_ERROR if the level parameter is invalid.
  73110. */
  73111. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  73112. uLong sourceLen, int level)
  73113. {
  73114. z_stream stream;
  73115. int err;
  73116. stream.next_in = (Bytef*)source;
  73117. stream.avail_in = (uInt)sourceLen;
  73118. #ifdef MAXSEG_64K
  73119. /* Check for source > 64K on 16-bit machine: */
  73120. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  73121. #endif
  73122. stream.next_out = dest;
  73123. stream.avail_out = (uInt)*destLen;
  73124. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  73125. stream.zalloc = (alloc_func)0;
  73126. stream.zfree = (free_func)0;
  73127. stream.opaque = (voidpf)0;
  73128. err = deflateInit(&stream, level);
  73129. if (err != Z_OK) return err;
  73130. err = deflate(&stream, Z_FINISH);
  73131. if (err != Z_STREAM_END) {
  73132. deflateEnd(&stream);
  73133. return err == Z_OK ? Z_BUF_ERROR : err;
  73134. }
  73135. *destLen = stream.total_out;
  73136. err = deflateEnd(&stream);
  73137. return err;
  73138. }
  73139. /* ===========================================================================
  73140. */
  73141. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  73142. {
  73143. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  73144. }
  73145. /* ===========================================================================
  73146. If the default memLevel or windowBits for deflateInit() is changed, then
  73147. this function needs to be updated.
  73148. */
  73149. uLong ZEXPORT compressBound (uLong sourceLen)
  73150. {
  73151. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  73152. }
  73153. /********* End of inlined file: compress.c *********/
  73154. #undef DO1
  73155. #undef DO8
  73156. /********* Start of inlined file: crc32.c *********/
  73157. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73158. /*
  73159. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  73160. protection on the static variables used to control the first-use generation
  73161. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  73162. first call get_crc_table() to initialize the tables before allowing more than
  73163. one thread to use crc32().
  73164. */
  73165. #ifdef MAKECRCH
  73166. # include <stdio.h>
  73167. # ifndef DYNAMIC_CRC_TABLE
  73168. # define DYNAMIC_CRC_TABLE
  73169. # endif /* !DYNAMIC_CRC_TABLE */
  73170. #endif /* MAKECRCH */
  73171. /********* Start of inlined file: zutil.h *********/
  73172. /* WARNING: this file should *not* be used by applications. It is
  73173. part of the implementation of the compression library and is
  73174. subject to change. Applications should only use zlib.h.
  73175. */
  73176. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73177. #ifndef ZUTIL_H
  73178. #define ZUTIL_H
  73179. #define ZLIB_INTERNAL
  73180. #ifdef STDC
  73181. # ifndef _WIN32_WCE
  73182. # include <stddef.h>
  73183. # endif
  73184. # include <string.h>
  73185. # include <stdlib.h>
  73186. #endif
  73187. #ifdef NO_ERRNO_H
  73188. # ifdef _WIN32_WCE
  73189. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  73190. * errno. We define it as a global variable to simplify porting.
  73191. * Its value is always 0 and should not be used. We rename it to
  73192. * avoid conflict with other libraries that use the same workaround.
  73193. */
  73194. # define errno z_errno
  73195. # endif
  73196. extern int errno;
  73197. #else
  73198. # ifndef _WIN32_WCE
  73199. # include <errno.h>
  73200. # endif
  73201. #endif
  73202. #ifndef local
  73203. # define local static
  73204. #endif
  73205. /* compile with -Dlocal if your debugger can't find static symbols */
  73206. typedef unsigned char uch;
  73207. typedef uch FAR uchf;
  73208. typedef unsigned short ush;
  73209. typedef ush FAR ushf;
  73210. typedef unsigned long ulg;
  73211. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  73212. /* (size given to avoid silly warnings with Visual C++) */
  73213. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  73214. #define ERR_RETURN(strm,err) \
  73215. return (strm->msg = (char*)ERR_MSG(err), (err))
  73216. /* To be used only when the state is known to be valid */
  73217. /* common constants */
  73218. #ifndef DEF_WBITS
  73219. # define DEF_WBITS MAX_WBITS
  73220. #endif
  73221. /* default windowBits for decompression. MAX_WBITS is for compression only */
  73222. #if MAX_MEM_LEVEL >= 8
  73223. # define DEF_MEM_LEVEL 8
  73224. #else
  73225. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  73226. #endif
  73227. /* default memLevel */
  73228. #define STORED_BLOCK 0
  73229. #define STATIC_TREES 1
  73230. #define DYN_TREES 2
  73231. /* The three kinds of block type */
  73232. #define MIN_MATCH 3
  73233. #define MAX_MATCH 258
  73234. /* The minimum and maximum match lengths */
  73235. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  73236. /* target dependencies */
  73237. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  73238. # define OS_CODE 0x00
  73239. # if defined(__TURBOC__) || defined(__BORLANDC__)
  73240. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  73241. /* Allow compilation with ANSI keywords only enabled */
  73242. void _Cdecl farfree( void *block );
  73243. void *_Cdecl farmalloc( unsigned long nbytes );
  73244. # else
  73245. # include <alloc.h>
  73246. # endif
  73247. # else /* MSC or DJGPP */
  73248. # include <malloc.h>
  73249. # endif
  73250. #endif
  73251. #ifdef AMIGA
  73252. # define OS_CODE 0x01
  73253. #endif
  73254. #if defined(VAXC) || defined(VMS)
  73255. # define OS_CODE 0x02
  73256. # define F_OPEN(name, mode) \
  73257. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  73258. #endif
  73259. #if defined(ATARI) || defined(atarist)
  73260. # define OS_CODE 0x05
  73261. #endif
  73262. #ifdef OS2
  73263. # define OS_CODE 0x06
  73264. # ifdef M_I86
  73265. #include <malloc.h>
  73266. # endif
  73267. #endif
  73268. #if defined(MACOS) || TARGET_OS_MAC
  73269. # define OS_CODE 0x07
  73270. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  73271. # include <unix.h> /* for fdopen */
  73272. # else
  73273. # ifndef fdopen
  73274. # define fdopen(fd,mode) NULL /* No fdopen() */
  73275. # endif
  73276. # endif
  73277. #endif
  73278. #ifdef TOPS20
  73279. # define OS_CODE 0x0a
  73280. #endif
  73281. #ifdef WIN32
  73282. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  73283. # define OS_CODE 0x0b
  73284. # endif
  73285. #endif
  73286. #ifdef __50SERIES /* Prime/PRIMOS */
  73287. # define OS_CODE 0x0f
  73288. #endif
  73289. #if defined(_BEOS_) || defined(RISCOS)
  73290. # define fdopen(fd,mode) NULL /* No fdopen() */
  73291. #endif
  73292. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  73293. # if defined(_WIN32_WCE)
  73294. # define fdopen(fd,mode) NULL /* No fdopen() */
  73295. # ifndef _PTRDIFF_T_DEFINED
  73296. typedef int ptrdiff_t;
  73297. # define _PTRDIFF_T_DEFINED
  73298. # endif
  73299. # else
  73300. # define fdopen(fd,type) _fdopen(fd,type)
  73301. # endif
  73302. #endif
  73303. /* common defaults */
  73304. #ifndef OS_CODE
  73305. # define OS_CODE 0x03 /* assume Unix */
  73306. #endif
  73307. #ifndef F_OPEN
  73308. # define F_OPEN(name, mode) fopen((name), (mode))
  73309. #endif
  73310. /* functions */
  73311. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  73312. # ifndef HAVE_VSNPRINTF
  73313. # define HAVE_VSNPRINTF
  73314. # endif
  73315. #endif
  73316. #if defined(__CYGWIN__)
  73317. # ifndef HAVE_VSNPRINTF
  73318. # define HAVE_VSNPRINTF
  73319. # endif
  73320. #endif
  73321. #ifndef HAVE_VSNPRINTF
  73322. # ifdef MSDOS
  73323. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  73324. but for now we just assume it doesn't. */
  73325. # define NO_vsnprintf
  73326. # endif
  73327. # ifdef __TURBOC__
  73328. # define NO_vsnprintf
  73329. # endif
  73330. # ifdef WIN32
  73331. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  73332. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  73333. # define vsnprintf _vsnprintf
  73334. # endif
  73335. # endif
  73336. # ifdef __SASC
  73337. # define NO_vsnprintf
  73338. # endif
  73339. #endif
  73340. #ifdef VMS
  73341. # define NO_vsnprintf
  73342. #endif
  73343. #if defined(pyr)
  73344. # define NO_MEMCPY
  73345. #endif
  73346. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  73347. /* Use our own functions for small and medium model with MSC <= 5.0.
  73348. * You may have to use the same strategy for Borland C (untested).
  73349. * The __SC__ check is for Symantec.
  73350. */
  73351. # define NO_MEMCPY
  73352. #endif
  73353. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  73354. # define HAVE_MEMCPY
  73355. #endif
  73356. #ifdef HAVE_MEMCPY
  73357. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  73358. # define zmemcpy _fmemcpy
  73359. # define zmemcmp _fmemcmp
  73360. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  73361. # else
  73362. # define zmemcpy memcpy
  73363. # define zmemcmp memcmp
  73364. # define zmemzero(dest, len) memset(dest, 0, len)
  73365. # endif
  73366. #else
  73367. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  73368. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  73369. extern void zmemzero OF((Bytef* dest, uInt len));
  73370. #endif
  73371. /* Diagnostic functions */
  73372. #ifdef DEBUG
  73373. # include <stdio.h>
  73374. extern int z_verbose;
  73375. extern void z_error OF((char *m));
  73376. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  73377. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  73378. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  73379. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  73380. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  73381. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  73382. #else
  73383. # define Assert(cond,msg)
  73384. # define Trace(x)
  73385. # define Tracev(x)
  73386. # define Tracevv(x)
  73387. # define Tracec(c,x)
  73388. # define Tracecv(c,x)
  73389. #endif
  73390. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  73391. void zcfree OF((voidpf opaque, voidpf ptr));
  73392. #define ZALLOC(strm, items, size) \
  73393. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  73394. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  73395. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  73396. #endif /* ZUTIL_H */
  73397. /********* End of inlined file: zutil.h *********/
  73398. /* for STDC and FAR definitions */
  73399. #define local static
  73400. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  73401. #ifndef NOBYFOUR
  73402. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  73403. # include <limits.h>
  73404. # define BYFOUR
  73405. # if (UINT_MAX == 0xffffffffUL)
  73406. typedef unsigned int u4;
  73407. # else
  73408. # if (ULONG_MAX == 0xffffffffUL)
  73409. typedef unsigned long u4;
  73410. # else
  73411. # if (USHRT_MAX == 0xffffffffUL)
  73412. typedef unsigned short u4;
  73413. # else
  73414. # undef BYFOUR /* can't find a four-byte integer type! */
  73415. # endif
  73416. # endif
  73417. # endif
  73418. # endif /* STDC */
  73419. #endif /* !NOBYFOUR */
  73420. /* Definitions for doing the crc four data bytes at a time. */
  73421. #ifdef BYFOUR
  73422. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  73423. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  73424. local unsigned long crc32_little OF((unsigned long,
  73425. const unsigned char FAR *, unsigned));
  73426. local unsigned long crc32_big OF((unsigned long,
  73427. const unsigned char FAR *, unsigned));
  73428. # define TBLS 8
  73429. #else
  73430. # define TBLS 1
  73431. #endif /* BYFOUR */
  73432. /* Local functions for crc concatenation */
  73433. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  73434. unsigned long vec));
  73435. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  73436. #ifdef DYNAMIC_CRC_TABLE
  73437. local volatile int crc_table_empty = 1;
  73438. local unsigned long FAR crc_table[TBLS][256];
  73439. local void make_crc_table OF((void));
  73440. #ifdef MAKECRCH
  73441. local void write_table OF((FILE *, const unsigned long FAR *));
  73442. #endif /* MAKECRCH */
  73443. /*
  73444. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  73445. x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
  73446. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  73447. with the lowest powers in the most significant bit. Then adding polynomials
  73448. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  73449. one. If we call the above polynomial p, and represent a byte as the
  73450. polynomial q, also with the lowest power in the most significant bit (so the
  73451. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  73452. where a mod b means the remainder after dividing a by b.
  73453. This calculation is done using the shift-register method of multiplying and
  73454. taking the remainder. The register is initialized to zero, and for each
  73455. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  73456. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  73457. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  73458. out is a one). We start with the highest power (least significant bit) of
  73459. q and repeat for all eight bits of q.
  73460. The first table is simply the CRC of all possible eight bit values. This is
  73461. all the information needed to generate CRCs on data a byte at a time for all
  73462. combinations of CRC register values and incoming bytes. The remaining tables
  73463. allow for word-at-a-time CRC calculation for both big-endian and little-
  73464. endian machines, where a word is four bytes.
  73465. */
  73466. local void make_crc_table()
  73467. {
  73468. unsigned long c;
  73469. int n, k;
  73470. unsigned long poly; /* polynomial exclusive-or pattern */
  73471. /* terms of polynomial defining this crc (except x^32): */
  73472. static volatile int first = 1; /* flag to limit concurrent making */
  73473. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  73474. /* See if another task is already doing this (not thread-safe, but better
  73475. than nothing -- significantly reduces duration of vulnerability in
  73476. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  73477. if (first) {
  73478. first = 0;
  73479. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  73480. poly = 0UL;
  73481. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  73482. poly |= 1UL << (31 - p[n]);
  73483. /* generate a crc for every 8-bit value */
  73484. for (n = 0; n < 256; n++) {
  73485. c = (unsigned long)n;
  73486. for (k = 0; k < 8; k++)
  73487. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  73488. crc_table[0][n] = c;
  73489. }
  73490. #ifdef BYFOUR
  73491. /* generate crc for each value followed by one, two, and three zeros,
  73492. and then the byte reversal of those as well as the first table */
  73493. for (n = 0; n < 256; n++) {
  73494. c = crc_table[0][n];
  73495. crc_table[4][n] = REV(c);
  73496. for (k = 1; k < 4; k++) {
  73497. c = crc_table[0][c & 0xff] ^ (c >> 8);
  73498. crc_table[k][n] = c;
  73499. crc_table[k + 4][n] = REV(c);
  73500. }
  73501. }
  73502. #endif /* BYFOUR */
  73503. crc_table_empty = 0;
  73504. }
  73505. else { /* not first */
  73506. /* wait for the other guy to finish (not efficient, but rare) */
  73507. while (crc_table_empty)
  73508. ;
  73509. }
  73510. #ifdef MAKECRCH
  73511. /* write out CRC tables to crc32.h */
  73512. {
  73513. FILE *out;
  73514. out = fopen("crc32.h", "w");
  73515. if (out == NULL) return;
  73516. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  73517. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  73518. fprintf(out, "local const unsigned long FAR ");
  73519. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  73520. write_table(out, crc_table[0]);
  73521. # ifdef BYFOUR
  73522. fprintf(out, "#ifdef BYFOUR\n");
  73523. for (k = 1; k < 8; k++) {
  73524. fprintf(out, " },\n {\n");
  73525. write_table(out, crc_table[k]);
  73526. }
  73527. fprintf(out, "#endif\n");
  73528. # endif /* BYFOUR */
  73529. fprintf(out, " }\n};\n");
  73530. fclose(out);
  73531. }
  73532. #endif /* MAKECRCH */
  73533. }
  73534. #ifdef MAKECRCH
  73535. local void write_table(out, table)
  73536. FILE *out;
  73537. const unsigned long FAR *table;
  73538. {
  73539. int n;
  73540. for (n = 0; n < 256; n++)
  73541. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  73542. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  73543. }
  73544. #endif /* MAKECRCH */
  73545. #else /* !DYNAMIC_CRC_TABLE */
  73546. /* ========================================================================
  73547. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  73548. */
  73549. /********* Start of inlined file: crc32.h *********/
  73550. local const unsigned long FAR crc_table[TBLS][256] =
  73551. {
  73552. {
  73553. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  73554. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  73555. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  73556. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  73557. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  73558. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  73559. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  73560. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  73561. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  73562. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  73563. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  73564. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  73565. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  73566. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  73567. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  73568. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  73569. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  73570. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  73571. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  73572. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  73573. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  73574. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  73575. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  73576. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  73577. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  73578. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  73579. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  73580. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  73581. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  73582. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  73583. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  73584. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  73585. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  73586. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  73587. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  73588. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  73589. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  73590. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  73591. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  73592. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  73593. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  73594. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  73595. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  73596. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  73597. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  73598. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  73599. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  73600. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  73601. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  73602. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  73603. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  73604. 0x2d02ef8dUL
  73605. #ifdef BYFOUR
  73606. },
  73607. {
  73608. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  73609. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  73610. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  73611. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  73612. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  73613. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  73614. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  73615. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  73616. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  73617. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  73618. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  73619. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  73620. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  73621. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  73622. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  73623. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  73624. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  73625. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  73626. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  73627. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  73628. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  73629. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  73630. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  73631. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  73632. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  73633. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  73634. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  73635. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  73636. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  73637. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  73638. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  73639. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  73640. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  73641. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  73642. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  73643. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  73644. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  73645. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  73646. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  73647. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  73648. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  73649. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  73650. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  73651. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  73652. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  73653. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  73654. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  73655. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  73656. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  73657. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  73658. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  73659. 0x9324fd72UL
  73660. },
  73661. {
  73662. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  73663. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  73664. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  73665. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  73666. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  73667. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  73668. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  73669. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  73670. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  73671. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  73672. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  73673. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  73674. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  73675. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  73676. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  73677. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  73678. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  73679. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  73680. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  73681. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  73682. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  73683. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  73684. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  73685. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  73686. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  73687. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  73688. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  73689. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  73690. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  73691. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  73692. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  73693. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  73694. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  73695. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  73696. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  73697. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  73698. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  73699. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  73700. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  73701. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  73702. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  73703. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  73704. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  73705. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  73706. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  73707. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  73708. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  73709. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  73710. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  73711. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  73712. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  73713. 0xbe9834edUL
  73714. },
  73715. {
  73716. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  73717. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  73718. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  73719. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  73720. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  73721. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  73722. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  73723. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  73724. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  73725. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  73726. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  73727. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  73728. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  73729. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  73730. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  73731. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  73732. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  73733. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  73734. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  73735. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  73736. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  73737. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  73738. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  73739. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  73740. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  73741. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  73742. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  73743. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  73744. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  73745. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  73746. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  73747. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  73748. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  73749. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  73750. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  73751. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  73752. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  73753. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  73754. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  73755. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  73756. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  73757. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  73758. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  73759. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  73760. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  73761. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  73762. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  73763. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  73764. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  73765. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  73766. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  73767. 0xde0506f1UL
  73768. },
  73769. {
  73770. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  73771. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  73772. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  73773. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  73774. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  73775. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  73776. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  73777. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  73778. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  73779. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  73780. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  73781. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  73782. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  73783. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  73784. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  73785. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  73786. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  73787. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  73788. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  73789. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  73790. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  73791. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  73792. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  73793. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  73794. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  73795. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  73796. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  73797. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  73798. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  73799. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  73800. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  73801. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  73802. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  73803. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  73804. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  73805. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  73806. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  73807. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  73808. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  73809. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  73810. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  73811. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  73812. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  73813. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  73814. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  73815. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  73816. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  73817. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  73818. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  73819. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  73820. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  73821. 0x8def022dUL
  73822. },
  73823. {
  73824. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  73825. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  73826. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  73827. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  73828. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  73829. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  73830. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  73831. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  73832. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  73833. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  73834. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  73835. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  73836. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  73837. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  73838. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  73839. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  73840. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  73841. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  73842. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  73843. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  73844. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  73845. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  73846. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  73847. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  73848. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  73849. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  73850. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  73851. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  73852. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  73853. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  73854. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  73855. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  73856. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  73857. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  73858. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  73859. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  73860. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  73861. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  73862. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  73863. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  73864. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  73865. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  73866. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  73867. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  73868. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  73869. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  73870. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  73871. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  73872. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  73873. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  73874. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  73875. 0x72fd2493UL
  73876. },
  73877. {
  73878. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  73879. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  73880. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  73881. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  73882. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  73883. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  73884. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  73885. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  73886. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  73887. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  73888. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  73889. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  73890. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  73891. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  73892. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  73893. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  73894. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  73895. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  73896. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  73897. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  73898. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  73899. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  73900. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  73901. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  73902. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  73903. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  73904. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  73905. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  73906. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  73907. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  73908. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  73909. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  73910. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  73911. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  73912. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  73913. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  73914. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  73915. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  73916. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  73917. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  73918. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  73919. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  73920. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  73921. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  73922. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  73923. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  73924. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  73925. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  73926. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  73927. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  73928. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  73929. 0xed3498beUL
  73930. },
  73931. {
  73932. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  73933. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  73934. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  73935. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  73936. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  73937. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  73938. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  73939. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  73940. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  73941. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  73942. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  73943. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  73944. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  73945. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  73946. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  73947. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  73948. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  73949. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  73950. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  73951. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  73952. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  73953. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  73954. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  73955. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  73956. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  73957. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  73958. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  73959. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  73960. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  73961. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  73962. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  73963. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  73964. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  73965. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  73966. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  73967. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  73968. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  73969. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  73970. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  73971. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  73972. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  73973. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  73974. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  73975. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  73976. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  73977. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  73978. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  73979. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  73980. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  73981. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  73982. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  73983. 0xf10605deUL
  73984. #endif
  73985. }
  73986. };
  73987. /********* End of inlined file: crc32.h *********/
  73988. #endif /* DYNAMIC_CRC_TABLE */
  73989. /* =========================================================================
  73990. * This function can be used by asm versions of crc32()
  73991. */
  73992. const unsigned long FAR * ZEXPORT get_crc_table()
  73993. {
  73994. #ifdef DYNAMIC_CRC_TABLE
  73995. if (crc_table_empty)
  73996. make_crc_table();
  73997. #endif /* DYNAMIC_CRC_TABLE */
  73998. return (const unsigned long FAR *)crc_table;
  73999. }
  74000. /* ========================================================================= */
  74001. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  74002. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  74003. /* ========================================================================= */
  74004. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  74005. {
  74006. if (buf == Z_NULL) return 0UL;
  74007. #ifdef DYNAMIC_CRC_TABLE
  74008. if (crc_table_empty)
  74009. make_crc_table();
  74010. #endif /* DYNAMIC_CRC_TABLE */
  74011. #ifdef BYFOUR
  74012. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  74013. u4 endian;
  74014. endian = 1;
  74015. if (*((unsigned char *)(&endian)))
  74016. return crc32_little(crc, buf, len);
  74017. else
  74018. return crc32_big(crc, buf, len);
  74019. }
  74020. #endif /* BYFOUR */
  74021. crc = crc ^ 0xffffffffUL;
  74022. while (len >= 8) {
  74023. DO8;
  74024. len -= 8;
  74025. }
  74026. if (len) do {
  74027. DO1;
  74028. } while (--len);
  74029. return crc ^ 0xffffffffUL;
  74030. }
  74031. #ifdef BYFOUR
  74032. /* ========================================================================= */
  74033. #define DOLIT4 c ^= *buf4++; \
  74034. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  74035. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  74036. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  74037. /* ========================================================================= */
  74038. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  74039. {
  74040. register u4 c;
  74041. register const u4 FAR *buf4;
  74042. c = (u4)crc;
  74043. c = ~c;
  74044. while (len && ((ptrdiff_t)buf & 3)) {
  74045. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  74046. len--;
  74047. }
  74048. buf4 = (const u4 FAR *)(const void FAR *)buf;
  74049. while (len >= 32) {
  74050. DOLIT32;
  74051. len -= 32;
  74052. }
  74053. while (len >= 4) {
  74054. DOLIT4;
  74055. len -= 4;
  74056. }
  74057. buf = (const unsigned char FAR *)buf4;
  74058. if (len) do {
  74059. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  74060. } while (--len);
  74061. c = ~c;
  74062. return (unsigned long)c;
  74063. }
  74064. /* ========================================================================= */
  74065. #define DOBIG4 c ^= *++buf4; \
  74066. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  74067. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  74068. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  74069. /* ========================================================================= */
  74070. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  74071. {
  74072. register u4 c;
  74073. register const u4 FAR *buf4;
  74074. c = REV((u4)crc);
  74075. c = ~c;
  74076. while (len && ((ptrdiff_t)buf & 3)) {
  74077. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  74078. len--;
  74079. }
  74080. buf4 = (const u4 FAR *)(const void FAR *)buf;
  74081. buf4--;
  74082. while (len >= 32) {
  74083. DOBIG32;
  74084. len -= 32;
  74085. }
  74086. while (len >= 4) {
  74087. DOBIG4;
  74088. len -= 4;
  74089. }
  74090. buf4++;
  74091. buf = (const unsigned char FAR *)buf4;
  74092. if (len) do {
  74093. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  74094. } while (--len);
  74095. c = ~c;
  74096. return (unsigned long)(REV(c));
  74097. }
  74098. #endif /* BYFOUR */
  74099. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  74100. /* ========================================================================= */
  74101. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  74102. {
  74103. unsigned long sum;
  74104. sum = 0;
  74105. while (vec) {
  74106. if (vec & 1)
  74107. sum ^= *mat;
  74108. vec >>= 1;
  74109. mat++;
  74110. }
  74111. return sum;
  74112. }
  74113. /* ========================================================================= */
  74114. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  74115. {
  74116. int n;
  74117. for (n = 0; n < GF2_DIM; n++)
  74118. square[n] = gf2_matrix_times(mat, mat[n]);
  74119. }
  74120. /* ========================================================================= */
  74121. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  74122. {
  74123. int n;
  74124. unsigned long row;
  74125. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  74126. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  74127. /* degenerate case */
  74128. if (len2 == 0)
  74129. return crc1;
  74130. /* put operator for one zero bit in odd */
  74131. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  74132. row = 1;
  74133. for (n = 1; n < GF2_DIM; n++) {
  74134. odd[n] = row;
  74135. row <<= 1;
  74136. }
  74137. /* put operator for two zero bits in even */
  74138. gf2_matrix_square(even, odd);
  74139. /* put operator for four zero bits in odd */
  74140. gf2_matrix_square(odd, even);
  74141. /* apply len2 zeros to crc1 (first square will put the operator for one
  74142. zero byte, eight zero bits, in even) */
  74143. do {
  74144. /* apply zeros operator for this bit of len2 */
  74145. gf2_matrix_square(even, odd);
  74146. if (len2 & 1)
  74147. crc1 = gf2_matrix_times(even, crc1);
  74148. len2 >>= 1;
  74149. /* if no more bits set, then done */
  74150. if (len2 == 0)
  74151. break;
  74152. /* another iteration of the loop with odd and even swapped */
  74153. gf2_matrix_square(odd, even);
  74154. if (len2 & 1)
  74155. crc1 = gf2_matrix_times(odd, crc1);
  74156. len2 >>= 1;
  74157. /* if no more bits set, then done */
  74158. } while (len2 != 0);
  74159. /* return combined crc */
  74160. crc1 ^= crc2;
  74161. return crc1;
  74162. }
  74163. /********* End of inlined file: crc32.c *********/
  74164. /********* Start of inlined file: deflate.c *********/
  74165. /*
  74166. * ALGORITHM
  74167. *
  74168. * The "deflation" process depends on being able to identify portions
  74169. * of the input text which are identical to earlier input (within a
  74170. * sliding window trailing behind the input currently being processed).
  74171. *
  74172. * The most straightforward technique turns out to be the fastest for
  74173. * most input files: try all possible matches and select the longest.
  74174. * The key feature of this algorithm is that insertions into the string
  74175. * dictionary are very simple and thus fast, and deletions are avoided
  74176. * completely. Insertions are performed at each input character, whereas
  74177. * string matches are performed only when the previous match ends. So it
  74178. * is preferable to spend more time in matches to allow very fast string
  74179. * insertions and avoid deletions. The matching algorithm for small
  74180. * strings is inspired from that of Rabin & Karp. A brute force approach
  74181. * is used to find longer strings when a small match has been found.
  74182. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  74183. * (by Leonid Broukhis).
  74184. * A previous version of this file used a more sophisticated algorithm
  74185. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  74186. * time, but has a larger average cost, uses more memory and is patented.
  74187. * However the F&G algorithm may be faster for some highly redundant
  74188. * files if the parameter max_chain_length (described below) is too large.
  74189. *
  74190. * ACKNOWLEDGEMENTS
  74191. *
  74192. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  74193. * I found it in 'freeze' written by Leonid Broukhis.
  74194. * Thanks to many people for bug reports and testing.
  74195. *
  74196. * REFERENCES
  74197. *
  74198. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  74199. * Available in http://www.ietf.org/rfc/rfc1951.txt
  74200. *
  74201. * A description of the Rabin and Karp algorithm is given in the book
  74202. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  74203. *
  74204. * Fiala,E.R., and Greene,D.H.
  74205. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  74206. *
  74207. */
  74208. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74209. /********* Start of inlined file: deflate.h *********/
  74210. /* WARNING: this file should *not* be used by applications. It is
  74211. part of the implementation of the compression library and is
  74212. subject to change. Applications should only use zlib.h.
  74213. */
  74214. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74215. #ifndef DEFLATE_H
  74216. #define DEFLATE_H
  74217. /* define NO_GZIP when compiling if you want to disable gzip header and
  74218. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  74219. the crc code when it is not needed. For shared libraries, gzip encoding
  74220. should be left enabled. */
  74221. #ifndef NO_GZIP
  74222. # define GZIP
  74223. #endif
  74224. #define NO_DUMMY_DECL
  74225. /* ===========================================================================
  74226. * Internal compression state.
  74227. */
  74228. #define LENGTH_CODES 29
  74229. /* number of length codes, not counting the special END_BLOCK code */
  74230. #define LITERALS 256
  74231. /* number of literal bytes 0..255 */
  74232. #define L_CODES (LITERALS+1+LENGTH_CODES)
  74233. /* number of Literal or Length codes, including the END_BLOCK code */
  74234. #define D_CODES 30
  74235. /* number of distance codes */
  74236. #define BL_CODES 19
  74237. /* number of codes used to transfer the bit lengths */
  74238. #define HEAP_SIZE (2*L_CODES+1)
  74239. /* maximum heap size */
  74240. #define MAX_BITS 15
  74241. /* All codes must not exceed MAX_BITS bits */
  74242. #define INIT_STATE 42
  74243. #define EXTRA_STATE 69
  74244. #define NAME_STATE 73
  74245. #define COMMENT_STATE 91
  74246. #define HCRC_STATE 103
  74247. #define BUSY_STATE 113
  74248. #define FINISH_STATE 666
  74249. /* Stream status */
  74250. /* Data structure describing a single value and its code string. */
  74251. typedef struct ct_data_s {
  74252. union {
  74253. ush freq; /* frequency count */
  74254. ush code; /* bit string */
  74255. } fc;
  74256. union {
  74257. ush dad; /* father node in Huffman tree */
  74258. ush len; /* length of bit string */
  74259. } dl;
  74260. } FAR ct_data;
  74261. #define Freq fc.freq
  74262. #define Code fc.code
  74263. #define Dad dl.dad
  74264. #define Len dl.len
  74265. typedef struct static_tree_desc_s static_tree_desc;
  74266. typedef struct tree_desc_s {
  74267. ct_data *dyn_tree; /* the dynamic tree */
  74268. int max_code; /* largest code with non zero frequency */
  74269. static_tree_desc *stat_desc; /* the corresponding static tree */
  74270. } FAR tree_desc;
  74271. typedef ush Pos;
  74272. typedef Pos FAR Posf;
  74273. typedef unsigned IPos;
  74274. /* A Pos is an index in the character window. We use short instead of int to
  74275. * save space in the various tables. IPos is used only for parameter passing.
  74276. */
  74277. typedef struct internal_state {
  74278. z_streamp strm; /* pointer back to this zlib stream */
  74279. int status; /* as the name implies */
  74280. Bytef *pending_buf; /* output still pending */
  74281. ulg pending_buf_size; /* size of pending_buf */
  74282. Bytef *pending_out; /* next pending byte to output to the stream */
  74283. uInt pending; /* nb of bytes in the pending buffer */
  74284. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  74285. gz_headerp gzhead; /* gzip header information to write */
  74286. uInt gzindex; /* where in extra, name, or comment */
  74287. Byte method; /* STORED (for zip only) or DEFLATED */
  74288. int last_flush; /* value of flush param for previous deflate call */
  74289. /* used by deflate.c: */
  74290. uInt w_size; /* LZ77 window size (32K by default) */
  74291. uInt w_bits; /* log2(w_size) (8..16) */
  74292. uInt w_mask; /* w_size - 1 */
  74293. Bytef *window;
  74294. /* Sliding window. Input bytes are read into the second half of the window,
  74295. * and move to the first half later to keep a dictionary of at least wSize
  74296. * bytes. With this organization, matches are limited to a distance of
  74297. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  74298. * performed with a length multiple of the block size. Also, it limits
  74299. * the window size to 64K, which is quite useful on MSDOS.
  74300. * To do: use the user input buffer as sliding window.
  74301. */
  74302. ulg window_size;
  74303. /* Actual size of window: 2*wSize, except when the user input buffer
  74304. * is directly used as sliding window.
  74305. */
  74306. Posf *prev;
  74307. /* Link to older string with same hash index. To limit the size of this
  74308. * array to 64K, this link is maintained only for the last 32K strings.
  74309. * An index in this array is thus a window index modulo 32K.
  74310. */
  74311. Posf *head; /* Heads of the hash chains or NIL. */
  74312. uInt ins_h; /* hash index of string to be inserted */
  74313. uInt hash_size; /* number of elements in hash table */
  74314. uInt hash_bits; /* log2(hash_size) */
  74315. uInt hash_mask; /* hash_size-1 */
  74316. uInt hash_shift;
  74317. /* Number of bits by which ins_h must be shifted at each input
  74318. * step. It must be such that after MIN_MATCH steps, the oldest
  74319. * byte no longer takes part in the hash key, that is:
  74320. * hash_shift * MIN_MATCH >= hash_bits
  74321. */
  74322. long block_start;
  74323. /* Window position at the beginning of the current output block. Gets
  74324. * negative when the window is moved backwards.
  74325. */
  74326. uInt match_length; /* length of best match */
  74327. IPos prev_match; /* previous match */
  74328. int match_available; /* set if previous match exists */
  74329. uInt strstart; /* start of string to insert */
  74330. uInt match_start; /* start of matching string */
  74331. uInt lookahead; /* number of valid bytes ahead in window */
  74332. uInt prev_length;
  74333. /* Length of the best match at previous step. Matches not greater than this
  74334. * are discarded. This is used in the lazy match evaluation.
  74335. */
  74336. uInt max_chain_length;
  74337. /* To speed up deflation, hash chains are never searched beyond this
  74338. * length. A higher limit improves compression ratio but degrades the
  74339. * speed.
  74340. */
  74341. uInt max_lazy_match;
  74342. /* Attempt to find a better match only when the current match is strictly
  74343. * smaller than this value. This mechanism is used only for compression
  74344. * levels >= 4.
  74345. */
  74346. # define max_insert_length max_lazy_match
  74347. /* Insert new strings in the hash table only if the match length is not
  74348. * greater than this length. This saves time but degrades compression.
  74349. * max_insert_length is used only for compression levels <= 3.
  74350. */
  74351. int level; /* compression level (1..9) */
  74352. int strategy; /* favor or force Huffman coding*/
  74353. uInt good_match;
  74354. /* Use a faster search when the previous match is longer than this */
  74355. int nice_match; /* Stop searching when current match exceeds this */
  74356. /* used by trees.c: */
  74357. /* Didn't use ct_data typedef below to supress compiler warning */
  74358. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  74359. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  74360. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  74361. struct tree_desc_s l_desc; /* desc. for literal tree */
  74362. struct tree_desc_s d_desc; /* desc. for distance tree */
  74363. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  74364. ush bl_count[MAX_BITS+1];
  74365. /* number of codes at each bit length for an optimal tree */
  74366. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  74367. int heap_len; /* number of elements in the heap */
  74368. int heap_max; /* element of largest frequency */
  74369. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  74370. * The same heap array is used to build all trees.
  74371. */
  74372. uch depth[2*L_CODES+1];
  74373. /* Depth of each subtree used as tie breaker for trees of equal frequency
  74374. */
  74375. uchf *l_buf; /* buffer for literals or lengths */
  74376. uInt lit_bufsize;
  74377. /* Size of match buffer for literals/lengths. There are 4 reasons for
  74378. * limiting lit_bufsize to 64K:
  74379. * - frequencies can be kept in 16 bit counters
  74380. * - if compression is not successful for the first block, all input
  74381. * data is still in the window so we can still emit a stored block even
  74382. * when input comes from standard input. (This can also be done for
  74383. * all blocks if lit_bufsize is not greater than 32K.)
  74384. * - if compression is not successful for a file smaller than 64K, we can
  74385. * even emit a stored file instead of a stored block (saving 5 bytes).
  74386. * This is applicable only for zip (not gzip or zlib).
  74387. * - creating new Huffman trees less frequently may not provide fast
  74388. * adaptation to changes in the input data statistics. (Take for
  74389. * example a binary file with poorly compressible code followed by
  74390. * a highly compressible string table.) Smaller buffer sizes give
  74391. * fast adaptation but have of course the overhead of transmitting
  74392. * trees more frequently.
  74393. * - I can't count above 4
  74394. */
  74395. uInt last_lit; /* running index in l_buf */
  74396. ushf *d_buf;
  74397. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  74398. * the same number of elements. To use different lengths, an extra flag
  74399. * array would be necessary.
  74400. */
  74401. ulg opt_len; /* bit length of current block with optimal trees */
  74402. ulg static_len; /* bit length of current block with static trees */
  74403. uInt matches; /* number of string matches in current block */
  74404. int last_eob_len; /* bit length of EOB code for last block */
  74405. #ifdef DEBUG
  74406. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  74407. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  74408. #endif
  74409. ush bi_buf;
  74410. /* Output buffer. bits are inserted starting at the bottom (least
  74411. * significant bits).
  74412. */
  74413. int bi_valid;
  74414. /* Number of valid bits in bi_buf. All bits above the last valid bit
  74415. * are always zero.
  74416. */
  74417. } FAR deflate_state;
  74418. /* Output a byte on the stream.
  74419. * IN assertion: there is enough room in pending_buf.
  74420. */
  74421. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  74422. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  74423. /* Minimum amount of lookahead, except at the end of the input file.
  74424. * See deflate.c for comments about the MIN_MATCH+1.
  74425. */
  74426. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  74427. /* In order to simplify the code, particularly on 16 bit machines, match
  74428. * distances are limited to MAX_DIST instead of WSIZE.
  74429. */
  74430. /* in trees.c */
  74431. void _tr_init OF((deflate_state *s));
  74432. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  74433. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  74434. int eof));
  74435. void _tr_align OF((deflate_state *s));
  74436. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  74437. int eof));
  74438. #define d_code(dist) \
  74439. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  74440. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  74441. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  74442. * used.
  74443. */
  74444. #ifndef DEBUG
  74445. /* Inline versions of _tr_tally for speed: */
  74446. #if defined(GEN_TREES_H) || !defined(STDC)
  74447. extern uch _length_code[];
  74448. extern uch _dist_code[];
  74449. #else
  74450. extern const uch _length_code[];
  74451. extern const uch _dist_code[];
  74452. #endif
  74453. # define _tr_tally_lit(s, c, flush) \
  74454. { uch cc = (c); \
  74455. s->d_buf[s->last_lit] = 0; \
  74456. s->l_buf[s->last_lit++] = cc; \
  74457. s->dyn_ltree[cc].Freq++; \
  74458. flush = (s->last_lit == s->lit_bufsize-1); \
  74459. }
  74460. # define _tr_tally_dist(s, distance, length, flush) \
  74461. { uch len = (length); \
  74462. ush dist = (distance); \
  74463. s->d_buf[s->last_lit] = dist; \
  74464. s->l_buf[s->last_lit++] = len; \
  74465. dist--; \
  74466. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  74467. s->dyn_dtree[d_code(dist)].Freq++; \
  74468. flush = (s->last_lit == s->lit_bufsize-1); \
  74469. }
  74470. #else
  74471. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  74472. # define _tr_tally_dist(s, distance, length, flush) \
  74473. flush = _tr_tally(s, distance, length)
  74474. #endif
  74475. #endif /* DEFLATE_H */
  74476. /********* End of inlined file: deflate.h *********/
  74477. const char deflate_copyright[] =
  74478. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  74479. /*
  74480. If you use the zlib library in a product, an acknowledgment is welcome
  74481. in the documentation of your product. If for some reason you cannot
  74482. include such an acknowledgment, I would appreciate that you keep this
  74483. copyright string in the executable of your product.
  74484. */
  74485. /* ===========================================================================
  74486. * Function prototypes.
  74487. */
  74488. typedef enum {
  74489. need_more, /* block not completed, need more input or more output */
  74490. block_done, /* block flush performed */
  74491. finish_started, /* finish started, need only more output at next deflate */
  74492. finish_done /* finish done, accept no more input or output */
  74493. } block_state;
  74494. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  74495. /* Compression function. Returns the block state after the call. */
  74496. local void fill_window OF((deflate_state *s));
  74497. local block_state deflate_stored OF((deflate_state *s, int flush));
  74498. local block_state deflate_fast OF((deflate_state *s, int flush));
  74499. #ifndef FASTEST
  74500. local block_state deflate_slow OF((deflate_state *s, int flush));
  74501. #endif
  74502. local void lm_init OF((deflate_state *s));
  74503. local void putShortMSB OF((deflate_state *s, uInt b));
  74504. local void flush_pending OF((z_streamp strm));
  74505. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  74506. #ifndef FASTEST
  74507. #ifdef ASMV
  74508. void match_init OF((void)); /* asm code initialization */
  74509. uInt longest_match OF((deflate_state *s, IPos cur_match));
  74510. #else
  74511. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  74512. #endif
  74513. #endif
  74514. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  74515. #ifdef DEBUG
  74516. local void check_match OF((deflate_state *s, IPos start, IPos match,
  74517. int length));
  74518. #endif
  74519. /* ===========================================================================
  74520. * Local data
  74521. */
  74522. #define NIL 0
  74523. /* Tail of hash chains */
  74524. #ifndef TOO_FAR
  74525. # define TOO_FAR 4096
  74526. #endif
  74527. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  74528. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  74529. /* Minimum amount of lookahead, except at the end of the input file.
  74530. * See deflate.c for comments about the MIN_MATCH+1.
  74531. */
  74532. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  74533. * the desired pack level (0..9). The values given below have been tuned to
  74534. * exclude worst case performance for pathological files. Better values may be
  74535. * found for specific files.
  74536. */
  74537. typedef struct config_s {
  74538. ush good_length; /* reduce lazy search above this match length */
  74539. ush max_lazy; /* do not perform lazy search above this match length */
  74540. ush nice_length; /* quit search above this match length */
  74541. ush max_chain;
  74542. compress_func func;
  74543. } config;
  74544. #ifdef FASTEST
  74545. local const config configuration_table[2] = {
  74546. /* good lazy nice chain */
  74547. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  74548. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  74549. #else
  74550. local const config configuration_table[10] = {
  74551. /* good lazy nice chain */
  74552. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  74553. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  74554. /* 2 */ {4, 5, 16, 8, deflate_fast},
  74555. /* 3 */ {4, 6, 32, 32, deflate_fast},
  74556. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  74557. /* 5 */ {8, 16, 32, 32, deflate_slow},
  74558. /* 6 */ {8, 16, 128, 128, deflate_slow},
  74559. /* 7 */ {8, 32, 128, 256, deflate_slow},
  74560. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  74561. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  74562. #endif
  74563. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  74564. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  74565. * meaning.
  74566. */
  74567. #define EQUAL 0
  74568. /* result of memcmp for equal strings */
  74569. #ifndef NO_DUMMY_DECL
  74570. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  74571. #endif
  74572. /* ===========================================================================
  74573. * Update a hash value with the given input byte
  74574. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  74575. * input characters, so that a running hash key can be computed from the
  74576. * previous key instead of complete recalculation each time.
  74577. */
  74578. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  74579. /* ===========================================================================
  74580. * Insert string str in the dictionary and set match_head to the previous head
  74581. * of the hash chain (the most recent string with same hash key). Return
  74582. * the previous length of the hash chain.
  74583. * If this file is compiled with -DFASTEST, the compression level is forced
  74584. * to 1, and no hash chains are maintained.
  74585. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  74586. * input characters and the first MIN_MATCH bytes of str are valid
  74587. * (except for the last MIN_MATCH-1 bytes of the input file).
  74588. */
  74589. #ifdef FASTEST
  74590. #define INSERT_STRING(s, str, match_head) \
  74591. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  74592. match_head = s->head[s->ins_h], \
  74593. s->head[s->ins_h] = (Pos)(str))
  74594. #else
  74595. #define INSERT_STRING(s, str, match_head) \
  74596. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  74597. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  74598. s->head[s->ins_h] = (Pos)(str))
  74599. #endif
  74600. /* ===========================================================================
  74601. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  74602. * prev[] will be initialized on the fly.
  74603. */
  74604. #define CLEAR_HASH(s) \
  74605. s->head[s->hash_size-1] = NIL; \
  74606. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  74607. /* ========================================================================= */
  74608. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  74609. {
  74610. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  74611. Z_DEFAULT_STRATEGY, version, stream_size);
  74612. /* To do: ignore strm->next_in if we use it as window */
  74613. }
  74614. /* ========================================================================= */
  74615. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  74616. {
  74617. deflate_state *s;
  74618. int wrap = 1;
  74619. static const char my_version[] = ZLIB_VERSION;
  74620. ushf *overlay;
  74621. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  74622. * output size for (length,distance) codes is <= 24 bits.
  74623. */
  74624. if (version == Z_NULL || version[0] != my_version[0] ||
  74625. stream_size != sizeof(z_stream)) {
  74626. return Z_VERSION_ERROR;
  74627. }
  74628. if (strm == Z_NULL) return Z_STREAM_ERROR;
  74629. strm->msg = Z_NULL;
  74630. if (strm->zalloc == (alloc_func)0) {
  74631. strm->zalloc = zcalloc;
  74632. strm->opaque = (voidpf)0;
  74633. }
  74634. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  74635. #ifdef FASTEST
  74636. if (level != 0) level = 1;
  74637. #else
  74638. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  74639. #endif
  74640. if (windowBits < 0) { /* suppress zlib wrapper */
  74641. wrap = 0;
  74642. windowBits = -windowBits;
  74643. }
  74644. #ifdef GZIP
  74645. else if (windowBits > 15) {
  74646. wrap = 2; /* write gzip wrapper instead */
  74647. windowBits -= 16;
  74648. }
  74649. #endif
  74650. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  74651. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  74652. strategy < 0 || strategy > Z_FIXED) {
  74653. return Z_STREAM_ERROR;
  74654. }
  74655. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  74656. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  74657. if (s == Z_NULL) return Z_MEM_ERROR;
  74658. strm->state = (struct internal_state FAR *)s;
  74659. s->strm = strm;
  74660. s->wrap = wrap;
  74661. s->gzhead = Z_NULL;
  74662. s->w_bits = windowBits;
  74663. s->w_size = 1 << s->w_bits;
  74664. s->w_mask = s->w_size - 1;
  74665. s->hash_bits = memLevel + 7;
  74666. s->hash_size = 1 << s->hash_bits;
  74667. s->hash_mask = s->hash_size - 1;
  74668. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  74669. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  74670. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  74671. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  74672. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  74673. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  74674. s->pending_buf = (uchf *) overlay;
  74675. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  74676. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  74677. s->pending_buf == Z_NULL) {
  74678. s->status = FINISH_STATE;
  74679. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  74680. deflateEnd (strm);
  74681. return Z_MEM_ERROR;
  74682. }
  74683. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  74684. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  74685. s->level = level;
  74686. s->strategy = strategy;
  74687. s->method = (Byte)method;
  74688. return deflateReset(strm);
  74689. }
  74690. /* ========================================================================= */
  74691. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  74692. {
  74693. deflate_state *s;
  74694. uInt length = dictLength;
  74695. uInt n;
  74696. IPos hash_head = 0;
  74697. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  74698. strm->state->wrap == 2 ||
  74699. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  74700. return Z_STREAM_ERROR;
  74701. s = strm->state;
  74702. if (s->wrap)
  74703. strm->adler = adler32(strm->adler, dictionary, dictLength);
  74704. if (length < MIN_MATCH) return Z_OK;
  74705. if (length > MAX_DIST(s)) {
  74706. length = MAX_DIST(s);
  74707. dictionary += dictLength - length; /* use the tail of the dictionary */
  74708. }
  74709. zmemcpy(s->window, dictionary, length);
  74710. s->strstart = length;
  74711. s->block_start = (long)length;
  74712. /* Insert all strings in the hash table (except for the last two bytes).
  74713. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  74714. * call of fill_window.
  74715. */
  74716. s->ins_h = s->window[0];
  74717. UPDATE_HASH(s, s->ins_h, s->window[1]);
  74718. for (n = 0; n <= length - MIN_MATCH; n++) {
  74719. INSERT_STRING(s, n, hash_head);
  74720. }
  74721. if (hash_head) hash_head = 0; /* to make compiler happy */
  74722. return Z_OK;
  74723. }
  74724. /* ========================================================================= */
  74725. int ZEXPORT deflateReset (z_streamp strm)
  74726. {
  74727. deflate_state *s;
  74728. if (strm == Z_NULL || strm->state == Z_NULL ||
  74729. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  74730. return Z_STREAM_ERROR;
  74731. }
  74732. strm->total_in = strm->total_out = 0;
  74733. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  74734. strm->data_type = Z_UNKNOWN;
  74735. s = (deflate_state *)strm->state;
  74736. s->pending = 0;
  74737. s->pending_out = s->pending_buf;
  74738. if (s->wrap < 0) {
  74739. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  74740. }
  74741. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  74742. strm->adler =
  74743. #ifdef GZIP
  74744. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  74745. #endif
  74746. adler32(0L, Z_NULL, 0);
  74747. s->last_flush = Z_NO_FLUSH;
  74748. _tr_init(s);
  74749. lm_init(s);
  74750. return Z_OK;
  74751. }
  74752. /* ========================================================================= */
  74753. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  74754. {
  74755. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74756. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  74757. strm->state->gzhead = head;
  74758. return Z_OK;
  74759. }
  74760. /* ========================================================================= */
  74761. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  74762. {
  74763. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74764. strm->state->bi_valid = bits;
  74765. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  74766. return Z_OK;
  74767. }
  74768. /* ========================================================================= */
  74769. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  74770. {
  74771. deflate_state *s;
  74772. compress_func func;
  74773. int err = Z_OK;
  74774. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74775. s = strm->state;
  74776. #ifdef FASTEST
  74777. if (level != 0) level = 1;
  74778. #else
  74779. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  74780. #endif
  74781. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  74782. return Z_STREAM_ERROR;
  74783. }
  74784. func = configuration_table[s->level].func;
  74785. if (func != configuration_table[level].func && strm->total_in != 0) {
  74786. /* Flush the last buffer: */
  74787. err = deflate(strm, Z_PARTIAL_FLUSH);
  74788. }
  74789. if (s->level != level) {
  74790. s->level = level;
  74791. s->max_lazy_match = configuration_table[level].max_lazy;
  74792. s->good_match = configuration_table[level].good_length;
  74793. s->nice_match = configuration_table[level].nice_length;
  74794. s->max_chain_length = configuration_table[level].max_chain;
  74795. }
  74796. s->strategy = strategy;
  74797. return err;
  74798. }
  74799. /* ========================================================================= */
  74800. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  74801. {
  74802. deflate_state *s;
  74803. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74804. s = strm->state;
  74805. s->good_match = good_length;
  74806. s->max_lazy_match = max_lazy;
  74807. s->nice_match = nice_length;
  74808. s->max_chain_length = max_chain;
  74809. return Z_OK;
  74810. }
  74811. /* =========================================================================
  74812. * For the default windowBits of 15 and memLevel of 8, this function returns
  74813. * a close to exact, as well as small, upper bound on the compressed size.
  74814. * They are coded as constants here for a reason--if the #define's are
  74815. * changed, then this function needs to be changed as well. The return
  74816. * value for 15 and 8 only works for those exact settings.
  74817. *
  74818. * For any setting other than those defaults for windowBits and memLevel,
  74819. * the value returned is a conservative worst case for the maximum expansion
  74820. * resulting from using fixed blocks instead of stored blocks, which deflate
  74821. * can emit on compressed data for some combinations of the parameters.
  74822. *
  74823. * This function could be more sophisticated to provide closer upper bounds
  74824. * for every combination of windowBits and memLevel, as well as wrap.
  74825. * But even the conservative upper bound of about 14% expansion does not
  74826. * seem onerous for output buffer allocation.
  74827. */
  74828. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  74829. {
  74830. deflate_state *s;
  74831. uLong destLen;
  74832. /* conservative upper bound */
  74833. destLen = sourceLen +
  74834. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  74835. /* if can't get parameters, return conservative bound */
  74836. if (strm == Z_NULL || strm->state == Z_NULL)
  74837. return destLen;
  74838. /* if not default parameters, return conservative bound */
  74839. s = strm->state;
  74840. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  74841. return destLen;
  74842. /* default settings: return tight bound for that case */
  74843. return compressBound(sourceLen);
  74844. }
  74845. /* =========================================================================
  74846. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  74847. * IN assertion: the stream state is correct and there is enough room in
  74848. * pending_buf.
  74849. */
  74850. local void putShortMSB (deflate_state *s, uInt b)
  74851. {
  74852. put_byte(s, (Byte)(b >> 8));
  74853. put_byte(s, (Byte)(b & 0xff));
  74854. }
  74855. /* =========================================================================
  74856. * Flush as much pending output as possible. All deflate() output goes
  74857. * through this function so some applications may wish to modify it
  74858. * to avoid allocating a large strm->next_out buffer and copying into it.
  74859. * (See also read_buf()).
  74860. */
  74861. local void flush_pending (z_streamp strm)
  74862. {
  74863. unsigned len = strm->state->pending;
  74864. if (len > strm->avail_out) len = strm->avail_out;
  74865. if (len == 0) return;
  74866. zmemcpy(strm->next_out, strm->state->pending_out, len);
  74867. strm->next_out += len;
  74868. strm->state->pending_out += len;
  74869. strm->total_out += len;
  74870. strm->avail_out -= len;
  74871. strm->state->pending -= len;
  74872. if (strm->state->pending == 0) {
  74873. strm->state->pending_out = strm->state->pending_buf;
  74874. }
  74875. }
  74876. /* ========================================================================= */
  74877. int ZEXPORT deflate (z_streamp strm, int flush)
  74878. {
  74879. int old_flush; /* value of flush param for previous deflate call */
  74880. deflate_state *s;
  74881. if (strm == Z_NULL || strm->state == Z_NULL ||
  74882. flush > Z_FINISH || flush < 0) {
  74883. return Z_STREAM_ERROR;
  74884. }
  74885. s = strm->state;
  74886. if (strm->next_out == Z_NULL ||
  74887. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  74888. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  74889. ERR_RETURN(strm, Z_STREAM_ERROR);
  74890. }
  74891. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  74892. s->strm = strm; /* just in case */
  74893. old_flush = s->last_flush;
  74894. s->last_flush = flush;
  74895. /* Write the header */
  74896. if (s->status == INIT_STATE) {
  74897. #ifdef GZIP
  74898. if (s->wrap == 2) {
  74899. strm->adler = crc32(0L, Z_NULL, 0);
  74900. put_byte(s, 31);
  74901. put_byte(s, 139);
  74902. put_byte(s, 8);
  74903. if (s->gzhead == NULL) {
  74904. put_byte(s, 0);
  74905. put_byte(s, 0);
  74906. put_byte(s, 0);
  74907. put_byte(s, 0);
  74908. put_byte(s, 0);
  74909. put_byte(s, s->level == 9 ? 2 :
  74910. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  74911. 4 : 0));
  74912. put_byte(s, OS_CODE);
  74913. s->status = BUSY_STATE;
  74914. }
  74915. else {
  74916. put_byte(s, (s->gzhead->text ? 1 : 0) +
  74917. (s->gzhead->hcrc ? 2 : 0) +
  74918. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  74919. (s->gzhead->name == Z_NULL ? 0 : 8) +
  74920. (s->gzhead->comment == Z_NULL ? 0 : 16)
  74921. );
  74922. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  74923. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  74924. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  74925. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  74926. put_byte(s, s->level == 9 ? 2 :
  74927. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  74928. 4 : 0));
  74929. put_byte(s, s->gzhead->os & 0xff);
  74930. if (s->gzhead->extra != NULL) {
  74931. put_byte(s, s->gzhead->extra_len & 0xff);
  74932. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  74933. }
  74934. if (s->gzhead->hcrc)
  74935. strm->adler = crc32(strm->adler, s->pending_buf,
  74936. s->pending);
  74937. s->gzindex = 0;
  74938. s->status = EXTRA_STATE;
  74939. }
  74940. }
  74941. else
  74942. #endif
  74943. {
  74944. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  74945. uInt level_flags;
  74946. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  74947. level_flags = 0;
  74948. else if (s->level < 6)
  74949. level_flags = 1;
  74950. else if (s->level == 6)
  74951. level_flags = 2;
  74952. else
  74953. level_flags = 3;
  74954. header |= (level_flags << 6);
  74955. if (s->strstart != 0) header |= PRESET_DICT;
  74956. header += 31 - (header % 31);
  74957. s->status = BUSY_STATE;
  74958. putShortMSB(s, header);
  74959. /* Save the adler32 of the preset dictionary: */
  74960. if (s->strstart != 0) {
  74961. putShortMSB(s, (uInt)(strm->adler >> 16));
  74962. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  74963. }
  74964. strm->adler = adler32(0L, Z_NULL, 0);
  74965. }
  74966. }
  74967. #ifdef GZIP
  74968. if (s->status == EXTRA_STATE) {
  74969. if (s->gzhead->extra != NULL) {
  74970. uInt beg = s->pending; /* start of bytes to update crc */
  74971. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  74972. if (s->pending == s->pending_buf_size) {
  74973. if (s->gzhead->hcrc && s->pending > beg)
  74974. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  74975. s->pending - beg);
  74976. flush_pending(strm);
  74977. beg = s->pending;
  74978. if (s->pending == s->pending_buf_size)
  74979. break;
  74980. }
  74981. put_byte(s, s->gzhead->extra[s->gzindex]);
  74982. s->gzindex++;
  74983. }
  74984. if (s->gzhead->hcrc && s->pending > beg)
  74985. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  74986. s->pending - beg);
  74987. if (s->gzindex == s->gzhead->extra_len) {
  74988. s->gzindex = 0;
  74989. s->status = NAME_STATE;
  74990. }
  74991. }
  74992. else
  74993. s->status = NAME_STATE;
  74994. }
  74995. if (s->status == NAME_STATE) {
  74996. if (s->gzhead->name != NULL) {
  74997. uInt beg = s->pending; /* start of bytes to update crc */
  74998. int val;
  74999. do {
  75000. if (s->pending == s->pending_buf_size) {
  75001. if (s->gzhead->hcrc && s->pending > beg)
  75002. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75003. s->pending - beg);
  75004. flush_pending(strm);
  75005. beg = s->pending;
  75006. if (s->pending == s->pending_buf_size) {
  75007. val = 1;
  75008. break;
  75009. }
  75010. }
  75011. val = s->gzhead->name[s->gzindex++];
  75012. put_byte(s, val);
  75013. } while (val != 0);
  75014. if (s->gzhead->hcrc && s->pending > beg)
  75015. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75016. s->pending - beg);
  75017. if (val == 0) {
  75018. s->gzindex = 0;
  75019. s->status = COMMENT_STATE;
  75020. }
  75021. }
  75022. else
  75023. s->status = COMMENT_STATE;
  75024. }
  75025. if (s->status == COMMENT_STATE) {
  75026. if (s->gzhead->comment != NULL) {
  75027. uInt beg = s->pending; /* start of bytes to update crc */
  75028. int val;
  75029. do {
  75030. if (s->pending == s->pending_buf_size) {
  75031. if (s->gzhead->hcrc && s->pending > beg)
  75032. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75033. s->pending - beg);
  75034. flush_pending(strm);
  75035. beg = s->pending;
  75036. if (s->pending == s->pending_buf_size) {
  75037. val = 1;
  75038. break;
  75039. }
  75040. }
  75041. val = s->gzhead->comment[s->gzindex++];
  75042. put_byte(s, val);
  75043. } while (val != 0);
  75044. if (s->gzhead->hcrc && s->pending > beg)
  75045. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75046. s->pending - beg);
  75047. if (val == 0)
  75048. s->status = HCRC_STATE;
  75049. }
  75050. else
  75051. s->status = HCRC_STATE;
  75052. }
  75053. if (s->status == HCRC_STATE) {
  75054. if (s->gzhead->hcrc) {
  75055. if (s->pending + 2 > s->pending_buf_size)
  75056. flush_pending(strm);
  75057. if (s->pending + 2 <= s->pending_buf_size) {
  75058. put_byte(s, (Byte)(strm->adler & 0xff));
  75059. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  75060. strm->adler = crc32(0L, Z_NULL, 0);
  75061. s->status = BUSY_STATE;
  75062. }
  75063. }
  75064. else
  75065. s->status = BUSY_STATE;
  75066. }
  75067. #endif
  75068. /* Flush as much pending output as possible */
  75069. if (s->pending != 0) {
  75070. flush_pending(strm);
  75071. if (strm->avail_out == 0) {
  75072. /* Since avail_out is 0, deflate will be called again with
  75073. * more output space, but possibly with both pending and
  75074. * avail_in equal to zero. There won't be anything to do,
  75075. * but this is not an error situation so make sure we
  75076. * return OK instead of BUF_ERROR at next call of deflate:
  75077. */
  75078. s->last_flush = -1;
  75079. return Z_OK;
  75080. }
  75081. /* Make sure there is something to do and avoid duplicate consecutive
  75082. * flushes. For repeated and useless calls with Z_FINISH, we keep
  75083. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  75084. */
  75085. } else if (strm->avail_in == 0 && flush <= old_flush &&
  75086. flush != Z_FINISH) {
  75087. ERR_RETURN(strm, Z_BUF_ERROR);
  75088. }
  75089. /* User must not provide more input after the first FINISH: */
  75090. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  75091. ERR_RETURN(strm, Z_BUF_ERROR);
  75092. }
  75093. /* Start a new block or continue the current one.
  75094. */
  75095. if (strm->avail_in != 0 || s->lookahead != 0 ||
  75096. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  75097. block_state bstate;
  75098. bstate = (*(configuration_table[s->level].func))(s, flush);
  75099. if (bstate == finish_started || bstate == finish_done) {
  75100. s->status = FINISH_STATE;
  75101. }
  75102. if (bstate == need_more || bstate == finish_started) {
  75103. if (strm->avail_out == 0) {
  75104. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  75105. }
  75106. return Z_OK;
  75107. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  75108. * of deflate should use the same flush parameter to make sure
  75109. * that the flush is complete. So we don't have to output an
  75110. * empty block here, this will be done at next call. This also
  75111. * ensures that for a very small output buffer, we emit at most
  75112. * one empty block.
  75113. */
  75114. }
  75115. if (bstate == block_done) {
  75116. if (flush == Z_PARTIAL_FLUSH) {
  75117. _tr_align(s);
  75118. } else { /* FULL_FLUSH or SYNC_FLUSH */
  75119. _tr_stored_block(s, (char*)0, 0L, 0);
  75120. /* For a full flush, this empty block will be recognized
  75121. * as a special marker by inflate_sync().
  75122. */
  75123. if (flush == Z_FULL_FLUSH) {
  75124. CLEAR_HASH(s); /* forget history */
  75125. }
  75126. }
  75127. flush_pending(strm);
  75128. if (strm->avail_out == 0) {
  75129. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  75130. return Z_OK;
  75131. }
  75132. }
  75133. }
  75134. Assert(strm->avail_out > 0, "bug2");
  75135. if (flush != Z_FINISH) return Z_OK;
  75136. if (s->wrap <= 0) return Z_STREAM_END;
  75137. /* Write the trailer */
  75138. #ifdef GZIP
  75139. if (s->wrap == 2) {
  75140. put_byte(s, (Byte)(strm->adler & 0xff));
  75141. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  75142. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  75143. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  75144. put_byte(s, (Byte)(strm->total_in & 0xff));
  75145. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  75146. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  75147. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  75148. }
  75149. else
  75150. #endif
  75151. {
  75152. putShortMSB(s, (uInt)(strm->adler >> 16));
  75153. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  75154. }
  75155. flush_pending(strm);
  75156. /* If avail_out is zero, the application will call deflate again
  75157. * to flush the rest.
  75158. */
  75159. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  75160. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  75161. }
  75162. /* ========================================================================= */
  75163. int ZEXPORT deflateEnd (z_streamp strm)
  75164. {
  75165. int status;
  75166. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  75167. status = strm->state->status;
  75168. if (status != INIT_STATE &&
  75169. status != EXTRA_STATE &&
  75170. status != NAME_STATE &&
  75171. status != COMMENT_STATE &&
  75172. status != HCRC_STATE &&
  75173. status != BUSY_STATE &&
  75174. status != FINISH_STATE) {
  75175. return Z_STREAM_ERROR;
  75176. }
  75177. /* Deallocate in reverse order of allocations: */
  75178. TRY_FREE(strm, strm->state->pending_buf);
  75179. TRY_FREE(strm, strm->state->head);
  75180. TRY_FREE(strm, strm->state->prev);
  75181. TRY_FREE(strm, strm->state->window);
  75182. ZFREE(strm, strm->state);
  75183. strm->state = Z_NULL;
  75184. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  75185. }
  75186. /* =========================================================================
  75187. * Copy the source state to the destination state.
  75188. * To simplify the source, this is not supported for 16-bit MSDOS (which
  75189. * doesn't have enough memory anyway to duplicate compression states).
  75190. */
  75191. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  75192. {
  75193. #ifdef MAXSEG_64K
  75194. return Z_STREAM_ERROR;
  75195. #else
  75196. deflate_state *ds;
  75197. deflate_state *ss;
  75198. ushf *overlay;
  75199. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  75200. return Z_STREAM_ERROR;
  75201. }
  75202. ss = source->state;
  75203. zmemcpy(dest, source, sizeof(z_stream));
  75204. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  75205. if (ds == Z_NULL) return Z_MEM_ERROR;
  75206. dest->state = (struct internal_state FAR *) ds;
  75207. zmemcpy(ds, ss, sizeof(deflate_state));
  75208. ds->strm = dest;
  75209. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  75210. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  75211. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  75212. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  75213. ds->pending_buf = (uchf *) overlay;
  75214. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  75215. ds->pending_buf == Z_NULL) {
  75216. deflateEnd (dest);
  75217. return Z_MEM_ERROR;
  75218. }
  75219. /* following zmemcpy do not work for 16-bit MSDOS */
  75220. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  75221. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  75222. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  75223. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  75224. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  75225. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  75226. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  75227. ds->l_desc.dyn_tree = ds->dyn_ltree;
  75228. ds->d_desc.dyn_tree = ds->dyn_dtree;
  75229. ds->bl_desc.dyn_tree = ds->bl_tree;
  75230. return Z_OK;
  75231. #endif /* MAXSEG_64K */
  75232. }
  75233. /* ===========================================================================
  75234. * Read a new buffer from the current input stream, update the adler32
  75235. * and total number of bytes read. All deflate() input goes through
  75236. * this function so some applications may wish to modify it to avoid
  75237. * allocating a large strm->next_in buffer and copying from it.
  75238. * (See also flush_pending()).
  75239. */
  75240. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  75241. {
  75242. unsigned len = strm->avail_in;
  75243. if (len > size) len = size;
  75244. if (len == 0) return 0;
  75245. strm->avail_in -= len;
  75246. if (strm->state->wrap == 1) {
  75247. strm->adler = adler32(strm->adler, strm->next_in, len);
  75248. }
  75249. #ifdef GZIP
  75250. else if (strm->state->wrap == 2) {
  75251. strm->adler = crc32(strm->adler, strm->next_in, len);
  75252. }
  75253. #endif
  75254. zmemcpy(buf, strm->next_in, len);
  75255. strm->next_in += len;
  75256. strm->total_in += len;
  75257. return (int)len;
  75258. }
  75259. /* ===========================================================================
  75260. * Initialize the "longest match" routines for a new zlib stream
  75261. */
  75262. local void lm_init (deflate_state *s)
  75263. {
  75264. s->window_size = (ulg)2L*s->w_size;
  75265. CLEAR_HASH(s);
  75266. /* Set the default configuration parameters:
  75267. */
  75268. s->max_lazy_match = configuration_table[s->level].max_lazy;
  75269. s->good_match = configuration_table[s->level].good_length;
  75270. s->nice_match = configuration_table[s->level].nice_length;
  75271. s->max_chain_length = configuration_table[s->level].max_chain;
  75272. s->strstart = 0;
  75273. s->block_start = 0L;
  75274. s->lookahead = 0;
  75275. s->match_length = s->prev_length = MIN_MATCH-1;
  75276. s->match_available = 0;
  75277. s->ins_h = 0;
  75278. #ifndef FASTEST
  75279. #ifdef ASMV
  75280. match_init(); /* initialize the asm code */
  75281. #endif
  75282. #endif
  75283. }
  75284. #ifndef FASTEST
  75285. /* ===========================================================================
  75286. * Set match_start to the longest match starting at the given string and
  75287. * return its length. Matches shorter or equal to prev_length are discarded,
  75288. * in which case the result is equal to prev_length and match_start is
  75289. * garbage.
  75290. * IN assertions: cur_match is the head of the hash chain for the current
  75291. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  75292. * OUT assertion: the match length is not greater than s->lookahead.
  75293. */
  75294. #ifndef ASMV
  75295. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  75296. * match.S. The code will be functionally equivalent.
  75297. */
  75298. local uInt longest_match(deflate_state *s, IPos cur_match)
  75299. {
  75300. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  75301. register Bytef *scan = s->window + s->strstart; /* current string */
  75302. register Bytef *match; /* matched string */
  75303. register int len; /* length of current match */
  75304. int best_len = s->prev_length; /* best match length so far */
  75305. int nice_match = s->nice_match; /* stop if match long enough */
  75306. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  75307. s->strstart - (IPos)MAX_DIST(s) : NIL;
  75308. /* Stop when cur_match becomes <= limit. To simplify the code,
  75309. * we prevent matches with the string of window index 0.
  75310. */
  75311. Posf *prev = s->prev;
  75312. uInt wmask = s->w_mask;
  75313. #ifdef UNALIGNED_OK
  75314. /* Compare two bytes at a time. Note: this is not always beneficial.
  75315. * Try with and without -DUNALIGNED_OK to check.
  75316. */
  75317. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  75318. register ush scan_start = *(ushf*)scan;
  75319. register ush scan_end = *(ushf*)(scan+best_len-1);
  75320. #else
  75321. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  75322. register Byte scan_end1 = scan[best_len-1];
  75323. register Byte scan_end = scan[best_len];
  75324. #endif
  75325. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  75326. * It is easy to get rid of this optimization if necessary.
  75327. */
  75328. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  75329. /* Do not waste too much time if we already have a good match: */
  75330. if (s->prev_length >= s->good_match) {
  75331. chain_length >>= 2;
  75332. }
  75333. /* Do not look for matches beyond the end of the input. This is necessary
  75334. * to make deflate deterministic.
  75335. */
  75336. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  75337. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  75338. do {
  75339. Assert(cur_match < s->strstart, "no future");
  75340. match = s->window + cur_match;
  75341. /* Skip to next match if the match length cannot increase
  75342. * or if the match length is less than 2. Note that the checks below
  75343. * for insufficient lookahead only occur occasionally for performance
  75344. * reasons. Therefore uninitialized memory will be accessed, and
  75345. * conditional jumps will be made that depend on those values.
  75346. * However the length of the match is limited to the lookahead, so
  75347. * the output of deflate is not affected by the uninitialized values.
  75348. */
  75349. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  75350. /* This code assumes sizeof(unsigned short) == 2. Do not use
  75351. * UNALIGNED_OK if your compiler uses a different size.
  75352. */
  75353. if (*(ushf*)(match+best_len-1) != scan_end ||
  75354. *(ushf*)match != scan_start) continue;
  75355. /* It is not necessary to compare scan[2] and match[2] since they are
  75356. * always equal when the other bytes match, given that the hash keys
  75357. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  75358. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  75359. * lookahead only every 4th comparison; the 128th check will be made
  75360. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  75361. * necessary to put more guard bytes at the end of the window, or
  75362. * to check more often for insufficient lookahead.
  75363. */
  75364. Assert(scan[2] == match[2], "scan[2]?");
  75365. scan++, match++;
  75366. do {
  75367. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  75368. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  75369. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  75370. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  75371. scan < strend);
  75372. /* The funny "do {}" generates better code on most compilers */
  75373. /* Here, scan <= window+strstart+257 */
  75374. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  75375. if (*scan == *match) scan++;
  75376. len = (MAX_MATCH - 1) - (int)(strend-scan);
  75377. scan = strend - (MAX_MATCH-1);
  75378. #else /* UNALIGNED_OK */
  75379. if (match[best_len] != scan_end ||
  75380. match[best_len-1] != scan_end1 ||
  75381. *match != *scan ||
  75382. *++match != scan[1]) continue;
  75383. /* The check at best_len-1 can be removed because it will be made
  75384. * again later. (This heuristic is not always a win.)
  75385. * It is not necessary to compare scan[2] and match[2] since they
  75386. * are always equal when the other bytes match, given that
  75387. * the hash keys are equal and that HASH_BITS >= 8.
  75388. */
  75389. scan += 2, match++;
  75390. Assert(*scan == *match, "match[2]?");
  75391. /* We check for insufficient lookahead only every 8th comparison;
  75392. * the 256th check will be made at strstart+258.
  75393. */
  75394. do {
  75395. } while (*++scan == *++match && *++scan == *++match &&
  75396. *++scan == *++match && *++scan == *++match &&
  75397. *++scan == *++match && *++scan == *++match &&
  75398. *++scan == *++match && *++scan == *++match &&
  75399. scan < strend);
  75400. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  75401. len = MAX_MATCH - (int)(strend - scan);
  75402. scan = strend - MAX_MATCH;
  75403. #endif /* UNALIGNED_OK */
  75404. if (len > best_len) {
  75405. s->match_start = cur_match;
  75406. best_len = len;
  75407. if (len >= nice_match) break;
  75408. #ifdef UNALIGNED_OK
  75409. scan_end = *(ushf*)(scan+best_len-1);
  75410. #else
  75411. scan_end1 = scan[best_len-1];
  75412. scan_end = scan[best_len];
  75413. #endif
  75414. }
  75415. } while ((cur_match = prev[cur_match & wmask]) > limit
  75416. && --chain_length != 0);
  75417. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  75418. return s->lookahead;
  75419. }
  75420. #endif /* ASMV */
  75421. #endif /* FASTEST */
  75422. /* ---------------------------------------------------------------------------
  75423. * Optimized version for level == 1 or strategy == Z_RLE only
  75424. */
  75425. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  75426. {
  75427. register Bytef *scan = s->window + s->strstart; /* current string */
  75428. register Bytef *match; /* matched string */
  75429. register int len; /* length of current match */
  75430. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  75431. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  75432. * It is easy to get rid of this optimization if necessary.
  75433. */
  75434. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  75435. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  75436. Assert(cur_match < s->strstart, "no future");
  75437. match = s->window + cur_match;
  75438. /* Return failure if the match length is less than 2:
  75439. */
  75440. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  75441. /* The check at best_len-1 can be removed because it will be made
  75442. * again later. (This heuristic is not always a win.)
  75443. * It is not necessary to compare scan[2] and match[2] since they
  75444. * are always equal when the other bytes match, given that
  75445. * the hash keys are equal and that HASH_BITS >= 8.
  75446. */
  75447. scan += 2, match += 2;
  75448. Assert(*scan == *match, "match[2]?");
  75449. /* We check for insufficient lookahead only every 8th comparison;
  75450. * the 256th check will be made at strstart+258.
  75451. */
  75452. do {
  75453. } while (*++scan == *++match && *++scan == *++match &&
  75454. *++scan == *++match && *++scan == *++match &&
  75455. *++scan == *++match && *++scan == *++match &&
  75456. *++scan == *++match && *++scan == *++match &&
  75457. scan < strend);
  75458. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  75459. len = MAX_MATCH - (int)(strend - scan);
  75460. if (len < MIN_MATCH) return MIN_MATCH - 1;
  75461. s->match_start = cur_match;
  75462. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  75463. }
  75464. #ifdef DEBUG
  75465. /* ===========================================================================
  75466. * Check that the match at match_start is indeed a match.
  75467. */
  75468. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  75469. {
  75470. /* check that the match is indeed a match */
  75471. if (zmemcmp(s->window + match,
  75472. s->window + start, length) != EQUAL) {
  75473. fprintf(stderr, " start %u, match %u, length %d\n",
  75474. start, match, length);
  75475. do {
  75476. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  75477. } while (--length != 0);
  75478. z_error("invalid match");
  75479. }
  75480. if (z_verbose > 1) {
  75481. fprintf(stderr,"\\[%d,%d]", start-match, length);
  75482. do { putc(s->window[start++], stderr); } while (--length != 0);
  75483. }
  75484. }
  75485. #else
  75486. # define check_match(s, start, match, length)
  75487. #endif /* DEBUG */
  75488. /* ===========================================================================
  75489. * Fill the window when the lookahead becomes insufficient.
  75490. * Updates strstart and lookahead.
  75491. *
  75492. * IN assertion: lookahead < MIN_LOOKAHEAD
  75493. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  75494. * At least one byte has been read, or avail_in == 0; reads are
  75495. * performed for at least two bytes (required for the zip translate_eol
  75496. * option -- not supported here).
  75497. */
  75498. local void fill_window (deflate_state *s)
  75499. {
  75500. register unsigned n, m;
  75501. register Posf *p;
  75502. unsigned more; /* Amount of free space at the end of the window. */
  75503. uInt wsize = s->w_size;
  75504. do {
  75505. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  75506. /* Deal with !@#$% 64K limit: */
  75507. if (sizeof(int) <= 2) {
  75508. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  75509. more = wsize;
  75510. } else if (more == (unsigned)(-1)) {
  75511. /* Very unlikely, but possible on 16 bit machine if
  75512. * strstart == 0 && lookahead == 1 (input done a byte at time)
  75513. */
  75514. more--;
  75515. }
  75516. }
  75517. /* If the window is almost full and there is insufficient lookahead,
  75518. * move the upper half to the lower one to make room in the upper half.
  75519. */
  75520. if (s->strstart >= wsize+MAX_DIST(s)) {
  75521. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  75522. s->match_start -= wsize;
  75523. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  75524. s->block_start -= (long) wsize;
  75525. /* Slide the hash table (could be avoided with 32 bit values
  75526. at the expense of memory usage). We slide even when level == 0
  75527. to keep the hash table consistent if we switch back to level > 0
  75528. later. (Using level 0 permanently is not an optimal usage of
  75529. zlib, so we don't care about this pathological case.)
  75530. */
  75531. /* %%% avoid this when Z_RLE */
  75532. n = s->hash_size;
  75533. p = &s->head[n];
  75534. do {
  75535. m = *--p;
  75536. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  75537. } while (--n);
  75538. n = wsize;
  75539. #ifndef FASTEST
  75540. p = &s->prev[n];
  75541. do {
  75542. m = *--p;
  75543. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  75544. /* If n is not on any hash chain, prev[n] is garbage but
  75545. * its value will never be used.
  75546. */
  75547. } while (--n);
  75548. #endif
  75549. more += wsize;
  75550. }
  75551. if (s->strm->avail_in == 0) return;
  75552. /* If there was no sliding:
  75553. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  75554. * more == window_size - lookahead - strstart
  75555. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  75556. * => more >= window_size - 2*WSIZE + 2
  75557. * In the BIG_MEM or MMAP case (not yet supported),
  75558. * window_size == input_size + MIN_LOOKAHEAD &&
  75559. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  75560. * Otherwise, window_size == 2*WSIZE so more >= 2.
  75561. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  75562. */
  75563. Assert(more >= 2, "more < 2");
  75564. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  75565. s->lookahead += n;
  75566. /* Initialize the hash value now that we have some input: */
  75567. if (s->lookahead >= MIN_MATCH) {
  75568. s->ins_h = s->window[s->strstart];
  75569. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  75570. #if MIN_MATCH != 3
  75571. Call UPDATE_HASH() MIN_MATCH-3 more times
  75572. #endif
  75573. }
  75574. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  75575. * but this is not important since only literal bytes will be emitted.
  75576. */
  75577. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  75578. }
  75579. /* ===========================================================================
  75580. * Flush the current block, with given end-of-file flag.
  75581. * IN assertion: strstart is set to the end of the current match.
  75582. */
  75583. #define FLUSH_BLOCK_ONLY(s, eof) { \
  75584. _tr_flush_block(s, (s->block_start >= 0L ? \
  75585. (charf *)&s->window[(unsigned)s->block_start] : \
  75586. (charf *)Z_NULL), \
  75587. (ulg)((long)s->strstart - s->block_start), \
  75588. (eof)); \
  75589. s->block_start = s->strstart; \
  75590. flush_pending(s->strm); \
  75591. Tracev((stderr,"[FLUSH]")); \
  75592. }
  75593. /* Same but force premature exit if necessary. */
  75594. #define FLUSH_BLOCK(s, eof) { \
  75595. FLUSH_BLOCK_ONLY(s, eof); \
  75596. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  75597. }
  75598. /* ===========================================================================
  75599. * Copy without compression as much as possible from the input stream, return
  75600. * the current block state.
  75601. * This function does not insert new strings in the dictionary since
  75602. * uncompressible data is probably not useful. This function is used
  75603. * only for the level=0 compression option.
  75604. * NOTE: this function should be optimized to avoid extra copying from
  75605. * window to pending_buf.
  75606. */
  75607. local block_state deflate_stored(deflate_state *s, int flush)
  75608. {
  75609. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  75610. * to pending_buf_size, and each stored block has a 5 byte header:
  75611. */
  75612. ulg max_block_size = 0xffff;
  75613. ulg max_start;
  75614. if (max_block_size > s->pending_buf_size - 5) {
  75615. max_block_size = s->pending_buf_size - 5;
  75616. }
  75617. /* Copy as much as possible from input to output: */
  75618. for (;;) {
  75619. /* Fill the window as much as possible: */
  75620. if (s->lookahead <= 1) {
  75621. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  75622. s->block_start >= (long)s->w_size, "slide too late");
  75623. fill_window(s);
  75624. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  75625. if (s->lookahead == 0) break; /* flush the current block */
  75626. }
  75627. Assert(s->block_start >= 0L, "block gone");
  75628. s->strstart += s->lookahead;
  75629. s->lookahead = 0;
  75630. /* Emit a stored block if pending_buf will be full: */
  75631. max_start = s->block_start + max_block_size;
  75632. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  75633. /* strstart == 0 is possible when wraparound on 16-bit machine */
  75634. s->lookahead = (uInt)(s->strstart - max_start);
  75635. s->strstart = (uInt)max_start;
  75636. FLUSH_BLOCK(s, 0);
  75637. }
  75638. /* Flush if we may have to slide, otherwise block_start may become
  75639. * negative and the data will be gone:
  75640. */
  75641. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  75642. FLUSH_BLOCK(s, 0);
  75643. }
  75644. }
  75645. FLUSH_BLOCK(s, flush == Z_FINISH);
  75646. return flush == Z_FINISH ? finish_done : block_done;
  75647. }
  75648. /* ===========================================================================
  75649. * Compress as much as possible from the input stream, return the current
  75650. * block state.
  75651. * This function does not perform lazy evaluation of matches and inserts
  75652. * new strings in the dictionary only for unmatched strings or for short
  75653. * matches. It is used only for the fast compression options.
  75654. */
  75655. local block_state deflate_fast(deflate_state *s, int flush)
  75656. {
  75657. IPos hash_head = NIL; /* head of the hash chain */
  75658. int bflush; /* set if current block must be flushed */
  75659. for (;;) {
  75660. /* Make sure that we always have enough lookahead, except
  75661. * at the end of the input file. We need MAX_MATCH bytes
  75662. * for the next match, plus MIN_MATCH bytes to insert the
  75663. * string following the next match.
  75664. */
  75665. if (s->lookahead < MIN_LOOKAHEAD) {
  75666. fill_window(s);
  75667. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  75668. return need_more;
  75669. }
  75670. if (s->lookahead == 0) break; /* flush the current block */
  75671. }
  75672. /* Insert the string window[strstart .. strstart+2] in the
  75673. * dictionary, and set hash_head to the head of the hash chain:
  75674. */
  75675. if (s->lookahead >= MIN_MATCH) {
  75676. INSERT_STRING(s, s->strstart, hash_head);
  75677. }
  75678. /* Find the longest match, discarding those <= prev_length.
  75679. * At this point we have always match_length < MIN_MATCH
  75680. */
  75681. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  75682. /* To simplify the code, we prevent matches with the string
  75683. * of window index 0 (in particular we have to avoid a match
  75684. * of the string with itself at the start of the input file).
  75685. */
  75686. #ifdef FASTEST
  75687. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  75688. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  75689. s->match_length = longest_match_fast (s, hash_head);
  75690. }
  75691. #else
  75692. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  75693. s->match_length = longest_match (s, hash_head);
  75694. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  75695. s->match_length = longest_match_fast (s, hash_head);
  75696. }
  75697. #endif
  75698. /* longest_match() or longest_match_fast() sets match_start */
  75699. }
  75700. if (s->match_length >= MIN_MATCH) {
  75701. check_match(s, s->strstart, s->match_start, s->match_length);
  75702. _tr_tally_dist(s, s->strstart - s->match_start,
  75703. s->match_length - MIN_MATCH, bflush);
  75704. s->lookahead -= s->match_length;
  75705. /* Insert new strings in the hash table only if the match length
  75706. * is not too large. This saves time but degrades compression.
  75707. */
  75708. #ifndef FASTEST
  75709. if (s->match_length <= s->max_insert_length &&
  75710. s->lookahead >= MIN_MATCH) {
  75711. s->match_length--; /* string at strstart already in table */
  75712. do {
  75713. s->strstart++;
  75714. INSERT_STRING(s, s->strstart, hash_head);
  75715. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  75716. * always MIN_MATCH bytes ahead.
  75717. */
  75718. } while (--s->match_length != 0);
  75719. s->strstart++;
  75720. } else
  75721. #endif
  75722. {
  75723. s->strstart += s->match_length;
  75724. s->match_length = 0;
  75725. s->ins_h = s->window[s->strstart];
  75726. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  75727. #if MIN_MATCH != 3
  75728. Call UPDATE_HASH() MIN_MATCH-3 more times
  75729. #endif
  75730. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  75731. * matter since it will be recomputed at next deflate call.
  75732. */
  75733. }
  75734. } else {
  75735. /* No match, output a literal byte */
  75736. Tracevv((stderr,"%c", s->window[s->strstart]));
  75737. _tr_tally_lit (s, s->window[s->strstart], bflush);
  75738. s->lookahead--;
  75739. s->strstart++;
  75740. }
  75741. if (bflush) FLUSH_BLOCK(s, 0);
  75742. }
  75743. FLUSH_BLOCK(s, flush == Z_FINISH);
  75744. return flush == Z_FINISH ? finish_done : block_done;
  75745. }
  75746. #ifndef FASTEST
  75747. /* ===========================================================================
  75748. * Same as above, but achieves better compression. We use a lazy
  75749. * evaluation for matches: a match is finally adopted only if there is
  75750. * no better match at the next window position.
  75751. */
  75752. local block_state deflate_slow(deflate_state *s, int flush)
  75753. {
  75754. IPos hash_head = NIL; /* head of hash chain */
  75755. int bflush; /* set if current block must be flushed */
  75756. /* Process the input block. */
  75757. for (;;) {
  75758. /* Make sure that we always have enough lookahead, except
  75759. * at the end of the input file. We need MAX_MATCH bytes
  75760. * for the next match, plus MIN_MATCH bytes to insert the
  75761. * string following the next match.
  75762. */
  75763. if (s->lookahead < MIN_LOOKAHEAD) {
  75764. fill_window(s);
  75765. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  75766. return need_more;
  75767. }
  75768. if (s->lookahead == 0) break; /* flush the current block */
  75769. }
  75770. /* Insert the string window[strstart .. strstart+2] in the
  75771. * dictionary, and set hash_head to the head of the hash chain:
  75772. */
  75773. if (s->lookahead >= MIN_MATCH) {
  75774. INSERT_STRING(s, s->strstart, hash_head);
  75775. }
  75776. /* Find the longest match, discarding those <= prev_length.
  75777. */
  75778. s->prev_length = s->match_length, s->prev_match = s->match_start;
  75779. s->match_length = MIN_MATCH-1;
  75780. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  75781. s->strstart - hash_head <= MAX_DIST(s)) {
  75782. /* To simplify the code, we prevent matches with the string
  75783. * of window index 0 (in particular we have to avoid a match
  75784. * of the string with itself at the start of the input file).
  75785. */
  75786. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  75787. s->match_length = longest_match (s, hash_head);
  75788. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  75789. s->match_length = longest_match_fast (s, hash_head);
  75790. }
  75791. /* longest_match() or longest_match_fast() sets match_start */
  75792. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  75793. #if TOO_FAR <= 32767
  75794. || (s->match_length == MIN_MATCH &&
  75795. s->strstart - s->match_start > TOO_FAR)
  75796. #endif
  75797. )) {
  75798. /* If prev_match is also MIN_MATCH, match_start is garbage
  75799. * but we will ignore the current match anyway.
  75800. */
  75801. s->match_length = MIN_MATCH-1;
  75802. }
  75803. }
  75804. /* If there was a match at the previous step and the current
  75805. * match is not better, output the previous match:
  75806. */
  75807. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  75808. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  75809. /* Do not insert strings in hash table beyond this. */
  75810. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  75811. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  75812. s->prev_length - MIN_MATCH, bflush);
  75813. /* Insert in hash table all strings up to the end of the match.
  75814. * strstart-1 and strstart are already inserted. If there is not
  75815. * enough lookahead, the last two strings are not inserted in
  75816. * the hash table.
  75817. */
  75818. s->lookahead -= s->prev_length-1;
  75819. s->prev_length -= 2;
  75820. do {
  75821. if (++s->strstart <= max_insert) {
  75822. INSERT_STRING(s, s->strstart, hash_head);
  75823. }
  75824. } while (--s->prev_length != 0);
  75825. s->match_available = 0;
  75826. s->match_length = MIN_MATCH-1;
  75827. s->strstart++;
  75828. if (bflush) FLUSH_BLOCK(s, 0);
  75829. } else if (s->match_available) {
  75830. /* If there was no match at the previous position, output a
  75831. * single literal. If there was a match but the current match
  75832. * is longer, truncate the previous match to a single literal.
  75833. */
  75834. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  75835. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  75836. if (bflush) {
  75837. FLUSH_BLOCK_ONLY(s, 0);
  75838. }
  75839. s->strstart++;
  75840. s->lookahead--;
  75841. if (s->strm->avail_out == 0) return need_more;
  75842. } else {
  75843. /* There is no previous match to compare with, wait for
  75844. * the next step to decide.
  75845. */
  75846. s->match_available = 1;
  75847. s->strstart++;
  75848. s->lookahead--;
  75849. }
  75850. }
  75851. Assert (flush != Z_NO_FLUSH, "no flush?");
  75852. if (s->match_available) {
  75853. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  75854. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  75855. s->match_available = 0;
  75856. }
  75857. FLUSH_BLOCK(s, flush == Z_FINISH);
  75858. return flush == Z_FINISH ? finish_done : block_done;
  75859. }
  75860. #endif /* FASTEST */
  75861. #if 0
  75862. /* ===========================================================================
  75863. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  75864. * one. Do not maintain a hash table. (It will be regenerated if this run of
  75865. * deflate switches away from Z_RLE.)
  75866. */
  75867. local block_state deflate_rle(s, flush)
  75868. deflate_state *s;
  75869. int flush;
  75870. {
  75871. int bflush; /* set if current block must be flushed */
  75872. uInt run; /* length of run */
  75873. uInt max; /* maximum length of run */
  75874. uInt prev; /* byte at distance one to match */
  75875. Bytef *scan; /* scan for end of run */
  75876. for (;;) {
  75877. /* Make sure that we always have enough lookahead, except
  75878. * at the end of the input file. We need MAX_MATCH bytes
  75879. * for the longest encodable run.
  75880. */
  75881. if (s->lookahead < MAX_MATCH) {
  75882. fill_window(s);
  75883. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  75884. return need_more;
  75885. }
  75886. if (s->lookahead == 0) break; /* flush the current block */
  75887. }
  75888. /* See how many times the previous byte repeats */
  75889. run = 0;
  75890. if (s->strstart > 0) { /* if there is a previous byte, that is */
  75891. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  75892. scan = s->window + s->strstart - 1;
  75893. prev = *scan++;
  75894. do {
  75895. if (*scan++ != prev)
  75896. break;
  75897. } while (++run < max);
  75898. }
  75899. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  75900. if (run >= MIN_MATCH) {
  75901. check_match(s, s->strstart, s->strstart - 1, run);
  75902. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  75903. s->lookahead -= run;
  75904. s->strstart += run;
  75905. } else {
  75906. /* No match, output a literal byte */
  75907. Tracevv((stderr,"%c", s->window[s->strstart]));
  75908. _tr_tally_lit (s, s->window[s->strstart], bflush);
  75909. s->lookahead--;
  75910. s->strstart++;
  75911. }
  75912. if (bflush) FLUSH_BLOCK(s, 0);
  75913. }
  75914. FLUSH_BLOCK(s, flush == Z_FINISH);
  75915. return flush == Z_FINISH ? finish_done : block_done;
  75916. }
  75917. #endif
  75918. /********* End of inlined file: deflate.c *********/
  75919. /********* Start of inlined file: infback.c *********/
  75920. /*
  75921. This code is largely copied from inflate.c. Normally either infback.o or
  75922. inflate.o would be linked into an application--not both. The interface
  75923. with inffast.c is retained so that optimized assembler-coded versions of
  75924. inflate_fast() can be used with either inflate.c or infback.c.
  75925. */
  75926. /********* Start of inlined file: inftrees.h *********/
  75927. /* WARNING: this file should *not* be used by applications. It is
  75928. part of the implementation of the compression library and is
  75929. subject to change. Applications should only use zlib.h.
  75930. */
  75931. #ifndef _INFTREES_H_
  75932. #define _INFTREES_H_
  75933. /* Structure for decoding tables. Each entry provides either the
  75934. information needed to do the operation requested by the code that
  75935. indexed that table entry, or it provides a pointer to another
  75936. table that indexes more bits of the code. op indicates whether
  75937. the entry is a pointer to another table, a literal, a length or
  75938. distance, an end-of-block, or an invalid code. For a table
  75939. pointer, the low four bits of op is the number of index bits of
  75940. that table. For a length or distance, the low four bits of op
  75941. is the number of extra bits to get after the code. bits is
  75942. the number of bits in this code or part of the code to drop off
  75943. of the bit buffer. val is the actual byte to output in the case
  75944. of a literal, the base length or distance, or the offset from
  75945. the current table to the next table. Each entry is four bytes. */
  75946. typedef struct {
  75947. unsigned char op; /* operation, extra bits, table bits */
  75948. unsigned char bits; /* bits in this part of the code */
  75949. unsigned short val; /* offset in table or code value */
  75950. } code;
  75951. /* op values as set by inflate_table():
  75952. 00000000 - literal
  75953. 0000tttt - table link, tttt != 0 is the number of table index bits
  75954. 0001eeee - length or distance, eeee is the number of extra bits
  75955. 01100000 - end of block
  75956. 01000000 - invalid code
  75957. */
  75958. /* Maximum size of dynamic tree. The maximum found in a long but non-
  75959. exhaustive search was 1444 code structures (852 for length/literals
  75960. and 592 for distances, the latter actually the result of an
  75961. exhaustive search). The true maximum is not known, but the value
  75962. below is more than safe. */
  75963. #define ENOUGH 2048
  75964. #define MAXD 592
  75965. /* Type of code to build for inftable() */
  75966. typedef enum {
  75967. CODES,
  75968. LENS,
  75969. DISTS
  75970. } codetype;
  75971. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  75972. unsigned codes, code FAR * FAR *table,
  75973. unsigned FAR *bits, unsigned short FAR *work));
  75974. #endif
  75975. /********* End of inlined file: inftrees.h *********/
  75976. /********* Start of inlined file: inflate.h *********/
  75977. /* WARNING: this file should *not* be used by applications. It is
  75978. part of the implementation of the compression library and is
  75979. subject to change. Applications should only use zlib.h.
  75980. */
  75981. #ifndef _INFLATE_H_
  75982. #define _INFLATE_H_
  75983. /* define NO_GZIP when compiling if you want to disable gzip header and
  75984. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  75985. the crc code when it is not needed. For shared libraries, gzip decoding
  75986. should be left enabled. */
  75987. #ifndef NO_GZIP
  75988. # define GUNZIP
  75989. #endif
  75990. /* Possible inflate modes between inflate() calls */
  75991. typedef enum {
  75992. HEAD, /* i: waiting for magic header */
  75993. FLAGS, /* i: waiting for method and flags (gzip) */
  75994. TIME, /* i: waiting for modification time (gzip) */
  75995. OS, /* i: waiting for extra flags and operating system (gzip) */
  75996. EXLEN, /* i: waiting for extra length (gzip) */
  75997. EXTRA, /* i: waiting for extra bytes (gzip) */
  75998. NAME, /* i: waiting for end of file name (gzip) */
  75999. COMMENT, /* i: waiting for end of comment (gzip) */
  76000. HCRC, /* i: waiting for header crc (gzip) */
  76001. DICTID, /* i: waiting for dictionary check value */
  76002. DICT, /* waiting for inflateSetDictionary() call */
  76003. TYPE, /* i: waiting for type bits, including last-flag bit */
  76004. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  76005. STORED, /* i: waiting for stored size (length and complement) */
  76006. COPY, /* i/o: waiting for input or output to copy stored block */
  76007. TABLE, /* i: waiting for dynamic block table lengths */
  76008. LENLENS, /* i: waiting for code length code lengths */
  76009. CODELENS, /* i: waiting for length/lit and distance code lengths */
  76010. LEN, /* i: waiting for length/lit code */
  76011. LENEXT, /* i: waiting for length extra bits */
  76012. DIST, /* i: waiting for distance code */
  76013. DISTEXT, /* i: waiting for distance extra bits */
  76014. MATCH, /* o: waiting for output space to copy string */
  76015. LIT, /* o: waiting for output space to write literal */
  76016. CHECK, /* i: waiting for 32-bit check value */
  76017. LENGTH, /* i: waiting for 32-bit length (gzip) */
  76018. DONE, /* finished check, done -- remain here until reset */
  76019. BAD, /* got a data error -- remain here until reset */
  76020. MEM, /* got an inflate() memory error -- remain here until reset */
  76021. SYNC /* looking for synchronization bytes to restart inflate() */
  76022. } inflate_mode;
  76023. /*
  76024. State transitions between above modes -
  76025. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  76026. Process header:
  76027. HEAD -> (gzip) or (zlib)
  76028. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  76029. NAME -> COMMENT -> HCRC -> TYPE
  76030. (zlib) -> DICTID or TYPE
  76031. DICTID -> DICT -> TYPE
  76032. Read deflate blocks:
  76033. TYPE -> STORED or TABLE or LEN or CHECK
  76034. STORED -> COPY -> TYPE
  76035. TABLE -> LENLENS -> CODELENS -> LEN
  76036. Read deflate codes:
  76037. LEN -> LENEXT or LIT or TYPE
  76038. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  76039. LIT -> LEN
  76040. Process trailer:
  76041. CHECK -> LENGTH -> DONE
  76042. */
  76043. /* state maintained between inflate() calls. Approximately 7K bytes. */
  76044. struct inflate_state {
  76045. inflate_mode mode; /* current inflate mode */
  76046. int last; /* true if processing last block */
  76047. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  76048. int havedict; /* true if dictionary provided */
  76049. int flags; /* gzip header method and flags (0 if zlib) */
  76050. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  76051. unsigned long check; /* protected copy of check value */
  76052. unsigned long total; /* protected copy of output count */
  76053. gz_headerp head; /* where to save gzip header information */
  76054. /* sliding window */
  76055. unsigned wbits; /* log base 2 of requested window size */
  76056. unsigned wsize; /* window size or zero if not using window */
  76057. unsigned whave; /* valid bytes in the window */
  76058. unsigned write; /* window write index */
  76059. unsigned char FAR *window; /* allocated sliding window, if needed */
  76060. /* bit accumulator */
  76061. unsigned long hold; /* input bit accumulator */
  76062. unsigned bits; /* number of bits in "in" */
  76063. /* for string and stored block copying */
  76064. unsigned length; /* literal or length of data to copy */
  76065. unsigned offset; /* distance back to copy string from */
  76066. /* for table and code decoding */
  76067. unsigned extra; /* extra bits needed */
  76068. /* fixed and dynamic code tables */
  76069. code const FAR *lencode; /* starting table for length/literal codes */
  76070. code const FAR *distcode; /* starting table for distance codes */
  76071. unsigned lenbits; /* index bits for lencode */
  76072. unsigned distbits; /* index bits for distcode */
  76073. /* dynamic table building */
  76074. unsigned ncode; /* number of code length code lengths */
  76075. unsigned nlen; /* number of length code lengths */
  76076. unsigned ndist; /* number of distance code lengths */
  76077. unsigned have; /* number of code lengths in lens[] */
  76078. code FAR *next; /* next available space in codes[] */
  76079. unsigned short lens[320]; /* temporary storage for code lengths */
  76080. unsigned short work[288]; /* work area for code table building */
  76081. code codes[ENOUGH]; /* space for code tables */
  76082. };
  76083. #endif
  76084. /********* End of inlined file: inflate.h *********/
  76085. /********* Start of inlined file: inffast.h *********/
  76086. /* WARNING: this file should *not* be used by applications. It is
  76087. part of the implementation of the compression library and is
  76088. subject to change. Applications should only use zlib.h.
  76089. */
  76090. void inflate_fast OF((z_streamp strm, unsigned start));
  76091. /********* End of inlined file: inffast.h *********/
  76092. /* function prototypes */
  76093. local void fixedtables1 OF((struct inflate_state FAR *state));
  76094. /*
  76095. strm provides memory allocation functions in zalloc and zfree, or
  76096. Z_NULL to use the library memory allocation functions.
  76097. windowBits is in the range 8..15, and window is a user-supplied
  76098. window and output buffer that is 2**windowBits bytes.
  76099. */
  76100. int ZEXPORT inflateBackInit_(z_streamp strm, int windowBits, unsigned char FAR *window, const char *version, int stream_size)
  76101. {
  76102. struct inflate_state FAR *state;
  76103. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  76104. stream_size != (int)(sizeof(z_stream)))
  76105. return Z_VERSION_ERROR;
  76106. if (strm == Z_NULL || window == Z_NULL ||
  76107. windowBits < 8 || windowBits > 15)
  76108. return Z_STREAM_ERROR;
  76109. strm->msg = Z_NULL; /* in case we return an error */
  76110. if (strm->zalloc == (alloc_func)0) {
  76111. strm->zalloc = zcalloc;
  76112. strm->opaque = (voidpf)0;
  76113. }
  76114. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  76115. state = (struct inflate_state FAR *)ZALLOC(strm, 1,
  76116. sizeof(struct inflate_state));
  76117. if (state == Z_NULL) return Z_MEM_ERROR;
  76118. Tracev((stderr, "inflate: allocated\n"));
  76119. strm->state = (struct internal_state FAR *)state;
  76120. state->dmax = 32768U;
  76121. state->wbits = windowBits;
  76122. state->wsize = 1U << windowBits;
  76123. state->window = window;
  76124. state->write = 0;
  76125. state->whave = 0;
  76126. return Z_OK;
  76127. }
  76128. /*
  76129. Return state with length and distance decoding tables and index sizes set to
  76130. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  76131. If BUILDFIXED is defined, then instead this routine builds the tables the
  76132. first time it's called, and returns those tables the first time and
  76133. thereafter. This reduces the size of the code by about 2K bytes, in
  76134. exchange for a little execution time. However, BUILDFIXED should not be
  76135. used for threaded applications, since the rewriting of the tables and virgin
  76136. may not be thread-safe.
  76137. */
  76138. local void fixedtables1 (struct inflate_state FAR *state)
  76139. {
  76140. #ifdef BUILDFIXED
  76141. static int virgin = 1;
  76142. static code *lenfix, *distfix;
  76143. static code fixed[544];
  76144. /* build fixed huffman tables if first call (may not be thread safe) */
  76145. if (virgin) {
  76146. unsigned sym, bits;
  76147. static code *next;
  76148. /* literal/length table */
  76149. sym = 0;
  76150. while (sym < 144) state->lens[sym++] = 8;
  76151. while (sym < 256) state->lens[sym++] = 9;
  76152. while (sym < 280) state->lens[sym++] = 7;
  76153. while (sym < 288) state->lens[sym++] = 8;
  76154. next = fixed;
  76155. lenfix = next;
  76156. bits = 9;
  76157. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  76158. /* distance table */
  76159. sym = 0;
  76160. while (sym < 32) state->lens[sym++] = 5;
  76161. distfix = next;
  76162. bits = 5;
  76163. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  76164. /* do this just once */
  76165. virgin = 0;
  76166. }
  76167. #else /* !BUILDFIXED */
  76168. /********* Start of inlined file: inffixed.h *********/
  76169. /* inffixed.h -- table for decoding fixed codes
  76170. * Generated automatically by makefixed().
  76171. */
  76172. /* WARNING: this file should *not* be used by applications. It
  76173. is part of the implementation of the compression library and
  76174. is subject to change. Applications should only use zlib.h.
  76175. */
  76176. static const code lenfix[512] = {
  76177. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  76178. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  76179. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  76180. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  76181. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  76182. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  76183. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  76184. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  76185. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  76186. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  76187. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  76188. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  76189. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  76190. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  76191. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  76192. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  76193. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  76194. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  76195. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  76196. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  76197. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  76198. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  76199. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  76200. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  76201. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  76202. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  76203. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  76204. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  76205. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  76206. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  76207. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  76208. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  76209. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  76210. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  76211. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  76212. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  76213. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  76214. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  76215. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  76216. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  76217. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  76218. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  76219. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  76220. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  76221. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  76222. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  76223. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  76224. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  76225. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  76226. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  76227. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  76228. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  76229. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  76230. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  76231. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  76232. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  76233. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  76234. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  76235. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  76236. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  76237. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  76238. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  76239. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  76240. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  76241. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  76242. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  76243. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  76244. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  76245. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  76246. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  76247. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  76248. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  76249. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  76250. {0,9,255}
  76251. };
  76252. static const code distfix[32] = {
  76253. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  76254. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  76255. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  76256. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  76257. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  76258. {22,5,193},{64,5,0}
  76259. };
  76260. /********* End of inlined file: inffixed.h *********/
  76261. #endif /* BUILDFIXED */
  76262. state->lencode = lenfix;
  76263. state->lenbits = 9;
  76264. state->distcode = distfix;
  76265. state->distbits = 5;
  76266. }
  76267. /* Macros for inflateBack(): */
  76268. /* Load returned state from inflate_fast() */
  76269. #define LOAD() \
  76270. do { \
  76271. put = strm->next_out; \
  76272. left = strm->avail_out; \
  76273. next = strm->next_in; \
  76274. have = strm->avail_in; \
  76275. hold = state->hold; \
  76276. bits = state->bits; \
  76277. } while (0)
  76278. /* Set state from registers for inflate_fast() */
  76279. #define RESTORE() \
  76280. do { \
  76281. strm->next_out = put; \
  76282. strm->avail_out = left; \
  76283. strm->next_in = next; \
  76284. strm->avail_in = have; \
  76285. state->hold = hold; \
  76286. state->bits = bits; \
  76287. } while (0)
  76288. /* Clear the input bit accumulator */
  76289. #define INITBITS() \
  76290. do { \
  76291. hold = 0; \
  76292. bits = 0; \
  76293. } while (0)
  76294. /* Assure that some input is available. If input is requested, but denied,
  76295. then return a Z_BUF_ERROR from inflateBack(). */
  76296. #define PULL() \
  76297. do { \
  76298. if (have == 0) { \
  76299. have = in(in_desc, &next); \
  76300. if (have == 0) { \
  76301. next = Z_NULL; \
  76302. ret = Z_BUF_ERROR; \
  76303. goto inf_leave; \
  76304. } \
  76305. } \
  76306. } while (0)
  76307. /* Get a byte of input into the bit accumulator, or return from inflateBack()
  76308. with an error if there is no input available. */
  76309. #define PULLBYTE() \
  76310. do { \
  76311. PULL(); \
  76312. have--; \
  76313. hold += (unsigned long)(*next++) << bits; \
  76314. bits += 8; \
  76315. } while (0)
  76316. /* Assure that there are at least n bits in the bit accumulator. If there is
  76317. not enough available input to do that, then return from inflateBack() with
  76318. an error. */
  76319. #define NEEDBITS(n) \
  76320. do { \
  76321. while (bits < (unsigned)(n)) \
  76322. PULLBYTE(); \
  76323. } while (0)
  76324. /* Return the low n bits of the bit accumulator (n < 16) */
  76325. #define BITS(n) \
  76326. ((unsigned)hold & ((1U << (n)) - 1))
  76327. /* Remove n bits from the bit accumulator */
  76328. #define DROPBITS(n) \
  76329. do { \
  76330. hold >>= (n); \
  76331. bits -= (unsigned)(n); \
  76332. } while (0)
  76333. /* Remove zero to seven bits as needed to go to a byte boundary */
  76334. #define BYTEBITS() \
  76335. do { \
  76336. hold >>= bits & 7; \
  76337. bits -= bits & 7; \
  76338. } while (0)
  76339. /* Assure that some output space is available, by writing out the window
  76340. if it's full. If the write fails, return from inflateBack() with a
  76341. Z_BUF_ERROR. */
  76342. #define ROOM() \
  76343. do { \
  76344. if (left == 0) { \
  76345. put = state->window; \
  76346. left = state->wsize; \
  76347. state->whave = left; \
  76348. if (out(out_desc, put, left)) { \
  76349. ret = Z_BUF_ERROR; \
  76350. goto inf_leave; \
  76351. } \
  76352. } \
  76353. } while (0)
  76354. /*
  76355. strm provides the memory allocation functions and window buffer on input,
  76356. and provides information on the unused input on return. For Z_DATA_ERROR
  76357. returns, strm will also provide an error message.
  76358. in() and out() are the call-back input and output functions. When
  76359. inflateBack() needs more input, it calls in(). When inflateBack() has
  76360. filled the window with output, or when it completes with data in the
  76361. window, it calls out() to write out the data. The application must not
  76362. change the provided input until in() is called again or inflateBack()
  76363. returns. The application must not change the window/output buffer until
  76364. inflateBack() returns.
  76365. in() and out() are called with a descriptor parameter provided in the
  76366. inflateBack() call. This parameter can be a structure that provides the
  76367. information required to do the read or write, as well as accumulated
  76368. information on the input and output such as totals and check values.
  76369. in() should return zero on failure. out() should return non-zero on
  76370. failure. If either in() or out() fails, than inflateBack() returns a
  76371. Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it
  76372. was in() or out() that caused in the error. Otherwise, inflateBack()
  76373. returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
  76374. error, or Z_MEM_ERROR if it could not allocate memory for the state.
  76375. inflateBack() can also return Z_STREAM_ERROR if the input parameters
  76376. are not correct, i.e. strm is Z_NULL or the state was not initialized.
  76377. */
  76378. int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc, out_func out, void FAR *out_desc)
  76379. {
  76380. struct inflate_state FAR *state;
  76381. unsigned char FAR *next; /* next input */
  76382. unsigned char FAR *put; /* next output */
  76383. unsigned have, left; /* available input and output */
  76384. unsigned long hold; /* bit buffer */
  76385. unsigned bits; /* bits in bit buffer */
  76386. unsigned copy; /* number of stored or match bytes to copy */
  76387. unsigned char FAR *from; /* where to copy match bytes from */
  76388. code thisx; /* current decoding table entry */
  76389. code last; /* parent table entry */
  76390. unsigned len; /* length to copy for repeats, bits to drop */
  76391. int ret; /* return code */
  76392. static const unsigned short order[19] = /* permutation of code lengths */
  76393. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  76394. /* Check that the strm exists and that the state was initialized */
  76395. if (strm == Z_NULL || strm->state == Z_NULL)
  76396. return Z_STREAM_ERROR;
  76397. state = (struct inflate_state FAR *)strm->state;
  76398. /* Reset the state */
  76399. strm->msg = Z_NULL;
  76400. state->mode = TYPE;
  76401. state->last = 0;
  76402. state->whave = 0;
  76403. next = strm->next_in;
  76404. have = next != Z_NULL ? strm->avail_in : 0;
  76405. hold = 0;
  76406. bits = 0;
  76407. put = state->window;
  76408. left = state->wsize;
  76409. /* Inflate until end of block marked as last */
  76410. for (;;)
  76411. switch (state->mode) {
  76412. case TYPE:
  76413. /* determine and dispatch block type */
  76414. if (state->last) {
  76415. BYTEBITS();
  76416. state->mode = DONE;
  76417. break;
  76418. }
  76419. NEEDBITS(3);
  76420. state->last = BITS(1);
  76421. DROPBITS(1);
  76422. switch (BITS(2)) {
  76423. case 0: /* stored block */
  76424. Tracev((stderr, "inflate: stored block%s\n",
  76425. state->last ? " (last)" : ""));
  76426. state->mode = STORED;
  76427. break;
  76428. case 1: /* fixed block */
  76429. fixedtables1(state);
  76430. Tracev((stderr, "inflate: fixed codes block%s\n",
  76431. state->last ? " (last)" : ""));
  76432. state->mode = LEN; /* decode codes */
  76433. break;
  76434. case 2: /* dynamic block */
  76435. Tracev((stderr, "inflate: dynamic codes block%s\n",
  76436. state->last ? " (last)" : ""));
  76437. state->mode = TABLE;
  76438. break;
  76439. case 3:
  76440. strm->msg = (char *)"invalid block type";
  76441. state->mode = BAD;
  76442. }
  76443. DROPBITS(2);
  76444. break;
  76445. case STORED:
  76446. /* get and verify stored block length */
  76447. BYTEBITS(); /* go to byte boundary */
  76448. NEEDBITS(32);
  76449. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  76450. strm->msg = (char *)"invalid stored block lengths";
  76451. state->mode = BAD;
  76452. break;
  76453. }
  76454. state->length = (unsigned)hold & 0xffff;
  76455. Tracev((stderr, "inflate: stored length %u\n",
  76456. state->length));
  76457. INITBITS();
  76458. /* copy stored block from input to output */
  76459. while (state->length != 0) {
  76460. copy = state->length;
  76461. PULL();
  76462. ROOM();
  76463. if (copy > have) copy = have;
  76464. if (copy > left) copy = left;
  76465. zmemcpy(put, next, copy);
  76466. have -= copy;
  76467. next += copy;
  76468. left -= copy;
  76469. put += copy;
  76470. state->length -= copy;
  76471. }
  76472. Tracev((stderr, "inflate: stored end\n"));
  76473. state->mode = TYPE;
  76474. break;
  76475. case TABLE:
  76476. /* get dynamic table entries descriptor */
  76477. NEEDBITS(14);
  76478. state->nlen = BITS(5) + 257;
  76479. DROPBITS(5);
  76480. state->ndist = BITS(5) + 1;
  76481. DROPBITS(5);
  76482. state->ncode = BITS(4) + 4;
  76483. DROPBITS(4);
  76484. #ifndef PKZIP_BUG_WORKAROUND
  76485. if (state->nlen > 286 || state->ndist > 30) {
  76486. strm->msg = (char *)"too many length or distance symbols";
  76487. state->mode = BAD;
  76488. break;
  76489. }
  76490. #endif
  76491. Tracev((stderr, "inflate: table sizes ok\n"));
  76492. /* get code length code lengths (not a typo) */
  76493. state->have = 0;
  76494. while (state->have < state->ncode) {
  76495. NEEDBITS(3);
  76496. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  76497. DROPBITS(3);
  76498. }
  76499. while (state->have < 19)
  76500. state->lens[order[state->have++]] = 0;
  76501. state->next = state->codes;
  76502. state->lencode = (code const FAR *)(state->next);
  76503. state->lenbits = 7;
  76504. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  76505. &(state->lenbits), state->work);
  76506. if (ret) {
  76507. strm->msg = (char *)"invalid code lengths set";
  76508. state->mode = BAD;
  76509. break;
  76510. }
  76511. Tracev((stderr, "inflate: code lengths ok\n"));
  76512. /* get length and distance code code lengths */
  76513. state->have = 0;
  76514. while (state->have < state->nlen + state->ndist) {
  76515. for (;;) {
  76516. thisx = state->lencode[BITS(state->lenbits)];
  76517. if ((unsigned)(thisx.bits) <= bits) break;
  76518. PULLBYTE();
  76519. }
  76520. if (thisx.val < 16) {
  76521. NEEDBITS(thisx.bits);
  76522. DROPBITS(thisx.bits);
  76523. state->lens[state->have++] = thisx.val;
  76524. }
  76525. else {
  76526. if (thisx.val == 16) {
  76527. NEEDBITS(thisx.bits + 2);
  76528. DROPBITS(thisx.bits);
  76529. if (state->have == 0) {
  76530. strm->msg = (char *)"invalid bit length repeat";
  76531. state->mode = BAD;
  76532. break;
  76533. }
  76534. len = (unsigned)(state->lens[state->have - 1]);
  76535. copy = 3 + BITS(2);
  76536. DROPBITS(2);
  76537. }
  76538. else if (thisx.val == 17) {
  76539. NEEDBITS(thisx.bits + 3);
  76540. DROPBITS(thisx.bits);
  76541. len = 0;
  76542. copy = 3 + BITS(3);
  76543. DROPBITS(3);
  76544. }
  76545. else {
  76546. NEEDBITS(thisx.bits + 7);
  76547. DROPBITS(thisx.bits);
  76548. len = 0;
  76549. copy = 11 + BITS(7);
  76550. DROPBITS(7);
  76551. }
  76552. if (state->have + copy > state->nlen + state->ndist) {
  76553. strm->msg = (char *)"invalid bit length repeat";
  76554. state->mode = BAD;
  76555. break;
  76556. }
  76557. while (copy--)
  76558. state->lens[state->have++] = (unsigned short)len;
  76559. }
  76560. }
  76561. /* handle error breaks in while */
  76562. if (state->mode == BAD) break;
  76563. /* build code tables */
  76564. state->next = state->codes;
  76565. state->lencode = (code const FAR *)(state->next);
  76566. state->lenbits = 9;
  76567. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  76568. &(state->lenbits), state->work);
  76569. if (ret) {
  76570. strm->msg = (char *)"invalid literal/lengths set";
  76571. state->mode = BAD;
  76572. break;
  76573. }
  76574. state->distcode = (code const FAR *)(state->next);
  76575. state->distbits = 6;
  76576. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  76577. &(state->next), &(state->distbits), state->work);
  76578. if (ret) {
  76579. strm->msg = (char *)"invalid distances set";
  76580. state->mode = BAD;
  76581. break;
  76582. }
  76583. Tracev((stderr, "inflate: codes ok\n"));
  76584. state->mode = LEN;
  76585. case LEN:
  76586. /* use inflate_fast() if we have enough input and output */
  76587. if (have >= 6 && left >= 258) {
  76588. RESTORE();
  76589. if (state->whave < state->wsize)
  76590. state->whave = state->wsize - left;
  76591. inflate_fast(strm, state->wsize);
  76592. LOAD();
  76593. break;
  76594. }
  76595. /* get a literal, length, or end-of-block code */
  76596. for (;;) {
  76597. thisx = state->lencode[BITS(state->lenbits)];
  76598. if ((unsigned)(thisx.bits) <= bits) break;
  76599. PULLBYTE();
  76600. }
  76601. if (thisx.op && (thisx.op & 0xf0) == 0) {
  76602. last = thisx;
  76603. for (;;) {
  76604. thisx = state->lencode[last.val +
  76605. (BITS(last.bits + last.op) >> last.bits)];
  76606. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  76607. PULLBYTE();
  76608. }
  76609. DROPBITS(last.bits);
  76610. }
  76611. DROPBITS(thisx.bits);
  76612. state->length = (unsigned)thisx.val;
  76613. /* process literal */
  76614. if (thisx.op == 0) {
  76615. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  76616. "inflate: literal '%c'\n" :
  76617. "inflate: literal 0x%02x\n", thisx.val));
  76618. ROOM();
  76619. *put++ = (unsigned char)(state->length);
  76620. left--;
  76621. state->mode = LEN;
  76622. break;
  76623. }
  76624. /* process end of block */
  76625. if (thisx.op & 32) {
  76626. Tracevv((stderr, "inflate: end of block\n"));
  76627. state->mode = TYPE;
  76628. break;
  76629. }
  76630. /* invalid code */
  76631. if (thisx.op & 64) {
  76632. strm->msg = (char *)"invalid literal/length code";
  76633. state->mode = BAD;
  76634. break;
  76635. }
  76636. /* length code -- get extra bits, if any */
  76637. state->extra = (unsigned)(thisx.op) & 15;
  76638. if (state->extra != 0) {
  76639. NEEDBITS(state->extra);
  76640. state->length += BITS(state->extra);
  76641. DROPBITS(state->extra);
  76642. }
  76643. Tracevv((stderr, "inflate: length %u\n", state->length));
  76644. /* get distance code */
  76645. for (;;) {
  76646. thisx = state->distcode[BITS(state->distbits)];
  76647. if ((unsigned)(thisx.bits) <= bits) break;
  76648. PULLBYTE();
  76649. }
  76650. if ((thisx.op & 0xf0) == 0) {
  76651. last = thisx;
  76652. for (;;) {
  76653. thisx = state->distcode[last.val +
  76654. (BITS(last.bits + last.op) >> last.bits)];
  76655. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  76656. PULLBYTE();
  76657. }
  76658. DROPBITS(last.bits);
  76659. }
  76660. DROPBITS(thisx.bits);
  76661. if (thisx.op & 64) {
  76662. strm->msg = (char *)"invalid distance code";
  76663. state->mode = BAD;
  76664. break;
  76665. }
  76666. state->offset = (unsigned)thisx.val;
  76667. /* get distance extra bits, if any */
  76668. state->extra = (unsigned)(thisx.op) & 15;
  76669. if (state->extra != 0) {
  76670. NEEDBITS(state->extra);
  76671. state->offset += BITS(state->extra);
  76672. DROPBITS(state->extra);
  76673. }
  76674. if (state->offset > state->wsize - (state->whave < state->wsize ?
  76675. left : 0)) {
  76676. strm->msg = (char *)"invalid distance too far back";
  76677. state->mode = BAD;
  76678. break;
  76679. }
  76680. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  76681. /* copy match from window to output */
  76682. do {
  76683. ROOM();
  76684. copy = state->wsize - state->offset;
  76685. if (copy < left) {
  76686. from = put + copy;
  76687. copy = left - copy;
  76688. }
  76689. else {
  76690. from = put - state->offset;
  76691. copy = left;
  76692. }
  76693. if (copy > state->length) copy = state->length;
  76694. state->length -= copy;
  76695. left -= copy;
  76696. do {
  76697. *put++ = *from++;
  76698. } while (--copy);
  76699. } while (state->length != 0);
  76700. break;
  76701. case DONE:
  76702. /* inflate stream terminated properly -- write leftover output */
  76703. ret = Z_STREAM_END;
  76704. if (left < state->wsize) {
  76705. if (out(out_desc, state->window, state->wsize - left))
  76706. ret = Z_BUF_ERROR;
  76707. }
  76708. goto inf_leave;
  76709. case BAD:
  76710. ret = Z_DATA_ERROR;
  76711. goto inf_leave;
  76712. default: /* can't happen, but makes compilers happy */
  76713. ret = Z_STREAM_ERROR;
  76714. goto inf_leave;
  76715. }
  76716. /* Return unused input */
  76717. inf_leave:
  76718. strm->next_in = next;
  76719. strm->avail_in = have;
  76720. return ret;
  76721. }
  76722. int ZEXPORT inflateBackEnd (z_streamp strm)
  76723. {
  76724. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  76725. return Z_STREAM_ERROR;
  76726. ZFREE(strm, strm->state);
  76727. strm->state = Z_NULL;
  76728. Tracev((stderr, "inflate: end\n"));
  76729. return Z_OK;
  76730. }
  76731. /********* End of inlined file: infback.c *********/
  76732. /********* Start of inlined file: inffast.c *********/
  76733. /********* Start of inlined file: inffast.h *********/
  76734. /* WARNING: this file should *not* be used by applications. It is
  76735. part of the implementation of the compression library and is
  76736. subject to change. Applications should only use zlib.h.
  76737. */
  76738. void inflate_fast OF((z_streamp strm, unsigned start));
  76739. /********* End of inlined file: inffast.h *********/
  76740. #ifndef ASMINF
  76741. /* Allow machine dependent optimization for post-increment or pre-increment.
  76742. Based on testing to date,
  76743. Pre-increment preferred for:
  76744. - PowerPC G3 (Adler)
  76745. - MIPS R5000 (Randers-Pehrson)
  76746. Post-increment preferred for:
  76747. - none
  76748. No measurable difference:
  76749. - Pentium III (Anderson)
  76750. - M68060 (Nikl)
  76751. */
  76752. #ifdef POSTINC
  76753. # define OFF 0
  76754. # define PUP(a) *(a)++
  76755. #else
  76756. # define OFF 1
  76757. # define PUP(a) *++(a)
  76758. #endif
  76759. /*
  76760. Decode literal, length, and distance codes and write out the resulting
  76761. literal and match bytes until either not enough input or output is
  76762. available, an end-of-block is encountered, or a data error is encountered.
  76763. When large enough input and output buffers are supplied to inflate(), for
  76764. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  76765. inflate execution time is spent in this routine.
  76766. Entry assumptions:
  76767. state->mode == LEN
  76768. strm->avail_in >= 6
  76769. strm->avail_out >= 258
  76770. start >= strm->avail_out
  76771. state->bits < 8
  76772. On return, state->mode is one of:
  76773. LEN -- ran out of enough output space or enough available input
  76774. TYPE -- reached end of block code, inflate() to interpret next block
  76775. BAD -- error in block data
  76776. Notes:
  76777. - The maximum input bits used by a length/distance pair is 15 bits for the
  76778. length code, 5 bits for the length extra, 15 bits for the distance code,
  76779. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  76780. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  76781. checking for available input while decoding.
  76782. - The maximum bytes that a single length/distance pair can output is 258
  76783. bytes, which is the maximum length that can be coded. inflate_fast()
  76784. requires strm->avail_out >= 258 for each loop to avoid checking for
  76785. output space.
  76786. */
  76787. void inflate_fast (z_streamp strm, unsigned start)
  76788. {
  76789. struct inflate_state FAR *state;
  76790. unsigned char FAR *in; /* local strm->next_in */
  76791. unsigned char FAR *last; /* while in < last, enough input available */
  76792. unsigned char FAR *out; /* local strm->next_out */
  76793. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  76794. unsigned char FAR *end; /* while out < end, enough space available */
  76795. #ifdef INFLATE_STRICT
  76796. unsigned dmax; /* maximum distance from zlib header */
  76797. #endif
  76798. unsigned wsize; /* window size or zero if not using window */
  76799. unsigned whave; /* valid bytes in the window */
  76800. unsigned write; /* window write index */
  76801. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  76802. unsigned long hold; /* local strm->hold */
  76803. unsigned bits; /* local strm->bits */
  76804. code const FAR *lcode; /* local strm->lencode */
  76805. code const FAR *dcode; /* local strm->distcode */
  76806. unsigned lmask; /* mask for first level of length codes */
  76807. unsigned dmask; /* mask for first level of distance codes */
  76808. code thisx; /* retrieved table entry */
  76809. unsigned op; /* code bits, operation, extra bits, or */
  76810. /* window position, window bytes to copy */
  76811. unsigned len; /* match length, unused bytes */
  76812. unsigned dist; /* match distance */
  76813. unsigned char FAR *from; /* where to copy match from */
  76814. /* copy state to local variables */
  76815. state = (struct inflate_state FAR *)strm->state;
  76816. in = strm->next_in - OFF;
  76817. last = in + (strm->avail_in - 5);
  76818. out = strm->next_out - OFF;
  76819. beg = out - (start - strm->avail_out);
  76820. end = out + (strm->avail_out - 257);
  76821. #ifdef INFLATE_STRICT
  76822. dmax = state->dmax;
  76823. #endif
  76824. wsize = state->wsize;
  76825. whave = state->whave;
  76826. write = state->write;
  76827. window = state->window;
  76828. hold = state->hold;
  76829. bits = state->bits;
  76830. lcode = state->lencode;
  76831. dcode = state->distcode;
  76832. lmask = (1U << state->lenbits) - 1;
  76833. dmask = (1U << state->distbits) - 1;
  76834. /* decode literals and length/distances until end-of-block or not enough
  76835. input data or output space */
  76836. do {
  76837. if (bits < 15) {
  76838. hold += (unsigned long)(PUP(in)) << bits;
  76839. bits += 8;
  76840. hold += (unsigned long)(PUP(in)) << bits;
  76841. bits += 8;
  76842. }
  76843. thisx = lcode[hold & lmask];
  76844. dolen:
  76845. op = (unsigned)(thisx.bits);
  76846. hold >>= op;
  76847. bits -= op;
  76848. op = (unsigned)(thisx.op);
  76849. if (op == 0) { /* literal */
  76850. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  76851. "inflate: literal '%c'\n" :
  76852. "inflate: literal 0x%02x\n", thisx.val));
  76853. PUP(out) = (unsigned char)(thisx.val);
  76854. }
  76855. else if (op & 16) { /* length base */
  76856. len = (unsigned)(thisx.val);
  76857. op &= 15; /* number of extra bits */
  76858. if (op) {
  76859. if (bits < op) {
  76860. hold += (unsigned long)(PUP(in)) << bits;
  76861. bits += 8;
  76862. }
  76863. len += (unsigned)hold & ((1U << op) - 1);
  76864. hold >>= op;
  76865. bits -= op;
  76866. }
  76867. Tracevv((stderr, "inflate: length %u\n", len));
  76868. if (bits < 15) {
  76869. hold += (unsigned long)(PUP(in)) << bits;
  76870. bits += 8;
  76871. hold += (unsigned long)(PUP(in)) << bits;
  76872. bits += 8;
  76873. }
  76874. thisx = dcode[hold & dmask];
  76875. dodist:
  76876. op = (unsigned)(thisx.bits);
  76877. hold >>= op;
  76878. bits -= op;
  76879. op = (unsigned)(thisx.op);
  76880. if (op & 16) { /* distance base */
  76881. dist = (unsigned)(thisx.val);
  76882. op &= 15; /* number of extra bits */
  76883. if (bits < op) {
  76884. hold += (unsigned long)(PUP(in)) << bits;
  76885. bits += 8;
  76886. if (bits < op) {
  76887. hold += (unsigned long)(PUP(in)) << bits;
  76888. bits += 8;
  76889. }
  76890. }
  76891. dist += (unsigned)hold & ((1U << op) - 1);
  76892. #ifdef INFLATE_STRICT
  76893. if (dist > dmax) {
  76894. strm->msg = (char *)"invalid distance too far back";
  76895. state->mode = BAD;
  76896. break;
  76897. }
  76898. #endif
  76899. hold >>= op;
  76900. bits -= op;
  76901. Tracevv((stderr, "inflate: distance %u\n", dist));
  76902. op = (unsigned)(out - beg); /* max distance in output */
  76903. if (dist > op) { /* see if copy from window */
  76904. op = dist - op; /* distance back in window */
  76905. if (op > whave) {
  76906. strm->msg = (char *)"invalid distance too far back";
  76907. state->mode = BAD;
  76908. break;
  76909. }
  76910. from = window - OFF;
  76911. if (write == 0) { /* very common case */
  76912. from += wsize - op;
  76913. if (op < len) { /* some from window */
  76914. len -= op;
  76915. do {
  76916. PUP(out) = PUP(from);
  76917. } while (--op);
  76918. from = out - dist; /* rest from output */
  76919. }
  76920. }
  76921. else if (write < op) { /* wrap around window */
  76922. from += wsize + write - op;
  76923. op -= write;
  76924. if (op < len) { /* some from end of window */
  76925. len -= op;
  76926. do {
  76927. PUP(out) = PUP(from);
  76928. } while (--op);
  76929. from = window - OFF;
  76930. if (write < len) { /* some from start of window */
  76931. op = write;
  76932. len -= op;
  76933. do {
  76934. PUP(out) = PUP(from);
  76935. } while (--op);
  76936. from = out - dist; /* rest from output */
  76937. }
  76938. }
  76939. }
  76940. else { /* contiguous in window */
  76941. from += write - op;
  76942. if (op < len) { /* some from window */
  76943. len -= op;
  76944. do {
  76945. PUP(out) = PUP(from);
  76946. } while (--op);
  76947. from = out - dist; /* rest from output */
  76948. }
  76949. }
  76950. while (len > 2) {
  76951. PUP(out) = PUP(from);
  76952. PUP(out) = PUP(from);
  76953. PUP(out) = PUP(from);
  76954. len -= 3;
  76955. }
  76956. if (len) {
  76957. PUP(out) = PUP(from);
  76958. if (len > 1)
  76959. PUP(out) = PUP(from);
  76960. }
  76961. }
  76962. else {
  76963. from = out - dist; /* copy direct from output */
  76964. do { /* minimum length is three */
  76965. PUP(out) = PUP(from);
  76966. PUP(out) = PUP(from);
  76967. PUP(out) = PUP(from);
  76968. len -= 3;
  76969. } while (len > 2);
  76970. if (len) {
  76971. PUP(out) = PUP(from);
  76972. if (len > 1)
  76973. PUP(out) = PUP(from);
  76974. }
  76975. }
  76976. }
  76977. else if ((op & 64) == 0) { /* 2nd level distance code */
  76978. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  76979. goto dodist;
  76980. }
  76981. else {
  76982. strm->msg = (char *)"invalid distance code";
  76983. state->mode = BAD;
  76984. break;
  76985. }
  76986. }
  76987. else if ((op & 64) == 0) { /* 2nd level length code */
  76988. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  76989. goto dolen;
  76990. }
  76991. else if (op & 32) { /* end-of-block */
  76992. Tracevv((stderr, "inflate: end of block\n"));
  76993. state->mode = TYPE;
  76994. break;
  76995. }
  76996. else {
  76997. strm->msg = (char *)"invalid literal/length code";
  76998. state->mode = BAD;
  76999. break;
  77000. }
  77001. } while (in < last && out < end);
  77002. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  77003. len = bits >> 3;
  77004. in -= len;
  77005. bits -= len << 3;
  77006. hold &= (1U << bits) - 1;
  77007. /* update state and return */
  77008. strm->next_in = in + OFF;
  77009. strm->next_out = out + OFF;
  77010. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  77011. strm->avail_out = (unsigned)(out < end ?
  77012. 257 + (end - out) : 257 - (out - end));
  77013. state->hold = hold;
  77014. state->bits = bits;
  77015. return;
  77016. }
  77017. /*
  77018. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  77019. - Using bit fields for code structure
  77020. - Different op definition to avoid & for extra bits (do & for table bits)
  77021. - Three separate decoding do-loops for direct, window, and write == 0
  77022. - Special case for distance > 1 copies to do overlapped load and store copy
  77023. - Explicit branch predictions (based on measured branch probabilities)
  77024. - Deferring match copy and interspersed it with decoding subsequent codes
  77025. - Swapping literal/length else
  77026. - Swapping window/direct else
  77027. - Larger unrolled copy loops (three is about right)
  77028. - Moving len -= 3 statement into middle of loop
  77029. */
  77030. #endif /* !ASMINF */
  77031. /********* End of inlined file: inffast.c *********/
  77032. #undef PULLBYTE
  77033. #undef LOAD
  77034. #undef RESTORE
  77035. #undef INITBITS
  77036. #undef NEEDBITS
  77037. #undef DROPBITS
  77038. #undef BYTEBITS
  77039. /********* Start of inlined file: inflate.c *********/
  77040. /*
  77041. * Change history:
  77042. *
  77043. * 1.2.beta0 24 Nov 2002
  77044. * - First version -- complete rewrite of inflate to simplify code, avoid
  77045. * creation of window when not needed, minimize use of window when it is
  77046. * needed, make inffast.c even faster, implement gzip decoding, and to
  77047. * improve code readability and style over the previous zlib inflate code
  77048. *
  77049. * 1.2.beta1 25 Nov 2002
  77050. * - Use pointers for available input and output checking in inffast.c
  77051. * - Remove input and output counters in inffast.c
  77052. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  77053. * - Remove unnecessary second byte pull from length extra in inffast.c
  77054. * - Unroll direct copy to three copies per loop in inffast.c
  77055. *
  77056. * 1.2.beta2 4 Dec 2002
  77057. * - Change external routine names to reduce potential conflicts
  77058. * - Correct filename to inffixed.h for fixed tables in inflate.c
  77059. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  77060. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  77061. * to avoid negation problem on Alphas (64 bit) in inflate.c
  77062. *
  77063. * 1.2.beta3 22 Dec 2002
  77064. * - Add comments on state->bits assertion in inffast.c
  77065. * - Add comments on op field in inftrees.h
  77066. * - Fix bug in reuse of allocated window after inflateReset()
  77067. * - Remove bit fields--back to byte structure for speed
  77068. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  77069. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  77070. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  77071. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  77072. * - Use local copies of stream next and avail values, as well as local bit
  77073. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  77074. *
  77075. * 1.2.beta4 1 Jan 2003
  77076. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  77077. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  77078. * - Add comments in inffast.c to introduce the inflate_fast() routine
  77079. * - Rearrange window copies in inflate_fast() for speed and simplification
  77080. * - Unroll last copy for window match in inflate_fast()
  77081. * - Use local copies of window variables in inflate_fast() for speed
  77082. * - Pull out common write == 0 case for speed in inflate_fast()
  77083. * - Make op and len in inflate_fast() unsigned for consistency
  77084. * - Add FAR to lcode and dcode declarations in inflate_fast()
  77085. * - Simplified bad distance check in inflate_fast()
  77086. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  77087. * source file infback.c to provide a call-back interface to inflate for
  77088. * programs like gzip and unzip -- uses window as output buffer to avoid
  77089. * window copying
  77090. *
  77091. * 1.2.beta5 1 Jan 2003
  77092. * - Improved inflateBack() interface to allow the caller to provide initial
  77093. * input in strm.
  77094. * - Fixed stored blocks bug in inflateBack()
  77095. *
  77096. * 1.2.beta6 4 Jan 2003
  77097. * - Added comments in inffast.c on effectiveness of POSTINC
  77098. * - Typecasting all around to reduce compiler warnings
  77099. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  77100. * make compilers happy
  77101. * - Changed type of window in inflateBackInit() to unsigned char *
  77102. *
  77103. * 1.2.beta7 27 Jan 2003
  77104. * - Changed many types to unsigned or unsigned short to avoid warnings
  77105. * - Added inflateCopy() function
  77106. *
  77107. * 1.2.0 9 Mar 2003
  77108. * - Changed inflateBack() interface to provide separate opaque descriptors
  77109. * for the in() and out() functions
  77110. * - Changed inflateBack() argument and in_func typedef to swap the length
  77111. * and buffer address return values for the input function
  77112. * - Check next_in and next_out for Z_NULL on entry to inflate()
  77113. *
  77114. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  77115. */
  77116. /********* Start of inlined file: inffast.h *********/
  77117. /* WARNING: this file should *not* be used by applications. It is
  77118. part of the implementation of the compression library and is
  77119. subject to change. Applications should only use zlib.h.
  77120. */
  77121. void inflate_fast OF((z_streamp strm, unsigned start));
  77122. /********* End of inlined file: inffast.h *********/
  77123. #ifdef MAKEFIXED
  77124. # ifndef BUILDFIXED
  77125. # define BUILDFIXED
  77126. # endif
  77127. #endif
  77128. /* function prototypes */
  77129. local void fixedtables OF((struct inflate_state FAR *state));
  77130. local int updatewindow OF((z_streamp strm, unsigned out));
  77131. #ifdef BUILDFIXED
  77132. void makefixed OF((void));
  77133. #endif
  77134. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  77135. unsigned len));
  77136. int ZEXPORT inflateReset (z_streamp strm)
  77137. {
  77138. struct inflate_state FAR *state;
  77139. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77140. state = (struct inflate_state FAR *)strm->state;
  77141. strm->total_in = strm->total_out = state->total = 0;
  77142. strm->msg = Z_NULL;
  77143. strm->adler = 1; /* to support ill-conceived Java test suite */
  77144. state->mode = HEAD;
  77145. state->last = 0;
  77146. state->havedict = 0;
  77147. state->dmax = 32768U;
  77148. state->head = Z_NULL;
  77149. state->wsize = 0;
  77150. state->whave = 0;
  77151. state->write = 0;
  77152. state->hold = 0;
  77153. state->bits = 0;
  77154. state->lencode = state->distcode = state->next = state->codes;
  77155. Tracev((stderr, "inflate: reset\n"));
  77156. return Z_OK;
  77157. }
  77158. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  77159. {
  77160. struct inflate_state FAR *state;
  77161. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77162. state = (struct inflate_state FAR *)strm->state;
  77163. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  77164. value &= (1L << bits) - 1;
  77165. state->hold += value << state->bits;
  77166. state->bits += bits;
  77167. return Z_OK;
  77168. }
  77169. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  77170. {
  77171. struct inflate_state FAR *state;
  77172. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  77173. stream_size != (int)(sizeof(z_stream)))
  77174. return Z_VERSION_ERROR;
  77175. if (strm == Z_NULL) return Z_STREAM_ERROR;
  77176. strm->msg = Z_NULL; /* in case we return an error */
  77177. if (strm->zalloc == (alloc_func)0) {
  77178. strm->zalloc = zcalloc;
  77179. strm->opaque = (voidpf)0;
  77180. }
  77181. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  77182. state = (struct inflate_state FAR *)
  77183. ZALLOC(strm, 1, sizeof(struct inflate_state));
  77184. if (state == Z_NULL) return Z_MEM_ERROR;
  77185. Tracev((stderr, "inflate: allocated\n"));
  77186. strm->state = (struct internal_state FAR *)state;
  77187. if (windowBits < 0) {
  77188. state->wrap = 0;
  77189. windowBits = -windowBits;
  77190. }
  77191. else {
  77192. state->wrap = (windowBits >> 4) + 1;
  77193. #ifdef GUNZIP
  77194. if (windowBits < 48) windowBits &= 15;
  77195. #endif
  77196. }
  77197. if (windowBits < 8 || windowBits > 15) {
  77198. ZFREE(strm, state);
  77199. strm->state = Z_NULL;
  77200. return Z_STREAM_ERROR;
  77201. }
  77202. state->wbits = (unsigned)windowBits;
  77203. state->window = Z_NULL;
  77204. return inflateReset(strm);
  77205. }
  77206. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  77207. {
  77208. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  77209. }
  77210. /*
  77211. Return state with length and distance decoding tables and index sizes set to
  77212. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  77213. If BUILDFIXED is defined, then instead this routine builds the tables the
  77214. first time it's called, and returns those tables the first time and
  77215. thereafter. This reduces the size of the code by about 2K bytes, in
  77216. exchange for a little execution time. However, BUILDFIXED should not be
  77217. used for threaded applications, since the rewriting of the tables and virgin
  77218. may not be thread-safe.
  77219. */
  77220. local void fixedtables (struct inflate_state FAR *state)
  77221. {
  77222. #ifdef BUILDFIXED
  77223. static int virgin = 1;
  77224. static code *lenfix, *distfix;
  77225. static code fixed[544];
  77226. /* build fixed huffman tables if first call (may not be thread safe) */
  77227. if (virgin) {
  77228. unsigned sym, bits;
  77229. static code *next;
  77230. /* literal/length table */
  77231. sym = 0;
  77232. while (sym < 144) state->lens[sym++] = 8;
  77233. while (sym < 256) state->lens[sym++] = 9;
  77234. while (sym < 280) state->lens[sym++] = 7;
  77235. while (sym < 288) state->lens[sym++] = 8;
  77236. next = fixed;
  77237. lenfix = next;
  77238. bits = 9;
  77239. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  77240. /* distance table */
  77241. sym = 0;
  77242. while (sym < 32) state->lens[sym++] = 5;
  77243. distfix = next;
  77244. bits = 5;
  77245. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  77246. /* do this just once */
  77247. virgin = 0;
  77248. }
  77249. #else /* !BUILDFIXED */
  77250. /********* Start of inlined file: inffixed.h *********/
  77251. /* inffixed.h -- table for decoding fixed codes
  77252. * Generated automatically by makefixed().
  77253. */
  77254. /* WARNING: this file should *not* be used by applications. It
  77255. is part of the implementation of the compression library and
  77256. is subject to change. Applications should only use zlib.h.
  77257. */
  77258. static const code lenfix[512] = {
  77259. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  77260. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  77261. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  77262. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  77263. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  77264. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  77265. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  77266. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  77267. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  77268. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  77269. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  77270. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  77271. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  77272. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  77273. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  77274. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  77275. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  77276. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  77277. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  77278. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  77279. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  77280. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  77281. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  77282. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  77283. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  77284. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  77285. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  77286. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  77287. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  77288. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  77289. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  77290. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  77291. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  77292. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  77293. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  77294. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  77295. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  77296. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  77297. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  77298. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  77299. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  77300. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  77301. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  77302. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  77303. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  77304. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  77305. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  77306. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  77307. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  77308. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  77309. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  77310. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  77311. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  77312. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  77313. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  77314. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  77315. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  77316. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  77317. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  77318. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  77319. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  77320. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  77321. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  77322. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  77323. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  77324. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  77325. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  77326. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  77327. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  77328. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  77329. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  77330. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  77331. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  77332. {0,9,255}
  77333. };
  77334. static const code distfix[32] = {
  77335. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  77336. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  77337. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  77338. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  77339. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  77340. {22,5,193},{64,5,0}
  77341. };
  77342. /********* End of inlined file: inffixed.h *********/
  77343. #endif /* BUILDFIXED */
  77344. state->lencode = lenfix;
  77345. state->lenbits = 9;
  77346. state->distcode = distfix;
  77347. state->distbits = 5;
  77348. }
  77349. #ifdef MAKEFIXED
  77350. #include <stdio.h>
  77351. /*
  77352. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  77353. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  77354. those tables to stdout, which would be piped to inffixed.h. A small program
  77355. can simply call makefixed to do this:
  77356. void makefixed(void);
  77357. int main(void)
  77358. {
  77359. makefixed();
  77360. return 0;
  77361. }
  77362. Then that can be linked with zlib built with MAKEFIXED defined and run:
  77363. a.out > inffixed.h
  77364. */
  77365. void makefixed()
  77366. {
  77367. unsigned low, size;
  77368. struct inflate_state state;
  77369. fixedtables(&state);
  77370. puts(" /* inffixed.h -- table for decoding fixed codes");
  77371. puts(" * Generated automatically by makefixed().");
  77372. puts(" */");
  77373. puts("");
  77374. puts(" /* WARNING: this file should *not* be used by applications.");
  77375. puts(" It is part of the implementation of this library and is");
  77376. puts(" subject to change. Applications should only use zlib.h.");
  77377. puts(" */");
  77378. puts("");
  77379. size = 1U << 9;
  77380. printf(" static const code lenfix[%u] = {", size);
  77381. low = 0;
  77382. for (;;) {
  77383. if ((low % 7) == 0) printf("\n ");
  77384. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  77385. state.lencode[low].val);
  77386. if (++low == size) break;
  77387. putchar(',');
  77388. }
  77389. puts("\n };");
  77390. size = 1U << 5;
  77391. printf("\n static const code distfix[%u] = {", size);
  77392. low = 0;
  77393. for (;;) {
  77394. if ((low % 6) == 0) printf("\n ");
  77395. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  77396. state.distcode[low].val);
  77397. if (++low == size) break;
  77398. putchar(',');
  77399. }
  77400. puts("\n };");
  77401. }
  77402. #endif /* MAKEFIXED */
  77403. /*
  77404. Update the window with the last wsize (normally 32K) bytes written before
  77405. returning. If window does not exist yet, create it. This is only called
  77406. when a window is already in use, or when output has been written during this
  77407. inflate call, but the end of the deflate stream has not been reached yet.
  77408. It is also called to create a window for dictionary data when a dictionary
  77409. is loaded.
  77410. Providing output buffers larger than 32K to inflate() should provide a speed
  77411. advantage, since only the last 32K of output is copied to the sliding window
  77412. upon return from inflate(), and since all distances after the first 32K of
  77413. output will fall in the output data, making match copies simpler and faster.
  77414. The advantage may be dependent on the size of the processor's data caches.
  77415. */
  77416. local int updatewindow (z_streamp strm, unsigned out)
  77417. {
  77418. struct inflate_state FAR *state;
  77419. unsigned copy, dist;
  77420. state = (struct inflate_state FAR *)strm->state;
  77421. /* if it hasn't been done already, allocate space for the window */
  77422. if (state->window == Z_NULL) {
  77423. state->window = (unsigned char FAR *)
  77424. ZALLOC(strm, 1U << state->wbits,
  77425. sizeof(unsigned char));
  77426. if (state->window == Z_NULL) return 1;
  77427. }
  77428. /* if window not in use yet, initialize */
  77429. if (state->wsize == 0) {
  77430. state->wsize = 1U << state->wbits;
  77431. state->write = 0;
  77432. state->whave = 0;
  77433. }
  77434. /* copy state->wsize or less output bytes into the circular window */
  77435. copy = out - strm->avail_out;
  77436. if (copy >= state->wsize) {
  77437. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  77438. state->write = 0;
  77439. state->whave = state->wsize;
  77440. }
  77441. else {
  77442. dist = state->wsize - state->write;
  77443. if (dist > copy) dist = copy;
  77444. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  77445. copy -= dist;
  77446. if (copy) {
  77447. zmemcpy(state->window, strm->next_out - copy, copy);
  77448. state->write = copy;
  77449. state->whave = state->wsize;
  77450. }
  77451. else {
  77452. state->write += dist;
  77453. if (state->write == state->wsize) state->write = 0;
  77454. if (state->whave < state->wsize) state->whave += dist;
  77455. }
  77456. }
  77457. return 0;
  77458. }
  77459. /* Macros for inflate(): */
  77460. /* check function to use adler32() for zlib or crc32() for gzip */
  77461. #ifdef GUNZIP
  77462. # define UPDATE(check, buf, len) \
  77463. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  77464. #else
  77465. # define UPDATE(check, buf, len) adler32(check, buf, len)
  77466. #endif
  77467. /* check macros for header crc */
  77468. #ifdef GUNZIP
  77469. # define CRC2(check, word) \
  77470. do { \
  77471. hbuf[0] = (unsigned char)(word); \
  77472. hbuf[1] = (unsigned char)((word) >> 8); \
  77473. check = crc32(check, hbuf, 2); \
  77474. } while (0)
  77475. # define CRC4(check, word) \
  77476. do { \
  77477. hbuf[0] = (unsigned char)(word); \
  77478. hbuf[1] = (unsigned char)((word) >> 8); \
  77479. hbuf[2] = (unsigned char)((word) >> 16); \
  77480. hbuf[3] = (unsigned char)((word) >> 24); \
  77481. check = crc32(check, hbuf, 4); \
  77482. } while (0)
  77483. #endif
  77484. /* Load registers with state in inflate() for speed */
  77485. #define LOAD() \
  77486. do { \
  77487. put = strm->next_out; \
  77488. left = strm->avail_out; \
  77489. next = strm->next_in; \
  77490. have = strm->avail_in; \
  77491. hold = state->hold; \
  77492. bits = state->bits; \
  77493. } while (0)
  77494. /* Restore state from registers in inflate() */
  77495. #define RESTORE() \
  77496. do { \
  77497. strm->next_out = put; \
  77498. strm->avail_out = left; \
  77499. strm->next_in = next; \
  77500. strm->avail_in = have; \
  77501. state->hold = hold; \
  77502. state->bits = bits; \
  77503. } while (0)
  77504. /* Clear the input bit accumulator */
  77505. #define INITBITS() \
  77506. do { \
  77507. hold = 0; \
  77508. bits = 0; \
  77509. } while (0)
  77510. /* Get a byte of input into the bit accumulator, or return from inflate()
  77511. if there is no input available. */
  77512. #define PULLBYTE() \
  77513. do { \
  77514. if (have == 0) goto inf_leave; \
  77515. have--; \
  77516. hold += (unsigned long)(*next++) << bits; \
  77517. bits += 8; \
  77518. } while (0)
  77519. /* Assure that there are at least n bits in the bit accumulator. If there is
  77520. not enough available input to do that, then return from inflate(). */
  77521. #define NEEDBITS(n) \
  77522. do { \
  77523. while (bits < (unsigned)(n)) \
  77524. PULLBYTE(); \
  77525. } while (0)
  77526. /* Return the low n bits of the bit accumulator (n < 16) */
  77527. #define BITS(n) \
  77528. ((unsigned)hold & ((1U << (n)) - 1))
  77529. /* Remove n bits from the bit accumulator */
  77530. #define DROPBITS(n) \
  77531. do { \
  77532. hold >>= (n); \
  77533. bits -= (unsigned)(n); \
  77534. } while (0)
  77535. /* Remove zero to seven bits as needed to go to a byte boundary */
  77536. #define BYTEBITS() \
  77537. do { \
  77538. hold >>= bits & 7; \
  77539. bits -= bits & 7; \
  77540. } while (0)
  77541. /* Reverse the bytes in a 32-bit value */
  77542. #define REVERSE(q) \
  77543. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  77544. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  77545. /*
  77546. inflate() uses a state machine to process as much input data and generate as
  77547. much output data as possible before returning. The state machine is
  77548. structured roughly as follows:
  77549. for (;;) switch (state) {
  77550. ...
  77551. case STATEn:
  77552. if (not enough input data or output space to make progress)
  77553. return;
  77554. ... make progress ...
  77555. state = STATEm;
  77556. break;
  77557. ...
  77558. }
  77559. so when inflate() is called again, the same case is attempted again, and
  77560. if the appropriate resources are provided, the machine proceeds to the
  77561. next state. The NEEDBITS() macro is usually the way the state evaluates
  77562. whether it can proceed or should return. NEEDBITS() does the return if
  77563. the requested bits are not available. The typical use of the BITS macros
  77564. is:
  77565. NEEDBITS(n);
  77566. ... do something with BITS(n) ...
  77567. DROPBITS(n);
  77568. where NEEDBITS(n) either returns from inflate() if there isn't enough
  77569. input left to load n bits into the accumulator, or it continues. BITS(n)
  77570. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  77571. the low n bits off the accumulator. INITBITS() clears the accumulator
  77572. and sets the number of available bits to zero. BYTEBITS() discards just
  77573. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  77574. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  77575. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  77576. if there is no input available. The decoding of variable length codes uses
  77577. PULLBYTE() directly in order to pull just enough bytes to decode the next
  77578. code, and no more.
  77579. Some states loop until they get enough input, making sure that enough
  77580. state information is maintained to continue the loop where it left off
  77581. if NEEDBITS() returns in the loop. For example, want, need, and keep
  77582. would all have to actually be part of the saved state in case NEEDBITS()
  77583. returns:
  77584. case STATEw:
  77585. while (want < need) {
  77586. NEEDBITS(n);
  77587. keep[want++] = BITS(n);
  77588. DROPBITS(n);
  77589. }
  77590. state = STATEx;
  77591. case STATEx:
  77592. As shown above, if the next state is also the next case, then the break
  77593. is omitted.
  77594. A state may also return if there is not enough output space available to
  77595. complete that state. Those states are copying stored data, writing a
  77596. literal byte, and copying a matching string.
  77597. When returning, a "goto inf_leave" is used to update the total counters,
  77598. update the check value, and determine whether any progress has been made
  77599. during that inflate() call in order to return the proper return code.
  77600. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  77601. When there is a window, goto inf_leave will update the window with the last
  77602. output written. If a goto inf_leave occurs in the middle of decompression
  77603. and there is no window currently, goto inf_leave will create one and copy
  77604. output to the window for the next call of inflate().
  77605. In this implementation, the flush parameter of inflate() only affects the
  77606. return code (per zlib.h). inflate() always writes as much as possible to
  77607. strm->next_out, given the space available and the provided input--the effect
  77608. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  77609. the allocation of and copying into a sliding window until necessary, which
  77610. provides the effect documented in zlib.h for Z_FINISH when the entire input
  77611. stream available. So the only thing the flush parameter actually does is:
  77612. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  77613. will return Z_BUF_ERROR if it has not reached the end of the stream.
  77614. */
  77615. int ZEXPORT inflate (z_streamp strm, int flush)
  77616. {
  77617. struct inflate_state FAR *state;
  77618. unsigned char FAR *next; /* next input */
  77619. unsigned char FAR *put; /* next output */
  77620. unsigned have, left; /* available input and output */
  77621. unsigned long hold; /* bit buffer */
  77622. unsigned bits; /* bits in bit buffer */
  77623. unsigned in, out; /* save starting available input and output */
  77624. unsigned copy; /* number of stored or match bytes to copy */
  77625. unsigned char FAR *from; /* where to copy match bytes from */
  77626. code thisx; /* current decoding table entry */
  77627. code last; /* parent table entry */
  77628. unsigned len; /* length to copy for repeats, bits to drop */
  77629. int ret; /* return code */
  77630. #ifdef GUNZIP
  77631. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  77632. #endif
  77633. static const unsigned short order[19] = /* permutation of code lengths */
  77634. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  77635. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  77636. (strm->next_in == Z_NULL && strm->avail_in != 0))
  77637. return Z_STREAM_ERROR;
  77638. state = (struct inflate_state FAR *)strm->state;
  77639. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  77640. LOAD();
  77641. in = have;
  77642. out = left;
  77643. ret = Z_OK;
  77644. for (;;)
  77645. switch (state->mode) {
  77646. case HEAD:
  77647. if (state->wrap == 0) {
  77648. state->mode = TYPEDO;
  77649. break;
  77650. }
  77651. NEEDBITS(16);
  77652. #ifdef GUNZIP
  77653. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  77654. state->check = crc32(0L, Z_NULL, 0);
  77655. CRC2(state->check, hold);
  77656. INITBITS();
  77657. state->mode = FLAGS;
  77658. break;
  77659. }
  77660. state->flags = 0; /* expect zlib header */
  77661. if (state->head != Z_NULL)
  77662. state->head->done = -1;
  77663. if (!(state->wrap & 1) || /* check if zlib header allowed */
  77664. #else
  77665. if (
  77666. #endif
  77667. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  77668. strm->msg = (char *)"incorrect header check";
  77669. state->mode = BAD;
  77670. break;
  77671. }
  77672. if (BITS(4) != Z_DEFLATED) {
  77673. strm->msg = (char *)"unknown compression method";
  77674. state->mode = BAD;
  77675. break;
  77676. }
  77677. DROPBITS(4);
  77678. len = BITS(4) + 8;
  77679. if (len > state->wbits) {
  77680. strm->msg = (char *)"invalid window size";
  77681. state->mode = BAD;
  77682. break;
  77683. }
  77684. state->dmax = 1U << len;
  77685. Tracev((stderr, "inflate: zlib header ok\n"));
  77686. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  77687. state->mode = hold & 0x200 ? DICTID : TYPE;
  77688. INITBITS();
  77689. break;
  77690. #ifdef GUNZIP
  77691. case FLAGS:
  77692. NEEDBITS(16);
  77693. state->flags = (int)(hold);
  77694. if ((state->flags & 0xff) != Z_DEFLATED) {
  77695. strm->msg = (char *)"unknown compression method";
  77696. state->mode = BAD;
  77697. break;
  77698. }
  77699. if (state->flags & 0xe000) {
  77700. strm->msg = (char *)"unknown header flags set";
  77701. state->mode = BAD;
  77702. break;
  77703. }
  77704. if (state->head != Z_NULL)
  77705. state->head->text = (int)((hold >> 8) & 1);
  77706. if (state->flags & 0x0200) CRC2(state->check, hold);
  77707. INITBITS();
  77708. state->mode = TIME;
  77709. case TIME:
  77710. NEEDBITS(32);
  77711. if (state->head != Z_NULL)
  77712. state->head->time = hold;
  77713. if (state->flags & 0x0200) CRC4(state->check, hold);
  77714. INITBITS();
  77715. state->mode = OS;
  77716. case OS:
  77717. NEEDBITS(16);
  77718. if (state->head != Z_NULL) {
  77719. state->head->xflags = (int)(hold & 0xff);
  77720. state->head->os = (int)(hold >> 8);
  77721. }
  77722. if (state->flags & 0x0200) CRC2(state->check, hold);
  77723. INITBITS();
  77724. state->mode = EXLEN;
  77725. case EXLEN:
  77726. if (state->flags & 0x0400) {
  77727. NEEDBITS(16);
  77728. state->length = (unsigned)(hold);
  77729. if (state->head != Z_NULL)
  77730. state->head->extra_len = (unsigned)hold;
  77731. if (state->flags & 0x0200) CRC2(state->check, hold);
  77732. INITBITS();
  77733. }
  77734. else if (state->head != Z_NULL)
  77735. state->head->extra = Z_NULL;
  77736. state->mode = EXTRA;
  77737. case EXTRA:
  77738. if (state->flags & 0x0400) {
  77739. copy = state->length;
  77740. if (copy > have) copy = have;
  77741. if (copy) {
  77742. if (state->head != Z_NULL &&
  77743. state->head->extra != Z_NULL) {
  77744. len = state->head->extra_len - state->length;
  77745. zmemcpy(state->head->extra + len, next,
  77746. len + copy > state->head->extra_max ?
  77747. state->head->extra_max - len : copy);
  77748. }
  77749. if (state->flags & 0x0200)
  77750. state->check = crc32(state->check, next, copy);
  77751. have -= copy;
  77752. next += copy;
  77753. state->length -= copy;
  77754. }
  77755. if (state->length) goto inf_leave;
  77756. }
  77757. state->length = 0;
  77758. state->mode = NAME;
  77759. case NAME:
  77760. if (state->flags & 0x0800) {
  77761. if (have == 0) goto inf_leave;
  77762. copy = 0;
  77763. do {
  77764. len = (unsigned)(next[copy++]);
  77765. if (state->head != Z_NULL &&
  77766. state->head->name != Z_NULL &&
  77767. state->length < state->head->name_max)
  77768. state->head->name[state->length++] = len;
  77769. } while (len && copy < have);
  77770. if (state->flags & 0x0200)
  77771. state->check = crc32(state->check, next, copy);
  77772. have -= copy;
  77773. next += copy;
  77774. if (len) goto inf_leave;
  77775. }
  77776. else if (state->head != Z_NULL)
  77777. state->head->name = Z_NULL;
  77778. state->length = 0;
  77779. state->mode = COMMENT;
  77780. case COMMENT:
  77781. if (state->flags & 0x1000) {
  77782. if (have == 0) goto inf_leave;
  77783. copy = 0;
  77784. do {
  77785. len = (unsigned)(next[copy++]);
  77786. if (state->head != Z_NULL &&
  77787. state->head->comment != Z_NULL &&
  77788. state->length < state->head->comm_max)
  77789. state->head->comment[state->length++] = len;
  77790. } while (len && copy < have);
  77791. if (state->flags & 0x0200)
  77792. state->check = crc32(state->check, next, copy);
  77793. have -= copy;
  77794. next += copy;
  77795. if (len) goto inf_leave;
  77796. }
  77797. else if (state->head != Z_NULL)
  77798. state->head->comment = Z_NULL;
  77799. state->mode = HCRC;
  77800. case HCRC:
  77801. if (state->flags & 0x0200) {
  77802. NEEDBITS(16);
  77803. if (hold != (state->check & 0xffff)) {
  77804. strm->msg = (char *)"header crc mismatch";
  77805. state->mode = BAD;
  77806. break;
  77807. }
  77808. INITBITS();
  77809. }
  77810. if (state->head != Z_NULL) {
  77811. state->head->hcrc = (int)((state->flags >> 9) & 1);
  77812. state->head->done = 1;
  77813. }
  77814. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  77815. state->mode = TYPE;
  77816. break;
  77817. #endif
  77818. case DICTID:
  77819. NEEDBITS(32);
  77820. strm->adler = state->check = REVERSE(hold);
  77821. INITBITS();
  77822. state->mode = DICT;
  77823. case DICT:
  77824. if (state->havedict == 0) {
  77825. RESTORE();
  77826. return Z_NEED_DICT;
  77827. }
  77828. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  77829. state->mode = TYPE;
  77830. case TYPE:
  77831. if (flush == Z_BLOCK) goto inf_leave;
  77832. case TYPEDO:
  77833. if (state->last) {
  77834. BYTEBITS();
  77835. state->mode = CHECK;
  77836. break;
  77837. }
  77838. NEEDBITS(3);
  77839. state->last = BITS(1);
  77840. DROPBITS(1);
  77841. switch (BITS(2)) {
  77842. case 0: /* stored block */
  77843. Tracev((stderr, "inflate: stored block%s\n",
  77844. state->last ? " (last)" : ""));
  77845. state->mode = STORED;
  77846. break;
  77847. case 1: /* fixed block */
  77848. fixedtables(state);
  77849. Tracev((stderr, "inflate: fixed codes block%s\n",
  77850. state->last ? " (last)" : ""));
  77851. state->mode = LEN; /* decode codes */
  77852. break;
  77853. case 2: /* dynamic block */
  77854. Tracev((stderr, "inflate: dynamic codes block%s\n",
  77855. state->last ? " (last)" : ""));
  77856. state->mode = TABLE;
  77857. break;
  77858. case 3:
  77859. strm->msg = (char *)"invalid block type";
  77860. state->mode = BAD;
  77861. }
  77862. DROPBITS(2);
  77863. break;
  77864. case STORED:
  77865. BYTEBITS(); /* go to byte boundary */
  77866. NEEDBITS(32);
  77867. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  77868. strm->msg = (char *)"invalid stored block lengths";
  77869. state->mode = BAD;
  77870. break;
  77871. }
  77872. state->length = (unsigned)hold & 0xffff;
  77873. Tracev((stderr, "inflate: stored length %u\n",
  77874. state->length));
  77875. INITBITS();
  77876. state->mode = COPY;
  77877. case COPY:
  77878. copy = state->length;
  77879. if (copy) {
  77880. if (copy > have) copy = have;
  77881. if (copy > left) copy = left;
  77882. if (copy == 0) goto inf_leave;
  77883. zmemcpy(put, next, copy);
  77884. have -= copy;
  77885. next += copy;
  77886. left -= copy;
  77887. put += copy;
  77888. state->length -= copy;
  77889. break;
  77890. }
  77891. Tracev((stderr, "inflate: stored end\n"));
  77892. state->mode = TYPE;
  77893. break;
  77894. case TABLE:
  77895. NEEDBITS(14);
  77896. state->nlen = BITS(5) + 257;
  77897. DROPBITS(5);
  77898. state->ndist = BITS(5) + 1;
  77899. DROPBITS(5);
  77900. state->ncode = BITS(4) + 4;
  77901. DROPBITS(4);
  77902. #ifndef PKZIP_BUG_WORKAROUND
  77903. if (state->nlen > 286 || state->ndist > 30) {
  77904. strm->msg = (char *)"too many length or distance symbols";
  77905. state->mode = BAD;
  77906. break;
  77907. }
  77908. #endif
  77909. Tracev((stderr, "inflate: table sizes ok\n"));
  77910. state->have = 0;
  77911. state->mode = LENLENS;
  77912. case LENLENS:
  77913. while (state->have < state->ncode) {
  77914. NEEDBITS(3);
  77915. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  77916. DROPBITS(3);
  77917. }
  77918. while (state->have < 19)
  77919. state->lens[order[state->have++]] = 0;
  77920. state->next = state->codes;
  77921. state->lencode = (code const FAR *)(state->next);
  77922. state->lenbits = 7;
  77923. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  77924. &(state->lenbits), state->work);
  77925. if (ret) {
  77926. strm->msg = (char *)"invalid code lengths set";
  77927. state->mode = BAD;
  77928. break;
  77929. }
  77930. Tracev((stderr, "inflate: code lengths ok\n"));
  77931. state->have = 0;
  77932. state->mode = CODELENS;
  77933. case CODELENS:
  77934. while (state->have < state->nlen + state->ndist) {
  77935. for (;;) {
  77936. thisx = state->lencode[BITS(state->lenbits)];
  77937. if ((unsigned)(thisx.bits) <= bits) break;
  77938. PULLBYTE();
  77939. }
  77940. if (thisx.val < 16) {
  77941. NEEDBITS(thisx.bits);
  77942. DROPBITS(thisx.bits);
  77943. state->lens[state->have++] = thisx.val;
  77944. }
  77945. else {
  77946. if (thisx.val == 16) {
  77947. NEEDBITS(thisx.bits + 2);
  77948. DROPBITS(thisx.bits);
  77949. if (state->have == 0) {
  77950. strm->msg = (char *)"invalid bit length repeat";
  77951. state->mode = BAD;
  77952. break;
  77953. }
  77954. len = state->lens[state->have - 1];
  77955. copy = 3 + BITS(2);
  77956. DROPBITS(2);
  77957. }
  77958. else if (thisx.val == 17) {
  77959. NEEDBITS(thisx.bits + 3);
  77960. DROPBITS(thisx.bits);
  77961. len = 0;
  77962. copy = 3 + BITS(3);
  77963. DROPBITS(3);
  77964. }
  77965. else {
  77966. NEEDBITS(thisx.bits + 7);
  77967. DROPBITS(thisx.bits);
  77968. len = 0;
  77969. copy = 11 + BITS(7);
  77970. DROPBITS(7);
  77971. }
  77972. if (state->have + copy > state->nlen + state->ndist) {
  77973. strm->msg = (char *)"invalid bit length repeat";
  77974. state->mode = BAD;
  77975. break;
  77976. }
  77977. while (copy--)
  77978. state->lens[state->have++] = (unsigned short)len;
  77979. }
  77980. }
  77981. /* handle error breaks in while */
  77982. if (state->mode == BAD) break;
  77983. /* build code tables */
  77984. state->next = state->codes;
  77985. state->lencode = (code const FAR *)(state->next);
  77986. state->lenbits = 9;
  77987. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  77988. &(state->lenbits), state->work);
  77989. if (ret) {
  77990. strm->msg = (char *)"invalid literal/lengths set";
  77991. state->mode = BAD;
  77992. break;
  77993. }
  77994. state->distcode = (code const FAR *)(state->next);
  77995. state->distbits = 6;
  77996. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  77997. &(state->next), &(state->distbits), state->work);
  77998. if (ret) {
  77999. strm->msg = (char *)"invalid distances set";
  78000. state->mode = BAD;
  78001. break;
  78002. }
  78003. Tracev((stderr, "inflate: codes ok\n"));
  78004. state->mode = LEN;
  78005. case LEN:
  78006. if (have >= 6 && left >= 258) {
  78007. RESTORE();
  78008. inflate_fast(strm, out);
  78009. LOAD();
  78010. break;
  78011. }
  78012. for (;;) {
  78013. thisx = state->lencode[BITS(state->lenbits)];
  78014. if ((unsigned)(thisx.bits) <= bits) break;
  78015. PULLBYTE();
  78016. }
  78017. if (thisx.op && (thisx.op & 0xf0) == 0) {
  78018. last = thisx;
  78019. for (;;) {
  78020. thisx = state->lencode[last.val +
  78021. (BITS(last.bits + last.op) >> last.bits)];
  78022. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  78023. PULLBYTE();
  78024. }
  78025. DROPBITS(last.bits);
  78026. }
  78027. DROPBITS(thisx.bits);
  78028. state->length = (unsigned)thisx.val;
  78029. if ((int)(thisx.op) == 0) {
  78030. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  78031. "inflate: literal '%c'\n" :
  78032. "inflate: literal 0x%02x\n", thisx.val));
  78033. state->mode = LIT;
  78034. break;
  78035. }
  78036. if (thisx.op & 32) {
  78037. Tracevv((stderr, "inflate: end of block\n"));
  78038. state->mode = TYPE;
  78039. break;
  78040. }
  78041. if (thisx.op & 64) {
  78042. strm->msg = (char *)"invalid literal/length code";
  78043. state->mode = BAD;
  78044. break;
  78045. }
  78046. state->extra = (unsigned)(thisx.op) & 15;
  78047. state->mode = LENEXT;
  78048. case LENEXT:
  78049. if (state->extra) {
  78050. NEEDBITS(state->extra);
  78051. state->length += BITS(state->extra);
  78052. DROPBITS(state->extra);
  78053. }
  78054. Tracevv((stderr, "inflate: length %u\n", state->length));
  78055. state->mode = DIST;
  78056. case DIST:
  78057. for (;;) {
  78058. thisx = state->distcode[BITS(state->distbits)];
  78059. if ((unsigned)(thisx.bits) <= bits) break;
  78060. PULLBYTE();
  78061. }
  78062. if ((thisx.op & 0xf0) == 0) {
  78063. last = thisx;
  78064. for (;;) {
  78065. thisx = state->distcode[last.val +
  78066. (BITS(last.bits + last.op) >> last.bits)];
  78067. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  78068. PULLBYTE();
  78069. }
  78070. DROPBITS(last.bits);
  78071. }
  78072. DROPBITS(thisx.bits);
  78073. if (thisx.op & 64) {
  78074. strm->msg = (char *)"invalid distance code";
  78075. state->mode = BAD;
  78076. break;
  78077. }
  78078. state->offset = (unsigned)thisx.val;
  78079. state->extra = (unsigned)(thisx.op) & 15;
  78080. state->mode = DISTEXT;
  78081. case DISTEXT:
  78082. if (state->extra) {
  78083. NEEDBITS(state->extra);
  78084. state->offset += BITS(state->extra);
  78085. DROPBITS(state->extra);
  78086. }
  78087. #ifdef INFLATE_STRICT
  78088. if (state->offset > state->dmax) {
  78089. strm->msg = (char *)"invalid distance too far back";
  78090. state->mode = BAD;
  78091. break;
  78092. }
  78093. #endif
  78094. if (state->offset > state->whave + out - left) {
  78095. strm->msg = (char *)"invalid distance too far back";
  78096. state->mode = BAD;
  78097. break;
  78098. }
  78099. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  78100. state->mode = MATCH;
  78101. case MATCH:
  78102. if (left == 0) goto inf_leave;
  78103. copy = out - left;
  78104. if (state->offset > copy) { /* copy from window */
  78105. copy = state->offset - copy;
  78106. if (copy > state->write) {
  78107. copy -= state->write;
  78108. from = state->window + (state->wsize - copy);
  78109. }
  78110. else
  78111. from = state->window + (state->write - copy);
  78112. if (copy > state->length) copy = state->length;
  78113. }
  78114. else { /* copy from output */
  78115. from = put - state->offset;
  78116. copy = state->length;
  78117. }
  78118. if (copy > left) copy = left;
  78119. left -= copy;
  78120. state->length -= copy;
  78121. do {
  78122. *put++ = *from++;
  78123. } while (--copy);
  78124. if (state->length == 0) state->mode = LEN;
  78125. break;
  78126. case LIT:
  78127. if (left == 0) goto inf_leave;
  78128. *put++ = (unsigned char)(state->length);
  78129. left--;
  78130. state->mode = LEN;
  78131. break;
  78132. case CHECK:
  78133. if (state->wrap) {
  78134. NEEDBITS(32);
  78135. out -= left;
  78136. strm->total_out += out;
  78137. state->total += out;
  78138. if (out)
  78139. strm->adler = state->check =
  78140. UPDATE(state->check, put - out, out);
  78141. out = left;
  78142. if ((
  78143. #ifdef GUNZIP
  78144. state->flags ? hold :
  78145. #endif
  78146. REVERSE(hold)) != state->check) {
  78147. strm->msg = (char *)"incorrect data check";
  78148. state->mode = BAD;
  78149. break;
  78150. }
  78151. INITBITS();
  78152. Tracev((stderr, "inflate: check matches trailer\n"));
  78153. }
  78154. #ifdef GUNZIP
  78155. state->mode = LENGTH;
  78156. case LENGTH:
  78157. if (state->wrap && state->flags) {
  78158. NEEDBITS(32);
  78159. if (hold != (state->total & 0xffffffffUL)) {
  78160. strm->msg = (char *)"incorrect length check";
  78161. state->mode = BAD;
  78162. break;
  78163. }
  78164. INITBITS();
  78165. Tracev((stderr, "inflate: length matches trailer\n"));
  78166. }
  78167. #endif
  78168. state->mode = DONE;
  78169. case DONE:
  78170. ret = Z_STREAM_END;
  78171. goto inf_leave;
  78172. case BAD:
  78173. ret = Z_DATA_ERROR;
  78174. goto inf_leave;
  78175. case MEM:
  78176. return Z_MEM_ERROR;
  78177. case SYNC:
  78178. default:
  78179. return Z_STREAM_ERROR;
  78180. }
  78181. /*
  78182. Return from inflate(), updating the total counts and the check value.
  78183. If there was no progress during the inflate() call, return a buffer
  78184. error. Call updatewindow() to create and/or update the window state.
  78185. Note: a memory error from inflate() is non-recoverable.
  78186. */
  78187. inf_leave:
  78188. RESTORE();
  78189. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  78190. if (updatewindow(strm, out)) {
  78191. state->mode = MEM;
  78192. return Z_MEM_ERROR;
  78193. }
  78194. in -= strm->avail_in;
  78195. out -= strm->avail_out;
  78196. strm->total_in += in;
  78197. strm->total_out += out;
  78198. state->total += out;
  78199. if (state->wrap && out)
  78200. strm->adler = state->check =
  78201. UPDATE(state->check, strm->next_out - out, out);
  78202. strm->data_type = state->bits + (state->last ? 64 : 0) +
  78203. (state->mode == TYPE ? 128 : 0);
  78204. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  78205. ret = Z_BUF_ERROR;
  78206. return ret;
  78207. }
  78208. int ZEXPORT inflateEnd (z_streamp strm)
  78209. {
  78210. struct inflate_state FAR *state;
  78211. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  78212. return Z_STREAM_ERROR;
  78213. state = (struct inflate_state FAR *)strm->state;
  78214. if (state->window != Z_NULL) ZFREE(strm, state->window);
  78215. ZFREE(strm, strm->state);
  78216. strm->state = Z_NULL;
  78217. Tracev((stderr, "inflate: end\n"));
  78218. return Z_OK;
  78219. }
  78220. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  78221. {
  78222. struct inflate_state FAR *state;
  78223. unsigned long id_;
  78224. /* check state */
  78225. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78226. state = (struct inflate_state FAR *)strm->state;
  78227. if (state->wrap != 0 && state->mode != DICT)
  78228. return Z_STREAM_ERROR;
  78229. /* check for correct dictionary id */
  78230. if (state->mode == DICT) {
  78231. id_ = adler32(0L, Z_NULL, 0);
  78232. id_ = adler32(id_, dictionary, dictLength);
  78233. if (id_ != state->check)
  78234. return Z_DATA_ERROR;
  78235. }
  78236. /* copy dictionary to window */
  78237. if (updatewindow(strm, strm->avail_out)) {
  78238. state->mode = MEM;
  78239. return Z_MEM_ERROR;
  78240. }
  78241. if (dictLength > state->wsize) {
  78242. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  78243. state->wsize);
  78244. state->whave = state->wsize;
  78245. }
  78246. else {
  78247. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  78248. dictLength);
  78249. state->whave = dictLength;
  78250. }
  78251. state->havedict = 1;
  78252. Tracev((stderr, "inflate: dictionary set\n"));
  78253. return Z_OK;
  78254. }
  78255. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  78256. {
  78257. struct inflate_state FAR *state;
  78258. /* check state */
  78259. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78260. state = (struct inflate_state FAR *)strm->state;
  78261. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  78262. /* save header structure */
  78263. state->head = head;
  78264. head->done = 0;
  78265. return Z_OK;
  78266. }
  78267. /*
  78268. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  78269. or when out of input. When called, *have is the number of pattern bytes
  78270. found in order so far, in 0..3. On return *have is updated to the new
  78271. state. If on return *have equals four, then the pattern was found and the
  78272. return value is how many bytes were read including the last byte of the
  78273. pattern. If *have is less than four, then the pattern has not been found
  78274. yet and the return value is len. In the latter case, syncsearch() can be
  78275. called again with more data and the *have state. *have is initialized to
  78276. zero for the first call.
  78277. */
  78278. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  78279. {
  78280. unsigned got;
  78281. unsigned next;
  78282. got = *have;
  78283. next = 0;
  78284. while (next < len && got < 4) {
  78285. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  78286. got++;
  78287. else if (buf[next])
  78288. got = 0;
  78289. else
  78290. got = 4 - got;
  78291. next++;
  78292. }
  78293. *have = got;
  78294. return next;
  78295. }
  78296. int ZEXPORT inflateSync (z_streamp strm)
  78297. {
  78298. unsigned len; /* number of bytes to look at or looked at */
  78299. unsigned long in, out; /* temporary to save total_in and total_out */
  78300. unsigned char buf[4]; /* to restore bit buffer to byte string */
  78301. struct inflate_state FAR *state;
  78302. /* check parameters */
  78303. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78304. state = (struct inflate_state FAR *)strm->state;
  78305. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  78306. /* if first time, start search in bit buffer */
  78307. if (state->mode != SYNC) {
  78308. state->mode = SYNC;
  78309. state->hold <<= state->bits & 7;
  78310. state->bits -= state->bits & 7;
  78311. len = 0;
  78312. while (state->bits >= 8) {
  78313. buf[len++] = (unsigned char)(state->hold);
  78314. state->hold >>= 8;
  78315. state->bits -= 8;
  78316. }
  78317. state->have = 0;
  78318. syncsearch(&(state->have), buf, len);
  78319. }
  78320. /* search available input */
  78321. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  78322. strm->avail_in -= len;
  78323. strm->next_in += len;
  78324. strm->total_in += len;
  78325. /* return no joy or set up to restart inflate() on a new block */
  78326. if (state->have != 4) return Z_DATA_ERROR;
  78327. in = strm->total_in; out = strm->total_out;
  78328. inflateReset(strm);
  78329. strm->total_in = in; strm->total_out = out;
  78330. state->mode = TYPE;
  78331. return Z_OK;
  78332. }
  78333. /*
  78334. Returns true if inflate is currently at the end of a block generated by
  78335. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  78336. implementation to provide an additional safety check. PPP uses
  78337. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  78338. block. When decompressing, PPP checks that at the end of input packet,
  78339. inflate is waiting for these length bytes.
  78340. */
  78341. int ZEXPORT inflateSyncPoint (z_streamp strm)
  78342. {
  78343. struct inflate_state FAR *state;
  78344. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78345. state = (struct inflate_state FAR *)strm->state;
  78346. return state->mode == STORED && state->bits == 0;
  78347. }
  78348. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  78349. {
  78350. struct inflate_state FAR *state;
  78351. struct inflate_state FAR *copy;
  78352. unsigned char FAR *window;
  78353. unsigned wsize;
  78354. /* check input */
  78355. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  78356. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  78357. return Z_STREAM_ERROR;
  78358. state = (struct inflate_state FAR *)source->state;
  78359. /* allocate space */
  78360. copy = (struct inflate_state FAR *)
  78361. ZALLOC(source, 1, sizeof(struct inflate_state));
  78362. if (copy == Z_NULL) return Z_MEM_ERROR;
  78363. window = Z_NULL;
  78364. if (state->window != Z_NULL) {
  78365. window = (unsigned char FAR *)
  78366. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  78367. if (window == Z_NULL) {
  78368. ZFREE(source, copy);
  78369. return Z_MEM_ERROR;
  78370. }
  78371. }
  78372. /* copy state */
  78373. zmemcpy(dest, source, sizeof(z_stream));
  78374. zmemcpy(copy, state, sizeof(struct inflate_state));
  78375. if (state->lencode >= state->codes &&
  78376. state->lencode <= state->codes + ENOUGH - 1) {
  78377. copy->lencode = copy->codes + (state->lencode - state->codes);
  78378. copy->distcode = copy->codes + (state->distcode - state->codes);
  78379. }
  78380. copy->next = copy->codes + (state->next - state->codes);
  78381. if (window != Z_NULL) {
  78382. wsize = 1U << state->wbits;
  78383. zmemcpy(window, state->window, wsize);
  78384. }
  78385. copy->window = window;
  78386. dest->state = (struct internal_state FAR *)copy;
  78387. return Z_OK;
  78388. }
  78389. /********* End of inlined file: inflate.c *********/
  78390. /********* Start of inlined file: inftrees.c *********/
  78391. #define MAXBITS 15
  78392. const char inflate_copyright[] =
  78393. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  78394. /*
  78395. If you use the zlib library in a product, an acknowledgment is welcome
  78396. in the documentation of your product. If for some reason you cannot
  78397. include such an acknowledgment, I would appreciate that you keep this
  78398. copyright string in the executable of your product.
  78399. */
  78400. /*
  78401. Build a set of tables to decode the provided canonical Huffman code.
  78402. The code lengths are lens[0..codes-1]. The result starts at *table,
  78403. whose indices are 0..2^bits-1. work is a writable array of at least
  78404. lens shorts, which is used as a work area. type is the type of code
  78405. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  78406. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  78407. on return points to the next available entry's address. bits is the
  78408. requested root table index bits, and on return it is the actual root
  78409. table index bits. It will differ if the request is greater than the
  78410. longest code or if it is less than the shortest code.
  78411. */
  78412. int inflate_table (codetype type,
  78413. unsigned short FAR *lens,
  78414. unsigned codes,
  78415. code FAR * FAR *table,
  78416. unsigned FAR *bits,
  78417. unsigned short FAR *work)
  78418. {
  78419. unsigned len; /* a code's length in bits */
  78420. unsigned sym; /* index of code symbols */
  78421. unsigned min, max; /* minimum and maximum code lengths */
  78422. unsigned root; /* number of index bits for root table */
  78423. unsigned curr; /* number of index bits for current table */
  78424. unsigned drop; /* code bits to drop for sub-table */
  78425. int left; /* number of prefix codes available */
  78426. unsigned used; /* code entries in table used */
  78427. unsigned huff; /* Huffman code */
  78428. unsigned incr; /* for incrementing code, index */
  78429. unsigned fill; /* index for replicating entries */
  78430. unsigned low; /* low bits for current root entry */
  78431. unsigned mask; /* mask for low root bits */
  78432. code thisx; /* table entry for duplication */
  78433. code FAR *next; /* next available space in table */
  78434. const unsigned short FAR *base; /* base value table to use */
  78435. const unsigned short FAR *extra; /* extra bits table to use */
  78436. int end; /* use base and extra for symbol > end */
  78437. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  78438. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  78439. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  78440. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  78441. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  78442. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  78443. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  78444. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  78445. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  78446. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  78447. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  78448. 8193, 12289, 16385, 24577, 0, 0};
  78449. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  78450. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  78451. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  78452. 28, 28, 29, 29, 64, 64};
  78453. /*
  78454. Process a set of code lengths to create a canonical Huffman code. The
  78455. code lengths are lens[0..codes-1]. Each length corresponds to the
  78456. symbols 0..codes-1. The Huffman code is generated by first sorting the
  78457. symbols by length from short to long, and retaining the symbol order
  78458. for codes with equal lengths. Then the code starts with all zero bits
  78459. for the first code of the shortest length, and the codes are integer
  78460. increments for the same length, and zeros are appended as the length
  78461. increases. For the deflate format, these bits are stored backwards
  78462. from their more natural integer increment ordering, and so when the
  78463. decoding tables are built in the large loop below, the integer codes
  78464. are incremented backwards.
  78465. This routine assumes, but does not check, that all of the entries in
  78466. lens[] are in the range 0..MAXBITS. The caller must assure this.
  78467. 1..MAXBITS is interpreted as that code length. zero means that that
  78468. symbol does not occur in this code.
  78469. The codes are sorted by computing a count of codes for each length,
  78470. creating from that a table of starting indices for each length in the
  78471. sorted table, and then entering the symbols in order in the sorted
  78472. table. The sorted table is work[], with that space being provided by
  78473. the caller.
  78474. The length counts are used for other purposes as well, i.e. finding
  78475. the minimum and maximum length codes, determining if there are any
  78476. codes at all, checking for a valid set of lengths, and looking ahead
  78477. at length counts to determine sub-table sizes when building the
  78478. decoding tables.
  78479. */
  78480. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  78481. for (len = 0; len <= MAXBITS; len++)
  78482. count[len] = 0;
  78483. for (sym = 0; sym < codes; sym++)
  78484. count[lens[sym]]++;
  78485. /* bound code lengths, force root to be within code lengths */
  78486. root = *bits;
  78487. for (max = MAXBITS; max >= 1; max--)
  78488. if (count[max] != 0) break;
  78489. if (root > max) root = max;
  78490. if (max == 0) { /* no symbols to code at all */
  78491. thisx.op = (unsigned char)64; /* invalid code marker */
  78492. thisx.bits = (unsigned char)1;
  78493. thisx.val = (unsigned short)0;
  78494. *(*table)++ = thisx; /* make a table to force an error */
  78495. *(*table)++ = thisx;
  78496. *bits = 1;
  78497. return 0; /* no symbols, but wait for decoding to report error */
  78498. }
  78499. for (min = 1; min <= MAXBITS; min++)
  78500. if (count[min] != 0) break;
  78501. if (root < min) root = min;
  78502. /* check for an over-subscribed or incomplete set of lengths */
  78503. left = 1;
  78504. for (len = 1; len <= MAXBITS; len++) {
  78505. left <<= 1;
  78506. left -= count[len];
  78507. if (left < 0) return -1; /* over-subscribed */
  78508. }
  78509. if (left > 0 && (type == CODES || max != 1))
  78510. return -1; /* incomplete set */
  78511. /* generate offsets into symbol table for each length for sorting */
  78512. offs[1] = 0;
  78513. for (len = 1; len < MAXBITS; len++)
  78514. offs[len + 1] = offs[len] + count[len];
  78515. /* sort symbols by length, by symbol order within each length */
  78516. for (sym = 0; sym < codes; sym++)
  78517. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  78518. /*
  78519. Create and fill in decoding tables. In this loop, the table being
  78520. filled is at next and has curr index bits. The code being used is huff
  78521. with length len. That code is converted to an index by dropping drop
  78522. bits off of the bottom. For codes where len is less than drop + curr,
  78523. those top drop + curr - len bits are incremented through all values to
  78524. fill the table with replicated entries.
  78525. root is the number of index bits for the root table. When len exceeds
  78526. root, sub-tables are created pointed to by the root entry with an index
  78527. of the low root bits of huff. This is saved in low to check for when a
  78528. new sub-table should be started. drop is zero when the root table is
  78529. being filled, and drop is root when sub-tables are being filled.
  78530. When a new sub-table is needed, it is necessary to look ahead in the
  78531. code lengths to determine what size sub-table is needed. The length
  78532. counts are used for this, and so count[] is decremented as codes are
  78533. entered in the tables.
  78534. used keeps track of how many table entries have been allocated from the
  78535. provided *table space. It is checked when a LENS table is being made
  78536. against the space in *table, ENOUGH, minus the maximum space needed by
  78537. the worst case distance code, MAXD. This should never happen, but the
  78538. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  78539. This assumes that when type == LENS, bits == 9.
  78540. sym increments through all symbols, and the loop terminates when
  78541. all codes of length max, i.e. all codes, have been processed. This
  78542. routine permits incomplete codes, so another loop after this one fills
  78543. in the rest of the decoding tables with invalid code markers.
  78544. */
  78545. /* set up for code type */
  78546. switch (type) {
  78547. case CODES:
  78548. base = extra = work; /* dummy value--not used */
  78549. end = 19;
  78550. break;
  78551. case LENS:
  78552. base = lbase;
  78553. base -= 257;
  78554. extra = lext;
  78555. extra -= 257;
  78556. end = 256;
  78557. break;
  78558. default: /* DISTS */
  78559. base = dbase;
  78560. extra = dext;
  78561. end = -1;
  78562. }
  78563. /* initialize state for loop */
  78564. huff = 0; /* starting code */
  78565. sym = 0; /* starting code symbol */
  78566. len = min; /* starting code length */
  78567. next = *table; /* current table to fill in */
  78568. curr = root; /* current table index bits */
  78569. drop = 0; /* current bits to drop from code for index */
  78570. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  78571. used = 1U << root; /* use root table entries */
  78572. mask = used - 1; /* mask for comparing low */
  78573. /* check available table space */
  78574. if (type == LENS && used >= ENOUGH - MAXD)
  78575. return 1;
  78576. /* process all codes and make table entries */
  78577. for (;;) {
  78578. /* create table entry */
  78579. thisx.bits = (unsigned char)(len - drop);
  78580. if ((int)(work[sym]) < end) {
  78581. thisx.op = (unsigned char)0;
  78582. thisx.val = work[sym];
  78583. }
  78584. else if ((int)(work[sym]) > end) {
  78585. thisx.op = (unsigned char)(extra[work[sym]]);
  78586. thisx.val = base[work[sym]];
  78587. }
  78588. else {
  78589. thisx.op = (unsigned char)(32 + 64); /* end of block */
  78590. thisx.val = 0;
  78591. }
  78592. /* replicate for those indices with low len bits equal to huff */
  78593. incr = 1U << (len - drop);
  78594. fill = 1U << curr;
  78595. min = fill; /* save offset to next table */
  78596. do {
  78597. fill -= incr;
  78598. next[(huff >> drop) + fill] = thisx;
  78599. } while (fill != 0);
  78600. /* backwards increment the len-bit code huff */
  78601. incr = 1U << (len - 1);
  78602. while (huff & incr)
  78603. incr >>= 1;
  78604. if (incr != 0) {
  78605. huff &= incr - 1;
  78606. huff += incr;
  78607. }
  78608. else
  78609. huff = 0;
  78610. /* go to next symbol, update count, len */
  78611. sym++;
  78612. if (--(count[len]) == 0) {
  78613. if (len == max) break;
  78614. len = lens[work[sym]];
  78615. }
  78616. /* create new sub-table if needed */
  78617. if (len > root && (huff & mask) != low) {
  78618. /* if first time, transition to sub-tables */
  78619. if (drop == 0)
  78620. drop = root;
  78621. /* increment past last table */
  78622. next += min; /* here min is 1 << curr */
  78623. /* determine length of next table */
  78624. curr = len - drop;
  78625. left = (int)(1 << curr);
  78626. while (curr + drop < max) {
  78627. left -= count[curr + drop];
  78628. if (left <= 0) break;
  78629. curr++;
  78630. left <<= 1;
  78631. }
  78632. /* check for enough space */
  78633. used += 1U << curr;
  78634. if (type == LENS && used >= ENOUGH - MAXD)
  78635. return 1;
  78636. /* point entry in root table to sub-table */
  78637. low = huff & mask;
  78638. (*table)[low].op = (unsigned char)curr;
  78639. (*table)[low].bits = (unsigned char)root;
  78640. (*table)[low].val = (unsigned short)(next - *table);
  78641. }
  78642. }
  78643. /*
  78644. Fill in rest of table for incomplete codes. This loop is similar to the
  78645. loop above in incrementing huff for table indices. It is assumed that
  78646. len is equal to curr + drop, so there is no loop needed to increment
  78647. through high index bits. When the current sub-table is filled, the loop
  78648. drops back to the root table to fill in any remaining entries there.
  78649. */
  78650. thisx.op = (unsigned char)64; /* invalid code marker */
  78651. thisx.bits = (unsigned char)(len - drop);
  78652. thisx.val = (unsigned short)0;
  78653. while (huff != 0) {
  78654. /* when done with sub-table, drop back to root table */
  78655. if (drop != 0 && (huff & mask) != low) {
  78656. drop = 0;
  78657. len = root;
  78658. next = *table;
  78659. thisx.bits = (unsigned char)len;
  78660. }
  78661. /* put invalid code marker in table */
  78662. next[huff >> drop] = thisx;
  78663. /* backwards increment the len-bit code huff */
  78664. incr = 1U << (len - 1);
  78665. while (huff & incr)
  78666. incr >>= 1;
  78667. if (incr != 0) {
  78668. huff &= incr - 1;
  78669. huff += incr;
  78670. }
  78671. else
  78672. huff = 0;
  78673. }
  78674. /* set return parameters */
  78675. *table += used;
  78676. *bits = root;
  78677. return 0;
  78678. }
  78679. /********* End of inlined file: inftrees.c *********/
  78680. /********* Start of inlined file: trees.c *********/
  78681. /*
  78682. * ALGORITHM
  78683. *
  78684. * The "deflation" process uses several Huffman trees. The more
  78685. * common source values are represented by shorter bit sequences.
  78686. *
  78687. * Each code tree is stored in a compressed form which is itself
  78688. * a Huffman encoding of the lengths of all the code strings (in
  78689. * ascending order by source values). The actual code strings are
  78690. * reconstructed from the lengths in the inflate process, as described
  78691. * in the deflate specification.
  78692. *
  78693. * REFERENCES
  78694. *
  78695. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  78696. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  78697. *
  78698. * Storer, James A.
  78699. * Data Compression: Methods and Theory, pp. 49-50.
  78700. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  78701. *
  78702. * Sedgewick, R.
  78703. * Algorithms, p290.
  78704. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  78705. */
  78706. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78707. /* #define GEN_TREES_H */
  78708. #ifdef DEBUG
  78709. # include <ctype.h>
  78710. #endif
  78711. /* ===========================================================================
  78712. * Constants
  78713. */
  78714. #define MAX_BL_BITS 7
  78715. /* Bit length codes must not exceed MAX_BL_BITS bits */
  78716. #define END_BLOCK 256
  78717. /* end of block literal code */
  78718. #define REP_3_6 16
  78719. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  78720. #define REPZ_3_10 17
  78721. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  78722. #define REPZ_11_138 18
  78723. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  78724. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  78725. = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
  78726. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  78727. = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
  78728. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  78729. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  78730. local const uch bl_order[BL_CODES]
  78731. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  78732. /* The lengths of the bit length codes are sent in order of decreasing
  78733. * probability, to avoid transmitting the lengths for unused bit length codes.
  78734. */
  78735. #define Buf_size (8 * 2*sizeof(char))
  78736. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  78737. * more than 16 bits on some systems.)
  78738. */
  78739. /* ===========================================================================
  78740. * Local data. These are initialized only once.
  78741. */
  78742. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  78743. #if defined(GEN_TREES_H) || !defined(STDC)
  78744. /* non ANSI compilers may not accept trees.h */
  78745. local ct_data static_ltree[L_CODES+2];
  78746. /* The static literal tree. Since the bit lengths are imposed, there is no
  78747. * need for the L_CODES extra codes used during heap construction. However
  78748. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  78749. * below).
  78750. */
  78751. local ct_data static_dtree[D_CODES];
  78752. /* The static distance tree. (Actually a trivial tree since all codes use
  78753. * 5 bits.)
  78754. */
  78755. uch _dist_code[DIST_CODE_LEN];
  78756. /* Distance codes. The first 256 values correspond to the distances
  78757. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  78758. * the 15 bit distances.
  78759. */
  78760. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  78761. /* length code for each normalized match length (0 == MIN_MATCH) */
  78762. local int base_length[LENGTH_CODES];
  78763. /* First normalized length for each code (0 = MIN_MATCH) */
  78764. local int base_dist[D_CODES];
  78765. /* First normalized distance for each code (0 = distance of 1) */
  78766. #else
  78767. /********* Start of inlined file: trees.h *********/
  78768. local const ct_data static_ltree[L_CODES+2] = {
  78769. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  78770. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  78771. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  78772. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  78773. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  78774. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  78775. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  78776. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  78777. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  78778. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  78779. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  78780. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  78781. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  78782. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  78783. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  78784. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  78785. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  78786. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  78787. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  78788. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  78789. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  78790. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  78791. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  78792. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  78793. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  78794. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  78795. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  78796. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  78797. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  78798. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  78799. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  78800. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  78801. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  78802. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  78803. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  78804. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  78805. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  78806. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  78807. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  78808. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  78809. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  78810. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  78811. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  78812. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  78813. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  78814. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  78815. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  78816. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  78817. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  78818. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  78819. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  78820. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  78821. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  78822. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  78823. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  78824. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  78825. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  78826. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  78827. };
  78828. local const ct_data static_dtree[D_CODES] = {
  78829. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  78830. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  78831. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  78832. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  78833. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  78834. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  78835. };
  78836. const uch _dist_code[DIST_CODE_LEN] = {
  78837. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  78838. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  78839. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  78840. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  78841. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  78842. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  78843. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  78844. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  78845. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  78846. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  78847. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  78848. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  78849. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  78850. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  78851. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  78852. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  78853. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  78854. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  78855. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  78856. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  78857. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  78858. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  78859. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  78860. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  78861. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  78862. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  78863. };
  78864. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  78865. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  78866. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  78867. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  78868. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  78869. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  78870. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  78871. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  78872. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  78873. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  78874. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  78875. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  78876. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  78877. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  78878. };
  78879. local const int base_length[LENGTH_CODES] = {
  78880. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  78881. 64, 80, 96, 112, 128, 160, 192, 224, 0
  78882. };
  78883. local const int base_dist[D_CODES] = {
  78884. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  78885. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  78886. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  78887. };
  78888. /********* End of inlined file: trees.h *********/
  78889. #endif /* GEN_TREES_H */
  78890. struct static_tree_desc_s {
  78891. const ct_data *static_tree; /* static tree or NULL */
  78892. const intf *extra_bits; /* extra bits for each code or NULL */
  78893. int extra_base; /* base index for extra_bits */
  78894. int elems; /* max number of elements in the tree */
  78895. int max_length; /* max bit length for the codes */
  78896. };
  78897. local static_tree_desc static_l_desc =
  78898. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  78899. local static_tree_desc static_d_desc =
  78900. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  78901. local static_tree_desc static_bl_desc =
  78902. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  78903. /* ===========================================================================
  78904. * Local (static) routines in this file.
  78905. */
  78906. local void tr_static_init OF((void));
  78907. local void init_block OF((deflate_state *s));
  78908. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  78909. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  78910. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  78911. local void build_tree OF((deflate_state *s, tree_desc *desc));
  78912. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  78913. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  78914. local int build_bl_tree OF((deflate_state *s));
  78915. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  78916. int blcodes));
  78917. local void compress_block OF((deflate_state *s, ct_data *ltree,
  78918. ct_data *dtree));
  78919. local void set_data_type OF((deflate_state *s));
  78920. local unsigned bi_reverse OF((unsigned value, int length));
  78921. local void bi_windup OF((deflate_state *s));
  78922. local void bi_flush OF((deflate_state *s));
  78923. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  78924. int header));
  78925. #ifdef GEN_TREES_H
  78926. local void gen_trees_header OF((void));
  78927. #endif
  78928. #ifndef DEBUG
  78929. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  78930. /* Send a code of the given tree. c and tree must not have side effects */
  78931. #else /* DEBUG */
  78932. # define send_code(s, c, tree) \
  78933. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  78934. send_bits(s, tree[c].Code, tree[c].Len); }
  78935. #endif
  78936. /* ===========================================================================
  78937. * Output a short LSB first on the stream.
  78938. * IN assertion: there is enough room in pendingBuf.
  78939. */
  78940. #define put_short(s, w) { \
  78941. put_byte(s, (uch)((w) & 0xff)); \
  78942. put_byte(s, (uch)((ush)(w) >> 8)); \
  78943. }
  78944. /* ===========================================================================
  78945. * Send a value on a given number of bits.
  78946. * IN assertion: length <= 16 and value fits in length bits.
  78947. */
  78948. #ifdef DEBUG
  78949. local void send_bits OF((deflate_state *s, int value, int length));
  78950. local void send_bits (deflate_state *s, int value, int length)
  78951. {
  78952. Tracevv((stderr," l %2d v %4x ", length, value));
  78953. Assert(length > 0 && length <= 15, "invalid length");
  78954. s->bits_sent += (ulg)length;
  78955. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  78956. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  78957. * unused bits in value.
  78958. */
  78959. if (s->bi_valid > (int)Buf_size - length) {
  78960. s->bi_buf |= (value << s->bi_valid);
  78961. put_short(s, s->bi_buf);
  78962. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  78963. s->bi_valid += length - Buf_size;
  78964. } else {
  78965. s->bi_buf |= value << s->bi_valid;
  78966. s->bi_valid += length;
  78967. }
  78968. }
  78969. #else /* !DEBUG */
  78970. #define send_bits(s, value, length) \
  78971. { int len = length;\
  78972. if (s->bi_valid > (int)Buf_size - len) {\
  78973. int val = value;\
  78974. s->bi_buf |= (val << s->bi_valid);\
  78975. put_short(s, s->bi_buf);\
  78976. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  78977. s->bi_valid += len - Buf_size;\
  78978. } else {\
  78979. s->bi_buf |= (value) << s->bi_valid;\
  78980. s->bi_valid += len;\
  78981. }\
  78982. }
  78983. #endif /* DEBUG */
  78984. /* the arguments must not have side effects */
  78985. /* ===========================================================================
  78986. * Initialize the various 'constant' tables.
  78987. */
  78988. local void tr_static_init()
  78989. {
  78990. #if defined(GEN_TREES_H) || !defined(STDC)
  78991. static int static_init_done = 0;
  78992. int n; /* iterates over tree elements */
  78993. int bits; /* bit counter */
  78994. int length; /* length value */
  78995. int code; /* code value */
  78996. int dist; /* distance index */
  78997. ush bl_count[MAX_BITS+1];
  78998. /* number of codes at each bit length for an optimal tree */
  78999. if (static_init_done) return;
  79000. /* For some embedded targets, global variables are not initialized: */
  79001. static_l_desc.static_tree = static_ltree;
  79002. static_l_desc.extra_bits = extra_lbits;
  79003. static_d_desc.static_tree = static_dtree;
  79004. static_d_desc.extra_bits = extra_dbits;
  79005. static_bl_desc.extra_bits = extra_blbits;
  79006. /* Initialize the mapping length (0..255) -> length code (0..28) */
  79007. length = 0;
  79008. for (code = 0; code < LENGTH_CODES-1; code++) {
  79009. base_length[code] = length;
  79010. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  79011. _length_code[length++] = (uch)code;
  79012. }
  79013. }
  79014. Assert (length == 256, "tr_static_init: length != 256");
  79015. /* Note that the length 255 (match length 258) can be represented
  79016. * in two different ways: code 284 + 5 bits or code 285, so we
  79017. * overwrite length_code[255] to use the best encoding:
  79018. */
  79019. _length_code[length-1] = (uch)code;
  79020. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  79021. dist = 0;
  79022. for (code = 0 ; code < 16; code++) {
  79023. base_dist[code] = dist;
  79024. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  79025. _dist_code[dist++] = (uch)code;
  79026. }
  79027. }
  79028. Assert (dist == 256, "tr_static_init: dist != 256");
  79029. dist >>= 7; /* from now on, all distances are divided by 128 */
  79030. for ( ; code < D_CODES; code++) {
  79031. base_dist[code] = dist << 7;
  79032. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  79033. _dist_code[256 + dist++] = (uch)code;
  79034. }
  79035. }
  79036. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  79037. /* Construct the codes of the static literal tree */
  79038. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  79039. n = 0;
  79040. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  79041. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  79042. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  79043. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  79044. /* Codes 286 and 287 do not exist, but we must include them in the
  79045. * tree construction to get a canonical Huffman tree (longest code
  79046. * all ones)
  79047. */
  79048. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  79049. /* The static distance tree is trivial: */
  79050. for (n = 0; n < D_CODES; n++) {
  79051. static_dtree[n].Len = 5;
  79052. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  79053. }
  79054. static_init_done = 1;
  79055. # ifdef GEN_TREES_H
  79056. gen_trees_header();
  79057. # endif
  79058. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  79059. }
  79060. /* ===========================================================================
  79061. * Genererate the file trees.h describing the static trees.
  79062. */
  79063. #ifdef GEN_TREES_H
  79064. # ifndef DEBUG
  79065. # include <stdio.h>
  79066. # endif
  79067. # define SEPARATOR(i, last, width) \
  79068. ((i) == (last)? "\n};\n\n" : \
  79069. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  79070. void gen_trees_header()
  79071. {
  79072. FILE *header = fopen("trees.h", "w");
  79073. int i;
  79074. Assert (header != NULL, "Can't open trees.h");
  79075. fprintf(header,
  79076. "/* header created automatically with -DGEN_TREES_H */\n\n");
  79077. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  79078. for (i = 0; i < L_CODES+2; i++) {
  79079. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  79080. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  79081. }
  79082. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  79083. for (i = 0; i < D_CODES; i++) {
  79084. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  79085. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  79086. }
  79087. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  79088. for (i = 0; i < DIST_CODE_LEN; i++) {
  79089. fprintf(header, "%2u%s", _dist_code[i],
  79090. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  79091. }
  79092. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  79093. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  79094. fprintf(header, "%2u%s", _length_code[i],
  79095. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  79096. }
  79097. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  79098. for (i = 0; i < LENGTH_CODES; i++) {
  79099. fprintf(header, "%1u%s", base_length[i],
  79100. SEPARATOR(i, LENGTH_CODES-1, 20));
  79101. }
  79102. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  79103. for (i = 0; i < D_CODES; i++) {
  79104. fprintf(header, "%5u%s", base_dist[i],
  79105. SEPARATOR(i, D_CODES-1, 10));
  79106. }
  79107. fclose(header);
  79108. }
  79109. #endif /* GEN_TREES_H */
  79110. /* ===========================================================================
  79111. * Initialize the tree data structures for a new zlib stream.
  79112. */
  79113. void _tr_init(deflate_state *s)
  79114. {
  79115. tr_static_init();
  79116. s->l_desc.dyn_tree = s->dyn_ltree;
  79117. s->l_desc.stat_desc = &static_l_desc;
  79118. s->d_desc.dyn_tree = s->dyn_dtree;
  79119. s->d_desc.stat_desc = &static_d_desc;
  79120. s->bl_desc.dyn_tree = s->bl_tree;
  79121. s->bl_desc.stat_desc = &static_bl_desc;
  79122. s->bi_buf = 0;
  79123. s->bi_valid = 0;
  79124. s->last_eob_len = 8; /* enough lookahead for inflate */
  79125. #ifdef DEBUG
  79126. s->compressed_len = 0L;
  79127. s->bits_sent = 0L;
  79128. #endif
  79129. /* Initialize the first block of the first file: */
  79130. init_block(s);
  79131. }
  79132. /* ===========================================================================
  79133. * Initialize a new block.
  79134. */
  79135. local void init_block (deflate_state *s)
  79136. {
  79137. int n; /* iterates over tree elements */
  79138. /* Initialize the trees. */
  79139. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  79140. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  79141. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  79142. s->dyn_ltree[END_BLOCK].Freq = 1;
  79143. s->opt_len = s->static_len = 0L;
  79144. s->last_lit = s->matches = 0;
  79145. }
  79146. #define SMALLEST 1
  79147. /* Index within the heap array of least frequent node in the Huffman tree */
  79148. /* ===========================================================================
  79149. * Remove the smallest element from the heap and recreate the heap with
  79150. * one less element. Updates heap and heap_len.
  79151. */
  79152. #define pqremove(s, tree, top) \
  79153. {\
  79154. top = s->heap[SMALLEST]; \
  79155. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  79156. pqdownheap(s, tree, SMALLEST); \
  79157. }
  79158. /* ===========================================================================
  79159. * Compares to subtrees, using the tree depth as tie breaker when
  79160. * the subtrees have equal frequency. This minimizes the worst case length.
  79161. */
  79162. #define smaller(tree, n, m, depth) \
  79163. (tree[n].Freq < tree[m].Freq || \
  79164. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  79165. /* ===========================================================================
  79166. * Restore the heap property by moving down the tree starting at node k,
  79167. * exchanging a node with the smallest of its two sons if necessary, stopping
  79168. * when the heap property is re-established (each father smaller than its
  79169. * two sons).
  79170. */
  79171. local void pqdownheap (deflate_state *s,
  79172. ct_data *tree, /* the tree to restore */
  79173. int k) /* node to move down */
  79174. {
  79175. int v = s->heap[k];
  79176. int j = k << 1; /* left son of k */
  79177. while (j <= s->heap_len) {
  79178. /* Set j to the smallest of the two sons: */
  79179. if (j < s->heap_len &&
  79180. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  79181. j++;
  79182. }
  79183. /* Exit if v is smaller than both sons */
  79184. if (smaller(tree, v, s->heap[j], s->depth)) break;
  79185. /* Exchange v with the smallest son */
  79186. s->heap[k] = s->heap[j]; k = j;
  79187. /* And continue down the tree, setting j to the left son of k */
  79188. j <<= 1;
  79189. }
  79190. s->heap[k] = v;
  79191. }
  79192. /* ===========================================================================
  79193. * Compute the optimal bit lengths for a tree and update the total bit length
  79194. * for the current block.
  79195. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  79196. * above are the tree nodes sorted by increasing frequency.
  79197. * OUT assertions: the field len is set to the optimal bit length, the
  79198. * array bl_count contains the frequencies for each bit length.
  79199. * The length opt_len is updated; static_len is also updated if stree is
  79200. * not null.
  79201. */
  79202. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  79203. {
  79204. ct_data *tree = desc->dyn_tree;
  79205. int max_code = desc->max_code;
  79206. const ct_data *stree = desc->stat_desc->static_tree;
  79207. const intf *extra = desc->stat_desc->extra_bits;
  79208. int base = desc->stat_desc->extra_base;
  79209. int max_length = desc->stat_desc->max_length;
  79210. int h; /* heap index */
  79211. int n, m; /* iterate over the tree elements */
  79212. int bits; /* bit length */
  79213. int xbits; /* extra bits */
  79214. ush f; /* frequency */
  79215. int overflow = 0; /* number of elements with bit length too large */
  79216. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  79217. /* In a first pass, compute the optimal bit lengths (which may
  79218. * overflow in the case of the bit length tree).
  79219. */
  79220. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  79221. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  79222. n = s->heap[h];
  79223. bits = tree[tree[n].Dad].Len + 1;
  79224. if (bits > max_length) bits = max_length, overflow++;
  79225. tree[n].Len = (ush)bits;
  79226. /* We overwrite tree[n].Dad which is no longer needed */
  79227. if (n > max_code) continue; /* not a leaf node */
  79228. s->bl_count[bits]++;
  79229. xbits = 0;
  79230. if (n >= base) xbits = extra[n-base];
  79231. f = tree[n].Freq;
  79232. s->opt_len += (ulg)f * (bits + xbits);
  79233. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  79234. }
  79235. if (overflow == 0) return;
  79236. Trace((stderr,"\nbit length overflow\n"));
  79237. /* This happens for example on obj2 and pic of the Calgary corpus */
  79238. /* Find the first bit length which could increase: */
  79239. do {
  79240. bits = max_length-1;
  79241. while (s->bl_count[bits] == 0) bits--;
  79242. s->bl_count[bits]--; /* move one leaf down the tree */
  79243. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  79244. s->bl_count[max_length]--;
  79245. /* The brother of the overflow item also moves one step up,
  79246. * but this does not affect bl_count[max_length]
  79247. */
  79248. overflow -= 2;
  79249. } while (overflow > 0);
  79250. /* Now recompute all bit lengths, scanning in increasing frequency.
  79251. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  79252. * lengths instead of fixing only the wrong ones. This idea is taken
  79253. * from 'ar' written by Haruhiko Okumura.)
  79254. */
  79255. for (bits = max_length; bits != 0; bits--) {
  79256. n = s->bl_count[bits];
  79257. while (n != 0) {
  79258. m = s->heap[--h];
  79259. if (m > max_code) continue;
  79260. if ((unsigned) tree[m].Len != (unsigned) bits) {
  79261. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  79262. s->opt_len += ((long)bits - (long)tree[m].Len)
  79263. *(long)tree[m].Freq;
  79264. tree[m].Len = (ush)bits;
  79265. }
  79266. n--;
  79267. }
  79268. }
  79269. }
  79270. /* ===========================================================================
  79271. * Generate the codes for a given tree and bit counts (which need not be
  79272. * optimal).
  79273. * IN assertion: the array bl_count contains the bit length statistics for
  79274. * the given tree and the field len is set for all tree elements.
  79275. * OUT assertion: the field code is set for all tree elements of non
  79276. * zero code length.
  79277. */
  79278. local void gen_codes (ct_data *tree, /* the tree to decorate */
  79279. int max_code, /* largest code with non zero frequency */
  79280. ushf *bl_count) /* number of codes at each bit length */
  79281. {
  79282. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  79283. ush code = 0; /* running code value */
  79284. int bits; /* bit index */
  79285. int n; /* code index */
  79286. /* The distribution counts are first used to generate the code values
  79287. * without bit reversal.
  79288. */
  79289. for (bits = 1; bits <= MAX_BITS; bits++) {
  79290. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  79291. }
  79292. /* Check that the bit counts in bl_count are consistent. The last code
  79293. * must be all ones.
  79294. */
  79295. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  79296. "inconsistent bit counts");
  79297. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  79298. for (n = 0; n <= max_code; n++) {
  79299. int len = tree[n].Len;
  79300. if (len == 0) continue;
  79301. /* Now reverse the bits */
  79302. tree[n].Code = bi_reverse(next_code[len]++, len);
  79303. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  79304. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  79305. }
  79306. }
  79307. /* ===========================================================================
  79308. * Construct one Huffman tree and assigns the code bit strings and lengths.
  79309. * Update the total bit length for the current block.
  79310. * IN assertion: the field freq is set for all tree elements.
  79311. * OUT assertions: the fields len and code are set to the optimal bit length
  79312. * and corresponding code. The length opt_len is updated; static_len is
  79313. * also updated if stree is not null. The field max_code is set.
  79314. */
  79315. local void build_tree (deflate_state *s,
  79316. tree_desc *desc) /* the tree descriptor */
  79317. {
  79318. ct_data *tree = desc->dyn_tree;
  79319. const ct_data *stree = desc->stat_desc->static_tree;
  79320. int elems = desc->stat_desc->elems;
  79321. int n, m; /* iterate over heap elements */
  79322. int max_code = -1; /* largest code with non zero frequency */
  79323. int node; /* new node being created */
  79324. /* Construct the initial heap, with least frequent element in
  79325. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  79326. * heap[0] is not used.
  79327. */
  79328. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  79329. for (n = 0; n < elems; n++) {
  79330. if (tree[n].Freq != 0) {
  79331. s->heap[++(s->heap_len)] = max_code = n;
  79332. s->depth[n] = 0;
  79333. } else {
  79334. tree[n].Len = 0;
  79335. }
  79336. }
  79337. /* The pkzip format requires that at least one distance code exists,
  79338. * and that at least one bit should be sent even if there is only one
  79339. * possible code. So to avoid special checks later on we force at least
  79340. * two codes of non zero frequency.
  79341. */
  79342. while (s->heap_len < 2) {
  79343. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  79344. tree[node].Freq = 1;
  79345. s->depth[node] = 0;
  79346. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  79347. /* node is 0 or 1 so it does not have extra bits */
  79348. }
  79349. desc->max_code = max_code;
  79350. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  79351. * establish sub-heaps of increasing lengths:
  79352. */
  79353. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  79354. /* Construct the Huffman tree by repeatedly combining the least two
  79355. * frequent nodes.
  79356. */
  79357. node = elems; /* next internal node of the tree */
  79358. do {
  79359. pqremove(s, tree, n); /* n = node of least frequency */
  79360. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  79361. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  79362. s->heap[--(s->heap_max)] = m;
  79363. /* Create a new node father of n and m */
  79364. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  79365. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  79366. s->depth[n] : s->depth[m]) + 1);
  79367. tree[n].Dad = tree[m].Dad = (ush)node;
  79368. #ifdef DUMP_BL_TREE
  79369. if (tree == s->bl_tree) {
  79370. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  79371. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  79372. }
  79373. #endif
  79374. /* and insert the new node in the heap */
  79375. s->heap[SMALLEST] = node++;
  79376. pqdownheap(s, tree, SMALLEST);
  79377. } while (s->heap_len >= 2);
  79378. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  79379. /* At this point, the fields freq and dad are set. We can now
  79380. * generate the bit lengths.
  79381. */
  79382. gen_bitlen(s, (tree_desc *)desc);
  79383. /* The field len is now set, we can generate the bit codes */
  79384. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  79385. }
  79386. /* ===========================================================================
  79387. * Scan a literal or distance tree to determine the frequencies of the codes
  79388. * in the bit length tree.
  79389. */
  79390. local void scan_tree (deflate_state *s,
  79391. ct_data *tree, /* the tree to be scanned */
  79392. int max_code) /* and its largest code of non zero frequency */
  79393. {
  79394. int n; /* iterates over all tree elements */
  79395. int prevlen = -1; /* last emitted length */
  79396. int curlen; /* length of current code */
  79397. int nextlen = tree[0].Len; /* length of next code */
  79398. int count = 0; /* repeat count of the current code */
  79399. int max_count = 7; /* max repeat count */
  79400. int min_count = 4; /* min repeat count */
  79401. if (nextlen == 0) max_count = 138, min_count = 3;
  79402. tree[max_code+1].Len = (ush)0xffff; /* guard */
  79403. for (n = 0; n <= max_code; n++) {
  79404. curlen = nextlen; nextlen = tree[n+1].Len;
  79405. if (++count < max_count && curlen == nextlen) {
  79406. continue;
  79407. } else if (count < min_count) {
  79408. s->bl_tree[curlen].Freq += count;
  79409. } else if (curlen != 0) {
  79410. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  79411. s->bl_tree[REP_3_6].Freq++;
  79412. } else if (count <= 10) {
  79413. s->bl_tree[REPZ_3_10].Freq++;
  79414. } else {
  79415. s->bl_tree[REPZ_11_138].Freq++;
  79416. }
  79417. count = 0; prevlen = curlen;
  79418. if (nextlen == 0) {
  79419. max_count = 138, min_count = 3;
  79420. } else if (curlen == nextlen) {
  79421. max_count = 6, min_count = 3;
  79422. } else {
  79423. max_count = 7, min_count = 4;
  79424. }
  79425. }
  79426. }
  79427. /* ===========================================================================
  79428. * Send a literal or distance tree in compressed form, using the codes in
  79429. * bl_tree.
  79430. */
  79431. local void send_tree (deflate_state *s,
  79432. ct_data *tree, /* the tree to be scanned */
  79433. int max_code) /* and its largest code of non zero frequency */
  79434. {
  79435. int n; /* iterates over all tree elements */
  79436. int prevlen = -1; /* last emitted length */
  79437. int curlen; /* length of current code */
  79438. int nextlen = tree[0].Len; /* length of next code */
  79439. int count = 0; /* repeat count of the current code */
  79440. int max_count = 7; /* max repeat count */
  79441. int min_count = 4; /* min repeat count */
  79442. /* tree[max_code+1].Len = -1; */ /* guard already set */
  79443. if (nextlen == 0) max_count = 138, min_count = 3;
  79444. for (n = 0; n <= max_code; n++) {
  79445. curlen = nextlen; nextlen = tree[n+1].Len;
  79446. if (++count < max_count && curlen == nextlen) {
  79447. continue;
  79448. } else if (count < min_count) {
  79449. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  79450. } else if (curlen != 0) {
  79451. if (curlen != prevlen) {
  79452. send_code(s, curlen, s->bl_tree); count--;
  79453. }
  79454. Assert(count >= 3 && count <= 6, " 3_6?");
  79455. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  79456. } else if (count <= 10) {
  79457. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  79458. } else {
  79459. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  79460. }
  79461. count = 0; prevlen = curlen;
  79462. if (nextlen == 0) {
  79463. max_count = 138, min_count = 3;
  79464. } else if (curlen == nextlen) {
  79465. max_count = 6, min_count = 3;
  79466. } else {
  79467. max_count = 7, min_count = 4;
  79468. }
  79469. }
  79470. }
  79471. /* ===========================================================================
  79472. * Construct the Huffman tree for the bit lengths and return the index in
  79473. * bl_order of the last bit length code to send.
  79474. */
  79475. local int build_bl_tree (deflate_state *s)
  79476. {
  79477. int max_blindex; /* index of last bit length code of non zero freq */
  79478. /* Determine the bit length frequencies for literal and distance trees */
  79479. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  79480. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  79481. /* Build the bit length tree: */
  79482. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  79483. /* opt_len now includes the length of the tree representations, except
  79484. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  79485. */
  79486. /* Determine the number of bit length codes to send. The pkzip format
  79487. * requires that at least 4 bit length codes be sent. (appnote.txt says
  79488. * 3 but the actual value used is 4.)
  79489. */
  79490. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  79491. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  79492. }
  79493. /* Update opt_len to include the bit length tree and counts */
  79494. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  79495. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  79496. s->opt_len, s->static_len));
  79497. return max_blindex;
  79498. }
  79499. /* ===========================================================================
  79500. * Send the header for a block using dynamic Huffman trees: the counts, the
  79501. * lengths of the bit length codes, the literal tree and the distance tree.
  79502. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  79503. */
  79504. local void send_all_trees (deflate_state *s,
  79505. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  79506. {
  79507. int rank; /* index in bl_order */
  79508. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  79509. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  79510. "too many codes");
  79511. Tracev((stderr, "\nbl counts: "));
  79512. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  79513. send_bits(s, dcodes-1, 5);
  79514. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  79515. for (rank = 0; rank < blcodes; rank++) {
  79516. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  79517. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  79518. }
  79519. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  79520. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  79521. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  79522. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  79523. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  79524. }
  79525. /* ===========================================================================
  79526. * Send a stored block
  79527. */
  79528. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  79529. {
  79530. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  79531. #ifdef DEBUG
  79532. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  79533. s->compressed_len += (stored_len + 4) << 3;
  79534. #endif
  79535. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  79536. }
  79537. /* ===========================================================================
  79538. * Send one empty static block to give enough lookahead for inflate.
  79539. * This takes 10 bits, of which 7 may remain in the bit buffer.
  79540. * The current inflate code requires 9 bits of lookahead. If the
  79541. * last two codes for the previous block (real code plus EOB) were coded
  79542. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  79543. * the last real code. In this case we send two empty static blocks instead
  79544. * of one. (There are no problems if the previous block is stored or fixed.)
  79545. * To simplify the code, we assume the worst case of last real code encoded
  79546. * on one bit only.
  79547. */
  79548. void _tr_align (deflate_state *s)
  79549. {
  79550. send_bits(s, STATIC_TREES<<1, 3);
  79551. send_code(s, END_BLOCK, static_ltree);
  79552. #ifdef DEBUG
  79553. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  79554. #endif
  79555. bi_flush(s);
  79556. /* Of the 10 bits for the empty block, we have already sent
  79557. * (10 - bi_valid) bits. The lookahead for the last real code (before
  79558. * the EOB of the previous block) was thus at least one plus the length
  79559. * of the EOB plus what we have just sent of the empty static block.
  79560. */
  79561. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  79562. send_bits(s, STATIC_TREES<<1, 3);
  79563. send_code(s, END_BLOCK, static_ltree);
  79564. #ifdef DEBUG
  79565. s->compressed_len += 10L;
  79566. #endif
  79567. bi_flush(s);
  79568. }
  79569. s->last_eob_len = 7;
  79570. }
  79571. /* ===========================================================================
  79572. * Determine the best encoding for the current block: dynamic trees, static
  79573. * trees or store, and output the encoded block to the zip file.
  79574. */
  79575. void _tr_flush_block (deflate_state *s,
  79576. charf *buf, /* input block, or NULL if too old */
  79577. ulg stored_len, /* length of input block */
  79578. int eof) /* true if this is the last block for a file */
  79579. {
  79580. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  79581. int max_blindex = 0; /* index of last bit length code of non zero freq */
  79582. /* Build the Huffman trees unless a stored block is forced */
  79583. if (s->level > 0) {
  79584. /* Check if the file is binary or text */
  79585. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  79586. set_data_type(s);
  79587. /* Construct the literal and distance trees */
  79588. build_tree(s, (tree_desc *)(&(s->l_desc)));
  79589. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  79590. s->static_len));
  79591. build_tree(s, (tree_desc *)(&(s->d_desc)));
  79592. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  79593. s->static_len));
  79594. /* At this point, opt_len and static_len are the total bit lengths of
  79595. * the compressed block data, excluding the tree representations.
  79596. */
  79597. /* Build the bit length tree for the above two trees, and get the index
  79598. * in bl_order of the last bit length code to send.
  79599. */
  79600. max_blindex = build_bl_tree(s);
  79601. /* Determine the best encoding. Compute the block lengths in bytes. */
  79602. opt_lenb = (s->opt_len+3+7)>>3;
  79603. static_lenb = (s->static_len+3+7)>>3;
  79604. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  79605. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  79606. s->last_lit));
  79607. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  79608. } else {
  79609. Assert(buf != (char*)0, "lost buf");
  79610. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  79611. }
  79612. #ifdef FORCE_STORED
  79613. if (buf != (char*)0) { /* force stored block */
  79614. #else
  79615. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  79616. /* 4: two words for the lengths */
  79617. #endif
  79618. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  79619. * Otherwise we can't have processed more than WSIZE input bytes since
  79620. * the last block flush, because compression would have been
  79621. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  79622. * transform a block into a stored block.
  79623. */
  79624. _tr_stored_block(s, buf, stored_len, eof);
  79625. #ifdef FORCE_STATIC
  79626. } else if (static_lenb >= 0) { /* force static trees */
  79627. #else
  79628. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  79629. #endif
  79630. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  79631. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  79632. #ifdef DEBUG
  79633. s->compressed_len += 3 + s->static_len;
  79634. #endif
  79635. } else {
  79636. send_bits(s, (DYN_TREES<<1)+eof, 3);
  79637. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  79638. max_blindex+1);
  79639. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  79640. #ifdef DEBUG
  79641. s->compressed_len += 3 + s->opt_len;
  79642. #endif
  79643. }
  79644. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  79645. /* The above check is made mod 2^32, for files larger than 512 MB
  79646. * and uLong implemented on 32 bits.
  79647. */
  79648. init_block(s);
  79649. if (eof) {
  79650. bi_windup(s);
  79651. #ifdef DEBUG
  79652. s->compressed_len += 7; /* align on byte boundary */
  79653. #endif
  79654. }
  79655. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  79656. s->compressed_len-7*eof));
  79657. }
  79658. /* ===========================================================================
  79659. * Save the match info and tally the frequency counts. Return true if
  79660. * the current block must be flushed.
  79661. */
  79662. int _tr_tally (deflate_state *s,
  79663. unsigned dist, /* distance of matched string */
  79664. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  79665. {
  79666. s->d_buf[s->last_lit] = (ush)dist;
  79667. s->l_buf[s->last_lit++] = (uch)lc;
  79668. if (dist == 0) {
  79669. /* lc is the unmatched char */
  79670. s->dyn_ltree[lc].Freq++;
  79671. } else {
  79672. s->matches++;
  79673. /* Here, lc is the match length - MIN_MATCH */
  79674. dist--; /* dist = match distance - 1 */
  79675. Assert((ush)dist < (ush)MAX_DIST(s) &&
  79676. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  79677. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  79678. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  79679. s->dyn_dtree[d_code(dist)].Freq++;
  79680. }
  79681. #ifdef TRUNCATE_BLOCK
  79682. /* Try to guess if it is profitable to stop the current block here */
  79683. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  79684. /* Compute an upper bound for the compressed length */
  79685. ulg out_length = (ulg)s->last_lit*8L;
  79686. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  79687. int dcode;
  79688. for (dcode = 0; dcode < D_CODES; dcode++) {
  79689. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  79690. (5L+extra_dbits[dcode]);
  79691. }
  79692. out_length >>= 3;
  79693. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  79694. s->last_lit, in_length, out_length,
  79695. 100L - out_length*100L/in_length));
  79696. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  79697. }
  79698. #endif
  79699. return (s->last_lit == s->lit_bufsize-1);
  79700. /* We avoid equality with lit_bufsize because of wraparound at 64K
  79701. * on 16 bit machines and because stored blocks are restricted to
  79702. * 64K-1 bytes.
  79703. */
  79704. }
  79705. /* ===========================================================================
  79706. * Send the block data compressed using the given Huffman trees
  79707. */
  79708. local void compress_block (deflate_state *s,
  79709. ct_data *ltree, /* literal tree */
  79710. ct_data *dtree) /* distance tree */
  79711. {
  79712. unsigned dist; /* distance of matched string */
  79713. int lc; /* match length or unmatched char (if dist == 0) */
  79714. unsigned lx = 0; /* running index in l_buf */
  79715. unsigned code; /* the code to send */
  79716. int extra; /* number of extra bits to send */
  79717. if (s->last_lit != 0) do {
  79718. dist = s->d_buf[lx];
  79719. lc = s->l_buf[lx++];
  79720. if (dist == 0) {
  79721. send_code(s, lc, ltree); /* send a literal byte */
  79722. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  79723. } else {
  79724. /* Here, lc is the match length - MIN_MATCH */
  79725. code = _length_code[lc];
  79726. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  79727. extra = extra_lbits[code];
  79728. if (extra != 0) {
  79729. lc -= base_length[code];
  79730. send_bits(s, lc, extra); /* send the extra length bits */
  79731. }
  79732. dist--; /* dist is now the match distance - 1 */
  79733. code = d_code(dist);
  79734. Assert (code < D_CODES, "bad d_code");
  79735. send_code(s, code, dtree); /* send the distance code */
  79736. extra = extra_dbits[code];
  79737. if (extra != 0) {
  79738. dist -= base_dist[code];
  79739. send_bits(s, dist, extra); /* send the extra distance bits */
  79740. }
  79741. } /* literal or match pair ? */
  79742. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  79743. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  79744. "pendingBuf overflow");
  79745. } while (lx < s->last_lit);
  79746. send_code(s, END_BLOCK, ltree);
  79747. s->last_eob_len = ltree[END_BLOCK].Len;
  79748. }
  79749. /* ===========================================================================
  79750. * Set the data type to BINARY or TEXT, using a crude approximation:
  79751. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  79752. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  79753. * IN assertion: the fields Freq of dyn_ltree are set.
  79754. */
  79755. local void set_data_type (deflate_state *s)
  79756. {
  79757. int n;
  79758. for (n = 0; n < 9; n++)
  79759. if (s->dyn_ltree[n].Freq != 0)
  79760. break;
  79761. if (n == 9)
  79762. for (n = 14; n < 32; n++)
  79763. if (s->dyn_ltree[n].Freq != 0)
  79764. break;
  79765. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  79766. }
  79767. /* ===========================================================================
  79768. * Reverse the first len bits of a code, using straightforward code (a faster
  79769. * method would use a table)
  79770. * IN assertion: 1 <= len <= 15
  79771. */
  79772. local unsigned bi_reverse (unsigned code, int len)
  79773. {
  79774. register unsigned res = 0;
  79775. do {
  79776. res |= code & 1;
  79777. code >>= 1, res <<= 1;
  79778. } while (--len > 0);
  79779. return res >> 1;
  79780. }
  79781. /* ===========================================================================
  79782. * Flush the bit buffer, keeping at most 7 bits in it.
  79783. */
  79784. local void bi_flush (deflate_state *s)
  79785. {
  79786. if (s->bi_valid == 16) {
  79787. put_short(s, s->bi_buf);
  79788. s->bi_buf = 0;
  79789. s->bi_valid = 0;
  79790. } else if (s->bi_valid >= 8) {
  79791. put_byte(s, (Byte)s->bi_buf);
  79792. s->bi_buf >>= 8;
  79793. s->bi_valid -= 8;
  79794. }
  79795. }
  79796. /* ===========================================================================
  79797. * Flush the bit buffer and align the output on a byte boundary
  79798. */
  79799. local void bi_windup (deflate_state *s)
  79800. {
  79801. if (s->bi_valid > 8) {
  79802. put_short(s, s->bi_buf);
  79803. } else if (s->bi_valid > 0) {
  79804. put_byte(s, (Byte)s->bi_buf);
  79805. }
  79806. s->bi_buf = 0;
  79807. s->bi_valid = 0;
  79808. #ifdef DEBUG
  79809. s->bits_sent = (s->bits_sent+7) & ~7;
  79810. #endif
  79811. }
  79812. /* ===========================================================================
  79813. * Copy a stored block, storing first the length and its
  79814. * one's complement if requested.
  79815. */
  79816. local void copy_block(deflate_state *s,
  79817. charf *buf, /* the input data */
  79818. unsigned len, /* its length */
  79819. int header) /* true if block header must be written */
  79820. {
  79821. bi_windup(s); /* align on byte boundary */
  79822. s->last_eob_len = 8; /* enough lookahead for inflate */
  79823. if (header) {
  79824. put_short(s, (ush)len);
  79825. put_short(s, (ush)~len);
  79826. #ifdef DEBUG
  79827. s->bits_sent += 2*16;
  79828. #endif
  79829. }
  79830. #ifdef DEBUG
  79831. s->bits_sent += (ulg)len<<3;
  79832. #endif
  79833. while (len--) {
  79834. put_byte(s, *buf++);
  79835. }
  79836. }
  79837. /********* End of inlined file: trees.c *********/
  79838. /********* Start of inlined file: uncompr.c *********/
  79839. /* @(#) $Id: uncompr.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79840. #define ZLIB_INTERNAL
  79841. /* ===========================================================================
  79842. Decompresses the source buffer into the destination buffer. sourceLen is
  79843. the byte length of the source buffer. Upon entry, destLen is the total
  79844. size of the destination buffer, which must be large enough to hold the
  79845. entire uncompressed data. (The size of the uncompressed data must have
  79846. been saved previously by the compressor and transmitted to the decompressor
  79847. by some mechanism outside the scope of this compression library.)
  79848. Upon exit, destLen is the actual size of the compressed buffer.
  79849. This function can be used to decompress a whole file at once if the
  79850. input file is mmap'ed.
  79851. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79852. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79853. buffer, or Z_DATA_ERROR if the input data was corrupted.
  79854. */
  79855. int ZEXPORT uncompress (Bytef *dest,
  79856. uLongf *destLen,
  79857. const Bytef *source,
  79858. uLong sourceLen)
  79859. {
  79860. z_stream stream;
  79861. int err;
  79862. stream.next_in = (Bytef*)source;
  79863. stream.avail_in = (uInt)sourceLen;
  79864. /* Check for source > 64K on 16-bit machine: */
  79865. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79866. stream.next_out = dest;
  79867. stream.avail_out = (uInt)*destLen;
  79868. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79869. stream.zalloc = (alloc_func)0;
  79870. stream.zfree = (free_func)0;
  79871. err = inflateInit(&stream);
  79872. if (err != Z_OK) return err;
  79873. err = inflate(&stream, Z_FINISH);
  79874. if (err != Z_STREAM_END) {
  79875. inflateEnd(&stream);
  79876. if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))
  79877. return Z_DATA_ERROR;
  79878. return err;
  79879. }
  79880. *destLen = stream.total_out;
  79881. err = inflateEnd(&stream);
  79882. return err;
  79883. }
  79884. /********* End of inlined file: uncompr.c *********/
  79885. /********* Start of inlined file: zutil.c *********/
  79886. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79887. #ifndef NO_DUMMY_DECL
  79888. struct internal_state {int dummy;}; /* for buggy compilers */
  79889. #endif
  79890. const char * const z_errmsg[10] = {
  79891. "need dictionary", /* Z_NEED_DICT 2 */
  79892. "stream end", /* Z_STREAM_END 1 */
  79893. "", /* Z_OK 0 */
  79894. "file error", /* Z_ERRNO (-1) */
  79895. "stream error", /* Z_STREAM_ERROR (-2) */
  79896. "data error", /* Z_DATA_ERROR (-3) */
  79897. "insufficient memory", /* Z_MEM_ERROR (-4) */
  79898. "buffer error", /* Z_BUF_ERROR (-5) */
  79899. "incompatible version",/* Z_VERSION_ERROR (-6) */
  79900. ""};
  79901. /*const char * ZEXPORT zlibVersion()
  79902. {
  79903. return ZLIB_VERSION;
  79904. }
  79905. uLong ZEXPORT zlibCompileFlags()
  79906. {
  79907. uLong flags;
  79908. flags = 0;
  79909. switch (sizeof(uInt)) {
  79910. case 2: break;
  79911. case 4: flags += 1; break;
  79912. case 8: flags += 2; break;
  79913. default: flags += 3;
  79914. }
  79915. switch (sizeof(uLong)) {
  79916. case 2: break;
  79917. case 4: flags += 1 << 2; break;
  79918. case 8: flags += 2 << 2; break;
  79919. default: flags += 3 << 2;
  79920. }
  79921. switch (sizeof(voidpf)) {
  79922. case 2: break;
  79923. case 4: flags += 1 << 4; break;
  79924. case 8: flags += 2 << 4; break;
  79925. default: flags += 3 << 4;
  79926. }
  79927. switch (sizeof(z_off_t)) {
  79928. case 2: break;
  79929. case 4: flags += 1 << 6; break;
  79930. case 8: flags += 2 << 6; break;
  79931. default: flags += 3 << 6;
  79932. }
  79933. #ifdef DEBUG
  79934. flags += 1 << 8;
  79935. #endif
  79936. #if defined(ASMV) || defined(ASMINF)
  79937. flags += 1 << 9;
  79938. #endif
  79939. #ifdef ZLIB_WINAPI
  79940. flags += 1 << 10;
  79941. #endif
  79942. #ifdef BUILDFIXED
  79943. flags += 1 << 12;
  79944. #endif
  79945. #ifdef DYNAMIC_CRC_TABLE
  79946. flags += 1 << 13;
  79947. #endif
  79948. #ifdef NO_GZCOMPRESS
  79949. flags += 1L << 16;
  79950. #endif
  79951. #ifdef NO_GZIP
  79952. flags += 1L << 17;
  79953. #endif
  79954. #ifdef PKZIP_BUG_WORKAROUND
  79955. flags += 1L << 20;
  79956. #endif
  79957. #ifdef FASTEST
  79958. flags += 1L << 21;
  79959. #endif
  79960. #ifdef STDC
  79961. # ifdef NO_vsnprintf
  79962. flags += 1L << 25;
  79963. # ifdef HAS_vsprintf_void
  79964. flags += 1L << 26;
  79965. # endif
  79966. # else
  79967. # ifdef HAS_vsnprintf_void
  79968. flags += 1L << 26;
  79969. # endif
  79970. # endif
  79971. #else
  79972. flags += 1L << 24;
  79973. # ifdef NO_snprintf
  79974. flags += 1L << 25;
  79975. # ifdef HAS_sprintf_void
  79976. flags += 1L << 26;
  79977. # endif
  79978. # else
  79979. # ifdef HAS_snprintf_void
  79980. flags += 1L << 26;
  79981. # endif
  79982. # endif
  79983. #endif
  79984. return flags;
  79985. }*/
  79986. #ifdef DEBUG
  79987. # ifndef verbose
  79988. # define verbose 0
  79989. # endif
  79990. int z_verbose = verbose;
  79991. void z_error (char *m)
  79992. {
  79993. fprintf(stderr, "%s\n", m);
  79994. exit(1);
  79995. }
  79996. #endif
  79997. /* exported to allow conversion of error code to string for compress() and
  79998. * uncompress()
  79999. */
  80000. const char * ZEXPORT zError(int err)
  80001. {
  80002. return ERR_MSG(err);
  80003. }
  80004. #if defined(_WIN32_WCE)
  80005. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  80006. * errno. We define it as a global variable to simplify porting.
  80007. * Its value is always 0 and should not be used.
  80008. */
  80009. int errno = 0;
  80010. #endif
  80011. #ifndef HAVE_MEMCPY
  80012. void zmemcpy(dest, source, len)
  80013. Bytef* dest;
  80014. const Bytef* source;
  80015. uInt len;
  80016. {
  80017. if (len == 0) return;
  80018. do {
  80019. *dest++ = *source++; /* ??? to be unrolled */
  80020. } while (--len != 0);
  80021. }
  80022. int zmemcmp(s1, s2, len)
  80023. const Bytef* s1;
  80024. const Bytef* s2;
  80025. uInt len;
  80026. {
  80027. uInt j;
  80028. for (j = 0; j < len; j++) {
  80029. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  80030. }
  80031. return 0;
  80032. }
  80033. void zmemzero(dest, len)
  80034. Bytef* dest;
  80035. uInt len;
  80036. {
  80037. if (len == 0) return;
  80038. do {
  80039. *dest++ = 0; /* ??? to be unrolled */
  80040. } while (--len != 0);
  80041. }
  80042. #endif
  80043. #ifdef SYS16BIT
  80044. #ifdef __TURBOC__
  80045. /* Turbo C in 16-bit mode */
  80046. # define MY_ZCALLOC
  80047. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  80048. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  80049. * must fix the pointer. Warning: the pointer must be put back to its
  80050. * original form in order to free it, use zcfree().
  80051. */
  80052. #define MAX_PTR 10
  80053. /* 10*64K = 640K */
  80054. local int next_ptr = 0;
  80055. typedef struct ptr_table_s {
  80056. voidpf org_ptr;
  80057. voidpf new_ptr;
  80058. } ptr_table;
  80059. local ptr_table table[MAX_PTR];
  80060. /* This table is used to remember the original form of pointers
  80061. * to large buffers (64K). Such pointers are normalized with a zero offset.
  80062. * Since MSDOS is not a preemptive multitasking OS, this table is not
  80063. * protected from concurrent access. This hack doesn't work anyway on
  80064. * a protected system like OS/2. Use Microsoft C instead.
  80065. */
  80066. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  80067. {
  80068. voidpf buf = opaque; /* just to make some compilers happy */
  80069. ulg bsize = (ulg)items*size;
  80070. /* If we allocate less than 65520 bytes, we assume that farmalloc
  80071. * will return a usable pointer which doesn't have to be normalized.
  80072. */
  80073. if (bsize < 65520L) {
  80074. buf = farmalloc(bsize);
  80075. if (*(ush*)&buf != 0) return buf;
  80076. } else {
  80077. buf = farmalloc(bsize + 16L);
  80078. }
  80079. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  80080. table[next_ptr].org_ptr = buf;
  80081. /* Normalize the pointer to seg:0 */
  80082. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  80083. *(ush*)&buf = 0;
  80084. table[next_ptr++].new_ptr = buf;
  80085. return buf;
  80086. }
  80087. void zcfree (voidpf opaque, voidpf ptr)
  80088. {
  80089. int n;
  80090. if (*(ush*)&ptr != 0) { /* object < 64K */
  80091. farfree(ptr);
  80092. return;
  80093. }
  80094. /* Find the original pointer */
  80095. for (n = 0; n < next_ptr; n++) {
  80096. if (ptr != table[n].new_ptr) continue;
  80097. farfree(table[n].org_ptr);
  80098. while (++n < next_ptr) {
  80099. table[n-1] = table[n];
  80100. }
  80101. next_ptr--;
  80102. return;
  80103. }
  80104. ptr = opaque; /* just to make some compilers happy */
  80105. Assert(0, "zcfree: ptr not found");
  80106. }
  80107. #endif /* __TURBOC__ */
  80108. #ifdef M_I86
  80109. /* Microsoft C in 16-bit mode */
  80110. # define MY_ZCALLOC
  80111. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  80112. # define _halloc halloc
  80113. # define _hfree hfree
  80114. #endif
  80115. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  80116. {
  80117. if (opaque) opaque = 0; /* to make compiler happy */
  80118. return _halloc((long)items, size);
  80119. }
  80120. void zcfree (voidpf opaque, voidpf ptr)
  80121. {
  80122. if (opaque) opaque = 0; /* to make compiler happy */
  80123. _hfree(ptr);
  80124. }
  80125. #endif /* M_I86 */
  80126. #endif /* SYS16BIT */
  80127. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  80128. #ifndef STDC
  80129. extern voidp malloc OF((uInt size));
  80130. extern voidp calloc OF((uInt items, uInt size));
  80131. extern void free OF((voidpf ptr));
  80132. #endif
  80133. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  80134. {
  80135. if (opaque) items += size - size; /* make compiler happy */
  80136. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  80137. (voidpf)calloc(items, size);
  80138. }
  80139. void zcfree (voidpf opaque, voidpf ptr)
  80140. {
  80141. free(ptr);
  80142. if (opaque) return; /* make compiler happy */
  80143. }
  80144. #endif /* MY_ZCALLOC */
  80145. /********* End of inlined file: zutil.c *********/
  80146. #undef Byte
  80147. }
  80148. }
  80149. #if JUCE_MSVC
  80150. #pragma warning (pop)
  80151. #endif
  80152. BEGIN_JUCE_NAMESPACE
  80153. using namespace zlibNamespace;
  80154. // internal helper object that holds the zlib structures so they don't have to be
  80155. // included publicly.
  80156. class GZIPDecompressHelper
  80157. {
  80158. private:
  80159. z_stream* stream;
  80160. uint8* data;
  80161. int dataSize;
  80162. public:
  80163. bool finished, needsDictionary, error;
  80164. GZIPDecompressHelper (const bool noWrap) throw()
  80165. : data (0),
  80166. dataSize (0),
  80167. finished (false),
  80168. needsDictionary (false),
  80169. error (false)
  80170. {
  80171. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  80172. if (inflateInit2 (stream, (noWrap) ? -MAX_WBITS
  80173. : MAX_WBITS) != Z_OK)
  80174. {
  80175. juce_free (stream);
  80176. stream = 0;
  80177. error = true;
  80178. finished = true;
  80179. }
  80180. }
  80181. ~GZIPDecompressHelper() throw()
  80182. {
  80183. if (stream != 0)
  80184. {
  80185. inflateEnd (stream);
  80186. juce_free (stream);
  80187. }
  80188. }
  80189. bool needsInput() const throw() { return dataSize <= 0; }
  80190. void setInput (uint8* const data_, const int size) throw()
  80191. {
  80192. data = data_;
  80193. dataSize = size;
  80194. }
  80195. int doNextBlock (uint8* const dest, const int destSize) throw()
  80196. {
  80197. if (stream != 0 && data != 0 && ! finished)
  80198. {
  80199. stream->next_in = data;
  80200. stream->next_out = dest;
  80201. stream->avail_in = dataSize;
  80202. stream->avail_out = destSize;
  80203. switch (inflate (stream, Z_PARTIAL_FLUSH))
  80204. {
  80205. case Z_STREAM_END:
  80206. finished = true;
  80207. // deliberate fall-through
  80208. case Z_OK:
  80209. data += dataSize - stream->avail_in;
  80210. dataSize = stream->avail_in;
  80211. return destSize - stream->avail_out;
  80212. case Z_NEED_DICT:
  80213. needsDictionary = true;
  80214. data += dataSize - stream->avail_in;
  80215. dataSize = stream->avail_in;
  80216. break;
  80217. case Z_DATA_ERROR:
  80218. case Z_MEM_ERROR:
  80219. error = true;
  80220. default:
  80221. break;
  80222. }
  80223. }
  80224. return 0;
  80225. }
  80226. };
  80227. const int gzipDecompBufferSize = 32768;
  80228. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  80229. const bool deleteSourceWhenDestroyed_,
  80230. const bool noWrap_,
  80231. const int64 uncompressedStreamLength_)
  80232. : sourceStream (sourceStream_),
  80233. uncompressedStreamLength (uncompressedStreamLength_),
  80234. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  80235. noWrap (noWrap_),
  80236. isEof (false),
  80237. activeBufferSize (0),
  80238. originalSourcePos (sourceStream_->getPosition()),
  80239. currentPos (0)
  80240. {
  80241. buffer = (uint8*) juce_malloc (gzipDecompBufferSize);
  80242. helper = new GZIPDecompressHelper (noWrap_);
  80243. }
  80244. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  80245. {
  80246. juce_free (buffer);
  80247. if (deleteSourceWhenDestroyed)
  80248. delete sourceStream;
  80249. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  80250. delete h;
  80251. }
  80252. int64 GZIPDecompressorInputStream::getTotalLength()
  80253. {
  80254. return uncompressedStreamLength;
  80255. }
  80256. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  80257. {
  80258. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  80259. if ((howMany > 0) && ! isEof)
  80260. {
  80261. jassert (destBuffer != 0);
  80262. if (destBuffer != 0)
  80263. {
  80264. int numRead = 0;
  80265. uint8* d = (uint8*) destBuffer;
  80266. while (! h->error)
  80267. {
  80268. const int n = h->doNextBlock (d, howMany);
  80269. currentPos += n;
  80270. if (n == 0)
  80271. {
  80272. if (h->finished || h->needsDictionary)
  80273. {
  80274. isEof = true;
  80275. return numRead;
  80276. }
  80277. if (h->needsInput())
  80278. {
  80279. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  80280. if (activeBufferSize > 0)
  80281. {
  80282. h->setInput ((uint8*) buffer, activeBufferSize);
  80283. }
  80284. else
  80285. {
  80286. isEof = true;
  80287. return numRead;
  80288. }
  80289. }
  80290. }
  80291. else
  80292. {
  80293. numRead += n;
  80294. howMany -= n;
  80295. d += n;
  80296. if (howMany <= 0)
  80297. return numRead;
  80298. }
  80299. }
  80300. }
  80301. }
  80302. return 0;
  80303. }
  80304. bool GZIPDecompressorInputStream::isExhausted()
  80305. {
  80306. const GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  80307. return h->error || isEof;
  80308. }
  80309. int64 GZIPDecompressorInputStream::getPosition()
  80310. {
  80311. return currentPos;
  80312. }
  80313. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  80314. {
  80315. if (newPos != currentPos)
  80316. {
  80317. // reset the stream and start again..
  80318. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  80319. delete h;
  80320. isEof = false;
  80321. activeBufferSize = 0;
  80322. currentPos = 0;
  80323. helper = new GZIPDecompressHelper (noWrap);
  80324. sourceStream->setPosition (originalSourcePos);
  80325. skipNextBytes (newPos);
  80326. }
  80327. return true;
  80328. }
  80329. END_JUCE_NAMESPACE
  80330. /********* End of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  80331. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  80332. /********* Start of inlined file: juce_FlacAudioFormat.cpp *********/
  80333. #ifdef _MSC_VER
  80334. #include <windows.h>
  80335. #endif
  80336. #if JUCE_USE_FLAC
  80337. #ifdef _MSC_VER
  80338. #pragma warning (disable : 4505)
  80339. #pragma warning (push)
  80340. #endif
  80341. namespace FlacNamespace
  80342. {
  80343. #define FLAC__NO_DLL 1
  80344. #if ! defined (SIZE_MAX)
  80345. #define SIZE_MAX 0xffffffff
  80346. #endif
  80347. #define __STDC_LIMIT_MACROS 1
  80348. /********* Start of inlined file: all.h *********/
  80349. #ifndef FLAC__ALL_H
  80350. #define FLAC__ALL_H
  80351. /********* Start of inlined file: export.h *********/
  80352. #ifndef FLAC__EXPORT_H
  80353. #define FLAC__EXPORT_H
  80354. /** \file include/FLAC/export.h
  80355. *
  80356. * \brief
  80357. * This module contains #defines and symbols for exporting function
  80358. * calls, and providing version information and compiled-in features.
  80359. *
  80360. * See the \link flac_export export \endlink module.
  80361. */
  80362. /** \defgroup flac_export FLAC/export.h: export symbols
  80363. * \ingroup flac
  80364. *
  80365. * \brief
  80366. * This module contains #defines and symbols for exporting function
  80367. * calls, and providing version information and compiled-in features.
  80368. *
  80369. * If you are compiling with MSVC and will link to the static library
  80370. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  80371. * make sure the symbols are exported properly.
  80372. *
  80373. * \{
  80374. */
  80375. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  80376. #define FLAC_API
  80377. #else
  80378. #ifdef FLAC_API_EXPORTS
  80379. #define FLAC_API _declspec(dllexport)
  80380. #else
  80381. #define FLAC_API _declspec(dllimport)
  80382. #endif
  80383. #endif
  80384. /** These #defines will mirror the libtool-based library version number, see
  80385. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  80386. */
  80387. #define FLAC_API_VERSION_CURRENT 10
  80388. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  80389. #define FLAC_API_VERSION_AGE 2 /**< see above */
  80390. #ifdef __cplusplus
  80391. extern "C" {
  80392. #endif
  80393. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  80394. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  80395. #ifdef __cplusplus
  80396. }
  80397. #endif
  80398. /* \} */
  80399. #endif
  80400. /********* End of inlined file: export.h *********/
  80401. /********* Start of inlined file: assert.h *********/
  80402. #ifndef FLAC__ASSERT_H
  80403. #define FLAC__ASSERT_H
  80404. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  80405. #ifdef DEBUG
  80406. #include <assert.h>
  80407. #define FLAC__ASSERT(x) assert(x)
  80408. #define FLAC__ASSERT_DECLARATION(x) x
  80409. #else
  80410. #define FLAC__ASSERT(x)
  80411. #define FLAC__ASSERT_DECLARATION(x)
  80412. #endif
  80413. #endif
  80414. /********* End of inlined file: assert.h *********/
  80415. /********* Start of inlined file: callback.h *********/
  80416. #ifndef FLAC__CALLBACK_H
  80417. #define FLAC__CALLBACK_H
  80418. /********* Start of inlined file: ordinals.h *********/
  80419. #ifndef FLAC__ORDINALS_H
  80420. #define FLAC__ORDINALS_H
  80421. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  80422. #include <inttypes.h>
  80423. #endif
  80424. typedef signed char FLAC__int8;
  80425. typedef unsigned char FLAC__uint8;
  80426. #if defined(_MSC_VER) || defined(__BORLANDC__)
  80427. typedef __int16 FLAC__int16;
  80428. typedef __int32 FLAC__int32;
  80429. typedef __int64 FLAC__int64;
  80430. typedef unsigned __int16 FLAC__uint16;
  80431. typedef unsigned __int32 FLAC__uint32;
  80432. typedef unsigned __int64 FLAC__uint64;
  80433. #elif defined(__EMX__)
  80434. typedef short FLAC__int16;
  80435. typedef long FLAC__int32;
  80436. typedef long long FLAC__int64;
  80437. typedef unsigned short FLAC__uint16;
  80438. typedef unsigned long FLAC__uint32;
  80439. typedef unsigned long long FLAC__uint64;
  80440. #else
  80441. typedef int16_t FLAC__int16;
  80442. typedef int32_t FLAC__int32;
  80443. typedef int64_t FLAC__int64;
  80444. typedef uint16_t FLAC__uint16;
  80445. typedef uint32_t FLAC__uint32;
  80446. typedef uint64_t FLAC__uint64;
  80447. #endif
  80448. typedef int FLAC__bool;
  80449. typedef FLAC__uint8 FLAC__byte;
  80450. #ifdef true
  80451. #undef true
  80452. #endif
  80453. #ifdef false
  80454. #undef false
  80455. #endif
  80456. #ifndef __cplusplus
  80457. #define true 1
  80458. #define false 0
  80459. #endif
  80460. #endif
  80461. /********* End of inlined file: ordinals.h *********/
  80462. #include <stdlib.h> /* for size_t */
  80463. /** \file include/FLAC/callback.h
  80464. *
  80465. * \brief
  80466. * This module defines the structures for describing I/O callbacks
  80467. * to the other FLAC interfaces.
  80468. *
  80469. * See the detailed documentation for callbacks in the
  80470. * \link flac_callbacks callbacks \endlink module.
  80471. */
  80472. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  80473. * \ingroup flac
  80474. *
  80475. * \brief
  80476. * This module defines the structures for describing I/O callbacks
  80477. * to the other FLAC interfaces.
  80478. *
  80479. * The purpose of the I/O callback functions is to create a common way
  80480. * for the metadata interfaces to handle I/O.
  80481. *
  80482. * Originally the metadata interfaces required filenames as the way of
  80483. * specifying FLAC files to operate on. This is problematic in some
  80484. * environments so there is an additional option to specify a set of
  80485. * callbacks for doing I/O on the FLAC file, instead of the filename.
  80486. *
  80487. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  80488. * opaque structure for a data source.
  80489. *
  80490. * The callback function prototypes are similar (but not identical) to the
  80491. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  80492. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  80493. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  80494. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  80495. * is required. \warning You generally CANNOT directly use fseek or ftell
  80496. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  80497. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  80498. * large files. You will have to find an equivalent function (e.g. ftello),
  80499. * or write a wrapper. The same is true for feof() since this is usually
  80500. * implemented as a macro, not as a function whose address can be taken.
  80501. *
  80502. * \{
  80503. */
  80504. #ifdef __cplusplus
  80505. extern "C" {
  80506. #endif
  80507. /** This is the opaque handle type used by the callbacks. Typically
  80508. * this is a \c FILE* or address of a file descriptor.
  80509. */
  80510. typedef void* FLAC__IOHandle;
  80511. /** Signature for the read callback.
  80512. * The signature and semantics match POSIX fread() implementations
  80513. * and can generally be used interchangeably.
  80514. *
  80515. * \param ptr The address of the read buffer.
  80516. * \param size The size of the records to be read.
  80517. * \param nmemb The number of records to be read.
  80518. * \param handle The handle to the data source.
  80519. * \retval size_t
  80520. * The number of records read.
  80521. */
  80522. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  80523. /** Signature for the write callback.
  80524. * The signature and semantics match POSIX fwrite() implementations
  80525. * and can generally be used interchangeably.
  80526. *
  80527. * \param ptr The address of the write buffer.
  80528. * \param size The size of the records to be written.
  80529. * \param nmemb The number of records to be written.
  80530. * \param handle The handle to the data source.
  80531. * \retval size_t
  80532. * The number of records written.
  80533. */
  80534. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  80535. /** Signature for the seek callback.
  80536. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  80537. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  80538. * and 32-bits wide.
  80539. *
  80540. * \param handle The handle to the data source.
  80541. * \param offset The new position, relative to \a whence
  80542. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  80543. * \retval int
  80544. * \c 0 on success, \c -1 on error.
  80545. */
  80546. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  80547. /** Signature for the tell callback.
  80548. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  80549. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  80550. * and 32-bits wide.
  80551. *
  80552. * \param handle The handle to the data source.
  80553. * \retval FLAC__int64
  80554. * The current position on success, \c -1 on error.
  80555. */
  80556. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  80557. /** Signature for the EOF callback.
  80558. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  80559. * on many systems, feof() is a macro, so in this case a wrapper function
  80560. * must be provided instead.
  80561. *
  80562. * \param handle The handle to the data source.
  80563. * \retval int
  80564. * \c 0 if not at end of file, nonzero if at end of file.
  80565. */
  80566. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  80567. /** Signature for the close callback.
  80568. * The signature and semantics match POSIX fclose() implementations
  80569. * and can generally be used interchangeably.
  80570. *
  80571. * \param handle The handle to the data source.
  80572. * \retval int
  80573. * \c 0 on success, \c EOF on error.
  80574. */
  80575. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  80576. /** A structure for holding a set of callbacks.
  80577. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  80578. * describe which of the callbacks are required. The ones that are not
  80579. * required may be set to NULL.
  80580. *
  80581. * If the seek requirement for an interface is optional, you can signify that
  80582. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  80583. */
  80584. typedef struct {
  80585. FLAC__IOCallback_Read read;
  80586. FLAC__IOCallback_Write write;
  80587. FLAC__IOCallback_Seek seek;
  80588. FLAC__IOCallback_Tell tell;
  80589. FLAC__IOCallback_Eof eof;
  80590. FLAC__IOCallback_Close close;
  80591. } FLAC__IOCallbacks;
  80592. /* \} */
  80593. #ifdef __cplusplus
  80594. }
  80595. #endif
  80596. #endif
  80597. /********* End of inlined file: callback.h *********/
  80598. /********* Start of inlined file: format.h *********/
  80599. #ifndef FLAC__FORMAT_H
  80600. #define FLAC__FORMAT_H
  80601. #ifdef __cplusplus
  80602. extern "C" {
  80603. #endif
  80604. /** \file include/FLAC/format.h
  80605. *
  80606. * \brief
  80607. * This module contains structure definitions for the representation
  80608. * of FLAC format components in memory. These are the basic
  80609. * structures used by the rest of the interfaces.
  80610. *
  80611. * See the detailed documentation in the
  80612. * \link flac_format format \endlink module.
  80613. */
  80614. /** \defgroup flac_format FLAC/format.h: format components
  80615. * \ingroup flac
  80616. *
  80617. * \brief
  80618. * This module contains structure definitions for the representation
  80619. * of FLAC format components in memory. These are the basic
  80620. * structures used by the rest of the interfaces.
  80621. *
  80622. * First, you should be familiar with the
  80623. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  80624. * follow directly from the specification. As a user of libFLAC, the
  80625. * interesting parts really are the structures that describe the frame
  80626. * header and metadata blocks.
  80627. *
  80628. * The format structures here are very primitive, designed to store
  80629. * information in an efficient way. Reading information from the
  80630. * structures is easy but creating or modifying them directly is
  80631. * more complex. For the most part, as a user of a library, editing
  80632. * is not necessary; however, for metadata blocks it is, so there are
  80633. * convenience functions provided in the \link flac_metadata metadata
  80634. * module \endlink to simplify the manipulation of metadata blocks.
  80635. *
  80636. * \note
  80637. * It's not the best convention, but symbols ending in _LEN are in bits
  80638. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  80639. * global variables because they are usually used when declaring byte
  80640. * arrays and some compilers require compile-time knowledge of array
  80641. * sizes when declared on the stack.
  80642. *
  80643. * \{
  80644. */
  80645. /*
  80646. Most of the values described in this file are defined by the FLAC
  80647. format specification. There is nothing to tune here.
  80648. */
  80649. /** The largest legal metadata type code. */
  80650. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  80651. /** The minimum block size, in samples, permitted by the format. */
  80652. #define FLAC__MIN_BLOCK_SIZE (16u)
  80653. /** The maximum block size, in samples, permitted by the format. */
  80654. #define FLAC__MAX_BLOCK_SIZE (65535u)
  80655. /** The maximum block size, in samples, permitted by the FLAC subset for
  80656. * sample rates up to 48kHz. */
  80657. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  80658. /** The maximum number of channels permitted by the format. */
  80659. #define FLAC__MAX_CHANNELS (8u)
  80660. /** The minimum sample resolution permitted by the format. */
  80661. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  80662. /** The maximum sample resolution permitted by the format. */
  80663. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  80664. /** The maximum sample resolution permitted by libFLAC.
  80665. *
  80666. * \warning
  80667. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  80668. * the reference encoder/decoder is currently limited to 24 bits because
  80669. * of prevalent 32-bit math, so make sure and use this value when
  80670. * appropriate.
  80671. */
  80672. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  80673. /** The maximum sample rate permitted by the format. The value is
  80674. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  80675. * as to why.
  80676. */
  80677. #define FLAC__MAX_SAMPLE_RATE (655350u)
  80678. /** The maximum LPC order permitted by the format. */
  80679. #define FLAC__MAX_LPC_ORDER (32u)
  80680. /** The maximum LPC order permitted by the FLAC subset for sample rates
  80681. * up to 48kHz. */
  80682. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  80683. /** The minimum quantized linear predictor coefficient precision
  80684. * permitted by the format.
  80685. */
  80686. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  80687. /** The maximum quantized linear predictor coefficient precision
  80688. * permitted by the format.
  80689. */
  80690. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  80691. /** The maximum order of the fixed predictors permitted by the format. */
  80692. #define FLAC__MAX_FIXED_ORDER (4u)
  80693. /** The maximum Rice partition order permitted by the format. */
  80694. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  80695. /** The maximum Rice partition order permitted by the FLAC Subset. */
  80696. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  80697. /** The version string of the release, stamped onto the libraries and binaries.
  80698. *
  80699. * \note
  80700. * This does not correspond to the shared library version number, which
  80701. * is used to determine binary compatibility.
  80702. */
  80703. extern FLAC_API const char *FLAC__VERSION_STRING;
  80704. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  80705. * This is a NUL-terminated ASCII string; when inserted into the
  80706. * VORBIS_COMMENT the trailing null is stripped.
  80707. */
  80708. extern FLAC_API const char *FLAC__VENDOR_STRING;
  80709. /** The byte string representation of the beginning of a FLAC stream. */
  80710. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  80711. /** The 32-bit integer big-endian representation of the beginning of
  80712. * a FLAC stream.
  80713. */
  80714. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  80715. /** The length of the FLAC signature in bits. */
  80716. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  80717. /** The length of the FLAC signature in bytes. */
  80718. #define FLAC__STREAM_SYNC_LENGTH (4u)
  80719. /*****************************************************************************
  80720. *
  80721. * Subframe structures
  80722. *
  80723. *****************************************************************************/
  80724. /*****************************************************************************/
  80725. /** An enumeration of the available entropy coding methods. */
  80726. typedef enum {
  80727. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  80728. /**< Residual is coded by partitioning into contexts, each with it's own
  80729. * 4-bit Rice parameter. */
  80730. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  80731. /**< Residual is coded by partitioning into contexts, each with it's own
  80732. * 5-bit Rice parameter. */
  80733. } FLAC__EntropyCodingMethodType;
  80734. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  80735. *
  80736. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  80737. * give the string equivalent. The contents should not be modified.
  80738. */
  80739. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  80740. /** Contents of a Rice partitioned residual
  80741. */
  80742. typedef struct {
  80743. unsigned *parameters;
  80744. /**< The Rice parameters for each context. */
  80745. unsigned *raw_bits;
  80746. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  80747. * partitions and zero for unescaped partitions.
  80748. */
  80749. unsigned capacity_by_order;
  80750. /**< The capacity of the \a parameters and \a raw_bits arrays
  80751. * specified as an order, i.e. the number of array elements
  80752. * allocated is 2 ^ \a capacity_by_order.
  80753. */
  80754. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  80755. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  80756. */
  80757. typedef struct {
  80758. unsigned order;
  80759. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  80760. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  80761. /**< The context's Rice parameters and/or raw bits. */
  80762. } FLAC__EntropyCodingMethod_PartitionedRice;
  80763. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  80764. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  80765. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  80766. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  80767. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  80768. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  80769. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  80770. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  80771. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  80772. */
  80773. typedef struct {
  80774. FLAC__EntropyCodingMethodType type;
  80775. union {
  80776. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  80777. } data;
  80778. } FLAC__EntropyCodingMethod;
  80779. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  80780. /*****************************************************************************/
  80781. /** An enumeration of the available subframe types. */
  80782. typedef enum {
  80783. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  80784. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  80785. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  80786. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  80787. } FLAC__SubframeType;
  80788. /** Maps a FLAC__SubframeType to a C string.
  80789. *
  80790. * Using a FLAC__SubframeType as the index to this array will
  80791. * give the string equivalent. The contents should not be modified.
  80792. */
  80793. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  80794. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  80795. */
  80796. typedef struct {
  80797. FLAC__int32 value; /**< The constant signal value. */
  80798. } FLAC__Subframe_Constant;
  80799. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  80800. */
  80801. typedef struct {
  80802. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  80803. } FLAC__Subframe_Verbatim;
  80804. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  80805. */
  80806. typedef struct {
  80807. FLAC__EntropyCodingMethod entropy_coding_method;
  80808. /**< The residual coding method. */
  80809. unsigned order;
  80810. /**< The polynomial order. */
  80811. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  80812. /**< Warmup samples to prime the predictor, length == order. */
  80813. const FLAC__int32 *residual;
  80814. /**< The residual signal, length == (blocksize minus order) samples. */
  80815. } FLAC__Subframe_Fixed;
  80816. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  80817. */
  80818. typedef struct {
  80819. FLAC__EntropyCodingMethod entropy_coding_method;
  80820. /**< The residual coding method. */
  80821. unsigned order;
  80822. /**< The FIR order. */
  80823. unsigned qlp_coeff_precision;
  80824. /**< Quantized FIR filter coefficient precision in bits. */
  80825. int quantization_level;
  80826. /**< The qlp coeff shift needed. */
  80827. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  80828. /**< FIR filter coefficients. */
  80829. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  80830. /**< Warmup samples to prime the predictor, length == order. */
  80831. const FLAC__int32 *residual;
  80832. /**< The residual signal, length == (blocksize minus order) samples. */
  80833. } FLAC__Subframe_LPC;
  80834. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  80835. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  80836. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  80837. */
  80838. typedef struct {
  80839. FLAC__SubframeType type;
  80840. union {
  80841. FLAC__Subframe_Constant constant;
  80842. FLAC__Subframe_Fixed fixed;
  80843. FLAC__Subframe_LPC lpc;
  80844. FLAC__Subframe_Verbatim verbatim;
  80845. } data;
  80846. unsigned wasted_bits;
  80847. } FLAC__Subframe;
  80848. /** == 1 (bit)
  80849. *
  80850. * This used to be a zero-padding bit (hence the name
  80851. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  80852. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  80853. * to mean something else.
  80854. */
  80855. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  80856. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  80857. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  80858. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  80859. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  80860. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  80861. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  80862. /*****************************************************************************/
  80863. /*****************************************************************************
  80864. *
  80865. * Frame structures
  80866. *
  80867. *****************************************************************************/
  80868. /** An enumeration of the available channel assignments. */
  80869. typedef enum {
  80870. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  80871. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  80872. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  80873. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  80874. } FLAC__ChannelAssignment;
  80875. /** Maps a FLAC__ChannelAssignment to a C string.
  80876. *
  80877. * Using a FLAC__ChannelAssignment as the index to this array will
  80878. * give the string equivalent. The contents should not be modified.
  80879. */
  80880. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  80881. /** An enumeration of the possible frame numbering methods. */
  80882. typedef enum {
  80883. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  80884. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  80885. } FLAC__FrameNumberType;
  80886. /** Maps a FLAC__FrameNumberType to a C string.
  80887. *
  80888. * Using a FLAC__FrameNumberType as the index to this array will
  80889. * give the string equivalent. The contents should not be modified.
  80890. */
  80891. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  80892. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  80893. */
  80894. typedef struct {
  80895. unsigned blocksize;
  80896. /**< The number of samples per subframe. */
  80897. unsigned sample_rate;
  80898. /**< The sample rate in Hz. */
  80899. unsigned channels;
  80900. /**< The number of channels (== number of subframes). */
  80901. FLAC__ChannelAssignment channel_assignment;
  80902. /**< The channel assignment for the frame. */
  80903. unsigned bits_per_sample;
  80904. /**< The sample resolution. */
  80905. FLAC__FrameNumberType number_type;
  80906. /**< The numbering scheme used for the frame. As a convenience, the
  80907. * decoder will always convert a frame number to a sample number because
  80908. * the rules are complex. */
  80909. union {
  80910. FLAC__uint32 frame_number;
  80911. FLAC__uint64 sample_number;
  80912. } number;
  80913. /**< The frame number or sample number of first sample in frame;
  80914. * use the \a number_type value to determine which to use. */
  80915. FLAC__uint8 crc;
  80916. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  80917. * of the raw frame header bytes, meaning everything before the CRC byte
  80918. * including the sync code.
  80919. */
  80920. } FLAC__FrameHeader;
  80921. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  80922. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  80923. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  80924. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  80925. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  80926. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  80927. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  80928. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  80929. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  80930. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  80931. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  80932. */
  80933. typedef struct {
  80934. FLAC__uint16 crc;
  80935. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  80936. * 0) of the bytes before the crc, back to and including the frame header
  80937. * sync code.
  80938. */
  80939. } FLAC__FrameFooter;
  80940. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  80941. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  80942. */
  80943. typedef struct {
  80944. FLAC__FrameHeader header;
  80945. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  80946. FLAC__FrameFooter footer;
  80947. } FLAC__Frame;
  80948. /*****************************************************************************/
  80949. /*****************************************************************************
  80950. *
  80951. * Meta-data structures
  80952. *
  80953. *****************************************************************************/
  80954. /** An enumeration of the available metadata block types. */
  80955. typedef enum {
  80956. FLAC__METADATA_TYPE_STREAMINFO = 0,
  80957. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  80958. FLAC__METADATA_TYPE_PADDING = 1,
  80959. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  80960. FLAC__METADATA_TYPE_APPLICATION = 2,
  80961. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  80962. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  80963. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  80964. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  80965. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  80966. FLAC__METADATA_TYPE_CUESHEET = 5,
  80967. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  80968. FLAC__METADATA_TYPE_PICTURE = 6,
  80969. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  80970. FLAC__METADATA_TYPE_UNDEFINED = 7
  80971. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  80972. } FLAC__MetadataType;
  80973. /** Maps a FLAC__MetadataType to a C string.
  80974. *
  80975. * Using a FLAC__MetadataType as the index to this array will
  80976. * give the string equivalent. The contents should not be modified.
  80977. */
  80978. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  80979. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  80980. */
  80981. typedef struct {
  80982. unsigned min_blocksize, max_blocksize;
  80983. unsigned min_framesize, max_framesize;
  80984. unsigned sample_rate;
  80985. unsigned channels;
  80986. unsigned bits_per_sample;
  80987. FLAC__uint64 total_samples;
  80988. FLAC__byte md5sum[16];
  80989. } FLAC__StreamMetadata_StreamInfo;
  80990. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  80991. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  80992. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  80993. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  80994. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  80995. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  80996. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  80997. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  80998. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  80999. /** The total stream length of the STREAMINFO block in bytes. */
  81000. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  81001. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  81002. */
  81003. typedef struct {
  81004. int dummy;
  81005. /**< Conceptually this is an empty struct since we don't store the
  81006. * padding bytes. Empty structs are not allowed by some C compilers,
  81007. * hence the dummy.
  81008. */
  81009. } FLAC__StreamMetadata_Padding;
  81010. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  81011. */
  81012. typedef struct {
  81013. FLAC__byte id[4];
  81014. FLAC__byte *data;
  81015. } FLAC__StreamMetadata_Application;
  81016. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  81017. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  81018. */
  81019. typedef struct {
  81020. FLAC__uint64 sample_number;
  81021. /**< The sample number of the target frame. */
  81022. FLAC__uint64 stream_offset;
  81023. /**< The offset, in bytes, of the target frame with respect to
  81024. * beginning of the first frame. */
  81025. unsigned frame_samples;
  81026. /**< The number of samples in the target frame. */
  81027. } FLAC__StreamMetadata_SeekPoint;
  81028. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  81029. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  81030. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  81031. /** The total stream length of a seek point in bytes. */
  81032. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  81033. /** The value used in the \a sample_number field of
  81034. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  81035. * point (== 0xffffffffffffffff).
  81036. */
  81037. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  81038. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  81039. *
  81040. * \note From the format specification:
  81041. * - The seek points must be sorted by ascending sample number.
  81042. * - Each seek point's sample number must be the first sample of the
  81043. * target frame.
  81044. * - Each seek point's sample number must be unique within the table.
  81045. * - Existence of a SEEKTABLE block implies a correct setting of
  81046. * total_samples in the stream_info block.
  81047. * - Behavior is undefined when more than one SEEKTABLE block is
  81048. * present in a stream.
  81049. */
  81050. typedef struct {
  81051. unsigned num_points;
  81052. FLAC__StreamMetadata_SeekPoint *points;
  81053. } FLAC__StreamMetadata_SeekTable;
  81054. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  81055. *
  81056. * For convenience, the APIs maintain a trailing NUL character at the end of
  81057. * \a entry which is not counted toward \a length, i.e.
  81058. * \code strlen(entry) == length \endcode
  81059. */
  81060. typedef struct {
  81061. FLAC__uint32 length;
  81062. FLAC__byte *entry;
  81063. } FLAC__StreamMetadata_VorbisComment_Entry;
  81064. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  81065. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  81066. */
  81067. typedef struct {
  81068. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  81069. FLAC__uint32 num_comments;
  81070. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  81071. } FLAC__StreamMetadata_VorbisComment;
  81072. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  81073. /** FLAC CUESHEET track index structure. (See the
  81074. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  81075. * the full description of each field.)
  81076. */
  81077. typedef struct {
  81078. FLAC__uint64 offset;
  81079. /**< Offset in samples, relative to the track offset, of the index
  81080. * point.
  81081. */
  81082. FLAC__byte number;
  81083. /**< The index point number. */
  81084. } FLAC__StreamMetadata_CueSheet_Index;
  81085. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  81086. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  81087. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  81088. /** FLAC CUESHEET track structure. (See the
  81089. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  81090. * the full description of each field.)
  81091. */
  81092. typedef struct {
  81093. FLAC__uint64 offset;
  81094. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  81095. FLAC__byte number;
  81096. /**< The track number. */
  81097. char isrc[13];
  81098. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  81099. unsigned type:1;
  81100. /**< The track type: 0 for audio, 1 for non-audio. */
  81101. unsigned pre_emphasis:1;
  81102. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  81103. FLAC__byte num_indices;
  81104. /**< The number of track index points. */
  81105. FLAC__StreamMetadata_CueSheet_Index *indices;
  81106. /**< NULL if num_indices == 0, else pointer to array of index points. */
  81107. } FLAC__StreamMetadata_CueSheet_Track;
  81108. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  81109. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  81110. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  81111. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  81112. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  81113. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  81114. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  81115. /** FLAC CUESHEET structure. (See the
  81116. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  81117. * for the full description of each field.)
  81118. */
  81119. typedef struct {
  81120. char media_catalog_number[129];
  81121. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  81122. * general, the media catalog number may be 0 to 128 bytes long; any
  81123. * unused characters should be right-padded with NUL characters.
  81124. */
  81125. FLAC__uint64 lead_in;
  81126. /**< The number of lead-in samples. */
  81127. FLAC__bool is_cd;
  81128. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  81129. unsigned num_tracks;
  81130. /**< The number of tracks. */
  81131. FLAC__StreamMetadata_CueSheet_Track *tracks;
  81132. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  81133. } FLAC__StreamMetadata_CueSheet;
  81134. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  81135. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  81136. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  81137. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  81138. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  81139. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  81140. typedef enum {
  81141. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  81142. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  81143. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  81144. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  81145. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  81146. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  81147. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  81148. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  81149. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  81150. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  81151. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  81152. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  81153. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  81154. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  81155. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  81156. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  81157. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  81158. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  81159. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  81160. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  81161. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  81162. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  81163. } FLAC__StreamMetadata_Picture_Type;
  81164. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  81165. *
  81166. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  81167. * will give the string equivalent. The contents should not be
  81168. * modified.
  81169. */
  81170. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  81171. /** FLAC PICTURE structure. (See the
  81172. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  81173. * for the full description of each field.)
  81174. */
  81175. typedef struct {
  81176. FLAC__StreamMetadata_Picture_Type type;
  81177. /**< The kind of picture stored. */
  81178. char *mime_type;
  81179. /**< Picture data's MIME type, in ASCII printable characters
  81180. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  81181. * use picture data of MIME type \c image/jpeg or \c image/png. A
  81182. * MIME type of '-->' is also allowed, in which case the picture
  81183. * data should be a complete URL. In file storage, the MIME type is
  81184. * stored as a 32-bit length followed by the ASCII string with no NUL
  81185. * terminator, but is converted to a plain C string in this structure
  81186. * for convenience.
  81187. */
  81188. FLAC__byte *description;
  81189. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  81190. * the description is stored as a 32-bit length followed by the UTF-8
  81191. * string with no NUL terminator, but is converted to a plain C string
  81192. * in this structure for convenience.
  81193. */
  81194. FLAC__uint32 width;
  81195. /**< Picture's width in pixels. */
  81196. FLAC__uint32 height;
  81197. /**< Picture's height in pixels. */
  81198. FLAC__uint32 depth;
  81199. /**< Picture's color depth in bits-per-pixel. */
  81200. FLAC__uint32 colors;
  81201. /**< For indexed palettes (like GIF), picture's number of colors (the
  81202. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  81203. */
  81204. FLAC__uint32 data_length;
  81205. /**< Length of binary picture data in bytes. */
  81206. FLAC__byte *data;
  81207. /**< Binary picture data. */
  81208. } FLAC__StreamMetadata_Picture;
  81209. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  81210. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  81211. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  81212. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  81213. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  81214. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  81215. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  81216. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  81217. /** Structure that is used when a metadata block of unknown type is loaded.
  81218. * The contents are opaque. The structure is used only internally to
  81219. * correctly handle unknown metadata.
  81220. */
  81221. typedef struct {
  81222. FLAC__byte *data;
  81223. } FLAC__StreamMetadata_Unknown;
  81224. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  81225. */
  81226. typedef struct {
  81227. FLAC__MetadataType type;
  81228. /**< The type of the metadata block; used determine which member of the
  81229. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  81230. * then \a data.unknown must be used. */
  81231. FLAC__bool is_last;
  81232. /**< \c true if this metadata block is the last, else \a false */
  81233. unsigned length;
  81234. /**< Length, in bytes, of the block data as it appears in the stream. */
  81235. union {
  81236. FLAC__StreamMetadata_StreamInfo stream_info;
  81237. FLAC__StreamMetadata_Padding padding;
  81238. FLAC__StreamMetadata_Application application;
  81239. FLAC__StreamMetadata_SeekTable seek_table;
  81240. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  81241. FLAC__StreamMetadata_CueSheet cue_sheet;
  81242. FLAC__StreamMetadata_Picture picture;
  81243. FLAC__StreamMetadata_Unknown unknown;
  81244. } data;
  81245. /**< Polymorphic block data; use the \a type value to determine which
  81246. * to use. */
  81247. } FLAC__StreamMetadata;
  81248. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  81249. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  81250. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  81251. /** The total stream length of a metadata block header in bytes. */
  81252. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  81253. /*****************************************************************************/
  81254. /*****************************************************************************
  81255. *
  81256. * Utility functions
  81257. *
  81258. *****************************************************************************/
  81259. /** Tests that a sample rate is valid for FLAC.
  81260. *
  81261. * \param sample_rate The sample rate to test for compliance.
  81262. * \retval FLAC__bool
  81263. * \c true if the given sample rate conforms to the specification, else
  81264. * \c false.
  81265. */
  81266. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  81267. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  81268. * for valid sample rates are slightly more complex since the rate has to
  81269. * be expressible completely in the frame header.
  81270. *
  81271. * \param sample_rate The sample rate to test for compliance.
  81272. * \retval FLAC__bool
  81273. * \c true if the given sample rate conforms to the specification for the
  81274. * subset, else \c false.
  81275. */
  81276. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  81277. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  81278. * comment specification.
  81279. *
  81280. * Vorbis comment names must be composed only of characters from
  81281. * [0x20-0x3C,0x3E-0x7D].
  81282. *
  81283. * \param name A NUL-terminated string to be checked.
  81284. * \assert
  81285. * \code name != NULL \endcode
  81286. * \retval FLAC__bool
  81287. * \c false if entry name is illegal, else \c true.
  81288. */
  81289. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  81290. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  81291. * comment specification.
  81292. *
  81293. * Vorbis comment values must be valid UTF-8 sequences.
  81294. *
  81295. * \param value A string to be checked.
  81296. * \param length A the length of \a value in bytes. May be
  81297. * \c (unsigned)(-1) to indicate that \a value is a plain
  81298. * UTF-8 NUL-terminated string.
  81299. * \assert
  81300. * \code value != NULL \endcode
  81301. * \retval FLAC__bool
  81302. * \c false if entry name is illegal, else \c true.
  81303. */
  81304. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  81305. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  81306. * comment specification.
  81307. *
  81308. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  81309. * 'value' must be legal according to
  81310. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  81311. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  81312. *
  81313. * \param entry An entry to be checked.
  81314. * \param length The length of \a entry in bytes.
  81315. * \assert
  81316. * \code value != NULL \endcode
  81317. * \retval FLAC__bool
  81318. * \c false if entry name is illegal, else \c true.
  81319. */
  81320. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  81321. /** Check a seek table to see if it conforms to the FLAC specification.
  81322. * See the format specification for limits on the contents of the
  81323. * seek table.
  81324. *
  81325. * \param seek_table A pointer to a seek table to be checked.
  81326. * \assert
  81327. * \code seek_table != NULL \endcode
  81328. * \retval FLAC__bool
  81329. * \c false if seek table is illegal, else \c true.
  81330. */
  81331. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  81332. /** Sort a seek table's seek points according to the format specification.
  81333. * This includes a "unique-ification" step to remove duplicates, i.e.
  81334. * seek points with identical \a sample_number values. Duplicate seek
  81335. * points are converted into placeholder points and sorted to the end of
  81336. * the table.
  81337. *
  81338. * \param seek_table A pointer to a seek table to be sorted.
  81339. * \assert
  81340. * \code seek_table != NULL \endcode
  81341. * \retval unsigned
  81342. * The number of duplicate seek points converted into placeholders.
  81343. */
  81344. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  81345. /** Check a cue sheet to see if it conforms to the FLAC specification.
  81346. * See the format specification for limits on the contents of the
  81347. * cue sheet.
  81348. *
  81349. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  81350. * \param check_cd_da_subset If \c true, check CUESHEET against more
  81351. * stringent requirements for a CD-DA (audio) disc.
  81352. * \param violation Address of a pointer to a string. If there is a
  81353. * violation, a pointer to a string explanation of the
  81354. * violation will be returned here. \a violation may be
  81355. * \c NULL if you don't need the returned string. Do not
  81356. * free the returned string; it will always point to static
  81357. * data.
  81358. * \assert
  81359. * \code cue_sheet != NULL \endcode
  81360. * \retval FLAC__bool
  81361. * \c false if cue sheet is illegal, else \c true.
  81362. */
  81363. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  81364. /** Check picture data to see if it conforms to the FLAC specification.
  81365. * See the format specification for limits on the contents of the
  81366. * PICTURE block.
  81367. *
  81368. * \param picture A pointer to existing picture data to be checked.
  81369. * \param violation Address of a pointer to a string. If there is a
  81370. * violation, a pointer to a string explanation of the
  81371. * violation will be returned here. \a violation may be
  81372. * \c NULL if you don't need the returned string. Do not
  81373. * free the returned string; it will always point to static
  81374. * data.
  81375. * \assert
  81376. * \code picture != NULL \endcode
  81377. * \retval FLAC__bool
  81378. * \c false if picture data is illegal, else \c true.
  81379. */
  81380. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  81381. /* \} */
  81382. #ifdef __cplusplus
  81383. }
  81384. #endif
  81385. #endif
  81386. /********* End of inlined file: format.h *********/
  81387. /********* Start of inlined file: metadata.h *********/
  81388. #ifndef FLAC__METADATA_H
  81389. #define FLAC__METADATA_H
  81390. #include <sys/types.h> /* for off_t */
  81391. /* --------------------------------------------------------------------
  81392. (For an example of how all these routines are used, see the source
  81393. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  81394. metaflac in src/metaflac/)
  81395. ------------------------------------------------------------------*/
  81396. /** \file include/FLAC/metadata.h
  81397. *
  81398. * \brief
  81399. * This module provides functions for creating and manipulating FLAC
  81400. * metadata blocks in memory, and three progressively more powerful
  81401. * interfaces for traversing and editing metadata in FLAC files.
  81402. *
  81403. * See the detailed documentation for each interface in the
  81404. * \link flac_metadata metadata \endlink module.
  81405. */
  81406. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  81407. * \ingroup flac
  81408. *
  81409. * \brief
  81410. * This module provides functions for creating and manipulating FLAC
  81411. * metadata blocks in memory, and three progressively more powerful
  81412. * interfaces for traversing and editing metadata in native FLAC files.
  81413. * Note that currently only the Chain interface (level 2) supports Ogg
  81414. * FLAC files, and it is read-only i.e. no writing back changed
  81415. * metadata to file.
  81416. *
  81417. * There are three metadata interfaces of increasing complexity:
  81418. *
  81419. * Level 0:
  81420. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  81421. * PICTURE blocks.
  81422. *
  81423. * Level 1:
  81424. * Read-write access to all metadata blocks. This level is write-
  81425. * efficient in most cases (more on this below), and uses less memory
  81426. * than level 2.
  81427. *
  81428. * Level 2:
  81429. * Read-write access to all metadata blocks. This level is write-
  81430. * efficient in all cases, but uses more memory since all metadata for
  81431. * the whole file is read into memory and manipulated before writing
  81432. * out again.
  81433. *
  81434. * What do we mean by efficient? Since FLAC metadata appears at the
  81435. * beginning of the file, when writing metadata back to a FLAC file
  81436. * it is possible to grow or shrink the metadata such that the entire
  81437. * file must be rewritten. However, if the size remains the same during
  81438. * changes or PADDING blocks are utilized, only the metadata needs to be
  81439. * overwritten, which is much faster.
  81440. *
  81441. * Efficient means the whole file is rewritten at most one time, and only
  81442. * when necessary. Level 1 is not efficient only in the case that you
  81443. * cause more than one metadata block to grow or shrink beyond what can
  81444. * be accomodated by padding. In this case you should probably use level
  81445. * 2, which allows you to edit all the metadata for a file in memory and
  81446. * write it out all at once.
  81447. *
  81448. * All levels know how to skip over and not disturb an ID3v2 tag at the
  81449. * front of the file.
  81450. *
  81451. * All levels access files via their filenames. In addition, level 2
  81452. * has additional alternative read and write functions that take an I/O
  81453. * handle and callbacks, for situations where access by filename is not
  81454. * possible.
  81455. *
  81456. * In addition to the three interfaces, this module defines functions for
  81457. * creating and manipulating various metadata objects in memory. As we see
  81458. * from the Format module, FLAC metadata blocks in memory are very primitive
  81459. * structures for storing information in an efficient way. Reading
  81460. * information from the structures is easy but creating or modifying them
  81461. * directly is more complex. The metadata object routines here facilitate
  81462. * this by taking care of the consistency and memory management drudgery.
  81463. *
  81464. * Unless you will be using the level 1 or 2 interfaces to modify existing
  81465. * metadata however, you will not probably not need these.
  81466. *
  81467. * From a dependency standpoint, none of the encoders or decoders require
  81468. * the metadata module. This is so that embedded users can strip out the
  81469. * metadata module from libFLAC to reduce the size and complexity.
  81470. */
  81471. #ifdef __cplusplus
  81472. extern "C" {
  81473. #endif
  81474. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  81475. * \ingroup flac_metadata
  81476. *
  81477. * \brief
  81478. * The level 0 interface consists of individual routines to read the
  81479. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  81480. * only a filename.
  81481. *
  81482. * They try to skip any ID3v2 tag at the head of the file.
  81483. *
  81484. * \{
  81485. */
  81486. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  81487. * will try to skip any ID3v2 tag at the head of the file.
  81488. *
  81489. * \param filename The path to the FLAC file to read.
  81490. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  81491. * FLAC__StreamMetadata is a simple structure with no
  81492. * memory allocation involved, you pass the address of
  81493. * an existing structure. It need not be initialized.
  81494. * \assert
  81495. * \code filename != NULL \endcode
  81496. * \code streaminfo != NULL \endcode
  81497. * \retval FLAC__bool
  81498. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  81499. * \c false if there was a memory allocation error, a file decoder error,
  81500. * or the file contained no STREAMINFO block. (A memory allocation error
  81501. * is possible because this function must set up a file decoder.)
  81502. */
  81503. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  81504. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  81505. * function will try to skip any ID3v2 tag at the head of the file.
  81506. *
  81507. * \param filename The path to the FLAC file to read.
  81508. * \param tags The address where the returned pointer will be
  81509. * stored. The \a tags object must be deleted by
  81510. * the caller using FLAC__metadata_object_delete().
  81511. * \assert
  81512. * \code filename != NULL \endcode
  81513. * \code tags != NULL \endcode
  81514. * \retval FLAC__bool
  81515. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  81516. * and \a *tags will be set to the address of the metadata structure.
  81517. * Returns \c false if there was a memory allocation error, a file
  81518. * decoder error, or the file contained no VORBIS_COMMENT block, and
  81519. * \a *tags will be set to \c NULL.
  81520. */
  81521. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  81522. /** Read the CUESHEET metadata block of the given FLAC file. This
  81523. * function will try to skip any ID3v2 tag at the head of the file.
  81524. *
  81525. * \param filename The path to the FLAC file to read.
  81526. * \param cuesheet The address where the returned pointer will be
  81527. * stored. The \a cuesheet object must be deleted by
  81528. * the caller using FLAC__metadata_object_delete().
  81529. * \assert
  81530. * \code filename != NULL \endcode
  81531. * \code cuesheet != NULL \endcode
  81532. * \retval FLAC__bool
  81533. * \c true if a valid CUESHEET block was read from \a filename,
  81534. * and \a *cuesheet will be set to the address of the metadata
  81535. * structure. Returns \c false if there was a memory allocation
  81536. * error, a file decoder error, or the file contained no CUESHEET
  81537. * block, and \a *cuesheet will be set to \c NULL.
  81538. */
  81539. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  81540. /** Read a PICTURE metadata block of the given FLAC file. This
  81541. * function will try to skip any ID3v2 tag at the head of the file.
  81542. * Since there can be more than one PICTURE block in a file, this
  81543. * function takes a number of parameters that act as constraints to
  81544. * the search. The PICTURE block with the largest area matching all
  81545. * the constraints will be returned, or \a *picture will be set to
  81546. * \c NULL if there was no such block.
  81547. *
  81548. * \param filename The path to the FLAC file to read.
  81549. * \param picture The address where the returned pointer will be
  81550. * stored. The \a picture object must be deleted by
  81551. * the caller using FLAC__metadata_object_delete().
  81552. * \param type The desired picture type. Use \c -1 to mean
  81553. * "any type".
  81554. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  81555. * string will be matched exactly. Use \c NULL to
  81556. * mean "any MIME type".
  81557. * \param description The desired description. The string will be
  81558. * matched exactly. Use \c NULL to mean "any
  81559. * description".
  81560. * \param max_width The maximum width in pixels desired. Use
  81561. * \c (unsigned)(-1) to mean "any width".
  81562. * \param max_height The maximum height in pixels desired. Use
  81563. * \c (unsigned)(-1) to mean "any height".
  81564. * \param max_depth The maximum color depth in bits-per-pixel desired.
  81565. * Use \c (unsigned)(-1) to mean "any depth".
  81566. * \param max_colors The maximum number of colors desired. Use
  81567. * \c (unsigned)(-1) to mean "any number of colors".
  81568. * \assert
  81569. * \code filename != NULL \endcode
  81570. * \code picture != NULL \endcode
  81571. * \retval FLAC__bool
  81572. * \c true if a valid PICTURE block was read from \a filename,
  81573. * and \a *picture will be set to the address of the metadata
  81574. * structure. Returns \c false if there was a memory allocation
  81575. * error, a file decoder error, or the file contained no PICTURE
  81576. * block, and \a *picture will be set to \c NULL.
  81577. */
  81578. FLAC_API FLAC__bool FLAC__metadata_get_picture(const char *filename, FLAC__StreamMetadata **picture, FLAC__StreamMetadata_Picture_Type type, const char *mime_type, const FLAC__byte *description, unsigned max_width, unsigned max_height, unsigned max_depth, unsigned max_colors);
  81579. /* \} */
  81580. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  81581. * \ingroup flac_metadata
  81582. *
  81583. * \brief
  81584. * The level 1 interface provides read-write access to FLAC file metadata and
  81585. * operates directly on the FLAC file.
  81586. *
  81587. * The general usage of this interface is:
  81588. *
  81589. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  81590. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  81591. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  81592. * see if the file is writable, or only read access is allowed.
  81593. * - Use FLAC__metadata_simple_iterator_next() and
  81594. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  81595. * This is does not read the actual blocks themselves.
  81596. * FLAC__metadata_simple_iterator_next() is relatively fast.
  81597. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  81598. * forward from the front of the file.
  81599. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  81600. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  81601. * the current iterator position. The returned object is yours to modify
  81602. * and free.
  81603. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  81604. * back. You must have write permission to the original file. Make sure to
  81605. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  81606. * below.
  81607. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  81608. * Use the object creation functions from
  81609. * \link flac_metadata_object here \endlink to generate new objects.
  81610. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  81611. * currently referred to by the iterator, or replace it with padding.
  81612. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  81613. * finished.
  81614. *
  81615. * \note
  81616. * The FLAC file remains open the whole time between
  81617. * FLAC__metadata_simple_iterator_init() and
  81618. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  81619. * the file during this time.
  81620. *
  81621. * \note
  81622. * Do not modify the \a is_last, \a length, or \a type fields of returned
  81623. * FLAC__StreamMetadata objects. These are managed automatically.
  81624. *
  81625. * \note
  81626. * If any of the modification functions
  81627. * (FLAC__metadata_simple_iterator_set_block(),
  81628. * FLAC__metadata_simple_iterator_delete_block(),
  81629. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  81630. * you should delete the iterator as it may no longer be valid.
  81631. *
  81632. * \{
  81633. */
  81634. struct FLAC__Metadata_SimpleIterator;
  81635. /** The opaque structure definition for the level 1 iterator type.
  81636. * See the
  81637. * \link flac_metadata_level1 metadata level 1 module \endlink
  81638. * for a detailed description.
  81639. */
  81640. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  81641. /** Status type for FLAC__Metadata_SimpleIterator.
  81642. *
  81643. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  81644. */
  81645. typedef enum {
  81646. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  81647. /**< The iterator is in the normal OK state */
  81648. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  81649. /**< The data passed into a function violated the function's usage criteria */
  81650. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  81651. /**< The iterator could not open the target file */
  81652. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  81653. /**< The iterator could not find the FLAC signature at the start of the file */
  81654. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  81655. /**< The iterator tried to write to a file that was not writable */
  81656. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  81657. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  81658. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  81659. /**< The iterator encountered an error while reading the FLAC file */
  81660. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  81661. /**< The iterator encountered an error while seeking in the FLAC file */
  81662. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  81663. /**< The iterator encountered an error while writing the FLAC file */
  81664. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  81665. /**< The iterator encountered an error renaming the FLAC file */
  81666. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  81667. /**< The iterator encountered an error removing the temporary file */
  81668. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  81669. /**< Memory allocation failed */
  81670. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  81671. /**< The caller violated an assertion or an unexpected error occurred */
  81672. } FLAC__Metadata_SimpleIteratorStatus;
  81673. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  81674. *
  81675. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  81676. * will give the string equivalent. The contents should not be modified.
  81677. */
  81678. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  81679. /** Create a new iterator instance.
  81680. *
  81681. * \retval FLAC__Metadata_SimpleIterator*
  81682. * \c NULL if there was an error allocating memory, else the new instance.
  81683. */
  81684. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  81685. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  81686. *
  81687. * \param iterator A pointer to an existing iterator.
  81688. * \assert
  81689. * \code iterator != NULL \endcode
  81690. */
  81691. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  81692. /** Get the current status of the iterator. Call this after a function
  81693. * returns \c false to get the reason for the error. Also resets the status
  81694. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  81695. *
  81696. * \param iterator A pointer to an existing iterator.
  81697. * \assert
  81698. * \code iterator != NULL \endcode
  81699. * \retval FLAC__Metadata_SimpleIteratorStatus
  81700. * The current status of the iterator.
  81701. */
  81702. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  81703. /** Initialize the iterator to point to the first metadata block in the
  81704. * given FLAC file.
  81705. *
  81706. * \param iterator A pointer to an existing iterator.
  81707. * \param filename The path to the FLAC file.
  81708. * \param read_only If \c true, the FLAC file will be opened
  81709. * in read-only mode; if \c false, the FLAC
  81710. * file will be opened for edit even if no
  81711. * edits are performed.
  81712. * \param preserve_file_stats If \c true, the owner and modification
  81713. * time will be preserved even if the FLAC
  81714. * file is written to.
  81715. * \assert
  81716. * \code iterator != NULL \endcode
  81717. * \code filename != NULL \endcode
  81718. * \retval FLAC__bool
  81719. * \c false if a memory allocation error occurs, the file can't be
  81720. * opened, or another error occurs, else \c true.
  81721. */
  81722. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool read_only, FLAC__bool preserve_file_stats);
  81723. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  81724. * FLAC__metadata_simple_iterator_set_block() and
  81725. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  81726. *
  81727. * \param iterator A pointer to an existing iterator.
  81728. * \assert
  81729. * \code iterator != NULL \endcode
  81730. * \retval FLAC__bool
  81731. * See above.
  81732. */
  81733. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  81734. /** Moves the iterator forward one metadata block, returning \c false if
  81735. * already at the end.
  81736. *
  81737. * \param iterator A pointer to an existing initialized iterator.
  81738. * \assert
  81739. * \code iterator != NULL \endcode
  81740. * \a iterator has been successfully initialized with
  81741. * FLAC__metadata_simple_iterator_init()
  81742. * \retval FLAC__bool
  81743. * \c false if already at the last metadata block of the chain, else
  81744. * \c true.
  81745. */
  81746. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  81747. /** Moves the iterator backward one metadata block, returning \c false if
  81748. * already at the beginning.
  81749. *
  81750. * \param iterator A pointer to an existing initialized iterator.
  81751. * \assert
  81752. * \code iterator != NULL \endcode
  81753. * \a iterator has been successfully initialized with
  81754. * FLAC__metadata_simple_iterator_init()
  81755. * \retval FLAC__bool
  81756. * \c false if already at the first metadata block of the chain, else
  81757. * \c true.
  81758. */
  81759. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  81760. /** Returns a flag telling if the current metadata block is the last.
  81761. *
  81762. * \param iterator A pointer to an existing initialized iterator.
  81763. * \assert
  81764. * \code iterator != NULL \endcode
  81765. * \a iterator has been successfully initialized with
  81766. * FLAC__metadata_simple_iterator_init()
  81767. * \retval FLAC__bool
  81768. * \c true if the current metadata block is the last in the file,
  81769. * else \c false.
  81770. */
  81771. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  81772. /** Get the offset of the metadata block at the current position. This
  81773. * avoids reading the actual block data which can save time for large
  81774. * blocks.
  81775. *
  81776. * \param iterator A pointer to an existing initialized iterator.
  81777. * \assert
  81778. * \code iterator != NULL \endcode
  81779. * \a iterator has been successfully initialized with
  81780. * FLAC__metadata_simple_iterator_init()
  81781. * \retval off_t
  81782. * The offset of the metadata block at the current iterator position.
  81783. * This is the byte offset relative to the beginning of the file of
  81784. * the current metadata block's header.
  81785. */
  81786. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  81787. /** Get the type of the metadata block at the current position. This
  81788. * avoids reading the actual block data which can save time for large
  81789. * blocks.
  81790. *
  81791. * \param iterator A pointer to an existing initialized iterator.
  81792. * \assert
  81793. * \code iterator != NULL \endcode
  81794. * \a iterator has been successfully initialized with
  81795. * FLAC__metadata_simple_iterator_init()
  81796. * \retval FLAC__MetadataType
  81797. * The type of the metadata block at the current iterator position.
  81798. */
  81799. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  81800. /** Get the length of the metadata block at the current position. This
  81801. * avoids reading the actual block data which can save time for large
  81802. * blocks.
  81803. *
  81804. * \param iterator A pointer to an existing initialized iterator.
  81805. * \assert
  81806. * \code iterator != NULL \endcode
  81807. * \a iterator has been successfully initialized with
  81808. * FLAC__metadata_simple_iterator_init()
  81809. * \retval unsigned
  81810. * The length of the metadata block at the current iterator position.
  81811. * The is same length as that in the
  81812. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  81813. * i.e. the length of the metadata body that follows the header.
  81814. */
  81815. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  81816. /** Get the application ID of the \c APPLICATION block at the current
  81817. * position. This avoids reading the actual block data which can save
  81818. * time for large blocks.
  81819. *
  81820. * \param iterator A pointer to an existing initialized iterator.
  81821. * \param id A pointer to a buffer of at least \c 4 bytes where
  81822. * the ID will be stored.
  81823. * \assert
  81824. * \code iterator != NULL \endcode
  81825. * \code id != NULL \endcode
  81826. * \a iterator has been successfully initialized with
  81827. * FLAC__metadata_simple_iterator_init()
  81828. * \retval FLAC__bool
  81829. * \c true if the ID was successfully read, else \c false, in which
  81830. * case you should check FLAC__metadata_simple_iterator_status() to
  81831. * find out why. If the status is
  81832. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  81833. * current metadata block is not an \c APPLICATION block. Otherwise
  81834. * if the status is
  81835. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  81836. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  81837. * occurred and the iterator can no longer be used.
  81838. */
  81839. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  81840. /** Get the metadata block at the current position. You can modify the
  81841. * block but must use FLAC__metadata_simple_iterator_set_block() to
  81842. * write it back to the FLAC file.
  81843. *
  81844. * You must call FLAC__metadata_object_delete() on the returned object
  81845. * when you are finished with it.
  81846. *
  81847. * \param iterator A pointer to an existing initialized iterator.
  81848. * \assert
  81849. * \code iterator != NULL \endcode
  81850. * \a iterator has been successfully initialized with
  81851. * FLAC__metadata_simple_iterator_init()
  81852. * \retval FLAC__StreamMetadata*
  81853. * The current metadata block, or \c NULL if there was a memory
  81854. * allocation error.
  81855. */
  81856. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  81857. /** Write a block back to the FLAC file. This function tries to be
  81858. * as efficient as possible; how the block is actually written is
  81859. * shown by the following:
  81860. *
  81861. * Existing block is a STREAMINFO block and the new block is a
  81862. * STREAMINFO block: the new block is written in place. Make sure
  81863. * you know what you're doing when changing the values of a
  81864. * STREAMINFO block.
  81865. *
  81866. * Existing block is a STREAMINFO block and the new block is a
  81867. * not a STREAMINFO block: this is an error since the first block
  81868. * must be a STREAMINFO block. Returns \c false without altering the
  81869. * file.
  81870. *
  81871. * Existing block is not a STREAMINFO block and the new block is a
  81872. * STREAMINFO block: this is an error since there may be only one
  81873. * STREAMINFO block. Returns \c false without altering the file.
  81874. *
  81875. * Existing block and new block are the same length: the existing
  81876. * block will be replaced by the new block, written in place.
  81877. *
  81878. * Existing block is longer than new block: if use_padding is \c true,
  81879. * the existing block will be overwritten in place with the new
  81880. * block followed by a PADDING block, if possible, to make the total
  81881. * size the same as the existing block. Remember that a padding
  81882. * block requires at least four bytes so if the difference in size
  81883. * between the new block and existing block is less than that, the
  81884. * entire file will have to be rewritten, using the new block's
  81885. * exact size. If use_padding is \c false, the entire file will be
  81886. * rewritten, replacing the existing block by the new block.
  81887. *
  81888. * Existing block is shorter than new block: if use_padding is \c true,
  81889. * the function will try and expand the new block into the following
  81890. * PADDING block, if it exists and doing so won't shrink the PADDING
  81891. * block to less than 4 bytes. If there is no following PADDING
  81892. * block, or it will shrink to less than 4 bytes, or use_padding is
  81893. * \c false, the entire file is rewritten, replacing the existing block
  81894. * with the new block. Note that in this case any following PADDING
  81895. * block is preserved as is.
  81896. *
  81897. * After writing the block, the iterator will remain in the same
  81898. * place, i.e. pointing to the new block.
  81899. *
  81900. * \param iterator A pointer to an existing initialized iterator.
  81901. * \param block The block to set.
  81902. * \param use_padding See above.
  81903. * \assert
  81904. * \code iterator != NULL \endcode
  81905. * \a iterator has been successfully initialized with
  81906. * FLAC__metadata_simple_iterator_init()
  81907. * \code block != NULL \endcode
  81908. * \retval FLAC__bool
  81909. * \c true if successful, else \c false.
  81910. */
  81911. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  81912. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  81913. * except that instead of writing over an existing block, it appends
  81914. * a block after the existing block. \a use_padding is again used to
  81915. * tell the function to try an expand into following padding in an
  81916. * attempt to avoid rewriting the entire file.
  81917. *
  81918. * This function will fail and return \c false if given a STREAMINFO
  81919. * block.
  81920. *
  81921. * After writing the block, the iterator will be pointing to the
  81922. * new block.
  81923. *
  81924. * \param iterator A pointer to an existing initialized iterator.
  81925. * \param block The block to set.
  81926. * \param use_padding See above.
  81927. * \assert
  81928. * \code iterator != NULL \endcode
  81929. * \a iterator has been successfully initialized with
  81930. * FLAC__metadata_simple_iterator_init()
  81931. * \code block != NULL \endcode
  81932. * \retval FLAC__bool
  81933. * \c true if successful, else \c false.
  81934. */
  81935. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  81936. /** Deletes the block at the current position. This will cause the
  81937. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  81938. * in which case the block will be replaced by an equal-sized PADDING
  81939. * block. The iterator will be left pointing to the block before the
  81940. * one just deleted.
  81941. *
  81942. * You may not delete the STREAMINFO block.
  81943. *
  81944. * \param iterator A pointer to an existing initialized iterator.
  81945. * \param use_padding See above.
  81946. * \assert
  81947. * \code iterator != NULL \endcode
  81948. * \a iterator has been successfully initialized with
  81949. * FLAC__metadata_simple_iterator_init()
  81950. * \retval FLAC__bool
  81951. * \c true if successful, else \c false.
  81952. */
  81953. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  81954. /* \} */
  81955. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  81956. * \ingroup flac_metadata
  81957. *
  81958. * \brief
  81959. * The level 2 interface provides read-write access to FLAC file metadata;
  81960. * all metadata is read into memory, operated on in memory, and then written
  81961. * to file, which is more efficient than level 1 when editing multiple blocks.
  81962. *
  81963. * Currently Ogg FLAC is supported for read only, via
  81964. * FLAC__metadata_chain_read_ogg() but a subsequent
  81965. * FLAC__metadata_chain_write() will fail.
  81966. *
  81967. * The general usage of this interface is:
  81968. *
  81969. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  81970. * linked list of FLAC metadata blocks.
  81971. * - Read all metadata into the the chain from a FLAC file using
  81972. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  81973. * check the status.
  81974. * - Optionally, consolidate the padding using
  81975. * FLAC__metadata_chain_merge_padding() or
  81976. * FLAC__metadata_chain_sort_padding().
  81977. * - Create a new iterator using FLAC__metadata_iterator_new()
  81978. * - Initialize the iterator to point to the first element in the chain
  81979. * using FLAC__metadata_iterator_init()
  81980. * - Traverse the chain using FLAC__metadata_iterator_next and
  81981. * FLAC__metadata_iterator_prev().
  81982. * - Get a block for reading or modification using
  81983. * FLAC__metadata_iterator_get_block(). The pointer to the object
  81984. * inside the chain is returned, so the block is yours to modify.
  81985. * Changes will be reflected in the FLAC file when you write the
  81986. * chain. You can also add and delete blocks (see functions below).
  81987. * - When done, write out the chain using FLAC__metadata_chain_write().
  81988. * Make sure to read the whole comment to the function below.
  81989. * - Delete the chain using FLAC__metadata_chain_delete().
  81990. *
  81991. * \note
  81992. * Even though the FLAC file is not open while the chain is being
  81993. * manipulated, you must not alter the file externally during
  81994. * this time. The chain assumes the FLAC file will not change
  81995. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  81996. * and FLAC__metadata_chain_write().
  81997. *
  81998. * \note
  81999. * Do not modify the is_last, length, or type fields of returned
  82000. * FLAC__StreamMetadata objects. These are managed automatically.
  82001. *
  82002. * \note
  82003. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  82004. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  82005. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  82006. * become owned by the chain and they will be deleted when the chain is
  82007. * deleted.
  82008. *
  82009. * \{
  82010. */
  82011. struct FLAC__Metadata_Chain;
  82012. /** The opaque structure definition for the level 2 chain type.
  82013. */
  82014. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  82015. struct FLAC__Metadata_Iterator;
  82016. /** The opaque structure definition for the level 2 iterator type.
  82017. */
  82018. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  82019. typedef enum {
  82020. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  82021. /**< The chain is in the normal OK state */
  82022. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  82023. /**< The data passed into a function violated the function's usage criteria */
  82024. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  82025. /**< The chain could not open the target file */
  82026. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  82027. /**< The chain could not find the FLAC signature at the start of the file */
  82028. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  82029. /**< The chain tried to write to a file that was not writable */
  82030. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  82031. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  82032. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  82033. /**< The chain encountered an error while reading the FLAC file */
  82034. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  82035. /**< The chain encountered an error while seeking in the FLAC file */
  82036. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  82037. /**< The chain encountered an error while writing the FLAC file */
  82038. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  82039. /**< The chain encountered an error renaming the FLAC file */
  82040. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  82041. /**< The chain encountered an error removing the temporary file */
  82042. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  82043. /**< Memory allocation failed */
  82044. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  82045. /**< The caller violated an assertion or an unexpected error occurred */
  82046. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  82047. /**< One or more of the required callbacks was NULL */
  82048. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  82049. /**< FLAC__metadata_chain_write() was called on a chain read by
  82050. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  82051. * or
  82052. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  82053. * was called on a chain read by
  82054. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  82055. * Matching read/write methods must always be used. */
  82056. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  82057. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  82058. * chain write requires a tempfile; use
  82059. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  82060. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  82061. * called when the chain write does not require a tempfile; use
  82062. * FLAC__metadata_chain_write_with_callbacks() instead.
  82063. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  82064. * before writing via callbacks. */
  82065. } FLAC__Metadata_ChainStatus;
  82066. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  82067. *
  82068. * Using a FLAC__Metadata_ChainStatus as the index to this array
  82069. * will give the string equivalent. The contents should not be modified.
  82070. */
  82071. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  82072. /*********** FLAC__Metadata_Chain ***********/
  82073. /** Create a new chain instance.
  82074. *
  82075. * \retval FLAC__Metadata_Chain*
  82076. * \c NULL if there was an error allocating memory, else the new instance.
  82077. */
  82078. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  82079. /** Free a chain instance. Deletes the object pointed to by \a chain.
  82080. *
  82081. * \param chain A pointer to an existing chain.
  82082. * \assert
  82083. * \code chain != NULL \endcode
  82084. */
  82085. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  82086. /** Get the current status of the chain. Call this after a function
  82087. * returns \c false to get the reason for the error. Also resets the
  82088. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  82089. *
  82090. * \param chain A pointer to an existing chain.
  82091. * \assert
  82092. * \code chain != NULL \endcode
  82093. * \retval FLAC__Metadata_ChainStatus
  82094. * The current status of the chain.
  82095. */
  82096. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  82097. /** Read all metadata from a FLAC file into the chain.
  82098. *
  82099. * \param chain A pointer to an existing chain.
  82100. * \param filename The path to the FLAC file to read.
  82101. * \assert
  82102. * \code chain != NULL \endcode
  82103. * \code filename != NULL \endcode
  82104. * \retval FLAC__bool
  82105. * \c true if a valid list of metadata blocks was read from
  82106. * \a filename, else \c false. On failure, check the status with
  82107. * FLAC__metadata_chain_status().
  82108. */
  82109. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  82110. /** Read all metadata from an Ogg FLAC file into the chain.
  82111. *
  82112. * \note Ogg FLAC metadata data writing is not supported yet and
  82113. * FLAC__metadata_chain_write() will fail.
  82114. *
  82115. * \param chain A pointer to an existing chain.
  82116. * \param filename The path to the Ogg FLAC file to read.
  82117. * \assert
  82118. * \code chain != NULL \endcode
  82119. * \code filename != NULL \endcode
  82120. * \retval FLAC__bool
  82121. * \c true if a valid list of metadata blocks was read from
  82122. * \a filename, else \c false. On failure, check the status with
  82123. * FLAC__metadata_chain_status().
  82124. */
  82125. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  82126. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  82127. *
  82128. * The \a handle need only be open for reading, but must be seekable.
  82129. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  82130. * for Windows).
  82131. *
  82132. * \param chain A pointer to an existing chain.
  82133. * \param handle The I/O handle of the FLAC stream to read. The
  82134. * handle will NOT be closed after the metadata is read;
  82135. * that is the duty of the caller.
  82136. * \param callbacks
  82137. * A set of callbacks to use for I/O. The mandatory
  82138. * callbacks are \a read, \a seek, and \a tell.
  82139. * \assert
  82140. * \code chain != NULL \endcode
  82141. * \retval FLAC__bool
  82142. * \c true if a valid list of metadata blocks was read from
  82143. * \a handle, else \c false. On failure, check the status with
  82144. * FLAC__metadata_chain_status().
  82145. */
  82146. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  82147. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  82148. *
  82149. * The \a handle need only be open for reading, but must be seekable.
  82150. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  82151. * for Windows).
  82152. *
  82153. * \note Ogg FLAC metadata data writing is not supported yet and
  82154. * FLAC__metadata_chain_write() will fail.
  82155. *
  82156. * \param chain A pointer to an existing chain.
  82157. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  82158. * handle will NOT be closed after the metadata is read;
  82159. * that is the duty of the caller.
  82160. * \param callbacks
  82161. * A set of callbacks to use for I/O. The mandatory
  82162. * callbacks are \a read, \a seek, and \a tell.
  82163. * \assert
  82164. * \code chain != NULL \endcode
  82165. * \retval FLAC__bool
  82166. * \c true if a valid list of metadata blocks was read from
  82167. * \a handle, else \c false. On failure, check the status with
  82168. * FLAC__metadata_chain_status().
  82169. */
  82170. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  82171. /** Checks if writing the given chain would require the use of a
  82172. * temporary file, or if it could be written in place.
  82173. *
  82174. * Under certain conditions, padding can be utilized so that writing
  82175. * edited metadata back to the FLAC file does not require rewriting the
  82176. * entire file. If rewriting is required, then a temporary workfile is
  82177. * required. When writing metadata using callbacks, you must check
  82178. * this function to know whether to call
  82179. * FLAC__metadata_chain_write_with_callbacks() or
  82180. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  82181. * writing with FLAC__metadata_chain_write(), the temporary file is
  82182. * handled internally.
  82183. *
  82184. * \param chain A pointer to an existing chain.
  82185. * \param use_padding
  82186. * Whether or not padding will be allowed to be used
  82187. * during the write. The value of \a use_padding given
  82188. * here must match the value later passed to
  82189. * FLAC__metadata_chain_write_with_callbacks() or
  82190. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  82191. * \assert
  82192. * \code chain != NULL \endcode
  82193. * \retval FLAC__bool
  82194. * \c true if writing the current chain would require a tempfile, or
  82195. * \c false if metadata can be written in place.
  82196. */
  82197. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  82198. /** Write all metadata out to the FLAC file. This function tries to be as
  82199. * efficient as possible; how the metadata is actually written is shown by
  82200. * the following:
  82201. *
  82202. * If the current chain is the same size as the existing metadata, the new
  82203. * data is written in place.
  82204. *
  82205. * If the current chain is longer than the existing metadata, and
  82206. * \a use_padding is \c true, and the last block is a PADDING block of
  82207. * sufficient length, the function will truncate the final padding block
  82208. * so that the overall size of the metadata is the same as the existing
  82209. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  82210. * the above conditions are met, the entire FLAC file must be rewritten.
  82211. * If you want to use padding this way it is a good idea to call
  82212. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  82213. * amount of padding to work with, unless you need to preserve ordering
  82214. * of the PADDING blocks for some reason.
  82215. *
  82216. * If the current chain is shorter than the existing metadata, and
  82217. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  82218. * is extended to make the overall size the same as the existing data. If
  82219. * \a use_padding is \c true and the last block is not a PADDING block, a new
  82220. * PADDING block is added to the end of the new data to make it the same
  82221. * size as the existing data (if possible, see the note to
  82222. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  82223. * and the new data is written in place. If none of the above apply or
  82224. * \a use_padding is \c false, the entire FLAC file is rewritten.
  82225. *
  82226. * If \a preserve_file_stats is \c true, the owner and modification time will
  82227. * be preserved even if the FLAC file is written.
  82228. *
  82229. * For this write function to be used, the chain must have been read with
  82230. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  82231. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  82232. *
  82233. * \param chain A pointer to an existing chain.
  82234. * \param use_padding See above.
  82235. * \param preserve_file_stats See above.
  82236. * \assert
  82237. * \code chain != NULL \endcode
  82238. * \retval FLAC__bool
  82239. * \c true if the write succeeded, else \c false. On failure,
  82240. * check the status with FLAC__metadata_chain_status().
  82241. */
  82242. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  82243. /** Write all metadata out to a FLAC stream via callbacks.
  82244. *
  82245. * (See FLAC__metadata_chain_write() for the details on how padding is
  82246. * used to write metadata in place if possible.)
  82247. *
  82248. * The \a handle must be open for updating and be seekable. The
  82249. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  82250. * for Windows).
  82251. *
  82252. * For this write function to be used, the chain must have been read with
  82253. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  82254. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  82255. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  82256. * \c false.
  82257. *
  82258. * \param chain A pointer to an existing chain.
  82259. * \param use_padding See FLAC__metadata_chain_write()
  82260. * \param handle The I/O handle of the FLAC stream to write. The
  82261. * handle will NOT be closed after the metadata is
  82262. * written; that is the duty of the caller.
  82263. * \param callbacks A set of callbacks to use for I/O. The mandatory
  82264. * callbacks are \a write and \a seek.
  82265. * \assert
  82266. * \code chain != NULL \endcode
  82267. * \retval FLAC__bool
  82268. * \c true if the write succeeded, else \c false. On failure,
  82269. * check the status with FLAC__metadata_chain_status().
  82270. */
  82271. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  82272. /** Write all metadata out to a FLAC stream via callbacks.
  82273. *
  82274. * (See FLAC__metadata_chain_write() for the details on how padding is
  82275. * used to write metadata in place if possible.)
  82276. *
  82277. * This version of the write-with-callbacks function must be used when
  82278. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  82279. * this function, you must supply an I/O handle corresponding to the
  82280. * FLAC file to edit, and a temporary handle to which the new FLAC
  82281. * file will be written. It is the caller's job to move this temporary
  82282. * FLAC file on top of the original FLAC file to complete the metadata
  82283. * edit.
  82284. *
  82285. * The \a handle must be open for reading and be seekable. The
  82286. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  82287. * for Windows).
  82288. *
  82289. * The \a temp_handle must be open for writing. The
  82290. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  82291. * for Windows). It should be an empty stream, or at least positioned
  82292. * at the start-of-file (in which case it is the caller's duty to
  82293. * truncate it on return).
  82294. *
  82295. * For this write function to be used, the chain must have been read with
  82296. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  82297. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  82298. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  82299. * \c true.
  82300. *
  82301. * \param chain A pointer to an existing chain.
  82302. * \param use_padding See FLAC__metadata_chain_write()
  82303. * \param handle The I/O handle of the original FLAC stream to read.
  82304. * The handle will NOT be closed after the metadata is
  82305. * written; that is the duty of the caller.
  82306. * \param callbacks A set of callbacks to use for I/O on \a handle.
  82307. * The mandatory callbacks are \a read, \a seek, and
  82308. * \a eof.
  82309. * \param temp_handle The I/O handle of the FLAC stream to write. The
  82310. * handle will NOT be closed after the metadata is
  82311. * written; that is the duty of the caller.
  82312. * \param temp_callbacks
  82313. * A set of callbacks to use for I/O on temp_handle.
  82314. * The only mandatory callback is \a write.
  82315. * \assert
  82316. * \code chain != NULL \endcode
  82317. * \retval FLAC__bool
  82318. * \c true if the write succeeded, else \c false. On failure,
  82319. * check the status with FLAC__metadata_chain_status().
  82320. */
  82321. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks_and_tempfile(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, FLAC__IOHandle temp_handle, FLAC__IOCallbacks temp_callbacks);
  82322. /** Merge adjacent PADDING blocks into a single block.
  82323. *
  82324. * \note This function does not write to the FLAC file, it only
  82325. * modifies the chain.
  82326. *
  82327. * \warning Any iterator on the current chain will become invalid after this
  82328. * call. You should delete the iterator and get a new one.
  82329. *
  82330. * \param chain A pointer to an existing chain.
  82331. * \assert
  82332. * \code chain != NULL \endcode
  82333. */
  82334. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  82335. /** This function will move all PADDING blocks to the end on the metadata,
  82336. * then merge them into a single block.
  82337. *
  82338. * \note This function does not write to the FLAC file, it only
  82339. * modifies the chain.
  82340. *
  82341. * \warning Any iterator on the current chain will become invalid after this
  82342. * call. You should delete the iterator and get a new one.
  82343. *
  82344. * \param chain A pointer to an existing chain.
  82345. * \assert
  82346. * \code chain != NULL \endcode
  82347. */
  82348. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  82349. /*********** FLAC__Metadata_Iterator ***********/
  82350. /** Create a new iterator instance.
  82351. *
  82352. * \retval FLAC__Metadata_Iterator*
  82353. * \c NULL if there was an error allocating memory, else the new instance.
  82354. */
  82355. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  82356. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  82357. *
  82358. * \param iterator A pointer to an existing iterator.
  82359. * \assert
  82360. * \code iterator != NULL \endcode
  82361. */
  82362. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  82363. /** Initialize the iterator to point to the first metadata block in the
  82364. * given chain.
  82365. *
  82366. * \param iterator A pointer to an existing iterator.
  82367. * \param chain A pointer to an existing and initialized (read) chain.
  82368. * \assert
  82369. * \code iterator != NULL \endcode
  82370. * \code chain != NULL \endcode
  82371. */
  82372. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  82373. /** Moves the iterator forward one metadata block, returning \c false if
  82374. * already at the end.
  82375. *
  82376. * \param iterator A pointer to an existing initialized iterator.
  82377. * \assert
  82378. * \code iterator != NULL \endcode
  82379. * \a iterator has been successfully initialized with
  82380. * FLAC__metadata_iterator_init()
  82381. * \retval FLAC__bool
  82382. * \c false if already at the last metadata block of the chain, else
  82383. * \c true.
  82384. */
  82385. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  82386. /** Moves the iterator backward one metadata block, returning \c false if
  82387. * already at the beginning.
  82388. *
  82389. * \param iterator A pointer to an existing initialized iterator.
  82390. * \assert
  82391. * \code iterator != NULL \endcode
  82392. * \a iterator has been successfully initialized with
  82393. * FLAC__metadata_iterator_init()
  82394. * \retval FLAC__bool
  82395. * \c false if already at the first metadata block of the chain, else
  82396. * \c true.
  82397. */
  82398. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  82399. /** Get the type of the metadata block at the current position.
  82400. *
  82401. * \param iterator A pointer to an existing initialized iterator.
  82402. * \assert
  82403. * \code iterator != NULL \endcode
  82404. * \a iterator has been successfully initialized with
  82405. * FLAC__metadata_iterator_init()
  82406. * \retval FLAC__MetadataType
  82407. * The type of the metadata block at the current iterator position.
  82408. */
  82409. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  82410. /** Get the metadata block at the current position. You can modify
  82411. * the block in place but must write the chain before the changes
  82412. * are reflected to the FLAC file. You do not need to call
  82413. * FLAC__metadata_iterator_set_block() to reflect the changes;
  82414. * the pointer returned by FLAC__metadata_iterator_get_block()
  82415. * points directly into the chain.
  82416. *
  82417. * \warning
  82418. * Do not call FLAC__metadata_object_delete() on the returned object;
  82419. * to delete a block use FLAC__metadata_iterator_delete_block().
  82420. *
  82421. * \param iterator A pointer to an existing initialized iterator.
  82422. * \assert
  82423. * \code iterator != NULL \endcode
  82424. * \a iterator has been successfully initialized with
  82425. * FLAC__metadata_iterator_init()
  82426. * \retval FLAC__StreamMetadata*
  82427. * The current metadata block.
  82428. */
  82429. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  82430. /** Set the metadata block at the current position, replacing the existing
  82431. * block. The new block passed in becomes owned by the chain and it will be
  82432. * deleted when the chain is deleted.
  82433. *
  82434. * \param iterator A pointer to an existing initialized iterator.
  82435. * \param block A pointer to a metadata block.
  82436. * \assert
  82437. * \code iterator != NULL \endcode
  82438. * \a iterator has been successfully initialized with
  82439. * FLAC__metadata_iterator_init()
  82440. * \code block != NULL \endcode
  82441. * \retval FLAC__bool
  82442. * \c false if the conditions in the above description are not met, or
  82443. * a memory allocation error occurs, otherwise \c true.
  82444. */
  82445. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  82446. /** Removes the current block from the chain. If \a replace_with_padding is
  82447. * \c true, the block will instead be replaced with a padding block of equal
  82448. * size. You can not delete the STREAMINFO block. The iterator will be
  82449. * left pointing to the block before the one just "deleted", even if
  82450. * \a replace_with_padding is \c true.
  82451. *
  82452. * \param iterator A pointer to an existing initialized iterator.
  82453. * \param replace_with_padding See above.
  82454. * \assert
  82455. * \code iterator != NULL \endcode
  82456. * \a iterator has been successfully initialized with
  82457. * FLAC__metadata_iterator_init()
  82458. * \retval FLAC__bool
  82459. * \c false if the conditions in the above description are not met,
  82460. * otherwise \c true.
  82461. */
  82462. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  82463. /** Insert a new block before the current block. You cannot insert a block
  82464. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  82465. * as there can be only one, the one that already exists at the head when you
  82466. * read in a chain. The chain takes ownership of the new block and it will be
  82467. * deleted when the chain is deleted. The iterator will be left pointing to
  82468. * the new block.
  82469. *
  82470. * \param iterator A pointer to an existing initialized iterator.
  82471. * \param block A pointer to a metadata block to insert.
  82472. * \assert
  82473. * \code iterator != NULL \endcode
  82474. * \a iterator has been successfully initialized with
  82475. * FLAC__metadata_iterator_init()
  82476. * \retval FLAC__bool
  82477. * \c false if the conditions in the above description are not met, or
  82478. * a memory allocation error occurs, otherwise \c true.
  82479. */
  82480. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  82481. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  82482. * block as there can be only one, the one that already exists at the head when
  82483. * you read in a chain. The chain takes ownership of the new block and it will
  82484. * be deleted when the chain is deleted. The iterator will be left pointing to
  82485. * the new block.
  82486. *
  82487. * \param iterator A pointer to an existing initialized iterator.
  82488. * \param block A pointer to a metadata block to insert.
  82489. * \assert
  82490. * \code iterator != NULL \endcode
  82491. * \a iterator has been successfully initialized with
  82492. * FLAC__metadata_iterator_init()
  82493. * \retval FLAC__bool
  82494. * \c false if the conditions in the above description are not met, or
  82495. * a memory allocation error occurs, otherwise \c true.
  82496. */
  82497. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  82498. /* \} */
  82499. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  82500. * \ingroup flac_metadata
  82501. *
  82502. * \brief
  82503. * This module contains methods for manipulating FLAC metadata objects.
  82504. *
  82505. * Since many are variable length we have to be careful about the memory
  82506. * management. We decree that all pointers to data in the object are
  82507. * owned by the object and memory-managed by the object.
  82508. *
  82509. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  82510. * functions to create all instances. When using the
  82511. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  82512. * \a copy to \c true to have the function make it's own copy of the data, or
  82513. * to \c false to give the object ownership of your data. In the latter case
  82514. * your pointer must be freeable by free() and will be free()d when the object
  82515. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  82516. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  82517. * the length argument is 0 and the \a copy argument is \c false.
  82518. *
  82519. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  82520. * will return \c NULL in the case of a memory allocation error, otherwise a new
  82521. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  82522. * case of a memory allocation error.
  82523. *
  82524. * We don't have the convenience of C++ here, so note that the library relies
  82525. * on you to keep the types straight. In other words, if you pass, for
  82526. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  82527. * FLAC__metadata_object_application_set_data(), you will get an assertion
  82528. * failure.
  82529. *
  82530. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  82531. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  82532. * toward the length or stored in the stream, but it can make working with plain
  82533. * comments (those that don't contain embedded-NULs in the value) easier.
  82534. * Entries passed into these functions have trailing NULs added if missing, and
  82535. * returned entries are guaranteed to have a trailing NUL.
  82536. *
  82537. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  82538. * comment entry/name/value will first validate that it complies with the Vorbis
  82539. * comment specification and return false if it does not.
  82540. *
  82541. * There is no need to recalculate the length field on metadata blocks you
  82542. * have modified. They will be calculated automatically before they are
  82543. * written back to a file.
  82544. *
  82545. * \{
  82546. */
  82547. /** Create a new metadata object instance of the given type.
  82548. *
  82549. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  82550. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  82551. * the vendor string set (but zero comments).
  82552. *
  82553. * Do not pass in a value greater than or equal to
  82554. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  82555. * doing.
  82556. *
  82557. * \param type Type of object to create
  82558. * \retval FLAC__StreamMetadata*
  82559. * \c NULL if there was an error allocating memory or the type code is
  82560. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  82561. */
  82562. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  82563. /** Create a copy of an existing metadata object.
  82564. *
  82565. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  82566. * object is also copied. The caller takes ownership of the new block and
  82567. * is responsible for freeing it with FLAC__metadata_object_delete().
  82568. *
  82569. * \param object Pointer to object to copy.
  82570. * \assert
  82571. * \code object != NULL \endcode
  82572. * \retval FLAC__StreamMetadata*
  82573. * \c NULL if there was an error allocating memory, else the new instance.
  82574. */
  82575. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  82576. /** Free a metadata object. Deletes the object pointed to by \a object.
  82577. *
  82578. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  82579. * object is also deleted.
  82580. *
  82581. * \param object A pointer to an existing object.
  82582. * \assert
  82583. * \code object != NULL \endcode
  82584. */
  82585. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  82586. /** Compares two metadata objects.
  82587. *
  82588. * The compare is "deep", i.e. dynamically allocated data within the
  82589. * object is also compared.
  82590. *
  82591. * \param block1 A pointer to an existing object.
  82592. * \param block2 A pointer to an existing object.
  82593. * \assert
  82594. * \code block1 != NULL \endcode
  82595. * \code block2 != NULL \endcode
  82596. * \retval FLAC__bool
  82597. * \c true if objects are identical, else \c false.
  82598. */
  82599. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  82600. /** Sets the application data of an APPLICATION block.
  82601. *
  82602. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  82603. * takes ownership of the pointer. The existing data will be freed if this
  82604. * function is successful, otherwise the original data will remain if \a copy
  82605. * is \c true and malloc() fails.
  82606. *
  82607. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  82608. *
  82609. * \param object A pointer to an existing APPLICATION object.
  82610. * \param data A pointer to the data to set.
  82611. * \param length The length of \a data in bytes.
  82612. * \param copy See above.
  82613. * \assert
  82614. * \code object != NULL \endcode
  82615. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  82616. * \code (data != NULL && length > 0) ||
  82617. * (data == NULL && length == 0 && copy == false) \endcode
  82618. * \retval FLAC__bool
  82619. * \c false if \a copy is \c true and malloc() fails, else \c true.
  82620. */
  82621. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  82622. /** Resize the seekpoint array.
  82623. *
  82624. * If the size shrinks, elements will truncated; if it grows, new placeholder
  82625. * points will be added to the end.
  82626. *
  82627. * \param object A pointer to an existing SEEKTABLE object.
  82628. * \param new_num_points The desired length of the array; may be \c 0.
  82629. * \assert
  82630. * \code object != NULL \endcode
  82631. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82632. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  82633. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  82634. * \retval FLAC__bool
  82635. * \c false if memory allocation error, else \c true.
  82636. */
  82637. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  82638. /** Set a seekpoint in a seektable.
  82639. *
  82640. * \param object A pointer to an existing SEEKTABLE object.
  82641. * \param point_num Index into seekpoint array to set.
  82642. * \param point The point to set.
  82643. * \assert
  82644. * \code object != NULL \endcode
  82645. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82646. * \code object->data.seek_table.num_points > point_num \endcode
  82647. */
  82648. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  82649. /** Insert a seekpoint into a seektable.
  82650. *
  82651. * \param object A pointer to an existing SEEKTABLE object.
  82652. * \param point_num Index into seekpoint array to set.
  82653. * \param point The point to set.
  82654. * \assert
  82655. * \code object != NULL \endcode
  82656. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82657. * \code object->data.seek_table.num_points >= point_num \endcode
  82658. * \retval FLAC__bool
  82659. * \c false if memory allocation error, else \c true.
  82660. */
  82661. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  82662. /** Delete a seekpoint from a seektable.
  82663. *
  82664. * \param object A pointer to an existing SEEKTABLE object.
  82665. * \param point_num Index into seekpoint array to set.
  82666. * \assert
  82667. * \code object != NULL \endcode
  82668. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82669. * \code object->data.seek_table.num_points > point_num \endcode
  82670. * \retval FLAC__bool
  82671. * \c false if memory allocation error, else \c true.
  82672. */
  82673. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  82674. /** Check a seektable to see if it conforms to the FLAC specification.
  82675. * See the format specification for limits on the contents of the
  82676. * seektable.
  82677. *
  82678. * \param object A pointer to an existing SEEKTABLE object.
  82679. * \assert
  82680. * \code object != NULL \endcode
  82681. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82682. * \retval FLAC__bool
  82683. * \c false if seek table is illegal, else \c true.
  82684. */
  82685. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  82686. /** Append a number of placeholder points to the end of a seek table.
  82687. *
  82688. * \note
  82689. * As with the other ..._seektable_template_... functions, you should
  82690. * call FLAC__metadata_object_seektable_template_sort() when finished
  82691. * to make the seek table legal.
  82692. *
  82693. * \param object A pointer to an existing SEEKTABLE object.
  82694. * \param num The number of placeholder points to append.
  82695. * \assert
  82696. * \code object != NULL \endcode
  82697. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82698. * \retval FLAC__bool
  82699. * \c false if memory allocation fails, else \c true.
  82700. */
  82701. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  82702. /** Append a specific seek point template to the end of a seek table.
  82703. *
  82704. * \note
  82705. * As with the other ..._seektable_template_... functions, you should
  82706. * call FLAC__metadata_object_seektable_template_sort() when finished
  82707. * to make the seek table legal.
  82708. *
  82709. * \param object A pointer to an existing SEEKTABLE object.
  82710. * \param sample_number The sample number of the seek point template.
  82711. * \assert
  82712. * \code object != NULL \endcode
  82713. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82714. * \retval FLAC__bool
  82715. * \c false if memory allocation fails, else \c true.
  82716. */
  82717. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  82718. /** Append specific seek point templates to the end of a seek table.
  82719. *
  82720. * \note
  82721. * As with the other ..._seektable_template_... functions, you should
  82722. * call FLAC__metadata_object_seektable_template_sort() when finished
  82723. * to make the seek table legal.
  82724. *
  82725. * \param object A pointer to an existing SEEKTABLE object.
  82726. * \param sample_numbers An array of sample numbers for the seek points.
  82727. * \param num The number of seek point templates to append.
  82728. * \assert
  82729. * \code object != NULL \endcode
  82730. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82731. * \retval FLAC__bool
  82732. * \c false if memory allocation fails, else \c true.
  82733. */
  82734. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  82735. /** Append a set of evenly-spaced seek point templates to the end of a
  82736. * seek table.
  82737. *
  82738. * \note
  82739. * As with the other ..._seektable_template_... functions, you should
  82740. * call FLAC__metadata_object_seektable_template_sort() when finished
  82741. * to make the seek table legal.
  82742. *
  82743. * \param object A pointer to an existing SEEKTABLE object.
  82744. * \param num The number of placeholder points to append.
  82745. * \param total_samples The total number of samples to be encoded;
  82746. * the seekpoints will be spaced approximately
  82747. * \a total_samples / \a num samples apart.
  82748. * \assert
  82749. * \code object != NULL \endcode
  82750. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82751. * \code total_samples > 0 \endcode
  82752. * \retval FLAC__bool
  82753. * \c false if memory allocation fails, else \c true.
  82754. */
  82755. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  82756. /** Append a set of evenly-spaced seek point templates to the end of a
  82757. * seek table.
  82758. *
  82759. * \note
  82760. * As with the other ..._seektable_template_... functions, you should
  82761. * call FLAC__metadata_object_seektable_template_sort() when finished
  82762. * to make the seek table legal.
  82763. *
  82764. * \param object A pointer to an existing SEEKTABLE object.
  82765. * \param samples The number of samples apart to space the placeholder
  82766. * points. The first point will be at sample \c 0, the
  82767. * second at sample \a samples, then 2*\a samples, and
  82768. * so on. As long as \a samples and \a total_samples
  82769. * are greater than \c 0, there will always be at least
  82770. * one seekpoint at sample \c 0.
  82771. * \param total_samples The total number of samples to be encoded;
  82772. * the seekpoints will be spaced
  82773. * \a samples samples apart.
  82774. * \assert
  82775. * \code object != NULL \endcode
  82776. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82777. * \code samples > 0 \endcode
  82778. * \code total_samples > 0 \endcode
  82779. * \retval FLAC__bool
  82780. * \c false if memory allocation fails, else \c true.
  82781. */
  82782. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  82783. /** Sort a seek table's seek points according to the format specification,
  82784. * removing duplicates.
  82785. *
  82786. * \param object A pointer to a seek table to be sorted.
  82787. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  82788. * If \c true, duplicates are deleted and the seek table is
  82789. * shrunk appropriately; the number of placeholder points
  82790. * present in the seek table will be the same after the call
  82791. * as before.
  82792. * \assert
  82793. * \code object != NULL \endcode
  82794. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82795. * \retval FLAC__bool
  82796. * \c false if realloc() fails, else \c true.
  82797. */
  82798. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  82799. /** Sets the vendor string in a VORBIS_COMMENT block.
  82800. *
  82801. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82802. * one already.
  82803. *
  82804. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82805. * takes ownership of the \c entry.entry pointer.
  82806. *
  82807. * \note If this function returns \c false, the caller still owns the
  82808. * pointer.
  82809. *
  82810. * \param object A pointer to an existing VORBIS_COMMENT object.
  82811. * \param entry The entry to set the vendor string to.
  82812. * \param copy See above.
  82813. * \assert
  82814. * \code object != NULL \endcode
  82815. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82816. * \code (entry.entry != NULL && entry.length > 0) ||
  82817. * (entry.entry == NULL && entry.length == 0) \endcode
  82818. * \retval FLAC__bool
  82819. * \c false if memory allocation fails or \a entry does not comply with the
  82820. * Vorbis comment specification, else \c true.
  82821. */
  82822. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82823. /** Resize the comment array.
  82824. *
  82825. * If the size shrinks, elements will truncated; if it grows, new empty
  82826. * fields will be added to the end.
  82827. *
  82828. * \param object A pointer to an existing VORBIS_COMMENT object.
  82829. * \param new_num_comments The desired length of the array; may be \c 0.
  82830. * \assert
  82831. * \code object != NULL \endcode
  82832. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82833. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  82834. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  82835. * \retval FLAC__bool
  82836. * \c false if memory allocation fails, else \c true.
  82837. */
  82838. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  82839. /** Sets a comment in a VORBIS_COMMENT block.
  82840. *
  82841. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82842. * one already.
  82843. *
  82844. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82845. * takes ownership of the \c entry.entry pointer.
  82846. *
  82847. * \note If this function returns \c false, the caller still owns the
  82848. * pointer.
  82849. *
  82850. * \param object A pointer to an existing VORBIS_COMMENT object.
  82851. * \param comment_num Index into comment array to set.
  82852. * \param entry The entry to set the comment to.
  82853. * \param copy See above.
  82854. * \assert
  82855. * \code object != NULL \endcode
  82856. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82857. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  82858. * \code (entry.entry != NULL && entry.length > 0) ||
  82859. * (entry.entry == NULL && entry.length == 0) \endcode
  82860. * \retval FLAC__bool
  82861. * \c false if memory allocation fails or \a entry does not comply with the
  82862. * Vorbis comment specification, else \c true.
  82863. */
  82864. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82865. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  82866. *
  82867. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82868. * one already.
  82869. *
  82870. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82871. * takes ownership of the \c entry.entry pointer.
  82872. *
  82873. * \note If this function returns \c false, the caller still owns the
  82874. * pointer.
  82875. *
  82876. * \param object A pointer to an existing VORBIS_COMMENT object.
  82877. * \param comment_num The index at which to insert the comment. The comments
  82878. * at and after \a comment_num move right one position.
  82879. * To append a comment to the end, set \a comment_num to
  82880. * \c object->data.vorbis_comment.num_comments .
  82881. * \param entry The comment to insert.
  82882. * \param copy See above.
  82883. * \assert
  82884. * \code object != NULL \endcode
  82885. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82886. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  82887. * \code (entry.entry != NULL && entry.length > 0) ||
  82888. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  82889. * \retval FLAC__bool
  82890. * \c false if memory allocation fails or \a entry does not comply with the
  82891. * Vorbis comment specification, else \c true.
  82892. */
  82893. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82894. /** Appends a comment to a VORBIS_COMMENT block.
  82895. *
  82896. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82897. * one already.
  82898. *
  82899. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82900. * takes ownership of the \c entry.entry pointer.
  82901. *
  82902. * \note If this function returns \c false, the caller still owns the
  82903. * pointer.
  82904. *
  82905. * \param object A pointer to an existing VORBIS_COMMENT object.
  82906. * \param entry The comment to insert.
  82907. * \param copy See above.
  82908. * \assert
  82909. * \code object != NULL \endcode
  82910. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82911. * \code (entry.entry != NULL && entry.length > 0) ||
  82912. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  82913. * \retval FLAC__bool
  82914. * \c false if memory allocation fails or \a entry does not comply with the
  82915. * Vorbis comment specification, else \c true.
  82916. */
  82917. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82918. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  82919. *
  82920. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82921. * one already.
  82922. *
  82923. * Depending on the the value of \a all, either all or just the first comment
  82924. * whose field name(s) match the given entry's name will be replaced by the
  82925. * given entry. If no comments match, \a entry will simply be appended.
  82926. *
  82927. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82928. * takes ownership of the \c entry.entry pointer.
  82929. *
  82930. * \note If this function returns \c false, the caller still owns the
  82931. * pointer.
  82932. *
  82933. * \param object A pointer to an existing VORBIS_COMMENT object.
  82934. * \param entry The comment to insert.
  82935. * \param all If \c true, all comments whose field name matches
  82936. * \a entry's field name will be removed, and \a entry will
  82937. * be inserted at the position of the first matching
  82938. * comment. If \c false, only the first comment whose
  82939. * field name matches \a entry's field name will be
  82940. * replaced with \a entry.
  82941. * \param copy See above.
  82942. * \assert
  82943. * \code object != NULL \endcode
  82944. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82945. * \code (entry.entry != NULL && entry.length > 0) ||
  82946. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  82947. * \retval FLAC__bool
  82948. * \c false if memory allocation fails or \a entry does not comply with the
  82949. * Vorbis comment specification, else \c true.
  82950. */
  82951. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  82952. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  82953. *
  82954. * \param object A pointer to an existing VORBIS_COMMENT object.
  82955. * \param comment_num The index of the comment to delete.
  82956. * \assert
  82957. * \code object != NULL \endcode
  82958. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82959. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  82960. * \retval FLAC__bool
  82961. * \c false if realloc() fails, else \c true.
  82962. */
  82963. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  82964. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  82965. *
  82966. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  82967. * memory and shall be owned by the caller. For convenience the entry will
  82968. * have a terminating NUL.
  82969. *
  82970. * \param entry A pointer to a Vorbis comment entry. The entry's
  82971. * \c entry pointer should not point to allocated
  82972. * memory as it will be overwritten.
  82973. * \param field_name The field name in ASCII, \c NUL terminated.
  82974. * \param field_value The field value in UTF-8, \c NUL terminated.
  82975. * \assert
  82976. * \code entry != NULL \endcode
  82977. * \code field_name != NULL \endcode
  82978. * \code field_value != NULL \endcode
  82979. * \retval FLAC__bool
  82980. * \c false if malloc() fails, or if \a field_name or \a field_value does
  82981. * not comply with the Vorbis comment specification, else \c true.
  82982. */
  82983. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(FLAC__StreamMetadata_VorbisComment_Entry *entry, const char *field_name, const char *field_value);
  82984. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  82985. *
  82986. * The returned pointers to name and value will be allocated by malloc()
  82987. * and shall be owned by the caller.
  82988. *
  82989. * \param entry An existing Vorbis comment entry.
  82990. * \param field_name The address of where the returned pointer to the
  82991. * field name will be stored.
  82992. * \param field_value The address of where the returned pointer to the
  82993. * field value will be stored.
  82994. * \assert
  82995. * \code (entry.entry != NULL && entry.length > 0) \endcode
  82996. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  82997. * \code field_name != NULL \endcode
  82998. * \code field_value != NULL \endcode
  82999. * \retval FLAC__bool
  83000. * \c false if memory allocation fails or \a entry does not comply with the
  83001. * Vorbis comment specification, else \c true.
  83002. */
  83003. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair(const FLAC__StreamMetadata_VorbisComment_Entry entry, char **field_name, char **field_value);
  83004. /** Check if the given Vorbis comment entry's field name matches the given
  83005. * field name.
  83006. *
  83007. * \param entry An existing Vorbis comment entry.
  83008. * \param field_name The field name to check.
  83009. * \param field_name_length The length of \a field_name, not including the
  83010. * terminating \c NUL.
  83011. * \assert
  83012. * \code (entry.entry != NULL && entry.length > 0) \endcode
  83013. * \retval FLAC__bool
  83014. * \c true if the field names match, else \c false
  83015. */
  83016. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  83017. /** Find a Vorbis comment with the given field name.
  83018. *
  83019. * The search begins at entry number \a offset; use an offset of 0 to
  83020. * search from the beginning of the comment array.
  83021. *
  83022. * \param object A pointer to an existing VORBIS_COMMENT object.
  83023. * \param offset The offset into the comment array from where to start
  83024. * the search.
  83025. * \param field_name The field name of the comment to find.
  83026. * \assert
  83027. * \code object != NULL \endcode
  83028. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83029. * \code field_name != NULL \endcode
  83030. * \retval int
  83031. * The offset in the comment array of the first comment whose field
  83032. * name matches \a field_name, or \c -1 if no match was found.
  83033. */
  83034. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  83035. /** Remove first Vorbis comment matching the given field name.
  83036. *
  83037. * \param object A pointer to an existing VORBIS_COMMENT object.
  83038. * \param field_name The field name of comment to delete.
  83039. * \assert
  83040. * \code object != NULL \endcode
  83041. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83042. * \retval int
  83043. * \c -1 for memory allocation error, \c 0 for no matching entries,
  83044. * \c 1 for one matching entry deleted.
  83045. */
  83046. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  83047. /** Remove all Vorbis comments matching the given field name.
  83048. *
  83049. * \param object A pointer to an existing VORBIS_COMMENT object.
  83050. * \param field_name The field name of comments to delete.
  83051. * \assert
  83052. * \code object != NULL \endcode
  83053. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83054. * \retval int
  83055. * \c -1 for memory allocation error, \c 0 for no matching entries,
  83056. * else the number of matching entries deleted.
  83057. */
  83058. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  83059. /** Create a new CUESHEET track instance.
  83060. *
  83061. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  83062. *
  83063. * \retval FLAC__StreamMetadata_CueSheet_Track*
  83064. * \c NULL if there was an error allocating memory, else the new instance.
  83065. */
  83066. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  83067. /** Create a copy of an existing CUESHEET track object.
  83068. *
  83069. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  83070. * object is also copied. The caller takes ownership of the new object and
  83071. * is responsible for freeing it with
  83072. * FLAC__metadata_object_cuesheet_track_delete().
  83073. *
  83074. * \param object Pointer to object to copy.
  83075. * \assert
  83076. * \code object != NULL \endcode
  83077. * \retval FLAC__StreamMetadata_CueSheet_Track*
  83078. * \c NULL if there was an error allocating memory, else the new instance.
  83079. */
  83080. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  83081. /** Delete a CUESHEET track object
  83082. *
  83083. * \param object A pointer to an existing CUESHEET track object.
  83084. * \assert
  83085. * \code object != NULL \endcode
  83086. */
  83087. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  83088. /** Resize a track's index point array.
  83089. *
  83090. * If the size shrinks, elements will truncated; if it grows, new blank
  83091. * indices will be added to the end.
  83092. *
  83093. * \param object A pointer to an existing CUESHEET object.
  83094. * \param track_num The index of the track to modify. NOTE: this is not
  83095. * necessarily the same as the track's \a number field.
  83096. * \param new_num_indices The desired length of the array; may be \c 0.
  83097. * \assert
  83098. * \code object != NULL \endcode
  83099. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83100. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83101. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  83102. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  83103. * \retval FLAC__bool
  83104. * \c false if memory allocation error, else \c true.
  83105. */
  83106. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  83107. /** Insert an index point in a CUESHEET track at the given index.
  83108. *
  83109. * \param object A pointer to an existing CUESHEET object.
  83110. * \param track_num The index of the track to modify. NOTE: this is not
  83111. * necessarily the same as the track's \a number field.
  83112. * \param index_num The index into the track's index array at which to
  83113. * insert the index point. NOTE: this is not necessarily
  83114. * the same as the index point's \a number field. The
  83115. * indices at and after \a index_num move right one
  83116. * position. To append an index point to the end, set
  83117. * \a index_num to
  83118. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  83119. * \param index The index point to insert.
  83120. * \assert
  83121. * \code object != NULL \endcode
  83122. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83123. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83124. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  83125. * \retval FLAC__bool
  83126. * \c false if realloc() fails, else \c true.
  83127. */
  83128. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num, FLAC__StreamMetadata_CueSheet_Index index);
  83129. /** Insert a blank index point in a CUESHEET track at the given index.
  83130. *
  83131. * A blank index point is one in which all field values are zero.
  83132. *
  83133. * \param object A pointer to an existing CUESHEET object.
  83134. * \param track_num The index of the track to modify. NOTE: this is not
  83135. * necessarily the same as the track's \a number field.
  83136. * \param index_num The index into the track's index array at which to
  83137. * insert the index point. NOTE: this is not necessarily
  83138. * the same as the index point's \a number field. The
  83139. * indices at and after \a index_num move right one
  83140. * position. To append an index point to the end, set
  83141. * \a index_num to
  83142. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  83143. * \assert
  83144. * \code object != NULL \endcode
  83145. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83146. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83147. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  83148. * \retval FLAC__bool
  83149. * \c false if realloc() fails, else \c true.
  83150. */
  83151. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  83152. /** Delete an index point in a CUESHEET track at the given index.
  83153. *
  83154. * \param object A pointer to an existing CUESHEET object.
  83155. * \param track_num The index into the track array of the track to
  83156. * modify. NOTE: this is not necessarily the same
  83157. * as the track's \a number field.
  83158. * \param index_num The index into the track's index array of the index
  83159. * to delete. NOTE: this is not necessarily the same
  83160. * as the index's \a number field.
  83161. * \assert
  83162. * \code object != NULL \endcode
  83163. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83164. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83165. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  83166. * \retval FLAC__bool
  83167. * \c false if realloc() fails, else \c true.
  83168. */
  83169. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  83170. /** Resize the track array.
  83171. *
  83172. * If the size shrinks, elements will truncated; if it grows, new blank
  83173. * tracks will be added to the end.
  83174. *
  83175. * \param object A pointer to an existing CUESHEET object.
  83176. * \param new_num_tracks The desired length of the array; may be \c 0.
  83177. * \assert
  83178. * \code object != NULL \endcode
  83179. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83180. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  83181. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  83182. * \retval FLAC__bool
  83183. * \c false if memory allocation error, else \c true.
  83184. */
  83185. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  83186. /** Sets a track in a CUESHEET block.
  83187. *
  83188. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  83189. * takes ownership of the \a track pointer.
  83190. *
  83191. * \param object A pointer to an existing CUESHEET object.
  83192. * \param track_num Index into track array to set. NOTE: this is not
  83193. * necessarily the same as the track's \a number field.
  83194. * \param track The track to set the track to. You may safely pass in
  83195. * a const pointer if \a copy is \c true.
  83196. * \param copy See above.
  83197. * \assert
  83198. * \code object != NULL \endcode
  83199. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83200. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  83201. * \code (track->indices != NULL && track->num_indices > 0) ||
  83202. * (track->indices == NULL && track->num_indices == 0)
  83203. * \retval FLAC__bool
  83204. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83205. */
  83206. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  83207. /** Insert a track in a CUESHEET block at the given index.
  83208. *
  83209. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  83210. * takes ownership of the \a track pointer.
  83211. *
  83212. * \param object A pointer to an existing CUESHEET object.
  83213. * \param track_num The index at which to insert the track. NOTE: this
  83214. * is not necessarily the same as the track's \a number
  83215. * field. The tracks at and after \a track_num move right
  83216. * one position. To append a track to the end, set
  83217. * \a track_num to \c object->data.cue_sheet.num_tracks .
  83218. * \param track The track to insert. You may safely pass in a const
  83219. * pointer if \a copy is \c true.
  83220. * \param copy See above.
  83221. * \assert
  83222. * \code object != NULL \endcode
  83223. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83224. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  83225. * \retval FLAC__bool
  83226. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83227. */
  83228. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  83229. /** Insert a blank track in a CUESHEET block at the given index.
  83230. *
  83231. * A blank track is one in which all field values are zero.
  83232. *
  83233. * \param object A pointer to an existing CUESHEET object.
  83234. * \param track_num The index at which to insert the track. NOTE: this
  83235. * is not necessarily the same as the track's \a number
  83236. * field. The tracks at and after \a track_num move right
  83237. * one position. To append a track to the end, set
  83238. * \a track_num to \c object->data.cue_sheet.num_tracks .
  83239. * \assert
  83240. * \code object != NULL \endcode
  83241. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83242. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  83243. * \retval FLAC__bool
  83244. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83245. */
  83246. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  83247. /** Delete a track in a CUESHEET block at the given index.
  83248. *
  83249. * \param object A pointer to an existing CUESHEET object.
  83250. * \param track_num The index into the track array of the track to
  83251. * delete. NOTE: this is not necessarily the same
  83252. * as the track's \a number field.
  83253. * \assert
  83254. * \code object != NULL \endcode
  83255. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83256. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83257. * \retval FLAC__bool
  83258. * \c false if realloc() fails, else \c true.
  83259. */
  83260. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  83261. /** Check a cue sheet to see if it conforms to the FLAC specification.
  83262. * See the format specification for limits on the contents of the
  83263. * cue sheet.
  83264. *
  83265. * \param object A pointer to an existing CUESHEET object.
  83266. * \param check_cd_da_subset If \c true, check CUESHEET against more
  83267. * stringent requirements for a CD-DA (audio) disc.
  83268. * \param violation Address of a pointer to a string. If there is a
  83269. * violation, a pointer to a string explanation of the
  83270. * violation will be returned here. \a violation may be
  83271. * \c NULL if you don't need the returned string. Do not
  83272. * free the returned string; it will always point to static
  83273. * data.
  83274. * \assert
  83275. * \code object != NULL \endcode
  83276. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83277. * \retval FLAC__bool
  83278. * \c false if cue sheet is illegal, else \c true.
  83279. */
  83280. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  83281. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  83282. * assumes the cue sheet corresponds to a CD; the result is undefined
  83283. * if the cuesheet's is_cd bit is not set.
  83284. *
  83285. * \param object A pointer to an existing CUESHEET object.
  83286. * \assert
  83287. * \code object != NULL \endcode
  83288. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83289. * \retval FLAC__uint32
  83290. * The unsigned integer representation of the CDDB/freedb ID
  83291. */
  83292. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  83293. /** Sets the MIME type of a PICTURE block.
  83294. *
  83295. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  83296. * takes ownership of the pointer. The existing string will be freed if this
  83297. * function is successful, otherwise the original string will remain if \a copy
  83298. * is \c true and malloc() fails.
  83299. *
  83300. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  83301. *
  83302. * \param object A pointer to an existing PICTURE object.
  83303. * \param mime_type A pointer to the MIME type string. The string must be
  83304. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  83305. * is done.
  83306. * \param copy See above.
  83307. * \assert
  83308. * \code object != NULL \endcode
  83309. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  83310. * \code (mime_type != NULL) \endcode
  83311. * \retval FLAC__bool
  83312. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83313. */
  83314. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  83315. /** Sets the description of a PICTURE block.
  83316. *
  83317. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  83318. * takes ownership of the pointer. The existing string will be freed if this
  83319. * function is successful, otherwise the original string will remain if \a copy
  83320. * is \c true and malloc() fails.
  83321. *
  83322. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  83323. *
  83324. * \param object A pointer to an existing PICTURE object.
  83325. * \param description A pointer to the description string. The string must be
  83326. * valid UTF-8, NUL-terminated. No validation is done.
  83327. * \param copy See above.
  83328. * \assert
  83329. * \code object != NULL \endcode
  83330. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  83331. * \code (description != NULL) \endcode
  83332. * \retval FLAC__bool
  83333. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83334. */
  83335. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  83336. /** Sets the picture data of a PICTURE block.
  83337. *
  83338. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  83339. * takes ownership of the pointer. Also sets the \a data_length field of the
  83340. * metadata object to what is passed in as the \a length parameter. The
  83341. * existing data will be freed if this function is successful, otherwise the
  83342. * original data and data_length will remain if \a copy is \c true and
  83343. * malloc() fails.
  83344. *
  83345. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  83346. *
  83347. * \param object A pointer to an existing PICTURE object.
  83348. * \param data A pointer to the data to set.
  83349. * \param length The length of \a data in bytes.
  83350. * \param copy See above.
  83351. * \assert
  83352. * \code object != NULL \endcode
  83353. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  83354. * \code (data != NULL && length > 0) ||
  83355. * (data == NULL && length == 0 && copy == false) \endcode
  83356. * \retval FLAC__bool
  83357. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83358. */
  83359. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  83360. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  83361. * See the format specification for limits on the contents of the
  83362. * PICTURE block.
  83363. *
  83364. * \param object A pointer to existing PICTURE block to be checked.
  83365. * \param violation Address of a pointer to a string. If there is a
  83366. * violation, a pointer to a string explanation of the
  83367. * violation will be returned here. \a violation may be
  83368. * \c NULL if you don't need the returned string. Do not
  83369. * free the returned string; it will always point to static
  83370. * data.
  83371. * \assert
  83372. * \code object != NULL \endcode
  83373. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  83374. * \retval FLAC__bool
  83375. * \c false if PICTURE block is illegal, else \c true.
  83376. */
  83377. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  83378. /* \} */
  83379. #ifdef __cplusplus
  83380. }
  83381. #endif
  83382. #endif
  83383. /********* End of inlined file: metadata.h *********/
  83384. /********* Start of inlined file: stream_decoder.h *********/
  83385. #ifndef FLAC__STREAM_DECODER_H
  83386. #define FLAC__STREAM_DECODER_H
  83387. #include <stdio.h> /* for FILE */
  83388. #ifdef __cplusplus
  83389. extern "C" {
  83390. #endif
  83391. /** \file include/FLAC/stream_decoder.h
  83392. *
  83393. * \brief
  83394. * This module contains the functions which implement the stream
  83395. * decoder.
  83396. *
  83397. * See the detailed documentation in the
  83398. * \link flac_stream_decoder stream decoder \endlink module.
  83399. */
  83400. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  83401. * \ingroup flac
  83402. *
  83403. * \brief
  83404. * This module describes the decoder layers provided by libFLAC.
  83405. *
  83406. * The stream decoder can be used to decode complete streams either from
  83407. * the client via callbacks, or directly from a file, depending on how
  83408. * it is initialized. When decoding via callbacks, the client provides
  83409. * callbacks for reading FLAC data and writing decoded samples, and
  83410. * handling metadata and errors. If the client also supplies seek-related
  83411. * callback, the decoder function for sample-accurate seeking within the
  83412. * FLAC input is also available. When decoding from a file, the client
  83413. * needs only supply a filename or open \c FILE* and write/metadata/error
  83414. * callbacks; the rest of the callbacks are supplied internally. For more
  83415. * info see the \link flac_stream_decoder stream decoder \endlink module.
  83416. */
  83417. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  83418. * \ingroup flac_decoder
  83419. *
  83420. * \brief
  83421. * This module contains the functions which implement the stream
  83422. * decoder.
  83423. *
  83424. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  83425. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  83426. *
  83427. * The basic usage of this decoder is as follows:
  83428. * - The program creates an instance of a decoder using
  83429. * FLAC__stream_decoder_new().
  83430. * - The program overrides the default settings using
  83431. * FLAC__stream_decoder_set_*() functions.
  83432. * - The program initializes the instance to validate the settings and
  83433. * prepare for decoding using
  83434. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  83435. * or FLAC__stream_decoder_init_file() for native FLAC,
  83436. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  83437. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  83438. * - The program calls the FLAC__stream_decoder_process_*() functions
  83439. * to decode data, which subsequently calls the callbacks.
  83440. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  83441. * which flushes the input and output and resets the decoder to the
  83442. * uninitialized state.
  83443. * - The instance may be used again or deleted with
  83444. * FLAC__stream_decoder_delete().
  83445. *
  83446. * In more detail, the program will create a new instance by calling
  83447. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  83448. * functions to override the default decoder options, and call
  83449. * one of the FLAC__stream_decoder_init_*() functions.
  83450. *
  83451. * There are three initialization functions for native FLAC, one for
  83452. * setting up the decoder to decode FLAC data from the client via
  83453. * callbacks, and two for decoding directly from a FLAC file.
  83454. *
  83455. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  83456. * You must also supply several callbacks for handling I/O. Some (like
  83457. * seeking) are optional, depending on the capabilities of the input.
  83458. *
  83459. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  83460. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  83461. * \c FILE* or filename and fewer callbacks; the decoder will handle
  83462. * the other callbacks internally.
  83463. *
  83464. * There are three similarly-named init functions for decoding from Ogg
  83465. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  83466. * library has been built with Ogg support.
  83467. *
  83468. * Once the decoder is initialized, your program will call one of several
  83469. * functions to start the decoding process:
  83470. *
  83471. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  83472. * most one metadata block or audio frame and return, calling either the
  83473. * metadata callback or write callback, respectively, once. If the decoder
  83474. * loses sync it will return with only the error callback being called.
  83475. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  83476. * to process the stream from the current location and stop upon reaching
  83477. * the first audio frame. The client will get one metadata, write, or error
  83478. * callback per metadata block, audio frame, or sync error, respectively.
  83479. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  83480. * to process the stream from the current location until the read callback
  83481. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  83482. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  83483. * write, or error callback per metadata block, audio frame, or sync error,
  83484. * respectively.
  83485. *
  83486. * When the decoder has finished decoding (normally or through an abort),
  83487. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  83488. * ensures the decoder is in the correct state and frees memory. Then the
  83489. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  83490. * again to decode another stream.
  83491. *
  83492. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  83493. * At any point after the stream decoder has been initialized, the client can
  83494. * call this function to seek to an exact sample within the stream.
  83495. * Subsequently, the first time the write callback is called it will be
  83496. * passed a (possibly partial) block starting at that sample.
  83497. *
  83498. * If the client cannot seek via the callback interface provided, but still
  83499. * has another way of seeking, it can flush the decoder using
  83500. * FLAC__stream_decoder_flush() and start feeding data from the new position
  83501. * through the read callback.
  83502. *
  83503. * The stream decoder also provides MD5 signature checking. If this is
  83504. * turned on before initialization, FLAC__stream_decoder_finish() will
  83505. * report when the decoded MD5 signature does not match the one stored
  83506. * in the STREAMINFO block. MD5 checking is automatically turned off
  83507. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  83508. * in the STREAMINFO block or when a seek is attempted.
  83509. *
  83510. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  83511. * attention. By default, the decoder only calls the metadata_callback for
  83512. * the STREAMINFO block. These functions allow you to tell the decoder
  83513. * explicitly which blocks to parse and return via the metadata_callback
  83514. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  83515. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  83516. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  83517. * which blocks to return. Remember that metadata blocks can potentially
  83518. * be big (for example, cover art) so filtering out the ones you don't
  83519. * use can reduce the memory requirements of the decoder. Also note the
  83520. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  83521. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  83522. * filtering APPLICATION blocks based on the application ID.
  83523. *
  83524. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  83525. * they still can legally be filtered from the metadata_callback.
  83526. *
  83527. * \note
  83528. * The "set" functions may only be called when the decoder is in the
  83529. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  83530. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  83531. * before FLAC__stream_decoder_init_*(). If this is the case they will
  83532. * return \c true, otherwise \c false.
  83533. *
  83534. * \note
  83535. * FLAC__stream_decoder_finish() resets all settings to the constructor
  83536. * defaults, including the callbacks.
  83537. *
  83538. * \{
  83539. */
  83540. /** State values for a FLAC__StreamDecoder
  83541. *
  83542. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  83543. */
  83544. typedef enum {
  83545. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  83546. /**< The decoder is ready to search for metadata. */
  83547. FLAC__STREAM_DECODER_READ_METADATA,
  83548. /**< The decoder is ready to or is in the process of reading metadata. */
  83549. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  83550. /**< The decoder is ready to or is in the process of searching for the
  83551. * frame sync code.
  83552. */
  83553. FLAC__STREAM_DECODER_READ_FRAME,
  83554. /**< The decoder is ready to or is in the process of reading a frame. */
  83555. FLAC__STREAM_DECODER_END_OF_STREAM,
  83556. /**< The decoder has reached the end of the stream. */
  83557. FLAC__STREAM_DECODER_OGG_ERROR,
  83558. /**< An error occurred in the underlying Ogg layer. */
  83559. FLAC__STREAM_DECODER_SEEK_ERROR,
  83560. /**< An error occurred while seeking. The decoder must be flushed
  83561. * with FLAC__stream_decoder_flush() or reset with
  83562. * FLAC__stream_decoder_reset() before decoding can continue.
  83563. */
  83564. FLAC__STREAM_DECODER_ABORTED,
  83565. /**< The decoder was aborted by the read callback. */
  83566. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  83567. /**< An error occurred allocating memory. The decoder is in an invalid
  83568. * state and can no longer be used.
  83569. */
  83570. FLAC__STREAM_DECODER_UNINITIALIZED
  83571. /**< The decoder is in the uninitialized state; one of the
  83572. * FLAC__stream_decoder_init_*() functions must be called before samples
  83573. * can be processed.
  83574. */
  83575. } FLAC__StreamDecoderState;
  83576. /** Maps a FLAC__StreamDecoderState to a C string.
  83577. *
  83578. * Using a FLAC__StreamDecoderState as the index to this array
  83579. * will give the string equivalent. The contents should not be modified.
  83580. */
  83581. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  83582. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  83583. */
  83584. typedef enum {
  83585. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  83586. /**< Initialization was successful. */
  83587. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  83588. /**< The library was not compiled with support for the given container
  83589. * format.
  83590. */
  83591. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  83592. /**< A required callback was not supplied. */
  83593. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  83594. /**< An error occurred allocating memory. */
  83595. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  83596. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  83597. * FLAC__stream_decoder_init_ogg_file(). */
  83598. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  83599. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  83600. * already initialized, usually because
  83601. * FLAC__stream_decoder_finish() was not called.
  83602. */
  83603. } FLAC__StreamDecoderInitStatus;
  83604. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  83605. *
  83606. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  83607. * will give the string equivalent. The contents should not be modified.
  83608. */
  83609. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  83610. /** Return values for the FLAC__StreamDecoder read callback.
  83611. */
  83612. typedef enum {
  83613. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  83614. /**< The read was OK and decoding can continue. */
  83615. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  83616. /**< The read was attempted while at the end of the stream. Note that
  83617. * the client must only return this value when the read callback was
  83618. * called when already at the end of the stream. Otherwise, if the read
  83619. * itself moves to the end of the stream, the client should still return
  83620. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  83621. * the next read callback it should return
  83622. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  83623. * of \c 0.
  83624. */
  83625. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  83626. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  83627. } FLAC__StreamDecoderReadStatus;
  83628. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  83629. *
  83630. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  83631. * will give the string equivalent. The contents should not be modified.
  83632. */
  83633. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  83634. /** Return values for the FLAC__StreamDecoder seek callback.
  83635. */
  83636. typedef enum {
  83637. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  83638. /**< The seek was OK and decoding can continue. */
  83639. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  83640. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  83641. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  83642. /**< Client does not support seeking. */
  83643. } FLAC__StreamDecoderSeekStatus;
  83644. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  83645. *
  83646. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  83647. * will give the string equivalent. The contents should not be modified.
  83648. */
  83649. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  83650. /** Return values for the FLAC__StreamDecoder tell callback.
  83651. */
  83652. typedef enum {
  83653. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  83654. /**< The tell was OK and decoding can continue. */
  83655. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  83656. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  83657. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  83658. /**< Client does not support telling the position. */
  83659. } FLAC__StreamDecoderTellStatus;
  83660. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  83661. *
  83662. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  83663. * will give the string equivalent. The contents should not be modified.
  83664. */
  83665. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  83666. /** Return values for the FLAC__StreamDecoder length callback.
  83667. */
  83668. typedef enum {
  83669. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  83670. /**< The length call was OK and decoding can continue. */
  83671. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  83672. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  83673. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  83674. /**< Client does not support reporting the length. */
  83675. } FLAC__StreamDecoderLengthStatus;
  83676. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  83677. *
  83678. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  83679. * will give the string equivalent. The contents should not be modified.
  83680. */
  83681. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  83682. /** Return values for the FLAC__StreamDecoder write callback.
  83683. */
  83684. typedef enum {
  83685. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  83686. /**< The write was OK and decoding can continue. */
  83687. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  83688. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  83689. } FLAC__StreamDecoderWriteStatus;
  83690. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  83691. *
  83692. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  83693. * will give the string equivalent. The contents should not be modified.
  83694. */
  83695. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  83696. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  83697. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  83698. * all. The rest could be caused by bad sync (false synchronization on
  83699. * data that is not the start of a frame) or corrupted data. The error
  83700. * itself is the decoder's best guess at what happened assuming a correct
  83701. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  83702. * could be caused by a correct sync on the start of a frame, but some
  83703. * data in the frame header was corrupted. Or it could be the result of
  83704. * syncing on a point the stream that looked like the starting of a frame
  83705. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  83706. * could be because the decoder encountered a valid frame made by a future
  83707. * version of the encoder which it cannot parse, or because of a false
  83708. * sync making it appear as though an encountered frame was generated by
  83709. * a future encoder.
  83710. */
  83711. typedef enum {
  83712. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  83713. /**< An error in the stream caused the decoder to lose synchronization. */
  83714. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  83715. /**< The decoder encountered a corrupted frame header. */
  83716. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  83717. /**< The frame's data did not match the CRC in the footer. */
  83718. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  83719. /**< The decoder encountered reserved fields in use in the stream. */
  83720. } FLAC__StreamDecoderErrorStatus;
  83721. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  83722. *
  83723. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  83724. * will give the string equivalent. The contents should not be modified.
  83725. */
  83726. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  83727. /***********************************************************************
  83728. *
  83729. * class FLAC__StreamDecoder
  83730. *
  83731. ***********************************************************************/
  83732. struct FLAC__StreamDecoderProtected;
  83733. struct FLAC__StreamDecoderPrivate;
  83734. /** The opaque structure definition for the stream decoder type.
  83735. * See the \link flac_stream_decoder stream decoder module \endlink
  83736. * for a detailed description.
  83737. */
  83738. typedef struct {
  83739. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  83740. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  83741. } FLAC__StreamDecoder;
  83742. /** Signature for the read callback.
  83743. *
  83744. * A function pointer matching this signature must be passed to
  83745. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83746. * called when the decoder needs more input data. The address of the
  83747. * buffer to be filled is supplied, along with the number of bytes the
  83748. * buffer can hold. The callback may choose to supply less data and
  83749. * modify the byte count but must be careful not to overflow the buffer.
  83750. * The callback then returns a status code chosen from
  83751. * FLAC__StreamDecoderReadStatus.
  83752. *
  83753. * Here is an example of a read callback for stdio streams:
  83754. * \code
  83755. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  83756. * {
  83757. * FILE *file = ((MyClientData*)client_data)->file;
  83758. * if(*bytes > 0) {
  83759. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  83760. * if(ferror(file))
  83761. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  83762. * else if(*bytes == 0)
  83763. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  83764. * else
  83765. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  83766. * }
  83767. * else
  83768. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  83769. * }
  83770. * \endcode
  83771. *
  83772. * \note In general, FLAC__StreamDecoder functions which change the
  83773. * state should not be called on the \a decoder while in the callback.
  83774. *
  83775. * \param decoder The decoder instance calling the callback.
  83776. * \param buffer A pointer to a location for the callee to store
  83777. * data to be decoded.
  83778. * \param bytes A pointer to the size of the buffer. On entry
  83779. * to the callback, it contains the maximum number
  83780. * of bytes that may be stored in \a buffer. The
  83781. * callee must set it to the actual number of bytes
  83782. * stored (0 in case of error or end-of-stream) before
  83783. * returning.
  83784. * \param client_data The callee's client data set through
  83785. * FLAC__stream_decoder_init_*().
  83786. * \retval FLAC__StreamDecoderReadStatus
  83787. * The callee's return status. Note that the callback should return
  83788. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  83789. * zero bytes were read and there is no more data to be read.
  83790. */
  83791. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  83792. /** Signature for the seek callback.
  83793. *
  83794. * A function pointer matching this signature may be passed to
  83795. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83796. * called when the decoder needs to seek the input stream. The decoder
  83797. * will pass the absolute byte offset to seek to, 0 meaning the
  83798. * beginning of the stream.
  83799. *
  83800. * Here is an example of a seek callback for stdio streams:
  83801. * \code
  83802. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  83803. * {
  83804. * FILE *file = ((MyClientData*)client_data)->file;
  83805. * if(file == stdin)
  83806. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  83807. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  83808. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  83809. * else
  83810. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  83811. * }
  83812. * \endcode
  83813. *
  83814. * \note In general, FLAC__StreamDecoder functions which change the
  83815. * state should not be called on the \a decoder while in the callback.
  83816. *
  83817. * \param decoder The decoder instance calling the callback.
  83818. * \param absolute_byte_offset The offset from the beginning of the stream
  83819. * to seek to.
  83820. * \param client_data The callee's client data set through
  83821. * FLAC__stream_decoder_init_*().
  83822. * \retval FLAC__StreamDecoderSeekStatus
  83823. * The callee's return status.
  83824. */
  83825. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  83826. /** Signature for the tell callback.
  83827. *
  83828. * A function pointer matching this signature may be passed to
  83829. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83830. * called when the decoder wants to know the current position of the
  83831. * stream. The callback should return the byte offset from the
  83832. * beginning of the stream.
  83833. *
  83834. * Here is an example of a tell callback for stdio streams:
  83835. * \code
  83836. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  83837. * {
  83838. * FILE *file = ((MyClientData*)client_data)->file;
  83839. * off_t pos;
  83840. * if(file == stdin)
  83841. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  83842. * else if((pos = ftello(file)) < 0)
  83843. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  83844. * else {
  83845. * *absolute_byte_offset = (FLAC__uint64)pos;
  83846. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  83847. * }
  83848. * }
  83849. * \endcode
  83850. *
  83851. * \note In general, FLAC__StreamDecoder functions which change the
  83852. * state should not be called on the \a decoder while in the callback.
  83853. *
  83854. * \param decoder The decoder instance calling the callback.
  83855. * \param absolute_byte_offset A pointer to storage for the current offset
  83856. * from the beginning of the stream.
  83857. * \param client_data The callee's client data set through
  83858. * FLAC__stream_decoder_init_*().
  83859. * \retval FLAC__StreamDecoderTellStatus
  83860. * The callee's return status.
  83861. */
  83862. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  83863. /** Signature for the length callback.
  83864. *
  83865. * A function pointer matching this signature may be passed to
  83866. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83867. * called when the decoder wants to know the total length of the stream
  83868. * in bytes.
  83869. *
  83870. * Here is an example of a length callback for stdio streams:
  83871. * \code
  83872. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  83873. * {
  83874. * FILE *file = ((MyClientData*)client_data)->file;
  83875. * struct stat filestats;
  83876. *
  83877. * if(file == stdin)
  83878. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  83879. * else if(fstat(fileno(file), &filestats) != 0)
  83880. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  83881. * else {
  83882. * *stream_length = (FLAC__uint64)filestats.st_size;
  83883. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  83884. * }
  83885. * }
  83886. * \endcode
  83887. *
  83888. * \note In general, FLAC__StreamDecoder functions which change the
  83889. * state should not be called on the \a decoder while in the callback.
  83890. *
  83891. * \param decoder The decoder instance calling the callback.
  83892. * \param stream_length A pointer to storage for the length of the stream
  83893. * in bytes.
  83894. * \param client_data The callee's client data set through
  83895. * FLAC__stream_decoder_init_*().
  83896. * \retval FLAC__StreamDecoderLengthStatus
  83897. * The callee's return status.
  83898. */
  83899. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  83900. /** Signature for the EOF callback.
  83901. *
  83902. * A function pointer matching this signature may be passed to
  83903. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83904. * called when the decoder needs to know if the end of the stream has
  83905. * been reached.
  83906. *
  83907. * Here is an example of a EOF callback for stdio streams:
  83908. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  83909. * \code
  83910. * {
  83911. * FILE *file = ((MyClientData*)client_data)->file;
  83912. * return feof(file)? true : false;
  83913. * }
  83914. * \endcode
  83915. *
  83916. * \note In general, FLAC__StreamDecoder functions which change the
  83917. * state should not be called on the \a decoder while in the callback.
  83918. *
  83919. * \param decoder The decoder instance calling the callback.
  83920. * \param client_data The callee's client data set through
  83921. * FLAC__stream_decoder_init_*().
  83922. * \retval FLAC__bool
  83923. * \c true if the currently at the end of the stream, else \c false.
  83924. */
  83925. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  83926. /** Signature for the write callback.
  83927. *
  83928. * A function pointer matching this signature must be passed to one of
  83929. * the FLAC__stream_decoder_init_*() functions.
  83930. * The supplied function will be called when the decoder has decoded a
  83931. * single audio frame. The decoder will pass the frame metadata as well
  83932. * as an array of pointers (one for each channel) pointing to the
  83933. * decoded audio.
  83934. *
  83935. * \note In general, FLAC__StreamDecoder functions which change the
  83936. * state should not be called on the \a decoder while in the callback.
  83937. *
  83938. * \param decoder The decoder instance calling the callback.
  83939. * \param frame The description of the decoded frame. See
  83940. * FLAC__Frame.
  83941. * \param buffer An array of pointers to decoded channels of data.
  83942. * Each pointer will point to an array of signed
  83943. * samples of length \a frame->header.blocksize.
  83944. * Channels will be ordered according to the FLAC
  83945. * specification; see the documentation for the
  83946. * <A HREF="../format.html#frame_header">frame header</A>.
  83947. * \param client_data The callee's client data set through
  83948. * FLAC__stream_decoder_init_*().
  83949. * \retval FLAC__StreamDecoderWriteStatus
  83950. * The callee's return status.
  83951. */
  83952. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  83953. /** Signature for the metadata callback.
  83954. *
  83955. * A function pointer matching this signature must be passed to one of
  83956. * the FLAC__stream_decoder_init_*() functions.
  83957. * The supplied function will be called when the decoder has decoded a
  83958. * metadata block. In a valid FLAC file there will always be one
  83959. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  83960. * These will be supplied by the decoder in the same order as they
  83961. * appear in the stream and always before the first audio frame (i.e.
  83962. * write callback). The metadata block that is passed in must not be
  83963. * modified, and it doesn't live beyond the callback, so you should make
  83964. * a copy of it with FLAC__metadata_object_clone() if you will need it
  83965. * elsewhere. Since metadata blocks can potentially be large, by
  83966. * default the decoder only calls the metadata callback for the
  83967. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  83968. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  83969. *
  83970. * \note In general, FLAC__StreamDecoder functions which change the
  83971. * state should not be called on the \a decoder while in the callback.
  83972. *
  83973. * \param decoder The decoder instance calling the callback.
  83974. * \param metadata The decoded metadata block.
  83975. * \param client_data The callee's client data set through
  83976. * FLAC__stream_decoder_init_*().
  83977. */
  83978. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  83979. /** Signature for the error callback.
  83980. *
  83981. * A function pointer matching this signature must be passed to one of
  83982. * the FLAC__stream_decoder_init_*() functions.
  83983. * The supplied function will be called whenever an error occurs during
  83984. * decoding.
  83985. *
  83986. * \note In general, FLAC__StreamDecoder functions which change the
  83987. * state should not be called on the \a decoder while in the callback.
  83988. *
  83989. * \param decoder The decoder instance calling the callback.
  83990. * \param status The error encountered by the decoder.
  83991. * \param client_data The callee's client data set through
  83992. * FLAC__stream_decoder_init_*().
  83993. */
  83994. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  83995. /***********************************************************************
  83996. *
  83997. * Class constructor/destructor
  83998. *
  83999. ***********************************************************************/
  84000. /** Create a new stream decoder instance. The instance is created with
  84001. * default settings; see the individual FLAC__stream_decoder_set_*()
  84002. * functions for each setting's default.
  84003. *
  84004. * \retval FLAC__StreamDecoder*
  84005. * \c NULL if there was an error allocating memory, else the new instance.
  84006. */
  84007. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  84008. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  84009. *
  84010. * \param decoder A pointer to an existing decoder.
  84011. * \assert
  84012. * \code decoder != NULL \endcode
  84013. */
  84014. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  84015. /***********************************************************************
  84016. *
  84017. * Public class method prototypes
  84018. *
  84019. ***********************************************************************/
  84020. /** Set the serial number for the FLAC stream within the Ogg container.
  84021. * The default behavior is to use the serial number of the first Ogg
  84022. * page. Setting a serial number here will explicitly specify which
  84023. * stream is to be decoded.
  84024. *
  84025. * \note
  84026. * This does not need to be set for native FLAC decoding.
  84027. *
  84028. * \default \c use serial number of first page
  84029. * \param decoder A decoder instance to set.
  84030. * \param serial_number See above.
  84031. * \assert
  84032. * \code decoder != NULL \endcode
  84033. * \retval FLAC__bool
  84034. * \c false if the decoder is already initialized, else \c true.
  84035. */
  84036. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  84037. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  84038. * compute the MD5 signature of the unencoded audio data while decoding
  84039. * and compare it to the signature from the STREAMINFO block, if it
  84040. * exists, during FLAC__stream_decoder_finish().
  84041. *
  84042. * MD5 signature checking will be turned off (until the next
  84043. * FLAC__stream_decoder_reset()) if there is no signature in the
  84044. * STREAMINFO block or when a seek is attempted.
  84045. *
  84046. * Clients that do not use the MD5 check should leave this off to speed
  84047. * up decoding.
  84048. *
  84049. * \default \c false
  84050. * \param decoder A decoder instance to set.
  84051. * \param value Flag value (see above).
  84052. * \assert
  84053. * \code decoder != NULL \endcode
  84054. * \retval FLAC__bool
  84055. * \c false if the decoder is already initialized, else \c true.
  84056. */
  84057. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  84058. /** Direct the decoder to pass on all metadata blocks of type \a type.
  84059. *
  84060. * \default By default, only the \c STREAMINFO block is returned via the
  84061. * metadata callback.
  84062. * \param decoder A decoder instance to set.
  84063. * \param type See above.
  84064. * \assert
  84065. * \code decoder != NULL \endcode
  84066. * \a type is valid
  84067. * \retval FLAC__bool
  84068. * \c false if the decoder is already initialized, else \c true.
  84069. */
  84070. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  84071. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  84072. * given \a id.
  84073. *
  84074. * \default By default, only the \c STREAMINFO block is returned via the
  84075. * metadata callback.
  84076. * \param decoder A decoder instance to set.
  84077. * \param id See above.
  84078. * \assert
  84079. * \code decoder != NULL \endcode
  84080. * \code id != NULL \endcode
  84081. * \retval FLAC__bool
  84082. * \c false if the decoder is already initialized, else \c true.
  84083. */
  84084. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  84085. /** Direct the decoder to pass on all metadata blocks of any type.
  84086. *
  84087. * \default By default, only the \c STREAMINFO block is returned via the
  84088. * metadata callback.
  84089. * \param decoder A decoder instance to set.
  84090. * \assert
  84091. * \code decoder != NULL \endcode
  84092. * \retval FLAC__bool
  84093. * \c false if the decoder is already initialized, else \c true.
  84094. */
  84095. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  84096. /** Direct the decoder to filter out all metadata blocks of type \a type.
  84097. *
  84098. * \default By default, only the \c STREAMINFO block is returned via the
  84099. * metadata callback.
  84100. * \param decoder A decoder instance to set.
  84101. * \param type See above.
  84102. * \assert
  84103. * \code decoder != NULL \endcode
  84104. * \a type is valid
  84105. * \retval FLAC__bool
  84106. * \c false if the decoder is already initialized, else \c true.
  84107. */
  84108. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  84109. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  84110. * the given \a id.
  84111. *
  84112. * \default By default, only the \c STREAMINFO block is returned via the
  84113. * metadata callback.
  84114. * \param decoder A decoder instance to set.
  84115. * \param id See above.
  84116. * \assert
  84117. * \code decoder != NULL \endcode
  84118. * \code id != NULL \endcode
  84119. * \retval FLAC__bool
  84120. * \c false if the decoder is already initialized, else \c true.
  84121. */
  84122. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  84123. /** Direct the decoder to filter out all metadata blocks of any type.
  84124. *
  84125. * \default By default, only the \c STREAMINFO block is returned via the
  84126. * metadata callback.
  84127. * \param decoder A decoder instance to set.
  84128. * \assert
  84129. * \code decoder != NULL \endcode
  84130. * \retval FLAC__bool
  84131. * \c false if the decoder is already initialized, else \c true.
  84132. */
  84133. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  84134. /** Get the current decoder state.
  84135. *
  84136. * \param decoder A decoder instance to query.
  84137. * \assert
  84138. * \code decoder != NULL \endcode
  84139. * \retval FLAC__StreamDecoderState
  84140. * The current decoder state.
  84141. */
  84142. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  84143. /** Get the current decoder state as a C string.
  84144. *
  84145. * \param decoder A decoder instance to query.
  84146. * \assert
  84147. * \code decoder != NULL \endcode
  84148. * \retval const char *
  84149. * The decoder state as a C string. Do not modify the contents.
  84150. */
  84151. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  84152. /** Get the "MD5 signature checking" flag.
  84153. * This is the value of the setting, not whether or not the decoder is
  84154. * currently checking the MD5 (remember, it can be turned off automatically
  84155. * by a seek). When the decoder is reset the flag will be restored to the
  84156. * value returned by this function.
  84157. *
  84158. * \param decoder A decoder instance to query.
  84159. * \assert
  84160. * \code decoder != NULL \endcode
  84161. * \retval FLAC__bool
  84162. * See above.
  84163. */
  84164. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  84165. /** Get the total number of samples in the stream being decoded.
  84166. * Will only be valid after decoding has started and will contain the
  84167. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  84168. *
  84169. * \param decoder A decoder instance to query.
  84170. * \assert
  84171. * \code decoder != NULL \endcode
  84172. * \retval unsigned
  84173. * See above.
  84174. */
  84175. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  84176. /** Get the current number of channels in the stream being decoded.
  84177. * Will only be valid after decoding has started and will contain the
  84178. * value from the most recently decoded frame header.
  84179. *
  84180. * \param decoder A decoder instance to query.
  84181. * \assert
  84182. * \code decoder != NULL \endcode
  84183. * \retval unsigned
  84184. * See above.
  84185. */
  84186. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  84187. /** Get the current channel assignment in the stream being decoded.
  84188. * Will only be valid after decoding has started and will contain the
  84189. * value from the most recently decoded frame header.
  84190. *
  84191. * \param decoder A decoder instance to query.
  84192. * \assert
  84193. * \code decoder != NULL \endcode
  84194. * \retval FLAC__ChannelAssignment
  84195. * See above.
  84196. */
  84197. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  84198. /** Get the current sample resolution in the stream being decoded.
  84199. * Will only be valid after decoding has started and will contain the
  84200. * value from the most recently decoded frame header.
  84201. *
  84202. * \param decoder A decoder instance to query.
  84203. * \assert
  84204. * \code decoder != NULL \endcode
  84205. * \retval unsigned
  84206. * See above.
  84207. */
  84208. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  84209. /** Get the current sample rate in Hz of the stream being decoded.
  84210. * Will only be valid after decoding has started and will contain the
  84211. * value from the most recently decoded frame header.
  84212. *
  84213. * \param decoder A decoder instance to query.
  84214. * \assert
  84215. * \code decoder != NULL \endcode
  84216. * \retval unsigned
  84217. * See above.
  84218. */
  84219. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  84220. /** Get the current blocksize of the stream being decoded.
  84221. * Will only be valid after decoding has started and will contain the
  84222. * value from the most recently decoded frame header.
  84223. *
  84224. * \param decoder A decoder instance to query.
  84225. * \assert
  84226. * \code decoder != NULL \endcode
  84227. * \retval unsigned
  84228. * See above.
  84229. */
  84230. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  84231. /** Returns the decoder's current read position within the stream.
  84232. * The position is the byte offset from the start of the stream.
  84233. * Bytes before this position have been fully decoded. Note that
  84234. * there may still be undecoded bytes in the decoder's read FIFO.
  84235. * The returned position is correct even after a seek.
  84236. *
  84237. * \warning This function currently only works for native FLAC,
  84238. * not Ogg FLAC streams.
  84239. *
  84240. * \param decoder A decoder instance to query.
  84241. * \param position Address at which to return the desired position.
  84242. * \assert
  84243. * \code decoder != NULL \endcode
  84244. * \code position != NULL \endcode
  84245. * \retval FLAC__bool
  84246. * \c true if successful, \c false if the stream is not native FLAC,
  84247. * or there was an error from the 'tell' callback or it returned
  84248. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  84249. */
  84250. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  84251. /** Initialize the decoder instance to decode native FLAC streams.
  84252. *
  84253. * This flavor of initialization sets up the decoder to decode from a
  84254. * native FLAC stream. I/O is performed via callbacks to the client.
  84255. * For decoding from a plain file via filename or open FILE*,
  84256. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  84257. * provide a simpler interface.
  84258. *
  84259. * This function should be called after FLAC__stream_decoder_new() and
  84260. * FLAC__stream_decoder_set_*() but before any of the
  84261. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84262. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84263. * if initialization succeeded.
  84264. *
  84265. * \param decoder An uninitialized decoder instance.
  84266. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  84267. * pointer must not be \c NULL.
  84268. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  84269. * pointer may be \c NULL if seeking is not
  84270. * supported. If \a seek_callback is not \c NULL then a
  84271. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  84272. * Alternatively, a dummy seek callback that just
  84273. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  84274. * may also be supplied, all though this is slightly
  84275. * less efficient for the decoder.
  84276. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  84277. * pointer may be \c NULL if not supported by the client. If
  84278. * \a seek_callback is not \c NULL then a
  84279. * \a tell_callback must also be supplied.
  84280. * Alternatively, a dummy tell callback that just
  84281. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  84282. * may also be supplied, all though this is slightly
  84283. * less efficient for the decoder.
  84284. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  84285. * pointer may be \c NULL if not supported by the client. If
  84286. * \a seek_callback is not \c NULL then a
  84287. * \a length_callback must also be supplied.
  84288. * Alternatively, a dummy length callback that just
  84289. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  84290. * may also be supplied, all though this is slightly
  84291. * less efficient for the decoder.
  84292. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  84293. * pointer may be \c NULL if not supported by the client. If
  84294. * \a seek_callback is not \c NULL then a
  84295. * \a eof_callback must also be supplied.
  84296. * Alternatively, a dummy length callback that just
  84297. * returns \c false
  84298. * may also be supplied, all though this is slightly
  84299. * less efficient for the decoder.
  84300. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84301. * pointer must not be \c NULL.
  84302. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84303. * pointer may be \c NULL if the callback is not
  84304. * desired.
  84305. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84306. * pointer must not be \c NULL.
  84307. * \param client_data This value will be supplied to callbacks in their
  84308. * \a client_data argument.
  84309. * \assert
  84310. * \code decoder != NULL \endcode
  84311. * \retval FLAC__StreamDecoderInitStatus
  84312. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84313. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84314. */
  84315. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  84316. FLAC__StreamDecoder *decoder,
  84317. FLAC__StreamDecoderReadCallback read_callback,
  84318. FLAC__StreamDecoderSeekCallback seek_callback,
  84319. FLAC__StreamDecoderTellCallback tell_callback,
  84320. FLAC__StreamDecoderLengthCallback length_callback,
  84321. FLAC__StreamDecoderEofCallback eof_callback,
  84322. FLAC__StreamDecoderWriteCallback write_callback,
  84323. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84324. FLAC__StreamDecoderErrorCallback error_callback,
  84325. void *client_data
  84326. );
  84327. /** Initialize the decoder instance to decode Ogg FLAC streams.
  84328. *
  84329. * This flavor of initialization sets up the decoder to decode from a
  84330. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  84331. * client. For decoding from a plain file via filename or open FILE*,
  84332. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  84333. * provide a simpler interface.
  84334. *
  84335. * This function should be called after FLAC__stream_decoder_new() and
  84336. * FLAC__stream_decoder_set_*() but before any of the
  84337. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84338. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84339. * if initialization succeeded.
  84340. *
  84341. * \note Support for Ogg FLAC in the library is optional. If this
  84342. * library has been built without support for Ogg FLAC, this function
  84343. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  84344. *
  84345. * \param decoder An uninitialized decoder instance.
  84346. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  84347. * pointer must not be \c NULL.
  84348. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  84349. * pointer may be \c NULL if seeking is not
  84350. * supported. If \a seek_callback is not \c NULL then a
  84351. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  84352. * Alternatively, a dummy seek callback that just
  84353. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  84354. * may also be supplied, all though this is slightly
  84355. * less efficient for the decoder.
  84356. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  84357. * pointer may be \c NULL if not supported by the client. If
  84358. * \a seek_callback is not \c NULL then a
  84359. * \a tell_callback must also be supplied.
  84360. * Alternatively, a dummy tell callback that just
  84361. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  84362. * may also be supplied, all though this is slightly
  84363. * less efficient for the decoder.
  84364. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  84365. * pointer may be \c NULL if not supported by the client. If
  84366. * \a seek_callback is not \c NULL then a
  84367. * \a length_callback must also be supplied.
  84368. * Alternatively, a dummy length callback that just
  84369. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  84370. * may also be supplied, all though this is slightly
  84371. * less efficient for the decoder.
  84372. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  84373. * pointer may be \c NULL if not supported by the client. If
  84374. * \a seek_callback is not \c NULL then a
  84375. * \a eof_callback must also be supplied.
  84376. * Alternatively, a dummy length callback that just
  84377. * returns \c false
  84378. * may also be supplied, all though this is slightly
  84379. * less efficient for the decoder.
  84380. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84381. * pointer must not be \c NULL.
  84382. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84383. * pointer may be \c NULL if the callback is not
  84384. * desired.
  84385. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84386. * pointer must not be \c NULL.
  84387. * \param client_data This value will be supplied to callbacks in their
  84388. * \a client_data argument.
  84389. * \assert
  84390. * \code decoder != NULL \endcode
  84391. * \retval FLAC__StreamDecoderInitStatus
  84392. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84393. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84394. */
  84395. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  84396. FLAC__StreamDecoder *decoder,
  84397. FLAC__StreamDecoderReadCallback read_callback,
  84398. FLAC__StreamDecoderSeekCallback seek_callback,
  84399. FLAC__StreamDecoderTellCallback tell_callback,
  84400. FLAC__StreamDecoderLengthCallback length_callback,
  84401. FLAC__StreamDecoderEofCallback eof_callback,
  84402. FLAC__StreamDecoderWriteCallback write_callback,
  84403. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84404. FLAC__StreamDecoderErrorCallback error_callback,
  84405. void *client_data
  84406. );
  84407. /** Initialize the decoder instance to decode native FLAC files.
  84408. *
  84409. * This flavor of initialization sets up the decoder to decode from a
  84410. * plain native FLAC file. For non-stdio streams, you must use
  84411. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  84412. *
  84413. * This function should be called after FLAC__stream_decoder_new() and
  84414. * FLAC__stream_decoder_set_*() but before any of the
  84415. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84416. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84417. * if initialization succeeded.
  84418. *
  84419. * \param decoder An uninitialized decoder instance.
  84420. * \param file An open FLAC file. The file should have been
  84421. * opened with mode \c "rb" and rewound. The file
  84422. * becomes owned by the decoder and should not be
  84423. * manipulated by the client while decoding.
  84424. * Unless \a file is \c stdin, it will be closed
  84425. * when FLAC__stream_decoder_finish() is called.
  84426. * Note however that seeking will not work when
  84427. * decoding from \c stdout since it is not seekable.
  84428. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84429. * pointer must not be \c NULL.
  84430. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84431. * pointer may be \c NULL if the callback is not
  84432. * desired.
  84433. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84434. * pointer must not be \c NULL.
  84435. * \param client_data This value will be supplied to callbacks in their
  84436. * \a client_data argument.
  84437. * \assert
  84438. * \code decoder != NULL \endcode
  84439. * \code file != NULL \endcode
  84440. * \retval FLAC__StreamDecoderInitStatus
  84441. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84442. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84443. */
  84444. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  84445. FLAC__StreamDecoder *decoder,
  84446. FILE *file,
  84447. FLAC__StreamDecoderWriteCallback write_callback,
  84448. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84449. FLAC__StreamDecoderErrorCallback error_callback,
  84450. void *client_data
  84451. );
  84452. /** Initialize the decoder instance to decode Ogg FLAC files.
  84453. *
  84454. * This flavor of initialization sets up the decoder to decode from a
  84455. * plain Ogg FLAC file. For non-stdio streams, you must use
  84456. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  84457. *
  84458. * This function should be called after FLAC__stream_decoder_new() and
  84459. * FLAC__stream_decoder_set_*() but before any of the
  84460. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84461. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84462. * if initialization succeeded.
  84463. *
  84464. * \note Support for Ogg FLAC in the library is optional. If this
  84465. * library has been built without support for Ogg FLAC, this function
  84466. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  84467. *
  84468. * \param decoder An uninitialized decoder instance.
  84469. * \param file An open FLAC file. The file should have been
  84470. * opened with mode \c "rb" and rewound. The file
  84471. * becomes owned by the decoder and should not be
  84472. * manipulated by the client while decoding.
  84473. * Unless \a file is \c stdin, it will be closed
  84474. * when FLAC__stream_decoder_finish() is called.
  84475. * Note however that seeking will not work when
  84476. * decoding from \c stdout since it is not seekable.
  84477. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84478. * pointer must not be \c NULL.
  84479. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84480. * pointer may be \c NULL if the callback is not
  84481. * desired.
  84482. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84483. * pointer must not be \c NULL.
  84484. * \param client_data This value will be supplied to callbacks in their
  84485. * \a client_data argument.
  84486. * \assert
  84487. * \code decoder != NULL \endcode
  84488. * \code file != NULL \endcode
  84489. * \retval FLAC__StreamDecoderInitStatus
  84490. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84491. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84492. */
  84493. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  84494. FLAC__StreamDecoder *decoder,
  84495. FILE *file,
  84496. FLAC__StreamDecoderWriteCallback write_callback,
  84497. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84498. FLAC__StreamDecoderErrorCallback error_callback,
  84499. void *client_data
  84500. );
  84501. /** Initialize the decoder instance to decode native FLAC files.
  84502. *
  84503. * This flavor of initialization sets up the decoder to decode from a plain
  84504. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  84505. * example, with Unicode filenames on Windows), you must use
  84506. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  84507. * and provide callbacks for the I/O.
  84508. *
  84509. * This function should be called after FLAC__stream_decoder_new() and
  84510. * FLAC__stream_decoder_set_*() but before any of the
  84511. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84512. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84513. * if initialization succeeded.
  84514. *
  84515. * \param decoder An uninitialized decoder instance.
  84516. * \param filename The name of the file to decode from. The file will
  84517. * be opened with fopen(). Use \c NULL to decode from
  84518. * \c stdin. Note that \c stdin is not seekable.
  84519. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84520. * pointer must not be \c NULL.
  84521. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84522. * pointer may be \c NULL if the callback is not
  84523. * desired.
  84524. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84525. * pointer must not be \c NULL.
  84526. * \param client_data This value will be supplied to callbacks in their
  84527. * \a client_data argument.
  84528. * \assert
  84529. * \code decoder != NULL \endcode
  84530. * \retval FLAC__StreamDecoderInitStatus
  84531. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84532. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84533. */
  84534. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  84535. FLAC__StreamDecoder *decoder,
  84536. const char *filename,
  84537. FLAC__StreamDecoderWriteCallback write_callback,
  84538. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84539. FLAC__StreamDecoderErrorCallback error_callback,
  84540. void *client_data
  84541. );
  84542. /** Initialize the decoder instance to decode Ogg FLAC files.
  84543. *
  84544. * This flavor of initialization sets up the decoder to decode from a plain
  84545. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  84546. * example, with Unicode filenames on Windows), you must use
  84547. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  84548. * and provide callbacks for the I/O.
  84549. *
  84550. * This function should be called after FLAC__stream_decoder_new() and
  84551. * FLAC__stream_decoder_set_*() but before any of the
  84552. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84553. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84554. * if initialization succeeded.
  84555. *
  84556. * \note Support for Ogg FLAC in the library is optional. If this
  84557. * library has been built without support for Ogg FLAC, this function
  84558. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  84559. *
  84560. * \param decoder An uninitialized decoder instance.
  84561. * \param filename The name of the file to decode from. The file will
  84562. * be opened with fopen(). Use \c NULL to decode from
  84563. * \c stdin. Note that \c stdin is not seekable.
  84564. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84565. * pointer must not be \c NULL.
  84566. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84567. * pointer may be \c NULL if the callback is not
  84568. * desired.
  84569. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84570. * pointer must not be \c NULL.
  84571. * \param client_data This value will be supplied to callbacks in their
  84572. * \a client_data argument.
  84573. * \assert
  84574. * \code decoder != NULL \endcode
  84575. * \retval FLAC__StreamDecoderInitStatus
  84576. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84577. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84578. */
  84579. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  84580. FLAC__StreamDecoder *decoder,
  84581. const char *filename,
  84582. FLAC__StreamDecoderWriteCallback write_callback,
  84583. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84584. FLAC__StreamDecoderErrorCallback error_callback,
  84585. void *client_data
  84586. );
  84587. /** Finish the decoding process.
  84588. * Flushes the decoding buffer, releases resources, resets the decoder
  84589. * settings to their defaults, and returns the decoder state to
  84590. * FLAC__STREAM_DECODER_UNINITIALIZED.
  84591. *
  84592. * In the event of a prematurely-terminated decode, it is not strictly
  84593. * necessary to call this immediately before FLAC__stream_decoder_delete()
  84594. * but it is good practice to match every FLAC__stream_decoder_init_*()
  84595. * with a FLAC__stream_decoder_finish().
  84596. *
  84597. * \param decoder An uninitialized decoder instance.
  84598. * \assert
  84599. * \code decoder != NULL \endcode
  84600. * \retval FLAC__bool
  84601. * \c false if MD5 checking is on AND a STREAMINFO block was available
  84602. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  84603. * signature does not match the one computed by the decoder; else
  84604. * \c true.
  84605. */
  84606. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  84607. /** Flush the stream input.
  84608. * The decoder's input buffer will be cleared and the state set to
  84609. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  84610. * off MD5 checking.
  84611. *
  84612. * \param decoder A decoder instance.
  84613. * \assert
  84614. * \code decoder != NULL \endcode
  84615. * \retval FLAC__bool
  84616. * \c true if successful, else \c false if a memory allocation
  84617. * error occurs (in which case the state will be set to
  84618. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  84619. */
  84620. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  84621. /** Reset the decoding process.
  84622. * The decoder's input buffer will be cleared and the state set to
  84623. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  84624. * FLAC__stream_decoder_finish() except that the settings are
  84625. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  84626. * before decoding again. MD5 checking will be restored to its original
  84627. * setting.
  84628. *
  84629. * If the decoder is seekable, or was initialized with
  84630. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  84631. * the decoder will also attempt to seek to the beginning of the file.
  84632. * If this rewind fails, this function will return \c false. It follows
  84633. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  84634. * \c stdin.
  84635. *
  84636. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  84637. * and is not seekable (i.e. no seek callback was provided or the seek
  84638. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  84639. * is the duty of the client to start feeding data from the beginning of
  84640. * the stream on the next FLAC__stream_decoder_process() or
  84641. * FLAC__stream_decoder_process_interleaved() call.
  84642. *
  84643. * \param decoder A decoder instance.
  84644. * \assert
  84645. * \code decoder != NULL \endcode
  84646. * \retval FLAC__bool
  84647. * \c true if successful, else \c false if a memory allocation occurs
  84648. * (in which case the state will be set to
  84649. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  84650. * occurs (the state will be unchanged).
  84651. */
  84652. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  84653. /** Decode one metadata block or audio frame.
  84654. * This version instructs the decoder to decode a either a single metadata
  84655. * block or a single frame and stop, unless the callbacks return a fatal
  84656. * error or the read callback returns
  84657. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  84658. *
  84659. * As the decoder needs more input it will call the read callback.
  84660. * Depending on what was decoded, the metadata or write callback will be
  84661. * called with the decoded metadata block or audio frame.
  84662. *
  84663. * Unless there is a fatal read error or end of stream, this function
  84664. * will return once one whole frame is decoded. In other words, if the
  84665. * stream is not synchronized or points to a corrupt frame header, the
  84666. * decoder will continue to try and resync until it gets to a valid
  84667. * frame, then decode one frame, then return. If the decoder points to
  84668. * a frame whose frame CRC in the frame footer does not match the
  84669. * computed frame CRC, this function will issue a
  84670. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  84671. * error callback, and return, having decoded one complete, although
  84672. * corrupt, frame. (Such corrupted frames are sent as silence of the
  84673. * correct length to the write callback.)
  84674. *
  84675. * \param decoder An initialized decoder instance.
  84676. * \assert
  84677. * \code decoder != NULL \endcode
  84678. * \retval FLAC__bool
  84679. * \c false if any fatal read, write, or memory allocation error
  84680. * occurred (meaning decoding must stop), else \c true; for more
  84681. * information about the decoder, check the decoder state with
  84682. * FLAC__stream_decoder_get_state().
  84683. */
  84684. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  84685. /** Decode until the end of the metadata.
  84686. * This version instructs the decoder to decode from the current position
  84687. * and continue until all the metadata has been read, or until the
  84688. * callbacks return a fatal error or the read callback returns
  84689. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  84690. *
  84691. * As the decoder needs more input it will call the read callback.
  84692. * As each metadata block is decoded, the metadata callback will be called
  84693. * with the decoded metadata.
  84694. *
  84695. * \param decoder An initialized decoder instance.
  84696. * \assert
  84697. * \code decoder != NULL \endcode
  84698. * \retval FLAC__bool
  84699. * \c false if any fatal read, write, or memory allocation error
  84700. * occurred (meaning decoding must stop), else \c true; for more
  84701. * information about the decoder, check the decoder state with
  84702. * FLAC__stream_decoder_get_state().
  84703. */
  84704. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  84705. /** Decode until the end of the stream.
  84706. * This version instructs the decoder to decode from the current position
  84707. * and continue until the end of stream (the read callback returns
  84708. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  84709. * callbacks return a fatal error.
  84710. *
  84711. * As the decoder needs more input it will call the read callback.
  84712. * As each metadata block and frame is decoded, the metadata or write
  84713. * callback will be called with the decoded metadata or frame.
  84714. *
  84715. * \param decoder An initialized decoder instance.
  84716. * \assert
  84717. * \code decoder != NULL \endcode
  84718. * \retval FLAC__bool
  84719. * \c false if any fatal read, write, or memory allocation error
  84720. * occurred (meaning decoding must stop), else \c true; for more
  84721. * information about the decoder, check the decoder state with
  84722. * FLAC__stream_decoder_get_state().
  84723. */
  84724. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  84725. /** Skip one audio frame.
  84726. * This version instructs the decoder to 'skip' a single frame and stop,
  84727. * unless the callbacks return a fatal error or the read callback returns
  84728. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  84729. *
  84730. * The decoding flow is the same as what occurs when
  84731. * FLAC__stream_decoder_process_single() is called to process an audio
  84732. * frame, except that this function does not decode the parsed data into
  84733. * PCM or call the write callback. The integrity of the frame is still
  84734. * checked the same way as in the other process functions.
  84735. *
  84736. * This function will return once one whole frame is skipped, in the
  84737. * same way that FLAC__stream_decoder_process_single() will return once
  84738. * one whole frame is decoded.
  84739. *
  84740. * This function can be used in more quickly determining FLAC frame
  84741. * boundaries when decoding of the actual data is not needed, for
  84742. * example when an application is separating a FLAC stream into frames
  84743. * for editing or storing in a container. To do this, the application
  84744. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  84745. * to the next frame, then use
  84746. * FLAC__stream_decoder_get_decode_position() to find the new frame
  84747. * boundary.
  84748. *
  84749. * This function should only be called when the stream has advanced
  84750. * past all the metadata, otherwise it will return \c false.
  84751. *
  84752. * \param decoder An initialized decoder instance not in a metadata
  84753. * state.
  84754. * \assert
  84755. * \code decoder != NULL \endcode
  84756. * \retval FLAC__bool
  84757. * \c false if any fatal read, write, or memory allocation error
  84758. * occurred (meaning decoding must stop), or if the decoder
  84759. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  84760. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  84761. * information about the decoder, check the decoder state with
  84762. * FLAC__stream_decoder_get_state().
  84763. */
  84764. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  84765. /** Flush the input and seek to an absolute sample.
  84766. * Decoding will resume at the given sample. Note that because of
  84767. * this, the next write callback may contain a partial block. The
  84768. * client must support seeking the input or this function will fail
  84769. * and return \c false. Furthermore, if the decoder state is
  84770. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  84771. * with FLAC__stream_decoder_flush() or reset with
  84772. * FLAC__stream_decoder_reset() before decoding can continue.
  84773. *
  84774. * \param decoder A decoder instance.
  84775. * \param sample The target sample number to seek to.
  84776. * \assert
  84777. * \code decoder != NULL \endcode
  84778. * \retval FLAC__bool
  84779. * \c true if successful, else \c false.
  84780. */
  84781. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  84782. /* \} */
  84783. #ifdef __cplusplus
  84784. }
  84785. #endif
  84786. #endif
  84787. /********* End of inlined file: stream_decoder.h *********/
  84788. /********* Start of inlined file: stream_encoder.h *********/
  84789. #ifndef FLAC__STREAM_ENCODER_H
  84790. #define FLAC__STREAM_ENCODER_H
  84791. #include <stdio.h> /* for FILE */
  84792. #ifdef __cplusplus
  84793. extern "C" {
  84794. #endif
  84795. /** \file include/FLAC/stream_encoder.h
  84796. *
  84797. * \brief
  84798. * This module contains the functions which implement the stream
  84799. * encoder.
  84800. *
  84801. * See the detailed documentation in the
  84802. * \link flac_stream_encoder stream encoder \endlink module.
  84803. */
  84804. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  84805. * \ingroup flac
  84806. *
  84807. * \brief
  84808. * This module describes the encoder layers provided by libFLAC.
  84809. *
  84810. * The stream encoder can be used to encode complete streams either to the
  84811. * client via callbacks, or directly to a file, depending on how it is
  84812. * initialized. When encoding via callbacks, the client provides a write
  84813. * callback which will be called whenever FLAC data is ready to be written.
  84814. * If the client also supplies a seek callback, the encoder will also
  84815. * automatically handle the writing back of metadata discovered while
  84816. * encoding, like stream info, seek points offsets, etc. When encoding to
  84817. * a file, the client needs only supply a filename or open \c FILE* and an
  84818. * optional progress callback for periodic notification of progress; the
  84819. * write and seek callbacks are supplied internally. For more info see the
  84820. * \link flac_stream_encoder stream encoder \endlink module.
  84821. */
  84822. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  84823. * \ingroup flac_encoder
  84824. *
  84825. * \brief
  84826. * This module contains the functions which implement the stream
  84827. * encoder.
  84828. *
  84829. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  84830. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  84831. *
  84832. * The basic usage of this encoder is as follows:
  84833. * - The program creates an instance of an encoder using
  84834. * FLAC__stream_encoder_new().
  84835. * - The program overrides the default settings using
  84836. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  84837. * functions should be called:
  84838. * - FLAC__stream_encoder_set_channels()
  84839. * - FLAC__stream_encoder_set_bits_per_sample()
  84840. * - FLAC__stream_encoder_set_sample_rate()
  84841. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  84842. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  84843. * - If the application wants to control the compression level or set its own
  84844. * metadata, then the following should also be called:
  84845. * - FLAC__stream_encoder_set_compression_level()
  84846. * - FLAC__stream_encoder_set_verify()
  84847. * - FLAC__stream_encoder_set_metadata()
  84848. * - The rest of the set functions should only be called if the client needs
  84849. * exact control over how the audio is compressed; thorough understanding
  84850. * of the FLAC format is necessary to achieve good results.
  84851. * - The program initializes the instance to validate the settings and
  84852. * prepare for encoding using
  84853. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  84854. * or FLAC__stream_encoder_init_file() for native FLAC
  84855. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  84856. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  84857. * - The program calls FLAC__stream_encoder_process() or
  84858. * FLAC__stream_encoder_process_interleaved() to encode data, which
  84859. * subsequently calls the callbacks when there is encoder data ready
  84860. * to be written.
  84861. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  84862. * which causes the encoder to encode any data still in its input pipe,
  84863. * update the metadata with the final encoding statistics if output
  84864. * seeking is possible, and finally reset the encoder to the
  84865. * uninitialized state.
  84866. * - The instance may be used again or deleted with
  84867. * FLAC__stream_encoder_delete().
  84868. *
  84869. * In more detail, the stream encoder functions similarly to the
  84870. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  84871. * callbacks and more options. Typically the client will create a new
  84872. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  84873. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  84874. * calling one of the FLAC__stream_encoder_init_*() functions.
  84875. *
  84876. * Unlike the decoders, the stream encoder has many options that can
  84877. * affect the speed and compression ratio. When setting these parameters
  84878. * you should have some basic knowledge of the format (see the
  84879. * <A HREF="../documentation.html#format">user-level documentation</A>
  84880. * or the <A HREF="../format.html">formal description</A>). The
  84881. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  84882. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  84883. * functions will do this, so make sure to pay attention to the state
  84884. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  84885. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  84886. * before FLAC__stream_encoder_init_*() will take on the defaults from
  84887. * the constructor.
  84888. *
  84889. * There are three initialization functions for native FLAC, one for
  84890. * setting up the encoder to encode FLAC data to the client via
  84891. * callbacks, and two for encoding directly to a file.
  84892. *
  84893. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  84894. * You must also supply a write callback which will be called anytime
  84895. * there is raw encoded data to write. If the client can seek the output
  84896. * it is best to also supply seek and tell callbacks, as this allows the
  84897. * encoder to go back after encoding is finished to write back
  84898. * information that was collected while encoding, like seek point offsets,
  84899. * frame sizes, etc.
  84900. *
  84901. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  84902. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  84903. * filename or open \c FILE*; the encoder will handle all the callbacks
  84904. * internally. You may also supply a progress callback for periodic
  84905. * notification of the encoding progress.
  84906. *
  84907. * There are three similarly-named init functions for encoding to Ogg
  84908. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  84909. * library has been built with Ogg support.
  84910. *
  84911. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  84912. * call the write callback several times, once with the \c fLaC signature,
  84913. * and once for each encoded metadata block. Note that for Ogg FLAC
  84914. * encoding you will usually get at least twice the number of callbacks than
  84915. * with native FLAC, one for the Ogg page header and one for the page body.
  84916. *
  84917. * After initializing the instance, the client may feed audio data to the
  84918. * encoder in one of two ways:
  84919. *
  84920. * - Channel separate, through FLAC__stream_encoder_process() - The client
  84921. * will pass an array of pointers to buffers, one for each channel, to
  84922. * the encoder, each of the same length. The samples need not be
  84923. * block-aligned, but each channel should have the same number of samples.
  84924. * - Channel interleaved, through
  84925. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  84926. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  84927. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  84928. * Again, the samples need not be block-aligned but they must be
  84929. * sample-aligned, i.e. the first value should be channel0_sample0 and
  84930. * the last value channelN_sampleM.
  84931. *
  84932. * Note that for either process call, each sample in the buffers should be a
  84933. * signed integer, right-justified to the resolution set by
  84934. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  84935. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  84936. *
  84937. * When the client is finished encoding data, it calls
  84938. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  84939. * data still in its input pipe, and call the metadata callback with the
  84940. * final encoding statistics. Then the instance may be deleted with
  84941. * FLAC__stream_encoder_delete() or initialized again to encode another
  84942. * stream.
  84943. *
  84944. * For programs that write their own metadata, but that do not know the
  84945. * actual metadata until after encoding, it is advantageous to instruct
  84946. * the encoder to write a PADDING block of the correct size, so that
  84947. * instead of rewriting the whole stream after encoding, the program can
  84948. * just overwrite the PADDING block. If only the maximum size of the
  84949. * metadata is known, the program can write a slightly larger padding
  84950. * block, then split it after encoding.
  84951. *
  84952. * Make sure you understand how lengths are calculated. All FLAC metadata
  84953. * blocks have a 4 byte header which contains the type and length. This
  84954. * length does not include the 4 bytes of the header. See the format page
  84955. * for the specification of metadata blocks and their lengths.
  84956. *
  84957. * \note
  84958. * If you are writing the FLAC data to a file via callbacks, make sure it
  84959. * is open for update (e.g. mode "w+" for stdio streams). This is because
  84960. * after the first encoding pass, the encoder will try to seek back to the
  84961. * beginning of the stream, to the STREAMINFO block, to write some data
  84962. * there. (If using FLAC__stream_encoder_init*_file() or
  84963. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  84964. *
  84965. * \note
  84966. * The "set" functions may only be called when the encoder is in the
  84967. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  84968. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  84969. * before FLAC__stream_encoder_init_*(). If this is the case they will
  84970. * return \c true, otherwise \c false.
  84971. *
  84972. * \note
  84973. * FLAC__stream_encoder_finish() resets all settings to the constructor
  84974. * defaults.
  84975. *
  84976. * \{
  84977. */
  84978. /** State values for a FLAC__StreamEncoder.
  84979. *
  84980. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  84981. *
  84982. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  84983. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  84984. * must be deleted with FLAC__stream_encoder_delete().
  84985. */
  84986. typedef enum {
  84987. FLAC__STREAM_ENCODER_OK = 0,
  84988. /**< The encoder is in the normal OK state and samples can be processed. */
  84989. FLAC__STREAM_ENCODER_UNINITIALIZED,
  84990. /**< The encoder is in the uninitialized state; one of the
  84991. * FLAC__stream_encoder_init_*() functions must be called before samples
  84992. * can be processed.
  84993. */
  84994. FLAC__STREAM_ENCODER_OGG_ERROR,
  84995. /**< An error occurred in the underlying Ogg layer. */
  84996. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  84997. /**< An error occurred in the underlying verify stream decoder;
  84998. * check FLAC__stream_encoder_get_verify_decoder_state().
  84999. */
  85000. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  85001. /**< The verify decoder detected a mismatch between the original
  85002. * audio signal and the decoded audio signal.
  85003. */
  85004. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  85005. /**< One of the callbacks returned a fatal error. */
  85006. FLAC__STREAM_ENCODER_IO_ERROR,
  85007. /**< An I/O error occurred while opening/reading/writing a file.
  85008. * Check \c errno.
  85009. */
  85010. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  85011. /**< An error occurred while writing the stream; usually, the
  85012. * write_callback returned an error.
  85013. */
  85014. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  85015. /**< Memory allocation failed. */
  85016. } FLAC__StreamEncoderState;
  85017. /** Maps a FLAC__StreamEncoderState to a C string.
  85018. *
  85019. * Using a FLAC__StreamEncoderState as the index to this array
  85020. * will give the string equivalent. The contents should not be modified.
  85021. */
  85022. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  85023. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  85024. */
  85025. typedef enum {
  85026. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  85027. /**< Initialization was successful. */
  85028. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  85029. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  85030. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  85031. /**< The library was not compiled with support for the given container
  85032. * format.
  85033. */
  85034. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  85035. /**< A required callback was not supplied. */
  85036. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  85037. /**< The encoder has an invalid setting for number of channels. */
  85038. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  85039. /**< The encoder has an invalid setting for bits-per-sample.
  85040. * FLAC supports 4-32 bps but the reference encoder currently supports
  85041. * only up to 24 bps.
  85042. */
  85043. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  85044. /**< The encoder has an invalid setting for the input sample rate. */
  85045. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  85046. /**< The encoder has an invalid setting for the block size. */
  85047. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  85048. /**< The encoder has an invalid setting for the maximum LPC order. */
  85049. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  85050. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  85051. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  85052. /**< The specified block size is less than the maximum LPC order. */
  85053. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  85054. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  85055. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  85056. /**< The metadata input to the encoder is invalid, in one of the following ways:
  85057. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  85058. * - One of the metadata blocks contains an undefined type
  85059. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  85060. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  85061. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  85062. */
  85063. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  85064. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  85065. * already initialized, usually because
  85066. * FLAC__stream_encoder_finish() was not called.
  85067. */
  85068. } FLAC__StreamEncoderInitStatus;
  85069. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  85070. *
  85071. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  85072. * will give the string equivalent. The contents should not be modified.
  85073. */
  85074. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  85075. /** Return values for the FLAC__StreamEncoder read callback.
  85076. */
  85077. typedef enum {
  85078. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  85079. /**< The read was OK and decoding can continue. */
  85080. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  85081. /**< The read was attempted at the end of the stream. */
  85082. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  85083. /**< An unrecoverable error occurred. */
  85084. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  85085. /**< Client does not support reading back from the output. */
  85086. } FLAC__StreamEncoderReadStatus;
  85087. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  85088. *
  85089. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  85090. * will give the string equivalent. The contents should not be modified.
  85091. */
  85092. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  85093. /** Return values for the FLAC__StreamEncoder write callback.
  85094. */
  85095. typedef enum {
  85096. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  85097. /**< The write was OK and encoding can continue. */
  85098. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  85099. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  85100. } FLAC__StreamEncoderWriteStatus;
  85101. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  85102. *
  85103. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  85104. * will give the string equivalent. The contents should not be modified.
  85105. */
  85106. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  85107. /** Return values for the FLAC__StreamEncoder seek callback.
  85108. */
  85109. typedef enum {
  85110. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  85111. /**< The seek was OK and encoding can continue. */
  85112. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  85113. /**< An unrecoverable error occurred. */
  85114. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  85115. /**< Client does not support seeking. */
  85116. } FLAC__StreamEncoderSeekStatus;
  85117. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  85118. *
  85119. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  85120. * will give the string equivalent. The contents should not be modified.
  85121. */
  85122. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  85123. /** Return values for the FLAC__StreamEncoder tell callback.
  85124. */
  85125. typedef enum {
  85126. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  85127. /**< The tell was OK and encoding can continue. */
  85128. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  85129. /**< An unrecoverable error occurred. */
  85130. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  85131. /**< Client does not support seeking. */
  85132. } FLAC__StreamEncoderTellStatus;
  85133. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  85134. *
  85135. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  85136. * will give the string equivalent. The contents should not be modified.
  85137. */
  85138. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  85139. /***********************************************************************
  85140. *
  85141. * class FLAC__StreamEncoder
  85142. *
  85143. ***********************************************************************/
  85144. struct FLAC__StreamEncoderProtected;
  85145. struct FLAC__StreamEncoderPrivate;
  85146. /** The opaque structure definition for the stream encoder type.
  85147. * See the \link flac_stream_encoder stream encoder module \endlink
  85148. * for a detailed description.
  85149. */
  85150. typedef struct {
  85151. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  85152. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  85153. } FLAC__StreamEncoder;
  85154. /** Signature for the read callback.
  85155. *
  85156. * A function pointer matching this signature must be passed to
  85157. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  85158. * The supplied function will be called when the encoder needs to read back
  85159. * encoded data. This happens during the metadata callback, when the encoder
  85160. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  85161. * while encoding. The address of the buffer to be filled is supplied, along
  85162. * with the number of bytes the buffer can hold. The callback may choose to
  85163. * supply less data and modify the byte count but must be careful not to
  85164. * overflow the buffer. The callback then returns a status code chosen from
  85165. * FLAC__StreamEncoderReadStatus.
  85166. *
  85167. * Here is an example of a read callback for stdio streams:
  85168. * \code
  85169. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  85170. * {
  85171. * FILE *file = ((MyClientData*)client_data)->file;
  85172. * if(*bytes > 0) {
  85173. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  85174. * if(ferror(file))
  85175. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  85176. * else if(*bytes == 0)
  85177. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  85178. * else
  85179. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  85180. * }
  85181. * else
  85182. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  85183. * }
  85184. * \endcode
  85185. *
  85186. * \note In general, FLAC__StreamEncoder functions which change the
  85187. * state should not be called on the \a encoder while in the callback.
  85188. *
  85189. * \param encoder The encoder instance calling the callback.
  85190. * \param buffer A pointer to a location for the callee to store
  85191. * data to be encoded.
  85192. * \param bytes A pointer to the size of the buffer. On entry
  85193. * to the callback, it contains the maximum number
  85194. * of bytes that may be stored in \a buffer. The
  85195. * callee must set it to the actual number of bytes
  85196. * stored (0 in case of error or end-of-stream) before
  85197. * returning.
  85198. * \param client_data The callee's client data set through
  85199. * FLAC__stream_encoder_set_client_data().
  85200. * \retval FLAC__StreamEncoderReadStatus
  85201. * The callee's return status.
  85202. */
  85203. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  85204. /** Signature for the write callback.
  85205. *
  85206. * A function pointer matching this signature must be passed to
  85207. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  85208. * by the encoder anytime there is raw encoded data ready to write. It may
  85209. * include metadata mixed with encoded audio frames and the data is not
  85210. * guaranteed to be aligned on frame or metadata block boundaries.
  85211. *
  85212. * The only duty of the callback is to write out the \a bytes worth of data
  85213. * in \a buffer to the current position in the output stream. The arguments
  85214. * \a samples and \a current_frame are purely informational. If \a samples
  85215. * is greater than \c 0, then \a current_frame will hold the current frame
  85216. * number that is being written; otherwise it indicates that the write
  85217. * callback is being called to write metadata.
  85218. *
  85219. * \note
  85220. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  85221. * write callback will be called twice when writing each audio
  85222. * frame; once for the page header, and once for the page body.
  85223. * When writing the page header, the \a samples argument to the
  85224. * write callback will be \c 0.
  85225. *
  85226. * \note In general, FLAC__StreamEncoder functions which change the
  85227. * state should not be called on the \a encoder while in the callback.
  85228. *
  85229. * \param encoder The encoder instance calling the callback.
  85230. * \param buffer An array of encoded data of length \a bytes.
  85231. * \param bytes The byte length of \a buffer.
  85232. * \param samples The number of samples encoded by \a buffer.
  85233. * \c 0 has a special meaning; see above.
  85234. * \param current_frame The number of the current frame being encoded.
  85235. * \param client_data The callee's client data set through
  85236. * FLAC__stream_encoder_init_*().
  85237. * \retval FLAC__StreamEncoderWriteStatus
  85238. * The callee's return status.
  85239. */
  85240. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  85241. /** Signature for the seek callback.
  85242. *
  85243. * A function pointer matching this signature may be passed to
  85244. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  85245. * when the encoder needs to seek the output stream. The encoder will pass
  85246. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  85247. *
  85248. * Here is an example of a seek callback for stdio streams:
  85249. * \code
  85250. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  85251. * {
  85252. * FILE *file = ((MyClientData*)client_data)->file;
  85253. * if(file == stdin)
  85254. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  85255. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  85256. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  85257. * else
  85258. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  85259. * }
  85260. * \endcode
  85261. *
  85262. * \note In general, FLAC__StreamEncoder functions which change the
  85263. * state should not be called on the \a encoder while in the callback.
  85264. *
  85265. * \param encoder The encoder instance calling the callback.
  85266. * \param absolute_byte_offset The offset from the beginning of the stream
  85267. * to seek to.
  85268. * \param client_data The callee's client data set through
  85269. * FLAC__stream_encoder_init_*().
  85270. * \retval FLAC__StreamEncoderSeekStatus
  85271. * The callee's return status.
  85272. */
  85273. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  85274. /** Signature for the tell callback.
  85275. *
  85276. * A function pointer matching this signature may be passed to
  85277. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  85278. * when the encoder needs to know the current position of the output stream.
  85279. *
  85280. * \warning
  85281. * The callback must return the true current byte offset of the output to
  85282. * which the encoder is writing. If you are buffering the output, make
  85283. * sure and take this into account. If you are writing directly to a
  85284. * FILE* from your write callback, ftell() is sufficient. If you are
  85285. * writing directly to a file descriptor from your write callback, you
  85286. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  85287. * these points to rewrite metadata after encoding.
  85288. *
  85289. * Here is an example of a tell callback for stdio streams:
  85290. * \code
  85291. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  85292. * {
  85293. * FILE *file = ((MyClientData*)client_data)->file;
  85294. * off_t pos;
  85295. * if(file == stdin)
  85296. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  85297. * else if((pos = ftello(file)) < 0)
  85298. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  85299. * else {
  85300. * *absolute_byte_offset = (FLAC__uint64)pos;
  85301. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  85302. * }
  85303. * }
  85304. * \endcode
  85305. *
  85306. * \note In general, FLAC__StreamEncoder functions which change the
  85307. * state should not be called on the \a encoder while in the callback.
  85308. *
  85309. * \param encoder The encoder instance calling the callback.
  85310. * \param absolute_byte_offset The address at which to store the current
  85311. * position of the output.
  85312. * \param client_data The callee's client data set through
  85313. * FLAC__stream_encoder_init_*().
  85314. * \retval FLAC__StreamEncoderTellStatus
  85315. * The callee's return status.
  85316. */
  85317. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  85318. /** Signature for the metadata callback.
  85319. *
  85320. * A function pointer matching this signature may be passed to
  85321. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  85322. * once at the end of encoding with the populated STREAMINFO structure. This
  85323. * is so the client can seek back to the beginning of the file and write the
  85324. * STREAMINFO block with the correct statistics after encoding (like
  85325. * minimum/maximum frame size and total samples).
  85326. *
  85327. * \note In general, FLAC__StreamEncoder functions which change the
  85328. * state should not be called on the \a encoder while in the callback.
  85329. *
  85330. * \param encoder The encoder instance calling the callback.
  85331. * \param metadata The final populated STREAMINFO block.
  85332. * \param client_data The callee's client data set through
  85333. * FLAC__stream_encoder_init_*().
  85334. */
  85335. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  85336. /** Signature for the progress callback.
  85337. *
  85338. * A function pointer matching this signature may be passed to
  85339. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  85340. * The supplied function will be called when the encoder has finished
  85341. * writing a frame. The \c total_frames_estimate argument to the
  85342. * callback will be based on the value from
  85343. * FLAC__stream_encoder_set_total_samples_estimate().
  85344. *
  85345. * \note In general, FLAC__StreamEncoder functions which change the
  85346. * state should not be called on the \a encoder while in the callback.
  85347. *
  85348. * \param encoder The encoder instance calling the callback.
  85349. * \param bytes_written Bytes written so far.
  85350. * \param samples_written Samples written so far.
  85351. * \param frames_written Frames written so far.
  85352. * \param total_frames_estimate The estimate of the total number of
  85353. * frames to be written.
  85354. * \param client_data The callee's client data set through
  85355. * FLAC__stream_encoder_init_*().
  85356. */
  85357. typedef void (*FLAC__StreamEncoderProgressCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
  85358. /***********************************************************************
  85359. *
  85360. * Class constructor/destructor
  85361. *
  85362. ***********************************************************************/
  85363. /** Create a new stream encoder instance. The instance is created with
  85364. * default settings; see the individual FLAC__stream_encoder_set_*()
  85365. * functions for each setting's default.
  85366. *
  85367. * \retval FLAC__StreamEncoder*
  85368. * \c NULL if there was an error allocating memory, else the new instance.
  85369. */
  85370. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  85371. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  85372. *
  85373. * \param encoder A pointer to an existing encoder.
  85374. * \assert
  85375. * \code encoder != NULL \endcode
  85376. */
  85377. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  85378. /***********************************************************************
  85379. *
  85380. * Public class method prototypes
  85381. *
  85382. ***********************************************************************/
  85383. /** Set the serial number for the FLAC stream to use in the Ogg container.
  85384. *
  85385. * \note
  85386. * This does not need to be set for native FLAC encoding.
  85387. *
  85388. * \note
  85389. * It is recommended to set a serial number explicitly as the default of '0'
  85390. * may collide with other streams.
  85391. *
  85392. * \default \c 0
  85393. * \param encoder An encoder instance to set.
  85394. * \param serial_number See above.
  85395. * \assert
  85396. * \code encoder != NULL \endcode
  85397. * \retval FLAC__bool
  85398. * \c false if the encoder is already initialized, else \c true.
  85399. */
  85400. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  85401. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  85402. * encoded output by feeding it through an internal decoder and comparing
  85403. * the original signal against the decoded signal. If a mismatch occurs,
  85404. * the process call will return \c false. Note that this will slow the
  85405. * encoding process by the extra time required for decoding and comparison.
  85406. *
  85407. * \default \c false
  85408. * \param encoder An encoder instance to set.
  85409. * \param value Flag value (see above).
  85410. * \assert
  85411. * \code encoder != NULL \endcode
  85412. * \retval FLAC__bool
  85413. * \c false if the encoder is already initialized, else \c true.
  85414. */
  85415. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85416. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  85417. * the encoder will comply with the Subset and will check the
  85418. * settings during FLAC__stream_encoder_init_*() to see if all settings
  85419. * comply. If \c false, the settings may take advantage of the full
  85420. * range that the format allows.
  85421. *
  85422. * Make sure you know what it entails before setting this to \c false.
  85423. *
  85424. * \default \c true
  85425. * \param encoder An encoder instance to set.
  85426. * \param value Flag value (see above).
  85427. * \assert
  85428. * \code encoder != NULL \endcode
  85429. * \retval FLAC__bool
  85430. * \c false if the encoder is already initialized, else \c true.
  85431. */
  85432. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85433. /** Set the number of channels to be encoded.
  85434. *
  85435. * \default \c 2
  85436. * \param encoder An encoder instance to set.
  85437. * \param value See above.
  85438. * \assert
  85439. * \code encoder != NULL \endcode
  85440. * \retval FLAC__bool
  85441. * \c false if the encoder is already initialized, else \c true.
  85442. */
  85443. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  85444. /** Set the sample resolution of the input to be encoded.
  85445. *
  85446. * \warning
  85447. * Do not feed the encoder data that is wider than the value you
  85448. * set here or you will generate an invalid stream.
  85449. *
  85450. * \default \c 16
  85451. * \param encoder An encoder instance to set.
  85452. * \param value See above.
  85453. * \assert
  85454. * \code encoder != NULL \endcode
  85455. * \retval FLAC__bool
  85456. * \c false if the encoder is already initialized, else \c true.
  85457. */
  85458. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  85459. /** Set the sample rate (in Hz) of the input to be encoded.
  85460. *
  85461. * \default \c 44100
  85462. * \param encoder An encoder instance to set.
  85463. * \param value See above.
  85464. * \assert
  85465. * \code encoder != NULL \endcode
  85466. * \retval FLAC__bool
  85467. * \c false if the encoder is already initialized, else \c true.
  85468. */
  85469. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  85470. /** Set the compression level
  85471. *
  85472. * The compression level is roughly proportional to the amount of effort
  85473. * the encoder expends to compress the file. A higher level usually
  85474. * means more computation but higher compression. The default level is
  85475. * suitable for most applications.
  85476. *
  85477. * Currently the levels range from \c 0 (fastest, least compression) to
  85478. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  85479. * treated as \c 8.
  85480. *
  85481. * This function automatically calls the following other \c _set_
  85482. * functions with appropriate values, so the client does not need to
  85483. * unless it specifically wants to override them:
  85484. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  85485. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  85486. * - FLAC__stream_encoder_set_apodization()
  85487. * - FLAC__stream_encoder_set_max_lpc_order()
  85488. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  85489. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  85490. * - FLAC__stream_encoder_set_do_escape_coding()
  85491. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  85492. * - FLAC__stream_encoder_set_min_residual_partition_order()
  85493. * - FLAC__stream_encoder_set_max_residual_partition_order()
  85494. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  85495. *
  85496. * The actual values set for each level are:
  85497. * <table>
  85498. * <tr>
  85499. * <td><b>level</b><td>
  85500. * <td>do mid-side stereo<td>
  85501. * <td>loose mid-side stereo<td>
  85502. * <td>apodization<td>
  85503. * <td>max lpc order<td>
  85504. * <td>qlp coeff precision<td>
  85505. * <td>qlp coeff prec search<td>
  85506. * <td>escape coding<td>
  85507. * <td>exhaustive model search<td>
  85508. * <td>min residual partition order<td>
  85509. * <td>max residual partition order<td>
  85510. * <td>rice parameter search dist<td>
  85511. * </tr>
  85512. * <tr> <td><b>0</b><td> <td>false<td> <td>false<td> <td>tukey(0.5)<td> <td>0<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>3<td> <td>0<td> </tr>
  85513. * <tr> <td><b>1</b><td> <td>true<td> <td>true<td> <td>tukey(0.5)<td> <td>0<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>3<td> <td>0<td> </tr>
  85514. * <tr> <td><b>2</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>0<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>3<td> <td>0<td> </tr>
  85515. * <tr> <td><b>3</b><td> <td>false<td> <td>false<td> <td>tukey(0.5)<td> <td>6<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>4<td> <td>0<td> </tr>
  85516. * <tr> <td><b>4</b><td> <td>true<td> <td>true<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>4<td> <td>0<td> </tr>
  85517. * <tr> <td><b>5</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>5<td> <td>0<td> </tr>
  85518. * <tr> <td><b>6</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>6<td> <td>0<td> </tr>
  85519. * <tr> <td><b>7</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>true<td> <td>0<td> <td>6<td> <td>0<td> </tr>
  85520. * <tr> <td><b>8</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>12<td> <td>0<td> <td>false<td> <td>false<td> <td>true<td> <td>0<td> <td>6<td> <td>0<td> </tr>
  85521. * </table>
  85522. *
  85523. * \default \c 5
  85524. * \param encoder An encoder instance to set.
  85525. * \param value See above.
  85526. * \assert
  85527. * \code encoder != NULL \endcode
  85528. * \retval FLAC__bool
  85529. * \c false if the encoder is already initialized, else \c true.
  85530. */
  85531. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  85532. /** Set the blocksize to use while encoding.
  85533. *
  85534. * The number of samples to use per frame. Use \c 0 to let the encoder
  85535. * estimate a blocksize; this is usually best.
  85536. *
  85537. * \default \c 0
  85538. * \param encoder An encoder instance to set.
  85539. * \param value See above.
  85540. * \assert
  85541. * \code encoder != NULL \endcode
  85542. * \retval FLAC__bool
  85543. * \c false if the encoder is already initialized, else \c true.
  85544. */
  85545. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  85546. /** Set to \c true to enable mid-side encoding on stereo input. The
  85547. * number of channels must be 2 for this to have any effect. Set to
  85548. * \c false to use only independent channel coding.
  85549. *
  85550. * \default \c false
  85551. * \param encoder An encoder instance to set.
  85552. * \param value Flag value (see above).
  85553. * \assert
  85554. * \code encoder != NULL \endcode
  85555. * \retval FLAC__bool
  85556. * \c false if the encoder is already initialized, else \c true.
  85557. */
  85558. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85559. /** Set to \c true to enable adaptive switching between mid-side and
  85560. * left-right encoding on stereo input. Set to \c false to use
  85561. * exhaustive searching. Setting this to \c true requires
  85562. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  85563. * \c true in order to have any effect.
  85564. *
  85565. * \default \c false
  85566. * \param encoder An encoder instance to set.
  85567. * \param value Flag value (see above).
  85568. * \assert
  85569. * \code encoder != NULL \endcode
  85570. * \retval FLAC__bool
  85571. * \c false if the encoder is already initialized, else \c true.
  85572. */
  85573. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85574. /** Sets the apodization function(s) the encoder will use when windowing
  85575. * audio data for LPC analysis.
  85576. *
  85577. * The \a specification is a plain ASCII string which specifies exactly
  85578. * which functions to use. There may be more than one (up to 32),
  85579. * separated by \c ';' characters. Some functions take one or more
  85580. * comma-separated arguments in parentheses.
  85581. *
  85582. * The available functions are \c bartlett, \c bartlett_hann,
  85583. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  85584. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  85585. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  85586. *
  85587. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  85588. * (0<STDDEV<=0.5).
  85589. *
  85590. * For \c tukey(P), P specifies the fraction of the window that is
  85591. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  85592. * corresponds to \c hann.
  85593. *
  85594. * Example specifications are \c "blackman" or
  85595. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  85596. *
  85597. * Any function that is specified erroneously is silently dropped. Up
  85598. * to 32 functions are kept, the rest are dropped. If the specification
  85599. * is empty the encoder defaults to \c "tukey(0.5)".
  85600. *
  85601. * When more than one function is specified, then for every subframe the
  85602. * encoder will try each of them separately and choose the window that
  85603. * results in the smallest compressed subframe.
  85604. *
  85605. * Note that each function specified causes the encoder to occupy a
  85606. * floating point array in which to store the window.
  85607. *
  85608. * \default \c "tukey(0.5)"
  85609. * \param encoder An encoder instance to set.
  85610. * \param specification See above.
  85611. * \assert
  85612. * \code encoder != NULL \endcode
  85613. * \code specification != NULL \endcode
  85614. * \retval FLAC__bool
  85615. * \c false if the encoder is already initialized, else \c true.
  85616. */
  85617. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  85618. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  85619. *
  85620. * \default \c 0
  85621. * \param encoder An encoder instance to set.
  85622. * \param value See above.
  85623. * \assert
  85624. * \code encoder != NULL \endcode
  85625. * \retval FLAC__bool
  85626. * \c false if the encoder is already initialized, else \c true.
  85627. */
  85628. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  85629. /** Set the precision, in bits, of the quantized linear predictor
  85630. * coefficients, or \c 0 to let the encoder select it based on the
  85631. * blocksize.
  85632. *
  85633. * \note
  85634. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  85635. * be less than 32.
  85636. *
  85637. * \default \c 0
  85638. * \param encoder An encoder instance to set.
  85639. * \param value See above.
  85640. * \assert
  85641. * \code encoder != NULL \endcode
  85642. * \retval FLAC__bool
  85643. * \c false if the encoder is already initialized, else \c true.
  85644. */
  85645. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  85646. /** Set to \c false to use only the specified quantized linear predictor
  85647. * coefficient precision, or \c true to search neighboring precision
  85648. * values and use the best one.
  85649. *
  85650. * \default \c false
  85651. * \param encoder An encoder instance to set.
  85652. * \param value See above.
  85653. * \assert
  85654. * \code encoder != NULL \endcode
  85655. * \retval FLAC__bool
  85656. * \c false if the encoder is already initialized, else \c true.
  85657. */
  85658. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85659. /** Deprecated. Setting this value has no effect.
  85660. *
  85661. * \default \c false
  85662. * \param encoder An encoder instance to set.
  85663. * \param value See above.
  85664. * \assert
  85665. * \code encoder != NULL \endcode
  85666. * \retval FLAC__bool
  85667. * \c false if the encoder is already initialized, else \c true.
  85668. */
  85669. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85670. /** Set to \c false to let the encoder estimate the best model order
  85671. * based on the residual signal energy, or \c true to force the
  85672. * encoder to evaluate all order models and select the best.
  85673. *
  85674. * \default \c false
  85675. * \param encoder An encoder instance to set.
  85676. * \param value See above.
  85677. * \assert
  85678. * \code encoder != NULL \endcode
  85679. * \retval FLAC__bool
  85680. * \c false if the encoder is already initialized, else \c true.
  85681. */
  85682. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85683. /** Set the minimum partition order to search when coding the residual.
  85684. * This is used in tandem with
  85685. * FLAC__stream_encoder_set_max_residual_partition_order().
  85686. *
  85687. * The partition order determines the context size in the residual.
  85688. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  85689. *
  85690. * Set both min and max values to \c 0 to force a single context,
  85691. * whose Rice parameter is based on the residual signal variance.
  85692. * Otherwise, set a min and max order, and the encoder will search
  85693. * all orders, using the mean of each context for its Rice parameter,
  85694. * and use the best.
  85695. *
  85696. * \default \c 0
  85697. * \param encoder An encoder instance to set.
  85698. * \param value See above.
  85699. * \assert
  85700. * \code encoder != NULL \endcode
  85701. * \retval FLAC__bool
  85702. * \c false if the encoder is already initialized, else \c true.
  85703. */
  85704. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  85705. /** Set the maximum partition order to search when coding the residual.
  85706. * This is used in tandem with
  85707. * FLAC__stream_encoder_set_min_residual_partition_order().
  85708. *
  85709. * The partition order determines the context size in the residual.
  85710. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  85711. *
  85712. * Set both min and max values to \c 0 to force a single context,
  85713. * whose Rice parameter is based on the residual signal variance.
  85714. * Otherwise, set a min and max order, and the encoder will search
  85715. * all orders, using the mean of each context for its Rice parameter,
  85716. * and use the best.
  85717. *
  85718. * \default \c 0
  85719. * \param encoder An encoder instance to set.
  85720. * \param value See above.
  85721. * \assert
  85722. * \code encoder != NULL \endcode
  85723. * \retval FLAC__bool
  85724. * \c false if the encoder is already initialized, else \c true.
  85725. */
  85726. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  85727. /** Deprecated. Setting this value has no effect.
  85728. *
  85729. * \default \c 0
  85730. * \param encoder An encoder instance to set.
  85731. * \param value See above.
  85732. * \assert
  85733. * \code encoder != NULL \endcode
  85734. * \retval FLAC__bool
  85735. * \c false if the encoder is already initialized, else \c true.
  85736. */
  85737. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  85738. /** Set an estimate of the total samples that will be encoded.
  85739. * This is merely an estimate and may be set to \c 0 if unknown.
  85740. * This value will be written to the STREAMINFO block before encoding,
  85741. * and can remove the need for the caller to rewrite the value later
  85742. * if the value is known before encoding.
  85743. *
  85744. * \default \c 0
  85745. * \param encoder An encoder instance to set.
  85746. * \param value See above.
  85747. * \assert
  85748. * \code encoder != NULL \endcode
  85749. * \retval FLAC__bool
  85750. * \c false if the encoder is already initialized, else \c true.
  85751. */
  85752. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  85753. /** Set the metadata blocks to be emitted to the stream before encoding.
  85754. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  85755. * array of pointers to metadata blocks. The array is non-const since
  85756. * the encoder may need to change the \a is_last flag inside them, and
  85757. * in some cases update seek point offsets. Otherwise, the encoder will
  85758. * not modify or free the blocks. It is up to the caller to free the
  85759. * metadata blocks after encoding finishes.
  85760. *
  85761. * \note
  85762. * The encoder stores only copies of the pointers in the \a metadata array;
  85763. * the metadata blocks themselves must survive at least until after
  85764. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  85765. *
  85766. * \note
  85767. * The STREAMINFO block is always written and no STREAMINFO block may
  85768. * occur in the supplied array.
  85769. *
  85770. * \note
  85771. * By default the encoder does not create a SEEKTABLE. If one is supplied
  85772. * in the \a metadata array, but the client has specified that it does not
  85773. * support seeking, then the SEEKTABLE will be written verbatim. However
  85774. * by itself this is not very useful as the client will not know the stream
  85775. * offsets for the seekpoints ahead of time. In order to get a proper
  85776. * seektable the client must support seeking. See next note.
  85777. *
  85778. * \note
  85779. * SEEKTABLE blocks are handled specially. Since you will not know
  85780. * the values for the seek point stream offsets, you should pass in
  85781. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  85782. * required sample numbers (or placeholder points), with \c 0 for the
  85783. * \a frame_samples and \a stream_offset fields for each point. If the
  85784. * client has specified that it supports seeking by providing a seek
  85785. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  85786. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  85787. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  85788. * then while it is encoding the encoder will fill the stream offsets in
  85789. * for you and when encoding is finished, it will seek back and write the
  85790. * real values into the SEEKTABLE block in the stream. There are helper
  85791. * routines for manipulating seektable template blocks; see metadata.h:
  85792. * FLAC__metadata_object_seektable_template_*(). If the client does
  85793. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  85794. * will slow down or remove the ability to seek in the FLAC stream.
  85795. *
  85796. * \note
  85797. * The encoder instance \b will modify the first \c SEEKTABLE block
  85798. * as it transforms the template to a valid seektable while encoding,
  85799. * but it is still up to the caller to free all metadata blocks after
  85800. * encoding.
  85801. *
  85802. * \note
  85803. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  85804. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  85805. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  85806. * will simply write it's own into the stream. If no VORBIS_COMMENT
  85807. * block is present in the \a metadata array, libFLAC will write an
  85808. * empty one, containing only the vendor string.
  85809. *
  85810. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  85811. * the second metadata block of the stream. The encoder already supplies
  85812. * the STREAMINFO block automatically. If \a metadata does not contain a
  85813. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  85814. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  85815. * first, the init function will reorder \a metadata by moving the
  85816. * VORBIS_COMMENT block to the front; the relative ordering of the other
  85817. * blocks will remain as they were.
  85818. *
  85819. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  85820. * stream to \c 65535. If \a num_blocks exceeds this the function will
  85821. * return \c false.
  85822. *
  85823. * \default \c NULL, 0
  85824. * \param encoder An encoder instance to set.
  85825. * \param metadata See above.
  85826. * \param num_blocks See above.
  85827. * \assert
  85828. * \code encoder != NULL \endcode
  85829. * \retval FLAC__bool
  85830. * \c false if the encoder is already initialized, else \c true.
  85831. * \c false if the encoder is already initialized, or if
  85832. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  85833. */
  85834. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  85835. /** Get the current encoder state.
  85836. *
  85837. * \param encoder An encoder instance to query.
  85838. * \assert
  85839. * \code encoder != NULL \endcode
  85840. * \retval FLAC__StreamEncoderState
  85841. * The current encoder state.
  85842. */
  85843. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  85844. /** Get the state of the verify stream decoder.
  85845. * Useful when the stream encoder state is
  85846. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  85847. *
  85848. * \param encoder An encoder instance to query.
  85849. * \assert
  85850. * \code encoder != NULL \endcode
  85851. * \retval FLAC__StreamDecoderState
  85852. * The verify stream decoder state.
  85853. */
  85854. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  85855. /** Get the current encoder state as a C string.
  85856. * This version automatically resolves
  85857. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  85858. * verify decoder's state.
  85859. *
  85860. * \param encoder A encoder instance to query.
  85861. * \assert
  85862. * \code encoder != NULL \endcode
  85863. * \retval const char *
  85864. * The encoder state as a C string. Do not modify the contents.
  85865. */
  85866. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  85867. /** Get relevant values about the nature of a verify decoder error.
  85868. * Useful when the stream encoder state is
  85869. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  85870. * be addresses in which the stats will be returned, or NULL if value
  85871. * is not desired.
  85872. *
  85873. * \param encoder An encoder instance to query.
  85874. * \param absolute_sample The absolute sample number of the mismatch.
  85875. * \param frame_number The number of the frame in which the mismatch occurred.
  85876. * \param channel The channel in which the mismatch occurred.
  85877. * \param sample The number of the sample (relative to the frame) in
  85878. * which the mismatch occurred.
  85879. * \param expected The expected value for the sample in question.
  85880. * \param got The actual value returned by the decoder.
  85881. * \assert
  85882. * \code encoder != NULL \endcode
  85883. */
  85884. FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got);
  85885. /** Get the "verify" flag.
  85886. *
  85887. * \param encoder An encoder instance to query.
  85888. * \assert
  85889. * \code encoder != NULL \endcode
  85890. * \retval FLAC__bool
  85891. * See FLAC__stream_encoder_set_verify().
  85892. */
  85893. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  85894. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  85895. *
  85896. * \param encoder An encoder instance to query.
  85897. * \assert
  85898. * \code encoder != NULL \endcode
  85899. * \retval FLAC__bool
  85900. * See FLAC__stream_encoder_set_streamable_subset().
  85901. */
  85902. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  85903. /** Get the number of input channels being processed.
  85904. *
  85905. * \param encoder An encoder instance to query.
  85906. * \assert
  85907. * \code encoder != NULL \endcode
  85908. * \retval unsigned
  85909. * See FLAC__stream_encoder_set_channels().
  85910. */
  85911. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  85912. /** Get the input sample resolution setting.
  85913. *
  85914. * \param encoder An encoder instance to query.
  85915. * \assert
  85916. * \code encoder != NULL \endcode
  85917. * \retval unsigned
  85918. * See FLAC__stream_encoder_set_bits_per_sample().
  85919. */
  85920. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  85921. /** Get the input sample rate setting.
  85922. *
  85923. * \param encoder An encoder instance to query.
  85924. * \assert
  85925. * \code encoder != NULL \endcode
  85926. * \retval unsigned
  85927. * See FLAC__stream_encoder_set_sample_rate().
  85928. */
  85929. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  85930. /** Get the blocksize setting.
  85931. *
  85932. * \param encoder An encoder instance to query.
  85933. * \assert
  85934. * \code encoder != NULL \endcode
  85935. * \retval unsigned
  85936. * See FLAC__stream_encoder_set_blocksize().
  85937. */
  85938. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  85939. /** Get the "mid/side stereo coding" flag.
  85940. *
  85941. * \param encoder An encoder instance to query.
  85942. * \assert
  85943. * \code encoder != NULL \endcode
  85944. * \retval FLAC__bool
  85945. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  85946. */
  85947. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  85948. /** Get the "adaptive mid/side switching" flag.
  85949. *
  85950. * \param encoder An encoder instance to query.
  85951. * \assert
  85952. * \code encoder != NULL \endcode
  85953. * \retval FLAC__bool
  85954. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  85955. */
  85956. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  85957. /** Get the maximum LPC order setting.
  85958. *
  85959. * \param encoder An encoder instance to query.
  85960. * \assert
  85961. * \code encoder != NULL \endcode
  85962. * \retval unsigned
  85963. * See FLAC__stream_encoder_set_max_lpc_order().
  85964. */
  85965. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  85966. /** Get the quantized linear predictor coefficient precision setting.
  85967. *
  85968. * \param encoder An encoder instance to query.
  85969. * \assert
  85970. * \code encoder != NULL \endcode
  85971. * \retval unsigned
  85972. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  85973. */
  85974. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  85975. /** Get the qlp coefficient precision search flag.
  85976. *
  85977. * \param encoder An encoder instance to query.
  85978. * \assert
  85979. * \code encoder != NULL \endcode
  85980. * \retval FLAC__bool
  85981. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  85982. */
  85983. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  85984. /** Get the "escape coding" flag.
  85985. *
  85986. * \param encoder An encoder instance to query.
  85987. * \assert
  85988. * \code encoder != NULL \endcode
  85989. * \retval FLAC__bool
  85990. * See FLAC__stream_encoder_set_do_escape_coding().
  85991. */
  85992. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  85993. /** Get the exhaustive model search flag.
  85994. *
  85995. * \param encoder An encoder instance to query.
  85996. * \assert
  85997. * \code encoder != NULL \endcode
  85998. * \retval FLAC__bool
  85999. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  86000. */
  86001. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  86002. /** Get the minimum residual partition order setting.
  86003. *
  86004. * \param encoder An encoder instance to query.
  86005. * \assert
  86006. * \code encoder != NULL \endcode
  86007. * \retval unsigned
  86008. * See FLAC__stream_encoder_set_min_residual_partition_order().
  86009. */
  86010. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  86011. /** Get maximum residual partition order setting.
  86012. *
  86013. * \param encoder An encoder instance to query.
  86014. * \assert
  86015. * \code encoder != NULL \endcode
  86016. * \retval unsigned
  86017. * See FLAC__stream_encoder_set_max_residual_partition_order().
  86018. */
  86019. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  86020. /** Get the Rice parameter search distance setting.
  86021. *
  86022. * \param encoder An encoder instance to query.
  86023. * \assert
  86024. * \code encoder != NULL \endcode
  86025. * \retval unsigned
  86026. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  86027. */
  86028. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  86029. /** Get the previously set estimate of the total samples to be encoded.
  86030. * The encoder merely mimics back the value given to
  86031. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  86032. * other way of knowing how many samples the client will encode.
  86033. *
  86034. * \param encoder An encoder instance to set.
  86035. * \assert
  86036. * \code encoder != NULL \endcode
  86037. * \retval FLAC__uint64
  86038. * See FLAC__stream_encoder_get_total_samples_estimate().
  86039. */
  86040. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  86041. /** Initialize the encoder instance to encode native FLAC streams.
  86042. *
  86043. * This flavor of initialization sets up the encoder to encode to a
  86044. * native FLAC stream. I/O is performed via callbacks to the client.
  86045. * For encoding to a plain file via filename or open \c FILE*,
  86046. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  86047. * provide a simpler interface.
  86048. *
  86049. * This function should be called after FLAC__stream_encoder_new() and
  86050. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86051. * or FLAC__stream_encoder_process_interleaved().
  86052. * initialization succeeded.
  86053. *
  86054. * The call to FLAC__stream_encoder_init_stream() currently will also
  86055. * immediately call the write callback several times, once with the \c fLaC
  86056. * signature, and once for each encoded metadata block.
  86057. *
  86058. * \param encoder An uninitialized encoder instance.
  86059. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  86060. * pointer must not be \c NULL.
  86061. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  86062. * pointer may be \c NULL if seeking is not
  86063. * supported. The encoder uses seeking to go back
  86064. * and write some some stream statistics to the
  86065. * STREAMINFO block; this is recommended but not
  86066. * necessary to create a valid FLAC stream. If
  86067. * \a seek_callback is not \c NULL then a
  86068. * \a tell_callback must also be supplied.
  86069. * Alternatively, a dummy seek callback that just
  86070. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  86071. * may also be supplied, all though this is slightly
  86072. * less efficient for the encoder.
  86073. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  86074. * pointer may be \c NULL if seeking is not
  86075. * supported. If \a seek_callback is \c NULL then
  86076. * this argument will be ignored. If
  86077. * \a seek_callback is not \c NULL then a
  86078. * \a tell_callback must also be supplied.
  86079. * Alternatively, a dummy tell callback that just
  86080. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  86081. * may also be supplied, all though this is slightly
  86082. * less efficient for the encoder.
  86083. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  86084. * pointer may be \c NULL if the callback is not
  86085. * desired. If the client provides a seek callback,
  86086. * this function is not necessary as the encoder
  86087. * will automatically seek back and update the
  86088. * STREAMINFO block. It may also be \c NULL if the
  86089. * client does not support seeking, since it will
  86090. * have no way of going back to update the
  86091. * STREAMINFO. However the client can still supply
  86092. * a callback if it would like to know the details
  86093. * from the STREAMINFO.
  86094. * \param client_data This value will be supplied to callbacks in their
  86095. * \a client_data argument.
  86096. * \assert
  86097. * \code encoder != NULL \endcode
  86098. * \retval FLAC__StreamEncoderInitStatus
  86099. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86100. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86101. */
  86102. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(FLAC__StreamEncoder *encoder, FLAC__StreamEncoderWriteCallback write_callback, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderTellCallback tell_callback, FLAC__StreamEncoderMetadataCallback metadata_callback, void *client_data);
  86103. /** Initialize the encoder instance to encode Ogg FLAC streams.
  86104. *
  86105. * This flavor of initialization sets up the encoder to encode to a FLAC
  86106. * stream in an Ogg container. I/O is performed via callbacks to the
  86107. * client. For encoding to a plain file via filename or open \c FILE*,
  86108. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  86109. * provide a simpler interface.
  86110. *
  86111. * This function should be called after FLAC__stream_encoder_new() and
  86112. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86113. * or FLAC__stream_encoder_process_interleaved().
  86114. * initialization succeeded.
  86115. *
  86116. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  86117. * immediately call the write callback several times to write the metadata
  86118. * packets.
  86119. *
  86120. * \param encoder An uninitialized encoder instance.
  86121. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  86122. * pointer must not be \c NULL if \a seek_callback
  86123. * is non-NULL since they are both needed to be
  86124. * able to write data back to the Ogg FLAC stream
  86125. * in the post-encode phase.
  86126. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  86127. * pointer must not be \c NULL.
  86128. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  86129. * pointer may be \c NULL if seeking is not
  86130. * supported. The encoder uses seeking to go back
  86131. * and write some some stream statistics to the
  86132. * STREAMINFO block; this is recommended but not
  86133. * necessary to create a valid FLAC stream. If
  86134. * \a seek_callback is not \c NULL then a
  86135. * \a tell_callback must also be supplied.
  86136. * Alternatively, a dummy seek callback that just
  86137. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  86138. * may also be supplied, all though this is slightly
  86139. * less efficient for the encoder.
  86140. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  86141. * pointer may be \c NULL if seeking is not
  86142. * supported. If \a seek_callback is \c NULL then
  86143. * this argument will be ignored. If
  86144. * \a seek_callback is not \c NULL then a
  86145. * \a tell_callback must also be supplied.
  86146. * Alternatively, a dummy tell callback that just
  86147. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  86148. * may also be supplied, all though this is slightly
  86149. * less efficient for the encoder.
  86150. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  86151. * pointer may be \c NULL if the callback is not
  86152. * desired. If the client provides a seek callback,
  86153. * this function is not necessary as the encoder
  86154. * will automatically seek back and update the
  86155. * STREAMINFO block. It may also be \c NULL if the
  86156. * client does not support seeking, since it will
  86157. * have no way of going back to update the
  86158. * STREAMINFO. However the client can still supply
  86159. * a callback if it would like to know the details
  86160. * from the STREAMINFO.
  86161. * \param client_data This value will be supplied to callbacks in their
  86162. * \a client_data argument.
  86163. * \assert
  86164. * \code encoder != NULL \endcode
  86165. * \retval FLAC__StreamEncoderInitStatus
  86166. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86167. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86168. */
  86169. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(FLAC__StreamEncoder *encoder, FLAC__StreamEncoderReadCallback read_callback, FLAC__StreamEncoderWriteCallback write_callback, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderTellCallback tell_callback, FLAC__StreamEncoderMetadataCallback metadata_callback, void *client_data);
  86170. /** Initialize the encoder instance to encode native FLAC files.
  86171. *
  86172. * This flavor of initialization sets up the encoder to encode to a
  86173. * plain native FLAC file. For non-stdio streams, you must use
  86174. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  86175. *
  86176. * This function should be called after FLAC__stream_encoder_new() and
  86177. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86178. * or FLAC__stream_encoder_process_interleaved().
  86179. * initialization succeeded.
  86180. *
  86181. * \param encoder An uninitialized encoder instance.
  86182. * \param file An open file. The file should have been opened
  86183. * with mode \c "w+b" and rewound. The file
  86184. * becomes owned by the encoder and should not be
  86185. * manipulated by the client while encoding.
  86186. * Unless \a file is \c stdout, it will be closed
  86187. * when FLAC__stream_encoder_finish() is called.
  86188. * Note however that a proper SEEKTABLE cannot be
  86189. * created when encoding to \c stdout since it is
  86190. * not seekable.
  86191. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  86192. * pointer may be \c NULL if the callback is not
  86193. * desired.
  86194. * \param client_data This value will be supplied to callbacks in their
  86195. * \a client_data argument.
  86196. * \assert
  86197. * \code encoder != NULL \endcode
  86198. * \code file != NULL \endcode
  86199. * \retval FLAC__StreamEncoderInitStatus
  86200. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86201. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86202. */
  86203. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  86204. /** Initialize the encoder instance to encode Ogg FLAC files.
  86205. *
  86206. * This flavor of initialization sets up the encoder to encode to a
  86207. * plain Ogg FLAC file. For non-stdio streams, you must use
  86208. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  86209. *
  86210. * This function should be called after FLAC__stream_encoder_new() and
  86211. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86212. * or FLAC__stream_encoder_process_interleaved().
  86213. * initialization succeeded.
  86214. *
  86215. * \param encoder An uninitialized encoder instance.
  86216. * \param file An open file. The file should have been opened
  86217. * with mode \c "w+b" and rewound. The file
  86218. * becomes owned by the encoder and should not be
  86219. * manipulated by the client while encoding.
  86220. * Unless \a file is \c stdout, it will be closed
  86221. * when FLAC__stream_encoder_finish() is called.
  86222. * Note however that a proper SEEKTABLE cannot be
  86223. * created when encoding to \c stdout since it is
  86224. * not seekable.
  86225. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  86226. * pointer may be \c NULL if the callback is not
  86227. * desired.
  86228. * \param client_data This value will be supplied to callbacks in their
  86229. * \a client_data argument.
  86230. * \assert
  86231. * \code encoder != NULL \endcode
  86232. * \code file != NULL \endcode
  86233. * \retval FLAC__StreamEncoderInitStatus
  86234. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86235. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86236. */
  86237. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  86238. /** Initialize the encoder instance to encode native FLAC files.
  86239. *
  86240. * This flavor of initialization sets up the encoder to encode to a plain
  86241. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  86242. * with Unicode filenames on Windows), you must use
  86243. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  86244. * and provide callbacks for the I/O.
  86245. *
  86246. * This function should be called after FLAC__stream_encoder_new() and
  86247. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86248. * or FLAC__stream_encoder_process_interleaved().
  86249. * initialization succeeded.
  86250. *
  86251. * \param encoder An uninitialized encoder instance.
  86252. * \param filename The name of the file to encode to. The file will
  86253. * be opened with fopen(). Use \c NULL to encode to
  86254. * \c stdout. Note however that a proper SEEKTABLE
  86255. * cannot be created when encoding to \c stdout since
  86256. * it is not seekable.
  86257. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  86258. * pointer may be \c NULL if the callback is not
  86259. * desired.
  86260. * \param client_data This value will be supplied to callbacks in their
  86261. * \a client_data argument.
  86262. * \assert
  86263. * \code encoder != NULL \endcode
  86264. * \retval FLAC__StreamEncoderInitStatus
  86265. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86266. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86267. */
  86268. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  86269. /** Initialize the encoder instance to encode Ogg FLAC files.
  86270. *
  86271. * This flavor of initialization sets up the encoder to encode to a plain
  86272. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  86273. * with Unicode filenames on Windows), you must use
  86274. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  86275. * and provide callbacks for the I/O.
  86276. *
  86277. * This function should be called after FLAC__stream_encoder_new() and
  86278. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86279. * or FLAC__stream_encoder_process_interleaved().
  86280. * initialization succeeded.
  86281. *
  86282. * \param encoder An uninitialized encoder instance.
  86283. * \param filename The name of the file to encode to. The file will
  86284. * be opened with fopen(). Use \c NULL to encode to
  86285. * \c stdout. Note however that a proper SEEKTABLE
  86286. * cannot be created when encoding to \c stdout since
  86287. * it is not seekable.
  86288. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  86289. * pointer may be \c NULL if the callback is not
  86290. * desired.
  86291. * \param client_data This value will be supplied to callbacks in their
  86292. * \a client_data argument.
  86293. * \assert
  86294. * \code encoder != NULL \endcode
  86295. * \retval FLAC__StreamEncoderInitStatus
  86296. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86297. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86298. */
  86299. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  86300. /** Finish the encoding process.
  86301. * Flushes the encoding buffer, releases resources, resets the encoder
  86302. * settings to their defaults, and returns the encoder state to
  86303. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  86304. * one or more write callbacks before returning, and will generate
  86305. * a metadata callback.
  86306. *
  86307. * Note that in the course of processing the last frame, errors can
  86308. * occur, so the caller should be sure to check the return value to
  86309. * ensure the file was encoded properly.
  86310. *
  86311. * In the event of a prematurely-terminated encode, it is not strictly
  86312. * necessary to call this immediately before FLAC__stream_encoder_delete()
  86313. * but it is good practice to match every FLAC__stream_encoder_init_*()
  86314. * with a FLAC__stream_encoder_finish().
  86315. *
  86316. * \param encoder An uninitialized encoder instance.
  86317. * \assert
  86318. * \code encoder != NULL \endcode
  86319. * \retval FLAC__bool
  86320. * \c false if an error occurred processing the last frame; or if verify
  86321. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  86322. * verify mismatch; else \c true. If \c false, caller should check the
  86323. * state with FLAC__stream_encoder_get_state() for more information
  86324. * about the error.
  86325. */
  86326. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  86327. /** Submit data for encoding.
  86328. * This version allows you to supply the input data via an array of
  86329. * pointers, each pointer pointing to an array of \a samples samples
  86330. * representing one channel. The samples need not be block-aligned,
  86331. * but each channel should have the same number of samples. Each sample
  86332. * should be a signed integer, right-justified to the resolution set by
  86333. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  86334. * resolution is 16 bits per sample, the samples should all be in the
  86335. * range [-32768,32767].
  86336. *
  86337. * For applications where channel order is important, channels must
  86338. * follow the order as described in the
  86339. * <A HREF="../format.html#frame_header">frame header</A>.
  86340. *
  86341. * \param encoder An initialized encoder instance in the OK state.
  86342. * \param buffer An array of pointers to each channel's signal.
  86343. * \param samples The number of samples in one channel.
  86344. * \assert
  86345. * \code encoder != NULL \endcode
  86346. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  86347. * \retval FLAC__bool
  86348. * \c true if successful, else \c false; in this case, check the
  86349. * encoder state with FLAC__stream_encoder_get_state() to see what
  86350. * went wrong.
  86351. */
  86352. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  86353. /** Submit data for encoding.
  86354. * This version allows you to supply the input data where the channels
  86355. * are interleaved into a single array (i.e. channel0_sample0,
  86356. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  86357. * The samples need not be block-aligned but they must be
  86358. * sample-aligned, i.e. the first value should be channel0_sample0
  86359. * and the last value channelN_sampleM. Each sample should be a signed
  86360. * integer, right-justified to the resolution set by
  86361. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  86362. * resolution is 16 bits per sample, the samples should all be in the
  86363. * range [-32768,32767].
  86364. *
  86365. * For applications where channel order is important, channels must
  86366. * follow the order as described in the
  86367. * <A HREF="../format.html#frame_header">frame header</A>.
  86368. *
  86369. * \param encoder An initialized encoder instance in the OK state.
  86370. * \param buffer An array of channel-interleaved data (see above).
  86371. * \param samples The number of samples in one channel, the same as for
  86372. * FLAC__stream_encoder_process(). For example, if
  86373. * encoding two channels, \c 1000 \a samples corresponds
  86374. * to a \a buffer of 2000 values.
  86375. * \assert
  86376. * \code encoder != NULL \endcode
  86377. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  86378. * \retval FLAC__bool
  86379. * \c true if successful, else \c false; in this case, check the
  86380. * encoder state with FLAC__stream_encoder_get_state() to see what
  86381. * went wrong.
  86382. */
  86383. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  86384. /* \} */
  86385. #ifdef __cplusplus
  86386. }
  86387. #endif
  86388. #endif
  86389. /********* End of inlined file: stream_encoder.h *********/
  86390. #ifdef _MSC_VER
  86391. /* OPT: an MSVC built-in would be better */
  86392. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  86393. {
  86394. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  86395. return (x>>16) | (x<<16);
  86396. }
  86397. #endif
  86398. #if defined(_MSC_VER) && defined(_X86_)
  86399. /* OPT: an MSVC built-in would be better */
  86400. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  86401. {
  86402. __asm {
  86403. mov edx, start
  86404. mov ecx, len
  86405. test ecx, ecx
  86406. loop1:
  86407. jz done1
  86408. mov eax, [edx]
  86409. bswap eax
  86410. mov [edx], eax
  86411. add edx, 4
  86412. dec ecx
  86413. jmp short loop1
  86414. done1:
  86415. }
  86416. }
  86417. #endif
  86418. /** \mainpage
  86419. *
  86420. * \section intro Introduction
  86421. *
  86422. * This is the documentation for the FLAC C and C++ APIs. It is
  86423. * highly interconnected; this introduction should give you a top
  86424. * level idea of the structure and how to find the information you
  86425. * need. As a prerequisite you should have at least a basic
  86426. * knowledge of the FLAC format, documented
  86427. * <A HREF="../format.html">here</A>.
  86428. *
  86429. * \section c_api FLAC C API
  86430. *
  86431. * The FLAC C API is the interface to libFLAC, a set of structures
  86432. * describing the components of FLAC streams, and functions for
  86433. * encoding and decoding streams, as well as manipulating FLAC
  86434. * metadata in files. The public include files will be installed
  86435. * in your include area (for example /usr/include/FLAC/...).
  86436. *
  86437. * By writing a little code and linking against libFLAC, it is
  86438. * relatively easy to add FLAC support to another program. The
  86439. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  86440. * Complete source code of libFLAC as well as the command-line
  86441. * encoder and plugins is available and is a useful source of
  86442. * examples.
  86443. *
  86444. * Aside from encoders and decoders, libFLAC provides a powerful
  86445. * metadata interface for manipulating metadata in FLAC files. It
  86446. * allows the user to add, delete, and modify FLAC metadata blocks
  86447. * and it can automatically take advantage of PADDING blocks to avoid
  86448. * rewriting the entire FLAC file when changing the size of the
  86449. * metadata.
  86450. *
  86451. * libFLAC usually only requires the standard C library and C math
  86452. * library. In particular, threading is not used so there is no
  86453. * dependency on a thread library. However, libFLAC does not use
  86454. * global variables and should be thread-safe.
  86455. *
  86456. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  86457. * However the metadata editing interfaces currently have limited
  86458. * read-only support for Ogg FLAC files.
  86459. *
  86460. * \section cpp_api FLAC C++ API
  86461. *
  86462. * The FLAC C++ API is a set of classes that encapsulate the
  86463. * structures and functions in libFLAC. They provide slightly more
  86464. * functionality with respect to metadata but are otherwise
  86465. * equivalent. For the most part, they share the same usage as
  86466. * their counterparts in libFLAC, and the FLAC C API documentation
  86467. * can be used as a supplement. The public include files
  86468. * for the C++ API will be installed in your include area (for
  86469. * example /usr/include/FLAC++/...).
  86470. *
  86471. * libFLAC++ is also licensed under
  86472. * <A HREF="../license.html">Xiph's BSD license</A>.
  86473. *
  86474. * \section getting_started Getting Started
  86475. *
  86476. * A good starting point for learning the API is to browse through
  86477. * the <A HREF="modules.html">modules</A>. Modules are logical
  86478. * groupings of related functions or classes, which correspond roughly
  86479. * to header files or sections of header files. Each module includes a
  86480. * detailed description of the general usage of its functions or
  86481. * classes.
  86482. *
  86483. * From there you can go on to look at the documentation of
  86484. * individual functions. You can see different views of the individual
  86485. * functions through the links in top bar across this page.
  86486. *
  86487. * If you prefer a more hands-on approach, you can jump right to some
  86488. * <A HREF="../documentation_example_code.html">example code</A>.
  86489. *
  86490. * \section porting_guide Porting Guide
  86491. *
  86492. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  86493. * has been introduced which gives detailed instructions on how to
  86494. * port your code to newer versions of FLAC.
  86495. *
  86496. * \section embedded_developers Embedded Developers
  86497. *
  86498. * libFLAC has grown larger over time as more functionality has been
  86499. * included, but much of it may be unnecessary for a particular embedded
  86500. * implementation. Unused parts may be pruned by some simple editing of
  86501. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  86502. * metadata interface are all independent from each other.
  86503. *
  86504. * It is easiest to just describe the dependencies:
  86505. *
  86506. * - All modules depend on the \link flac_format Format \endlink module.
  86507. * - The decoders and encoders depend on the bitbuffer.
  86508. * - The decoder is independent of the encoder. The encoder uses the
  86509. * decoder because of the verify feature, but this can be removed if
  86510. * not needed.
  86511. * - Parts of the metadata interface require the stream decoder (but not
  86512. * the encoder).
  86513. * - Ogg support is selectable through the compile time macro
  86514. * \c FLAC__HAS_OGG.
  86515. *
  86516. * For example, if your application only requires the stream decoder, no
  86517. * encoder, and no metadata interface, you can remove the stream encoder
  86518. * and the metadata interface, which will greatly reduce the size of the
  86519. * library.
  86520. *
  86521. * Also, there are several places in the libFLAC code with comments marked
  86522. * with "OPT:" where a #define can be changed to enable code that might be
  86523. * faster on a specific platform. Experimenting with these can yield faster
  86524. * binaries.
  86525. */
  86526. /** \defgroup porting Porting Guide for New Versions
  86527. *
  86528. * This module describes differences in the library interfaces from
  86529. * version to version. It assists in the porting of code that uses
  86530. * the libraries to newer versions of FLAC.
  86531. *
  86532. * One simple facility for making porting easier that has been added
  86533. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  86534. * library's includes (e.g. \c include/FLAC/export.h). The
  86535. * \c #defines mirror the libraries'
  86536. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  86537. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  86538. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  86539. * These can be used to support multiple versions of an API during the
  86540. * transition phase, e.g.
  86541. *
  86542. * \code
  86543. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  86544. * legacy code
  86545. * #else
  86546. * new code
  86547. * #endif
  86548. * \endcode
  86549. *
  86550. * The the source will work for multiple versions and the legacy code can
  86551. * easily be removed when the transition is complete.
  86552. *
  86553. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  86554. * include/FLAC/export.h), which can be used to determine whether or not
  86555. * the library has been compiled with support for Ogg FLAC. This is
  86556. * simpler than trying to call an Ogg init function and catching the
  86557. * error.
  86558. */
  86559. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  86560. * \ingroup porting
  86561. *
  86562. * \brief
  86563. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  86564. *
  86565. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  86566. * been simplified. First, libOggFLAC has been merged into libFLAC and
  86567. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  86568. * decoding layers and three encoding layers have been merged into a
  86569. * single stream decoder and stream encoder. That is, the functionality
  86570. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  86571. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  86572. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  86573. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  86574. * is there is now a single API that can be used to encode or decode
  86575. * streams to/from native FLAC or Ogg FLAC and the single API can work
  86576. * on both seekable and non-seekable streams.
  86577. *
  86578. * Instead of creating an encoder or decoder of a certain layer, now the
  86579. * client will always create a FLAC__StreamEncoder or
  86580. * FLAC__StreamDecoder. The old layers are now differentiated by the
  86581. * initialization function. For example, for the decoder,
  86582. * FLAC__stream_decoder_init() has been replaced by
  86583. * FLAC__stream_decoder_init_stream(). This init function takes
  86584. * callbacks for the I/O, and the seeking callbacks are optional. This
  86585. * allows the client to use the same object for seekable and
  86586. * non-seekable streams. For decoding a FLAC file directly, the client
  86587. * can use FLAC__stream_decoder_init_file() and pass just a filename
  86588. * and fewer callbacks; most of the other callbacks are supplied
  86589. * internally. For situations where fopen()ing by filename is not
  86590. * possible (e.g. Unicode filenames on Windows) the client can instead
  86591. * open the file itself and supply the FILE* to
  86592. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  86593. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  86594. * Since the callbacks and client data are now passed to the init
  86595. * function, the FLAC__stream_decoder_set_*_callback() functions and
  86596. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  86597. * rest of the calls to the decoder are the same as before.
  86598. *
  86599. * There are counterpart init functions for Ogg FLAC, e.g.
  86600. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  86601. * and callbacks are the same as for native FLAC.
  86602. *
  86603. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  86604. * been set up like so:
  86605. *
  86606. * \code
  86607. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  86608. * if(decoder == NULL) do_something;
  86609. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  86610. * [... other settings ...]
  86611. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  86612. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  86613. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  86614. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  86615. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  86616. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  86617. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  86618. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  86619. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  86620. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  86621. * \endcode
  86622. *
  86623. * In FLAC 1.1.3 it is like this:
  86624. *
  86625. * \code
  86626. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  86627. * if(decoder == NULL) do_something;
  86628. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  86629. * [... other settings ...]
  86630. * if(FLAC__stream_decoder_init_stream(
  86631. * decoder,
  86632. * my_read_callback,
  86633. * my_seek_callback, // or NULL
  86634. * my_tell_callback, // or NULL
  86635. * my_length_callback, // or NULL
  86636. * my_eof_callback, // or NULL
  86637. * my_write_callback,
  86638. * my_metadata_callback, // or NULL
  86639. * my_error_callback,
  86640. * my_client_data
  86641. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  86642. * \endcode
  86643. *
  86644. * or you could do;
  86645. *
  86646. * \code
  86647. * [...]
  86648. * FILE *file = fopen("somefile.flac","rb");
  86649. * if(file == NULL) do_somthing;
  86650. * if(FLAC__stream_decoder_init_FILE(
  86651. * decoder,
  86652. * file,
  86653. * my_write_callback,
  86654. * my_metadata_callback, // or NULL
  86655. * my_error_callback,
  86656. * my_client_data
  86657. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  86658. * \endcode
  86659. *
  86660. * or just:
  86661. *
  86662. * \code
  86663. * [...]
  86664. * if(FLAC__stream_decoder_init_file(
  86665. * decoder,
  86666. * "somefile.flac",
  86667. * my_write_callback,
  86668. * my_metadata_callback, // or NULL
  86669. * my_error_callback,
  86670. * my_client_data
  86671. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  86672. * \endcode
  86673. *
  86674. * Another small change to the decoder is in how it handles unparseable
  86675. * streams. Before, when the decoder found an unparseable stream
  86676. * (reserved for when the decoder encounters a stream from a future
  86677. * encoder that it can't parse), it changed the state to
  86678. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  86679. * drops sync and calls the error callback with a new error code
  86680. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  86681. * more robust. If your error callback does not discriminate on the the
  86682. * error state, your code does not need to be changed.
  86683. *
  86684. * The encoder now has a new setting:
  86685. * FLAC__stream_encoder_set_apodization(). This is for setting the
  86686. * method used to window the data before LPC analysis. You only need to
  86687. * add a call to this function if the default is not suitable. There
  86688. * are also two new convenience functions that may be useful:
  86689. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  86690. * FLAC__metadata_get_cuesheet().
  86691. *
  86692. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  86693. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  86694. * is now \c size_t instead of \c unsigned.
  86695. */
  86696. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  86697. * \ingroup porting
  86698. *
  86699. * \brief
  86700. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  86701. *
  86702. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  86703. * There was a slight change in the implementation of
  86704. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  86705. * of the \a metadata array of pointers so the client no longer needs
  86706. * to maintain it after the call. The objects themselves that are
  86707. * pointed to by the array are still not copied though and must be
  86708. * maintained until the call to FLAC__stream_encoder_finish().
  86709. */
  86710. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  86711. * \ingroup porting
  86712. *
  86713. * \brief
  86714. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  86715. *
  86716. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  86717. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  86718. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  86719. *
  86720. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  86721. * has changed to reflect the conversion of one of the reserved bits
  86722. * into active use. It used to be \c 2 and now is \c 1. However the
  86723. * FLAC frame header length has not changed, so to skip the proper
  86724. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  86725. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  86726. */
  86727. /** \defgroup flac FLAC C API
  86728. *
  86729. * The FLAC C API is the interface to libFLAC, a set of structures
  86730. * describing the components of FLAC streams, and functions for
  86731. * encoding and decoding streams, as well as manipulating FLAC
  86732. * metadata in files.
  86733. *
  86734. * You should start with the format components as all other modules
  86735. * are dependent on it.
  86736. */
  86737. #endif
  86738. /********* End of inlined file: all.h *********/
  86739. /********* Start of inlined file: bitmath.c *********/
  86740. /********* Start of inlined file: juce_FlacHeader.h *********/
  86741. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  86742. // tasks..
  86743. #define VERSION "1.2.1"
  86744. #define FLAC__NO_DLL 1
  86745. #ifdef _MSC_VER
  86746. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  86747. #endif
  86748. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  86749. #define FLAC__SYS_DARWIN 1
  86750. #endif
  86751. /********* End of inlined file: juce_FlacHeader.h *********/
  86752. #if JUCE_USE_FLAC
  86753. #if HAVE_CONFIG_H
  86754. # include <config.h>
  86755. #endif
  86756. /********* Start of inlined file: bitmath.h *********/
  86757. #ifndef FLAC__PRIVATE__BITMATH_H
  86758. #define FLAC__PRIVATE__BITMATH_H
  86759. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  86760. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  86761. unsigned FLAC__bitmath_silog2(int v);
  86762. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  86763. #endif
  86764. /********* End of inlined file: bitmath.h *********/
  86765. /* An example of what FLAC__bitmath_ilog2() computes:
  86766. *
  86767. * ilog2( 0) = assertion failure
  86768. * ilog2( 1) = 0
  86769. * ilog2( 2) = 1
  86770. * ilog2( 3) = 1
  86771. * ilog2( 4) = 2
  86772. * ilog2( 5) = 2
  86773. * ilog2( 6) = 2
  86774. * ilog2( 7) = 2
  86775. * ilog2( 8) = 3
  86776. * ilog2( 9) = 3
  86777. * ilog2(10) = 3
  86778. * ilog2(11) = 3
  86779. * ilog2(12) = 3
  86780. * ilog2(13) = 3
  86781. * ilog2(14) = 3
  86782. * ilog2(15) = 3
  86783. * ilog2(16) = 4
  86784. * ilog2(17) = 4
  86785. * ilog2(18) = 4
  86786. */
  86787. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  86788. {
  86789. unsigned l = 0;
  86790. FLAC__ASSERT(v > 0);
  86791. while(v >>= 1)
  86792. l++;
  86793. return l;
  86794. }
  86795. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  86796. {
  86797. unsigned l = 0;
  86798. FLAC__ASSERT(v > 0);
  86799. while(v >>= 1)
  86800. l++;
  86801. return l;
  86802. }
  86803. /* An example of what FLAC__bitmath_silog2() computes:
  86804. *
  86805. * silog2(-10) = 5
  86806. * silog2(- 9) = 5
  86807. * silog2(- 8) = 4
  86808. * silog2(- 7) = 4
  86809. * silog2(- 6) = 4
  86810. * silog2(- 5) = 4
  86811. * silog2(- 4) = 3
  86812. * silog2(- 3) = 3
  86813. * silog2(- 2) = 2
  86814. * silog2(- 1) = 2
  86815. * silog2( 0) = 0
  86816. * silog2( 1) = 2
  86817. * silog2( 2) = 3
  86818. * silog2( 3) = 3
  86819. * silog2( 4) = 4
  86820. * silog2( 5) = 4
  86821. * silog2( 6) = 4
  86822. * silog2( 7) = 4
  86823. * silog2( 8) = 5
  86824. * silog2( 9) = 5
  86825. * silog2( 10) = 5
  86826. */
  86827. unsigned FLAC__bitmath_silog2(int v)
  86828. {
  86829. while(1) {
  86830. if(v == 0) {
  86831. return 0;
  86832. }
  86833. else if(v > 0) {
  86834. unsigned l = 0;
  86835. while(v) {
  86836. l++;
  86837. v >>= 1;
  86838. }
  86839. return l+1;
  86840. }
  86841. else if(v == -1) {
  86842. return 2;
  86843. }
  86844. else {
  86845. v++;
  86846. v = -v;
  86847. }
  86848. }
  86849. }
  86850. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  86851. {
  86852. while(1) {
  86853. if(v == 0) {
  86854. return 0;
  86855. }
  86856. else if(v > 0) {
  86857. unsigned l = 0;
  86858. while(v) {
  86859. l++;
  86860. v >>= 1;
  86861. }
  86862. return l+1;
  86863. }
  86864. else if(v == -1) {
  86865. return 2;
  86866. }
  86867. else {
  86868. v++;
  86869. v = -v;
  86870. }
  86871. }
  86872. }
  86873. #endif
  86874. /********* End of inlined file: bitmath.c *********/
  86875. /********* Start of inlined file: bitreader.c *********/
  86876. /********* Start of inlined file: juce_FlacHeader.h *********/
  86877. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  86878. // tasks..
  86879. #define VERSION "1.2.1"
  86880. #define FLAC__NO_DLL 1
  86881. #ifdef _MSC_VER
  86882. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  86883. #endif
  86884. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  86885. #define FLAC__SYS_DARWIN 1
  86886. #endif
  86887. /********* End of inlined file: juce_FlacHeader.h *********/
  86888. #if JUCE_USE_FLAC
  86889. #if HAVE_CONFIG_H
  86890. # include <config.h>
  86891. #endif
  86892. #include <stdlib.h> /* for malloc() */
  86893. #include <string.h> /* for memcpy(), memset() */
  86894. #ifdef _MSC_VER
  86895. #include <winsock.h> /* for ntohl() */
  86896. #elif defined FLAC__SYS_DARWIN
  86897. #include <machine/endian.h> /* for ntohl() */
  86898. #elif defined __MINGW32__
  86899. #include <winsock.h> /* for ntohl() */
  86900. #else
  86901. #include <netinet/in.h> /* for ntohl() */
  86902. #endif
  86903. /********* Start of inlined file: bitreader.h *********/
  86904. #ifndef FLAC__PRIVATE__BITREADER_H
  86905. #define FLAC__PRIVATE__BITREADER_H
  86906. #include <stdio.h> /* for FILE */
  86907. /********* Start of inlined file: cpu.h *********/
  86908. #ifndef FLAC__PRIVATE__CPU_H
  86909. #define FLAC__PRIVATE__CPU_H
  86910. #ifdef HAVE_CONFIG_H
  86911. #include <config.h>
  86912. #endif
  86913. typedef enum {
  86914. FLAC__CPUINFO_TYPE_IA32,
  86915. FLAC__CPUINFO_TYPE_PPC,
  86916. FLAC__CPUINFO_TYPE_UNKNOWN
  86917. } FLAC__CPUInfo_Type;
  86918. typedef struct {
  86919. FLAC__bool cpuid;
  86920. FLAC__bool bswap;
  86921. FLAC__bool cmov;
  86922. FLAC__bool mmx;
  86923. FLAC__bool fxsr;
  86924. FLAC__bool sse;
  86925. FLAC__bool sse2;
  86926. FLAC__bool sse3;
  86927. FLAC__bool ssse3;
  86928. FLAC__bool _3dnow;
  86929. FLAC__bool ext3dnow;
  86930. FLAC__bool extmmx;
  86931. } FLAC__CPUInfo_IA32;
  86932. typedef struct {
  86933. FLAC__bool altivec;
  86934. FLAC__bool ppc64;
  86935. } FLAC__CPUInfo_PPC;
  86936. typedef struct {
  86937. FLAC__bool use_asm;
  86938. FLAC__CPUInfo_Type type;
  86939. union {
  86940. FLAC__CPUInfo_IA32 ia32;
  86941. FLAC__CPUInfo_PPC ppc;
  86942. } data;
  86943. } FLAC__CPUInfo;
  86944. void FLAC__cpu_info(FLAC__CPUInfo *info);
  86945. #ifndef FLAC__NO_ASM
  86946. #ifdef FLAC__CPU_IA32
  86947. #ifdef FLAC__HAS_NASM
  86948. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  86949. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  86950. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  86951. #endif
  86952. #endif
  86953. #endif
  86954. #endif
  86955. /********* End of inlined file: cpu.h *********/
  86956. /*
  86957. * opaque structure definition
  86958. */
  86959. struct FLAC__BitReader;
  86960. typedef struct FLAC__BitReader FLAC__BitReader;
  86961. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  86962. /*
  86963. * construction, deletion, initialization, etc functions
  86964. */
  86965. FLAC__BitReader *FLAC__bitreader_new(void);
  86966. void FLAC__bitreader_delete(FLAC__BitReader *br);
  86967. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  86968. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  86969. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  86970. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  86971. /*
  86972. * CRC functions
  86973. */
  86974. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  86975. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  86976. /*
  86977. * info functions
  86978. */
  86979. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  86980. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  86981. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  86982. /*
  86983. * read functions
  86984. */
  86985. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  86986. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  86987. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  86988. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  86989. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  86990. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  86991. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  86992. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  86993. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  86994. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  86995. #ifndef FLAC__NO_ASM
  86996. # ifdef FLAC__CPU_IA32
  86997. # ifdef FLAC__HAS_NASM
  86998. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  86999. # endif
  87000. # endif
  87001. #endif
  87002. #if 0 /* UNUSED */
  87003. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  87004. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  87005. #endif
  87006. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  87007. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  87008. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  87009. #endif
  87010. /********* End of inlined file: bitreader.h *********/
  87011. /********* Start of inlined file: crc.h *********/
  87012. #ifndef FLAC__PRIVATE__CRC_H
  87013. #define FLAC__PRIVATE__CRC_H
  87014. /* 8 bit CRC generator, MSB shifted first
  87015. ** polynomial = x^8 + x^2 + x^1 + x^0
  87016. ** init = 0
  87017. */
  87018. extern FLAC__byte const FLAC__crc8_table[256];
  87019. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  87020. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  87021. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  87022. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  87023. /* 16 bit CRC generator, MSB shifted first
  87024. ** polynomial = x^16 + x^15 + x^2 + x^0
  87025. ** init = 0
  87026. */
  87027. extern unsigned FLAC__crc16_table[256];
  87028. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  87029. /* this alternate may be faster on some systems/compilers */
  87030. #if 0
  87031. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  87032. #endif
  87033. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  87034. #endif
  87035. /********* End of inlined file: crc.h *********/
  87036. /* Things should be fastest when this matches the machine word size */
  87037. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  87038. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  87039. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  87040. typedef FLAC__uint32 brword;
  87041. #define FLAC__BYTES_PER_WORD 4
  87042. #define FLAC__BITS_PER_WORD 32
  87043. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  87044. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  87045. #if WORDS_BIGENDIAN
  87046. #define SWAP_BE_WORD_TO_HOST(x) (x)
  87047. #else
  87048. #if defined (_MSC_VER) && defined (_X86_)
  87049. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  87050. #else
  87051. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  87052. #endif
  87053. #endif
  87054. /* counts the # of zero MSBs in a word */
  87055. #define COUNT_ZERO_MSBS(word) ( \
  87056. (word) <= 0xffff ? \
  87057. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  87058. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  87059. )
  87060. /* this alternate might be slightly faster on some systems/compilers: */
  87061. #define COUNT_ZERO_MSBS2(word) ( (word) <= 0xff ? byte_to_unary_table[word] + 24 : ((word) <= 0xffff ? byte_to_unary_table[(word) >> 8] + 16 : ((word) <= 0xffffff ? byte_to_unary_table[(word) >> 16] + 8 : byte_to_unary_table[(word) >> 24])) )
  87062. /*
  87063. * This should be at least twice as large as the largest number of words
  87064. * required to represent any 'number' (in any encoding) you are going to
  87065. * read. With FLAC this is on the order of maybe a few hundred bits.
  87066. * If the buffer is smaller than that, the decoder won't be able to read
  87067. * in a whole number that is in a variable length encoding (e.g. Rice).
  87068. * But to be practical it should be at least 1K bytes.
  87069. *
  87070. * Increase this number to decrease the number of read callbacks, at the
  87071. * expense of using more memory. Or decrease for the reverse effect,
  87072. * keeping in mind the limit from the first paragraph. The optimal size
  87073. * also depends on the CPU cache size and other factors; some twiddling
  87074. * may be necessary to squeeze out the best performance.
  87075. */
  87076. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  87077. static const unsigned char byte_to_unary_table[] = {
  87078. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  87079. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  87080. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  87081. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  87082. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87083. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87084. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87085. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  87094. };
  87095. #ifdef min
  87096. #undef min
  87097. #endif
  87098. #define min(x,y) ((x)<(y)?(x):(y))
  87099. #ifdef max
  87100. #undef max
  87101. #endif
  87102. #define max(x,y) ((x)>(y)?(x):(y))
  87103. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  87104. #ifdef _MSC_VER
  87105. #define FLAC__U64L(x) x
  87106. #else
  87107. #define FLAC__U64L(x) x##LLU
  87108. #endif
  87109. #ifndef FLaC__INLINE
  87110. #define FLaC__INLINE
  87111. #endif
  87112. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  87113. struct FLAC__BitReader {
  87114. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  87115. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  87116. brword *buffer;
  87117. unsigned capacity; /* in words */
  87118. unsigned words; /* # of completed words in buffer */
  87119. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  87120. unsigned consumed_words; /* #words ... */
  87121. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  87122. unsigned read_crc16; /* the running frame CRC */
  87123. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  87124. FLAC__BitReaderReadCallback read_callback;
  87125. void *client_data;
  87126. FLAC__CPUInfo cpu_info;
  87127. };
  87128. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  87129. {
  87130. register unsigned crc = br->read_crc16;
  87131. #if FLAC__BYTES_PER_WORD == 4
  87132. switch(br->crc16_align) {
  87133. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  87134. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  87135. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  87136. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  87137. }
  87138. #elif FLAC__BYTES_PER_WORD == 8
  87139. switch(br->crc16_align) {
  87140. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  87141. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  87142. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  87143. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  87144. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  87145. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  87146. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  87147. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  87148. }
  87149. #else
  87150. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  87151. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  87152. br->read_crc16 = crc;
  87153. #endif
  87154. br->crc16_align = 0;
  87155. }
  87156. /* would be static except it needs to be called by asm routines */
  87157. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  87158. {
  87159. unsigned start, end;
  87160. size_t bytes;
  87161. FLAC__byte *target;
  87162. /* first shift the unconsumed buffer data toward the front as much as possible */
  87163. if(br->consumed_words > 0) {
  87164. start = br->consumed_words;
  87165. end = br->words + (br->bytes? 1:0);
  87166. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  87167. br->words -= start;
  87168. br->consumed_words = 0;
  87169. }
  87170. /*
  87171. * set the target for reading, taking into account word alignment and endianness
  87172. */
  87173. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  87174. if(bytes == 0)
  87175. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  87176. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  87177. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  87178. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  87179. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  87180. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  87181. * ^^-------target, bytes=3
  87182. * on LE machines, have to byteswap the odd tail word so nothing is
  87183. * overwritten:
  87184. */
  87185. #if WORDS_BIGENDIAN
  87186. #else
  87187. if(br->bytes)
  87188. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  87189. #endif
  87190. /* now it looks like:
  87191. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  87192. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  87193. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  87194. * ^^-------target, bytes=3
  87195. */
  87196. /* read in the data; note that the callback may return a smaller number of bytes */
  87197. if(!br->read_callback(target, &bytes, br->client_data))
  87198. return false;
  87199. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  87200. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  87201. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  87202. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  87203. * now have to byteswap on LE machines:
  87204. */
  87205. #if WORDS_BIGENDIAN
  87206. #else
  87207. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  87208. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  87209. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  87210. start = br->words;
  87211. local_swap32_block_(br->buffer + start, end - start);
  87212. }
  87213. else
  87214. # endif
  87215. for(start = br->words; start < end; start++)
  87216. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  87217. #endif
  87218. /* now it looks like:
  87219. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  87220. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  87221. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  87222. * finally we'll update the reader values:
  87223. */
  87224. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  87225. br->words = end / FLAC__BYTES_PER_WORD;
  87226. br->bytes = end % FLAC__BYTES_PER_WORD;
  87227. return true;
  87228. }
  87229. /***********************************************************************
  87230. *
  87231. * Class constructor/destructor
  87232. *
  87233. ***********************************************************************/
  87234. FLAC__BitReader *FLAC__bitreader_new(void)
  87235. {
  87236. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  87237. /* calloc() implies:
  87238. memset(br, 0, sizeof(FLAC__BitReader));
  87239. br->buffer = 0;
  87240. br->capacity = 0;
  87241. br->words = br->bytes = 0;
  87242. br->consumed_words = br->consumed_bits = 0;
  87243. br->read_callback = 0;
  87244. br->client_data = 0;
  87245. */
  87246. return br;
  87247. }
  87248. void FLAC__bitreader_delete(FLAC__BitReader *br)
  87249. {
  87250. FLAC__ASSERT(0 != br);
  87251. FLAC__bitreader_free(br);
  87252. free(br);
  87253. }
  87254. /***********************************************************************
  87255. *
  87256. * Public class methods
  87257. *
  87258. ***********************************************************************/
  87259. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  87260. {
  87261. FLAC__ASSERT(0 != br);
  87262. br->words = br->bytes = 0;
  87263. br->consumed_words = br->consumed_bits = 0;
  87264. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  87265. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  87266. if(br->buffer == 0)
  87267. return false;
  87268. br->read_callback = rcb;
  87269. br->client_data = cd;
  87270. br->cpu_info = cpu;
  87271. return true;
  87272. }
  87273. void FLAC__bitreader_free(FLAC__BitReader *br)
  87274. {
  87275. FLAC__ASSERT(0 != br);
  87276. if(0 != br->buffer)
  87277. free(br->buffer);
  87278. br->buffer = 0;
  87279. br->capacity = 0;
  87280. br->words = br->bytes = 0;
  87281. br->consumed_words = br->consumed_bits = 0;
  87282. br->read_callback = 0;
  87283. br->client_data = 0;
  87284. }
  87285. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  87286. {
  87287. br->words = br->bytes = 0;
  87288. br->consumed_words = br->consumed_bits = 0;
  87289. return true;
  87290. }
  87291. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  87292. {
  87293. unsigned i, j;
  87294. if(br == 0) {
  87295. fprintf(out, "bitreader is NULL\n");
  87296. }
  87297. else {
  87298. fprintf(out, "bitreader: capacity=%u words=%u bytes=%u consumed: words=%u, bits=%u\n", br->capacity, br->words, br->bytes, br->consumed_words, br->consumed_bits);
  87299. for(i = 0; i < br->words; i++) {
  87300. fprintf(out, "%08X: ", i);
  87301. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  87302. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  87303. fprintf(out, ".");
  87304. else
  87305. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  87306. fprintf(out, "\n");
  87307. }
  87308. if(br->bytes > 0) {
  87309. fprintf(out, "%08X: ", i);
  87310. for(j = 0; j < br->bytes*8; j++)
  87311. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  87312. fprintf(out, ".");
  87313. else
  87314. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  87315. fprintf(out, "\n");
  87316. }
  87317. }
  87318. }
  87319. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  87320. {
  87321. FLAC__ASSERT(0 != br);
  87322. FLAC__ASSERT(0 != br->buffer);
  87323. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  87324. br->read_crc16 = (unsigned)seed;
  87325. br->crc16_align = br->consumed_bits;
  87326. }
  87327. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  87328. {
  87329. FLAC__ASSERT(0 != br);
  87330. FLAC__ASSERT(0 != br->buffer);
  87331. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  87332. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  87333. /* CRC any tail bytes in a partially-consumed word */
  87334. if(br->consumed_bits) {
  87335. const brword tail = br->buffer[br->consumed_words];
  87336. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  87337. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  87338. }
  87339. return br->read_crc16;
  87340. }
  87341. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  87342. {
  87343. return ((br->consumed_bits & 7) == 0);
  87344. }
  87345. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  87346. {
  87347. return 8 - (br->consumed_bits & 7);
  87348. }
  87349. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  87350. {
  87351. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  87352. }
  87353. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  87354. {
  87355. FLAC__ASSERT(0 != br);
  87356. FLAC__ASSERT(0 != br->buffer);
  87357. FLAC__ASSERT(bits <= 32);
  87358. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  87359. FLAC__ASSERT(br->consumed_words <= br->words);
  87360. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  87361. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  87362. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  87363. *val = 0;
  87364. return true;
  87365. }
  87366. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  87367. if(!bitreader_read_from_client_(br))
  87368. return false;
  87369. }
  87370. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  87371. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  87372. if(br->consumed_bits) {
  87373. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87374. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  87375. const brword word = br->buffer[br->consumed_words];
  87376. if(bits < n) {
  87377. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  87378. br->consumed_bits += bits;
  87379. return true;
  87380. }
  87381. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  87382. bits -= n;
  87383. crc16_update_word_(br, word);
  87384. br->consumed_words++;
  87385. br->consumed_bits = 0;
  87386. if(bits) { /* if there are still bits left to read, there have to be less than 32 so they will all be in the next word */
  87387. *val <<= bits;
  87388. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  87389. br->consumed_bits = bits;
  87390. }
  87391. return true;
  87392. }
  87393. else {
  87394. const brword word = br->buffer[br->consumed_words];
  87395. if(bits < FLAC__BITS_PER_WORD) {
  87396. *val = word >> (FLAC__BITS_PER_WORD-bits);
  87397. br->consumed_bits = bits;
  87398. return true;
  87399. }
  87400. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  87401. *val = word;
  87402. crc16_update_word_(br, word);
  87403. br->consumed_words++;
  87404. return true;
  87405. }
  87406. }
  87407. else {
  87408. /* in this case we're starting our read at a partial tail word;
  87409. * the reader has guaranteed that we have at least 'bits' bits
  87410. * available to read, which makes this case simpler.
  87411. */
  87412. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  87413. if(br->consumed_bits) {
  87414. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87415. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  87416. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  87417. br->consumed_bits += bits;
  87418. return true;
  87419. }
  87420. else {
  87421. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  87422. br->consumed_bits += bits;
  87423. return true;
  87424. }
  87425. }
  87426. }
  87427. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  87428. {
  87429. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  87430. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  87431. return false;
  87432. /* sign-extend: */
  87433. *val <<= (32-bits);
  87434. *val >>= (32-bits);
  87435. return true;
  87436. }
  87437. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  87438. {
  87439. FLAC__uint32 hi, lo;
  87440. if(bits > 32) {
  87441. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  87442. return false;
  87443. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  87444. return false;
  87445. *val = hi;
  87446. *val <<= 32;
  87447. *val |= lo;
  87448. }
  87449. else {
  87450. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  87451. return false;
  87452. *val = lo;
  87453. }
  87454. return true;
  87455. }
  87456. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  87457. {
  87458. FLAC__uint32 x8, x32 = 0;
  87459. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  87460. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  87461. return false;
  87462. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  87463. return false;
  87464. x32 |= (x8 << 8);
  87465. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  87466. return false;
  87467. x32 |= (x8 << 16);
  87468. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  87469. return false;
  87470. x32 |= (x8 << 24);
  87471. *val = x32;
  87472. return true;
  87473. }
  87474. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  87475. {
  87476. /*
  87477. * OPT: a faster implementation is possible but probably not that useful
  87478. * since this is only called a couple of times in the metadata readers.
  87479. */
  87480. FLAC__ASSERT(0 != br);
  87481. FLAC__ASSERT(0 != br->buffer);
  87482. if(bits > 0) {
  87483. const unsigned n = br->consumed_bits & 7;
  87484. unsigned m;
  87485. FLAC__uint32 x;
  87486. if(n != 0) {
  87487. m = min(8-n, bits);
  87488. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  87489. return false;
  87490. bits -= m;
  87491. }
  87492. m = bits / 8;
  87493. if(m > 0) {
  87494. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  87495. return false;
  87496. bits %= 8;
  87497. }
  87498. if(bits > 0) {
  87499. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  87500. return false;
  87501. }
  87502. }
  87503. return true;
  87504. }
  87505. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  87506. {
  87507. FLAC__uint32 x;
  87508. FLAC__ASSERT(0 != br);
  87509. FLAC__ASSERT(0 != br->buffer);
  87510. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  87511. /* step 1: skip over partial head word to get word aligned */
  87512. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  87513. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87514. return false;
  87515. nvals--;
  87516. }
  87517. if(0 == nvals)
  87518. return true;
  87519. /* step 2: skip whole words in chunks */
  87520. while(nvals >= FLAC__BYTES_PER_WORD) {
  87521. if(br->consumed_words < br->words) {
  87522. br->consumed_words++;
  87523. nvals -= FLAC__BYTES_PER_WORD;
  87524. }
  87525. else if(!bitreader_read_from_client_(br))
  87526. return false;
  87527. }
  87528. /* step 3: skip any remainder from partial tail bytes */
  87529. while(nvals) {
  87530. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87531. return false;
  87532. nvals--;
  87533. }
  87534. return true;
  87535. }
  87536. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  87537. {
  87538. FLAC__uint32 x;
  87539. FLAC__ASSERT(0 != br);
  87540. FLAC__ASSERT(0 != br->buffer);
  87541. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  87542. /* step 1: read from partial head word to get word aligned */
  87543. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  87544. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87545. return false;
  87546. *val++ = (FLAC__byte)x;
  87547. nvals--;
  87548. }
  87549. if(0 == nvals)
  87550. return true;
  87551. /* step 2: read whole words in chunks */
  87552. while(nvals >= FLAC__BYTES_PER_WORD) {
  87553. if(br->consumed_words < br->words) {
  87554. const brword word = br->buffer[br->consumed_words++];
  87555. #if FLAC__BYTES_PER_WORD == 4
  87556. val[0] = (FLAC__byte)(word >> 24);
  87557. val[1] = (FLAC__byte)(word >> 16);
  87558. val[2] = (FLAC__byte)(word >> 8);
  87559. val[3] = (FLAC__byte)word;
  87560. #elif FLAC__BYTES_PER_WORD == 8
  87561. val[0] = (FLAC__byte)(word >> 56);
  87562. val[1] = (FLAC__byte)(word >> 48);
  87563. val[2] = (FLAC__byte)(word >> 40);
  87564. val[3] = (FLAC__byte)(word >> 32);
  87565. val[4] = (FLAC__byte)(word >> 24);
  87566. val[5] = (FLAC__byte)(word >> 16);
  87567. val[6] = (FLAC__byte)(word >> 8);
  87568. val[7] = (FLAC__byte)word;
  87569. #else
  87570. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  87571. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  87572. #endif
  87573. val += FLAC__BYTES_PER_WORD;
  87574. nvals -= FLAC__BYTES_PER_WORD;
  87575. }
  87576. else if(!bitreader_read_from_client_(br))
  87577. return false;
  87578. }
  87579. /* step 3: read any remainder from partial tail bytes */
  87580. while(nvals) {
  87581. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87582. return false;
  87583. *val++ = (FLAC__byte)x;
  87584. nvals--;
  87585. }
  87586. return true;
  87587. }
  87588. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  87589. #if 0 /* slow but readable version */
  87590. {
  87591. unsigned bit;
  87592. FLAC__ASSERT(0 != br);
  87593. FLAC__ASSERT(0 != br->buffer);
  87594. *val = 0;
  87595. while(1) {
  87596. if(!FLAC__bitreader_read_bit(br, &bit))
  87597. return false;
  87598. if(bit)
  87599. break;
  87600. else
  87601. *val++;
  87602. }
  87603. return true;
  87604. }
  87605. #else
  87606. {
  87607. unsigned i;
  87608. FLAC__ASSERT(0 != br);
  87609. FLAC__ASSERT(0 != br->buffer);
  87610. *val = 0;
  87611. while(1) {
  87612. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  87613. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  87614. if(b) {
  87615. i = COUNT_ZERO_MSBS(b);
  87616. *val += i;
  87617. i++;
  87618. br->consumed_bits += i;
  87619. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  87620. crc16_update_word_(br, br->buffer[br->consumed_words]);
  87621. br->consumed_words++;
  87622. br->consumed_bits = 0;
  87623. }
  87624. return true;
  87625. }
  87626. else {
  87627. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  87628. crc16_update_word_(br, br->buffer[br->consumed_words]);
  87629. br->consumed_words++;
  87630. br->consumed_bits = 0;
  87631. /* didn't find stop bit yet, have to keep going... */
  87632. }
  87633. }
  87634. /* at this point we've eaten up all the whole words; have to try
  87635. * reading through any tail bytes before calling the read callback.
  87636. * this is a repeat of the above logic adjusted for the fact we
  87637. * don't have a whole word. note though if the client is feeding
  87638. * us data a byte at a time (unlikely), br->consumed_bits may not
  87639. * be zero.
  87640. */
  87641. if(br->bytes) {
  87642. const unsigned end = br->bytes * 8;
  87643. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  87644. if(b) {
  87645. i = COUNT_ZERO_MSBS(b);
  87646. *val += i;
  87647. i++;
  87648. br->consumed_bits += i;
  87649. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  87650. return true;
  87651. }
  87652. else {
  87653. *val += end - br->consumed_bits;
  87654. br->consumed_bits += end;
  87655. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  87656. /* didn't find stop bit yet, have to keep going... */
  87657. }
  87658. }
  87659. if(!bitreader_read_from_client_(br))
  87660. return false;
  87661. }
  87662. }
  87663. #endif
  87664. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  87665. {
  87666. FLAC__uint32 lsbs = 0, msbs = 0;
  87667. unsigned uval;
  87668. FLAC__ASSERT(0 != br);
  87669. FLAC__ASSERT(0 != br->buffer);
  87670. FLAC__ASSERT(parameter <= 31);
  87671. /* read the unary MSBs and end bit */
  87672. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  87673. return false;
  87674. /* read the binary LSBs */
  87675. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  87676. return false;
  87677. /* compose the value */
  87678. uval = (msbs << parameter) | lsbs;
  87679. if(uval & 1)
  87680. *val = -((int)(uval >> 1)) - 1;
  87681. else
  87682. *val = (int)(uval >> 1);
  87683. return true;
  87684. }
  87685. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  87686. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  87687. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  87688. /* OPT: possibly faster version for use with MSVC */
  87689. #ifdef _MSC_VER
  87690. {
  87691. unsigned i;
  87692. unsigned uval = 0;
  87693. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  87694. /* try and get br->consumed_words and br->consumed_bits into register;
  87695. * must remember to flush them back to *br before calling other
  87696. * bitwriter functions that use them, and before returning */
  87697. register unsigned cwords;
  87698. register unsigned cbits;
  87699. FLAC__ASSERT(0 != br);
  87700. FLAC__ASSERT(0 != br->buffer);
  87701. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  87702. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  87703. FLAC__ASSERT(parameter < 32);
  87704. /* the above two asserts also guarantee that the binary part never straddles more that 2 words, so we don't have to loop to read it */
  87705. if(nvals == 0)
  87706. return true;
  87707. cbits = br->consumed_bits;
  87708. cwords = br->consumed_words;
  87709. while(1) {
  87710. /* read unary part */
  87711. while(1) {
  87712. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87713. brword b = br->buffer[cwords] << cbits;
  87714. if(b) {
  87715. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  87716. __asm {
  87717. bsr eax, b
  87718. not eax
  87719. and eax, 31
  87720. mov i, eax
  87721. }
  87722. #else
  87723. i = COUNT_ZERO_MSBS(b);
  87724. #endif
  87725. uval += i;
  87726. bits = parameter;
  87727. i++;
  87728. cbits += i;
  87729. if(cbits == FLAC__BITS_PER_WORD) {
  87730. crc16_update_word_(br, br->buffer[cwords]);
  87731. cwords++;
  87732. cbits = 0;
  87733. }
  87734. goto break1;
  87735. }
  87736. else {
  87737. uval += FLAC__BITS_PER_WORD - cbits;
  87738. crc16_update_word_(br, br->buffer[cwords]);
  87739. cwords++;
  87740. cbits = 0;
  87741. /* didn't find stop bit yet, have to keep going... */
  87742. }
  87743. }
  87744. /* at this point we've eaten up all the whole words; have to try
  87745. * reading through any tail bytes before calling the read callback.
  87746. * this is a repeat of the above logic adjusted for the fact we
  87747. * don't have a whole word. note though if the client is feeding
  87748. * us data a byte at a time (unlikely), br->consumed_bits may not
  87749. * be zero.
  87750. */
  87751. if(br->bytes) {
  87752. const unsigned end = br->bytes * 8;
  87753. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  87754. if(b) {
  87755. i = COUNT_ZERO_MSBS(b);
  87756. uval += i;
  87757. bits = parameter;
  87758. i++;
  87759. cbits += i;
  87760. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87761. goto break1;
  87762. }
  87763. else {
  87764. uval += end - cbits;
  87765. cbits += end;
  87766. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87767. /* didn't find stop bit yet, have to keep going... */
  87768. }
  87769. }
  87770. /* flush registers and read; bitreader_read_from_client_() does
  87771. * not touch br->consumed_bits at all but we still need to set
  87772. * it in case it fails and we have to return false.
  87773. */
  87774. br->consumed_bits = cbits;
  87775. br->consumed_words = cwords;
  87776. if(!bitreader_read_from_client_(br))
  87777. return false;
  87778. cwords = br->consumed_words;
  87779. }
  87780. break1:
  87781. /* read binary part */
  87782. FLAC__ASSERT(cwords <= br->words);
  87783. if(bits) {
  87784. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  87785. /* flush registers and read; bitreader_read_from_client_() does
  87786. * not touch br->consumed_bits at all but we still need to set
  87787. * it in case it fails and we have to return false.
  87788. */
  87789. br->consumed_bits = cbits;
  87790. br->consumed_words = cwords;
  87791. if(!bitreader_read_from_client_(br))
  87792. return false;
  87793. cwords = br->consumed_words;
  87794. }
  87795. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87796. if(cbits) {
  87797. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87798. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  87799. const brword word = br->buffer[cwords];
  87800. if(bits < n) {
  87801. uval <<= bits;
  87802. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  87803. cbits += bits;
  87804. goto break2;
  87805. }
  87806. uval <<= n;
  87807. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  87808. bits -= n;
  87809. crc16_update_word_(br, word);
  87810. cwords++;
  87811. cbits = 0;
  87812. if(bits) { /* if there are still bits left to read, there have to be less than 32 so they will all be in the next word */
  87813. uval <<= bits;
  87814. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  87815. cbits = bits;
  87816. }
  87817. goto break2;
  87818. }
  87819. else {
  87820. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  87821. uval <<= bits;
  87822. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  87823. cbits = bits;
  87824. goto break2;
  87825. }
  87826. }
  87827. else {
  87828. /* in this case we're starting our read at a partial tail word;
  87829. * the reader has guaranteed that we have at least 'bits' bits
  87830. * available to read, which makes this case simpler.
  87831. */
  87832. uval <<= bits;
  87833. if(cbits) {
  87834. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87835. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  87836. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  87837. cbits += bits;
  87838. goto break2;
  87839. }
  87840. else {
  87841. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  87842. cbits += bits;
  87843. goto break2;
  87844. }
  87845. }
  87846. }
  87847. break2:
  87848. /* compose the value */
  87849. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  87850. /* are we done? */
  87851. --nvals;
  87852. if(nvals == 0) {
  87853. br->consumed_bits = cbits;
  87854. br->consumed_words = cwords;
  87855. return true;
  87856. }
  87857. uval = 0;
  87858. ++vals;
  87859. }
  87860. }
  87861. #else
  87862. {
  87863. unsigned i;
  87864. unsigned uval = 0;
  87865. /* try and get br->consumed_words and br->consumed_bits into register;
  87866. * must remember to flush them back to *br before calling other
  87867. * bitwriter functions that use them, and before returning */
  87868. register unsigned cwords;
  87869. register unsigned cbits;
  87870. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  87871. FLAC__ASSERT(0 != br);
  87872. FLAC__ASSERT(0 != br->buffer);
  87873. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  87874. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  87875. FLAC__ASSERT(parameter < 32);
  87876. /* the above two asserts also guarantee that the binary part never straddles more than 2 words, so we don't have to loop to read it */
  87877. if(nvals == 0)
  87878. return true;
  87879. cbits = br->consumed_bits;
  87880. cwords = br->consumed_words;
  87881. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  87882. while(1) {
  87883. /* read unary part */
  87884. while(1) {
  87885. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87886. brword b = br->buffer[cwords] << cbits;
  87887. if(b) {
  87888. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  87889. asm volatile (
  87890. "bsrl %1, %0;"
  87891. "notl %0;"
  87892. "andl $31, %0;"
  87893. : "=r"(i)
  87894. : "r"(b)
  87895. );
  87896. #else
  87897. i = COUNT_ZERO_MSBS(b);
  87898. #endif
  87899. uval += i;
  87900. cbits += i;
  87901. cbits++; /* skip over stop bit */
  87902. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  87903. crc16_update_word_(br, br->buffer[cwords]);
  87904. cwords++;
  87905. cbits = 0;
  87906. }
  87907. goto break1;
  87908. }
  87909. else {
  87910. uval += FLAC__BITS_PER_WORD - cbits;
  87911. crc16_update_word_(br, br->buffer[cwords]);
  87912. cwords++;
  87913. cbits = 0;
  87914. /* didn't find stop bit yet, have to keep going... */
  87915. }
  87916. }
  87917. /* at this point we've eaten up all the whole words; have to try
  87918. * reading through any tail bytes before calling the read callback.
  87919. * this is a repeat of the above logic adjusted for the fact we
  87920. * don't have a whole word. note though if the client is feeding
  87921. * us data a byte at a time (unlikely), br->consumed_bits may not
  87922. * be zero.
  87923. */
  87924. if(br->bytes) {
  87925. const unsigned end = br->bytes * 8;
  87926. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  87927. if(b) {
  87928. i = COUNT_ZERO_MSBS(b);
  87929. uval += i;
  87930. cbits += i;
  87931. cbits++; /* skip over stop bit */
  87932. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87933. goto break1;
  87934. }
  87935. else {
  87936. uval += end - cbits;
  87937. cbits += end;
  87938. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87939. /* didn't find stop bit yet, have to keep going... */
  87940. }
  87941. }
  87942. /* flush registers and read; bitreader_read_from_client_() does
  87943. * not touch br->consumed_bits at all but we still need to set
  87944. * it in case it fails and we have to return false.
  87945. */
  87946. br->consumed_bits = cbits;
  87947. br->consumed_words = cwords;
  87948. if(!bitreader_read_from_client_(br))
  87949. return false;
  87950. cwords = br->consumed_words;
  87951. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  87952. /* + uval to offset our count by the # of unary bits already
  87953. * consumed before the read, because we will add these back
  87954. * in all at once at break1
  87955. */
  87956. }
  87957. break1:
  87958. ucbits -= uval;
  87959. ucbits--; /* account for stop bit */
  87960. /* read binary part */
  87961. FLAC__ASSERT(cwords <= br->words);
  87962. if(parameter) {
  87963. while(ucbits < parameter) {
  87964. /* flush registers and read; bitreader_read_from_client_() does
  87965. * not touch br->consumed_bits at all but we still need to set
  87966. * it in case it fails and we have to return false.
  87967. */
  87968. br->consumed_bits = cbits;
  87969. br->consumed_words = cwords;
  87970. if(!bitreader_read_from_client_(br))
  87971. return false;
  87972. cwords = br->consumed_words;
  87973. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  87974. }
  87975. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87976. if(cbits) {
  87977. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  87978. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  87979. const brword word = br->buffer[cwords];
  87980. if(parameter < n) {
  87981. uval <<= parameter;
  87982. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  87983. cbits += parameter;
  87984. }
  87985. else {
  87986. uval <<= n;
  87987. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  87988. crc16_update_word_(br, word);
  87989. cwords++;
  87990. cbits = parameter - n;
  87991. if(cbits) { /* parameter > n, i.e. if there are still bits left to read, there have to be less than 32 so they will all be in the next word */
  87992. uval <<= cbits;
  87993. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  87994. }
  87995. }
  87996. }
  87997. else {
  87998. cbits = parameter;
  87999. uval <<= parameter;
  88000. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  88001. }
  88002. }
  88003. else {
  88004. /* in this case we're starting our read at a partial tail word;
  88005. * the reader has guaranteed that we have at least 'parameter'
  88006. * bits available to read, which makes this case simpler.
  88007. */
  88008. uval <<= parameter;
  88009. if(cbits) {
  88010. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88011. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  88012. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  88013. cbits += parameter;
  88014. }
  88015. else {
  88016. cbits = parameter;
  88017. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  88018. }
  88019. }
  88020. }
  88021. ucbits -= parameter;
  88022. /* compose the value */
  88023. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  88024. /* are we done? */
  88025. --nvals;
  88026. if(nvals == 0) {
  88027. br->consumed_bits = cbits;
  88028. br->consumed_words = cwords;
  88029. return true;
  88030. }
  88031. uval = 0;
  88032. ++vals;
  88033. }
  88034. }
  88035. #endif
  88036. #if 0 /* UNUSED */
  88037. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  88038. {
  88039. FLAC__uint32 lsbs = 0, msbs = 0;
  88040. unsigned bit, uval, k;
  88041. FLAC__ASSERT(0 != br);
  88042. FLAC__ASSERT(0 != br->buffer);
  88043. k = FLAC__bitmath_ilog2(parameter);
  88044. /* read the unary MSBs and end bit */
  88045. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  88046. return false;
  88047. /* read the binary LSBs */
  88048. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  88049. return false;
  88050. if(parameter == 1u<<k) {
  88051. /* compose the value */
  88052. uval = (msbs << k) | lsbs;
  88053. }
  88054. else {
  88055. unsigned d = (1 << (k+1)) - parameter;
  88056. if(lsbs >= d) {
  88057. if(!FLAC__bitreader_read_bit(br, &bit))
  88058. return false;
  88059. lsbs <<= 1;
  88060. lsbs |= bit;
  88061. lsbs -= d;
  88062. }
  88063. /* compose the value */
  88064. uval = msbs * parameter + lsbs;
  88065. }
  88066. /* unfold unsigned to signed */
  88067. if(uval & 1)
  88068. *val = -((int)(uval >> 1)) - 1;
  88069. else
  88070. *val = (int)(uval >> 1);
  88071. return true;
  88072. }
  88073. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  88074. {
  88075. FLAC__uint32 lsbs, msbs = 0;
  88076. unsigned bit, k;
  88077. FLAC__ASSERT(0 != br);
  88078. FLAC__ASSERT(0 != br->buffer);
  88079. k = FLAC__bitmath_ilog2(parameter);
  88080. /* read the unary MSBs and end bit */
  88081. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  88082. return false;
  88083. /* read the binary LSBs */
  88084. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  88085. return false;
  88086. if(parameter == 1u<<k) {
  88087. /* compose the value */
  88088. *val = (msbs << k) | lsbs;
  88089. }
  88090. else {
  88091. unsigned d = (1 << (k+1)) - parameter;
  88092. if(lsbs >= d) {
  88093. if(!FLAC__bitreader_read_bit(br, &bit))
  88094. return false;
  88095. lsbs <<= 1;
  88096. lsbs |= bit;
  88097. lsbs -= d;
  88098. }
  88099. /* compose the value */
  88100. *val = msbs * parameter + lsbs;
  88101. }
  88102. return true;
  88103. }
  88104. #endif /* UNUSED */
  88105. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  88106. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  88107. {
  88108. FLAC__uint32 v = 0;
  88109. FLAC__uint32 x;
  88110. unsigned i;
  88111. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88112. return false;
  88113. if(raw)
  88114. raw[(*rawlen)++] = (FLAC__byte)x;
  88115. if(!(x & 0x80)) { /* 0xxxxxxx */
  88116. v = x;
  88117. i = 0;
  88118. }
  88119. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  88120. v = x & 0x1F;
  88121. i = 1;
  88122. }
  88123. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  88124. v = x & 0x0F;
  88125. i = 2;
  88126. }
  88127. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  88128. v = x & 0x07;
  88129. i = 3;
  88130. }
  88131. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  88132. v = x & 0x03;
  88133. i = 4;
  88134. }
  88135. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  88136. v = x & 0x01;
  88137. i = 5;
  88138. }
  88139. else {
  88140. *val = 0xffffffff;
  88141. return true;
  88142. }
  88143. for( ; i; i--) {
  88144. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88145. return false;
  88146. if(raw)
  88147. raw[(*rawlen)++] = (FLAC__byte)x;
  88148. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  88149. *val = 0xffffffff;
  88150. return true;
  88151. }
  88152. v <<= 6;
  88153. v |= (x & 0x3F);
  88154. }
  88155. *val = v;
  88156. return true;
  88157. }
  88158. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  88159. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  88160. {
  88161. FLAC__uint64 v = 0;
  88162. FLAC__uint32 x;
  88163. unsigned i;
  88164. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88165. return false;
  88166. if(raw)
  88167. raw[(*rawlen)++] = (FLAC__byte)x;
  88168. if(!(x & 0x80)) { /* 0xxxxxxx */
  88169. v = x;
  88170. i = 0;
  88171. }
  88172. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  88173. v = x & 0x1F;
  88174. i = 1;
  88175. }
  88176. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  88177. v = x & 0x0F;
  88178. i = 2;
  88179. }
  88180. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  88181. v = x & 0x07;
  88182. i = 3;
  88183. }
  88184. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  88185. v = x & 0x03;
  88186. i = 4;
  88187. }
  88188. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  88189. v = x & 0x01;
  88190. i = 5;
  88191. }
  88192. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  88193. v = 0;
  88194. i = 6;
  88195. }
  88196. else {
  88197. *val = FLAC__U64L(0xffffffffffffffff);
  88198. return true;
  88199. }
  88200. for( ; i; i--) {
  88201. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88202. return false;
  88203. if(raw)
  88204. raw[(*rawlen)++] = (FLAC__byte)x;
  88205. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  88206. *val = FLAC__U64L(0xffffffffffffffff);
  88207. return true;
  88208. }
  88209. v <<= 6;
  88210. v |= (x & 0x3F);
  88211. }
  88212. *val = v;
  88213. return true;
  88214. }
  88215. #endif
  88216. /********* End of inlined file: bitreader.c *********/
  88217. /********* Start of inlined file: bitwriter.c *********/
  88218. /********* Start of inlined file: juce_FlacHeader.h *********/
  88219. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  88220. // tasks..
  88221. #define VERSION "1.2.1"
  88222. #define FLAC__NO_DLL 1
  88223. #ifdef _MSC_VER
  88224. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  88225. #endif
  88226. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  88227. #define FLAC__SYS_DARWIN 1
  88228. #endif
  88229. /********* End of inlined file: juce_FlacHeader.h *********/
  88230. #if JUCE_USE_FLAC
  88231. #if HAVE_CONFIG_H
  88232. # include <config.h>
  88233. #endif
  88234. #include <stdlib.h> /* for malloc() */
  88235. #include <string.h> /* for memcpy(), memset() */
  88236. #ifdef _MSC_VER
  88237. #include <winsock.h> /* for ntohl() */
  88238. #elif defined FLAC__SYS_DARWIN
  88239. #include <machine/endian.h> /* for ntohl() */
  88240. #elif defined __MINGW32__
  88241. #include <winsock.h> /* for ntohl() */
  88242. #else
  88243. #include <netinet/in.h> /* for ntohl() */
  88244. #endif
  88245. #if 0 /* UNUSED */
  88246. #endif
  88247. /********* Start of inlined file: bitwriter.h *********/
  88248. #ifndef FLAC__PRIVATE__BITWRITER_H
  88249. #define FLAC__PRIVATE__BITWRITER_H
  88250. #include <stdio.h> /* for FILE */
  88251. /*
  88252. * opaque structure definition
  88253. */
  88254. struct FLAC__BitWriter;
  88255. typedef struct FLAC__BitWriter FLAC__BitWriter;
  88256. /*
  88257. * construction, deletion, initialization, etc functions
  88258. */
  88259. FLAC__BitWriter *FLAC__bitwriter_new(void);
  88260. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  88261. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  88262. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  88263. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  88264. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  88265. /*
  88266. * CRC functions
  88267. *
  88268. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  88269. */
  88270. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  88271. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  88272. /*
  88273. * info functions
  88274. */
  88275. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  88276. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  88277. /*
  88278. * direct buffer access
  88279. *
  88280. * there may be no calls on the bitwriter between get and release.
  88281. * the bitwriter continues to own the returned buffer.
  88282. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  88283. */
  88284. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  88285. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  88286. /*
  88287. * write functions
  88288. */
  88289. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  88290. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  88291. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  88292. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  88293. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  88294. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  88295. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  88296. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  88297. #if 0 /* UNUSED */
  88298. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  88299. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  88300. #endif
  88301. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  88302. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  88303. #if 0 /* UNUSED */
  88304. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  88305. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  88306. #endif
  88307. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  88308. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  88309. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  88310. #endif
  88311. /********* End of inlined file: bitwriter.h *********/
  88312. /********* Start of inlined file: alloc.h *********/
  88313. #ifndef FLAC__SHARE__ALLOC_H
  88314. #define FLAC__SHARE__ALLOC_H
  88315. #if HAVE_CONFIG_H
  88316. # include <config.h>
  88317. #endif
  88318. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  88319. * before #including this file, otherwise SIZE_MAX might not be defined
  88320. */
  88321. #include <limits.h> /* for SIZE_MAX */
  88322. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  88323. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  88324. #endif
  88325. #include <stdlib.h> /* for size_t, malloc(), etc */
  88326. #ifndef SIZE_MAX
  88327. # ifndef SIZE_T_MAX
  88328. # ifdef _MSC_VER
  88329. # define SIZE_T_MAX UINT_MAX
  88330. # else
  88331. # error
  88332. # endif
  88333. # endif
  88334. # define SIZE_MAX SIZE_T_MAX
  88335. #endif
  88336. #ifndef FLaC__INLINE
  88337. #define FLaC__INLINE
  88338. #endif
  88339. /* avoid malloc()ing 0 bytes, see:
  88340. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  88341. */
  88342. static FLaC__INLINE void *safe_malloc_(size_t size)
  88343. {
  88344. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  88345. if(!size)
  88346. size++;
  88347. return malloc(size);
  88348. }
  88349. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  88350. {
  88351. if(!nmemb || !size)
  88352. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  88353. return calloc(nmemb, size);
  88354. }
  88355. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  88356. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  88357. {
  88358. size2 += size1;
  88359. if(size2 < size1)
  88360. return 0;
  88361. return safe_malloc_(size2);
  88362. }
  88363. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  88364. {
  88365. size2 += size1;
  88366. if(size2 < size1)
  88367. return 0;
  88368. size3 += size2;
  88369. if(size3 < size2)
  88370. return 0;
  88371. return safe_malloc_(size3);
  88372. }
  88373. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  88374. {
  88375. size2 += size1;
  88376. if(size2 < size1)
  88377. return 0;
  88378. size3 += size2;
  88379. if(size3 < size2)
  88380. return 0;
  88381. size4 += size3;
  88382. if(size4 < size3)
  88383. return 0;
  88384. return safe_malloc_(size4);
  88385. }
  88386. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  88387. #if 0
  88388. needs support for cases where sizeof(size_t) != 4
  88389. {
  88390. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  88391. if(sizeof(size_t) == 4) {
  88392. if ((double)size1 * (double)size2 < 4294967296.0)
  88393. return malloc(size1*size2);
  88394. }
  88395. return 0;
  88396. }
  88397. #else
  88398. /* better? */
  88399. {
  88400. if(!size1 || !size2)
  88401. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  88402. if(size1 > SIZE_MAX / size2)
  88403. return 0;
  88404. return malloc(size1*size2);
  88405. }
  88406. #endif
  88407. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  88408. {
  88409. if(!size1 || !size2 || !size3)
  88410. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  88411. if(size1 > SIZE_MAX / size2)
  88412. return 0;
  88413. size1 *= size2;
  88414. if(size1 > SIZE_MAX / size3)
  88415. return 0;
  88416. return malloc(size1*size3);
  88417. }
  88418. /* size1*size2 + size3 */
  88419. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  88420. {
  88421. if(!size1 || !size2)
  88422. return safe_malloc_(size3);
  88423. if(size1 > SIZE_MAX / size2)
  88424. return 0;
  88425. return safe_malloc_add_2op_(size1*size2, size3);
  88426. }
  88427. /* size1 * (size2 + size3) */
  88428. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  88429. {
  88430. if(!size1 || (!size2 && !size3))
  88431. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  88432. size2 += size3;
  88433. if(size2 < size3)
  88434. return 0;
  88435. return safe_malloc_mul_2op_(size1, size2);
  88436. }
  88437. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  88438. {
  88439. size2 += size1;
  88440. if(size2 < size1)
  88441. return 0;
  88442. return realloc(ptr, size2);
  88443. }
  88444. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  88445. {
  88446. size2 += size1;
  88447. if(size2 < size1)
  88448. return 0;
  88449. size3 += size2;
  88450. if(size3 < size2)
  88451. return 0;
  88452. return realloc(ptr, size3);
  88453. }
  88454. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  88455. {
  88456. size2 += size1;
  88457. if(size2 < size1)
  88458. return 0;
  88459. size3 += size2;
  88460. if(size3 < size2)
  88461. return 0;
  88462. size4 += size3;
  88463. if(size4 < size3)
  88464. return 0;
  88465. return realloc(ptr, size4);
  88466. }
  88467. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  88468. {
  88469. if(!size1 || !size2)
  88470. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  88471. if(size1 > SIZE_MAX / size2)
  88472. return 0;
  88473. return realloc(ptr, size1*size2);
  88474. }
  88475. /* size1 * (size2 + size3) */
  88476. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  88477. {
  88478. if(!size1 || (!size2 && !size3))
  88479. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  88480. size2 += size3;
  88481. if(size2 < size3)
  88482. return 0;
  88483. return safe_realloc_mul_2op_(ptr, size1, size2);
  88484. }
  88485. #endif
  88486. /********* End of inlined file: alloc.h *********/
  88487. /* Things should be fastest when this matches the machine word size */
  88488. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  88489. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  88490. typedef FLAC__uint32 bwword;
  88491. #define FLAC__BYTES_PER_WORD 4
  88492. #define FLAC__BITS_PER_WORD 32
  88493. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  88494. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  88495. #if WORDS_BIGENDIAN
  88496. #define SWAP_BE_WORD_TO_HOST(x) (x)
  88497. #else
  88498. #ifdef _MSC_VER
  88499. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  88500. #else
  88501. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  88502. #endif
  88503. #endif
  88504. /*
  88505. * The default capacity here doesn't matter too much. The buffer always grows
  88506. * to hold whatever is written to it. Usually the encoder will stop adding at
  88507. * a frame or metadata block, then write that out and clear the buffer for the
  88508. * next one.
  88509. */
  88510. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  88511. /* When growing, increment 4K at a time */
  88512. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  88513. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  88514. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  88515. #ifdef min
  88516. #undef min
  88517. #endif
  88518. #define min(x,y) ((x)<(y)?(x):(y))
  88519. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  88520. #ifdef _MSC_VER
  88521. #define FLAC__U64L(x) x
  88522. #else
  88523. #define FLAC__U64L(x) x##LLU
  88524. #endif
  88525. #ifndef FLaC__INLINE
  88526. #define FLaC__INLINE
  88527. #endif
  88528. struct FLAC__BitWriter {
  88529. bwword *buffer;
  88530. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  88531. unsigned capacity; /* capacity of buffer in words */
  88532. unsigned words; /* # of complete words in buffer */
  88533. unsigned bits; /* # of used bits in accum */
  88534. };
  88535. /* * WATCHOUT: The current implementation only grows the buffer. */
  88536. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  88537. {
  88538. unsigned new_capacity;
  88539. bwword *new_buffer;
  88540. FLAC__ASSERT(0 != bw);
  88541. FLAC__ASSERT(0 != bw->buffer);
  88542. /* calculate total words needed to store 'bits_to_add' additional bits */
  88543. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  88544. /* it's possible (due to pessimism in the growth estimation that
  88545. * leads to this call) that we don't actually need to grow
  88546. */
  88547. if(bw->capacity >= new_capacity)
  88548. return true;
  88549. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  88550. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  88551. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  88552. /* make sure we got everything right */
  88553. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  88554. FLAC__ASSERT(new_capacity > bw->capacity);
  88555. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  88556. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  88557. if(new_buffer == 0)
  88558. return false;
  88559. bw->buffer = new_buffer;
  88560. bw->capacity = new_capacity;
  88561. return true;
  88562. }
  88563. /***********************************************************************
  88564. *
  88565. * Class constructor/destructor
  88566. *
  88567. ***********************************************************************/
  88568. FLAC__BitWriter *FLAC__bitwriter_new(void)
  88569. {
  88570. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  88571. /* note that calloc() sets all members to 0 for us */
  88572. return bw;
  88573. }
  88574. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  88575. {
  88576. FLAC__ASSERT(0 != bw);
  88577. FLAC__bitwriter_free(bw);
  88578. free(bw);
  88579. }
  88580. /***********************************************************************
  88581. *
  88582. * Public class methods
  88583. *
  88584. ***********************************************************************/
  88585. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  88586. {
  88587. FLAC__ASSERT(0 != bw);
  88588. bw->words = bw->bits = 0;
  88589. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  88590. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  88591. if(bw->buffer == 0)
  88592. return false;
  88593. return true;
  88594. }
  88595. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  88596. {
  88597. FLAC__ASSERT(0 != bw);
  88598. if(0 != bw->buffer)
  88599. free(bw->buffer);
  88600. bw->buffer = 0;
  88601. bw->capacity = 0;
  88602. bw->words = bw->bits = 0;
  88603. }
  88604. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  88605. {
  88606. bw->words = bw->bits = 0;
  88607. }
  88608. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  88609. {
  88610. unsigned i, j;
  88611. if(bw == 0) {
  88612. fprintf(out, "bitwriter is NULL\n");
  88613. }
  88614. else {
  88615. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  88616. for(i = 0; i < bw->words; i++) {
  88617. fprintf(out, "%08X: ", i);
  88618. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  88619. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  88620. fprintf(out, "\n");
  88621. }
  88622. if(bw->bits > 0) {
  88623. fprintf(out, "%08X: ", i);
  88624. for(j = 0; j < bw->bits; j++)
  88625. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  88626. fprintf(out, "\n");
  88627. }
  88628. }
  88629. }
  88630. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  88631. {
  88632. const FLAC__byte *buffer;
  88633. size_t bytes;
  88634. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  88635. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  88636. return false;
  88637. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  88638. FLAC__bitwriter_release_buffer(bw);
  88639. return true;
  88640. }
  88641. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  88642. {
  88643. const FLAC__byte *buffer;
  88644. size_t bytes;
  88645. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  88646. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  88647. return false;
  88648. *crc = FLAC__crc8(buffer, bytes);
  88649. FLAC__bitwriter_release_buffer(bw);
  88650. return true;
  88651. }
  88652. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  88653. {
  88654. return ((bw->bits & 7) == 0);
  88655. }
  88656. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  88657. {
  88658. return FLAC__TOTAL_BITS(bw);
  88659. }
  88660. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  88661. {
  88662. FLAC__ASSERT((bw->bits & 7) == 0);
  88663. /* double protection */
  88664. if(bw->bits & 7)
  88665. return false;
  88666. /* if we have bits in the accumulator we have to flush those to the buffer first */
  88667. if(bw->bits) {
  88668. FLAC__ASSERT(bw->words <= bw->capacity);
  88669. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  88670. return false;
  88671. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  88672. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  88673. }
  88674. /* now we can just return what we have */
  88675. *buffer = (FLAC__byte*)bw->buffer;
  88676. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  88677. return true;
  88678. }
  88679. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  88680. {
  88681. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  88682. * get-mode' flag could be added everywhere and then cleared here
  88683. */
  88684. (void)bw;
  88685. }
  88686. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  88687. {
  88688. unsigned n;
  88689. FLAC__ASSERT(0 != bw);
  88690. FLAC__ASSERT(0 != bw->buffer);
  88691. if(bits == 0)
  88692. return true;
  88693. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  88694. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  88695. return false;
  88696. /* first part gets to word alignment */
  88697. if(bw->bits) {
  88698. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  88699. bw->accum <<= n;
  88700. bits -= n;
  88701. bw->bits += n;
  88702. if(bw->bits == FLAC__BITS_PER_WORD) {
  88703. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88704. bw->bits = 0;
  88705. }
  88706. else
  88707. return true;
  88708. }
  88709. /* do whole words */
  88710. while(bits >= FLAC__BITS_PER_WORD) {
  88711. bw->buffer[bw->words++] = 0;
  88712. bits -= FLAC__BITS_PER_WORD;
  88713. }
  88714. /* do any leftovers */
  88715. if(bits > 0) {
  88716. bw->accum = 0;
  88717. bw->bits = bits;
  88718. }
  88719. return true;
  88720. }
  88721. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  88722. {
  88723. register unsigned left;
  88724. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88725. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88726. FLAC__ASSERT(0 != bw);
  88727. FLAC__ASSERT(0 != bw->buffer);
  88728. FLAC__ASSERT(bits <= 32);
  88729. if(bits == 0)
  88730. return true;
  88731. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  88732. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  88733. return false;
  88734. left = FLAC__BITS_PER_WORD - bw->bits;
  88735. if(bits < left) {
  88736. bw->accum <<= bits;
  88737. bw->accum |= val;
  88738. bw->bits += bits;
  88739. }
  88740. else if(bw->bits) { /* WATCHOUT: if bw->bits == 0, left==FLAC__BITS_PER_WORD and bw->accum<<=left is a NOP instead of setting to 0 */
  88741. bw->accum <<= left;
  88742. bw->accum |= val >> (bw->bits = bits - left);
  88743. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88744. bw->accum = val;
  88745. }
  88746. else {
  88747. bw->accum = val;
  88748. bw->bits = 0;
  88749. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  88750. }
  88751. return true;
  88752. }
  88753. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  88754. {
  88755. /* zero-out unused bits */
  88756. if(bits < 32)
  88757. val &= (~(0xffffffff << bits));
  88758. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  88759. }
  88760. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  88761. {
  88762. /* this could be a little faster but it's not used for much */
  88763. if(bits > 32) {
  88764. return
  88765. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  88766. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  88767. }
  88768. else
  88769. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  88770. }
  88771. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  88772. {
  88773. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  88774. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  88775. return false;
  88776. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  88777. return false;
  88778. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  88779. return false;
  88780. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  88781. return false;
  88782. return true;
  88783. }
  88784. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  88785. {
  88786. unsigned i;
  88787. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  88788. for(i = 0; i < nvals; i++) {
  88789. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  88790. return false;
  88791. }
  88792. return true;
  88793. }
  88794. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  88795. {
  88796. if(val < 32)
  88797. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  88798. else
  88799. return
  88800. FLAC__bitwriter_write_zeroes(bw, val) &&
  88801. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  88802. }
  88803. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  88804. {
  88805. FLAC__uint32 uval;
  88806. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  88807. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  88808. uval = (val<<1) ^ (val>>31);
  88809. return 1 + parameter + (uval >> parameter);
  88810. }
  88811. #if 0 /* UNUSED */
  88812. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  88813. {
  88814. unsigned bits, msbs, uval;
  88815. unsigned k;
  88816. FLAC__ASSERT(parameter > 0);
  88817. /* fold signed to unsigned */
  88818. if(val < 0)
  88819. uval = (unsigned)(((-(++val)) << 1) + 1);
  88820. else
  88821. uval = (unsigned)(val << 1);
  88822. k = FLAC__bitmath_ilog2(parameter);
  88823. if(parameter == 1u<<k) {
  88824. FLAC__ASSERT(k <= 30);
  88825. msbs = uval >> k;
  88826. bits = 1 + k + msbs;
  88827. }
  88828. else {
  88829. unsigned q, r, d;
  88830. d = (1 << (k+1)) - parameter;
  88831. q = uval / parameter;
  88832. r = uval - (q * parameter);
  88833. bits = 1 + q + k;
  88834. if(r >= d)
  88835. bits++;
  88836. }
  88837. return bits;
  88838. }
  88839. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  88840. {
  88841. unsigned bits, msbs;
  88842. unsigned k;
  88843. FLAC__ASSERT(parameter > 0);
  88844. k = FLAC__bitmath_ilog2(parameter);
  88845. if(parameter == 1u<<k) {
  88846. FLAC__ASSERT(k <= 30);
  88847. msbs = uval >> k;
  88848. bits = 1 + k + msbs;
  88849. }
  88850. else {
  88851. unsigned q, r, d;
  88852. d = (1 << (k+1)) - parameter;
  88853. q = uval / parameter;
  88854. r = uval - (q * parameter);
  88855. bits = 1 + q + k;
  88856. if(r >= d)
  88857. bits++;
  88858. }
  88859. return bits;
  88860. }
  88861. #endif /* UNUSED */
  88862. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  88863. {
  88864. unsigned total_bits, interesting_bits, msbs;
  88865. FLAC__uint32 uval, pattern;
  88866. FLAC__ASSERT(0 != bw);
  88867. FLAC__ASSERT(0 != bw->buffer);
  88868. FLAC__ASSERT(parameter < 8*sizeof(uval));
  88869. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  88870. uval = (val<<1) ^ (val>>31);
  88871. msbs = uval >> parameter;
  88872. interesting_bits = 1 + parameter;
  88873. total_bits = interesting_bits + msbs;
  88874. pattern = 1 << parameter; /* the unary end bit */
  88875. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  88876. if(total_bits <= 32)
  88877. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  88878. else
  88879. return
  88880. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  88881. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  88882. }
  88883. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  88884. {
  88885. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  88886. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  88887. FLAC__uint32 uval;
  88888. unsigned left;
  88889. const unsigned lsbits = 1 + parameter;
  88890. unsigned msbits;
  88891. FLAC__ASSERT(0 != bw);
  88892. FLAC__ASSERT(0 != bw->buffer);
  88893. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  88894. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88895. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88896. while(nvals) {
  88897. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  88898. uval = (*vals<<1) ^ (*vals>>31);
  88899. msbits = uval >> parameter;
  88900. #if 0 /* OPT: can remove this special case if it doesn't make up for the extra compare (doesn't make a statistically significant difference with msvc or gcc/x86) */
  88901. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  88902. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  88903. bw->bits = bw->bits + msbits + lsbits;
  88904. uval |= mask1; /* set stop bit */
  88905. uval &= mask2; /* mask off unused top bits */
  88906. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  88907. bw->accum <<= msbits;
  88908. bw->accum <<= lsbits;
  88909. bw->accum |= uval;
  88910. if(bw->bits == FLAC__BITS_PER_WORD) {
  88911. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88912. bw->bits = 0;
  88913. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  88914. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  88915. FLAC__ASSERT(bw->capacity == bw->words);
  88916. return false;
  88917. }
  88918. }
  88919. }
  88920. else {
  88921. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  88922. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  88923. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  88924. bw->bits = bw->bits + msbits + lsbits;
  88925. uval |= mask1; /* set stop bit */
  88926. uval &= mask2; /* mask off unused top bits */
  88927. bw->accum <<= msbits + lsbits;
  88928. bw->accum |= uval;
  88929. }
  88930. else {
  88931. #endif
  88932. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  88933. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  88934. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  88935. return false;
  88936. if(msbits) {
  88937. /* first part gets to word alignment */
  88938. if(bw->bits) {
  88939. left = FLAC__BITS_PER_WORD - bw->bits;
  88940. if(msbits < left) {
  88941. bw->accum <<= msbits;
  88942. bw->bits += msbits;
  88943. goto break1;
  88944. }
  88945. else {
  88946. bw->accum <<= left;
  88947. msbits -= left;
  88948. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88949. bw->bits = 0;
  88950. }
  88951. }
  88952. /* do whole words */
  88953. while(msbits >= FLAC__BITS_PER_WORD) {
  88954. bw->buffer[bw->words++] = 0;
  88955. msbits -= FLAC__BITS_PER_WORD;
  88956. }
  88957. /* do any leftovers */
  88958. if(msbits > 0) {
  88959. bw->accum = 0;
  88960. bw->bits = msbits;
  88961. }
  88962. }
  88963. break1:
  88964. uval |= mask1; /* set stop bit */
  88965. uval &= mask2; /* mask off unused top bits */
  88966. left = FLAC__BITS_PER_WORD - bw->bits;
  88967. if(lsbits < left) {
  88968. bw->accum <<= lsbits;
  88969. bw->accum |= uval;
  88970. bw->bits += lsbits;
  88971. }
  88972. else {
  88973. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  88974. * be > lsbits (because of previous assertions) so it would have
  88975. * triggered the (lsbits<left) case above.
  88976. */
  88977. FLAC__ASSERT(bw->bits);
  88978. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  88979. bw->accum <<= left;
  88980. bw->accum |= uval >> (bw->bits = lsbits - left);
  88981. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88982. bw->accum = uval;
  88983. }
  88984. #if 1
  88985. }
  88986. #endif
  88987. vals++;
  88988. nvals--;
  88989. }
  88990. return true;
  88991. }
  88992. #if 0 /* UNUSED */
  88993. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  88994. {
  88995. unsigned total_bits, msbs, uval;
  88996. unsigned k;
  88997. FLAC__ASSERT(0 != bw);
  88998. FLAC__ASSERT(0 != bw->buffer);
  88999. FLAC__ASSERT(parameter > 0);
  89000. /* fold signed to unsigned */
  89001. if(val < 0)
  89002. uval = (unsigned)(((-(++val)) << 1) + 1);
  89003. else
  89004. uval = (unsigned)(val << 1);
  89005. k = FLAC__bitmath_ilog2(parameter);
  89006. if(parameter == 1u<<k) {
  89007. unsigned pattern;
  89008. FLAC__ASSERT(k <= 30);
  89009. msbs = uval >> k;
  89010. total_bits = 1 + k + msbs;
  89011. pattern = 1 << k; /* the unary end bit */
  89012. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  89013. if(total_bits <= 32) {
  89014. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  89015. return false;
  89016. }
  89017. else {
  89018. /* write the unary MSBs */
  89019. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  89020. return false;
  89021. /* write the unary end bit and binary LSBs */
  89022. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  89023. return false;
  89024. }
  89025. }
  89026. else {
  89027. unsigned q, r, d;
  89028. d = (1 << (k+1)) - parameter;
  89029. q = uval / parameter;
  89030. r = uval - (q * parameter);
  89031. /* write the unary MSBs */
  89032. if(!FLAC__bitwriter_write_zeroes(bw, q))
  89033. return false;
  89034. /* write the unary end bit */
  89035. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  89036. return false;
  89037. /* write the binary LSBs */
  89038. if(r >= d) {
  89039. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  89040. return false;
  89041. }
  89042. else {
  89043. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  89044. return false;
  89045. }
  89046. }
  89047. return true;
  89048. }
  89049. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  89050. {
  89051. unsigned total_bits, msbs;
  89052. unsigned k;
  89053. FLAC__ASSERT(0 != bw);
  89054. FLAC__ASSERT(0 != bw->buffer);
  89055. FLAC__ASSERT(parameter > 0);
  89056. k = FLAC__bitmath_ilog2(parameter);
  89057. if(parameter == 1u<<k) {
  89058. unsigned pattern;
  89059. FLAC__ASSERT(k <= 30);
  89060. msbs = uval >> k;
  89061. total_bits = 1 + k + msbs;
  89062. pattern = 1 << k; /* the unary end bit */
  89063. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  89064. if(total_bits <= 32) {
  89065. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  89066. return false;
  89067. }
  89068. else {
  89069. /* write the unary MSBs */
  89070. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  89071. return false;
  89072. /* write the unary end bit and binary LSBs */
  89073. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  89074. return false;
  89075. }
  89076. }
  89077. else {
  89078. unsigned q, r, d;
  89079. d = (1 << (k+1)) - parameter;
  89080. q = uval / parameter;
  89081. r = uval - (q * parameter);
  89082. /* write the unary MSBs */
  89083. if(!FLAC__bitwriter_write_zeroes(bw, q))
  89084. return false;
  89085. /* write the unary end bit */
  89086. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  89087. return false;
  89088. /* write the binary LSBs */
  89089. if(r >= d) {
  89090. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  89091. return false;
  89092. }
  89093. else {
  89094. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  89095. return false;
  89096. }
  89097. }
  89098. return true;
  89099. }
  89100. #endif /* UNUSED */
  89101. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  89102. {
  89103. FLAC__bool ok = 1;
  89104. FLAC__ASSERT(0 != bw);
  89105. FLAC__ASSERT(0 != bw->buffer);
  89106. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  89107. if(val < 0x80) {
  89108. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  89109. }
  89110. else if(val < 0x800) {
  89111. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  89112. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89113. }
  89114. else if(val < 0x10000) {
  89115. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  89116. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  89117. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89118. }
  89119. else if(val < 0x200000) {
  89120. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  89121. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  89122. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  89123. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89124. }
  89125. else if(val < 0x4000000) {
  89126. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  89127. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  89128. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  89129. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  89130. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89131. }
  89132. else {
  89133. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  89134. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  89135. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  89136. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  89137. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  89138. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89139. }
  89140. return ok;
  89141. }
  89142. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  89143. {
  89144. FLAC__bool ok = 1;
  89145. FLAC__ASSERT(0 != bw);
  89146. FLAC__ASSERT(0 != bw->buffer);
  89147. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  89148. if(val < 0x80) {
  89149. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  89150. }
  89151. else if(val < 0x800) {
  89152. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  89153. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89154. }
  89155. else if(val < 0x10000) {
  89156. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  89157. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  89158. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89159. }
  89160. else if(val < 0x200000) {
  89161. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  89162. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  89163. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  89164. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89165. }
  89166. else if(val < 0x4000000) {
  89167. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  89168. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  89169. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  89170. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  89171. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89172. }
  89173. else if(val < 0x80000000) {
  89174. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  89175. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  89176. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  89177. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  89178. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  89179. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89180. }
  89181. else {
  89182. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  89183. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  89184. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  89185. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  89186. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  89187. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  89188. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89189. }
  89190. return ok;
  89191. }
  89192. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  89193. {
  89194. /* 0-pad to byte boundary */
  89195. if(bw->bits & 7u)
  89196. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  89197. else
  89198. return true;
  89199. }
  89200. #endif
  89201. /********* End of inlined file: bitwriter.c *********/
  89202. /********* Start of inlined file: cpu.c *********/
  89203. /********* Start of inlined file: juce_FlacHeader.h *********/
  89204. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89205. // tasks..
  89206. #define VERSION "1.2.1"
  89207. #define FLAC__NO_DLL 1
  89208. #ifdef _MSC_VER
  89209. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89210. #endif
  89211. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89212. #define FLAC__SYS_DARWIN 1
  89213. #endif
  89214. /********* End of inlined file: juce_FlacHeader.h *********/
  89215. #if JUCE_USE_FLAC
  89216. #if HAVE_CONFIG_H
  89217. # include <config.h>
  89218. #endif
  89219. #include <stdlib.h>
  89220. #include <stdio.h>
  89221. #if defined FLAC__CPU_IA32
  89222. # include <signal.h>
  89223. #elif defined FLAC__CPU_PPC
  89224. # if !defined FLAC__NO_ASM
  89225. # if defined FLAC__SYS_DARWIN
  89226. # include <sys/sysctl.h>
  89227. # include <mach/mach.h>
  89228. # include <mach/mach_host.h>
  89229. # include <mach/host_info.h>
  89230. # include <mach/machine.h>
  89231. # ifndef CPU_SUBTYPE_POWERPC_970
  89232. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  89233. # endif
  89234. # else /* FLAC__SYS_DARWIN */
  89235. # include <signal.h>
  89236. # include <setjmp.h>
  89237. static sigjmp_buf jmpbuf;
  89238. static volatile sig_atomic_t canjump = 0;
  89239. static void sigill_handler (int sig)
  89240. {
  89241. if (!canjump) {
  89242. signal (sig, SIG_DFL);
  89243. raise (sig);
  89244. }
  89245. canjump = 0;
  89246. siglongjmp (jmpbuf, 1);
  89247. }
  89248. # endif /* FLAC__SYS_DARWIN */
  89249. # endif /* FLAC__NO_ASM */
  89250. #endif /* FLAC__CPU_PPC */
  89251. #if defined (__NetBSD__) || defined(__OpenBSD__)
  89252. #include <sys/param.h>
  89253. #include <sys/sysctl.h>
  89254. #include <machine/cpu.h>
  89255. #endif
  89256. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  89257. #include <sys/types.h>
  89258. #include <sys/sysctl.h>
  89259. #endif
  89260. #if defined(__APPLE__)
  89261. /* how to get sysctlbyname()? */
  89262. #endif
  89263. /* these are flags in EDX of CPUID AX=00000001 */
  89264. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  89265. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  89266. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  89267. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  89268. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  89269. /* these are flags in ECX of CPUID AX=00000001 */
  89270. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  89271. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  89272. /* these are flags in EDX of CPUID AX=80000001 */
  89273. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  89274. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  89275. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  89276. /*
  89277. * Extra stuff needed for detection of OS support for SSE on IA-32
  89278. */
  89279. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  89280. # if defined(__linux__)
  89281. /*
  89282. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  89283. * modify the return address to jump over the offending SSE instruction
  89284. * and also the operation following it that indicates the instruction
  89285. * executed successfully. In this way we use no global variables and
  89286. * stay thread-safe.
  89287. *
  89288. * 3 + 3 + 6:
  89289. * 3 bytes for "xorps xmm0,xmm0"
  89290. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  89291. * 6 bytes extra in case our estimate is wrong
  89292. * 12 bytes puts us in the NOP "landing zone"
  89293. */
  89294. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  89295. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  89296. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  89297. {
  89298. (void)signal;
  89299. sc.eip += 3 + 3 + 6;
  89300. }
  89301. # else
  89302. # include <sys/ucontext.h>
  89303. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  89304. {
  89305. (void)signal, (void)si;
  89306. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  89307. }
  89308. # endif
  89309. # elif defined(_MSC_VER)
  89310. # include <windows.h>
  89311. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  89312. # ifdef USE_TRY_CATCH_FLAVOR
  89313. # else
  89314. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  89315. {
  89316. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  89317. ep->ContextRecord->Eip += 3 + 3 + 6;
  89318. return EXCEPTION_CONTINUE_EXECUTION;
  89319. }
  89320. return EXCEPTION_CONTINUE_SEARCH;
  89321. }
  89322. # endif
  89323. # endif
  89324. #endif
  89325. void FLAC__cpu_info(FLAC__CPUInfo *info)
  89326. {
  89327. /*
  89328. * IA32-specific
  89329. */
  89330. #ifdef FLAC__CPU_IA32
  89331. info->type = FLAC__CPUINFO_TYPE_IA32;
  89332. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  89333. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  89334. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  89335. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  89336. info->data.ia32.cmov = false;
  89337. info->data.ia32.mmx = false;
  89338. info->data.ia32.fxsr = false;
  89339. info->data.ia32.sse = false;
  89340. info->data.ia32.sse2 = false;
  89341. info->data.ia32.sse3 = false;
  89342. info->data.ia32.ssse3 = false;
  89343. info->data.ia32._3dnow = false;
  89344. info->data.ia32.ext3dnow = false;
  89345. info->data.ia32.extmmx = false;
  89346. if(info->data.ia32.cpuid) {
  89347. /* http://www.sandpile.org/ia32/cpuid.htm */
  89348. FLAC__uint32 flags_edx, flags_ecx;
  89349. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  89350. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  89351. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  89352. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  89353. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  89354. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  89355. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  89356. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  89357. #ifdef FLAC__USE_3DNOW
  89358. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  89359. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  89360. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  89361. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  89362. #else
  89363. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  89364. #endif
  89365. #ifdef DEBUG
  89366. fprintf(stderr, "CPU info (IA-32):\n");
  89367. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  89368. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  89369. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  89370. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  89371. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  89372. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  89373. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  89374. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  89375. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  89376. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  89377. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  89378. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  89379. #endif
  89380. /*
  89381. * now have to check for OS support of SSE/SSE2
  89382. */
  89383. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  89384. #if defined FLAC__NO_SSE_OS
  89385. /* assume user knows better than us; turn it off */
  89386. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89387. #elif defined FLAC__SSE_OS
  89388. /* assume user knows better than us; leave as detected above */
  89389. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  89390. int sse = 0;
  89391. size_t len;
  89392. /* at least one of these must work: */
  89393. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  89394. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  89395. if(!sse)
  89396. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89397. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  89398. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  89399. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  89400. size_t len = sizeof(val);
  89401. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  89402. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89403. else { /* double-check SSE2 */
  89404. mib[1] = CPU_SSE2;
  89405. len = sizeof(val);
  89406. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  89407. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89408. }
  89409. # else
  89410. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89411. # endif
  89412. #elif defined(__linux__)
  89413. int sse = 0;
  89414. struct sigaction sigill_save;
  89415. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  89416. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  89417. #else
  89418. struct sigaction sigill_sse;
  89419. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  89420. __sigemptyset(&sigill_sse.sa_mask);
  89421. sigill_sse.sa_flags = SA_SIGINFO | SA_RESETHAND; /* SA_RESETHAND just in case our SIGILL return jump breaks, so we don't get stuck in a loop */
  89422. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  89423. #endif
  89424. {
  89425. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  89426. /* see sigill_handler_sse_os() for an explanation of the following: */
  89427. asm volatile (
  89428. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  89429. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  89430. "incl %0\n\t" /* SIGILL handler will jump over this */
  89431. /* landing zone */
  89432. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  89433. "nop\n\t"
  89434. "nop\n\t"
  89435. "nop\n\t"
  89436. "nop\n\t"
  89437. "nop\n\t"
  89438. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  89439. "nop\n\t"
  89440. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  89441. : "=r"(sse)
  89442. : "r"(sse)
  89443. );
  89444. sigaction(SIGILL, &sigill_save, NULL);
  89445. }
  89446. if(!sse)
  89447. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89448. #elif defined(_MSC_VER)
  89449. # ifdef USE_TRY_CATCH_FLAVOR
  89450. _try {
  89451. __asm {
  89452. # if _MSC_VER <= 1200
  89453. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  89454. _emit 0x0F
  89455. _emit 0x57
  89456. _emit 0xC0
  89457. # else
  89458. xorps xmm0,xmm0
  89459. # endif
  89460. }
  89461. }
  89462. _except(EXCEPTION_EXECUTE_HANDLER) {
  89463. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  89464. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89465. }
  89466. # else
  89467. int sse = 0;
  89468. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  89469. /* see GCC version above for explanation */
  89470. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  89471. /* http://www.codeproject.com/cpp/gccasm.asp */
  89472. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  89473. __asm {
  89474. # if _MSC_VER <= 1200
  89475. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  89476. _emit 0x0F
  89477. _emit 0x57
  89478. _emit 0xC0
  89479. # else
  89480. xorps xmm0,xmm0
  89481. # endif
  89482. inc sse
  89483. nop
  89484. nop
  89485. nop
  89486. nop
  89487. nop
  89488. nop
  89489. nop
  89490. nop
  89491. nop
  89492. }
  89493. SetUnhandledExceptionFilter(save);
  89494. if(!sse)
  89495. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89496. # endif
  89497. #else
  89498. /* no way to test, disable to be safe */
  89499. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89500. #endif
  89501. #ifdef DEBUG
  89502. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  89503. #endif
  89504. }
  89505. }
  89506. #else
  89507. info->use_asm = false;
  89508. #endif
  89509. /*
  89510. * PPC-specific
  89511. */
  89512. #elif defined FLAC__CPU_PPC
  89513. info->type = FLAC__CPUINFO_TYPE_PPC;
  89514. # if !defined FLAC__NO_ASM
  89515. info->use_asm = true;
  89516. # ifdef FLAC__USE_ALTIVEC
  89517. # if defined FLAC__SYS_DARWIN
  89518. {
  89519. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  89520. size_t len = sizeof(val);
  89521. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  89522. }
  89523. {
  89524. host_basic_info_data_t hostInfo;
  89525. mach_msg_type_number_t infoCount;
  89526. infoCount = HOST_BASIC_INFO_COUNT;
  89527. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  89528. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  89529. }
  89530. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  89531. {
  89532. /* no Darwin, do it the brute-force way */
  89533. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  89534. info->data.ppc.altivec = 0;
  89535. info->data.ppc.ppc64 = 0;
  89536. signal (SIGILL, sigill_handler);
  89537. canjump = 0;
  89538. if (!sigsetjmp (jmpbuf, 1)) {
  89539. canjump = 1;
  89540. asm volatile (
  89541. "mtspr 256, %0\n\t"
  89542. "vand %%v0, %%v0, %%v0"
  89543. :
  89544. : "r" (-1)
  89545. );
  89546. info->data.ppc.altivec = 1;
  89547. }
  89548. canjump = 0;
  89549. if (!sigsetjmp (jmpbuf, 1)) {
  89550. int x = 0;
  89551. canjump = 1;
  89552. /* PPC64 hardware implements the cntlzd instruction */
  89553. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  89554. info->data.ppc.ppc64 = 1;
  89555. }
  89556. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  89557. }
  89558. # endif
  89559. # else /* !FLAC__USE_ALTIVEC */
  89560. info->data.ppc.altivec = 0;
  89561. info->data.ppc.ppc64 = 0;
  89562. # endif
  89563. # else
  89564. info->use_asm = false;
  89565. # endif
  89566. /*
  89567. * unknown CPI
  89568. */
  89569. #else
  89570. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  89571. info->use_asm = false;
  89572. #endif
  89573. }
  89574. #endif
  89575. /********* End of inlined file: cpu.c *********/
  89576. /********* Start of inlined file: crc.c *********/
  89577. /********* Start of inlined file: juce_FlacHeader.h *********/
  89578. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89579. // tasks..
  89580. #define VERSION "1.2.1"
  89581. #define FLAC__NO_DLL 1
  89582. #ifdef _MSC_VER
  89583. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89584. #endif
  89585. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89586. #define FLAC__SYS_DARWIN 1
  89587. #endif
  89588. /********* End of inlined file: juce_FlacHeader.h *********/
  89589. #if JUCE_USE_FLAC
  89590. #if HAVE_CONFIG_H
  89591. # include <config.h>
  89592. #endif
  89593. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  89594. FLAC__byte const FLAC__crc8_table[256] = {
  89595. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  89596. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  89597. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  89598. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  89599. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  89600. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  89601. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  89602. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  89603. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  89604. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  89605. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  89606. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  89607. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  89608. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  89609. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  89610. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  89611. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  89612. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  89613. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  89614. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  89615. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  89616. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  89617. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  89618. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  89619. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  89620. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  89621. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  89622. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  89623. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  89624. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  89625. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  89626. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  89627. };
  89628. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  89629. unsigned FLAC__crc16_table[256] = {
  89630. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  89631. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  89632. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  89633. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  89634. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  89635. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  89636. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  89637. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  89638. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  89639. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  89640. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  89641. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  89642. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  89643. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  89644. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  89645. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  89646. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  89647. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  89648. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  89649. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  89650. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  89651. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  89652. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  89653. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  89654. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  89655. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  89656. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  89657. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  89658. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  89659. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  89660. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  89661. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  89662. };
  89663. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  89664. {
  89665. *crc = FLAC__crc8_table[*crc ^ data];
  89666. }
  89667. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  89668. {
  89669. while(len--)
  89670. *crc = FLAC__crc8_table[*crc ^ *data++];
  89671. }
  89672. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  89673. {
  89674. FLAC__uint8 crc = 0;
  89675. while(len--)
  89676. crc = FLAC__crc8_table[crc ^ *data++];
  89677. return crc;
  89678. }
  89679. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  89680. {
  89681. unsigned crc = 0;
  89682. while(len--)
  89683. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  89684. return crc;
  89685. }
  89686. #endif
  89687. /********* End of inlined file: crc.c *********/
  89688. /********* Start of inlined file: fixed.c *********/
  89689. /********* Start of inlined file: juce_FlacHeader.h *********/
  89690. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89691. // tasks..
  89692. #define VERSION "1.2.1"
  89693. #define FLAC__NO_DLL 1
  89694. #ifdef _MSC_VER
  89695. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89696. #endif
  89697. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89698. #define FLAC__SYS_DARWIN 1
  89699. #endif
  89700. /********* End of inlined file: juce_FlacHeader.h *********/
  89701. #if JUCE_USE_FLAC
  89702. #if HAVE_CONFIG_H
  89703. # include <config.h>
  89704. #endif
  89705. #include <math.h>
  89706. #include <string.h>
  89707. /********* Start of inlined file: fixed.h *********/
  89708. #ifndef FLAC__PRIVATE__FIXED_H
  89709. #define FLAC__PRIVATE__FIXED_H
  89710. #ifdef HAVE_CONFIG_H
  89711. #include <config.h>
  89712. #endif
  89713. /********* Start of inlined file: float.h *********/
  89714. #ifndef FLAC__PRIVATE__FLOAT_H
  89715. #define FLAC__PRIVATE__FLOAT_H
  89716. #ifdef HAVE_CONFIG_H
  89717. #include <config.h>
  89718. #endif
  89719. /*
  89720. * These typedefs make it easier to ensure that integer versions of
  89721. * the library really only contain integer operations. All the code
  89722. * in libFLAC should use FLAC__float and FLAC__double in place of
  89723. * float and double, and be protected by checks of the macro
  89724. * FLAC__INTEGER_ONLY_LIBRARY.
  89725. *
  89726. * FLAC__real is the basic floating point type used in LPC analysis.
  89727. */
  89728. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89729. typedef double FLAC__double;
  89730. typedef float FLAC__float;
  89731. /*
  89732. * WATCHOUT: changing FLAC__real will change the signatures of many
  89733. * functions that have assembly language equivalents and break them.
  89734. */
  89735. typedef float FLAC__real;
  89736. #else
  89737. /*
  89738. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  89739. * for the integer part and lower 16 bits for the fractional part.
  89740. */
  89741. typedef FLAC__int32 FLAC__fixedpoint;
  89742. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  89743. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  89744. extern const FLAC__fixedpoint FLAC__FP_ONE;
  89745. extern const FLAC__fixedpoint FLAC__FP_LN2;
  89746. extern const FLAC__fixedpoint FLAC__FP_E;
  89747. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  89748. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  89749. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  89750. /*
  89751. * FLAC__fixedpoint_log2()
  89752. * --------------------------------------------------------------------
  89753. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  89754. * algorithm by Knuth for x >= 1.0
  89755. *
  89756. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  89757. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  89758. *
  89759. * 'precision' roughly limits the number of iterations that are done;
  89760. * use (unsigned)(-1) for maximum precision.
  89761. *
  89762. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  89763. * function will punt and return 0.
  89764. *
  89765. * The return value will also have 'fracbits' fractional bits.
  89766. */
  89767. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  89768. #endif
  89769. #endif
  89770. /********* End of inlined file: float.h *********/
  89771. /********* Start of inlined file: format.h *********/
  89772. #ifndef FLAC__PRIVATE__FORMAT_H
  89773. #define FLAC__PRIVATE__FORMAT_H
  89774. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  89775. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  89776. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  89777. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  89778. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  89779. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  89780. #endif
  89781. /********* End of inlined file: format.h *********/
  89782. /*
  89783. * FLAC__fixed_compute_best_predictor()
  89784. * --------------------------------------------------------------------
  89785. * Compute the best fixed predictor and the expected bits-per-sample
  89786. * of the residual signal for each order. The _wide() version uses
  89787. * 64-bit integers which is statistically necessary when bits-per-
  89788. * sample + log2(blocksize) > 30
  89789. *
  89790. * IN data[0,data_len-1]
  89791. * IN data_len
  89792. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  89793. */
  89794. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89795. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  89796. # ifndef FLAC__NO_ASM
  89797. # ifdef FLAC__CPU_IA32
  89798. # ifdef FLAC__HAS_NASM
  89799. unsigned FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  89800. # endif
  89801. # endif
  89802. # endif
  89803. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  89804. #else
  89805. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  89806. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  89807. #endif
  89808. /*
  89809. * FLAC__fixed_compute_residual()
  89810. * --------------------------------------------------------------------
  89811. * Compute the residual signal obtained from sutracting the predicted
  89812. * signal from the original.
  89813. *
  89814. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  89815. * IN data_len length of original signal
  89816. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  89817. * OUT residual[0,data_len-1] residual signal
  89818. */
  89819. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  89820. /*
  89821. * FLAC__fixed_restore_signal()
  89822. * --------------------------------------------------------------------
  89823. * Restore the original signal by summing the residual and the
  89824. * predictor.
  89825. *
  89826. * IN residual[0,data_len-1] residual signal
  89827. * IN data_len length of original signal
  89828. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  89829. * *** IMPORTANT: the caller must pass in the historical samples:
  89830. * IN data[-order,-1] previously-reconstructed historical samples
  89831. * OUT data[0,data_len-1] original signal
  89832. */
  89833. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  89834. #endif
  89835. /********* End of inlined file: fixed.h *********/
  89836. #ifndef M_LN2
  89837. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  89838. #define M_LN2 0.69314718055994530942
  89839. #endif
  89840. #ifdef min
  89841. #undef min
  89842. #endif
  89843. #define min(x,y) ((x) < (y)? (x) : (y))
  89844. #ifdef local_abs
  89845. #undef local_abs
  89846. #endif
  89847. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  89848. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  89849. /* rbps stands for residual bits per sample
  89850. *
  89851. * (ln(2) * err)
  89852. * rbps = log (-----------)
  89853. * 2 ( n )
  89854. */
  89855. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  89856. {
  89857. FLAC__uint32 rbps;
  89858. unsigned bits; /* the number of bits required to represent a number */
  89859. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  89860. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  89861. FLAC__ASSERT(err > 0);
  89862. FLAC__ASSERT(n > 0);
  89863. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  89864. if(err <= n)
  89865. return 0;
  89866. /*
  89867. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  89868. * These allow us later to know we won't lose too much precision in the
  89869. * fixed-point division (err<<fracbits)/n.
  89870. */
  89871. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  89872. err <<= fracbits;
  89873. err /= n;
  89874. /* err now holds err/n with fracbits fractional bits */
  89875. /*
  89876. * Whittle err down to 16 bits max. 16 significant bits is enough for
  89877. * our purposes.
  89878. */
  89879. FLAC__ASSERT(err > 0);
  89880. bits = FLAC__bitmath_ilog2(err)+1;
  89881. if(bits > 16) {
  89882. err >>= (bits-16);
  89883. fracbits -= (bits-16);
  89884. }
  89885. rbps = (FLAC__uint32)err;
  89886. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  89887. rbps *= FLAC__FP_LN2;
  89888. fracbits += 16;
  89889. FLAC__ASSERT(fracbits >= 0);
  89890. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  89891. {
  89892. const int f = fracbits & 3;
  89893. if(f) {
  89894. rbps >>= f;
  89895. fracbits -= f;
  89896. }
  89897. }
  89898. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  89899. if(rbps == 0)
  89900. return 0;
  89901. /*
  89902. * The return value must have 16 fractional bits. Since the whole part
  89903. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  89904. * must be >= -3, these assertion allows us to be able to shift rbps
  89905. * left if necessary to get 16 fracbits without losing any bits of the
  89906. * whole part of rbps.
  89907. *
  89908. * There is a slight chance due to accumulated error that the whole part
  89909. * will require 6 bits, so we use 6 in the assertion. Really though as
  89910. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  89911. */
  89912. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  89913. FLAC__ASSERT(fracbits >= -3);
  89914. /* now shift the decimal point into place */
  89915. if(fracbits < 16)
  89916. return rbps << (16-fracbits);
  89917. else if(fracbits > 16)
  89918. return rbps >> (fracbits-16);
  89919. else
  89920. return rbps;
  89921. }
  89922. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  89923. {
  89924. FLAC__uint32 rbps;
  89925. unsigned bits; /* the number of bits required to represent a number */
  89926. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  89927. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  89928. FLAC__ASSERT(err > 0);
  89929. FLAC__ASSERT(n > 0);
  89930. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  89931. if(err <= n)
  89932. return 0;
  89933. /*
  89934. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  89935. * These allow us later to know we won't lose too much precision in the
  89936. * fixed-point division (err<<fracbits)/n.
  89937. */
  89938. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  89939. err <<= fracbits;
  89940. err /= n;
  89941. /* err now holds err/n with fracbits fractional bits */
  89942. /*
  89943. * Whittle err down to 16 bits max. 16 significant bits is enough for
  89944. * our purposes.
  89945. */
  89946. FLAC__ASSERT(err > 0);
  89947. bits = FLAC__bitmath_ilog2_wide(err)+1;
  89948. if(bits > 16) {
  89949. err >>= (bits-16);
  89950. fracbits -= (bits-16);
  89951. }
  89952. rbps = (FLAC__uint32)err;
  89953. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  89954. rbps *= FLAC__FP_LN2;
  89955. fracbits += 16;
  89956. FLAC__ASSERT(fracbits >= 0);
  89957. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  89958. {
  89959. const int f = fracbits & 3;
  89960. if(f) {
  89961. rbps >>= f;
  89962. fracbits -= f;
  89963. }
  89964. }
  89965. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  89966. if(rbps == 0)
  89967. return 0;
  89968. /*
  89969. * The return value must have 16 fractional bits. Since the whole part
  89970. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  89971. * must be >= -3, these assertion allows us to be able to shift rbps
  89972. * left if necessary to get 16 fracbits without losing any bits of the
  89973. * whole part of rbps.
  89974. *
  89975. * There is a slight chance due to accumulated error that the whole part
  89976. * will require 6 bits, so we use 6 in the assertion. Really though as
  89977. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  89978. */
  89979. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  89980. FLAC__ASSERT(fracbits >= -3);
  89981. /* now shift the decimal point into place */
  89982. if(fracbits < 16)
  89983. return rbps << (16-fracbits);
  89984. else if(fracbits > 16)
  89985. return rbps >> (fracbits-16);
  89986. else
  89987. return rbps;
  89988. }
  89989. #endif
  89990. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89991. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  89992. #else
  89993. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  89994. #endif
  89995. {
  89996. FLAC__int32 last_error_0 = data[-1];
  89997. FLAC__int32 last_error_1 = data[-1] - data[-2];
  89998. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  89999. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  90000. FLAC__int32 error, save;
  90001. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  90002. unsigned i, order;
  90003. for(i = 0; i < data_len; i++) {
  90004. error = data[i] ; total_error_0 += local_abs(error); save = error;
  90005. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  90006. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  90007. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  90008. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  90009. }
  90010. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  90011. order = 0;
  90012. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  90013. order = 1;
  90014. else if(total_error_2 < min(total_error_3, total_error_4))
  90015. order = 2;
  90016. else if(total_error_3 < total_error_4)
  90017. order = 3;
  90018. else
  90019. order = 4;
  90020. /* Estimate the expected number of bits per residual signal sample. */
  90021. /* 'total_error*' is linearly related to the variance of the residual */
  90022. /* signal, so we use it directly to compute E(|x|) */
  90023. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  90024. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  90025. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  90026. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  90027. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  90028. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90029. residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0);
  90030. residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0);
  90031. residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0);
  90032. residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0);
  90033. residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0);
  90034. #else
  90035. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  90036. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  90037. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  90038. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  90039. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  90040. #endif
  90041. return order;
  90042. }
  90043. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90044. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  90045. #else
  90046. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  90047. #endif
  90048. {
  90049. FLAC__int32 last_error_0 = data[-1];
  90050. FLAC__int32 last_error_1 = data[-1] - data[-2];
  90051. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  90052. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  90053. FLAC__int32 error, save;
  90054. /* total_error_* are 64-bits to avoid overflow when encoding
  90055. * erratic signals when the bits-per-sample and blocksize are
  90056. * large.
  90057. */
  90058. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  90059. unsigned i, order;
  90060. for(i = 0; i < data_len; i++) {
  90061. error = data[i] ; total_error_0 += local_abs(error); save = error;
  90062. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  90063. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  90064. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  90065. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  90066. }
  90067. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  90068. order = 0;
  90069. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  90070. order = 1;
  90071. else if(total_error_2 < min(total_error_3, total_error_4))
  90072. order = 2;
  90073. else if(total_error_3 < total_error_4)
  90074. order = 3;
  90075. else
  90076. order = 4;
  90077. /* Estimate the expected number of bits per residual signal sample. */
  90078. /* 'total_error*' is linearly related to the variance of the residual */
  90079. /* signal, so we use it directly to compute E(|x|) */
  90080. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  90081. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  90082. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  90083. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  90084. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  90085. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90086. #if defined _MSC_VER || defined __MINGW32__
  90087. /* with MSVC you have to spoon feed it the casting */
  90088. residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0);
  90089. residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0);
  90090. residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0);
  90091. residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0);
  90092. residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0);
  90093. #else
  90094. residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0);
  90095. residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0);
  90096. residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0);
  90097. residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0);
  90098. residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0);
  90099. #endif
  90100. #else
  90101. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  90102. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  90103. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  90104. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  90105. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  90106. #endif
  90107. return order;
  90108. }
  90109. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  90110. {
  90111. const int idata_len = (int)data_len;
  90112. int i;
  90113. switch(order) {
  90114. case 0:
  90115. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  90116. memcpy(residual, data, sizeof(residual[0])*data_len);
  90117. break;
  90118. case 1:
  90119. for(i = 0; i < idata_len; i++)
  90120. residual[i] = data[i] - data[i-1];
  90121. break;
  90122. case 2:
  90123. for(i = 0; i < idata_len; i++)
  90124. #if 1 /* OPT: may be faster with some compilers on some systems */
  90125. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  90126. #else
  90127. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  90128. #endif
  90129. break;
  90130. case 3:
  90131. for(i = 0; i < idata_len; i++)
  90132. #if 1 /* OPT: may be faster with some compilers on some systems */
  90133. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  90134. #else
  90135. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  90136. #endif
  90137. break;
  90138. case 4:
  90139. for(i = 0; i < idata_len; i++)
  90140. #if 1 /* OPT: may be faster with some compilers on some systems */
  90141. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  90142. #else
  90143. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  90144. #endif
  90145. break;
  90146. default:
  90147. FLAC__ASSERT(0);
  90148. }
  90149. }
  90150. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  90151. {
  90152. int i, idata_len = (int)data_len;
  90153. switch(order) {
  90154. case 0:
  90155. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  90156. memcpy(data, residual, sizeof(residual[0])*data_len);
  90157. break;
  90158. case 1:
  90159. for(i = 0; i < idata_len; i++)
  90160. data[i] = residual[i] + data[i-1];
  90161. break;
  90162. case 2:
  90163. for(i = 0; i < idata_len; i++)
  90164. #if 1 /* OPT: may be faster with some compilers on some systems */
  90165. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  90166. #else
  90167. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  90168. #endif
  90169. break;
  90170. case 3:
  90171. for(i = 0; i < idata_len; i++)
  90172. #if 1 /* OPT: may be faster with some compilers on some systems */
  90173. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  90174. #else
  90175. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  90176. #endif
  90177. break;
  90178. case 4:
  90179. for(i = 0; i < idata_len; i++)
  90180. #if 1 /* OPT: may be faster with some compilers on some systems */
  90181. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  90182. #else
  90183. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  90184. #endif
  90185. break;
  90186. default:
  90187. FLAC__ASSERT(0);
  90188. }
  90189. }
  90190. #endif
  90191. /********* End of inlined file: fixed.c *********/
  90192. /********* Start of inlined file: float.c *********/
  90193. /********* Start of inlined file: juce_FlacHeader.h *********/
  90194. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90195. // tasks..
  90196. #define VERSION "1.2.1"
  90197. #define FLAC__NO_DLL 1
  90198. #ifdef _MSC_VER
  90199. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90200. #endif
  90201. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90202. #define FLAC__SYS_DARWIN 1
  90203. #endif
  90204. /********* End of inlined file: juce_FlacHeader.h *********/
  90205. #if JUCE_USE_FLAC
  90206. #if HAVE_CONFIG_H
  90207. # include <config.h>
  90208. #endif
  90209. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  90210. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  90211. #ifdef _MSC_VER
  90212. #define FLAC__U64L(x) x
  90213. #else
  90214. #define FLAC__U64L(x) x##LLU
  90215. #endif
  90216. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  90217. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  90218. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  90219. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  90220. const FLAC__fixedpoint FLAC__FP_E = 178145;
  90221. /* Lookup tables for Knuth's logarithm algorithm */
  90222. #define LOG2_LOOKUP_PRECISION 16
  90223. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  90224. {
  90225. /*
  90226. * 0 fraction bits
  90227. */
  90228. /* undefined */ 0x00000000,
  90229. /* lg(2/1) = */ 0x00000001,
  90230. /* lg(4/3) = */ 0x00000000,
  90231. /* lg(8/7) = */ 0x00000000,
  90232. /* lg(16/15) = */ 0x00000000,
  90233. /* lg(32/31) = */ 0x00000000,
  90234. /* lg(64/63) = */ 0x00000000,
  90235. /* lg(128/127) = */ 0x00000000,
  90236. /* lg(256/255) = */ 0x00000000,
  90237. /* lg(512/511) = */ 0x00000000,
  90238. /* lg(1024/1023) = */ 0x00000000,
  90239. /* lg(2048/2047) = */ 0x00000000,
  90240. /* lg(4096/4095) = */ 0x00000000,
  90241. /* lg(8192/8191) = */ 0x00000000,
  90242. /* lg(16384/16383) = */ 0x00000000,
  90243. /* lg(32768/32767) = */ 0x00000000
  90244. },
  90245. {
  90246. /*
  90247. * 4 fraction bits
  90248. */
  90249. /* undefined */ 0x00000000,
  90250. /* lg(2/1) = */ 0x00000010,
  90251. /* lg(4/3) = */ 0x00000007,
  90252. /* lg(8/7) = */ 0x00000003,
  90253. /* lg(16/15) = */ 0x00000001,
  90254. /* lg(32/31) = */ 0x00000001,
  90255. /* lg(64/63) = */ 0x00000000,
  90256. /* lg(128/127) = */ 0x00000000,
  90257. /* lg(256/255) = */ 0x00000000,
  90258. /* lg(512/511) = */ 0x00000000,
  90259. /* lg(1024/1023) = */ 0x00000000,
  90260. /* lg(2048/2047) = */ 0x00000000,
  90261. /* lg(4096/4095) = */ 0x00000000,
  90262. /* lg(8192/8191) = */ 0x00000000,
  90263. /* lg(16384/16383) = */ 0x00000000,
  90264. /* lg(32768/32767) = */ 0x00000000
  90265. },
  90266. {
  90267. /*
  90268. * 8 fraction bits
  90269. */
  90270. /* undefined */ 0x00000000,
  90271. /* lg(2/1) = */ 0x00000100,
  90272. /* lg(4/3) = */ 0x0000006a,
  90273. /* lg(8/7) = */ 0x00000031,
  90274. /* lg(16/15) = */ 0x00000018,
  90275. /* lg(32/31) = */ 0x0000000c,
  90276. /* lg(64/63) = */ 0x00000006,
  90277. /* lg(128/127) = */ 0x00000003,
  90278. /* lg(256/255) = */ 0x00000001,
  90279. /* lg(512/511) = */ 0x00000001,
  90280. /* lg(1024/1023) = */ 0x00000000,
  90281. /* lg(2048/2047) = */ 0x00000000,
  90282. /* lg(4096/4095) = */ 0x00000000,
  90283. /* lg(8192/8191) = */ 0x00000000,
  90284. /* lg(16384/16383) = */ 0x00000000,
  90285. /* lg(32768/32767) = */ 0x00000000
  90286. },
  90287. {
  90288. /*
  90289. * 12 fraction bits
  90290. */
  90291. /* undefined */ 0x00000000,
  90292. /* lg(2/1) = */ 0x00001000,
  90293. /* lg(4/3) = */ 0x000006a4,
  90294. /* lg(8/7) = */ 0x00000315,
  90295. /* lg(16/15) = */ 0x0000017d,
  90296. /* lg(32/31) = */ 0x000000bc,
  90297. /* lg(64/63) = */ 0x0000005d,
  90298. /* lg(128/127) = */ 0x0000002e,
  90299. /* lg(256/255) = */ 0x00000017,
  90300. /* lg(512/511) = */ 0x0000000c,
  90301. /* lg(1024/1023) = */ 0x00000006,
  90302. /* lg(2048/2047) = */ 0x00000003,
  90303. /* lg(4096/4095) = */ 0x00000001,
  90304. /* lg(8192/8191) = */ 0x00000001,
  90305. /* lg(16384/16383) = */ 0x00000000,
  90306. /* lg(32768/32767) = */ 0x00000000
  90307. },
  90308. {
  90309. /*
  90310. * 16 fraction bits
  90311. */
  90312. /* undefined */ 0x00000000,
  90313. /* lg(2/1) = */ 0x00010000,
  90314. /* lg(4/3) = */ 0x00006a40,
  90315. /* lg(8/7) = */ 0x00003151,
  90316. /* lg(16/15) = */ 0x000017d6,
  90317. /* lg(32/31) = */ 0x00000bba,
  90318. /* lg(64/63) = */ 0x000005d1,
  90319. /* lg(128/127) = */ 0x000002e6,
  90320. /* lg(256/255) = */ 0x00000172,
  90321. /* lg(512/511) = */ 0x000000b9,
  90322. /* lg(1024/1023) = */ 0x0000005c,
  90323. /* lg(2048/2047) = */ 0x0000002e,
  90324. /* lg(4096/4095) = */ 0x00000017,
  90325. /* lg(8192/8191) = */ 0x0000000c,
  90326. /* lg(16384/16383) = */ 0x00000006,
  90327. /* lg(32768/32767) = */ 0x00000003
  90328. },
  90329. {
  90330. /*
  90331. * 20 fraction bits
  90332. */
  90333. /* undefined */ 0x00000000,
  90334. /* lg(2/1) = */ 0x00100000,
  90335. /* lg(4/3) = */ 0x0006a3fe,
  90336. /* lg(8/7) = */ 0x00031513,
  90337. /* lg(16/15) = */ 0x00017d60,
  90338. /* lg(32/31) = */ 0x0000bb9d,
  90339. /* lg(64/63) = */ 0x00005d10,
  90340. /* lg(128/127) = */ 0x00002e59,
  90341. /* lg(256/255) = */ 0x00001721,
  90342. /* lg(512/511) = */ 0x00000b8e,
  90343. /* lg(1024/1023) = */ 0x000005c6,
  90344. /* lg(2048/2047) = */ 0x000002e3,
  90345. /* lg(4096/4095) = */ 0x00000171,
  90346. /* lg(8192/8191) = */ 0x000000b9,
  90347. /* lg(16384/16383) = */ 0x0000005c,
  90348. /* lg(32768/32767) = */ 0x0000002e
  90349. },
  90350. {
  90351. /*
  90352. * 24 fraction bits
  90353. */
  90354. /* undefined */ 0x00000000,
  90355. /* lg(2/1) = */ 0x01000000,
  90356. /* lg(4/3) = */ 0x006a3fe6,
  90357. /* lg(8/7) = */ 0x00315130,
  90358. /* lg(16/15) = */ 0x0017d605,
  90359. /* lg(32/31) = */ 0x000bb9ca,
  90360. /* lg(64/63) = */ 0x0005d0fc,
  90361. /* lg(128/127) = */ 0x0002e58f,
  90362. /* lg(256/255) = */ 0x0001720e,
  90363. /* lg(512/511) = */ 0x0000b8d8,
  90364. /* lg(1024/1023) = */ 0x00005c61,
  90365. /* lg(2048/2047) = */ 0x00002e2d,
  90366. /* lg(4096/4095) = */ 0x00001716,
  90367. /* lg(8192/8191) = */ 0x00000b8b,
  90368. /* lg(16384/16383) = */ 0x000005c5,
  90369. /* lg(32768/32767) = */ 0x000002e3
  90370. },
  90371. {
  90372. /*
  90373. * 28 fraction bits
  90374. */
  90375. /* undefined */ 0x00000000,
  90376. /* lg(2/1) = */ 0x10000000,
  90377. /* lg(4/3) = */ 0x06a3fe5c,
  90378. /* lg(8/7) = */ 0x03151301,
  90379. /* lg(16/15) = */ 0x017d6049,
  90380. /* lg(32/31) = */ 0x00bb9ca6,
  90381. /* lg(64/63) = */ 0x005d0fba,
  90382. /* lg(128/127) = */ 0x002e58f7,
  90383. /* lg(256/255) = */ 0x001720da,
  90384. /* lg(512/511) = */ 0x000b8d87,
  90385. /* lg(1024/1023) = */ 0x0005c60b,
  90386. /* lg(2048/2047) = */ 0x0002e2d7,
  90387. /* lg(4096/4095) = */ 0x00017160,
  90388. /* lg(8192/8191) = */ 0x0000b8ad,
  90389. /* lg(16384/16383) = */ 0x00005c56,
  90390. /* lg(32768/32767) = */ 0x00002e2b
  90391. }
  90392. };
  90393. #if 0
  90394. static const FLAC__uint64 log2_lookup_wide[] = {
  90395. {
  90396. /*
  90397. * 32 fraction bits
  90398. */
  90399. /* undefined */ 0x00000000,
  90400. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  90401. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  90402. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  90403. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  90404. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  90405. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  90406. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  90407. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  90408. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  90409. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  90410. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  90411. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  90412. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  90413. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  90414. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  90415. },
  90416. {
  90417. /*
  90418. * 48 fraction bits
  90419. */
  90420. /* undefined */ 0x00000000,
  90421. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  90422. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  90423. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  90424. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  90425. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  90426. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  90427. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  90428. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  90429. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  90430. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  90431. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  90432. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  90433. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  90434. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  90435. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  90436. }
  90437. };
  90438. #endif
  90439. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  90440. {
  90441. const FLAC__uint32 ONE = (1u << fracbits);
  90442. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  90443. FLAC__ASSERT(fracbits < 32);
  90444. FLAC__ASSERT((fracbits & 0x3) == 0);
  90445. if(x < ONE)
  90446. return 0;
  90447. if(precision > LOG2_LOOKUP_PRECISION)
  90448. precision = LOG2_LOOKUP_PRECISION;
  90449. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  90450. {
  90451. FLAC__uint32 y = 0;
  90452. FLAC__uint32 z = x >> 1, k = 1;
  90453. while (x > ONE && k < precision) {
  90454. if (x - z >= ONE) {
  90455. x -= z;
  90456. z = x >> k;
  90457. y += table[k];
  90458. }
  90459. else {
  90460. z >>= 1;
  90461. k++;
  90462. }
  90463. }
  90464. return y;
  90465. }
  90466. }
  90467. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  90468. #endif
  90469. /********* End of inlined file: float.c *********/
  90470. /********* Start of inlined file: format.c *********/
  90471. /********* Start of inlined file: juce_FlacHeader.h *********/
  90472. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90473. // tasks..
  90474. #define VERSION "1.2.1"
  90475. #define FLAC__NO_DLL 1
  90476. #ifdef _MSC_VER
  90477. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90478. #endif
  90479. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90480. #define FLAC__SYS_DARWIN 1
  90481. #endif
  90482. /********* End of inlined file: juce_FlacHeader.h *********/
  90483. #if JUCE_USE_FLAC
  90484. #if HAVE_CONFIG_H
  90485. # include <config.h>
  90486. #endif
  90487. #include <stdio.h>
  90488. #include <stdlib.h> /* for qsort() */
  90489. #include <string.h> /* for memset() */
  90490. #ifndef FLaC__INLINE
  90491. #define FLaC__INLINE
  90492. #endif
  90493. #ifdef min
  90494. #undef min
  90495. #endif
  90496. #define min(a,b) ((a)<(b)?(a):(b))
  90497. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  90498. #ifdef _MSC_VER
  90499. #define FLAC__U64L(x) x
  90500. #else
  90501. #define FLAC__U64L(x) x##LLU
  90502. #endif
  90503. /* VERSION should come from configure */
  90504. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  90505. ;
  90506. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  90507. /* yet one more hack because of MSVC6: */
  90508. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  90509. #else
  90510. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  90511. #endif
  90512. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  90513. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  90514. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  90515. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  90516. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  90517. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  90518. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  90519. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  90520. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  90521. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  90522. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  90523. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  90524. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  90525. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  90526. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  90527. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  90528. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  90529. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  90530. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  90531. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  90532. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  90533. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  90534. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  90535. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  90536. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  90537. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  90538. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  90539. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  90540. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  90541. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  90542. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  90543. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  90544. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  90545. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  90546. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  90547. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  90548. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  90549. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  90550. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  90551. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  90552. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  90553. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  90554. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  90555. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  90556. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  90557. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  90558. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  90559. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  90560. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  90561. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  90562. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  90563. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  90564. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  90565. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  90566. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  90567. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  90568. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  90569. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  90570. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  90571. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  90572. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  90573. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  90574. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  90575. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  90576. "PARTITIONED_RICE",
  90577. "PARTITIONED_RICE2"
  90578. };
  90579. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  90580. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  90581. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  90582. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  90583. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  90584. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  90585. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  90586. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  90587. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  90588. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  90589. "CONSTANT",
  90590. "VERBATIM",
  90591. "FIXED",
  90592. "LPC"
  90593. };
  90594. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  90595. "INDEPENDENT",
  90596. "LEFT_SIDE",
  90597. "RIGHT_SIDE",
  90598. "MID_SIDE"
  90599. };
  90600. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  90601. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  90602. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  90603. };
  90604. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  90605. "STREAMINFO",
  90606. "PADDING",
  90607. "APPLICATION",
  90608. "SEEKTABLE",
  90609. "VORBIS_COMMENT",
  90610. "CUESHEET",
  90611. "PICTURE"
  90612. };
  90613. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  90614. "Other",
  90615. "32x32 pixels 'file icon' (PNG only)",
  90616. "Other file icon",
  90617. "Cover (front)",
  90618. "Cover (back)",
  90619. "Leaflet page",
  90620. "Media (e.g. label side of CD)",
  90621. "Lead artist/lead performer/soloist",
  90622. "Artist/performer",
  90623. "Conductor",
  90624. "Band/Orchestra",
  90625. "Composer",
  90626. "Lyricist/text writer",
  90627. "Recording Location",
  90628. "During recording",
  90629. "During performance",
  90630. "Movie/video screen capture",
  90631. "A bright coloured fish",
  90632. "Illustration",
  90633. "Band/artist logotype",
  90634. "Publisher/Studio logotype"
  90635. };
  90636. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  90637. {
  90638. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  90639. return false;
  90640. }
  90641. else
  90642. return true;
  90643. }
  90644. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  90645. {
  90646. if(
  90647. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  90648. (
  90649. sample_rate >= (1u << 16) &&
  90650. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  90651. )
  90652. ) {
  90653. return false;
  90654. }
  90655. else
  90656. return true;
  90657. }
  90658. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  90659. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  90660. {
  90661. unsigned i;
  90662. FLAC__uint64 prev_sample_number = 0;
  90663. FLAC__bool got_prev = false;
  90664. FLAC__ASSERT(0 != seek_table);
  90665. for(i = 0; i < seek_table->num_points; i++) {
  90666. if(got_prev) {
  90667. if(
  90668. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  90669. seek_table->points[i].sample_number <= prev_sample_number
  90670. )
  90671. return false;
  90672. }
  90673. prev_sample_number = seek_table->points[i].sample_number;
  90674. got_prev = true;
  90675. }
  90676. return true;
  90677. }
  90678. /* used as the sort predicate for qsort() */
  90679. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  90680. {
  90681. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  90682. if(l->sample_number == r->sample_number)
  90683. return 0;
  90684. else if(l->sample_number < r->sample_number)
  90685. return -1;
  90686. else
  90687. return 1;
  90688. }
  90689. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  90690. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  90691. {
  90692. unsigned i, j;
  90693. FLAC__bool first;
  90694. FLAC__ASSERT(0 != seek_table);
  90695. /* sort the seekpoints */
  90696. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  90697. /* uniquify the seekpoints */
  90698. first = true;
  90699. for(i = j = 0; i < seek_table->num_points; i++) {
  90700. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  90701. if(!first) {
  90702. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  90703. continue;
  90704. }
  90705. }
  90706. first = false;
  90707. seek_table->points[j++] = seek_table->points[i];
  90708. }
  90709. for(i = j; i < seek_table->num_points; i++) {
  90710. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  90711. seek_table->points[i].stream_offset = 0;
  90712. seek_table->points[i].frame_samples = 0;
  90713. }
  90714. return j;
  90715. }
  90716. /*
  90717. * also disallows non-shortest-form encodings, c.f.
  90718. * http://www.unicode.org/versions/corrigendum1.html
  90719. * and a more clear explanation at the end of this section:
  90720. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  90721. */
  90722. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  90723. {
  90724. FLAC__ASSERT(0 != utf8);
  90725. if ((utf8[0] & 0x80) == 0) {
  90726. return 1;
  90727. }
  90728. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  90729. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  90730. return 0;
  90731. return 2;
  90732. }
  90733. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  90734. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  90735. return 0;
  90736. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  90737. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  90738. return 0;
  90739. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  90740. return 0;
  90741. return 3;
  90742. }
  90743. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  90744. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  90745. return 0;
  90746. return 4;
  90747. }
  90748. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  90749. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  90750. return 0;
  90751. return 5;
  90752. }
  90753. else if ((utf8[0] & 0xFE) == 0xFC && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80 && (utf8[5] & 0xC0) == 0x80) {
  90754. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  90755. return 0;
  90756. return 6;
  90757. }
  90758. else {
  90759. return 0;
  90760. }
  90761. }
  90762. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  90763. {
  90764. char c;
  90765. for(c = *name; c; c = *(++name))
  90766. if(c < 0x20 || c == 0x3d || c > 0x7d)
  90767. return false;
  90768. return true;
  90769. }
  90770. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  90771. {
  90772. if(length == (unsigned)(-1)) {
  90773. while(*value) {
  90774. unsigned n = utf8len_(value);
  90775. if(n == 0)
  90776. return false;
  90777. value += n;
  90778. }
  90779. }
  90780. else {
  90781. const FLAC__byte *end = value + length;
  90782. while(value < end) {
  90783. unsigned n = utf8len_(value);
  90784. if(n == 0)
  90785. return false;
  90786. value += n;
  90787. }
  90788. if(value != end)
  90789. return false;
  90790. }
  90791. return true;
  90792. }
  90793. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  90794. {
  90795. const FLAC__byte *s, *end;
  90796. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  90797. if(*s < 0x20 || *s > 0x7D)
  90798. return false;
  90799. }
  90800. if(s == end)
  90801. return false;
  90802. s++; /* skip '=' */
  90803. while(s < end) {
  90804. unsigned n = utf8len_(s);
  90805. if(n == 0)
  90806. return false;
  90807. s += n;
  90808. }
  90809. if(s != end)
  90810. return false;
  90811. return true;
  90812. }
  90813. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  90814. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  90815. {
  90816. unsigned i, j;
  90817. if(check_cd_da_subset) {
  90818. if(cue_sheet->lead_in < 2 * 44100) {
  90819. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  90820. return false;
  90821. }
  90822. if(cue_sheet->lead_in % 588 != 0) {
  90823. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  90824. return false;
  90825. }
  90826. }
  90827. if(cue_sheet->num_tracks == 0) {
  90828. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  90829. return false;
  90830. }
  90831. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  90832. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  90833. return false;
  90834. }
  90835. for(i = 0; i < cue_sheet->num_tracks; i++) {
  90836. if(cue_sheet->tracks[i].number == 0) {
  90837. if(violation) *violation = "cue sheet may not have a track number 0";
  90838. return false;
  90839. }
  90840. if(check_cd_da_subset) {
  90841. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  90842. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  90843. return false;
  90844. }
  90845. }
  90846. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  90847. if(violation) {
  90848. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  90849. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  90850. else
  90851. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  90852. }
  90853. return false;
  90854. }
  90855. if(i < cue_sheet->num_tracks - 1) {
  90856. if(cue_sheet->tracks[i].num_indices == 0) {
  90857. if(violation) *violation = "cue sheet track must have at least one index point";
  90858. return false;
  90859. }
  90860. if(cue_sheet->tracks[i].indices[0].number > 1) {
  90861. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  90862. return false;
  90863. }
  90864. }
  90865. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  90866. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  90867. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  90868. return false;
  90869. }
  90870. if(j > 0) {
  90871. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  90872. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  90873. return false;
  90874. }
  90875. }
  90876. }
  90877. }
  90878. return true;
  90879. }
  90880. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  90881. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  90882. {
  90883. char *p;
  90884. FLAC__byte *b;
  90885. for(p = picture->mime_type; *p; p++) {
  90886. if(*p < 0x20 || *p > 0x7e) {
  90887. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  90888. return false;
  90889. }
  90890. }
  90891. for(b = picture->description; *b; ) {
  90892. unsigned n = utf8len_(b);
  90893. if(n == 0) {
  90894. if(violation) *violation = "description string must be valid UTF-8";
  90895. return false;
  90896. }
  90897. b += n;
  90898. }
  90899. return true;
  90900. }
  90901. /*
  90902. * These routines are private to libFLAC
  90903. */
  90904. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  90905. {
  90906. return
  90907. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  90908. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  90909. blocksize,
  90910. predictor_order
  90911. );
  90912. }
  90913. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  90914. {
  90915. unsigned max_rice_partition_order = 0;
  90916. while(!(blocksize & 1)) {
  90917. max_rice_partition_order++;
  90918. blocksize >>= 1;
  90919. }
  90920. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  90921. }
  90922. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  90923. {
  90924. unsigned max_rice_partition_order = limit;
  90925. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  90926. max_rice_partition_order--;
  90927. FLAC__ASSERT(
  90928. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  90929. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  90930. );
  90931. return max_rice_partition_order;
  90932. }
  90933. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  90934. {
  90935. FLAC__ASSERT(0 != object);
  90936. object->parameters = 0;
  90937. object->raw_bits = 0;
  90938. object->capacity_by_order = 0;
  90939. }
  90940. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  90941. {
  90942. FLAC__ASSERT(0 != object);
  90943. if(0 != object->parameters)
  90944. free(object->parameters);
  90945. if(0 != object->raw_bits)
  90946. free(object->raw_bits);
  90947. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  90948. }
  90949. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  90950. {
  90951. FLAC__ASSERT(0 != object);
  90952. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  90953. if(object->capacity_by_order < max_partition_order) {
  90954. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  90955. return false;
  90956. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  90957. return false;
  90958. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  90959. object->capacity_by_order = max_partition_order;
  90960. }
  90961. return true;
  90962. }
  90963. #endif
  90964. /********* End of inlined file: format.c *********/
  90965. /********* Start of inlined file: lpc_flac.c *********/
  90966. /********* Start of inlined file: juce_FlacHeader.h *********/
  90967. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90968. // tasks..
  90969. #define VERSION "1.2.1"
  90970. #define FLAC__NO_DLL 1
  90971. #ifdef _MSC_VER
  90972. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90973. #endif
  90974. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90975. #define FLAC__SYS_DARWIN 1
  90976. #endif
  90977. /********* End of inlined file: juce_FlacHeader.h *********/
  90978. #if JUCE_USE_FLAC
  90979. #if HAVE_CONFIG_H
  90980. # include <config.h>
  90981. #endif
  90982. #include <math.h>
  90983. /********* Start of inlined file: lpc.h *********/
  90984. #ifndef FLAC__PRIVATE__LPC_H
  90985. #define FLAC__PRIVATE__LPC_H
  90986. #ifdef HAVE_CONFIG_H
  90987. #include <config.h>
  90988. #endif
  90989. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90990. /*
  90991. * FLAC__lpc_window_data()
  90992. * --------------------------------------------------------------------
  90993. * Applies the given window to the data.
  90994. * OPT: asm implementation
  90995. *
  90996. * IN in[0,data_len-1]
  90997. * IN window[0,data_len-1]
  90998. * OUT out[0,lag-1]
  90999. * IN data_len
  91000. */
  91001. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  91002. /*
  91003. * FLAC__lpc_compute_autocorrelation()
  91004. * --------------------------------------------------------------------
  91005. * Compute the autocorrelation for lags between 0 and lag-1.
  91006. * Assumes data[] outside of [0,data_len-1] == 0.
  91007. * Asserts that lag > 0.
  91008. *
  91009. * IN data[0,data_len-1]
  91010. * IN data_len
  91011. * IN 0 < lag <= data_len
  91012. * OUT autoc[0,lag-1]
  91013. */
  91014. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91015. #ifndef FLAC__NO_ASM
  91016. # ifdef FLAC__CPU_IA32
  91017. # ifdef FLAC__HAS_NASM
  91018. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91019. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91020. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91021. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91022. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91023. # endif
  91024. # endif
  91025. #endif
  91026. /*
  91027. * FLAC__lpc_compute_lp_coefficients()
  91028. * --------------------------------------------------------------------
  91029. * Computes LP coefficients for orders 1..max_order.
  91030. * Do not call if autoc[0] == 0.0. This means the signal is zero
  91031. * and there is no point in calculating a predictor.
  91032. *
  91033. * IN autoc[0,max_order] autocorrelation values
  91034. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  91035. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  91036. * *** IMPORTANT:
  91037. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  91038. * OUT error[0,max_order-1] error for each order (more
  91039. * specifically, the variance of
  91040. * the error signal times # of
  91041. * samples in the signal)
  91042. *
  91043. * Example: if max_order is 9, the LP coefficients for order 9 will be
  91044. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  91045. * in lp_coeff[7][0,7], etc.
  91046. */
  91047. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  91048. /*
  91049. * FLAC__lpc_quantize_coefficients()
  91050. * --------------------------------------------------------------------
  91051. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  91052. * must be less than 32 (sizeof(FLAC__int32)*8).
  91053. *
  91054. * IN lp_coeff[0,order-1] LP coefficients
  91055. * IN order LP order
  91056. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  91057. * desired precision (in bits, including sign
  91058. * bit) of largest coefficient
  91059. * OUT qlp_coeff[0,order-1] quantized coefficients
  91060. * OUT shift # of bits to shift right to get approximated
  91061. * LP coefficients. NOTE: could be negative.
  91062. * RETURN 0 => quantization OK
  91063. * 1 => coefficients require too much shifting for *shift to
  91064. * fit in the LPC subframe header. 'shift' is unset.
  91065. * 2 => coefficients are all zero, which is bad. 'shift' is
  91066. * unset.
  91067. */
  91068. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  91069. /*
  91070. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  91071. * --------------------------------------------------------------------
  91072. * Compute the residual signal obtained from sutracting the predicted
  91073. * signal from the original.
  91074. *
  91075. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  91076. * IN data_len length of original signal
  91077. * IN qlp_coeff[0,order-1] quantized LP coefficients
  91078. * IN order > 0 LP order
  91079. * IN lp_quantization quantization of LP coefficients in bits
  91080. * OUT residual[0,data_len-1] residual signal
  91081. */
  91082. void FLAC__lpc_compute_residual_from_qlp_coefficients(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  91083. void FLAC__lpc_compute_residual_from_qlp_coefficients_wide(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  91084. #ifndef FLAC__NO_ASM
  91085. # ifdef FLAC__CPU_IA32
  91086. # ifdef FLAC__HAS_NASM
  91087. void FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  91088. void FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  91089. # endif
  91090. # endif
  91091. #endif
  91092. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  91093. /*
  91094. * FLAC__lpc_restore_signal()
  91095. * --------------------------------------------------------------------
  91096. * Restore the original signal by summing the residual and the
  91097. * predictor.
  91098. *
  91099. * IN residual[0,data_len-1] residual signal
  91100. * IN data_len length of original signal
  91101. * IN qlp_coeff[0,order-1] quantized LP coefficients
  91102. * IN order > 0 LP order
  91103. * IN lp_quantization quantization of LP coefficients in bits
  91104. * *** IMPORTANT: the caller must pass in the historical samples:
  91105. * IN data[-order,-1] previously-reconstructed historical samples
  91106. * OUT data[0,data_len-1] original signal
  91107. */
  91108. void FLAC__lpc_restore_signal(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  91109. void FLAC__lpc_restore_signal_wide(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  91110. #ifndef FLAC__NO_ASM
  91111. # ifdef FLAC__CPU_IA32
  91112. # ifdef FLAC__HAS_NASM
  91113. void FLAC__lpc_restore_signal_asm_ia32(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  91114. void FLAC__lpc_restore_signal_asm_ia32_mmx(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  91115. # endif /* FLAC__HAS_NASM */
  91116. # elif defined FLAC__CPU_PPC
  91117. void FLAC__lpc_restore_signal_asm_ppc_altivec_16(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  91118. void FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  91119. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  91120. #endif /* FLAC__NO_ASM */
  91121. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91122. /*
  91123. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  91124. * --------------------------------------------------------------------
  91125. * Compute the expected number of bits per residual signal sample
  91126. * based on the LP error (which is related to the residual variance).
  91127. *
  91128. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  91129. * IN total_samples > 0 # of samples in residual signal
  91130. * RETURN expected bits per sample
  91131. */
  91132. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  91133. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  91134. /*
  91135. * FLAC__lpc_compute_best_order()
  91136. * --------------------------------------------------------------------
  91137. * Compute the best order from the array of signal errors returned
  91138. * during coefficient computation.
  91139. *
  91140. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  91141. * IN max_order > 0 max LP order
  91142. * IN total_samples > 0 # of samples in residual signal
  91143. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  91144. * (includes warmup sample size and quantized LP coefficient)
  91145. * RETURN [1,max_order] best order
  91146. */
  91147. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  91148. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  91149. #endif
  91150. /********* End of inlined file: lpc.h *********/
  91151. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  91152. #include <stdio.h>
  91153. #endif
  91154. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91155. #ifndef M_LN2
  91156. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  91157. #define M_LN2 0.69314718055994530942
  91158. #endif
  91159. /* OPT: #undef'ing this may improve the speed on some architectures */
  91160. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  91161. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  91162. {
  91163. unsigned i;
  91164. for(i = 0; i < data_len; i++)
  91165. out[i] = in[i] * window[i];
  91166. }
  91167. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  91168. {
  91169. /* a readable, but slower, version */
  91170. #if 0
  91171. FLAC__real d;
  91172. unsigned i;
  91173. FLAC__ASSERT(lag > 0);
  91174. FLAC__ASSERT(lag <= data_len);
  91175. /*
  91176. * Technically we should subtract the mean first like so:
  91177. * for(i = 0; i < data_len; i++)
  91178. * data[i] -= mean;
  91179. * but it appears not to make enough of a difference to matter, and
  91180. * most signals are already closely centered around zero
  91181. */
  91182. while(lag--) {
  91183. for(i = lag, d = 0.0; i < data_len; i++)
  91184. d += data[i] * data[i - lag];
  91185. autoc[lag] = d;
  91186. }
  91187. #endif
  91188. /*
  91189. * this version tends to run faster because of better data locality
  91190. * ('data_len' is usually much larger than 'lag')
  91191. */
  91192. FLAC__real d;
  91193. unsigned sample, coeff;
  91194. const unsigned limit = data_len - lag;
  91195. FLAC__ASSERT(lag > 0);
  91196. FLAC__ASSERT(lag <= data_len);
  91197. for(coeff = 0; coeff < lag; coeff++)
  91198. autoc[coeff] = 0.0;
  91199. for(sample = 0; sample <= limit; sample++) {
  91200. d = data[sample];
  91201. for(coeff = 0; coeff < lag; coeff++)
  91202. autoc[coeff] += d * data[sample+coeff];
  91203. }
  91204. for(; sample < data_len; sample++) {
  91205. d = data[sample];
  91206. for(coeff = 0; coeff < data_len - sample; coeff++)
  91207. autoc[coeff] += d * data[sample+coeff];
  91208. }
  91209. }
  91210. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  91211. {
  91212. unsigned i, j;
  91213. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  91214. FLAC__ASSERT(0 != max_order);
  91215. FLAC__ASSERT(0 < *max_order);
  91216. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  91217. FLAC__ASSERT(autoc[0] != 0.0);
  91218. err = autoc[0];
  91219. for(i = 0; i < *max_order; i++) {
  91220. /* Sum up this iteration's reflection coefficient. */
  91221. r = -autoc[i+1];
  91222. for(j = 0; j < i; j++)
  91223. r -= lpc[j] * autoc[i-j];
  91224. ref[i] = (r/=err);
  91225. /* Update LPC coefficients and total error. */
  91226. lpc[i]=r;
  91227. for(j = 0; j < (i>>1); j++) {
  91228. FLAC__double tmp = lpc[j];
  91229. lpc[j] += r * lpc[i-1-j];
  91230. lpc[i-1-j] += r * tmp;
  91231. }
  91232. if(i & 1)
  91233. lpc[j] += lpc[j] * r;
  91234. err *= (1.0 - r * r);
  91235. /* save this order */
  91236. for(j = 0; j <= i; j++)
  91237. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  91238. error[i] = err;
  91239. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  91240. if(err == 0.0) {
  91241. *max_order = i+1;
  91242. return;
  91243. }
  91244. }
  91245. }
  91246. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  91247. {
  91248. unsigned i;
  91249. FLAC__double cmax;
  91250. FLAC__int32 qmax, qmin;
  91251. FLAC__ASSERT(precision > 0);
  91252. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  91253. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  91254. precision--;
  91255. qmax = 1 << precision;
  91256. qmin = -qmax;
  91257. qmax--;
  91258. /* calc cmax = max( |lp_coeff[i]| ) */
  91259. cmax = 0.0;
  91260. for(i = 0; i < order; i++) {
  91261. const FLAC__double d = fabs(lp_coeff[i]);
  91262. if(d > cmax)
  91263. cmax = d;
  91264. }
  91265. if(cmax <= 0.0) {
  91266. /* => coefficients are all 0, which means our constant-detect didn't work */
  91267. return 2;
  91268. }
  91269. else {
  91270. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  91271. const int min_shiftlimit = -max_shiftlimit - 1;
  91272. int log2cmax;
  91273. (void)frexp(cmax, &log2cmax);
  91274. log2cmax--;
  91275. *shift = (int)precision - log2cmax - 1;
  91276. if(*shift > max_shiftlimit)
  91277. *shift = max_shiftlimit;
  91278. else if(*shift < min_shiftlimit)
  91279. return 1;
  91280. }
  91281. if(*shift >= 0) {
  91282. FLAC__double error = 0.0;
  91283. FLAC__int32 q;
  91284. for(i = 0; i < order; i++) {
  91285. error += lp_coeff[i] * (1 << *shift);
  91286. #if 1 /* unfortunately lround() is C99 */
  91287. if(error >= 0.0)
  91288. q = (FLAC__int32)(error + 0.5);
  91289. else
  91290. q = (FLAC__int32)(error - 0.5);
  91291. #else
  91292. q = lround(error);
  91293. #endif
  91294. #ifdef FLAC__OVERFLOW_DETECT
  91295. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  91296. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q>qmax %d>%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmax,*shift,cmax,precision+1,i,lp_coeff[i]);
  91297. else if(q < qmin)
  91298. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q<qmin %d<%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmin,*shift,cmax,precision+1,i,lp_coeff[i]);
  91299. #endif
  91300. if(q > qmax)
  91301. q = qmax;
  91302. else if(q < qmin)
  91303. q = qmin;
  91304. error -= q;
  91305. qlp_coeff[i] = q;
  91306. }
  91307. }
  91308. /* negative shift is very rare but due to design flaw, negative shift is
  91309. * a NOP in the decoder, so it must be handled specially by scaling down
  91310. * coeffs
  91311. */
  91312. else {
  91313. const int nshift = -(*shift);
  91314. FLAC__double error = 0.0;
  91315. FLAC__int32 q;
  91316. #ifdef DEBUG
  91317. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  91318. #endif
  91319. for(i = 0; i < order; i++) {
  91320. error += lp_coeff[i] / (1 << nshift);
  91321. #if 1 /* unfortunately lround() is C99 */
  91322. if(error >= 0.0)
  91323. q = (FLAC__int32)(error + 0.5);
  91324. else
  91325. q = (FLAC__int32)(error - 0.5);
  91326. #else
  91327. q = lround(error);
  91328. #endif
  91329. #ifdef FLAC__OVERFLOW_DETECT
  91330. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  91331. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q>qmax %d>%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmax,*shift,cmax,precision+1,i,lp_coeff[i]);
  91332. else if(q < qmin)
  91333. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q<qmin %d<%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmin,*shift,cmax,precision+1,i,lp_coeff[i]);
  91334. #endif
  91335. if(q > qmax)
  91336. q = qmax;
  91337. else if(q < qmin)
  91338. q = qmin;
  91339. error -= q;
  91340. qlp_coeff[i] = q;
  91341. }
  91342. *shift = 0;
  91343. }
  91344. return 0;
  91345. }
  91346. void FLAC__lpc_compute_residual_from_qlp_coefficients(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
  91347. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  91348. {
  91349. FLAC__int64 sumo;
  91350. unsigned i, j;
  91351. FLAC__int32 sum;
  91352. const FLAC__int32 *history;
  91353. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  91354. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  91355. for(i=0;i<order;i++)
  91356. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  91357. fprintf(stderr,"\n");
  91358. #endif
  91359. FLAC__ASSERT(order > 0);
  91360. for(i = 0; i < data_len; i++) {
  91361. sumo = 0;
  91362. sum = 0;
  91363. history = data;
  91364. for(j = 0; j < order; j++) {
  91365. sum += qlp_coeff[j] * (*(--history));
  91366. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  91367. #if defined _MSC_VER
  91368. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  91369. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%I64d\n",i,j,qlp_coeff[j],*history,sumo);
  91370. #else
  91371. if(sumo > 2147483647ll || sumo < -2147483648ll)
  91372. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%lld\n",i,j,qlp_coeff[j],*history,(long long)sumo);
  91373. #endif
  91374. }
  91375. *(residual++) = *(data++) - (sum >> lp_quantization);
  91376. }
  91377. /* Here's a slower but clearer version:
  91378. for(i = 0; i < data_len; i++) {
  91379. sum = 0;
  91380. for(j = 0; j < order; j++)
  91381. sum += qlp_coeff[j] * data[i-j-1];
  91382. residual[i] = data[i] - (sum >> lp_quantization);
  91383. }
  91384. */
  91385. }
  91386. #else /* fully unrolled version for normal use */
  91387. {
  91388. int i;
  91389. FLAC__int32 sum;
  91390. FLAC__ASSERT(order > 0);
  91391. FLAC__ASSERT(order <= 32);
  91392. /*
  91393. * We do unique versions up to 12th order since that's the subset limit.
  91394. * Also they are roughly ordered to match frequency of occurrence to
  91395. * minimize branching.
  91396. */
  91397. if(order <= 12) {
  91398. if(order > 8) {
  91399. if(order > 10) {
  91400. if(order == 12) {
  91401. for(i = 0; i < (int)data_len; i++) {
  91402. sum = 0;
  91403. sum += qlp_coeff[11] * data[i-12];
  91404. sum += qlp_coeff[10] * data[i-11];
  91405. sum += qlp_coeff[9] * data[i-10];
  91406. sum += qlp_coeff[8] * data[i-9];
  91407. sum += qlp_coeff[7] * data[i-8];
  91408. sum += qlp_coeff[6] * data[i-7];
  91409. sum += qlp_coeff[5] * data[i-6];
  91410. sum += qlp_coeff[4] * data[i-5];
  91411. sum += qlp_coeff[3] * data[i-4];
  91412. sum += qlp_coeff[2] * data[i-3];
  91413. sum += qlp_coeff[1] * data[i-2];
  91414. sum += qlp_coeff[0] * data[i-1];
  91415. residual[i] = data[i] - (sum >> lp_quantization);
  91416. }
  91417. }
  91418. else { /* order == 11 */
  91419. for(i = 0; i < (int)data_len; i++) {
  91420. sum = 0;
  91421. sum += qlp_coeff[10] * data[i-11];
  91422. sum += qlp_coeff[9] * data[i-10];
  91423. sum += qlp_coeff[8] * data[i-9];
  91424. sum += qlp_coeff[7] * data[i-8];
  91425. sum += qlp_coeff[6] * data[i-7];
  91426. sum += qlp_coeff[5] * data[i-6];
  91427. sum += qlp_coeff[4] * data[i-5];
  91428. sum += qlp_coeff[3] * data[i-4];
  91429. sum += qlp_coeff[2] * data[i-3];
  91430. sum += qlp_coeff[1] * data[i-2];
  91431. sum += qlp_coeff[0] * data[i-1];
  91432. residual[i] = data[i] - (sum >> lp_quantization);
  91433. }
  91434. }
  91435. }
  91436. else {
  91437. if(order == 10) {
  91438. for(i = 0; i < (int)data_len; i++) {
  91439. sum = 0;
  91440. sum += qlp_coeff[9] * data[i-10];
  91441. sum += qlp_coeff[8] * data[i-9];
  91442. sum += qlp_coeff[7] * data[i-8];
  91443. sum += qlp_coeff[6] * data[i-7];
  91444. sum += qlp_coeff[5] * data[i-6];
  91445. sum += qlp_coeff[4] * data[i-5];
  91446. sum += qlp_coeff[3] * data[i-4];
  91447. sum += qlp_coeff[2] * data[i-3];
  91448. sum += qlp_coeff[1] * data[i-2];
  91449. sum += qlp_coeff[0] * data[i-1];
  91450. residual[i] = data[i] - (sum >> lp_quantization);
  91451. }
  91452. }
  91453. else { /* order == 9 */
  91454. for(i = 0; i < (int)data_len; i++) {
  91455. sum = 0;
  91456. sum += qlp_coeff[8] * data[i-9];
  91457. sum += qlp_coeff[7] * data[i-8];
  91458. sum += qlp_coeff[6] * data[i-7];
  91459. sum += qlp_coeff[5] * data[i-6];
  91460. sum += qlp_coeff[4] * data[i-5];
  91461. sum += qlp_coeff[3] * data[i-4];
  91462. sum += qlp_coeff[2] * data[i-3];
  91463. sum += qlp_coeff[1] * data[i-2];
  91464. sum += qlp_coeff[0] * data[i-1];
  91465. residual[i] = data[i] - (sum >> lp_quantization);
  91466. }
  91467. }
  91468. }
  91469. }
  91470. else if(order > 4) {
  91471. if(order > 6) {
  91472. if(order == 8) {
  91473. for(i = 0; i < (int)data_len; i++) {
  91474. sum = 0;
  91475. sum += qlp_coeff[7] * data[i-8];
  91476. sum += qlp_coeff[6] * data[i-7];
  91477. sum += qlp_coeff[5] * data[i-6];
  91478. sum += qlp_coeff[4] * data[i-5];
  91479. sum += qlp_coeff[3] * data[i-4];
  91480. sum += qlp_coeff[2] * data[i-3];
  91481. sum += qlp_coeff[1] * data[i-2];
  91482. sum += qlp_coeff[0] * data[i-1];
  91483. residual[i] = data[i] - (sum >> lp_quantization);
  91484. }
  91485. }
  91486. else { /* order == 7 */
  91487. for(i = 0; i < (int)data_len; i++) {
  91488. sum = 0;
  91489. sum += qlp_coeff[6] * data[i-7];
  91490. sum += qlp_coeff[5] * data[i-6];
  91491. sum += qlp_coeff[4] * data[i-5];
  91492. sum += qlp_coeff[3] * data[i-4];
  91493. sum += qlp_coeff[2] * data[i-3];
  91494. sum += qlp_coeff[1] * data[i-2];
  91495. sum += qlp_coeff[0] * data[i-1];
  91496. residual[i] = data[i] - (sum >> lp_quantization);
  91497. }
  91498. }
  91499. }
  91500. else {
  91501. if(order == 6) {
  91502. for(i = 0; i < (int)data_len; i++) {
  91503. sum = 0;
  91504. sum += qlp_coeff[5] * data[i-6];
  91505. sum += qlp_coeff[4] * data[i-5];
  91506. sum += qlp_coeff[3] * data[i-4];
  91507. sum += qlp_coeff[2] * data[i-3];
  91508. sum += qlp_coeff[1] * data[i-2];
  91509. sum += qlp_coeff[0] * data[i-1];
  91510. residual[i] = data[i] - (sum >> lp_quantization);
  91511. }
  91512. }
  91513. else { /* order == 5 */
  91514. for(i = 0; i < (int)data_len; i++) {
  91515. sum = 0;
  91516. sum += qlp_coeff[4] * data[i-5];
  91517. sum += qlp_coeff[3] * data[i-4];
  91518. sum += qlp_coeff[2] * data[i-3];
  91519. sum += qlp_coeff[1] * data[i-2];
  91520. sum += qlp_coeff[0] * data[i-1];
  91521. residual[i] = data[i] - (sum >> lp_quantization);
  91522. }
  91523. }
  91524. }
  91525. }
  91526. else {
  91527. if(order > 2) {
  91528. if(order == 4) {
  91529. for(i = 0; i < (int)data_len; i++) {
  91530. sum = 0;
  91531. sum += qlp_coeff[3] * data[i-4];
  91532. sum += qlp_coeff[2] * data[i-3];
  91533. sum += qlp_coeff[1] * data[i-2];
  91534. sum += qlp_coeff[0] * data[i-1];
  91535. residual[i] = data[i] - (sum >> lp_quantization);
  91536. }
  91537. }
  91538. else { /* order == 3 */
  91539. for(i = 0; i < (int)data_len; i++) {
  91540. sum = 0;
  91541. sum += qlp_coeff[2] * data[i-3];
  91542. sum += qlp_coeff[1] * data[i-2];
  91543. sum += qlp_coeff[0] * data[i-1];
  91544. residual[i] = data[i] - (sum >> lp_quantization);
  91545. }
  91546. }
  91547. }
  91548. else {
  91549. if(order == 2) {
  91550. for(i = 0; i < (int)data_len; i++) {
  91551. sum = 0;
  91552. sum += qlp_coeff[1] * data[i-2];
  91553. sum += qlp_coeff[0] * data[i-1];
  91554. residual[i] = data[i] - (sum >> lp_quantization);
  91555. }
  91556. }
  91557. else { /* order == 1 */
  91558. for(i = 0; i < (int)data_len; i++)
  91559. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  91560. }
  91561. }
  91562. }
  91563. }
  91564. else { /* order > 12 */
  91565. for(i = 0; i < (int)data_len; i++) {
  91566. sum = 0;
  91567. switch(order) {
  91568. case 32: sum += qlp_coeff[31] * data[i-32];
  91569. case 31: sum += qlp_coeff[30] * data[i-31];
  91570. case 30: sum += qlp_coeff[29] * data[i-30];
  91571. case 29: sum += qlp_coeff[28] * data[i-29];
  91572. case 28: sum += qlp_coeff[27] * data[i-28];
  91573. case 27: sum += qlp_coeff[26] * data[i-27];
  91574. case 26: sum += qlp_coeff[25] * data[i-26];
  91575. case 25: sum += qlp_coeff[24] * data[i-25];
  91576. case 24: sum += qlp_coeff[23] * data[i-24];
  91577. case 23: sum += qlp_coeff[22] * data[i-23];
  91578. case 22: sum += qlp_coeff[21] * data[i-22];
  91579. case 21: sum += qlp_coeff[20] * data[i-21];
  91580. case 20: sum += qlp_coeff[19] * data[i-20];
  91581. case 19: sum += qlp_coeff[18] * data[i-19];
  91582. case 18: sum += qlp_coeff[17] * data[i-18];
  91583. case 17: sum += qlp_coeff[16] * data[i-17];
  91584. case 16: sum += qlp_coeff[15] * data[i-16];
  91585. case 15: sum += qlp_coeff[14] * data[i-15];
  91586. case 14: sum += qlp_coeff[13] * data[i-14];
  91587. case 13: sum += qlp_coeff[12] * data[i-13];
  91588. sum += qlp_coeff[11] * data[i-12];
  91589. sum += qlp_coeff[10] * data[i-11];
  91590. sum += qlp_coeff[ 9] * data[i-10];
  91591. sum += qlp_coeff[ 8] * data[i- 9];
  91592. sum += qlp_coeff[ 7] * data[i- 8];
  91593. sum += qlp_coeff[ 6] * data[i- 7];
  91594. sum += qlp_coeff[ 5] * data[i- 6];
  91595. sum += qlp_coeff[ 4] * data[i- 5];
  91596. sum += qlp_coeff[ 3] * data[i- 4];
  91597. sum += qlp_coeff[ 2] * data[i- 3];
  91598. sum += qlp_coeff[ 1] * data[i- 2];
  91599. sum += qlp_coeff[ 0] * data[i- 1];
  91600. }
  91601. residual[i] = data[i] - (sum >> lp_quantization);
  91602. }
  91603. }
  91604. }
  91605. #endif
  91606. void FLAC__lpc_compute_residual_from_qlp_coefficients_wide(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
  91607. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  91608. {
  91609. unsigned i, j;
  91610. FLAC__int64 sum;
  91611. const FLAC__int32 *history;
  91612. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  91613. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  91614. for(i=0;i<order;i++)
  91615. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  91616. fprintf(stderr,"\n");
  91617. #endif
  91618. FLAC__ASSERT(order > 0);
  91619. for(i = 0; i < data_len; i++) {
  91620. sum = 0;
  91621. history = data;
  91622. for(j = 0; j < order; j++)
  91623. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  91624. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  91625. #if defined _MSC_VER
  91626. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  91627. #else
  91628. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  91629. #endif
  91630. break;
  91631. }
  91632. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  91633. #if defined _MSC_VER
  91634. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, data=%d, sum=%I64d, residual=%I64d\n", i, *data, sum >> lp_quantization, (FLAC__int64)(*data) - (sum >> lp_quantization));
  91635. #else
  91636. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, data=%d, sum=%lld, residual=%lld\n", i, *data, (long long)(sum >> lp_quantization), (long long)((FLAC__int64)(*data) - (sum >> lp_quantization)));
  91637. #endif
  91638. break;
  91639. }
  91640. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  91641. }
  91642. }
  91643. #else /* fully unrolled version for normal use */
  91644. {
  91645. int i;
  91646. FLAC__int64 sum;
  91647. FLAC__ASSERT(order > 0);
  91648. FLAC__ASSERT(order <= 32);
  91649. /*
  91650. * We do unique versions up to 12th order since that's the subset limit.
  91651. * Also they are roughly ordered to match frequency of occurrence to
  91652. * minimize branching.
  91653. */
  91654. if(order <= 12) {
  91655. if(order > 8) {
  91656. if(order > 10) {
  91657. if(order == 12) {
  91658. for(i = 0; i < (int)data_len; i++) {
  91659. sum = 0;
  91660. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  91661. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  91662. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  91663. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91664. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91665. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91666. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91667. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91668. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91669. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91670. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91671. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91672. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91673. }
  91674. }
  91675. else { /* order == 11 */
  91676. for(i = 0; i < (int)data_len; i++) {
  91677. sum = 0;
  91678. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  91679. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  91680. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91681. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91682. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91683. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91684. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91685. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91686. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91687. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91688. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91689. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91690. }
  91691. }
  91692. }
  91693. else {
  91694. if(order == 10) {
  91695. for(i = 0; i < (int)data_len; i++) {
  91696. sum = 0;
  91697. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  91698. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91699. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91700. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91701. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91702. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91703. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91704. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91705. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91706. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91707. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91708. }
  91709. }
  91710. else { /* order == 9 */
  91711. for(i = 0; i < (int)data_len; i++) {
  91712. sum = 0;
  91713. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91714. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91715. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91716. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91717. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91718. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91719. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91720. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91721. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91722. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91723. }
  91724. }
  91725. }
  91726. }
  91727. else if(order > 4) {
  91728. if(order > 6) {
  91729. if(order == 8) {
  91730. for(i = 0; i < (int)data_len; i++) {
  91731. sum = 0;
  91732. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91733. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91734. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91735. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91736. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91737. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91738. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91739. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91740. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91741. }
  91742. }
  91743. else { /* order == 7 */
  91744. for(i = 0; i < (int)data_len; i++) {
  91745. sum = 0;
  91746. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91747. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91748. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91749. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91750. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91751. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91752. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91753. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91754. }
  91755. }
  91756. }
  91757. else {
  91758. if(order == 6) {
  91759. for(i = 0; i < (int)data_len; i++) {
  91760. sum = 0;
  91761. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91762. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91763. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91764. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91765. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91766. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91767. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91768. }
  91769. }
  91770. else { /* order == 5 */
  91771. for(i = 0; i < (int)data_len; i++) {
  91772. sum = 0;
  91773. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91774. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91775. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91776. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91777. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91778. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91779. }
  91780. }
  91781. }
  91782. }
  91783. else {
  91784. if(order > 2) {
  91785. if(order == 4) {
  91786. for(i = 0; i < (int)data_len; i++) {
  91787. sum = 0;
  91788. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91789. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91790. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91791. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91792. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91793. }
  91794. }
  91795. else { /* order == 3 */
  91796. for(i = 0; i < (int)data_len; i++) {
  91797. sum = 0;
  91798. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91799. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91800. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91801. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91802. }
  91803. }
  91804. }
  91805. else {
  91806. if(order == 2) {
  91807. for(i = 0; i < (int)data_len; i++) {
  91808. sum = 0;
  91809. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91810. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91811. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91812. }
  91813. }
  91814. else { /* order == 1 */
  91815. for(i = 0; i < (int)data_len; i++)
  91816. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  91817. }
  91818. }
  91819. }
  91820. }
  91821. else { /* order > 12 */
  91822. for(i = 0; i < (int)data_len; i++) {
  91823. sum = 0;
  91824. switch(order) {
  91825. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  91826. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  91827. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  91828. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  91829. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  91830. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  91831. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  91832. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  91833. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  91834. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  91835. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  91836. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  91837. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  91838. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  91839. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  91840. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  91841. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  91842. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  91843. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  91844. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  91845. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  91846. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  91847. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  91848. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  91849. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  91850. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  91851. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  91852. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  91853. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  91854. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  91855. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  91856. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  91857. }
  91858. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91859. }
  91860. }
  91861. }
  91862. #endif
  91863. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  91864. void FLAC__lpc_restore_signal(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[])
  91865. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  91866. {
  91867. FLAC__int64 sumo;
  91868. unsigned i, j;
  91869. FLAC__int32 sum;
  91870. const FLAC__int32 *r = residual, *history;
  91871. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  91872. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  91873. for(i=0;i<order;i++)
  91874. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  91875. fprintf(stderr,"\n");
  91876. #endif
  91877. FLAC__ASSERT(order > 0);
  91878. for(i = 0; i < data_len; i++) {
  91879. sumo = 0;
  91880. sum = 0;
  91881. history = data;
  91882. for(j = 0; j < order; j++) {
  91883. sum += qlp_coeff[j] * (*(--history));
  91884. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  91885. #if defined _MSC_VER
  91886. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  91887. fprintf(stderr,"FLAC__lpc_restore_signal: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%I64d\n",i,j,qlp_coeff[j],*history,sumo);
  91888. #else
  91889. if(sumo > 2147483647ll || sumo < -2147483648ll)
  91890. fprintf(stderr,"FLAC__lpc_restore_signal: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%lld\n",i,j,qlp_coeff[j],*history,(long long)sumo);
  91891. #endif
  91892. }
  91893. *(data++) = *(r++) + (sum >> lp_quantization);
  91894. }
  91895. /* Here's a slower but clearer version:
  91896. for(i = 0; i < data_len; i++) {
  91897. sum = 0;
  91898. for(j = 0; j < order; j++)
  91899. sum += qlp_coeff[j] * data[i-j-1];
  91900. data[i] = residual[i] + (sum >> lp_quantization);
  91901. }
  91902. */
  91903. }
  91904. #else /* fully unrolled version for normal use */
  91905. {
  91906. int i;
  91907. FLAC__int32 sum;
  91908. FLAC__ASSERT(order > 0);
  91909. FLAC__ASSERT(order <= 32);
  91910. /*
  91911. * We do unique versions up to 12th order since that's the subset limit.
  91912. * Also they are roughly ordered to match frequency of occurrence to
  91913. * minimize branching.
  91914. */
  91915. if(order <= 12) {
  91916. if(order > 8) {
  91917. if(order > 10) {
  91918. if(order == 12) {
  91919. for(i = 0; i < (int)data_len; i++) {
  91920. sum = 0;
  91921. sum += qlp_coeff[11] * data[i-12];
  91922. sum += qlp_coeff[10] * data[i-11];
  91923. sum += qlp_coeff[9] * data[i-10];
  91924. sum += qlp_coeff[8] * data[i-9];
  91925. sum += qlp_coeff[7] * data[i-8];
  91926. sum += qlp_coeff[6] * data[i-7];
  91927. sum += qlp_coeff[5] * data[i-6];
  91928. sum += qlp_coeff[4] * data[i-5];
  91929. sum += qlp_coeff[3] * data[i-4];
  91930. sum += qlp_coeff[2] * data[i-3];
  91931. sum += qlp_coeff[1] * data[i-2];
  91932. sum += qlp_coeff[0] * data[i-1];
  91933. data[i] = residual[i] + (sum >> lp_quantization);
  91934. }
  91935. }
  91936. else { /* order == 11 */
  91937. for(i = 0; i < (int)data_len; i++) {
  91938. sum = 0;
  91939. sum += qlp_coeff[10] * data[i-11];
  91940. sum += qlp_coeff[9] * data[i-10];
  91941. sum += qlp_coeff[8] * data[i-9];
  91942. sum += qlp_coeff[7] * data[i-8];
  91943. sum += qlp_coeff[6] * data[i-7];
  91944. sum += qlp_coeff[5] * data[i-6];
  91945. sum += qlp_coeff[4] * data[i-5];
  91946. sum += qlp_coeff[3] * data[i-4];
  91947. sum += qlp_coeff[2] * data[i-3];
  91948. sum += qlp_coeff[1] * data[i-2];
  91949. sum += qlp_coeff[0] * data[i-1];
  91950. data[i] = residual[i] + (sum >> lp_quantization);
  91951. }
  91952. }
  91953. }
  91954. else {
  91955. if(order == 10) {
  91956. for(i = 0; i < (int)data_len; i++) {
  91957. sum = 0;
  91958. sum += qlp_coeff[9] * data[i-10];
  91959. sum += qlp_coeff[8] * data[i-9];
  91960. sum += qlp_coeff[7] * data[i-8];
  91961. sum += qlp_coeff[6] * data[i-7];
  91962. sum += qlp_coeff[5] * data[i-6];
  91963. sum += qlp_coeff[4] * data[i-5];
  91964. sum += qlp_coeff[3] * data[i-4];
  91965. sum += qlp_coeff[2] * data[i-3];
  91966. sum += qlp_coeff[1] * data[i-2];
  91967. sum += qlp_coeff[0] * data[i-1];
  91968. data[i] = residual[i] + (sum >> lp_quantization);
  91969. }
  91970. }
  91971. else { /* order == 9 */
  91972. for(i = 0; i < (int)data_len; i++) {
  91973. sum = 0;
  91974. sum += qlp_coeff[8] * data[i-9];
  91975. sum += qlp_coeff[7] * data[i-8];
  91976. sum += qlp_coeff[6] * data[i-7];
  91977. sum += qlp_coeff[5] * data[i-6];
  91978. sum += qlp_coeff[4] * data[i-5];
  91979. sum += qlp_coeff[3] * data[i-4];
  91980. sum += qlp_coeff[2] * data[i-3];
  91981. sum += qlp_coeff[1] * data[i-2];
  91982. sum += qlp_coeff[0] * data[i-1];
  91983. data[i] = residual[i] + (sum >> lp_quantization);
  91984. }
  91985. }
  91986. }
  91987. }
  91988. else if(order > 4) {
  91989. if(order > 6) {
  91990. if(order == 8) {
  91991. for(i = 0; i < (int)data_len; i++) {
  91992. sum = 0;
  91993. sum += qlp_coeff[7] * data[i-8];
  91994. sum += qlp_coeff[6] * data[i-7];
  91995. sum += qlp_coeff[5] * data[i-6];
  91996. sum += qlp_coeff[4] * data[i-5];
  91997. sum += qlp_coeff[3] * data[i-4];
  91998. sum += qlp_coeff[2] * data[i-3];
  91999. sum += qlp_coeff[1] * data[i-2];
  92000. sum += qlp_coeff[0] * data[i-1];
  92001. data[i] = residual[i] + (sum >> lp_quantization);
  92002. }
  92003. }
  92004. else { /* order == 7 */
  92005. for(i = 0; i < (int)data_len; i++) {
  92006. sum = 0;
  92007. sum += qlp_coeff[6] * data[i-7];
  92008. sum += qlp_coeff[5] * data[i-6];
  92009. sum += qlp_coeff[4] * data[i-5];
  92010. sum += qlp_coeff[3] * data[i-4];
  92011. sum += qlp_coeff[2] * data[i-3];
  92012. sum += qlp_coeff[1] * data[i-2];
  92013. sum += qlp_coeff[0] * data[i-1];
  92014. data[i] = residual[i] + (sum >> lp_quantization);
  92015. }
  92016. }
  92017. }
  92018. else {
  92019. if(order == 6) {
  92020. for(i = 0; i < (int)data_len; i++) {
  92021. sum = 0;
  92022. sum += qlp_coeff[5] * data[i-6];
  92023. sum += qlp_coeff[4] * data[i-5];
  92024. sum += qlp_coeff[3] * data[i-4];
  92025. sum += qlp_coeff[2] * data[i-3];
  92026. sum += qlp_coeff[1] * data[i-2];
  92027. sum += qlp_coeff[0] * data[i-1];
  92028. data[i] = residual[i] + (sum >> lp_quantization);
  92029. }
  92030. }
  92031. else { /* order == 5 */
  92032. for(i = 0; i < (int)data_len; i++) {
  92033. sum = 0;
  92034. sum += qlp_coeff[4] * data[i-5];
  92035. sum += qlp_coeff[3] * data[i-4];
  92036. sum += qlp_coeff[2] * data[i-3];
  92037. sum += qlp_coeff[1] * data[i-2];
  92038. sum += qlp_coeff[0] * data[i-1];
  92039. data[i] = residual[i] + (sum >> lp_quantization);
  92040. }
  92041. }
  92042. }
  92043. }
  92044. else {
  92045. if(order > 2) {
  92046. if(order == 4) {
  92047. for(i = 0; i < (int)data_len; i++) {
  92048. sum = 0;
  92049. sum += qlp_coeff[3] * data[i-4];
  92050. sum += qlp_coeff[2] * data[i-3];
  92051. sum += qlp_coeff[1] * data[i-2];
  92052. sum += qlp_coeff[0] * data[i-1];
  92053. data[i] = residual[i] + (sum >> lp_quantization);
  92054. }
  92055. }
  92056. else { /* order == 3 */
  92057. for(i = 0; i < (int)data_len; i++) {
  92058. sum = 0;
  92059. sum += qlp_coeff[2] * data[i-3];
  92060. sum += qlp_coeff[1] * data[i-2];
  92061. sum += qlp_coeff[0] * data[i-1];
  92062. data[i] = residual[i] + (sum >> lp_quantization);
  92063. }
  92064. }
  92065. }
  92066. else {
  92067. if(order == 2) {
  92068. for(i = 0; i < (int)data_len; i++) {
  92069. sum = 0;
  92070. sum += qlp_coeff[1] * data[i-2];
  92071. sum += qlp_coeff[0] * data[i-1];
  92072. data[i] = residual[i] + (sum >> lp_quantization);
  92073. }
  92074. }
  92075. else { /* order == 1 */
  92076. for(i = 0; i < (int)data_len; i++)
  92077. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  92078. }
  92079. }
  92080. }
  92081. }
  92082. else { /* order > 12 */
  92083. for(i = 0; i < (int)data_len; i++) {
  92084. sum = 0;
  92085. switch(order) {
  92086. case 32: sum += qlp_coeff[31] * data[i-32];
  92087. case 31: sum += qlp_coeff[30] * data[i-31];
  92088. case 30: sum += qlp_coeff[29] * data[i-30];
  92089. case 29: sum += qlp_coeff[28] * data[i-29];
  92090. case 28: sum += qlp_coeff[27] * data[i-28];
  92091. case 27: sum += qlp_coeff[26] * data[i-27];
  92092. case 26: sum += qlp_coeff[25] * data[i-26];
  92093. case 25: sum += qlp_coeff[24] * data[i-25];
  92094. case 24: sum += qlp_coeff[23] * data[i-24];
  92095. case 23: sum += qlp_coeff[22] * data[i-23];
  92096. case 22: sum += qlp_coeff[21] * data[i-22];
  92097. case 21: sum += qlp_coeff[20] * data[i-21];
  92098. case 20: sum += qlp_coeff[19] * data[i-20];
  92099. case 19: sum += qlp_coeff[18] * data[i-19];
  92100. case 18: sum += qlp_coeff[17] * data[i-18];
  92101. case 17: sum += qlp_coeff[16] * data[i-17];
  92102. case 16: sum += qlp_coeff[15] * data[i-16];
  92103. case 15: sum += qlp_coeff[14] * data[i-15];
  92104. case 14: sum += qlp_coeff[13] * data[i-14];
  92105. case 13: sum += qlp_coeff[12] * data[i-13];
  92106. sum += qlp_coeff[11] * data[i-12];
  92107. sum += qlp_coeff[10] * data[i-11];
  92108. sum += qlp_coeff[ 9] * data[i-10];
  92109. sum += qlp_coeff[ 8] * data[i- 9];
  92110. sum += qlp_coeff[ 7] * data[i- 8];
  92111. sum += qlp_coeff[ 6] * data[i- 7];
  92112. sum += qlp_coeff[ 5] * data[i- 6];
  92113. sum += qlp_coeff[ 4] * data[i- 5];
  92114. sum += qlp_coeff[ 3] * data[i- 4];
  92115. sum += qlp_coeff[ 2] * data[i- 3];
  92116. sum += qlp_coeff[ 1] * data[i- 2];
  92117. sum += qlp_coeff[ 0] * data[i- 1];
  92118. }
  92119. data[i] = residual[i] + (sum >> lp_quantization);
  92120. }
  92121. }
  92122. }
  92123. #endif
  92124. void FLAC__lpc_restore_signal_wide(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[])
  92125. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  92126. {
  92127. unsigned i, j;
  92128. FLAC__int64 sum;
  92129. const FLAC__int32 *r = residual, *history;
  92130. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  92131. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  92132. for(i=0;i<order;i++)
  92133. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  92134. fprintf(stderr,"\n");
  92135. #endif
  92136. FLAC__ASSERT(order > 0);
  92137. for(i = 0; i < data_len; i++) {
  92138. sum = 0;
  92139. history = data;
  92140. for(j = 0; j < order; j++)
  92141. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  92142. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  92143. #ifdef _MSC_VER
  92144. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  92145. #else
  92146. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  92147. #endif
  92148. break;
  92149. }
  92150. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  92151. #ifdef _MSC_VER
  92152. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, residual=%d, sum=%I64d, data=%I64d\n", i, *r, sum >> lp_quantization, (FLAC__int64)(*r) + (sum >> lp_quantization));
  92153. #else
  92154. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, residual=%d, sum=%lld, data=%lld\n", i, *r, (long long)(sum >> lp_quantization), (long long)((FLAC__int64)(*r) + (sum >> lp_quantization)));
  92155. #endif
  92156. break;
  92157. }
  92158. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  92159. }
  92160. }
  92161. #else /* fully unrolled version for normal use */
  92162. {
  92163. int i;
  92164. FLAC__int64 sum;
  92165. FLAC__ASSERT(order > 0);
  92166. FLAC__ASSERT(order <= 32);
  92167. /*
  92168. * We do unique versions up to 12th order since that's the subset limit.
  92169. * Also they are roughly ordered to match frequency of occurrence to
  92170. * minimize branching.
  92171. */
  92172. if(order <= 12) {
  92173. if(order > 8) {
  92174. if(order > 10) {
  92175. if(order == 12) {
  92176. for(i = 0; i < (int)data_len; i++) {
  92177. sum = 0;
  92178. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  92179. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  92180. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  92181. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92182. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92183. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92184. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92185. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92186. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92187. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92188. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92189. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92190. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92191. }
  92192. }
  92193. else { /* order == 11 */
  92194. for(i = 0; i < (int)data_len; i++) {
  92195. sum = 0;
  92196. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  92197. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  92198. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92199. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92200. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92201. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92202. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92203. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92204. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92205. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92206. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92207. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92208. }
  92209. }
  92210. }
  92211. else {
  92212. if(order == 10) {
  92213. for(i = 0; i < (int)data_len; i++) {
  92214. sum = 0;
  92215. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  92216. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92217. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92218. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92219. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92220. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92221. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92222. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92223. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92224. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92225. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92226. }
  92227. }
  92228. else { /* order == 9 */
  92229. for(i = 0; i < (int)data_len; i++) {
  92230. sum = 0;
  92231. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92232. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92233. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92234. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92235. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92236. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92237. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92238. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92239. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92240. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92241. }
  92242. }
  92243. }
  92244. }
  92245. else if(order > 4) {
  92246. if(order > 6) {
  92247. if(order == 8) {
  92248. for(i = 0; i < (int)data_len; i++) {
  92249. sum = 0;
  92250. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92251. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92252. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92253. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92254. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92255. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92256. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92257. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92258. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92259. }
  92260. }
  92261. else { /* order == 7 */
  92262. for(i = 0; i < (int)data_len; i++) {
  92263. sum = 0;
  92264. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92265. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92266. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92267. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92268. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92269. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92270. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92271. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92272. }
  92273. }
  92274. }
  92275. else {
  92276. if(order == 6) {
  92277. for(i = 0; i < (int)data_len; i++) {
  92278. sum = 0;
  92279. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92280. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92281. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92282. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92283. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92284. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92285. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92286. }
  92287. }
  92288. else { /* order == 5 */
  92289. for(i = 0; i < (int)data_len; i++) {
  92290. sum = 0;
  92291. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92292. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92293. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92294. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92295. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92296. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92297. }
  92298. }
  92299. }
  92300. }
  92301. else {
  92302. if(order > 2) {
  92303. if(order == 4) {
  92304. for(i = 0; i < (int)data_len; i++) {
  92305. sum = 0;
  92306. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92307. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92308. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92309. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92310. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92311. }
  92312. }
  92313. else { /* order == 3 */
  92314. for(i = 0; i < (int)data_len; i++) {
  92315. sum = 0;
  92316. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92317. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92318. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92319. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92320. }
  92321. }
  92322. }
  92323. else {
  92324. if(order == 2) {
  92325. for(i = 0; i < (int)data_len; i++) {
  92326. sum = 0;
  92327. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92328. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92329. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92330. }
  92331. }
  92332. else { /* order == 1 */
  92333. for(i = 0; i < (int)data_len; i++)
  92334. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  92335. }
  92336. }
  92337. }
  92338. }
  92339. else { /* order > 12 */
  92340. for(i = 0; i < (int)data_len; i++) {
  92341. sum = 0;
  92342. switch(order) {
  92343. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  92344. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  92345. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  92346. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  92347. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  92348. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  92349. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  92350. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  92351. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  92352. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  92353. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  92354. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  92355. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  92356. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  92357. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  92358. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  92359. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  92360. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  92361. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  92362. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  92363. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  92364. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  92365. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  92366. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  92367. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  92368. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  92369. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  92370. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  92371. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  92372. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  92373. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  92374. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  92375. }
  92376. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92377. }
  92378. }
  92379. }
  92380. #endif
  92381. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92382. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  92383. {
  92384. FLAC__double error_scale;
  92385. FLAC__ASSERT(total_samples > 0);
  92386. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  92387. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  92388. }
  92389. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  92390. {
  92391. if(lpc_error > 0.0) {
  92392. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  92393. if(bps >= 0.0)
  92394. return bps;
  92395. else
  92396. return 0.0;
  92397. }
  92398. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  92399. return 1e32;
  92400. }
  92401. else {
  92402. return 0.0;
  92403. }
  92404. }
  92405. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  92406. {
  92407. unsigned order, index, best_index; /* 'index' the index into lpc_error; index==order-1 since lpc_error[0] is for order==1, lpc_error[1] is for order==2, etc */
  92408. FLAC__double bits, best_bits, error_scale;
  92409. FLAC__ASSERT(max_order > 0);
  92410. FLAC__ASSERT(total_samples > 0);
  92411. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  92412. best_index = 0;
  92413. best_bits = (unsigned)(-1);
  92414. for(index = 0, order = 1; index < max_order; index++, order++) {
  92415. bits = FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error[index], error_scale) * (FLAC__double)(total_samples - order) + (FLAC__double)(order * overhead_bits_per_order);
  92416. if(bits < best_bits) {
  92417. best_index = index;
  92418. best_bits = bits;
  92419. }
  92420. }
  92421. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  92422. }
  92423. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  92424. #endif
  92425. /********* End of inlined file: lpc_flac.c *********/
  92426. /********* Start of inlined file: md5.c *********/
  92427. /********* Start of inlined file: juce_FlacHeader.h *********/
  92428. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92429. // tasks..
  92430. #define VERSION "1.2.1"
  92431. #define FLAC__NO_DLL 1
  92432. #ifdef _MSC_VER
  92433. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92434. #endif
  92435. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  92436. #define FLAC__SYS_DARWIN 1
  92437. #endif
  92438. /********* End of inlined file: juce_FlacHeader.h *********/
  92439. #if JUCE_USE_FLAC
  92440. #if HAVE_CONFIG_H
  92441. # include <config.h>
  92442. #endif
  92443. #include <stdlib.h> /* for malloc() */
  92444. #include <string.h> /* for memcpy() */
  92445. /********* Start of inlined file: md5.h *********/
  92446. #ifndef FLAC__PRIVATE__MD5_H
  92447. #define FLAC__PRIVATE__MD5_H
  92448. /*
  92449. * This is the header file for the MD5 message-digest algorithm.
  92450. * The algorithm is due to Ron Rivest. This code was
  92451. * written by Colin Plumb in 1993, no copyright is claimed.
  92452. * This code is in the public domain; do with it what you wish.
  92453. *
  92454. * Equivalent code is available from RSA Data Security, Inc.
  92455. * This code has been tested against that, and is equivalent,
  92456. * except that you don't need to include two pages of legalese
  92457. * with every copy.
  92458. *
  92459. * To compute the message digest of a chunk of bytes, declare an
  92460. * MD5Context structure, pass it to MD5Init, call MD5Update as
  92461. * needed on buffers full of bytes, and then call MD5Final, which
  92462. * will fill a supplied 16-byte array with the digest.
  92463. *
  92464. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  92465. * header definitions; now uses stuff from dpkg's config.h
  92466. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  92467. * Still in the public domain.
  92468. *
  92469. * Josh Coalson: made some changes to integrate with libFLAC.
  92470. * Still in the public domain, with no warranty.
  92471. */
  92472. typedef struct {
  92473. FLAC__uint32 in[16];
  92474. FLAC__uint32 buf[4];
  92475. FLAC__uint32 bytes[2];
  92476. FLAC__byte *internal_buf;
  92477. size_t capacity;
  92478. } FLAC__MD5Context;
  92479. void FLAC__MD5Init(FLAC__MD5Context *context);
  92480. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  92481. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  92482. #endif
  92483. /********* End of inlined file: md5.h *********/
  92484. #ifndef FLaC__INLINE
  92485. #define FLaC__INLINE
  92486. #endif
  92487. /*
  92488. * This code implements the MD5 message-digest algorithm.
  92489. * The algorithm is due to Ron Rivest. This code was
  92490. * written by Colin Plumb in 1993, no copyright is claimed.
  92491. * This code is in the public domain; do with it what you wish.
  92492. *
  92493. * Equivalent code is available from RSA Data Security, Inc.
  92494. * This code has been tested against that, and is equivalent,
  92495. * except that you don't need to include two pages of legalese
  92496. * with every copy.
  92497. *
  92498. * To compute the message digest of a chunk of bytes, declare an
  92499. * MD5Context structure, pass it to MD5Init, call MD5Update as
  92500. * needed on buffers full of bytes, and then call MD5Final, which
  92501. * will fill a supplied 16-byte array with the digest.
  92502. *
  92503. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  92504. * definitions; now uses stuff from dpkg's config.h.
  92505. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  92506. * Still in the public domain.
  92507. *
  92508. * Josh Coalson: made some changes to integrate with libFLAC.
  92509. * Still in the public domain.
  92510. */
  92511. /* The four core functions - F1 is optimized somewhat */
  92512. /* #define F1(x, y, z) (x & y | ~x & z) */
  92513. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  92514. #define F2(x, y, z) F1(z, x, y)
  92515. #define F3(x, y, z) (x ^ y ^ z)
  92516. #define F4(x, y, z) (y ^ (x | ~z))
  92517. /* This is the central step in the MD5 algorithm. */
  92518. #define MD5STEP(f,w,x,y,z,in,s) \
  92519. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  92520. /*
  92521. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  92522. * reflect the addition of 16 longwords of new data. MD5Update blocks
  92523. * the data and converts bytes into longwords for this routine.
  92524. */
  92525. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  92526. {
  92527. register FLAC__uint32 a, b, c, d;
  92528. a = buf[0];
  92529. b = buf[1];
  92530. c = buf[2];
  92531. d = buf[3];
  92532. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  92533. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  92534. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  92535. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  92536. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  92537. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  92538. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  92539. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  92540. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  92541. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  92542. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  92543. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  92544. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  92545. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  92546. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  92547. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  92548. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  92549. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  92550. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  92551. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  92552. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  92553. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  92554. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  92555. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  92556. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  92557. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  92558. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  92559. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  92560. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  92561. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  92562. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  92563. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  92564. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  92565. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  92566. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  92567. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  92568. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  92569. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  92570. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  92571. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  92572. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  92573. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  92574. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  92575. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  92576. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  92577. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  92578. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  92579. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  92580. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  92581. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  92582. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  92583. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  92584. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  92585. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  92586. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  92587. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  92588. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  92589. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  92590. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  92591. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  92592. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  92593. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  92594. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  92595. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  92596. buf[0] += a;
  92597. buf[1] += b;
  92598. buf[2] += c;
  92599. buf[3] += d;
  92600. }
  92601. #if WORDS_BIGENDIAN
  92602. //@@@@@@ OPT: use bswap/intrinsics
  92603. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  92604. {
  92605. register FLAC__uint32 x;
  92606. do {
  92607. x = *buf;
  92608. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  92609. *buf++ = (x >> 16) | (x << 16);
  92610. } while (--words);
  92611. }
  92612. static void byteSwapX16(FLAC__uint32 *buf)
  92613. {
  92614. register FLAC__uint32 x;
  92615. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92616. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92617. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92618. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92619. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92620. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92621. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92622. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92623. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92624. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92625. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92626. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92627. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92628. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92629. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92630. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  92631. }
  92632. #else
  92633. #define byteSwap(buf, words)
  92634. #define byteSwapX16(buf)
  92635. #endif
  92636. /*
  92637. * Update context to reflect the concatenation of another buffer full
  92638. * of bytes.
  92639. */
  92640. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  92641. {
  92642. FLAC__uint32 t;
  92643. /* Update byte count */
  92644. t = ctx->bytes[0];
  92645. if ((ctx->bytes[0] = t + len) < t)
  92646. ctx->bytes[1]++; /* Carry from low to high */
  92647. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  92648. if (t > len) {
  92649. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  92650. return;
  92651. }
  92652. /* First chunk is an odd size */
  92653. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  92654. byteSwapX16(ctx->in);
  92655. FLAC__MD5Transform(ctx->buf, ctx->in);
  92656. buf += t;
  92657. len -= t;
  92658. /* Process data in 64-byte chunks */
  92659. while (len >= 64) {
  92660. memcpy(ctx->in, buf, 64);
  92661. byteSwapX16(ctx->in);
  92662. FLAC__MD5Transform(ctx->buf, ctx->in);
  92663. buf += 64;
  92664. len -= 64;
  92665. }
  92666. /* Handle any remaining bytes of data. */
  92667. memcpy(ctx->in, buf, len);
  92668. }
  92669. /*
  92670. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  92671. * initialization constants.
  92672. */
  92673. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  92674. {
  92675. ctx->buf[0] = 0x67452301;
  92676. ctx->buf[1] = 0xefcdab89;
  92677. ctx->buf[2] = 0x98badcfe;
  92678. ctx->buf[3] = 0x10325476;
  92679. ctx->bytes[0] = 0;
  92680. ctx->bytes[1] = 0;
  92681. ctx->internal_buf = 0;
  92682. ctx->capacity = 0;
  92683. }
  92684. /*
  92685. * Final wrapup - pad to 64-byte boundary with the bit pattern
  92686. * 1 0* (64-bit count of bits processed, MSB-first)
  92687. */
  92688. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  92689. {
  92690. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  92691. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  92692. /* Set the first char of padding to 0x80. There is always room. */
  92693. *p++ = 0x80;
  92694. /* Bytes of padding needed to make 56 bytes (-8..55) */
  92695. count = 56 - 1 - count;
  92696. if (count < 0) { /* Padding forces an extra block */
  92697. memset(p, 0, count + 8);
  92698. byteSwapX16(ctx->in);
  92699. FLAC__MD5Transform(ctx->buf, ctx->in);
  92700. p = (FLAC__byte *)ctx->in;
  92701. count = 56;
  92702. }
  92703. memset(p, 0, count);
  92704. byteSwap(ctx->in, 14);
  92705. /* Append length in bits and transform */
  92706. ctx->in[14] = ctx->bytes[0] << 3;
  92707. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  92708. FLAC__MD5Transform(ctx->buf, ctx->in);
  92709. byteSwap(ctx->buf, 4);
  92710. memcpy(digest, ctx->buf, 16);
  92711. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  92712. if(0 != ctx->internal_buf) {
  92713. free(ctx->internal_buf);
  92714. ctx->internal_buf = 0;
  92715. ctx->capacity = 0;
  92716. }
  92717. }
  92718. /*
  92719. * Convert the incoming audio signal to a byte stream
  92720. */
  92721. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  92722. {
  92723. unsigned channel, sample;
  92724. register FLAC__int32 a_word;
  92725. register FLAC__byte *buf_ = buf;
  92726. #if WORDS_BIGENDIAN
  92727. #else
  92728. if(channels == 2 && bytes_per_sample == 2) {
  92729. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  92730. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  92731. for(sample = 0; sample < samples; sample++, buf1_+=2)
  92732. *buf1_ = (FLAC__int16)signal[1][sample];
  92733. }
  92734. else if(channels == 1 && bytes_per_sample == 2) {
  92735. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  92736. for(sample = 0; sample < samples; sample++)
  92737. *buf1_++ = (FLAC__int16)signal[0][sample];
  92738. }
  92739. else
  92740. #endif
  92741. if(bytes_per_sample == 2) {
  92742. if(channels == 2) {
  92743. for(sample = 0; sample < samples; sample++) {
  92744. a_word = signal[0][sample];
  92745. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92746. *buf_++ = (FLAC__byte)a_word;
  92747. a_word = signal[1][sample];
  92748. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92749. *buf_++ = (FLAC__byte)a_word;
  92750. }
  92751. }
  92752. else if(channels == 1) {
  92753. for(sample = 0; sample < samples; sample++) {
  92754. a_word = signal[0][sample];
  92755. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92756. *buf_++ = (FLAC__byte)a_word;
  92757. }
  92758. }
  92759. else {
  92760. for(sample = 0; sample < samples; sample++) {
  92761. for(channel = 0; channel < channels; channel++) {
  92762. a_word = signal[channel][sample];
  92763. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92764. *buf_++ = (FLAC__byte)a_word;
  92765. }
  92766. }
  92767. }
  92768. }
  92769. else if(bytes_per_sample == 3) {
  92770. if(channels == 2) {
  92771. for(sample = 0; sample < samples; sample++) {
  92772. a_word = signal[0][sample];
  92773. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92774. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92775. *buf_++ = (FLAC__byte)a_word;
  92776. a_word = signal[1][sample];
  92777. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92778. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92779. *buf_++ = (FLAC__byte)a_word;
  92780. }
  92781. }
  92782. else if(channels == 1) {
  92783. for(sample = 0; sample < samples; sample++) {
  92784. a_word = signal[0][sample];
  92785. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92786. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92787. *buf_++ = (FLAC__byte)a_word;
  92788. }
  92789. }
  92790. else {
  92791. for(sample = 0; sample < samples; sample++) {
  92792. for(channel = 0; channel < channels; channel++) {
  92793. a_word = signal[channel][sample];
  92794. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92795. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92796. *buf_++ = (FLAC__byte)a_word;
  92797. }
  92798. }
  92799. }
  92800. }
  92801. else if(bytes_per_sample == 1) {
  92802. if(channels == 2) {
  92803. for(sample = 0; sample < samples; sample++) {
  92804. a_word = signal[0][sample];
  92805. *buf_++ = (FLAC__byte)a_word;
  92806. a_word = signal[1][sample];
  92807. *buf_++ = (FLAC__byte)a_word;
  92808. }
  92809. }
  92810. else if(channels == 1) {
  92811. for(sample = 0; sample < samples; sample++) {
  92812. a_word = signal[0][sample];
  92813. *buf_++ = (FLAC__byte)a_word;
  92814. }
  92815. }
  92816. else {
  92817. for(sample = 0; sample < samples; sample++) {
  92818. for(channel = 0; channel < channels; channel++) {
  92819. a_word = signal[channel][sample];
  92820. *buf_++ = (FLAC__byte)a_word;
  92821. }
  92822. }
  92823. }
  92824. }
  92825. else { /* bytes_per_sample == 4, maybe optimize more later */
  92826. for(sample = 0; sample < samples; sample++) {
  92827. for(channel = 0; channel < channels; channel++) {
  92828. a_word = signal[channel][sample];
  92829. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92830. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92831. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92832. *buf_++ = (FLAC__byte)a_word;
  92833. }
  92834. }
  92835. }
  92836. }
  92837. /*
  92838. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  92839. */
  92840. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  92841. {
  92842. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  92843. /* overflow check */
  92844. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  92845. return false;
  92846. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  92847. return false;
  92848. if(ctx->capacity < bytes_needed) {
  92849. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  92850. if(0 == tmp) {
  92851. free(ctx->internal_buf);
  92852. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  92853. return false;
  92854. }
  92855. ctx->internal_buf = tmp;
  92856. ctx->capacity = bytes_needed;
  92857. }
  92858. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  92859. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  92860. return true;
  92861. }
  92862. #endif
  92863. /********* End of inlined file: md5.c *********/
  92864. /********* Start of inlined file: memory.c *********/
  92865. /********* Start of inlined file: juce_FlacHeader.h *********/
  92866. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92867. // tasks..
  92868. #define VERSION "1.2.1"
  92869. #define FLAC__NO_DLL 1
  92870. #ifdef _MSC_VER
  92871. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92872. #endif
  92873. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  92874. #define FLAC__SYS_DARWIN 1
  92875. #endif
  92876. /********* End of inlined file: juce_FlacHeader.h *********/
  92877. #if JUCE_USE_FLAC
  92878. #if HAVE_CONFIG_H
  92879. # include <config.h>
  92880. #endif
  92881. /********* Start of inlined file: memory.h *********/
  92882. #ifndef FLAC__PRIVATE__MEMORY_H
  92883. #define FLAC__PRIVATE__MEMORY_H
  92884. #ifdef HAVE_CONFIG_H
  92885. #include <config.h>
  92886. #endif
  92887. #include <stdlib.h> /* for size_t */
  92888. /* Returns the unaligned address returned by malloc.
  92889. * Use free() on this address to deallocate.
  92890. */
  92891. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  92892. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  92893. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  92894. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  92895. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  92896. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92897. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  92898. #endif
  92899. #endif
  92900. /********* End of inlined file: memory.h *********/
  92901. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  92902. {
  92903. void *x;
  92904. FLAC__ASSERT(0 != aligned_address);
  92905. #ifdef FLAC__ALIGN_MALLOC_DATA
  92906. /* align on 32-byte (256-bit) boundary */
  92907. x = safe_malloc_add_2op_(bytes, /*+*/31);
  92908. #ifdef SIZEOF_VOIDP
  92909. #if SIZEOF_VOIDP == 4
  92910. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  92911. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  92912. #elif SIZEOF_VOIDP == 8
  92913. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  92914. #else
  92915. # error Unsupported sizeof(void*)
  92916. #endif
  92917. #else
  92918. /* there's got to be a better way to do this right for all archs */
  92919. if(sizeof(void*) == sizeof(unsigned))
  92920. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  92921. else if(sizeof(void*) == sizeof(FLAC__uint64))
  92922. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  92923. else
  92924. return 0;
  92925. #endif
  92926. #else
  92927. x = safe_malloc_(bytes);
  92928. *aligned_address = x;
  92929. #endif
  92930. return x;
  92931. }
  92932. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  92933. {
  92934. FLAC__int32 *pu; /* unaligned pointer */
  92935. union { /* union needed to comply with C99 pointer aliasing rules */
  92936. FLAC__int32 *pa; /* aligned pointer */
  92937. void *pv; /* aligned pointer alias */
  92938. } u;
  92939. FLAC__ASSERT(elements > 0);
  92940. FLAC__ASSERT(0 != unaligned_pointer);
  92941. FLAC__ASSERT(0 != aligned_pointer);
  92942. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  92943. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  92944. return false;
  92945. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  92946. if(0 == pu) {
  92947. return false;
  92948. }
  92949. else {
  92950. if(*unaligned_pointer != 0)
  92951. free(*unaligned_pointer);
  92952. *unaligned_pointer = pu;
  92953. *aligned_pointer = u.pa;
  92954. return true;
  92955. }
  92956. }
  92957. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  92958. {
  92959. FLAC__uint32 *pu; /* unaligned pointer */
  92960. union { /* union needed to comply with C99 pointer aliasing rules */
  92961. FLAC__uint32 *pa; /* aligned pointer */
  92962. void *pv; /* aligned pointer alias */
  92963. } u;
  92964. FLAC__ASSERT(elements > 0);
  92965. FLAC__ASSERT(0 != unaligned_pointer);
  92966. FLAC__ASSERT(0 != aligned_pointer);
  92967. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  92968. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  92969. return false;
  92970. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  92971. if(0 == pu) {
  92972. return false;
  92973. }
  92974. else {
  92975. if(*unaligned_pointer != 0)
  92976. free(*unaligned_pointer);
  92977. *unaligned_pointer = pu;
  92978. *aligned_pointer = u.pa;
  92979. return true;
  92980. }
  92981. }
  92982. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  92983. {
  92984. FLAC__uint64 *pu; /* unaligned pointer */
  92985. union { /* union needed to comply with C99 pointer aliasing rules */
  92986. FLAC__uint64 *pa; /* aligned pointer */
  92987. void *pv; /* aligned pointer alias */
  92988. } u;
  92989. FLAC__ASSERT(elements > 0);
  92990. FLAC__ASSERT(0 != unaligned_pointer);
  92991. FLAC__ASSERT(0 != aligned_pointer);
  92992. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  92993. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  92994. return false;
  92995. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  92996. if(0 == pu) {
  92997. return false;
  92998. }
  92999. else {
  93000. if(*unaligned_pointer != 0)
  93001. free(*unaligned_pointer);
  93002. *unaligned_pointer = pu;
  93003. *aligned_pointer = u.pa;
  93004. return true;
  93005. }
  93006. }
  93007. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  93008. {
  93009. unsigned *pu; /* unaligned pointer */
  93010. union { /* union needed to comply with C99 pointer aliasing rules */
  93011. unsigned *pa; /* aligned pointer */
  93012. void *pv; /* aligned pointer alias */
  93013. } u;
  93014. FLAC__ASSERT(elements > 0);
  93015. FLAC__ASSERT(0 != unaligned_pointer);
  93016. FLAC__ASSERT(0 != aligned_pointer);
  93017. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  93018. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  93019. return false;
  93020. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  93021. if(0 == pu) {
  93022. return false;
  93023. }
  93024. else {
  93025. if(*unaligned_pointer != 0)
  93026. free(*unaligned_pointer);
  93027. *unaligned_pointer = pu;
  93028. *aligned_pointer = u.pa;
  93029. return true;
  93030. }
  93031. }
  93032. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93033. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  93034. {
  93035. FLAC__real *pu; /* unaligned pointer */
  93036. union { /* union needed to comply with C99 pointer aliasing rules */
  93037. FLAC__real *pa; /* aligned pointer */
  93038. void *pv; /* aligned pointer alias */
  93039. } u;
  93040. FLAC__ASSERT(elements > 0);
  93041. FLAC__ASSERT(0 != unaligned_pointer);
  93042. FLAC__ASSERT(0 != aligned_pointer);
  93043. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  93044. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  93045. return false;
  93046. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  93047. if(0 == pu) {
  93048. return false;
  93049. }
  93050. else {
  93051. if(*unaligned_pointer != 0)
  93052. free(*unaligned_pointer);
  93053. *unaligned_pointer = pu;
  93054. *aligned_pointer = u.pa;
  93055. return true;
  93056. }
  93057. }
  93058. #endif
  93059. #endif
  93060. /********* End of inlined file: memory.c *********/
  93061. /********* Start of inlined file: stream_decoder.c *********/
  93062. /********* Start of inlined file: juce_FlacHeader.h *********/
  93063. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93064. // tasks..
  93065. #define VERSION "1.2.1"
  93066. #define FLAC__NO_DLL 1
  93067. #ifdef _MSC_VER
  93068. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93069. #endif
  93070. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  93071. #define FLAC__SYS_DARWIN 1
  93072. #endif
  93073. /********* End of inlined file: juce_FlacHeader.h *********/
  93074. #if JUCE_USE_FLAC
  93075. #if HAVE_CONFIG_H
  93076. # include <config.h>
  93077. #endif
  93078. #if defined _MSC_VER || defined __MINGW32__
  93079. #include <io.h> /* for _setmode() */
  93080. #include <fcntl.h> /* for _O_BINARY */
  93081. #endif
  93082. #if defined __CYGWIN__ || defined __EMX__
  93083. #include <io.h> /* for setmode(), O_BINARY */
  93084. #include <fcntl.h> /* for _O_BINARY */
  93085. #endif
  93086. #include <stdio.h>
  93087. #include <stdlib.h> /* for malloc() */
  93088. #include <string.h> /* for memset/memcpy() */
  93089. #include <sys/stat.h> /* for stat() */
  93090. #include <sys/types.h> /* for off_t */
  93091. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  93092. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  93093. #define fseeko fseek
  93094. #define ftello ftell
  93095. #endif
  93096. #endif
  93097. /********* Start of inlined file: stream_decoder.h *********/
  93098. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  93099. #define FLAC__PROTECTED__STREAM_DECODER_H
  93100. #if FLAC__HAS_OGG
  93101. #include "include/private/ogg_decoder_aspect.h"
  93102. #endif
  93103. typedef struct FLAC__StreamDecoderProtected {
  93104. FLAC__StreamDecoderState state;
  93105. unsigned channels;
  93106. FLAC__ChannelAssignment channel_assignment;
  93107. unsigned bits_per_sample;
  93108. unsigned sample_rate; /* in Hz */
  93109. unsigned blocksize; /* in samples (per channel) */
  93110. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  93111. #if FLAC__HAS_OGG
  93112. FLAC__OggDecoderAspect ogg_decoder_aspect;
  93113. #endif
  93114. } FLAC__StreamDecoderProtected;
  93115. /*
  93116. * return the number of input bytes consumed
  93117. */
  93118. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  93119. #endif
  93120. /********* End of inlined file: stream_decoder.h *********/
  93121. #ifdef max
  93122. #undef max
  93123. #endif
  93124. #define max(a,b) ((a)>(b)?(a):(b))
  93125. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93126. #ifdef _MSC_VER
  93127. #define FLAC__U64L(x) x
  93128. #else
  93129. #define FLAC__U64L(x) x##LLU
  93130. #endif
  93131. /* technically this should be in an "export.c" but this is convenient enough */
  93132. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  93133. #if FLAC__HAS_OGG
  93134. 1
  93135. #else
  93136. 0
  93137. #endif
  93138. ;
  93139. /***********************************************************************
  93140. *
  93141. * Private static data
  93142. *
  93143. ***********************************************************************/
  93144. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  93145. /***********************************************************************
  93146. *
  93147. * Private class method prototypes
  93148. *
  93149. ***********************************************************************/
  93150. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  93151. static FILE *get_binary_stdin_(void);
  93152. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  93153. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  93154. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  93155. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  93156. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  93157. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  93158. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  93159. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  93160. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  93161. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  93162. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  93163. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  93164. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  93165. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  93166. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  93167. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  93168. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  93169. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  93170. static FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended);
  93171. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  93172. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  93173. #if FLAC__HAS_OGG
  93174. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  93175. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  93176. #endif
  93177. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  93178. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  93179. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  93180. #if FLAC__HAS_OGG
  93181. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  93182. #endif
  93183. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  93184. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  93185. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  93186. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  93187. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  93188. /***********************************************************************
  93189. *
  93190. * Private class data
  93191. *
  93192. ***********************************************************************/
  93193. typedef struct FLAC__StreamDecoderPrivate {
  93194. #if FLAC__HAS_OGG
  93195. FLAC__bool is_ogg;
  93196. #endif
  93197. FLAC__StreamDecoderReadCallback read_callback;
  93198. FLAC__StreamDecoderSeekCallback seek_callback;
  93199. FLAC__StreamDecoderTellCallback tell_callback;
  93200. FLAC__StreamDecoderLengthCallback length_callback;
  93201. FLAC__StreamDecoderEofCallback eof_callback;
  93202. FLAC__StreamDecoderWriteCallback write_callback;
  93203. FLAC__StreamDecoderMetadataCallback metadata_callback;
  93204. FLAC__StreamDecoderErrorCallback error_callback;
  93205. /* generic 32-bit datapath: */
  93206. void (*local_lpc_restore_signal)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  93207. /* generic 64-bit datapath: */
  93208. void (*local_lpc_restore_signal_64bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  93209. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  93210. void (*local_lpc_restore_signal_16bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  93211. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit), AND order <= 8: */
  93212. void (*local_lpc_restore_signal_16bit_order8)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  93213. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  93214. void *client_data;
  93215. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  93216. FLAC__BitReader *input;
  93217. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  93218. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  93219. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  93220. unsigned output_capacity, output_channels;
  93221. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  93222. FLAC__uint64 samples_decoded;
  93223. FLAC__bool has_stream_info, has_seek_table;
  93224. FLAC__StreamMetadata stream_info;
  93225. FLAC__StreamMetadata seek_table;
  93226. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  93227. FLAC__byte *metadata_filter_ids;
  93228. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  93229. FLAC__Frame frame;
  93230. FLAC__bool cached; /* true if there is a byte in lookahead */
  93231. FLAC__CPUInfo cpuinfo;
  93232. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  93233. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  93234. /* unaligned (original) pointers to allocated data */
  93235. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  93236. FLAC__bool do_md5_checking; /* initially gets protected_->md5_checking but is turned off after a seek or if the metadata has a zero MD5 */
  93237. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  93238. FLAC__bool is_seeking;
  93239. FLAC__MD5Context md5context;
  93240. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  93241. /* (the rest of these are only used for seeking) */
  93242. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  93243. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  93244. FLAC__uint64 target_sample;
  93245. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  93246. #if FLAC__HAS_OGG
  93247. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  93248. #endif
  93249. } FLAC__StreamDecoderPrivate;
  93250. /***********************************************************************
  93251. *
  93252. * Public static class data
  93253. *
  93254. ***********************************************************************/
  93255. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  93256. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  93257. "FLAC__STREAM_DECODER_READ_METADATA",
  93258. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  93259. "FLAC__STREAM_DECODER_READ_FRAME",
  93260. "FLAC__STREAM_DECODER_END_OF_STREAM",
  93261. "FLAC__STREAM_DECODER_OGG_ERROR",
  93262. "FLAC__STREAM_DECODER_SEEK_ERROR",
  93263. "FLAC__STREAM_DECODER_ABORTED",
  93264. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  93265. "FLAC__STREAM_DECODER_UNINITIALIZED"
  93266. };
  93267. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  93268. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  93269. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  93270. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  93271. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  93272. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  93273. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  93274. };
  93275. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  93276. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  93277. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  93278. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  93279. };
  93280. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  93281. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  93282. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  93283. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  93284. };
  93285. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  93286. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  93287. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  93288. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  93289. };
  93290. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  93291. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  93292. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  93293. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  93294. };
  93295. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  93296. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  93297. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  93298. };
  93299. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  93300. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  93301. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  93302. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  93303. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  93304. };
  93305. /***********************************************************************
  93306. *
  93307. * Class constructor/destructor
  93308. *
  93309. ***********************************************************************/
  93310. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  93311. {
  93312. FLAC__StreamDecoder *decoder;
  93313. unsigned i;
  93314. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  93315. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  93316. if(decoder == 0) {
  93317. return 0;
  93318. }
  93319. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  93320. if(decoder->protected_ == 0) {
  93321. free(decoder);
  93322. return 0;
  93323. }
  93324. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  93325. if(decoder->private_ == 0) {
  93326. free(decoder->protected_);
  93327. free(decoder);
  93328. return 0;
  93329. }
  93330. decoder->private_->input = FLAC__bitreader_new();
  93331. if(decoder->private_->input == 0) {
  93332. free(decoder->private_);
  93333. free(decoder->protected_);
  93334. free(decoder);
  93335. return 0;
  93336. }
  93337. decoder->private_->metadata_filter_ids_capacity = 16;
  93338. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  93339. FLAC__bitreader_delete(decoder->private_->input);
  93340. free(decoder->private_);
  93341. free(decoder->protected_);
  93342. free(decoder);
  93343. return 0;
  93344. }
  93345. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  93346. decoder->private_->output[i] = 0;
  93347. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  93348. }
  93349. decoder->private_->output_capacity = 0;
  93350. decoder->private_->output_channels = 0;
  93351. decoder->private_->has_seek_table = false;
  93352. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  93353. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  93354. decoder->private_->file = 0;
  93355. set_defaults_dec(decoder);
  93356. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  93357. return decoder;
  93358. }
  93359. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  93360. {
  93361. unsigned i;
  93362. FLAC__ASSERT(0 != decoder);
  93363. FLAC__ASSERT(0 != decoder->protected_);
  93364. FLAC__ASSERT(0 != decoder->private_);
  93365. FLAC__ASSERT(0 != decoder->private_->input);
  93366. (void)FLAC__stream_decoder_finish(decoder);
  93367. if(0 != decoder->private_->metadata_filter_ids)
  93368. free(decoder->private_->metadata_filter_ids);
  93369. FLAC__bitreader_delete(decoder->private_->input);
  93370. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  93371. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  93372. free(decoder->private_);
  93373. free(decoder->protected_);
  93374. free(decoder);
  93375. }
  93376. /***********************************************************************
  93377. *
  93378. * Public class methods
  93379. *
  93380. ***********************************************************************/
  93381. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  93382. FLAC__StreamDecoder *decoder,
  93383. FLAC__StreamDecoderReadCallback read_callback,
  93384. FLAC__StreamDecoderSeekCallback seek_callback,
  93385. FLAC__StreamDecoderTellCallback tell_callback,
  93386. FLAC__StreamDecoderLengthCallback length_callback,
  93387. FLAC__StreamDecoderEofCallback eof_callback,
  93388. FLAC__StreamDecoderWriteCallback write_callback,
  93389. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93390. FLAC__StreamDecoderErrorCallback error_callback,
  93391. void *client_data,
  93392. FLAC__bool is_ogg
  93393. )
  93394. {
  93395. FLAC__ASSERT(0 != decoder);
  93396. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93397. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  93398. #if !FLAC__HAS_OGG
  93399. if(is_ogg)
  93400. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  93401. #endif
  93402. if(
  93403. 0 == read_callback ||
  93404. 0 == write_callback ||
  93405. 0 == error_callback ||
  93406. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  93407. )
  93408. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  93409. #if FLAC__HAS_OGG
  93410. decoder->private_->is_ogg = is_ogg;
  93411. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  93412. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  93413. #endif
  93414. /*
  93415. * get the CPU info and set the function pointers
  93416. */
  93417. FLAC__cpu_info(&decoder->private_->cpuinfo);
  93418. /* first default to the non-asm routines */
  93419. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  93420. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  93421. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  93422. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  93423. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  93424. /* now override with asm where appropriate */
  93425. #ifndef FLAC__NO_ASM
  93426. if(decoder->private_->cpuinfo.use_asm) {
  93427. #ifdef FLAC__CPU_IA32
  93428. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  93429. #ifdef FLAC__HAS_NASM
  93430. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  93431. if(decoder->private_->cpuinfo.data.ia32.bswap)
  93432. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  93433. #endif
  93434. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  93435. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  93436. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  93437. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  93438. }
  93439. else {
  93440. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  93441. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  93442. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  93443. }
  93444. #endif
  93445. #elif defined FLAC__CPU_PPC
  93446. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  93447. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  93448. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  93449. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  93450. }
  93451. #endif
  93452. }
  93453. #endif
  93454. /* from here on, errors are fatal */
  93455. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  93456. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93457. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  93458. }
  93459. decoder->private_->read_callback = read_callback;
  93460. decoder->private_->seek_callback = seek_callback;
  93461. decoder->private_->tell_callback = tell_callback;
  93462. decoder->private_->length_callback = length_callback;
  93463. decoder->private_->eof_callback = eof_callback;
  93464. decoder->private_->write_callback = write_callback;
  93465. decoder->private_->metadata_callback = metadata_callback;
  93466. decoder->private_->error_callback = error_callback;
  93467. decoder->private_->client_data = client_data;
  93468. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  93469. decoder->private_->samples_decoded = 0;
  93470. decoder->private_->has_stream_info = false;
  93471. decoder->private_->cached = false;
  93472. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  93473. decoder->private_->is_seeking = false;
  93474. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  93475. if(!FLAC__stream_decoder_reset(decoder)) {
  93476. /* above call sets the state for us */
  93477. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  93478. }
  93479. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  93480. }
  93481. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  93482. FLAC__StreamDecoder *decoder,
  93483. FLAC__StreamDecoderReadCallback read_callback,
  93484. FLAC__StreamDecoderSeekCallback seek_callback,
  93485. FLAC__StreamDecoderTellCallback tell_callback,
  93486. FLAC__StreamDecoderLengthCallback length_callback,
  93487. FLAC__StreamDecoderEofCallback eof_callback,
  93488. FLAC__StreamDecoderWriteCallback write_callback,
  93489. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93490. FLAC__StreamDecoderErrorCallback error_callback,
  93491. void *client_data
  93492. )
  93493. {
  93494. return init_stream_internal_dec(
  93495. decoder,
  93496. read_callback,
  93497. seek_callback,
  93498. tell_callback,
  93499. length_callback,
  93500. eof_callback,
  93501. write_callback,
  93502. metadata_callback,
  93503. error_callback,
  93504. client_data,
  93505. /*is_ogg=*/false
  93506. );
  93507. }
  93508. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  93509. FLAC__StreamDecoder *decoder,
  93510. FLAC__StreamDecoderReadCallback read_callback,
  93511. FLAC__StreamDecoderSeekCallback seek_callback,
  93512. FLAC__StreamDecoderTellCallback tell_callback,
  93513. FLAC__StreamDecoderLengthCallback length_callback,
  93514. FLAC__StreamDecoderEofCallback eof_callback,
  93515. FLAC__StreamDecoderWriteCallback write_callback,
  93516. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93517. FLAC__StreamDecoderErrorCallback error_callback,
  93518. void *client_data
  93519. )
  93520. {
  93521. return init_stream_internal_dec(
  93522. decoder,
  93523. read_callback,
  93524. seek_callback,
  93525. tell_callback,
  93526. length_callback,
  93527. eof_callback,
  93528. write_callback,
  93529. metadata_callback,
  93530. error_callback,
  93531. client_data,
  93532. /*is_ogg=*/true
  93533. );
  93534. }
  93535. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  93536. FLAC__StreamDecoder *decoder,
  93537. FILE *file,
  93538. FLAC__StreamDecoderWriteCallback write_callback,
  93539. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93540. FLAC__StreamDecoderErrorCallback error_callback,
  93541. void *client_data,
  93542. FLAC__bool is_ogg
  93543. )
  93544. {
  93545. FLAC__ASSERT(0 != decoder);
  93546. FLAC__ASSERT(0 != file);
  93547. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93548. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  93549. if(0 == write_callback || 0 == error_callback)
  93550. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  93551. /*
  93552. * To make sure that our file does not go unclosed after an error, we
  93553. * must assign the FILE pointer before any further error can occur in
  93554. * this routine.
  93555. */
  93556. if(file == stdin)
  93557. file = get_binary_stdin_(); /* just to be safe */
  93558. decoder->private_->file = file;
  93559. return init_stream_internal_dec(
  93560. decoder,
  93561. file_read_callback_dec,
  93562. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  93563. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  93564. decoder->private_->file == stdin? 0: file_length_callback_,
  93565. file_eof_callback_,
  93566. write_callback,
  93567. metadata_callback,
  93568. error_callback,
  93569. client_data,
  93570. is_ogg
  93571. );
  93572. }
  93573. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  93574. FLAC__StreamDecoder *decoder,
  93575. FILE *file,
  93576. FLAC__StreamDecoderWriteCallback write_callback,
  93577. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93578. FLAC__StreamDecoderErrorCallback error_callback,
  93579. void *client_data
  93580. )
  93581. {
  93582. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  93583. }
  93584. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  93585. FLAC__StreamDecoder *decoder,
  93586. FILE *file,
  93587. FLAC__StreamDecoderWriteCallback write_callback,
  93588. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93589. FLAC__StreamDecoderErrorCallback error_callback,
  93590. void *client_data
  93591. )
  93592. {
  93593. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  93594. }
  93595. static FLAC__StreamDecoderInitStatus init_file_internal_(
  93596. FLAC__StreamDecoder *decoder,
  93597. const char *filename,
  93598. FLAC__StreamDecoderWriteCallback write_callback,
  93599. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93600. FLAC__StreamDecoderErrorCallback error_callback,
  93601. void *client_data,
  93602. FLAC__bool is_ogg
  93603. )
  93604. {
  93605. FILE *file;
  93606. FLAC__ASSERT(0 != decoder);
  93607. /*
  93608. * To make sure that our file does not go unclosed after an error, we
  93609. * have to do the same entrance checks here that are later performed
  93610. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  93611. */
  93612. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93613. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  93614. if(0 == write_callback || 0 == error_callback)
  93615. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  93616. file = filename? fopen(filename, "rb") : stdin;
  93617. if(0 == file)
  93618. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  93619. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  93620. }
  93621. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  93622. FLAC__StreamDecoder *decoder,
  93623. const char *filename,
  93624. FLAC__StreamDecoderWriteCallback write_callback,
  93625. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93626. FLAC__StreamDecoderErrorCallback error_callback,
  93627. void *client_data
  93628. )
  93629. {
  93630. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  93631. }
  93632. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  93633. FLAC__StreamDecoder *decoder,
  93634. const char *filename,
  93635. FLAC__StreamDecoderWriteCallback write_callback,
  93636. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93637. FLAC__StreamDecoderErrorCallback error_callback,
  93638. void *client_data
  93639. )
  93640. {
  93641. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  93642. }
  93643. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  93644. {
  93645. FLAC__bool md5_failed = false;
  93646. unsigned i;
  93647. FLAC__ASSERT(0 != decoder);
  93648. FLAC__ASSERT(0 != decoder->private_);
  93649. FLAC__ASSERT(0 != decoder->protected_);
  93650. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  93651. return true;
  93652. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  93653. * always call FLAC__MD5Final()
  93654. */
  93655. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  93656. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  93657. free(decoder->private_->seek_table.data.seek_table.points);
  93658. decoder->private_->seek_table.data.seek_table.points = 0;
  93659. decoder->private_->has_seek_table = false;
  93660. }
  93661. FLAC__bitreader_free(decoder->private_->input);
  93662. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  93663. /* WATCHOUT:
  93664. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  93665. * output arrays have a buffer of up to 3 zeroes in front
  93666. * (at negative indices) for alignment purposes; we use 4
  93667. * to keep the data well-aligned.
  93668. */
  93669. if(0 != decoder->private_->output[i]) {
  93670. free(decoder->private_->output[i]-4);
  93671. decoder->private_->output[i] = 0;
  93672. }
  93673. if(0 != decoder->private_->residual_unaligned[i]) {
  93674. free(decoder->private_->residual_unaligned[i]);
  93675. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  93676. }
  93677. }
  93678. decoder->private_->output_capacity = 0;
  93679. decoder->private_->output_channels = 0;
  93680. #if FLAC__HAS_OGG
  93681. if(decoder->private_->is_ogg)
  93682. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  93683. #endif
  93684. if(0 != decoder->private_->file) {
  93685. if(decoder->private_->file != stdin)
  93686. fclose(decoder->private_->file);
  93687. decoder->private_->file = 0;
  93688. }
  93689. if(decoder->private_->do_md5_checking) {
  93690. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  93691. md5_failed = true;
  93692. }
  93693. decoder->private_->is_seeking = false;
  93694. set_defaults_dec(decoder);
  93695. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  93696. return !md5_failed;
  93697. }
  93698. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  93699. {
  93700. FLAC__ASSERT(0 != decoder);
  93701. FLAC__ASSERT(0 != decoder->private_);
  93702. FLAC__ASSERT(0 != decoder->protected_);
  93703. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93704. return false;
  93705. #if FLAC__HAS_OGG
  93706. /* can't check decoder->private_->is_ogg since that's not set until init time */
  93707. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  93708. return true;
  93709. #else
  93710. (void)value;
  93711. return false;
  93712. #endif
  93713. }
  93714. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  93715. {
  93716. FLAC__ASSERT(0 != decoder);
  93717. FLAC__ASSERT(0 != decoder->protected_);
  93718. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93719. return false;
  93720. decoder->protected_->md5_checking = value;
  93721. return true;
  93722. }
  93723. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  93724. {
  93725. FLAC__ASSERT(0 != decoder);
  93726. FLAC__ASSERT(0 != decoder->private_);
  93727. FLAC__ASSERT(0 != decoder->protected_);
  93728. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  93729. /* double protection */
  93730. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  93731. return false;
  93732. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93733. return false;
  93734. decoder->private_->metadata_filter[type] = true;
  93735. if(type == FLAC__METADATA_TYPE_APPLICATION)
  93736. decoder->private_->metadata_filter_ids_count = 0;
  93737. return true;
  93738. }
  93739. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  93740. {
  93741. FLAC__ASSERT(0 != decoder);
  93742. FLAC__ASSERT(0 != decoder->private_);
  93743. FLAC__ASSERT(0 != decoder->protected_);
  93744. FLAC__ASSERT(0 != id);
  93745. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93746. return false;
  93747. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  93748. return true;
  93749. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  93750. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  93751. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)safe_realloc_mul_2op_(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity, /*times*/2))) {
  93752. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93753. return false;
  93754. }
  93755. decoder->private_->metadata_filter_ids_capacity *= 2;
  93756. }
  93757. memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
  93758. decoder->private_->metadata_filter_ids_count++;
  93759. return true;
  93760. }
  93761. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  93762. {
  93763. unsigned i;
  93764. FLAC__ASSERT(0 != decoder);
  93765. FLAC__ASSERT(0 != decoder->private_);
  93766. FLAC__ASSERT(0 != decoder->protected_);
  93767. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93768. return false;
  93769. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  93770. decoder->private_->metadata_filter[i] = true;
  93771. decoder->private_->metadata_filter_ids_count = 0;
  93772. return true;
  93773. }
  93774. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  93775. {
  93776. FLAC__ASSERT(0 != decoder);
  93777. FLAC__ASSERT(0 != decoder->private_);
  93778. FLAC__ASSERT(0 != decoder->protected_);
  93779. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  93780. /* double protection */
  93781. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  93782. return false;
  93783. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93784. return false;
  93785. decoder->private_->metadata_filter[type] = false;
  93786. if(type == FLAC__METADATA_TYPE_APPLICATION)
  93787. decoder->private_->metadata_filter_ids_count = 0;
  93788. return true;
  93789. }
  93790. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  93791. {
  93792. FLAC__ASSERT(0 != decoder);
  93793. FLAC__ASSERT(0 != decoder->private_);
  93794. FLAC__ASSERT(0 != decoder->protected_);
  93795. FLAC__ASSERT(0 != id);
  93796. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93797. return false;
  93798. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  93799. return true;
  93800. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  93801. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  93802. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)safe_realloc_mul_2op_(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity, /*times*/2))) {
  93803. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93804. return false;
  93805. }
  93806. decoder->private_->metadata_filter_ids_capacity *= 2;
  93807. }
  93808. memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
  93809. decoder->private_->metadata_filter_ids_count++;
  93810. return true;
  93811. }
  93812. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  93813. {
  93814. FLAC__ASSERT(0 != decoder);
  93815. FLAC__ASSERT(0 != decoder->private_);
  93816. FLAC__ASSERT(0 != decoder->protected_);
  93817. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93818. return false;
  93819. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  93820. decoder->private_->metadata_filter_ids_count = 0;
  93821. return true;
  93822. }
  93823. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  93824. {
  93825. FLAC__ASSERT(0 != decoder);
  93826. FLAC__ASSERT(0 != decoder->protected_);
  93827. return decoder->protected_->state;
  93828. }
  93829. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  93830. {
  93831. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  93832. }
  93833. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  93834. {
  93835. FLAC__ASSERT(0 != decoder);
  93836. FLAC__ASSERT(0 != decoder->protected_);
  93837. return decoder->protected_->md5_checking;
  93838. }
  93839. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  93840. {
  93841. FLAC__ASSERT(0 != decoder);
  93842. FLAC__ASSERT(0 != decoder->protected_);
  93843. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  93844. }
  93845. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  93846. {
  93847. FLAC__ASSERT(0 != decoder);
  93848. FLAC__ASSERT(0 != decoder->protected_);
  93849. return decoder->protected_->channels;
  93850. }
  93851. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  93852. {
  93853. FLAC__ASSERT(0 != decoder);
  93854. FLAC__ASSERT(0 != decoder->protected_);
  93855. return decoder->protected_->channel_assignment;
  93856. }
  93857. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  93858. {
  93859. FLAC__ASSERT(0 != decoder);
  93860. FLAC__ASSERT(0 != decoder->protected_);
  93861. return decoder->protected_->bits_per_sample;
  93862. }
  93863. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  93864. {
  93865. FLAC__ASSERT(0 != decoder);
  93866. FLAC__ASSERT(0 != decoder->protected_);
  93867. return decoder->protected_->sample_rate;
  93868. }
  93869. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  93870. {
  93871. FLAC__ASSERT(0 != decoder);
  93872. FLAC__ASSERT(0 != decoder->protected_);
  93873. return decoder->protected_->blocksize;
  93874. }
  93875. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  93876. {
  93877. FLAC__ASSERT(0 != decoder);
  93878. FLAC__ASSERT(0 != decoder->private_);
  93879. FLAC__ASSERT(0 != position);
  93880. #if FLAC__HAS_OGG
  93881. if(decoder->private_->is_ogg)
  93882. return false;
  93883. #endif
  93884. if(0 == decoder->private_->tell_callback)
  93885. return false;
  93886. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  93887. return false;
  93888. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  93889. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  93890. return false;
  93891. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  93892. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  93893. return true;
  93894. }
  93895. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  93896. {
  93897. FLAC__ASSERT(0 != decoder);
  93898. FLAC__ASSERT(0 != decoder->private_);
  93899. FLAC__ASSERT(0 != decoder->protected_);
  93900. decoder->private_->samples_decoded = 0;
  93901. decoder->private_->do_md5_checking = false;
  93902. #if FLAC__HAS_OGG
  93903. if(decoder->private_->is_ogg)
  93904. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  93905. #endif
  93906. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  93907. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93908. return false;
  93909. }
  93910. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  93911. return true;
  93912. }
  93913. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  93914. {
  93915. FLAC__ASSERT(0 != decoder);
  93916. FLAC__ASSERT(0 != decoder->private_);
  93917. FLAC__ASSERT(0 != decoder->protected_);
  93918. if(!FLAC__stream_decoder_flush(decoder)) {
  93919. /* above call sets the state for us */
  93920. return false;
  93921. }
  93922. #if FLAC__HAS_OGG
  93923. /*@@@ could go in !internal_reset_hack block below */
  93924. if(decoder->private_->is_ogg)
  93925. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  93926. #endif
  93927. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  93928. * (internal_reset_hack) don't try to rewind since we are already at
  93929. * the beginning of the stream and don't want to fail if the input is
  93930. * not seekable.
  93931. */
  93932. if(!decoder->private_->internal_reset_hack) {
  93933. if(decoder->private_->file == stdin)
  93934. return false; /* can't rewind stdin, reset fails */
  93935. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  93936. return false; /* seekable and seek fails, reset fails */
  93937. }
  93938. else
  93939. decoder->private_->internal_reset_hack = false;
  93940. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  93941. decoder->private_->has_stream_info = false;
  93942. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  93943. free(decoder->private_->seek_table.data.seek_table.points);
  93944. decoder->private_->seek_table.data.seek_table.points = 0;
  93945. decoder->private_->has_seek_table = false;
  93946. }
  93947. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  93948. /*
  93949. * This goes in reset() and not flush() because according to the spec, a
  93950. * fixed-blocksize stream must stay that way through the whole stream.
  93951. */
  93952. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  93953. /* We initialize the FLAC__MD5Context even though we may never use it. This
  93954. * is because md5 checking may be turned on to start and then turned off if
  93955. * a seek occurs. So we init the context here and finalize it in
  93956. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  93957. * properly.
  93958. */
  93959. FLAC__MD5Init(&decoder->private_->md5context);
  93960. decoder->private_->first_frame_offset = 0;
  93961. decoder->private_->unparseable_frame_count = 0;
  93962. return true;
  93963. }
  93964. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  93965. {
  93966. FLAC__bool got_a_frame;
  93967. FLAC__ASSERT(0 != decoder);
  93968. FLAC__ASSERT(0 != decoder->protected_);
  93969. while(1) {
  93970. switch(decoder->protected_->state) {
  93971. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  93972. if(!find_metadata_(decoder))
  93973. return false; /* above function sets the status for us */
  93974. break;
  93975. case FLAC__STREAM_DECODER_READ_METADATA:
  93976. if(!read_metadata_(decoder))
  93977. return false; /* above function sets the status for us */
  93978. else
  93979. return true;
  93980. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  93981. if(!frame_sync_(decoder))
  93982. return true; /* above function sets the status for us */
  93983. break;
  93984. case FLAC__STREAM_DECODER_READ_FRAME:
  93985. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  93986. return false; /* above function sets the status for us */
  93987. if(got_a_frame)
  93988. return true; /* above function sets the status for us */
  93989. break;
  93990. case FLAC__STREAM_DECODER_END_OF_STREAM:
  93991. case FLAC__STREAM_DECODER_ABORTED:
  93992. return true;
  93993. default:
  93994. FLAC__ASSERT(0);
  93995. return false;
  93996. }
  93997. }
  93998. }
  93999. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  94000. {
  94001. FLAC__ASSERT(0 != decoder);
  94002. FLAC__ASSERT(0 != decoder->protected_);
  94003. while(1) {
  94004. switch(decoder->protected_->state) {
  94005. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  94006. if(!find_metadata_(decoder))
  94007. return false; /* above function sets the status for us */
  94008. break;
  94009. case FLAC__STREAM_DECODER_READ_METADATA:
  94010. if(!read_metadata_(decoder))
  94011. return false; /* above function sets the status for us */
  94012. break;
  94013. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  94014. case FLAC__STREAM_DECODER_READ_FRAME:
  94015. case FLAC__STREAM_DECODER_END_OF_STREAM:
  94016. case FLAC__STREAM_DECODER_ABORTED:
  94017. return true;
  94018. default:
  94019. FLAC__ASSERT(0);
  94020. return false;
  94021. }
  94022. }
  94023. }
  94024. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  94025. {
  94026. FLAC__bool dummy;
  94027. FLAC__ASSERT(0 != decoder);
  94028. FLAC__ASSERT(0 != decoder->protected_);
  94029. while(1) {
  94030. switch(decoder->protected_->state) {
  94031. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  94032. if(!find_metadata_(decoder))
  94033. return false; /* above function sets the status for us */
  94034. break;
  94035. case FLAC__STREAM_DECODER_READ_METADATA:
  94036. if(!read_metadata_(decoder))
  94037. return false; /* above function sets the status for us */
  94038. break;
  94039. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  94040. if(!frame_sync_(decoder))
  94041. return true; /* above function sets the status for us */
  94042. break;
  94043. case FLAC__STREAM_DECODER_READ_FRAME:
  94044. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  94045. return false; /* above function sets the status for us */
  94046. break;
  94047. case FLAC__STREAM_DECODER_END_OF_STREAM:
  94048. case FLAC__STREAM_DECODER_ABORTED:
  94049. return true;
  94050. default:
  94051. FLAC__ASSERT(0);
  94052. return false;
  94053. }
  94054. }
  94055. }
  94056. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  94057. {
  94058. FLAC__bool got_a_frame;
  94059. FLAC__ASSERT(0 != decoder);
  94060. FLAC__ASSERT(0 != decoder->protected_);
  94061. while(1) {
  94062. switch(decoder->protected_->state) {
  94063. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  94064. case FLAC__STREAM_DECODER_READ_METADATA:
  94065. return false; /* above function sets the status for us */
  94066. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  94067. if(!frame_sync_(decoder))
  94068. return true; /* above function sets the status for us */
  94069. break;
  94070. case FLAC__STREAM_DECODER_READ_FRAME:
  94071. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  94072. return false; /* above function sets the status for us */
  94073. if(got_a_frame)
  94074. return true; /* above function sets the status for us */
  94075. break;
  94076. case FLAC__STREAM_DECODER_END_OF_STREAM:
  94077. case FLAC__STREAM_DECODER_ABORTED:
  94078. return true;
  94079. default:
  94080. FLAC__ASSERT(0);
  94081. return false;
  94082. }
  94083. }
  94084. }
  94085. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  94086. {
  94087. FLAC__uint64 length;
  94088. FLAC__ASSERT(0 != decoder);
  94089. if(
  94090. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  94091. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  94092. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  94093. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  94094. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  94095. )
  94096. return false;
  94097. if(0 == decoder->private_->seek_callback)
  94098. return false;
  94099. FLAC__ASSERT(decoder->private_->seek_callback);
  94100. FLAC__ASSERT(decoder->private_->tell_callback);
  94101. FLAC__ASSERT(decoder->private_->length_callback);
  94102. FLAC__ASSERT(decoder->private_->eof_callback);
  94103. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  94104. return false;
  94105. decoder->private_->is_seeking = true;
  94106. /* turn off md5 checking if a seek is attempted */
  94107. decoder->private_->do_md5_checking = false;
  94108. /* get the file length (currently our algorithm needs to know the length so it's also an error to get FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED) */
  94109. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  94110. decoder->private_->is_seeking = false;
  94111. return false;
  94112. }
  94113. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  94114. if(
  94115. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  94116. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  94117. ) {
  94118. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  94119. /* above call sets the state for us */
  94120. decoder->private_->is_seeking = false;
  94121. return false;
  94122. }
  94123. /* check this again in case we didn't know total_samples the first time */
  94124. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  94125. decoder->private_->is_seeking = false;
  94126. return false;
  94127. }
  94128. }
  94129. {
  94130. const FLAC__bool ok =
  94131. #if FLAC__HAS_OGG
  94132. decoder->private_->is_ogg?
  94133. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  94134. #endif
  94135. seek_to_absolute_sample_(decoder, length, sample)
  94136. ;
  94137. decoder->private_->is_seeking = false;
  94138. return ok;
  94139. }
  94140. }
  94141. /***********************************************************************
  94142. *
  94143. * Protected class methods
  94144. *
  94145. ***********************************************************************/
  94146. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  94147. {
  94148. FLAC__ASSERT(0 != decoder);
  94149. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94150. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  94151. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  94152. }
  94153. /***********************************************************************
  94154. *
  94155. * Private class methods
  94156. *
  94157. ***********************************************************************/
  94158. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  94159. {
  94160. #if FLAC__HAS_OGG
  94161. decoder->private_->is_ogg = false;
  94162. #endif
  94163. decoder->private_->read_callback = 0;
  94164. decoder->private_->seek_callback = 0;
  94165. decoder->private_->tell_callback = 0;
  94166. decoder->private_->length_callback = 0;
  94167. decoder->private_->eof_callback = 0;
  94168. decoder->private_->write_callback = 0;
  94169. decoder->private_->metadata_callback = 0;
  94170. decoder->private_->error_callback = 0;
  94171. decoder->private_->client_data = 0;
  94172. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  94173. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  94174. decoder->private_->metadata_filter_ids_count = 0;
  94175. decoder->protected_->md5_checking = false;
  94176. #if FLAC__HAS_OGG
  94177. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  94178. #endif
  94179. }
  94180. /*
  94181. * This will forcibly set stdin to binary mode (for OSes that require it)
  94182. */
  94183. FILE *get_binary_stdin_(void)
  94184. {
  94185. /* if something breaks here it is probably due to the presence or
  94186. * absence of an underscore before the identifiers 'setmode',
  94187. * 'fileno', and/or 'O_BINARY'; check your system header files.
  94188. */
  94189. #if defined _MSC_VER || defined __MINGW32__
  94190. _setmode(_fileno(stdin), _O_BINARY);
  94191. #elif defined __CYGWIN__
  94192. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  94193. setmode(_fileno(stdin), _O_BINARY);
  94194. #elif defined __EMX__
  94195. setmode(fileno(stdin), O_BINARY);
  94196. #endif
  94197. return stdin;
  94198. }
  94199. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  94200. {
  94201. unsigned i;
  94202. FLAC__int32 *tmp;
  94203. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  94204. return true;
  94205. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  94206. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  94207. if(0 != decoder->private_->output[i]) {
  94208. free(decoder->private_->output[i]-4);
  94209. decoder->private_->output[i] = 0;
  94210. }
  94211. if(0 != decoder->private_->residual_unaligned[i]) {
  94212. free(decoder->private_->residual_unaligned[i]);
  94213. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  94214. }
  94215. }
  94216. for(i = 0; i < channels; i++) {
  94217. /* WATCHOUT:
  94218. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  94219. * output arrays have a buffer of up to 3 zeroes in front
  94220. * (at negative indices) for alignment purposes; we use 4
  94221. * to keep the data well-aligned.
  94222. */
  94223. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  94224. if(tmp == 0) {
  94225. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94226. return false;
  94227. }
  94228. memset(tmp, 0, sizeof(FLAC__int32)*4);
  94229. decoder->private_->output[i] = tmp + 4;
  94230. /* WATCHOUT:
  94231. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  94232. */
  94233. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  94234. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94235. return false;
  94236. }
  94237. }
  94238. decoder->private_->output_capacity = size;
  94239. decoder->private_->output_channels = channels;
  94240. return true;
  94241. }
  94242. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  94243. {
  94244. size_t i;
  94245. FLAC__ASSERT(0 != decoder);
  94246. FLAC__ASSERT(0 != decoder->private_);
  94247. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  94248. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  94249. return true;
  94250. return false;
  94251. }
  94252. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  94253. {
  94254. FLAC__uint32 x;
  94255. unsigned i, id_;
  94256. FLAC__bool first = true;
  94257. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94258. for(i = id_ = 0; i < 4; ) {
  94259. if(decoder->private_->cached) {
  94260. x = (FLAC__uint32)decoder->private_->lookahead;
  94261. decoder->private_->cached = false;
  94262. }
  94263. else {
  94264. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94265. return false; /* read_callback_ sets the state for us */
  94266. }
  94267. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  94268. first = true;
  94269. i++;
  94270. id_ = 0;
  94271. continue;
  94272. }
  94273. if(x == ID3V2_TAG_[id_]) {
  94274. id_++;
  94275. i = 0;
  94276. if(id_ == 3) {
  94277. if(!skip_id3v2_tag_(decoder))
  94278. return false; /* skip_id3v2_tag_ sets the state for us */
  94279. }
  94280. continue;
  94281. }
  94282. id_ = 0;
  94283. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94284. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  94285. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94286. return false; /* read_callback_ sets the state for us */
  94287. /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */
  94288. /* else we have to check if the second byte is the end of a sync code */
  94289. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94290. decoder->private_->lookahead = (FLAC__byte)x;
  94291. decoder->private_->cached = true;
  94292. }
  94293. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  94294. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  94295. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  94296. return true;
  94297. }
  94298. }
  94299. i = 0;
  94300. if(first) {
  94301. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94302. first = false;
  94303. }
  94304. }
  94305. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  94306. return true;
  94307. }
  94308. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  94309. {
  94310. FLAC__bool is_last;
  94311. FLAC__uint32 i, x, type, length;
  94312. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94313. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  94314. return false; /* read_callback_ sets the state for us */
  94315. is_last = x? true : false;
  94316. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  94317. return false; /* read_callback_ sets the state for us */
  94318. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  94319. return false; /* read_callback_ sets the state for us */
  94320. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  94321. if(!read_metadata_streaminfo_(decoder, is_last, length))
  94322. return false;
  94323. decoder->private_->has_stream_info = true;
  94324. if(0 == memcmp(decoder->private_->stream_info.data.stream_info.md5sum, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16))
  94325. decoder->private_->do_md5_checking = false;
  94326. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  94327. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  94328. }
  94329. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  94330. if(!read_metadata_seektable_(decoder, is_last, length))
  94331. return false;
  94332. decoder->private_->has_seek_table = true;
  94333. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  94334. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  94335. }
  94336. else {
  94337. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  94338. unsigned real_length = length;
  94339. FLAC__StreamMetadata block;
  94340. block.is_last = is_last;
  94341. block.type = (FLAC__MetadataType)type;
  94342. block.length = length;
  94343. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  94344. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  94345. return false; /* read_callback_ sets the state for us */
  94346. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  94347. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  94348. return false;
  94349. }
  94350. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  94351. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  94352. skip_it = !skip_it;
  94353. }
  94354. if(skip_it) {
  94355. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  94356. return false; /* read_callback_ sets the state for us */
  94357. }
  94358. else {
  94359. switch(type) {
  94360. case FLAC__METADATA_TYPE_PADDING:
  94361. /* skip the padding bytes */
  94362. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  94363. return false; /* read_callback_ sets the state for us */
  94364. break;
  94365. case FLAC__METADATA_TYPE_APPLICATION:
  94366. /* remember, we read the ID already */
  94367. if(real_length > 0) {
  94368. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  94369. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94370. return false;
  94371. }
  94372. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  94373. return false; /* read_callback_ sets the state for us */
  94374. }
  94375. else
  94376. block.data.application.data = 0;
  94377. break;
  94378. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  94379. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  94380. return false;
  94381. break;
  94382. case FLAC__METADATA_TYPE_CUESHEET:
  94383. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  94384. return false;
  94385. break;
  94386. case FLAC__METADATA_TYPE_PICTURE:
  94387. if(!read_metadata_picture_(decoder, &block.data.picture))
  94388. return false;
  94389. break;
  94390. case FLAC__METADATA_TYPE_STREAMINFO:
  94391. case FLAC__METADATA_TYPE_SEEKTABLE:
  94392. FLAC__ASSERT(0);
  94393. break;
  94394. default:
  94395. if(real_length > 0) {
  94396. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  94397. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94398. return false;
  94399. }
  94400. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  94401. return false; /* read_callback_ sets the state for us */
  94402. }
  94403. else
  94404. block.data.unknown.data = 0;
  94405. break;
  94406. }
  94407. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  94408. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  94409. /* now we have to free any malloc()ed data in the block */
  94410. switch(type) {
  94411. case FLAC__METADATA_TYPE_PADDING:
  94412. break;
  94413. case FLAC__METADATA_TYPE_APPLICATION:
  94414. if(0 != block.data.application.data)
  94415. free(block.data.application.data);
  94416. break;
  94417. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  94418. if(0 != block.data.vorbis_comment.vendor_string.entry)
  94419. free(block.data.vorbis_comment.vendor_string.entry);
  94420. if(block.data.vorbis_comment.num_comments > 0)
  94421. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  94422. if(0 != block.data.vorbis_comment.comments[i].entry)
  94423. free(block.data.vorbis_comment.comments[i].entry);
  94424. if(0 != block.data.vorbis_comment.comments)
  94425. free(block.data.vorbis_comment.comments);
  94426. break;
  94427. case FLAC__METADATA_TYPE_CUESHEET:
  94428. if(block.data.cue_sheet.num_tracks > 0)
  94429. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  94430. if(0 != block.data.cue_sheet.tracks[i].indices)
  94431. free(block.data.cue_sheet.tracks[i].indices);
  94432. if(0 != block.data.cue_sheet.tracks)
  94433. free(block.data.cue_sheet.tracks);
  94434. break;
  94435. case FLAC__METADATA_TYPE_PICTURE:
  94436. if(0 != block.data.picture.mime_type)
  94437. free(block.data.picture.mime_type);
  94438. if(0 != block.data.picture.description)
  94439. free(block.data.picture.description);
  94440. if(0 != block.data.picture.data)
  94441. free(block.data.picture.data);
  94442. break;
  94443. case FLAC__METADATA_TYPE_STREAMINFO:
  94444. case FLAC__METADATA_TYPE_SEEKTABLE:
  94445. FLAC__ASSERT(0);
  94446. default:
  94447. if(0 != block.data.unknown.data)
  94448. free(block.data.unknown.data);
  94449. break;
  94450. }
  94451. }
  94452. }
  94453. if(is_last) {
  94454. /* if this fails, it's OK, it's just a hint for the seek routine */
  94455. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  94456. decoder->private_->first_frame_offset = 0;
  94457. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94458. }
  94459. return true;
  94460. }
  94461. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  94462. {
  94463. FLAC__uint32 x;
  94464. unsigned bits, used_bits = 0;
  94465. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94466. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  94467. decoder->private_->stream_info.is_last = is_last;
  94468. decoder->private_->stream_info.length = length;
  94469. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  94470. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  94471. return false; /* read_callback_ sets the state for us */
  94472. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  94473. used_bits += bits;
  94474. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  94475. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  94476. return false; /* read_callback_ sets the state for us */
  94477. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  94478. used_bits += bits;
  94479. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  94480. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  94481. return false; /* read_callback_ sets the state for us */
  94482. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  94483. used_bits += bits;
  94484. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  94485. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  94486. return false; /* read_callback_ sets the state for us */
  94487. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  94488. used_bits += bits;
  94489. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  94490. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  94491. return false; /* read_callback_ sets the state for us */
  94492. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  94493. used_bits += bits;
  94494. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  94495. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  94496. return false; /* read_callback_ sets the state for us */
  94497. decoder->private_->stream_info.data.stream_info.channels = x+1;
  94498. used_bits += bits;
  94499. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  94500. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  94501. return false; /* read_callback_ sets the state for us */
  94502. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  94503. used_bits += bits;
  94504. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  94505. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &decoder->private_->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  94506. return false; /* read_callback_ sets the state for us */
  94507. used_bits += bits;
  94508. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  94509. return false; /* read_callback_ sets the state for us */
  94510. used_bits += 16*8;
  94511. /* skip the rest of the block */
  94512. FLAC__ASSERT(used_bits % 8 == 0);
  94513. length -= (used_bits / 8);
  94514. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  94515. return false; /* read_callback_ sets the state for us */
  94516. return true;
  94517. }
  94518. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  94519. {
  94520. FLAC__uint32 i, x;
  94521. FLAC__uint64 xx;
  94522. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94523. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  94524. decoder->private_->seek_table.is_last = is_last;
  94525. decoder->private_->seek_table.length = length;
  94526. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  94527. /* use realloc since we may pass through here several times (e.g. after seeking) */
  94528. if(0 == (decoder->private_->seek_table.data.seek_table.points = (FLAC__StreamMetadata_SeekPoint*)safe_realloc_mul_2op_(decoder->private_->seek_table.data.seek_table.points, decoder->private_->seek_table.data.seek_table.num_points, /*times*/sizeof(FLAC__StreamMetadata_SeekPoint)))) {
  94529. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94530. return false;
  94531. }
  94532. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  94533. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  94534. return false; /* read_callback_ sets the state for us */
  94535. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  94536. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  94537. return false; /* read_callback_ sets the state for us */
  94538. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  94539. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  94540. return false; /* read_callback_ sets the state for us */
  94541. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  94542. }
  94543. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  94544. /* if there is a partial point left, skip over it */
  94545. if(length > 0) {
  94546. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  94547. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  94548. return false; /* read_callback_ sets the state for us */
  94549. }
  94550. return true;
  94551. }
  94552. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  94553. {
  94554. FLAC__uint32 i;
  94555. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94556. /* read vendor string */
  94557. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  94558. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  94559. return false; /* read_callback_ sets the state for us */
  94560. if(obj->vendor_string.length > 0) {
  94561. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  94562. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94563. return false;
  94564. }
  94565. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  94566. return false; /* read_callback_ sets the state for us */
  94567. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  94568. }
  94569. else
  94570. obj->vendor_string.entry = 0;
  94571. /* read num comments */
  94572. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  94573. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  94574. return false; /* read_callback_ sets the state for us */
  94575. /* read comments */
  94576. if(obj->num_comments > 0) {
  94577. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  94578. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94579. return false;
  94580. }
  94581. for(i = 0; i < obj->num_comments; i++) {
  94582. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  94583. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  94584. return false; /* read_callback_ sets the state for us */
  94585. if(obj->comments[i].length > 0) {
  94586. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  94587. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94588. return false;
  94589. }
  94590. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  94591. return false; /* read_callback_ sets the state for us */
  94592. obj->comments[i].entry[obj->comments[i].length] = '\0';
  94593. }
  94594. else
  94595. obj->comments[i].entry = 0;
  94596. }
  94597. }
  94598. else {
  94599. obj->comments = 0;
  94600. }
  94601. return true;
  94602. }
  94603. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  94604. {
  94605. FLAC__uint32 i, j, x;
  94606. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94607. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  94608. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  94609. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8))
  94610. return false; /* read_callback_ sets the state for us */
  94611. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  94612. return false; /* read_callback_ sets the state for us */
  94613. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  94614. return false; /* read_callback_ sets the state for us */
  94615. obj->is_cd = x? true : false;
  94616. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  94617. return false; /* read_callback_ sets the state for us */
  94618. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  94619. return false; /* read_callback_ sets the state for us */
  94620. obj->num_tracks = x;
  94621. if(obj->num_tracks > 0) {
  94622. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  94623. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94624. return false;
  94625. }
  94626. for(i = 0; i < obj->num_tracks; i++) {
  94627. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  94628. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  94629. return false; /* read_callback_ sets the state for us */
  94630. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  94631. return false; /* read_callback_ sets the state for us */
  94632. track->number = (FLAC__byte)x;
  94633. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  94634. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  94635. return false; /* read_callback_ sets the state for us */
  94636. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  94637. return false; /* read_callback_ sets the state for us */
  94638. track->type = x;
  94639. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  94640. return false; /* read_callback_ sets the state for us */
  94641. track->pre_emphasis = x;
  94642. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  94643. return false; /* read_callback_ sets the state for us */
  94644. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  94645. return false; /* read_callback_ sets the state for us */
  94646. track->num_indices = (FLAC__byte)x;
  94647. if(track->num_indices > 0) {
  94648. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  94649. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94650. return false;
  94651. }
  94652. for(j = 0; j < track->num_indices; j++) {
  94653. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  94654. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  94655. return false; /* read_callback_ sets the state for us */
  94656. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  94657. return false; /* read_callback_ sets the state for us */
  94658. index->number = (FLAC__byte)x;
  94659. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  94660. return false; /* read_callback_ sets the state for us */
  94661. }
  94662. }
  94663. }
  94664. }
  94665. return true;
  94666. }
  94667. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  94668. {
  94669. FLAC__uint32 x;
  94670. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94671. /* read type */
  94672. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  94673. return false; /* read_callback_ sets the state for us */
  94674. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  94675. /* read MIME type */
  94676. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  94677. return false; /* read_callback_ sets the state for us */
  94678. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  94679. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94680. return false;
  94681. }
  94682. if(x > 0) {
  94683. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  94684. return false; /* read_callback_ sets the state for us */
  94685. }
  94686. obj->mime_type[x] = '\0';
  94687. /* read description */
  94688. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  94689. return false; /* read_callback_ sets the state for us */
  94690. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  94691. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94692. return false;
  94693. }
  94694. if(x > 0) {
  94695. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  94696. return false; /* read_callback_ sets the state for us */
  94697. }
  94698. obj->description[x] = '\0';
  94699. /* read width */
  94700. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  94701. return false; /* read_callback_ sets the state for us */
  94702. /* read height */
  94703. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  94704. return false; /* read_callback_ sets the state for us */
  94705. /* read depth */
  94706. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  94707. return false; /* read_callback_ sets the state for us */
  94708. /* read colors */
  94709. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  94710. return false; /* read_callback_ sets the state for us */
  94711. /* read data */
  94712. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  94713. return false; /* read_callback_ sets the state for us */
  94714. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  94715. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94716. return false;
  94717. }
  94718. if(obj->data_length > 0) {
  94719. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  94720. return false; /* read_callback_ sets the state for us */
  94721. }
  94722. return true;
  94723. }
  94724. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  94725. {
  94726. FLAC__uint32 x;
  94727. unsigned i, skip;
  94728. /* skip the version and flags bytes */
  94729. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  94730. return false; /* read_callback_ sets the state for us */
  94731. /* get the size (in bytes) to skip */
  94732. skip = 0;
  94733. for(i = 0; i < 4; i++) {
  94734. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94735. return false; /* read_callback_ sets the state for us */
  94736. skip <<= 7;
  94737. skip |= (x & 0x7f);
  94738. }
  94739. /* skip the rest of the tag */
  94740. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  94741. return false; /* read_callback_ sets the state for us */
  94742. return true;
  94743. }
  94744. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  94745. {
  94746. FLAC__uint32 x;
  94747. FLAC__bool first = true;
  94748. /* If we know the total number of samples in the stream, stop if we've read that many. */
  94749. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  94750. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  94751. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  94752. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  94753. return true;
  94754. }
  94755. }
  94756. /* make sure we're byte aligned */
  94757. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  94758. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  94759. return false; /* read_callback_ sets the state for us */
  94760. }
  94761. while(1) {
  94762. if(decoder->private_->cached) {
  94763. x = (FLAC__uint32)decoder->private_->lookahead;
  94764. decoder->private_->cached = false;
  94765. }
  94766. else {
  94767. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94768. return false; /* read_callback_ sets the state for us */
  94769. }
  94770. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94771. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  94772. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94773. return false; /* read_callback_ sets the state for us */
  94774. /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */
  94775. /* else we have to check if the second byte is the end of a sync code */
  94776. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94777. decoder->private_->lookahead = (FLAC__byte)x;
  94778. decoder->private_->cached = true;
  94779. }
  94780. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  94781. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  94782. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  94783. return true;
  94784. }
  94785. }
  94786. if(first) {
  94787. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94788. first = false;
  94789. }
  94790. }
  94791. return true;
  94792. }
  94793. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  94794. {
  94795. unsigned channel;
  94796. unsigned i;
  94797. FLAC__int32 mid, side;
  94798. unsigned frame_crc; /* the one we calculate from the input stream */
  94799. FLAC__uint32 x;
  94800. *got_a_frame = false;
  94801. /* init the CRC */
  94802. frame_crc = 0;
  94803. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  94804. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  94805. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  94806. if(!read_frame_header_(decoder))
  94807. return false;
  94808. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  94809. return true;
  94810. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  94811. return false;
  94812. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  94813. /*
  94814. * first figure the correct bits-per-sample of the subframe
  94815. */
  94816. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  94817. switch(decoder->private_->frame.header.channel_assignment) {
  94818. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  94819. /* no adjustment needed */
  94820. break;
  94821. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  94822. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94823. if(channel == 1)
  94824. bps++;
  94825. break;
  94826. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  94827. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94828. if(channel == 0)
  94829. bps++;
  94830. break;
  94831. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  94832. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94833. if(channel == 1)
  94834. bps++;
  94835. break;
  94836. default:
  94837. FLAC__ASSERT(0);
  94838. }
  94839. /*
  94840. * now read it
  94841. */
  94842. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  94843. return false;
  94844. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  94845. return true;
  94846. }
  94847. if(!read_zero_padding_(decoder))
  94848. return false;
  94849. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption (i.e. "zero bits" were not all zeroes) */
  94850. return true;
  94851. /*
  94852. * Read the frame CRC-16 from the footer and check
  94853. */
  94854. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  94855. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  94856. return false; /* read_callback_ sets the state for us */
  94857. if(frame_crc == x) {
  94858. if(do_full_decode) {
  94859. /* Undo any special channel coding */
  94860. switch(decoder->private_->frame.header.channel_assignment) {
  94861. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  94862. /* do nothing */
  94863. break;
  94864. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  94865. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94866. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  94867. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  94868. break;
  94869. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  94870. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94871. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  94872. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  94873. break;
  94874. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  94875. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94876. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  94877. #if 1
  94878. mid = decoder->private_->output[0][i];
  94879. side = decoder->private_->output[1][i];
  94880. mid <<= 1;
  94881. mid |= (side & 1); /* i.e. if 'side' is odd... */
  94882. decoder->private_->output[0][i] = (mid + side) >> 1;
  94883. decoder->private_->output[1][i] = (mid - side) >> 1;
  94884. #else
  94885. /* OPT: without 'side' temp variable */
  94886. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  94887. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  94888. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  94889. #endif
  94890. }
  94891. break;
  94892. default:
  94893. FLAC__ASSERT(0);
  94894. break;
  94895. }
  94896. }
  94897. }
  94898. else {
  94899. /* Bad frame, emit error and zero the output signal */
  94900. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  94901. if(do_full_decode) {
  94902. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  94903. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  94904. }
  94905. }
  94906. }
  94907. *got_a_frame = true;
  94908. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  94909. if(decoder->private_->next_fixed_block_size)
  94910. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  94911. /* put the latest values into the public section of the decoder instance */
  94912. decoder->protected_->channels = decoder->private_->frame.header.channels;
  94913. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  94914. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  94915. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  94916. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  94917. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  94918. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  94919. /* write it */
  94920. if(do_full_decode) {
  94921. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  94922. return false;
  94923. }
  94924. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94925. return true;
  94926. }
  94927. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  94928. {
  94929. FLAC__uint32 x;
  94930. FLAC__uint64 xx;
  94931. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  94932. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  94933. unsigned raw_header_len;
  94934. FLAC__bool is_unparseable = false;
  94935. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94936. /* init the raw header with the saved bits from synchronization */
  94937. raw_header[0] = decoder->private_->header_warmup[0];
  94938. raw_header[1] = decoder->private_->header_warmup[1];
  94939. raw_header_len = 2;
  94940. /* check to make sure that reserved bit is 0 */
  94941. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  94942. is_unparseable = true;
  94943. /*
  94944. * Note that along the way as we read the header, we look for a sync
  94945. * code inside. If we find one it would indicate that our original
  94946. * sync was bad since there cannot be a sync code in a valid header.
  94947. *
  94948. * Three kinds of things can go wrong when reading the frame header:
  94949. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  94950. * If we don't find a sync code, it can end up looking like we read
  94951. * a valid but unparseable header, until getting to the frame header
  94952. * CRC. Even then we could get a false positive on the CRC.
  94953. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  94954. * future encoder).
  94955. * 3) We may be on a damaged frame which appears valid but unparseable.
  94956. *
  94957. * For all these reasons, we try and read a complete frame header as
  94958. * long as it seems valid, even if unparseable, up until the frame
  94959. * header CRC.
  94960. */
  94961. /*
  94962. * read in the raw header as bytes so we can CRC it, and parse it on the way
  94963. */
  94964. for(i = 0; i < 2; i++) {
  94965. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94966. return false; /* read_callback_ sets the state for us */
  94967. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94968. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  94969. decoder->private_->lookahead = (FLAC__byte)x;
  94970. decoder->private_->cached = true;
  94971. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  94972. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94973. return true;
  94974. }
  94975. raw_header[raw_header_len++] = (FLAC__byte)x;
  94976. }
  94977. switch(x = raw_header[2] >> 4) {
  94978. case 0:
  94979. is_unparseable = true;
  94980. break;
  94981. case 1:
  94982. decoder->private_->frame.header.blocksize = 192;
  94983. break;
  94984. case 2:
  94985. case 3:
  94986. case 4:
  94987. case 5:
  94988. decoder->private_->frame.header.blocksize = 576 << (x-2);
  94989. break;
  94990. case 6:
  94991. case 7:
  94992. blocksize_hint = x;
  94993. break;
  94994. case 8:
  94995. case 9:
  94996. case 10:
  94997. case 11:
  94998. case 12:
  94999. case 13:
  95000. case 14:
  95001. case 15:
  95002. decoder->private_->frame.header.blocksize = 256 << (x-8);
  95003. break;
  95004. default:
  95005. FLAC__ASSERT(0);
  95006. break;
  95007. }
  95008. switch(x = raw_header[2] & 0x0f) {
  95009. case 0:
  95010. if(decoder->private_->has_stream_info)
  95011. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  95012. else
  95013. is_unparseable = true;
  95014. break;
  95015. case 1:
  95016. decoder->private_->frame.header.sample_rate = 88200;
  95017. break;
  95018. case 2:
  95019. decoder->private_->frame.header.sample_rate = 176400;
  95020. break;
  95021. case 3:
  95022. decoder->private_->frame.header.sample_rate = 192000;
  95023. break;
  95024. case 4:
  95025. decoder->private_->frame.header.sample_rate = 8000;
  95026. break;
  95027. case 5:
  95028. decoder->private_->frame.header.sample_rate = 16000;
  95029. break;
  95030. case 6:
  95031. decoder->private_->frame.header.sample_rate = 22050;
  95032. break;
  95033. case 7:
  95034. decoder->private_->frame.header.sample_rate = 24000;
  95035. break;
  95036. case 8:
  95037. decoder->private_->frame.header.sample_rate = 32000;
  95038. break;
  95039. case 9:
  95040. decoder->private_->frame.header.sample_rate = 44100;
  95041. break;
  95042. case 10:
  95043. decoder->private_->frame.header.sample_rate = 48000;
  95044. break;
  95045. case 11:
  95046. decoder->private_->frame.header.sample_rate = 96000;
  95047. break;
  95048. case 12:
  95049. case 13:
  95050. case 14:
  95051. sample_rate_hint = x;
  95052. break;
  95053. case 15:
  95054. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  95055. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95056. return true;
  95057. default:
  95058. FLAC__ASSERT(0);
  95059. }
  95060. x = (unsigned)(raw_header[3] >> 4);
  95061. if(x & 8) {
  95062. decoder->private_->frame.header.channels = 2;
  95063. switch(x & 7) {
  95064. case 0:
  95065. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  95066. break;
  95067. case 1:
  95068. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  95069. break;
  95070. case 2:
  95071. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  95072. break;
  95073. default:
  95074. is_unparseable = true;
  95075. break;
  95076. }
  95077. }
  95078. else {
  95079. decoder->private_->frame.header.channels = (unsigned)x + 1;
  95080. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  95081. }
  95082. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  95083. case 0:
  95084. if(decoder->private_->has_stream_info)
  95085. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  95086. else
  95087. is_unparseable = true;
  95088. break;
  95089. case 1:
  95090. decoder->private_->frame.header.bits_per_sample = 8;
  95091. break;
  95092. case 2:
  95093. decoder->private_->frame.header.bits_per_sample = 12;
  95094. break;
  95095. case 4:
  95096. decoder->private_->frame.header.bits_per_sample = 16;
  95097. break;
  95098. case 5:
  95099. decoder->private_->frame.header.bits_per_sample = 20;
  95100. break;
  95101. case 6:
  95102. decoder->private_->frame.header.bits_per_sample = 24;
  95103. break;
  95104. case 3:
  95105. case 7:
  95106. is_unparseable = true;
  95107. break;
  95108. default:
  95109. FLAC__ASSERT(0);
  95110. break;
  95111. }
  95112. /* check to make sure that reserved bit is 0 */
  95113. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  95114. is_unparseable = true;
  95115. /* read the frame's starting sample number (or frame number as the case may be) */
  95116. if(
  95117. raw_header[1] & 0x01 ||
  95118. /*@@@ this clause is a concession to the old way of doing variable blocksize; the only known implementation is flake and can probably be removed without inconveniencing anyone */
  95119. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  95120. ) { /* variable blocksize */
  95121. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  95122. return false; /* read_callback_ sets the state for us */
  95123. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  95124. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  95125. decoder->private_->cached = true;
  95126. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  95127. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95128. return true;
  95129. }
  95130. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  95131. decoder->private_->frame.header.number.sample_number = xx;
  95132. }
  95133. else { /* fixed blocksize */
  95134. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  95135. return false; /* read_callback_ sets the state for us */
  95136. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  95137. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  95138. decoder->private_->cached = true;
  95139. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  95140. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95141. return true;
  95142. }
  95143. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  95144. decoder->private_->frame.header.number.frame_number = x;
  95145. }
  95146. if(blocksize_hint) {
  95147. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95148. return false; /* read_callback_ sets the state for us */
  95149. raw_header[raw_header_len++] = (FLAC__byte)x;
  95150. if(blocksize_hint == 7) {
  95151. FLAC__uint32 _x;
  95152. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  95153. return false; /* read_callback_ sets the state for us */
  95154. raw_header[raw_header_len++] = (FLAC__byte)_x;
  95155. x = (x << 8) | _x;
  95156. }
  95157. decoder->private_->frame.header.blocksize = x+1;
  95158. }
  95159. if(sample_rate_hint) {
  95160. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95161. return false; /* read_callback_ sets the state for us */
  95162. raw_header[raw_header_len++] = (FLAC__byte)x;
  95163. if(sample_rate_hint != 12) {
  95164. FLAC__uint32 _x;
  95165. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  95166. return false; /* read_callback_ sets the state for us */
  95167. raw_header[raw_header_len++] = (FLAC__byte)_x;
  95168. x = (x << 8) | _x;
  95169. }
  95170. if(sample_rate_hint == 12)
  95171. decoder->private_->frame.header.sample_rate = x*1000;
  95172. else if(sample_rate_hint == 13)
  95173. decoder->private_->frame.header.sample_rate = x;
  95174. else
  95175. decoder->private_->frame.header.sample_rate = x*10;
  95176. }
  95177. /* read the CRC-8 byte */
  95178. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95179. return false; /* read_callback_ sets the state for us */
  95180. crc8 = (FLAC__byte)x;
  95181. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  95182. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  95183. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95184. return true;
  95185. }
  95186. /* calculate the sample number from the frame number if needed */
  95187. decoder->private_->next_fixed_block_size = 0;
  95188. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  95189. x = decoder->private_->frame.header.number.frame_number;
  95190. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  95191. if(decoder->private_->fixed_block_size)
  95192. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  95193. else if(decoder->private_->has_stream_info) {
  95194. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  95195. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  95196. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  95197. }
  95198. else
  95199. is_unparseable = true;
  95200. }
  95201. else if(x == 0) {
  95202. decoder->private_->frame.header.number.sample_number = 0;
  95203. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  95204. }
  95205. else {
  95206. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  95207. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  95208. }
  95209. }
  95210. if(is_unparseable) {
  95211. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  95212. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95213. return true;
  95214. }
  95215. return true;
  95216. }
  95217. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  95218. {
  95219. FLAC__uint32 x;
  95220. FLAC__bool wasted_bits;
  95221. unsigned i;
  95222. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  95223. return false; /* read_callback_ sets the state for us */
  95224. wasted_bits = (x & 1);
  95225. x &= 0xfe;
  95226. if(wasted_bits) {
  95227. unsigned u;
  95228. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  95229. return false; /* read_callback_ sets the state for us */
  95230. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  95231. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  95232. }
  95233. else
  95234. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  95235. /*
  95236. * Lots of magic numbers here
  95237. */
  95238. if(x & 0x80) {
  95239. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95240. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95241. return true;
  95242. }
  95243. else if(x == 0) {
  95244. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  95245. return false;
  95246. }
  95247. else if(x == 2) {
  95248. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  95249. return false;
  95250. }
  95251. else if(x < 16) {
  95252. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  95253. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95254. return true;
  95255. }
  95256. else if(x <= 24) {
  95257. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  95258. return false;
  95259. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  95260. return true;
  95261. }
  95262. else if(x < 64) {
  95263. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  95264. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95265. return true;
  95266. }
  95267. else {
  95268. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  95269. return false;
  95270. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  95271. return true;
  95272. }
  95273. if(wasted_bits && do_full_decode) {
  95274. x = decoder->private_->frame.subframes[channel].wasted_bits;
  95275. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  95276. decoder->private_->output[channel][i] <<= x;
  95277. }
  95278. return true;
  95279. }
  95280. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  95281. {
  95282. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  95283. FLAC__int32 x;
  95284. unsigned i;
  95285. FLAC__int32 *output = decoder->private_->output[channel];
  95286. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  95287. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  95288. return false; /* read_callback_ sets the state for us */
  95289. subframe->value = x;
  95290. /* decode the subframe */
  95291. if(do_full_decode) {
  95292. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  95293. output[i] = x;
  95294. }
  95295. return true;
  95296. }
  95297. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  95298. {
  95299. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  95300. FLAC__int32 i32;
  95301. FLAC__uint32 u32;
  95302. unsigned u;
  95303. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  95304. subframe->residual = decoder->private_->residual[channel];
  95305. subframe->order = order;
  95306. /* read warm-up samples */
  95307. for(u = 0; u < order; u++) {
  95308. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  95309. return false; /* read_callback_ sets the state for us */
  95310. subframe->warmup[u] = i32;
  95311. }
  95312. /* read entropy coding method info */
  95313. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  95314. return false; /* read_callback_ sets the state for us */
  95315. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  95316. switch(subframe->entropy_coding_method.type) {
  95317. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  95318. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  95319. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  95320. return false; /* read_callback_ sets the state for us */
  95321. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  95322. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  95323. break;
  95324. default:
  95325. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  95326. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95327. return true;
  95328. }
  95329. /* read residual */
  95330. switch(subframe->entropy_coding_method.type) {
  95331. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  95332. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  95333. if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2))
  95334. return false;
  95335. break;
  95336. default:
  95337. FLAC__ASSERT(0);
  95338. }
  95339. /* decode the subframe */
  95340. if(do_full_decode) {
  95341. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  95342. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  95343. }
  95344. return true;
  95345. }
  95346. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  95347. {
  95348. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  95349. FLAC__int32 i32;
  95350. FLAC__uint32 u32;
  95351. unsigned u;
  95352. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  95353. subframe->residual = decoder->private_->residual[channel];
  95354. subframe->order = order;
  95355. /* read warm-up samples */
  95356. for(u = 0; u < order; u++) {
  95357. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  95358. return false; /* read_callback_ sets the state for us */
  95359. subframe->warmup[u] = i32;
  95360. }
  95361. /* read qlp coeff precision */
  95362. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  95363. return false; /* read_callback_ sets the state for us */
  95364. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  95365. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95366. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95367. return true;
  95368. }
  95369. subframe->qlp_coeff_precision = u32+1;
  95370. /* read qlp shift */
  95371. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  95372. return false; /* read_callback_ sets the state for us */
  95373. subframe->quantization_level = i32;
  95374. /* read quantized lp coefficiencts */
  95375. for(u = 0; u < order; u++) {
  95376. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  95377. return false; /* read_callback_ sets the state for us */
  95378. subframe->qlp_coeff[u] = i32;
  95379. }
  95380. /* read entropy coding method info */
  95381. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  95382. return false; /* read_callback_ sets the state for us */
  95383. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  95384. switch(subframe->entropy_coding_method.type) {
  95385. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  95386. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  95387. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  95388. return false; /* read_callback_ sets the state for us */
  95389. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  95390. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  95391. break;
  95392. default:
  95393. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  95394. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95395. return true;
  95396. }
  95397. /* read residual */
  95398. switch(subframe->entropy_coding_method.type) {
  95399. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  95400. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  95401. if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2))
  95402. return false;
  95403. break;
  95404. default:
  95405. FLAC__ASSERT(0);
  95406. }
  95407. /* decode the subframe */
  95408. if(do_full_decode) {
  95409. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  95410. /*@@@@@@ technically not pessimistic enough, should be more like
  95411. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  95412. */
  95413. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  95414. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  95415. if(order <= 8)
  95416. decoder->private_->local_lpc_restore_signal_16bit_order8(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  95417. else
  95418. decoder->private_->local_lpc_restore_signal_16bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  95419. }
  95420. else
  95421. decoder->private_->local_lpc_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  95422. else
  95423. decoder->private_->local_lpc_restore_signal_64bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  95424. }
  95425. return true;
  95426. }
  95427. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  95428. {
  95429. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  95430. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  95431. unsigned i;
  95432. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  95433. subframe->data = residual;
  95434. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  95435. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  95436. return false; /* read_callback_ sets the state for us */
  95437. residual[i] = x;
  95438. }
  95439. /* decode the subframe */
  95440. if(do_full_decode)
  95441. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  95442. return true;
  95443. }
  95444. FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended)
  95445. {
  95446. FLAC__uint32 rice_parameter;
  95447. int i;
  95448. unsigned partition, sample, u;
  95449. const unsigned partitions = 1u << partition_order;
  95450. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  95451. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  95452. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  95453. /* sanity checks */
  95454. if(partition_order == 0) {
  95455. if(decoder->private_->frame.header.blocksize < predictor_order) {
  95456. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95457. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95458. return true;
  95459. }
  95460. }
  95461. else {
  95462. if(partition_samples < predictor_order) {
  95463. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95464. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95465. return true;
  95466. }
  95467. }
  95468. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  95469. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95470. return false;
  95471. }
  95472. sample = 0;
  95473. for(partition = 0; partition < partitions; partition++) {
  95474. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  95475. return false; /* read_callback_ sets the state for us */
  95476. partitioned_rice_contents->parameters[partition] = rice_parameter;
  95477. if(rice_parameter < pesc) {
  95478. partitioned_rice_contents->raw_bits[partition] = 0;
  95479. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  95480. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  95481. return false; /* read_callback_ sets the state for us */
  95482. sample += u;
  95483. }
  95484. else {
  95485. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  95486. return false; /* read_callback_ sets the state for us */
  95487. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  95488. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  95489. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  95490. return false; /* read_callback_ sets the state for us */
  95491. residual[sample] = i;
  95492. }
  95493. }
  95494. }
  95495. return true;
  95496. }
  95497. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  95498. {
  95499. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  95500. FLAC__uint32 zero = 0;
  95501. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  95502. return false; /* read_callback_ sets the state for us */
  95503. if(zero != 0) {
  95504. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95505. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95506. }
  95507. }
  95508. return true;
  95509. }
  95510. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  95511. {
  95512. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  95513. if(
  95514. #if FLAC__HAS_OGG
  95515. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  95516. !decoder->private_->is_ogg &&
  95517. #endif
  95518. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  95519. ) {
  95520. *bytes = 0;
  95521. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  95522. return false;
  95523. }
  95524. else if(*bytes > 0) {
  95525. /* While seeking, it is possible for our seek to land in the
  95526. * middle of audio data that looks exactly like a frame header
  95527. * from a future version of an encoder. When that happens, our
  95528. * error callback will get an
  95529. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  95530. * unparseable_frame_count. But there is a remote possibility
  95531. * that it is properly synced at such a "future-codec frame",
  95532. * so to make sure, we wait to see many "unparseable" errors in
  95533. * a row before bailing out.
  95534. */
  95535. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  95536. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  95537. return false;
  95538. }
  95539. else {
  95540. const FLAC__StreamDecoderReadStatus status =
  95541. #if FLAC__HAS_OGG
  95542. decoder->private_->is_ogg?
  95543. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  95544. #endif
  95545. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  95546. ;
  95547. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  95548. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  95549. return false;
  95550. }
  95551. else if(*bytes == 0) {
  95552. if(
  95553. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  95554. (
  95555. #if FLAC__HAS_OGG
  95556. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  95557. !decoder->private_->is_ogg &&
  95558. #endif
  95559. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  95560. )
  95561. ) {
  95562. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  95563. return false;
  95564. }
  95565. else
  95566. return true;
  95567. }
  95568. else
  95569. return true;
  95570. }
  95571. }
  95572. else {
  95573. /* abort to avoid a deadlock */
  95574. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  95575. return false;
  95576. }
  95577. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  95578. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  95579. * and at the same time hit the end of the stream (for example, seeking
  95580. * to a point that is after the beginning of the last Ogg page). There
  95581. * is no way to report an Ogg sync loss through the callbacks (see note
  95582. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  95583. * So to keep the decoder from stopping at this point we gate the call
  95584. * to the eof_callback and let the Ogg decoder aspect set the
  95585. * end-of-stream state when it is needed.
  95586. */
  95587. }
  95588. #if FLAC__HAS_OGG
  95589. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  95590. {
  95591. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  95592. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  95593. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  95594. /* we don't really have a way to handle lost sync via read
  95595. * callback so we'll let it pass and let the underlying
  95596. * FLAC decoder catch the error
  95597. */
  95598. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  95599. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  95600. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  95601. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  95602. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  95603. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  95604. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  95605. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  95606. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  95607. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  95608. default:
  95609. FLAC__ASSERT(0);
  95610. /* double protection */
  95611. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  95612. }
  95613. }
  95614. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  95615. {
  95616. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  95617. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  95618. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  95619. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  95620. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  95621. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  95622. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  95623. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  95624. default:
  95625. /* double protection: */
  95626. FLAC__ASSERT(0);
  95627. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  95628. }
  95629. }
  95630. #endif
  95631. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  95632. {
  95633. if(decoder->private_->is_seeking) {
  95634. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  95635. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  95636. FLAC__uint64 target_sample = decoder->private_->target_sample;
  95637. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  95638. #if FLAC__HAS_OGG
  95639. decoder->private_->got_a_frame = true;
  95640. #endif
  95641. decoder->private_->last_frame = *frame; /* save the frame */
  95642. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  95643. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  95644. /* kick out of seek mode */
  95645. decoder->private_->is_seeking = false;
  95646. /* shift out the samples before target_sample */
  95647. if(delta > 0) {
  95648. unsigned channel;
  95649. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  95650. for(channel = 0; channel < frame->header.channels; channel++)
  95651. newbuffer[channel] = buffer[channel] + delta;
  95652. decoder->private_->last_frame.header.blocksize -= delta;
  95653. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  95654. /* write the relevant samples */
  95655. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  95656. }
  95657. else {
  95658. /* write the relevant samples */
  95659. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  95660. }
  95661. }
  95662. else {
  95663. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  95664. }
  95665. }
  95666. else {
  95667. /*
  95668. * If we never got STREAMINFO, turn off MD5 checking to save
  95669. * cycles since we don't have a sum to compare to anyway
  95670. */
  95671. if(!decoder->private_->has_stream_info)
  95672. decoder->private_->do_md5_checking = false;
  95673. if(decoder->private_->do_md5_checking) {
  95674. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  95675. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  95676. }
  95677. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  95678. }
  95679. }
  95680. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  95681. {
  95682. if(!decoder->private_->is_seeking)
  95683. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  95684. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  95685. decoder->private_->unparseable_frame_count++;
  95686. }
  95687. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  95688. {
  95689. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  95690. FLAC__int64 pos = -1;
  95691. int i;
  95692. unsigned approx_bytes_per_frame;
  95693. FLAC__bool first_seek = true;
  95694. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  95695. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  95696. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  95697. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  95698. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  95699. /* take these from the current frame in case they've changed mid-stream */
  95700. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  95701. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  95702. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  95703. /* use values from stream info if we didn't decode a frame */
  95704. if(channels == 0)
  95705. channels = decoder->private_->stream_info.data.stream_info.channels;
  95706. if(bps == 0)
  95707. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  95708. /* we are just guessing here */
  95709. if(max_framesize > 0)
  95710. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  95711. /*
  95712. * Check if it's a known fixed-blocksize stream. Note that though
  95713. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  95714. * never get a STREAMINFO block when decoding so the value of
  95715. * min_blocksize might be zero.
  95716. */
  95717. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  95718. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  95719. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  95720. }
  95721. else
  95722. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  95723. /*
  95724. * First, we set an upper and lower bound on where in the
  95725. * stream we will search. For now we assume the worst case
  95726. * scenario, which is our best guess at the beginning of
  95727. * the first frame and end of the stream.
  95728. */
  95729. lower_bound = first_frame_offset;
  95730. lower_bound_sample = 0;
  95731. upper_bound = stream_length;
  95732. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  95733. /*
  95734. * Now we refine the bounds if we have a seektable with
  95735. * suitable points. Note that according to the spec they
  95736. * must be ordered by ascending sample number.
  95737. *
  95738. * Note: to protect against invalid seek tables we will ignore points
  95739. * that have frame_samples==0 or sample_number>=total_samples
  95740. */
  95741. if(seek_table) {
  95742. FLAC__uint64 new_lower_bound = lower_bound;
  95743. FLAC__uint64 new_upper_bound = upper_bound;
  95744. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  95745. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  95746. /* find the closest seek point <= target_sample, if it exists */
  95747. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  95748. if(
  95749. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  95750. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  95751. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  95752. seek_table->points[i].sample_number <= target_sample
  95753. )
  95754. break;
  95755. }
  95756. if(i >= 0) { /* i.e. we found a suitable seek point... */
  95757. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  95758. new_lower_bound_sample = seek_table->points[i].sample_number;
  95759. }
  95760. /* find the closest seek point > target_sample, if it exists */
  95761. for(i = 0; i < (int)seek_table->num_points; i++) {
  95762. if(
  95763. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  95764. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  95765. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  95766. seek_table->points[i].sample_number > target_sample
  95767. )
  95768. break;
  95769. }
  95770. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  95771. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  95772. new_upper_bound_sample = seek_table->points[i].sample_number;
  95773. }
  95774. /* final protection against unsorted seek tables; keep original values if bogus */
  95775. if(new_upper_bound >= new_lower_bound) {
  95776. lower_bound = new_lower_bound;
  95777. upper_bound = new_upper_bound;
  95778. lower_bound_sample = new_lower_bound_sample;
  95779. upper_bound_sample = new_upper_bound_sample;
  95780. }
  95781. }
  95782. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  95783. /* there are 2 insidious ways that the following equality occurs, which
  95784. * we need to fix:
  95785. * 1) total_samples is 0 (unknown) and target_sample is 0
  95786. * 2) total_samples is 0 (unknown) and target_sample happens to be
  95787. * exactly equal to the last seek point in the seek table; this
  95788. * means there is no seek point above it, and upper_bound_samples
  95789. * remains equal to the estimate (of target_samples) we made above
  95790. * in either case it does not hurt to move upper_bound_sample up by 1
  95791. */
  95792. if(upper_bound_sample == lower_bound_sample)
  95793. upper_bound_sample++;
  95794. decoder->private_->target_sample = target_sample;
  95795. while(1) {
  95796. /* check if the bounds are still ok */
  95797. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  95798. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95799. return false;
  95800. }
  95801. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95802. #if defined _MSC_VER || defined __MINGW32__
  95803. /* with VC++ you have to spoon feed it the casting */
  95804. pos = (FLAC__int64)lower_bound + (FLAC__int64)((FLAC__double)(FLAC__int64)(target_sample - lower_bound_sample) / (FLAC__double)(FLAC__int64)(upper_bound_sample - lower_bound_sample) * (FLAC__double)(FLAC__int64)(upper_bound - lower_bound)) - approx_bytes_per_frame;
  95805. #else
  95806. pos = (FLAC__int64)lower_bound + (FLAC__int64)((FLAC__double)(target_sample - lower_bound_sample) / (FLAC__double)(upper_bound_sample - lower_bound_sample) * (FLAC__double)(upper_bound - lower_bound)) - approx_bytes_per_frame;
  95807. #endif
  95808. #else
  95809. /* a little less accurate: */
  95810. if(upper_bound - lower_bound < 0xffffffff)
  95811. pos = (FLAC__int64)lower_bound + (FLAC__int64)(((target_sample - lower_bound_sample) * (upper_bound - lower_bound)) / (upper_bound_sample - lower_bound_sample)) - approx_bytes_per_frame;
  95812. else /* @@@ WATCHOUT, ~2TB limit */
  95813. pos = (FLAC__int64)lower_bound + (FLAC__int64)((((target_sample - lower_bound_sample)>>8) * ((upper_bound - lower_bound)>>8)) / ((upper_bound_sample - lower_bound_sample)>>16)) - approx_bytes_per_frame;
  95814. #endif
  95815. if(pos >= (FLAC__int64)upper_bound)
  95816. pos = (FLAC__int64)upper_bound - 1;
  95817. if(pos < (FLAC__int64)lower_bound)
  95818. pos = (FLAC__int64)lower_bound;
  95819. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  95820. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95821. return false;
  95822. }
  95823. if(!FLAC__stream_decoder_flush(decoder)) {
  95824. /* above call sets the state for us */
  95825. return false;
  95826. }
  95827. /* Now we need to get a frame. First we need to reset our
  95828. * unparseable_frame_count; if we get too many unparseable
  95829. * frames in a row, the read callback will return
  95830. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  95831. * FLAC__stream_decoder_process_single() to return false.
  95832. */
  95833. decoder->private_->unparseable_frame_count = 0;
  95834. if(!FLAC__stream_decoder_process_single(decoder)) {
  95835. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95836. return false;
  95837. }
  95838. /* our write callback will change the state when it gets to the target frame */
  95839. /* actually, we could have got_a_frame if our decoder is at FLAC__STREAM_DECODER_END_OF_STREAM so we need to check for that also */
  95840. #if 0
  95841. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  95842. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  95843. break;
  95844. #endif
  95845. if(!decoder->private_->is_seeking)
  95846. break;
  95847. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  95848. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  95849. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  95850. if (pos == (FLAC__int64)lower_bound) {
  95851. /* can't move back any more than the first frame, something is fatally wrong */
  95852. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95853. return false;
  95854. }
  95855. /* our last move backwards wasn't big enough, try again */
  95856. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  95857. continue;
  95858. }
  95859. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  95860. first_seek = false;
  95861. /* make sure we are not seeking in corrupted stream */
  95862. if (this_frame_sample < lower_bound_sample) {
  95863. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95864. return false;
  95865. }
  95866. /* we need to narrow the search */
  95867. if(target_sample < this_frame_sample) {
  95868. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  95869. /*@@@@@@ what will decode position be if at end of stream? */
  95870. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  95871. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95872. return false;
  95873. }
  95874. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  95875. }
  95876. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  95877. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  95878. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  95879. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95880. return false;
  95881. }
  95882. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  95883. }
  95884. }
  95885. return true;
  95886. }
  95887. #if FLAC__HAS_OGG
  95888. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  95889. {
  95890. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  95891. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  95892. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  95893. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  95894. FLAC__bool did_a_seek;
  95895. unsigned iteration = 0;
  95896. /* In the first iterations, we will calculate the target byte position
  95897. * by the distance from the target sample to left_sample and
  95898. * right_sample (let's call it "proportional search"). After that, we
  95899. * will switch to binary search.
  95900. */
  95901. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  95902. /* We will switch to a linear search once our current sample is less
  95903. * than this number of samples ahead of the target sample
  95904. */
  95905. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  95906. /* If the total number of samples is unknown, use a large value, and
  95907. * force binary search immediately.
  95908. */
  95909. if(right_sample == 0) {
  95910. right_sample = (FLAC__uint64)(-1);
  95911. BINARY_SEARCH_AFTER_ITERATION = 0;
  95912. }
  95913. decoder->private_->target_sample = target_sample;
  95914. for( ; ; iteration++) {
  95915. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  95916. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  95917. pos = (right_pos + left_pos) / 2;
  95918. }
  95919. else {
  95920. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95921. #if defined _MSC_VER || defined __MINGW32__
  95922. /* with MSVC you have to spoon feed it the casting */
  95923. pos = (FLAC__uint64)((FLAC__double)(FLAC__int64)(target_sample - left_sample) / (FLAC__double)(FLAC__int64)(right_sample - left_sample) * (FLAC__double)(FLAC__int64)(right_pos - left_pos));
  95924. #else
  95925. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  95926. #endif
  95927. #else
  95928. /* a little less accurate: */
  95929. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  95930. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  95931. else /* @@@ WATCHOUT, ~2TB limit */
  95932. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  95933. #endif
  95934. /* @@@ TODO: might want to limit pos to some distance
  95935. * before EOF, to make sure we land before the last frame,
  95936. * thereby getting a this_frame_sample and so having a better
  95937. * estimate.
  95938. */
  95939. }
  95940. /* physical seek */
  95941. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  95942. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95943. return false;
  95944. }
  95945. if(!FLAC__stream_decoder_flush(decoder)) {
  95946. /* above call sets the state for us */
  95947. return false;
  95948. }
  95949. did_a_seek = true;
  95950. }
  95951. else
  95952. did_a_seek = false;
  95953. decoder->private_->got_a_frame = false;
  95954. if(!FLAC__stream_decoder_process_single(decoder)) {
  95955. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95956. return false;
  95957. }
  95958. if(!decoder->private_->got_a_frame) {
  95959. if(did_a_seek) {
  95960. /* this can happen if we seek to a point after the last frame; we drop
  95961. * to binary search right away in this case to avoid any wasted
  95962. * iterations of proportional search.
  95963. */
  95964. right_pos = pos;
  95965. BINARY_SEARCH_AFTER_ITERATION = 0;
  95966. }
  95967. else {
  95968. /* this can probably only happen if total_samples is unknown and the
  95969. * target_sample is past the end of the stream
  95970. */
  95971. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95972. return false;
  95973. }
  95974. }
  95975. /* our write callback will change the state when it gets to the target frame */
  95976. else if(!decoder->private_->is_seeking) {
  95977. break;
  95978. }
  95979. else {
  95980. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  95981. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  95982. if (did_a_seek) {
  95983. if (this_frame_sample <= target_sample) {
  95984. /* The 'equal' case should not happen, since
  95985. * FLAC__stream_decoder_process_single()
  95986. * should recognize that it has hit the
  95987. * target sample and we would exit through
  95988. * the 'break' above.
  95989. */
  95990. FLAC__ASSERT(this_frame_sample != target_sample);
  95991. left_sample = this_frame_sample;
  95992. /* sanity check to avoid infinite loop */
  95993. if (left_pos == pos) {
  95994. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95995. return false;
  95996. }
  95997. left_pos = pos;
  95998. }
  95999. else if(this_frame_sample > target_sample) {
  96000. right_sample = this_frame_sample;
  96001. /* sanity check to avoid infinite loop */
  96002. if (right_pos == pos) {
  96003. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96004. return false;
  96005. }
  96006. right_pos = pos;
  96007. }
  96008. }
  96009. }
  96010. }
  96011. return true;
  96012. }
  96013. #endif
  96014. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  96015. {
  96016. (void)client_data;
  96017. if(*bytes > 0) {
  96018. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  96019. if(ferror(decoder->private_->file))
  96020. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  96021. else if(*bytes == 0)
  96022. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  96023. else
  96024. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  96025. }
  96026. else
  96027. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  96028. }
  96029. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  96030. {
  96031. (void)client_data;
  96032. if(decoder->private_->file == stdin)
  96033. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  96034. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  96035. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  96036. else
  96037. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  96038. }
  96039. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  96040. {
  96041. off_t pos;
  96042. (void)client_data;
  96043. if(decoder->private_->file == stdin)
  96044. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  96045. else if((pos = ftello(decoder->private_->file)) < 0)
  96046. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  96047. else {
  96048. *absolute_byte_offset = (FLAC__uint64)pos;
  96049. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  96050. }
  96051. }
  96052. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  96053. {
  96054. struct stat filestats;
  96055. (void)client_data;
  96056. if(decoder->private_->file == stdin)
  96057. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  96058. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  96059. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  96060. else {
  96061. *stream_length = (FLAC__uint64)filestats.st_size;
  96062. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  96063. }
  96064. }
  96065. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  96066. {
  96067. (void)client_data;
  96068. return feof(decoder->private_->file)? true : false;
  96069. }
  96070. #endif
  96071. /********* End of inlined file: stream_decoder.c *********/
  96072. /********* Start of inlined file: stream_encoder.c *********/
  96073. /********* Start of inlined file: juce_FlacHeader.h *********/
  96074. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96075. // tasks..
  96076. #define VERSION "1.2.1"
  96077. #define FLAC__NO_DLL 1
  96078. #ifdef _MSC_VER
  96079. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96080. #endif
  96081. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  96082. #define FLAC__SYS_DARWIN 1
  96083. #endif
  96084. /********* End of inlined file: juce_FlacHeader.h *********/
  96085. #if JUCE_USE_FLAC
  96086. #if HAVE_CONFIG_H
  96087. # include <config.h>
  96088. #endif
  96089. #if defined _MSC_VER || defined __MINGW32__
  96090. #include <io.h> /* for _setmode() */
  96091. #include <fcntl.h> /* for _O_BINARY */
  96092. #endif
  96093. #if defined __CYGWIN__ || defined __EMX__
  96094. #include <io.h> /* for setmode(), O_BINARY */
  96095. #include <fcntl.h> /* for _O_BINARY */
  96096. #endif
  96097. #include <limits.h>
  96098. #include <stdio.h>
  96099. #include <stdlib.h> /* for malloc() */
  96100. #include <string.h> /* for memcpy() */
  96101. #include <sys/types.h> /* for off_t */
  96102. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  96103. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  96104. #define fseeko fseek
  96105. #define ftello ftell
  96106. #endif
  96107. #endif
  96108. /********* Start of inlined file: stream_encoder.h *********/
  96109. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  96110. #define FLAC__PROTECTED__STREAM_ENCODER_H
  96111. #if FLAC__HAS_OGG
  96112. #include "private/ogg_encoder_aspect.h"
  96113. #endif
  96114. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96115. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  96116. typedef enum {
  96117. FLAC__APODIZATION_BARTLETT,
  96118. FLAC__APODIZATION_BARTLETT_HANN,
  96119. FLAC__APODIZATION_BLACKMAN,
  96120. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  96121. FLAC__APODIZATION_CONNES,
  96122. FLAC__APODIZATION_FLATTOP,
  96123. FLAC__APODIZATION_GAUSS,
  96124. FLAC__APODIZATION_HAMMING,
  96125. FLAC__APODIZATION_HANN,
  96126. FLAC__APODIZATION_KAISER_BESSEL,
  96127. FLAC__APODIZATION_NUTTALL,
  96128. FLAC__APODIZATION_RECTANGLE,
  96129. FLAC__APODIZATION_TRIANGLE,
  96130. FLAC__APODIZATION_TUKEY,
  96131. FLAC__APODIZATION_WELCH
  96132. } FLAC__ApodizationFunction;
  96133. typedef struct {
  96134. FLAC__ApodizationFunction type;
  96135. union {
  96136. struct {
  96137. FLAC__real stddev;
  96138. } gauss;
  96139. struct {
  96140. FLAC__real p;
  96141. } tukey;
  96142. } parameters;
  96143. } FLAC__ApodizationSpecification;
  96144. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96145. typedef struct FLAC__StreamEncoderProtected {
  96146. FLAC__StreamEncoderState state;
  96147. FLAC__bool verify;
  96148. FLAC__bool streamable_subset;
  96149. FLAC__bool do_md5;
  96150. FLAC__bool do_mid_side_stereo;
  96151. FLAC__bool loose_mid_side_stereo;
  96152. unsigned channels;
  96153. unsigned bits_per_sample;
  96154. unsigned sample_rate;
  96155. unsigned blocksize;
  96156. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96157. unsigned num_apodizations;
  96158. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  96159. #endif
  96160. unsigned max_lpc_order;
  96161. unsigned qlp_coeff_precision;
  96162. FLAC__bool do_qlp_coeff_prec_search;
  96163. FLAC__bool do_exhaustive_model_search;
  96164. FLAC__bool do_escape_coding;
  96165. unsigned min_residual_partition_order;
  96166. unsigned max_residual_partition_order;
  96167. unsigned rice_parameter_search_dist;
  96168. FLAC__uint64 total_samples_estimate;
  96169. FLAC__StreamMetadata **metadata;
  96170. unsigned num_metadata_blocks;
  96171. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  96172. #if FLAC__HAS_OGG
  96173. FLAC__OggEncoderAspect ogg_encoder_aspect;
  96174. #endif
  96175. } FLAC__StreamEncoderProtected;
  96176. #endif
  96177. /********* End of inlined file: stream_encoder.h *********/
  96178. #if FLAC__HAS_OGG
  96179. #include "include/private/ogg_helper.h"
  96180. #include "include/private/ogg_mapping.h"
  96181. #endif
  96182. /********* Start of inlined file: stream_encoder_framing.h *********/
  96183. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  96184. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  96185. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  96186. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  96187. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  96188. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  96189. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  96190. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  96191. #endif
  96192. /********* End of inlined file: stream_encoder_framing.h *********/
  96193. /********* Start of inlined file: window.h *********/
  96194. #ifndef FLAC__PRIVATE__WINDOW_H
  96195. #define FLAC__PRIVATE__WINDOW_H
  96196. #ifdef HAVE_CONFIG_H
  96197. #include <config.h>
  96198. #endif
  96199. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96200. /*
  96201. * FLAC__window_*()
  96202. * --------------------------------------------------------------------
  96203. * Calculates window coefficients according to different apodization
  96204. * functions.
  96205. *
  96206. * OUT window[0,L-1]
  96207. * IN L (number of points in window)
  96208. */
  96209. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  96210. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  96211. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  96212. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  96213. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  96214. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  96215. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  96216. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  96217. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  96218. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  96219. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  96220. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  96221. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  96222. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  96223. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  96224. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96225. #endif
  96226. /********* End of inlined file: window.h *********/
  96227. #ifndef FLaC__INLINE
  96228. #define FLaC__INLINE
  96229. #endif
  96230. #ifdef min
  96231. #undef min
  96232. #endif
  96233. #define min(x,y) ((x)<(y)?(x):(y))
  96234. #ifdef max
  96235. #undef max
  96236. #endif
  96237. #define max(x,y) ((x)>(y)?(x):(y))
  96238. /* Exact Rice codeword length calculation is off by default. The simple
  96239. * (and fast) estimation (of how many bits a residual value will be
  96240. * encoded with) in this encoder is very good, almost always yielding
  96241. * compression within 0.1% of exact calculation.
  96242. */
  96243. #undef EXACT_RICE_BITS_CALCULATION
  96244. /* Rice parameter searching is off by default. The simple (and fast)
  96245. * parameter estimation in this encoder is very good, almost always
  96246. * yielding compression within 0.1% of the optimal parameters.
  96247. */
  96248. #undef ENABLE_RICE_PARAMETER_SEARCH
  96249. typedef struct {
  96250. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  96251. unsigned size; /* of each data[] in samples */
  96252. unsigned tail;
  96253. } verify_input_fifo;
  96254. typedef struct {
  96255. const FLAC__byte *data;
  96256. unsigned capacity;
  96257. unsigned bytes;
  96258. } verify_output;
  96259. typedef enum {
  96260. ENCODER_IN_MAGIC = 0,
  96261. ENCODER_IN_METADATA = 1,
  96262. ENCODER_IN_AUDIO = 2
  96263. } EncoderStateHint;
  96264. static struct CompressionLevels {
  96265. FLAC__bool do_mid_side_stereo;
  96266. FLAC__bool loose_mid_side_stereo;
  96267. unsigned max_lpc_order;
  96268. unsigned qlp_coeff_precision;
  96269. FLAC__bool do_qlp_coeff_prec_search;
  96270. FLAC__bool do_escape_coding;
  96271. FLAC__bool do_exhaustive_model_search;
  96272. unsigned min_residual_partition_order;
  96273. unsigned max_residual_partition_order;
  96274. unsigned rice_parameter_search_dist;
  96275. } compression_levels_[] = {
  96276. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  96277. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  96278. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  96279. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  96280. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  96281. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  96282. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  96283. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  96284. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  96285. };
  96286. /***********************************************************************
  96287. *
  96288. * Private class method prototypes
  96289. *
  96290. ***********************************************************************/
  96291. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  96292. static void free_(FLAC__StreamEncoder *encoder);
  96293. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  96294. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  96295. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  96296. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  96297. #if FLAC__HAS_OGG
  96298. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  96299. #endif
  96300. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  96301. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  96302. static FLAC__bool process_subframe_(
  96303. FLAC__StreamEncoder *encoder,
  96304. unsigned min_partition_order,
  96305. unsigned max_partition_order,
  96306. const FLAC__FrameHeader *frame_header,
  96307. unsigned subframe_bps,
  96308. const FLAC__int32 integer_signal[],
  96309. FLAC__Subframe *subframe[2],
  96310. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  96311. FLAC__int32 *residual[2],
  96312. unsigned *best_subframe,
  96313. unsigned *best_bits
  96314. );
  96315. static FLAC__bool add_subframe_(
  96316. FLAC__StreamEncoder *encoder,
  96317. unsigned blocksize,
  96318. unsigned subframe_bps,
  96319. const FLAC__Subframe *subframe,
  96320. FLAC__BitWriter *frame
  96321. );
  96322. static unsigned evaluate_constant_subframe_(
  96323. FLAC__StreamEncoder *encoder,
  96324. const FLAC__int32 signal,
  96325. unsigned blocksize,
  96326. unsigned subframe_bps,
  96327. FLAC__Subframe *subframe
  96328. );
  96329. static unsigned evaluate_fixed_subframe_(
  96330. FLAC__StreamEncoder *encoder,
  96331. const FLAC__int32 signal[],
  96332. FLAC__int32 residual[],
  96333. FLAC__uint64 abs_residual_partition_sums[],
  96334. unsigned raw_bits_per_partition[],
  96335. unsigned blocksize,
  96336. unsigned subframe_bps,
  96337. unsigned order,
  96338. unsigned rice_parameter,
  96339. unsigned rice_parameter_limit,
  96340. unsigned min_partition_order,
  96341. unsigned max_partition_order,
  96342. FLAC__bool do_escape_coding,
  96343. unsigned rice_parameter_search_dist,
  96344. FLAC__Subframe *subframe,
  96345. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  96346. );
  96347. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96348. static unsigned evaluate_lpc_subframe_(
  96349. FLAC__StreamEncoder *encoder,
  96350. const FLAC__int32 signal[],
  96351. FLAC__int32 residual[],
  96352. FLAC__uint64 abs_residual_partition_sums[],
  96353. unsigned raw_bits_per_partition[],
  96354. const FLAC__real lp_coeff[],
  96355. unsigned blocksize,
  96356. unsigned subframe_bps,
  96357. unsigned order,
  96358. unsigned qlp_coeff_precision,
  96359. unsigned rice_parameter,
  96360. unsigned rice_parameter_limit,
  96361. unsigned min_partition_order,
  96362. unsigned max_partition_order,
  96363. FLAC__bool do_escape_coding,
  96364. unsigned rice_parameter_search_dist,
  96365. FLAC__Subframe *subframe,
  96366. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  96367. );
  96368. #endif
  96369. static unsigned evaluate_verbatim_subframe_(
  96370. FLAC__StreamEncoder *encoder,
  96371. const FLAC__int32 signal[],
  96372. unsigned blocksize,
  96373. unsigned subframe_bps,
  96374. FLAC__Subframe *subframe
  96375. );
  96376. static unsigned find_best_partition_order_(
  96377. struct FLAC__StreamEncoderPrivate *private_,
  96378. const FLAC__int32 residual[],
  96379. FLAC__uint64 abs_residual_partition_sums[],
  96380. unsigned raw_bits_per_partition[],
  96381. unsigned residual_samples,
  96382. unsigned predictor_order,
  96383. unsigned rice_parameter,
  96384. unsigned rice_parameter_limit,
  96385. unsigned min_partition_order,
  96386. unsigned max_partition_order,
  96387. unsigned bps,
  96388. FLAC__bool do_escape_coding,
  96389. unsigned rice_parameter_search_dist,
  96390. FLAC__EntropyCodingMethod *best_ecm
  96391. );
  96392. static void precompute_partition_info_sums_(
  96393. const FLAC__int32 residual[],
  96394. FLAC__uint64 abs_residual_partition_sums[],
  96395. unsigned residual_samples,
  96396. unsigned predictor_order,
  96397. unsigned min_partition_order,
  96398. unsigned max_partition_order,
  96399. unsigned bps
  96400. );
  96401. static void precompute_partition_info_escapes_(
  96402. const FLAC__int32 residual[],
  96403. unsigned raw_bits_per_partition[],
  96404. unsigned residual_samples,
  96405. unsigned predictor_order,
  96406. unsigned min_partition_order,
  96407. unsigned max_partition_order
  96408. );
  96409. static FLAC__bool set_partitioned_rice_(
  96410. #ifdef EXACT_RICE_BITS_CALCULATION
  96411. const FLAC__int32 residual[],
  96412. #endif
  96413. const FLAC__uint64 abs_residual_partition_sums[],
  96414. const unsigned raw_bits_per_partition[],
  96415. const unsigned residual_samples,
  96416. const unsigned predictor_order,
  96417. const unsigned suggested_rice_parameter,
  96418. const unsigned rice_parameter_limit,
  96419. const unsigned rice_parameter_search_dist,
  96420. const unsigned partition_order,
  96421. const FLAC__bool search_for_escapes,
  96422. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  96423. unsigned *bits
  96424. );
  96425. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  96426. /* verify-related routines: */
  96427. static void append_to_verify_fifo_(
  96428. verify_input_fifo *fifo,
  96429. const FLAC__int32 * const input[],
  96430. unsigned input_offset,
  96431. unsigned channels,
  96432. unsigned wide_samples
  96433. );
  96434. static void append_to_verify_fifo_interleaved_(
  96435. verify_input_fifo *fifo,
  96436. const FLAC__int32 input[],
  96437. unsigned input_offset,
  96438. unsigned channels,
  96439. unsigned wide_samples
  96440. );
  96441. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  96442. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  96443. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  96444. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  96445. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  96446. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  96447. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  96448. static FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  96449. static FILE *get_binary_stdout_(void);
  96450. /***********************************************************************
  96451. *
  96452. * Private class data
  96453. *
  96454. ***********************************************************************/
  96455. typedef struct FLAC__StreamEncoderPrivate {
  96456. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  96457. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  96458. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  96459. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96460. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  96461. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  96462. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  96463. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  96464. #endif
  96465. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  96466. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  96467. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  96468. FLAC__int32 *residual_workspace_mid_side[2][2];
  96469. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  96470. FLAC__Subframe subframe_workspace_mid_side[2][2];
  96471. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  96472. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  96473. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  96474. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  96475. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  96476. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  96477. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  96478. unsigned best_subframe_mid_side[2];
  96479. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  96480. unsigned best_subframe_bits_mid_side[2];
  96481. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  96482. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  96483. FLAC__BitWriter *frame; /* the current frame being worked on */
  96484. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  96485. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  96486. FLAC__ChannelAssignment last_channel_assignment;
  96487. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  96488. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  96489. unsigned current_sample_number;
  96490. unsigned current_frame_number;
  96491. FLAC__MD5Context md5context;
  96492. FLAC__CPUInfo cpuinfo;
  96493. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96494. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  96495. #else
  96496. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  96497. #endif
  96498. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96499. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96500. void (*local_lpc_compute_residual_from_qlp_coefficients)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  96501. void (*local_lpc_compute_residual_from_qlp_coefficients_64bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  96502. void (*local_lpc_compute_residual_from_qlp_coefficients_16bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  96503. #endif
  96504. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  96505. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  96506. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  96507. FLAC__bool disable_constant_subframes;
  96508. FLAC__bool disable_fixed_subframes;
  96509. FLAC__bool disable_verbatim_subframes;
  96510. #if FLAC__HAS_OGG
  96511. FLAC__bool is_ogg;
  96512. #endif
  96513. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  96514. FLAC__StreamEncoderSeekCallback seek_callback;
  96515. FLAC__StreamEncoderTellCallback tell_callback;
  96516. FLAC__StreamEncoderWriteCallback write_callback;
  96517. FLAC__StreamEncoderMetadataCallback metadata_callback;
  96518. FLAC__StreamEncoderProgressCallback progress_callback;
  96519. void *client_data;
  96520. unsigned first_seekpoint_to_check;
  96521. FILE *file; /* only used when encoding to a file */
  96522. FLAC__uint64 bytes_written;
  96523. FLAC__uint64 samples_written;
  96524. unsigned frames_written;
  96525. unsigned total_frames_estimate;
  96526. /* unaligned (original) pointers to allocated data */
  96527. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  96528. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  96529. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96530. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  96531. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  96532. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  96533. FLAC__real *windowed_signal_unaligned;
  96534. #endif
  96535. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  96536. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  96537. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  96538. unsigned *raw_bits_per_partition_unaligned;
  96539. /*
  96540. * These fields have been moved here from private function local
  96541. * declarations merely to save stack space during encoding.
  96542. */
  96543. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96544. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  96545. #endif
  96546. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  96547. /*
  96548. * The data for the verify section
  96549. */
  96550. struct {
  96551. FLAC__StreamDecoder *decoder;
  96552. EncoderStateHint state_hint;
  96553. FLAC__bool needs_magic_hack;
  96554. verify_input_fifo input_fifo;
  96555. verify_output output;
  96556. struct {
  96557. FLAC__uint64 absolute_sample;
  96558. unsigned frame_number;
  96559. unsigned channel;
  96560. unsigned sample;
  96561. FLAC__int32 expected;
  96562. FLAC__int32 got;
  96563. } error_stats;
  96564. } verify;
  96565. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  96566. } FLAC__StreamEncoderPrivate;
  96567. /***********************************************************************
  96568. *
  96569. * Public static class data
  96570. *
  96571. ***********************************************************************/
  96572. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  96573. "FLAC__STREAM_ENCODER_OK",
  96574. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  96575. "FLAC__STREAM_ENCODER_OGG_ERROR",
  96576. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  96577. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  96578. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  96579. "FLAC__STREAM_ENCODER_IO_ERROR",
  96580. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  96581. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  96582. };
  96583. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  96584. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  96585. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  96586. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  96587. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  96588. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  96589. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  96590. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  96591. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  96592. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  96593. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  96594. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  96595. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  96596. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  96597. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  96598. };
  96599. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  96600. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  96601. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  96602. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  96603. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  96604. };
  96605. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  96606. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  96607. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  96608. };
  96609. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  96610. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  96611. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  96612. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  96613. };
  96614. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  96615. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  96616. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  96617. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  96618. };
  96619. /* Number of samples that will be overread to watch for end of stream. By
  96620. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  96621. * always try to read blocksize+1 samples before encoding a block, so that
  96622. * even if the stream has a total sample count that is an integral multiple
  96623. * of the blocksize, we will still notice when we are encoding the last
  96624. * block. This is needed, for example, to correctly set the end-of-stream
  96625. * marker in Ogg FLAC.
  96626. *
  96627. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  96628. * not really any reason to change it.
  96629. */
  96630. static const unsigned OVERREAD_ = 1;
  96631. /***********************************************************************
  96632. *
  96633. * Class constructor/destructor
  96634. *
  96635. */
  96636. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  96637. {
  96638. FLAC__StreamEncoder *encoder;
  96639. unsigned i;
  96640. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  96641. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  96642. if(encoder == 0) {
  96643. return 0;
  96644. }
  96645. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  96646. if(encoder->protected_ == 0) {
  96647. free(encoder);
  96648. return 0;
  96649. }
  96650. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  96651. if(encoder->private_ == 0) {
  96652. free(encoder->protected_);
  96653. free(encoder);
  96654. return 0;
  96655. }
  96656. encoder->private_->frame = FLAC__bitwriter_new();
  96657. if(encoder->private_->frame == 0) {
  96658. free(encoder->private_);
  96659. free(encoder->protected_);
  96660. free(encoder);
  96661. return 0;
  96662. }
  96663. encoder->private_->file = 0;
  96664. set_defaults_enc(encoder);
  96665. encoder->private_->is_being_deleted = false;
  96666. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96667. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  96668. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  96669. }
  96670. for(i = 0; i < 2; i++) {
  96671. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  96672. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  96673. }
  96674. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96675. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  96676. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  96677. }
  96678. for(i = 0; i < 2; i++) {
  96679. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  96680. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  96681. }
  96682. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96683. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  96684. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  96685. }
  96686. for(i = 0; i < 2; i++) {
  96687. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  96688. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  96689. }
  96690. for(i = 0; i < 2; i++)
  96691. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  96692. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  96693. return encoder;
  96694. }
  96695. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  96696. {
  96697. unsigned i;
  96698. FLAC__ASSERT(0 != encoder);
  96699. FLAC__ASSERT(0 != encoder->protected_);
  96700. FLAC__ASSERT(0 != encoder->private_);
  96701. FLAC__ASSERT(0 != encoder->private_->frame);
  96702. encoder->private_->is_being_deleted = true;
  96703. (void)FLAC__stream_encoder_finish(encoder);
  96704. if(0 != encoder->private_->verify.decoder)
  96705. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  96706. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96707. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  96708. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  96709. }
  96710. for(i = 0; i < 2; i++) {
  96711. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  96712. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  96713. }
  96714. for(i = 0; i < 2; i++)
  96715. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  96716. FLAC__bitwriter_delete(encoder->private_->frame);
  96717. free(encoder->private_);
  96718. free(encoder->protected_);
  96719. free(encoder);
  96720. }
  96721. /***********************************************************************
  96722. *
  96723. * Public class methods
  96724. *
  96725. ***********************************************************************/
  96726. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  96727. FLAC__StreamEncoder *encoder,
  96728. FLAC__StreamEncoderReadCallback read_callback,
  96729. FLAC__StreamEncoderWriteCallback write_callback,
  96730. FLAC__StreamEncoderSeekCallback seek_callback,
  96731. FLAC__StreamEncoderTellCallback tell_callback,
  96732. FLAC__StreamEncoderMetadataCallback metadata_callback,
  96733. void *client_data,
  96734. FLAC__bool is_ogg
  96735. )
  96736. {
  96737. unsigned i;
  96738. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  96739. FLAC__ASSERT(0 != encoder);
  96740. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96741. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  96742. #if !FLAC__HAS_OGG
  96743. if(is_ogg)
  96744. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  96745. #endif
  96746. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  96747. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  96748. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  96749. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  96750. if(encoder->protected_->channels != 2) {
  96751. encoder->protected_->do_mid_side_stereo = false;
  96752. encoder->protected_->loose_mid_side_stereo = false;
  96753. }
  96754. else if(!encoder->protected_->do_mid_side_stereo)
  96755. encoder->protected_->loose_mid_side_stereo = false;
  96756. if(encoder->protected_->bits_per_sample >= 32)
  96757. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  96758. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  96759. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  96760. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  96761. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  96762. if(encoder->protected_->blocksize == 0) {
  96763. if(encoder->protected_->max_lpc_order == 0)
  96764. encoder->protected_->blocksize = 1152;
  96765. else
  96766. encoder->protected_->blocksize = 4096;
  96767. }
  96768. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  96769. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  96770. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  96771. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  96772. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  96773. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  96774. if(encoder->protected_->qlp_coeff_precision == 0) {
  96775. if(encoder->protected_->bits_per_sample < 16) {
  96776. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  96777. /* @@@ until then we'll make a guess */
  96778. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  96779. }
  96780. else if(encoder->protected_->bits_per_sample == 16) {
  96781. if(encoder->protected_->blocksize <= 192)
  96782. encoder->protected_->qlp_coeff_precision = 7;
  96783. else if(encoder->protected_->blocksize <= 384)
  96784. encoder->protected_->qlp_coeff_precision = 8;
  96785. else if(encoder->protected_->blocksize <= 576)
  96786. encoder->protected_->qlp_coeff_precision = 9;
  96787. else if(encoder->protected_->blocksize <= 1152)
  96788. encoder->protected_->qlp_coeff_precision = 10;
  96789. else if(encoder->protected_->blocksize <= 2304)
  96790. encoder->protected_->qlp_coeff_precision = 11;
  96791. else if(encoder->protected_->blocksize <= 4608)
  96792. encoder->protected_->qlp_coeff_precision = 12;
  96793. else
  96794. encoder->protected_->qlp_coeff_precision = 13;
  96795. }
  96796. else {
  96797. if(encoder->protected_->blocksize <= 384)
  96798. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  96799. else if(encoder->protected_->blocksize <= 1152)
  96800. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  96801. else
  96802. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  96803. }
  96804. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  96805. }
  96806. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  96807. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  96808. if(encoder->protected_->streamable_subset) {
  96809. if(
  96810. encoder->protected_->blocksize != 192 &&
  96811. encoder->protected_->blocksize != 576 &&
  96812. encoder->protected_->blocksize != 1152 &&
  96813. encoder->protected_->blocksize != 2304 &&
  96814. encoder->protected_->blocksize != 4608 &&
  96815. encoder->protected_->blocksize != 256 &&
  96816. encoder->protected_->blocksize != 512 &&
  96817. encoder->protected_->blocksize != 1024 &&
  96818. encoder->protected_->blocksize != 2048 &&
  96819. encoder->protected_->blocksize != 4096 &&
  96820. encoder->protected_->blocksize != 8192 &&
  96821. encoder->protected_->blocksize != 16384
  96822. )
  96823. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96824. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  96825. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96826. if(
  96827. encoder->protected_->bits_per_sample != 8 &&
  96828. encoder->protected_->bits_per_sample != 12 &&
  96829. encoder->protected_->bits_per_sample != 16 &&
  96830. encoder->protected_->bits_per_sample != 20 &&
  96831. encoder->protected_->bits_per_sample != 24
  96832. )
  96833. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96834. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  96835. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96836. if(
  96837. encoder->protected_->sample_rate <= 48000 &&
  96838. (
  96839. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  96840. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  96841. )
  96842. ) {
  96843. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96844. }
  96845. }
  96846. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  96847. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  96848. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  96849. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  96850. #if FLAC__HAS_OGG
  96851. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  96852. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  96853. unsigned i;
  96854. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  96855. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  96856. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  96857. for( ; i > 0; i--)
  96858. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  96859. encoder->protected_->metadata[0] = vc;
  96860. break;
  96861. }
  96862. }
  96863. }
  96864. #endif
  96865. /* keep track of any SEEKTABLE block */
  96866. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  96867. unsigned i;
  96868. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  96869. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  96870. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  96871. break; /* take only the first one */
  96872. }
  96873. }
  96874. }
  96875. /* validate metadata */
  96876. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  96877. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96878. metadata_has_seektable = false;
  96879. metadata_has_vorbis_comment = false;
  96880. metadata_picture_has_type1 = false;
  96881. metadata_picture_has_type2 = false;
  96882. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  96883. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  96884. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  96885. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96886. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  96887. if(metadata_has_seektable) /* only one is allowed */
  96888. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96889. metadata_has_seektable = true;
  96890. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  96891. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96892. }
  96893. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  96894. if(metadata_has_vorbis_comment) /* only one is allowed */
  96895. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96896. metadata_has_vorbis_comment = true;
  96897. }
  96898. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  96899. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  96900. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96901. }
  96902. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  96903. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  96904. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96905. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  96906. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  96907. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96908. metadata_picture_has_type1 = true;
  96909. /* standard icon must be 32x32 pixel PNG */
  96910. if(
  96911. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  96912. (
  96913. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  96914. m->data.picture.width != 32 ||
  96915. m->data.picture.height != 32
  96916. )
  96917. )
  96918. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96919. }
  96920. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  96921. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  96922. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96923. metadata_picture_has_type2 = true;
  96924. }
  96925. }
  96926. }
  96927. encoder->private_->input_capacity = 0;
  96928. for(i = 0; i < encoder->protected_->channels; i++) {
  96929. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  96930. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96931. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  96932. #endif
  96933. }
  96934. for(i = 0; i < 2; i++) {
  96935. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  96936. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96937. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  96938. #endif
  96939. }
  96940. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96941. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  96942. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  96943. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  96944. #endif
  96945. for(i = 0; i < encoder->protected_->channels; i++) {
  96946. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  96947. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  96948. encoder->private_->best_subframe[i] = 0;
  96949. }
  96950. for(i = 0; i < 2; i++) {
  96951. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  96952. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  96953. encoder->private_->best_subframe_mid_side[i] = 0;
  96954. }
  96955. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  96956. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  96957. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96958. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  96959. #else
  96960. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  96961. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  96962. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  96963. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  96964. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  96965. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  96966. encoder->private_->loose_mid_side_stereo_frames = (unsigned)FLAC__fixedpoint_trunc((((FLAC__uint64)(encoder->protected_->sample_rate) * (FLAC__uint64)(26214)) << 16) / (encoder->protected_->blocksize<<16) + FLAC__FP_ONE_HALF);
  96967. #endif
  96968. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  96969. encoder->private_->loose_mid_side_stereo_frames = 1;
  96970. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  96971. encoder->private_->current_sample_number = 0;
  96972. encoder->private_->current_frame_number = 0;
  96973. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  96974. encoder->private_->use_wide_by_order = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(max(encoder->protected_->max_lpc_order, FLAC__MAX_FIXED_ORDER))+1 > 30); /*@@@ need to use this? */
  96975. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  96976. /*
  96977. * get the CPU info and set the function pointers
  96978. */
  96979. FLAC__cpu_info(&encoder->private_->cpuinfo);
  96980. /* first default to the non-asm routines */
  96981. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96982. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  96983. #endif
  96984. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  96985. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96986. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  96987. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  96988. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  96989. #endif
  96990. /* now override with asm where appropriate */
  96991. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96992. # ifndef FLAC__NO_ASM
  96993. if(encoder->private_->cpuinfo.use_asm) {
  96994. # ifdef FLAC__CPU_IA32
  96995. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  96996. # ifdef FLAC__HAS_NASM
  96997. if(encoder->private_->cpuinfo.data.ia32.sse) {
  96998. if(encoder->protected_->max_lpc_order < 4)
  96999. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  97000. else if(encoder->protected_->max_lpc_order < 8)
  97001. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  97002. else if(encoder->protected_->max_lpc_order < 12)
  97003. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  97004. else
  97005. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  97006. }
  97007. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  97008. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  97009. else
  97010. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  97011. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  97012. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  97013. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  97014. }
  97015. else {
  97016. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  97017. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  97018. }
  97019. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  97020. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  97021. # endif /* FLAC__HAS_NASM */
  97022. # endif /* FLAC__CPU_IA32 */
  97023. }
  97024. # endif /* !FLAC__NO_ASM */
  97025. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  97026. /* finally override based on wide-ness if necessary */
  97027. if(encoder->private_->use_wide_by_block) {
  97028. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  97029. }
  97030. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  97031. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  97032. #if FLAC__HAS_OGG
  97033. encoder->private_->is_ogg = is_ogg;
  97034. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  97035. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  97036. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97037. }
  97038. #endif
  97039. encoder->private_->read_callback = read_callback;
  97040. encoder->private_->write_callback = write_callback;
  97041. encoder->private_->seek_callback = seek_callback;
  97042. encoder->private_->tell_callback = tell_callback;
  97043. encoder->private_->metadata_callback = metadata_callback;
  97044. encoder->private_->client_data = client_data;
  97045. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  97046. /* the above function sets the state for us in case of an error */
  97047. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97048. }
  97049. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  97050. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  97051. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97052. }
  97053. /*
  97054. * Set up the verify stuff if necessary
  97055. */
  97056. if(encoder->protected_->verify) {
  97057. /*
  97058. * First, set up the fifo which will hold the
  97059. * original signal to compare against
  97060. */
  97061. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  97062. for(i = 0; i < encoder->protected_->channels; i++) {
  97063. if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)safe_malloc_mul_2op_(sizeof(FLAC__int32), /*times*/encoder->private_->verify.input_fifo.size))) {
  97064. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  97065. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97066. }
  97067. }
  97068. encoder->private_->verify.input_fifo.tail = 0;
  97069. /*
  97070. * Now set up a stream decoder for verification
  97071. */
  97072. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  97073. if(0 == encoder->private_->verify.decoder) {
  97074. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  97075. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97076. }
  97077. if(FLAC__stream_decoder_init_stream(encoder->private_->verify.decoder, verify_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, verify_write_callback_, verify_metadata_callback_, verify_error_callback_, /*client_data=*/encoder) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
  97078. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  97079. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97080. }
  97081. }
  97082. encoder->private_->verify.error_stats.absolute_sample = 0;
  97083. encoder->private_->verify.error_stats.frame_number = 0;
  97084. encoder->private_->verify.error_stats.channel = 0;
  97085. encoder->private_->verify.error_stats.sample = 0;
  97086. encoder->private_->verify.error_stats.expected = 0;
  97087. encoder->private_->verify.error_stats.got = 0;
  97088. /*
  97089. * These must be done before we write any metadata, because that
  97090. * calls the write_callback, which uses these values.
  97091. */
  97092. encoder->private_->first_seekpoint_to_check = 0;
  97093. encoder->private_->samples_written = 0;
  97094. encoder->protected_->streaminfo_offset = 0;
  97095. encoder->protected_->seektable_offset = 0;
  97096. encoder->protected_->audio_offset = 0;
  97097. /*
  97098. * write the stream header
  97099. */
  97100. if(encoder->protected_->verify)
  97101. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  97102. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  97103. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  97104. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97105. }
  97106. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  97107. /* the above function sets the state for us in case of an error */
  97108. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97109. }
  97110. /*
  97111. * write the STREAMINFO metadata block
  97112. */
  97113. if(encoder->protected_->verify)
  97114. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  97115. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  97116. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  97117. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  97118. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  97119. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  97120. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  97121. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  97122. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  97123. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  97124. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  97125. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  97126. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  97127. if(encoder->protected_->do_md5)
  97128. FLAC__MD5Init(&encoder->private_->md5context);
  97129. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  97130. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  97131. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97132. }
  97133. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  97134. /* the above function sets the state for us in case of an error */
  97135. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97136. }
  97137. /*
  97138. * Now that the STREAMINFO block is written, we can init this to an
  97139. * absurdly-high value...
  97140. */
  97141. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  97142. /* ... and clear this to 0 */
  97143. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  97144. /*
  97145. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  97146. * if not, we will write an empty one (FLAC__add_metadata_block()
  97147. * automatically supplies the vendor string).
  97148. *
  97149. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  97150. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  97151. * true it will have already insured that the metadata list is properly
  97152. * ordered.)
  97153. */
  97154. if(!metadata_has_vorbis_comment) {
  97155. FLAC__StreamMetadata vorbis_comment;
  97156. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  97157. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  97158. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  97159. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  97160. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  97161. vorbis_comment.data.vorbis_comment.num_comments = 0;
  97162. vorbis_comment.data.vorbis_comment.comments = 0;
  97163. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  97164. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  97165. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97166. }
  97167. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  97168. /* the above function sets the state for us in case of an error */
  97169. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97170. }
  97171. }
  97172. /*
  97173. * write the user's metadata blocks
  97174. */
  97175. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  97176. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  97177. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  97178. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  97179. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97180. }
  97181. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  97182. /* the above function sets the state for us in case of an error */
  97183. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97184. }
  97185. }
  97186. /* now that all the metadata is written, we save the stream offset */
  97187. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &encoder->protected_->audio_offset, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) { /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  97188. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97189. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97190. }
  97191. if(encoder->protected_->verify)
  97192. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  97193. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  97194. }
  97195. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  97196. FLAC__StreamEncoder *encoder,
  97197. FLAC__StreamEncoderWriteCallback write_callback,
  97198. FLAC__StreamEncoderSeekCallback seek_callback,
  97199. FLAC__StreamEncoderTellCallback tell_callback,
  97200. FLAC__StreamEncoderMetadataCallback metadata_callback,
  97201. void *client_data
  97202. )
  97203. {
  97204. return init_stream_internal_enc(
  97205. encoder,
  97206. /*read_callback=*/0,
  97207. write_callback,
  97208. seek_callback,
  97209. tell_callback,
  97210. metadata_callback,
  97211. client_data,
  97212. /*is_ogg=*/false
  97213. );
  97214. }
  97215. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  97216. FLAC__StreamEncoder *encoder,
  97217. FLAC__StreamEncoderReadCallback read_callback,
  97218. FLAC__StreamEncoderWriteCallback write_callback,
  97219. FLAC__StreamEncoderSeekCallback seek_callback,
  97220. FLAC__StreamEncoderTellCallback tell_callback,
  97221. FLAC__StreamEncoderMetadataCallback metadata_callback,
  97222. void *client_data
  97223. )
  97224. {
  97225. return init_stream_internal_enc(
  97226. encoder,
  97227. read_callback,
  97228. write_callback,
  97229. seek_callback,
  97230. tell_callback,
  97231. metadata_callback,
  97232. client_data,
  97233. /*is_ogg=*/true
  97234. );
  97235. }
  97236. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  97237. FLAC__StreamEncoder *encoder,
  97238. FILE *file,
  97239. FLAC__StreamEncoderProgressCallback progress_callback,
  97240. void *client_data,
  97241. FLAC__bool is_ogg
  97242. )
  97243. {
  97244. FLAC__StreamEncoderInitStatus init_status;
  97245. FLAC__ASSERT(0 != encoder);
  97246. FLAC__ASSERT(0 != file);
  97247. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97248. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  97249. /* double protection */
  97250. if(file == 0) {
  97251. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  97252. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97253. }
  97254. /*
  97255. * To make sure that our file does not go unclosed after an error, we
  97256. * must assign the FILE pointer before any further error can occur in
  97257. * this routine.
  97258. */
  97259. if(file == stdout)
  97260. file = get_binary_stdout_(); /* just to be safe */
  97261. encoder->private_->file = file;
  97262. encoder->private_->progress_callback = progress_callback;
  97263. encoder->private_->bytes_written = 0;
  97264. encoder->private_->samples_written = 0;
  97265. encoder->private_->frames_written = 0;
  97266. init_status = init_stream_internal_enc(
  97267. encoder,
  97268. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  97269. file_write_callback_,
  97270. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  97271. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  97272. /*metadata_callback=*/0,
  97273. client_data,
  97274. is_ogg
  97275. );
  97276. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  97277. /* the above function sets the state for us in case of an error */
  97278. return init_status;
  97279. }
  97280. {
  97281. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  97282. FLAC__ASSERT(blocksize != 0);
  97283. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  97284. }
  97285. return init_status;
  97286. }
  97287. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  97288. FLAC__StreamEncoder *encoder,
  97289. FILE *file,
  97290. FLAC__StreamEncoderProgressCallback progress_callback,
  97291. void *client_data
  97292. )
  97293. {
  97294. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  97295. }
  97296. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  97297. FLAC__StreamEncoder *encoder,
  97298. FILE *file,
  97299. FLAC__StreamEncoderProgressCallback progress_callback,
  97300. void *client_data
  97301. )
  97302. {
  97303. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  97304. }
  97305. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  97306. FLAC__StreamEncoder *encoder,
  97307. const char *filename,
  97308. FLAC__StreamEncoderProgressCallback progress_callback,
  97309. void *client_data,
  97310. FLAC__bool is_ogg
  97311. )
  97312. {
  97313. FILE *file;
  97314. FLAC__ASSERT(0 != encoder);
  97315. /*
  97316. * To make sure that our file does not go unclosed after an error, we
  97317. * have to do the same entrance checks here that are later performed
  97318. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  97319. */
  97320. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97321. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  97322. file = filename? fopen(filename, "w+b") : stdout;
  97323. if(file == 0) {
  97324. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  97325. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97326. }
  97327. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  97328. }
  97329. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  97330. FLAC__StreamEncoder *encoder,
  97331. const char *filename,
  97332. FLAC__StreamEncoderProgressCallback progress_callback,
  97333. void *client_data
  97334. )
  97335. {
  97336. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  97337. }
  97338. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  97339. FLAC__StreamEncoder *encoder,
  97340. const char *filename,
  97341. FLAC__StreamEncoderProgressCallback progress_callback,
  97342. void *client_data
  97343. )
  97344. {
  97345. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  97346. }
  97347. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  97348. {
  97349. FLAC__bool error = false;
  97350. FLAC__ASSERT(0 != encoder);
  97351. FLAC__ASSERT(0 != encoder->private_);
  97352. FLAC__ASSERT(0 != encoder->protected_);
  97353. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  97354. return true;
  97355. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  97356. if(encoder->private_->current_sample_number != 0) {
  97357. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  97358. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  97359. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  97360. error = true;
  97361. }
  97362. }
  97363. if(encoder->protected_->do_md5)
  97364. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  97365. if(!encoder->private_->is_being_deleted) {
  97366. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  97367. if(encoder->private_->seek_callback) {
  97368. #if FLAC__HAS_OGG
  97369. if(encoder->private_->is_ogg)
  97370. update_ogg_metadata_(encoder);
  97371. else
  97372. #endif
  97373. update_metadata_(encoder);
  97374. /* check if an error occurred while updating metadata */
  97375. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  97376. error = true;
  97377. }
  97378. if(encoder->private_->metadata_callback)
  97379. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  97380. }
  97381. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  97382. if(!error)
  97383. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  97384. error = true;
  97385. }
  97386. }
  97387. if(0 != encoder->private_->file) {
  97388. if(encoder->private_->file != stdout)
  97389. fclose(encoder->private_->file);
  97390. encoder->private_->file = 0;
  97391. }
  97392. #if FLAC__HAS_OGG
  97393. if(encoder->private_->is_ogg)
  97394. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  97395. #endif
  97396. free_(encoder);
  97397. set_defaults_enc(encoder);
  97398. if(!error)
  97399. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  97400. return !error;
  97401. }
  97402. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  97403. {
  97404. FLAC__ASSERT(0 != encoder);
  97405. FLAC__ASSERT(0 != encoder->private_);
  97406. FLAC__ASSERT(0 != encoder->protected_);
  97407. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97408. return false;
  97409. #if FLAC__HAS_OGG
  97410. /* can't check encoder->private_->is_ogg since that's not set until init time */
  97411. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  97412. return true;
  97413. #else
  97414. (void)value;
  97415. return false;
  97416. #endif
  97417. }
  97418. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97419. {
  97420. FLAC__ASSERT(0 != encoder);
  97421. FLAC__ASSERT(0 != encoder->private_);
  97422. FLAC__ASSERT(0 != encoder->protected_);
  97423. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97424. return false;
  97425. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  97426. encoder->protected_->verify = value;
  97427. #endif
  97428. return true;
  97429. }
  97430. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97431. {
  97432. FLAC__ASSERT(0 != encoder);
  97433. FLAC__ASSERT(0 != encoder->private_);
  97434. FLAC__ASSERT(0 != encoder->protected_);
  97435. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97436. return false;
  97437. encoder->protected_->streamable_subset = value;
  97438. return true;
  97439. }
  97440. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97441. {
  97442. FLAC__ASSERT(0 != encoder);
  97443. FLAC__ASSERT(0 != encoder->private_);
  97444. FLAC__ASSERT(0 != encoder->protected_);
  97445. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97446. return false;
  97447. encoder->protected_->do_md5 = value;
  97448. return true;
  97449. }
  97450. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  97451. {
  97452. FLAC__ASSERT(0 != encoder);
  97453. FLAC__ASSERT(0 != encoder->private_);
  97454. FLAC__ASSERT(0 != encoder->protected_);
  97455. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97456. return false;
  97457. encoder->protected_->channels = value;
  97458. return true;
  97459. }
  97460. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  97461. {
  97462. FLAC__ASSERT(0 != encoder);
  97463. FLAC__ASSERT(0 != encoder->private_);
  97464. FLAC__ASSERT(0 != encoder->protected_);
  97465. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97466. return false;
  97467. encoder->protected_->bits_per_sample = value;
  97468. return true;
  97469. }
  97470. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  97471. {
  97472. FLAC__ASSERT(0 != encoder);
  97473. FLAC__ASSERT(0 != encoder->private_);
  97474. FLAC__ASSERT(0 != encoder->protected_);
  97475. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97476. return false;
  97477. encoder->protected_->sample_rate = value;
  97478. return true;
  97479. }
  97480. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  97481. {
  97482. FLAC__bool ok = true;
  97483. FLAC__ASSERT(0 != encoder);
  97484. FLAC__ASSERT(0 != encoder->private_);
  97485. FLAC__ASSERT(0 != encoder->protected_);
  97486. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97487. return false;
  97488. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  97489. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  97490. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  97491. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  97492. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97493. #if 0
  97494. /* was: */
  97495. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  97496. /* but it's too hard to specify the string in a locale-specific way */
  97497. #else
  97498. encoder->protected_->num_apodizations = 1;
  97499. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  97500. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  97501. #endif
  97502. #endif
  97503. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  97504. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  97505. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  97506. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  97507. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  97508. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  97509. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  97510. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  97511. return ok;
  97512. }
  97513. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  97514. {
  97515. FLAC__ASSERT(0 != encoder);
  97516. FLAC__ASSERT(0 != encoder->private_);
  97517. FLAC__ASSERT(0 != encoder->protected_);
  97518. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97519. return false;
  97520. encoder->protected_->blocksize = value;
  97521. return true;
  97522. }
  97523. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97524. {
  97525. FLAC__ASSERT(0 != encoder);
  97526. FLAC__ASSERT(0 != encoder->private_);
  97527. FLAC__ASSERT(0 != encoder->protected_);
  97528. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97529. return false;
  97530. encoder->protected_->do_mid_side_stereo = value;
  97531. return true;
  97532. }
  97533. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97534. {
  97535. FLAC__ASSERT(0 != encoder);
  97536. FLAC__ASSERT(0 != encoder->private_);
  97537. FLAC__ASSERT(0 != encoder->protected_);
  97538. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97539. return false;
  97540. encoder->protected_->loose_mid_side_stereo = value;
  97541. return true;
  97542. }
  97543. /*@@@@add to tests*/
  97544. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  97545. {
  97546. FLAC__ASSERT(0 != encoder);
  97547. FLAC__ASSERT(0 != encoder->private_);
  97548. FLAC__ASSERT(0 != encoder->protected_);
  97549. FLAC__ASSERT(0 != specification);
  97550. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97551. return false;
  97552. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  97553. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  97554. #else
  97555. encoder->protected_->num_apodizations = 0;
  97556. while(1) {
  97557. const char *s = strchr(specification, ';');
  97558. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  97559. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  97560. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  97561. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  97562. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  97563. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  97564. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  97565. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  97566. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  97567. else if(n==6 && 0 == strncmp("connes" , specification, n))
  97568. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  97569. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  97570. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  97571. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  97572. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  97573. if (stddev > 0.0 && stddev <= 0.5) {
  97574. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  97575. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  97576. }
  97577. }
  97578. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  97579. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  97580. else if(n==4 && 0 == strncmp("hann" , specification, n))
  97581. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  97582. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  97583. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  97584. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  97585. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  97586. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  97587. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  97588. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  97589. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  97590. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  97591. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  97592. if (p >= 0.0 && p <= 1.0) {
  97593. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  97594. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  97595. }
  97596. }
  97597. else if(n==5 && 0 == strncmp("welch" , specification, n))
  97598. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  97599. if (encoder->protected_->num_apodizations == 32)
  97600. break;
  97601. if (s)
  97602. specification = s+1;
  97603. else
  97604. break;
  97605. }
  97606. if(encoder->protected_->num_apodizations == 0) {
  97607. encoder->protected_->num_apodizations = 1;
  97608. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  97609. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  97610. }
  97611. #endif
  97612. return true;
  97613. }
  97614. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  97615. {
  97616. FLAC__ASSERT(0 != encoder);
  97617. FLAC__ASSERT(0 != encoder->private_);
  97618. FLAC__ASSERT(0 != encoder->protected_);
  97619. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97620. return false;
  97621. encoder->protected_->max_lpc_order = value;
  97622. return true;
  97623. }
  97624. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  97625. {
  97626. FLAC__ASSERT(0 != encoder);
  97627. FLAC__ASSERT(0 != encoder->private_);
  97628. FLAC__ASSERT(0 != encoder->protected_);
  97629. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97630. return false;
  97631. encoder->protected_->qlp_coeff_precision = value;
  97632. return true;
  97633. }
  97634. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97635. {
  97636. FLAC__ASSERT(0 != encoder);
  97637. FLAC__ASSERT(0 != encoder->private_);
  97638. FLAC__ASSERT(0 != encoder->protected_);
  97639. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97640. return false;
  97641. encoder->protected_->do_qlp_coeff_prec_search = value;
  97642. return true;
  97643. }
  97644. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97645. {
  97646. FLAC__ASSERT(0 != encoder);
  97647. FLAC__ASSERT(0 != encoder->private_);
  97648. FLAC__ASSERT(0 != encoder->protected_);
  97649. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97650. return false;
  97651. #if 0
  97652. /*@@@ deprecated: */
  97653. encoder->protected_->do_escape_coding = value;
  97654. #else
  97655. (void)value;
  97656. #endif
  97657. return true;
  97658. }
  97659. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97660. {
  97661. FLAC__ASSERT(0 != encoder);
  97662. FLAC__ASSERT(0 != encoder->private_);
  97663. FLAC__ASSERT(0 != encoder->protected_);
  97664. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97665. return false;
  97666. encoder->protected_->do_exhaustive_model_search = value;
  97667. return true;
  97668. }
  97669. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  97670. {
  97671. FLAC__ASSERT(0 != encoder);
  97672. FLAC__ASSERT(0 != encoder->private_);
  97673. FLAC__ASSERT(0 != encoder->protected_);
  97674. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97675. return false;
  97676. encoder->protected_->min_residual_partition_order = value;
  97677. return true;
  97678. }
  97679. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  97680. {
  97681. FLAC__ASSERT(0 != encoder);
  97682. FLAC__ASSERT(0 != encoder->private_);
  97683. FLAC__ASSERT(0 != encoder->protected_);
  97684. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97685. return false;
  97686. encoder->protected_->max_residual_partition_order = value;
  97687. return true;
  97688. }
  97689. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  97690. {
  97691. FLAC__ASSERT(0 != encoder);
  97692. FLAC__ASSERT(0 != encoder->private_);
  97693. FLAC__ASSERT(0 != encoder->protected_);
  97694. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97695. return false;
  97696. #if 0
  97697. /*@@@ deprecated: */
  97698. encoder->protected_->rice_parameter_search_dist = value;
  97699. #else
  97700. (void)value;
  97701. #endif
  97702. return true;
  97703. }
  97704. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  97705. {
  97706. FLAC__ASSERT(0 != encoder);
  97707. FLAC__ASSERT(0 != encoder->private_);
  97708. FLAC__ASSERT(0 != encoder->protected_);
  97709. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97710. return false;
  97711. encoder->protected_->total_samples_estimate = value;
  97712. return true;
  97713. }
  97714. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  97715. {
  97716. FLAC__ASSERT(0 != encoder);
  97717. FLAC__ASSERT(0 != encoder->private_);
  97718. FLAC__ASSERT(0 != encoder->protected_);
  97719. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97720. return false;
  97721. if(0 == metadata)
  97722. num_blocks = 0;
  97723. if(0 == num_blocks)
  97724. metadata = 0;
  97725. /* realloc() does not do exactly what we want so... */
  97726. if(encoder->protected_->metadata) {
  97727. free(encoder->protected_->metadata);
  97728. encoder->protected_->metadata = 0;
  97729. encoder->protected_->num_metadata_blocks = 0;
  97730. }
  97731. if(num_blocks) {
  97732. FLAC__StreamMetadata **m;
  97733. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  97734. return false;
  97735. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  97736. encoder->protected_->metadata = m;
  97737. encoder->protected_->num_metadata_blocks = num_blocks;
  97738. }
  97739. #if FLAC__HAS_OGG
  97740. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  97741. return false;
  97742. #endif
  97743. return true;
  97744. }
  97745. /*
  97746. * These three functions are not static, but not publically exposed in
  97747. * include/FLAC/ either. They are used by the test suite.
  97748. */
  97749. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97750. {
  97751. FLAC__ASSERT(0 != encoder);
  97752. FLAC__ASSERT(0 != encoder->private_);
  97753. FLAC__ASSERT(0 != encoder->protected_);
  97754. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97755. return false;
  97756. encoder->private_->disable_constant_subframes = value;
  97757. return true;
  97758. }
  97759. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97760. {
  97761. FLAC__ASSERT(0 != encoder);
  97762. FLAC__ASSERT(0 != encoder->private_);
  97763. FLAC__ASSERT(0 != encoder->protected_);
  97764. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97765. return false;
  97766. encoder->private_->disable_fixed_subframes = value;
  97767. return true;
  97768. }
  97769. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97770. {
  97771. FLAC__ASSERT(0 != encoder);
  97772. FLAC__ASSERT(0 != encoder->private_);
  97773. FLAC__ASSERT(0 != encoder->protected_);
  97774. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97775. return false;
  97776. encoder->private_->disable_verbatim_subframes = value;
  97777. return true;
  97778. }
  97779. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  97780. {
  97781. FLAC__ASSERT(0 != encoder);
  97782. FLAC__ASSERT(0 != encoder->private_);
  97783. FLAC__ASSERT(0 != encoder->protected_);
  97784. return encoder->protected_->state;
  97785. }
  97786. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  97787. {
  97788. FLAC__ASSERT(0 != encoder);
  97789. FLAC__ASSERT(0 != encoder->private_);
  97790. FLAC__ASSERT(0 != encoder->protected_);
  97791. if(encoder->protected_->verify)
  97792. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  97793. else
  97794. return FLAC__STREAM_DECODER_UNINITIALIZED;
  97795. }
  97796. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  97797. {
  97798. FLAC__ASSERT(0 != encoder);
  97799. FLAC__ASSERT(0 != encoder->private_);
  97800. FLAC__ASSERT(0 != encoder->protected_);
  97801. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  97802. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  97803. else
  97804. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  97805. }
  97806. FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got)
  97807. {
  97808. FLAC__ASSERT(0 != encoder);
  97809. FLAC__ASSERT(0 != encoder->private_);
  97810. FLAC__ASSERT(0 != encoder->protected_);
  97811. if(0 != absolute_sample)
  97812. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  97813. if(0 != frame_number)
  97814. *frame_number = encoder->private_->verify.error_stats.frame_number;
  97815. if(0 != channel)
  97816. *channel = encoder->private_->verify.error_stats.channel;
  97817. if(0 != sample)
  97818. *sample = encoder->private_->verify.error_stats.sample;
  97819. if(0 != expected)
  97820. *expected = encoder->private_->verify.error_stats.expected;
  97821. if(0 != got)
  97822. *got = encoder->private_->verify.error_stats.got;
  97823. }
  97824. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  97825. {
  97826. FLAC__ASSERT(0 != encoder);
  97827. FLAC__ASSERT(0 != encoder->private_);
  97828. FLAC__ASSERT(0 != encoder->protected_);
  97829. return encoder->protected_->verify;
  97830. }
  97831. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  97832. {
  97833. FLAC__ASSERT(0 != encoder);
  97834. FLAC__ASSERT(0 != encoder->private_);
  97835. FLAC__ASSERT(0 != encoder->protected_);
  97836. return encoder->protected_->streamable_subset;
  97837. }
  97838. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  97839. {
  97840. FLAC__ASSERT(0 != encoder);
  97841. FLAC__ASSERT(0 != encoder->private_);
  97842. FLAC__ASSERT(0 != encoder->protected_);
  97843. return encoder->protected_->do_md5;
  97844. }
  97845. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  97846. {
  97847. FLAC__ASSERT(0 != encoder);
  97848. FLAC__ASSERT(0 != encoder->private_);
  97849. FLAC__ASSERT(0 != encoder->protected_);
  97850. return encoder->protected_->channels;
  97851. }
  97852. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  97853. {
  97854. FLAC__ASSERT(0 != encoder);
  97855. FLAC__ASSERT(0 != encoder->private_);
  97856. FLAC__ASSERT(0 != encoder->protected_);
  97857. return encoder->protected_->bits_per_sample;
  97858. }
  97859. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  97860. {
  97861. FLAC__ASSERT(0 != encoder);
  97862. FLAC__ASSERT(0 != encoder->private_);
  97863. FLAC__ASSERT(0 != encoder->protected_);
  97864. return encoder->protected_->sample_rate;
  97865. }
  97866. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  97867. {
  97868. FLAC__ASSERT(0 != encoder);
  97869. FLAC__ASSERT(0 != encoder->private_);
  97870. FLAC__ASSERT(0 != encoder->protected_);
  97871. return encoder->protected_->blocksize;
  97872. }
  97873. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  97874. {
  97875. FLAC__ASSERT(0 != encoder);
  97876. FLAC__ASSERT(0 != encoder->private_);
  97877. FLAC__ASSERT(0 != encoder->protected_);
  97878. return encoder->protected_->do_mid_side_stereo;
  97879. }
  97880. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  97881. {
  97882. FLAC__ASSERT(0 != encoder);
  97883. FLAC__ASSERT(0 != encoder->private_);
  97884. FLAC__ASSERT(0 != encoder->protected_);
  97885. return encoder->protected_->loose_mid_side_stereo;
  97886. }
  97887. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  97888. {
  97889. FLAC__ASSERT(0 != encoder);
  97890. FLAC__ASSERT(0 != encoder->private_);
  97891. FLAC__ASSERT(0 != encoder->protected_);
  97892. return encoder->protected_->max_lpc_order;
  97893. }
  97894. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  97895. {
  97896. FLAC__ASSERT(0 != encoder);
  97897. FLAC__ASSERT(0 != encoder->private_);
  97898. FLAC__ASSERT(0 != encoder->protected_);
  97899. return encoder->protected_->qlp_coeff_precision;
  97900. }
  97901. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  97902. {
  97903. FLAC__ASSERT(0 != encoder);
  97904. FLAC__ASSERT(0 != encoder->private_);
  97905. FLAC__ASSERT(0 != encoder->protected_);
  97906. return encoder->protected_->do_qlp_coeff_prec_search;
  97907. }
  97908. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  97909. {
  97910. FLAC__ASSERT(0 != encoder);
  97911. FLAC__ASSERT(0 != encoder->private_);
  97912. FLAC__ASSERT(0 != encoder->protected_);
  97913. return encoder->protected_->do_escape_coding;
  97914. }
  97915. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  97916. {
  97917. FLAC__ASSERT(0 != encoder);
  97918. FLAC__ASSERT(0 != encoder->private_);
  97919. FLAC__ASSERT(0 != encoder->protected_);
  97920. return encoder->protected_->do_exhaustive_model_search;
  97921. }
  97922. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  97923. {
  97924. FLAC__ASSERT(0 != encoder);
  97925. FLAC__ASSERT(0 != encoder->private_);
  97926. FLAC__ASSERT(0 != encoder->protected_);
  97927. return encoder->protected_->min_residual_partition_order;
  97928. }
  97929. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  97930. {
  97931. FLAC__ASSERT(0 != encoder);
  97932. FLAC__ASSERT(0 != encoder->private_);
  97933. FLAC__ASSERT(0 != encoder->protected_);
  97934. return encoder->protected_->max_residual_partition_order;
  97935. }
  97936. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  97937. {
  97938. FLAC__ASSERT(0 != encoder);
  97939. FLAC__ASSERT(0 != encoder->private_);
  97940. FLAC__ASSERT(0 != encoder->protected_);
  97941. return encoder->protected_->rice_parameter_search_dist;
  97942. }
  97943. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  97944. {
  97945. FLAC__ASSERT(0 != encoder);
  97946. FLAC__ASSERT(0 != encoder->private_);
  97947. FLAC__ASSERT(0 != encoder->protected_);
  97948. return encoder->protected_->total_samples_estimate;
  97949. }
  97950. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  97951. {
  97952. unsigned i, j = 0, channel;
  97953. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  97954. FLAC__ASSERT(0 != encoder);
  97955. FLAC__ASSERT(0 != encoder->private_);
  97956. FLAC__ASSERT(0 != encoder->protected_);
  97957. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  97958. do {
  97959. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  97960. if(encoder->protected_->verify)
  97961. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  97962. for(channel = 0; channel < channels; channel++)
  97963. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  97964. if(encoder->protected_->do_mid_side_stereo) {
  97965. FLAC__ASSERT(channels == 2);
  97966. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  97967. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  97968. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  97969. encoder->private_->integer_signal_mid_side[0][i] = (buffer[0][j] + buffer[1][j]) >> 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
  97970. }
  97971. }
  97972. else
  97973. j += n;
  97974. encoder->private_->current_sample_number += n;
  97975. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  97976. if(encoder->private_->current_sample_number > blocksize) {
  97977. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  97978. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  97979. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  97980. return false;
  97981. /* move unprocessed overread samples to beginnings of arrays */
  97982. for(channel = 0; channel < channels; channel++)
  97983. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  97984. if(encoder->protected_->do_mid_side_stereo) {
  97985. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  97986. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  97987. }
  97988. encoder->private_->current_sample_number = 1;
  97989. }
  97990. } while(j < samples);
  97991. return true;
  97992. }
  97993. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  97994. {
  97995. unsigned i, j, k, channel;
  97996. FLAC__int32 x, mid, side;
  97997. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  97998. FLAC__ASSERT(0 != encoder);
  97999. FLAC__ASSERT(0 != encoder->private_);
  98000. FLAC__ASSERT(0 != encoder->protected_);
  98001. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  98002. j = k = 0;
  98003. /*
  98004. * we have several flavors of the same basic loop, optimized for
  98005. * different conditions:
  98006. */
  98007. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  98008. /*
  98009. * stereo coding: unroll channel loop
  98010. */
  98011. do {
  98012. if(encoder->protected_->verify)
  98013. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  98014. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  98015. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  98016. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  98017. x = buffer[k++];
  98018. encoder->private_->integer_signal[1][i] = x;
  98019. mid += x;
  98020. side -= x;
  98021. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  98022. encoder->private_->integer_signal_mid_side[1][i] = side;
  98023. encoder->private_->integer_signal_mid_side[0][i] = mid;
  98024. }
  98025. encoder->private_->current_sample_number = i;
  98026. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  98027. if(i > blocksize) {
  98028. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  98029. return false;
  98030. /* move unprocessed overread samples to beginnings of arrays */
  98031. FLAC__ASSERT(i == blocksize+OVERREAD_);
  98032. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  98033. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  98034. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  98035. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  98036. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  98037. encoder->private_->current_sample_number = 1;
  98038. }
  98039. } while(j < samples);
  98040. }
  98041. else {
  98042. /*
  98043. * independent channel coding: buffer each channel in inner loop
  98044. */
  98045. do {
  98046. if(encoder->protected_->verify)
  98047. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  98048. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  98049. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  98050. for(channel = 0; channel < channels; channel++)
  98051. encoder->private_->integer_signal[channel][i] = buffer[k++];
  98052. }
  98053. encoder->private_->current_sample_number = i;
  98054. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  98055. if(i > blocksize) {
  98056. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  98057. return false;
  98058. /* move unprocessed overread samples to beginnings of arrays */
  98059. FLAC__ASSERT(i == blocksize+OVERREAD_);
  98060. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  98061. for(channel = 0; channel < channels; channel++)
  98062. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  98063. encoder->private_->current_sample_number = 1;
  98064. }
  98065. } while(j < samples);
  98066. }
  98067. return true;
  98068. }
  98069. /***********************************************************************
  98070. *
  98071. * Private class methods
  98072. *
  98073. ***********************************************************************/
  98074. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  98075. {
  98076. FLAC__ASSERT(0 != encoder);
  98077. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  98078. encoder->protected_->verify = true;
  98079. #else
  98080. encoder->protected_->verify = false;
  98081. #endif
  98082. encoder->protected_->streamable_subset = true;
  98083. encoder->protected_->do_md5 = true;
  98084. encoder->protected_->do_mid_side_stereo = false;
  98085. encoder->protected_->loose_mid_side_stereo = false;
  98086. encoder->protected_->channels = 2;
  98087. encoder->protected_->bits_per_sample = 16;
  98088. encoder->protected_->sample_rate = 44100;
  98089. encoder->protected_->blocksize = 0;
  98090. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98091. encoder->protected_->num_apodizations = 1;
  98092. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  98093. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  98094. #endif
  98095. encoder->protected_->max_lpc_order = 0;
  98096. encoder->protected_->qlp_coeff_precision = 0;
  98097. encoder->protected_->do_qlp_coeff_prec_search = false;
  98098. encoder->protected_->do_exhaustive_model_search = false;
  98099. encoder->protected_->do_escape_coding = false;
  98100. encoder->protected_->min_residual_partition_order = 0;
  98101. encoder->protected_->max_residual_partition_order = 0;
  98102. encoder->protected_->rice_parameter_search_dist = 0;
  98103. encoder->protected_->total_samples_estimate = 0;
  98104. encoder->protected_->metadata = 0;
  98105. encoder->protected_->num_metadata_blocks = 0;
  98106. encoder->private_->seek_table = 0;
  98107. encoder->private_->disable_constant_subframes = false;
  98108. encoder->private_->disable_fixed_subframes = false;
  98109. encoder->private_->disable_verbatim_subframes = false;
  98110. #if FLAC__HAS_OGG
  98111. encoder->private_->is_ogg = false;
  98112. #endif
  98113. encoder->private_->read_callback = 0;
  98114. encoder->private_->write_callback = 0;
  98115. encoder->private_->seek_callback = 0;
  98116. encoder->private_->tell_callback = 0;
  98117. encoder->private_->metadata_callback = 0;
  98118. encoder->private_->progress_callback = 0;
  98119. encoder->private_->client_data = 0;
  98120. #if FLAC__HAS_OGG
  98121. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  98122. #endif
  98123. }
  98124. void free_(FLAC__StreamEncoder *encoder)
  98125. {
  98126. unsigned i, channel;
  98127. FLAC__ASSERT(0 != encoder);
  98128. if(encoder->protected_->metadata) {
  98129. free(encoder->protected_->metadata);
  98130. encoder->protected_->metadata = 0;
  98131. encoder->protected_->num_metadata_blocks = 0;
  98132. }
  98133. for(i = 0; i < encoder->protected_->channels; i++) {
  98134. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  98135. free(encoder->private_->integer_signal_unaligned[i]);
  98136. encoder->private_->integer_signal_unaligned[i] = 0;
  98137. }
  98138. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98139. if(0 != encoder->private_->real_signal_unaligned[i]) {
  98140. free(encoder->private_->real_signal_unaligned[i]);
  98141. encoder->private_->real_signal_unaligned[i] = 0;
  98142. }
  98143. #endif
  98144. }
  98145. for(i = 0; i < 2; i++) {
  98146. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  98147. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  98148. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  98149. }
  98150. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98151. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  98152. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  98153. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  98154. }
  98155. #endif
  98156. }
  98157. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98158. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  98159. if(0 != encoder->private_->window_unaligned[i]) {
  98160. free(encoder->private_->window_unaligned[i]);
  98161. encoder->private_->window_unaligned[i] = 0;
  98162. }
  98163. }
  98164. if(0 != encoder->private_->windowed_signal_unaligned) {
  98165. free(encoder->private_->windowed_signal_unaligned);
  98166. encoder->private_->windowed_signal_unaligned = 0;
  98167. }
  98168. #endif
  98169. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  98170. for(i = 0; i < 2; i++) {
  98171. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  98172. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  98173. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  98174. }
  98175. }
  98176. }
  98177. for(channel = 0; channel < 2; channel++) {
  98178. for(i = 0; i < 2; i++) {
  98179. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  98180. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  98181. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  98182. }
  98183. }
  98184. }
  98185. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  98186. free(encoder->private_->abs_residual_partition_sums_unaligned);
  98187. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  98188. }
  98189. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  98190. free(encoder->private_->raw_bits_per_partition_unaligned);
  98191. encoder->private_->raw_bits_per_partition_unaligned = 0;
  98192. }
  98193. if(encoder->protected_->verify) {
  98194. for(i = 0; i < encoder->protected_->channels; i++) {
  98195. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  98196. free(encoder->private_->verify.input_fifo.data[i]);
  98197. encoder->private_->verify.input_fifo.data[i] = 0;
  98198. }
  98199. }
  98200. }
  98201. FLAC__bitwriter_free(encoder->private_->frame);
  98202. }
  98203. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  98204. {
  98205. FLAC__bool ok;
  98206. unsigned i, channel;
  98207. FLAC__ASSERT(new_blocksize > 0);
  98208. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  98209. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  98210. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  98211. if(new_blocksize <= encoder->private_->input_capacity)
  98212. return true;
  98213. ok = true;
  98214. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  98215. * requires that the input arrays (in our case the integer signals)
  98216. * have a buffer of up to 3 zeroes in front (at negative indices) for
  98217. * alignment purposes; we use 4 in front to keep the data well-aligned.
  98218. */
  98219. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  98220. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  98221. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  98222. encoder->private_->integer_signal[i] += 4;
  98223. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98224. #if 0 /* @@@ currently unused */
  98225. if(encoder->protected_->max_lpc_order > 0)
  98226. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  98227. #endif
  98228. #endif
  98229. }
  98230. for(i = 0; ok && i < 2; i++) {
  98231. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_mid_side_unaligned[i], &encoder->private_->integer_signal_mid_side[i]);
  98232. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  98233. encoder->private_->integer_signal_mid_side[i] += 4;
  98234. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98235. #if 0 /* @@@ currently unused */
  98236. if(encoder->protected_->max_lpc_order > 0)
  98237. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_mid_side_unaligned[i], &encoder->private_->real_signal_mid_side[i]);
  98238. #endif
  98239. #endif
  98240. }
  98241. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98242. if(ok && encoder->protected_->max_lpc_order > 0) {
  98243. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  98244. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  98245. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  98246. }
  98247. #endif
  98248. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  98249. for(i = 0; ok && i < 2; i++) {
  98250. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  98251. }
  98252. }
  98253. for(channel = 0; ok && channel < 2; channel++) {
  98254. for(i = 0; ok && i < 2; i++) {
  98255. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_mid_side_unaligned[channel][i], &encoder->private_->residual_workspace_mid_side[channel][i]);
  98256. }
  98257. }
  98258. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  98259. /*@@@ new_blocksize*2 is too pessimistic, but to fix, we need smarter logic because a smaller new_blocksize can actually increase the # of partitions; would require moving this out into a separate function, then checking its capacity against the need of the current blocksize&min/max_partition_order (and maybe predictor order) */
  98260. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  98261. if(encoder->protected_->do_escape_coding)
  98262. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  98263. /* now adjust the windows if the blocksize has changed */
  98264. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98265. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  98266. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  98267. switch(encoder->protected_->apodizations[i].type) {
  98268. case FLAC__APODIZATION_BARTLETT:
  98269. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  98270. break;
  98271. case FLAC__APODIZATION_BARTLETT_HANN:
  98272. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  98273. break;
  98274. case FLAC__APODIZATION_BLACKMAN:
  98275. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  98276. break;
  98277. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  98278. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  98279. break;
  98280. case FLAC__APODIZATION_CONNES:
  98281. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  98282. break;
  98283. case FLAC__APODIZATION_FLATTOP:
  98284. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  98285. break;
  98286. case FLAC__APODIZATION_GAUSS:
  98287. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  98288. break;
  98289. case FLAC__APODIZATION_HAMMING:
  98290. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  98291. break;
  98292. case FLAC__APODIZATION_HANN:
  98293. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  98294. break;
  98295. case FLAC__APODIZATION_KAISER_BESSEL:
  98296. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  98297. break;
  98298. case FLAC__APODIZATION_NUTTALL:
  98299. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  98300. break;
  98301. case FLAC__APODIZATION_RECTANGLE:
  98302. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  98303. break;
  98304. case FLAC__APODIZATION_TRIANGLE:
  98305. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  98306. break;
  98307. case FLAC__APODIZATION_TUKEY:
  98308. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  98309. break;
  98310. case FLAC__APODIZATION_WELCH:
  98311. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  98312. break;
  98313. default:
  98314. FLAC__ASSERT(0);
  98315. /* double protection */
  98316. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  98317. break;
  98318. }
  98319. }
  98320. }
  98321. #endif
  98322. if(ok)
  98323. encoder->private_->input_capacity = new_blocksize;
  98324. else
  98325. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98326. return ok;
  98327. }
  98328. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  98329. {
  98330. const FLAC__byte *buffer;
  98331. size_t bytes;
  98332. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  98333. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  98334. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98335. return false;
  98336. }
  98337. if(encoder->protected_->verify) {
  98338. encoder->private_->verify.output.data = buffer;
  98339. encoder->private_->verify.output.bytes = bytes;
  98340. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  98341. encoder->private_->verify.needs_magic_hack = true;
  98342. }
  98343. else {
  98344. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  98345. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  98346. FLAC__bitwriter_clear(encoder->private_->frame);
  98347. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  98348. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  98349. return false;
  98350. }
  98351. }
  98352. }
  98353. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98354. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  98355. FLAC__bitwriter_clear(encoder->private_->frame);
  98356. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98357. return false;
  98358. }
  98359. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  98360. FLAC__bitwriter_clear(encoder->private_->frame);
  98361. if(samples > 0) {
  98362. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  98363. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  98364. }
  98365. return true;
  98366. }
  98367. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  98368. {
  98369. FLAC__StreamEncoderWriteStatus status;
  98370. FLAC__uint64 output_position = 0;
  98371. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  98372. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  98373. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98374. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  98375. }
  98376. /*
  98377. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  98378. */
  98379. if(samples == 0) {
  98380. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  98381. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  98382. encoder->protected_->streaminfo_offset = output_position;
  98383. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  98384. encoder->protected_->seektable_offset = output_position;
  98385. }
  98386. /*
  98387. * Mark the current seek point if hit (if audio_offset == 0 that
  98388. * means we're still writing metadata and haven't hit the first
  98389. * frame yet)
  98390. */
  98391. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  98392. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  98393. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  98394. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  98395. FLAC__uint64 test_sample;
  98396. unsigned i;
  98397. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  98398. test_sample = encoder->private_->seek_table->points[i].sample_number;
  98399. if(test_sample > frame_last_sample) {
  98400. break;
  98401. }
  98402. else if(test_sample >= frame_first_sample) {
  98403. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  98404. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  98405. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  98406. encoder->private_->first_seekpoint_to_check++;
  98407. /* DO NOT: "break;" and here's why:
  98408. * The seektable template may contain more than one target
  98409. * sample for any given frame; we will keep looping, generating
  98410. * duplicate seekpoints for them, and we'll clean it up later,
  98411. * just before writing the seektable back to the metadata.
  98412. */
  98413. }
  98414. else {
  98415. encoder->private_->first_seekpoint_to_check++;
  98416. }
  98417. }
  98418. }
  98419. #if FLAC__HAS_OGG
  98420. if(encoder->private_->is_ogg) {
  98421. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  98422. &encoder->protected_->ogg_encoder_aspect,
  98423. buffer,
  98424. bytes,
  98425. samples,
  98426. encoder->private_->current_frame_number,
  98427. is_last_block,
  98428. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  98429. encoder,
  98430. encoder->private_->client_data
  98431. );
  98432. }
  98433. else
  98434. #endif
  98435. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  98436. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98437. encoder->private_->bytes_written += bytes;
  98438. encoder->private_->samples_written += samples;
  98439. /* we keep a high watermark on the number of frames written because
  98440. * when the encoder goes back to write metadata, 'current_frame'
  98441. * will drop back to 0.
  98442. */
  98443. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  98444. }
  98445. else
  98446. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98447. return status;
  98448. }
  98449. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  98450. void update_metadata_(const FLAC__StreamEncoder *encoder)
  98451. {
  98452. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  98453. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  98454. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  98455. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  98456. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  98457. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  98458. FLAC__StreamEncoderSeekStatus seek_status;
  98459. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  98460. /* All this is based on intimate knowledge of the stream header
  98461. * layout, but a change to the header format that would break this
  98462. * would also break all streams encoded in the previous format.
  98463. */
  98464. /*
  98465. * Write MD5 signature
  98466. */
  98467. {
  98468. const unsigned md5_offset =
  98469. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98470. (
  98471. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98472. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  98473. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  98474. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  98475. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  98476. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  98477. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  98478. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  98479. ) / 8;
  98480. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  98481. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  98482. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98483. return;
  98484. }
  98485. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98486. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98487. return;
  98488. }
  98489. }
  98490. /*
  98491. * Write total samples
  98492. */
  98493. {
  98494. const unsigned total_samples_byte_offset =
  98495. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98496. (
  98497. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98498. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  98499. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  98500. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  98501. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  98502. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  98503. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  98504. - 4
  98505. ) / 8;
  98506. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  98507. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  98508. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  98509. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  98510. b[4] = (FLAC__byte)(samples & 0xFF);
  98511. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + total_samples_byte_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  98512. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  98513. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98514. return;
  98515. }
  98516. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98517. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98518. return;
  98519. }
  98520. }
  98521. /*
  98522. * Write min/max framesize
  98523. */
  98524. {
  98525. const unsigned min_framesize_offset =
  98526. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98527. (
  98528. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98529. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  98530. ) / 8;
  98531. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  98532. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  98533. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  98534. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  98535. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  98536. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  98537. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + min_framesize_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  98538. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  98539. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98540. return;
  98541. }
  98542. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98543. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98544. return;
  98545. }
  98546. }
  98547. /*
  98548. * Write seektable
  98549. */
  98550. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  98551. unsigned i;
  98552. FLAC__format_seektable_sort(encoder->private_->seek_table);
  98553. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  98554. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->seektable_offset + FLAC__STREAM_METADATA_HEADER_LENGTH, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  98555. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  98556. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98557. return;
  98558. }
  98559. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  98560. FLAC__uint64 xx;
  98561. unsigned x;
  98562. xx = encoder->private_->seek_table->points[i].sample_number;
  98563. b[7] = (FLAC__byte)xx; xx >>= 8;
  98564. b[6] = (FLAC__byte)xx; xx >>= 8;
  98565. b[5] = (FLAC__byte)xx; xx >>= 8;
  98566. b[4] = (FLAC__byte)xx; xx >>= 8;
  98567. b[3] = (FLAC__byte)xx; xx >>= 8;
  98568. b[2] = (FLAC__byte)xx; xx >>= 8;
  98569. b[1] = (FLAC__byte)xx; xx >>= 8;
  98570. b[0] = (FLAC__byte)xx; xx >>= 8;
  98571. xx = encoder->private_->seek_table->points[i].stream_offset;
  98572. b[15] = (FLAC__byte)xx; xx >>= 8;
  98573. b[14] = (FLAC__byte)xx; xx >>= 8;
  98574. b[13] = (FLAC__byte)xx; xx >>= 8;
  98575. b[12] = (FLAC__byte)xx; xx >>= 8;
  98576. b[11] = (FLAC__byte)xx; xx >>= 8;
  98577. b[10] = (FLAC__byte)xx; xx >>= 8;
  98578. b[9] = (FLAC__byte)xx; xx >>= 8;
  98579. b[8] = (FLAC__byte)xx; xx >>= 8;
  98580. x = encoder->private_->seek_table->points[i].frame_samples;
  98581. b[17] = (FLAC__byte)x; x >>= 8;
  98582. b[16] = (FLAC__byte)x; x >>= 8;
  98583. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98584. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98585. return;
  98586. }
  98587. }
  98588. }
  98589. }
  98590. #if FLAC__HAS_OGG
  98591. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  98592. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  98593. {
  98594. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  98595. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  98596. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  98597. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  98598. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  98599. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  98600. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  98601. FLAC__STREAM_SYNC_LENGTH
  98602. ;
  98603. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  98604. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  98605. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  98606. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  98607. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  98608. ogg_page page;
  98609. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  98610. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  98611. /* Pre-check that client supports seeking, since we don't want the
  98612. * ogg_helper code to ever have to deal with this condition.
  98613. */
  98614. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  98615. return;
  98616. /* All this is based on intimate knowledge of the stream header
  98617. * layout, but a change to the header format that would break this
  98618. * would also break all streams encoded in the previous format.
  98619. */
  98620. /**
  98621. ** Write STREAMINFO stats
  98622. **/
  98623. simple_ogg_page__init(&page);
  98624. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  98625. simple_ogg_page__clear(&page);
  98626. return; /* state already set */
  98627. }
  98628. /*
  98629. * Write MD5 signature
  98630. */
  98631. {
  98632. const unsigned md5_offset =
  98633. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  98634. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98635. (
  98636. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98637. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  98638. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  98639. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  98640. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  98641. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  98642. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  98643. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  98644. ) / 8;
  98645. if(md5_offset + 16 > (unsigned)page.body_len) {
  98646. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98647. simple_ogg_page__clear(&page);
  98648. return;
  98649. }
  98650. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  98651. }
  98652. /*
  98653. * Write total samples
  98654. */
  98655. {
  98656. const unsigned total_samples_byte_offset =
  98657. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  98658. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98659. (
  98660. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98661. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  98662. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  98663. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  98664. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  98665. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  98666. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  98667. - 4
  98668. ) / 8;
  98669. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  98670. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98671. simple_ogg_page__clear(&page);
  98672. return;
  98673. }
  98674. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  98675. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  98676. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  98677. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  98678. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  98679. b[4] = (FLAC__byte)(samples & 0xFF);
  98680. memcpy(page.body + total_samples_byte_offset, b, 5);
  98681. }
  98682. /*
  98683. * Write min/max framesize
  98684. */
  98685. {
  98686. const unsigned min_framesize_offset =
  98687. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  98688. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98689. (
  98690. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98691. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  98692. ) / 8;
  98693. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  98694. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98695. simple_ogg_page__clear(&page);
  98696. return;
  98697. }
  98698. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  98699. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  98700. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  98701. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  98702. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  98703. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  98704. memcpy(page.body + min_framesize_offset, b, 6);
  98705. }
  98706. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  98707. simple_ogg_page__clear(&page);
  98708. return; /* state already set */
  98709. }
  98710. simple_ogg_page__clear(&page);
  98711. /*
  98712. * Write seektable
  98713. */
  98714. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  98715. unsigned i;
  98716. FLAC__byte *p;
  98717. FLAC__format_seektable_sort(encoder->private_->seek_table);
  98718. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  98719. simple_ogg_page__init(&page);
  98720. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  98721. simple_ogg_page__clear(&page);
  98722. return; /* state already set */
  98723. }
  98724. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  98725. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98726. simple_ogg_page__clear(&page);
  98727. return;
  98728. }
  98729. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  98730. FLAC__uint64 xx;
  98731. unsigned x;
  98732. xx = encoder->private_->seek_table->points[i].sample_number;
  98733. b[7] = (FLAC__byte)xx; xx >>= 8;
  98734. b[6] = (FLAC__byte)xx; xx >>= 8;
  98735. b[5] = (FLAC__byte)xx; xx >>= 8;
  98736. b[4] = (FLAC__byte)xx; xx >>= 8;
  98737. b[3] = (FLAC__byte)xx; xx >>= 8;
  98738. b[2] = (FLAC__byte)xx; xx >>= 8;
  98739. b[1] = (FLAC__byte)xx; xx >>= 8;
  98740. b[0] = (FLAC__byte)xx; xx >>= 8;
  98741. xx = encoder->private_->seek_table->points[i].stream_offset;
  98742. b[15] = (FLAC__byte)xx; xx >>= 8;
  98743. b[14] = (FLAC__byte)xx; xx >>= 8;
  98744. b[13] = (FLAC__byte)xx; xx >>= 8;
  98745. b[12] = (FLAC__byte)xx; xx >>= 8;
  98746. b[11] = (FLAC__byte)xx; xx >>= 8;
  98747. b[10] = (FLAC__byte)xx; xx >>= 8;
  98748. b[9] = (FLAC__byte)xx; xx >>= 8;
  98749. b[8] = (FLAC__byte)xx; xx >>= 8;
  98750. x = encoder->private_->seek_table->points[i].frame_samples;
  98751. b[17] = (FLAC__byte)x; x >>= 8;
  98752. b[16] = (FLAC__byte)x; x >>= 8;
  98753. memcpy(p, b, 18);
  98754. }
  98755. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  98756. simple_ogg_page__clear(&page);
  98757. return; /* state already set */
  98758. }
  98759. simple_ogg_page__clear(&page);
  98760. }
  98761. }
  98762. #endif
  98763. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  98764. {
  98765. FLAC__uint16 crc;
  98766. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  98767. /*
  98768. * Accumulate raw signal to the MD5 signature
  98769. */
  98770. if(encoder->protected_->do_md5 && !FLAC__MD5Accumulate(&encoder->private_->md5context, (const FLAC__int32 * const *)encoder->private_->integer_signal, encoder->protected_->channels, encoder->protected_->blocksize, (encoder->protected_->bits_per_sample+7) / 8)) {
  98771. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98772. return false;
  98773. }
  98774. /*
  98775. * Process the frame header and subframes into the frame bitbuffer
  98776. */
  98777. if(!process_subframes_(encoder, is_fractional_block)) {
  98778. /* the above function sets the state for us in case of an error */
  98779. return false;
  98780. }
  98781. /*
  98782. * Zero-pad the frame to a byte_boundary
  98783. */
  98784. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  98785. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98786. return false;
  98787. }
  98788. /*
  98789. * CRC-16 the whole thing
  98790. */
  98791. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  98792. if(
  98793. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  98794. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  98795. ) {
  98796. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98797. return false;
  98798. }
  98799. /*
  98800. * Write it
  98801. */
  98802. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  98803. /* the above function sets the state for us in case of an error */
  98804. return false;
  98805. }
  98806. /*
  98807. * Get ready for the next frame
  98808. */
  98809. encoder->private_->current_sample_number = 0;
  98810. encoder->private_->current_frame_number++;
  98811. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  98812. return true;
  98813. }
  98814. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  98815. {
  98816. FLAC__FrameHeader frame_header;
  98817. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  98818. FLAC__bool do_independent, do_mid_side;
  98819. /*
  98820. * Calculate the min,max Rice partition orders
  98821. */
  98822. if(is_fractional_block) {
  98823. max_partition_order = 0;
  98824. }
  98825. else {
  98826. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  98827. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  98828. }
  98829. min_partition_order = min(min_partition_order, max_partition_order);
  98830. /*
  98831. * Setup the frame
  98832. */
  98833. frame_header.blocksize = encoder->protected_->blocksize;
  98834. frame_header.sample_rate = encoder->protected_->sample_rate;
  98835. frame_header.channels = encoder->protected_->channels;
  98836. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  98837. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  98838. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  98839. frame_header.number.frame_number = encoder->private_->current_frame_number;
  98840. /*
  98841. * Figure out what channel assignments to try
  98842. */
  98843. if(encoder->protected_->do_mid_side_stereo) {
  98844. if(encoder->protected_->loose_mid_side_stereo) {
  98845. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  98846. do_independent = true;
  98847. do_mid_side = true;
  98848. }
  98849. else {
  98850. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  98851. do_mid_side = !do_independent;
  98852. }
  98853. }
  98854. else {
  98855. do_independent = true;
  98856. do_mid_side = true;
  98857. }
  98858. }
  98859. else {
  98860. do_independent = true;
  98861. do_mid_side = false;
  98862. }
  98863. FLAC__ASSERT(do_independent || do_mid_side);
  98864. /*
  98865. * Check for wasted bits; set effective bps for each subframe
  98866. */
  98867. if(do_independent) {
  98868. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  98869. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  98870. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  98871. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  98872. }
  98873. }
  98874. if(do_mid_side) {
  98875. FLAC__ASSERT(encoder->protected_->channels == 2);
  98876. for(channel = 0; channel < 2; channel++) {
  98877. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  98878. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  98879. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  98880. }
  98881. }
  98882. /*
  98883. * First do a normal encoding pass of each independent channel
  98884. */
  98885. if(do_independent) {
  98886. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  98887. if(!
  98888. process_subframe_(
  98889. encoder,
  98890. min_partition_order,
  98891. max_partition_order,
  98892. &frame_header,
  98893. encoder->private_->subframe_bps[channel],
  98894. encoder->private_->integer_signal[channel],
  98895. encoder->private_->subframe_workspace_ptr[channel],
  98896. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  98897. encoder->private_->residual_workspace[channel],
  98898. encoder->private_->best_subframe+channel,
  98899. encoder->private_->best_subframe_bits+channel
  98900. )
  98901. )
  98902. return false;
  98903. }
  98904. }
  98905. /*
  98906. * Now do mid and side channels if requested
  98907. */
  98908. if(do_mid_side) {
  98909. FLAC__ASSERT(encoder->protected_->channels == 2);
  98910. for(channel = 0; channel < 2; channel++) {
  98911. if(!
  98912. process_subframe_(
  98913. encoder,
  98914. min_partition_order,
  98915. max_partition_order,
  98916. &frame_header,
  98917. encoder->private_->subframe_bps_mid_side[channel],
  98918. encoder->private_->integer_signal_mid_side[channel],
  98919. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  98920. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  98921. encoder->private_->residual_workspace_mid_side[channel],
  98922. encoder->private_->best_subframe_mid_side+channel,
  98923. encoder->private_->best_subframe_bits_mid_side+channel
  98924. )
  98925. )
  98926. return false;
  98927. }
  98928. }
  98929. /*
  98930. * Compose the frame bitbuffer
  98931. */
  98932. if(do_mid_side) {
  98933. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  98934. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  98935. FLAC__ChannelAssignment channel_assignment;
  98936. FLAC__ASSERT(encoder->protected_->channels == 2);
  98937. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  98938. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  98939. }
  98940. else {
  98941. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  98942. unsigned min_bits;
  98943. int ca;
  98944. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  98945. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  98946. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  98947. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  98948. FLAC__ASSERT(do_independent && do_mid_side);
  98949. /* We have to figure out which channel assignent results in the smallest frame */
  98950. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  98951. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  98952. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  98953. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  98954. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  98955. min_bits = bits[channel_assignment];
  98956. for(ca = 1; ca <= 3; ca++) {
  98957. if(bits[ca] < min_bits) {
  98958. min_bits = bits[ca];
  98959. channel_assignment = (FLAC__ChannelAssignment)ca;
  98960. }
  98961. }
  98962. }
  98963. frame_header.channel_assignment = channel_assignment;
  98964. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  98965. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98966. return false;
  98967. }
  98968. switch(channel_assignment) {
  98969. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  98970. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  98971. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  98972. break;
  98973. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  98974. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  98975. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  98976. break;
  98977. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  98978. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  98979. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  98980. break;
  98981. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  98982. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  98983. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  98984. break;
  98985. default:
  98986. FLAC__ASSERT(0);
  98987. }
  98988. switch(channel_assignment) {
  98989. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  98990. left_bps = encoder->private_->subframe_bps [0];
  98991. right_bps = encoder->private_->subframe_bps [1];
  98992. break;
  98993. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  98994. left_bps = encoder->private_->subframe_bps [0];
  98995. right_bps = encoder->private_->subframe_bps_mid_side[1];
  98996. break;
  98997. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  98998. left_bps = encoder->private_->subframe_bps_mid_side[1];
  98999. right_bps = encoder->private_->subframe_bps [1];
  99000. break;
  99001. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  99002. left_bps = encoder->private_->subframe_bps_mid_side[0];
  99003. right_bps = encoder->private_->subframe_bps_mid_side[1];
  99004. break;
  99005. default:
  99006. FLAC__ASSERT(0);
  99007. }
  99008. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  99009. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  99010. return false;
  99011. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  99012. return false;
  99013. }
  99014. else {
  99015. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  99016. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99017. return false;
  99018. }
  99019. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  99020. if(!add_subframe_(encoder, frame_header.blocksize, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame)) {
  99021. /* the above function sets the state for us in case of an error */
  99022. return false;
  99023. }
  99024. }
  99025. }
  99026. if(encoder->protected_->loose_mid_side_stereo) {
  99027. encoder->private_->loose_mid_side_stereo_frame_count++;
  99028. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  99029. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  99030. }
  99031. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  99032. return true;
  99033. }
  99034. FLAC__bool process_subframe_(
  99035. FLAC__StreamEncoder *encoder,
  99036. unsigned min_partition_order,
  99037. unsigned max_partition_order,
  99038. const FLAC__FrameHeader *frame_header,
  99039. unsigned subframe_bps,
  99040. const FLAC__int32 integer_signal[],
  99041. FLAC__Subframe *subframe[2],
  99042. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  99043. FLAC__int32 *residual[2],
  99044. unsigned *best_subframe,
  99045. unsigned *best_bits
  99046. )
  99047. {
  99048. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99049. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  99050. #else
  99051. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  99052. #endif
  99053. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99054. FLAC__double lpc_residual_bits_per_sample;
  99055. FLAC__real autoc[FLAC__MAX_LPC_ORDER+1]; /* WATCHOUT: the size is important even though encoder->protected_->max_lpc_order might be less; some asm routines need all the space */
  99056. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  99057. unsigned min_lpc_order, max_lpc_order, lpc_order;
  99058. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  99059. #endif
  99060. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  99061. unsigned rice_parameter;
  99062. unsigned _candidate_bits, _best_bits;
  99063. unsigned _best_subframe;
  99064. /* only use RICE2 partitions if stream bps > 16 */
  99065. const unsigned rice_parameter_limit = FLAC__stream_encoder_get_bits_per_sample(encoder) > 16? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  99066. FLAC__ASSERT(frame_header->blocksize > 0);
  99067. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  99068. _best_subframe = 0;
  99069. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  99070. _best_bits = UINT_MAX;
  99071. else
  99072. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  99073. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  99074. unsigned signal_is_constant = false;
  99075. guess_fixed_order = encoder->private_->local_fixed_compute_best_predictor(integer_signal+FLAC__MAX_FIXED_ORDER, frame_header->blocksize-FLAC__MAX_FIXED_ORDER, fixed_residual_bits_per_sample);
  99076. /* check for constant subframe */
  99077. if(
  99078. !encoder->private_->disable_constant_subframes &&
  99079. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99080. fixed_residual_bits_per_sample[1] == 0.0
  99081. #else
  99082. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  99083. #endif
  99084. ) {
  99085. /* the above means it's possible all samples are the same value; now double-check it: */
  99086. unsigned i;
  99087. signal_is_constant = true;
  99088. for(i = 1; i < frame_header->blocksize; i++) {
  99089. if(integer_signal[0] != integer_signal[i]) {
  99090. signal_is_constant = false;
  99091. break;
  99092. }
  99093. }
  99094. }
  99095. if(signal_is_constant) {
  99096. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  99097. if(_candidate_bits < _best_bits) {
  99098. _best_subframe = !_best_subframe;
  99099. _best_bits = _candidate_bits;
  99100. }
  99101. }
  99102. else {
  99103. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  99104. /* encode fixed */
  99105. if(encoder->protected_->do_exhaustive_model_search) {
  99106. min_fixed_order = 0;
  99107. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  99108. }
  99109. else {
  99110. min_fixed_order = max_fixed_order = guess_fixed_order;
  99111. }
  99112. if(max_fixed_order >= frame_header->blocksize)
  99113. max_fixed_order = frame_header->blocksize - 1;
  99114. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  99115. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99116. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  99117. continue; /* don't even try */
  99118. rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > 0.0)? (unsigned)(fixed_residual_bits_per_sample[fixed_order]+0.5) : 0; /* 0.5 is for rounding */
  99119. #else
  99120. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  99121. continue; /* don't even try */
  99122. rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > FLAC__FP_ZERO)? (unsigned)FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]+FLAC__FP_ONE_HALF) : 0; /* 0.5 is for rounding */
  99123. #endif
  99124. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  99125. if(rice_parameter >= rice_parameter_limit) {
  99126. #ifdef DEBUG_VERBOSE
  99127. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  99128. #endif
  99129. rice_parameter = rice_parameter_limit - 1;
  99130. }
  99131. _candidate_bits =
  99132. evaluate_fixed_subframe_(
  99133. encoder,
  99134. integer_signal,
  99135. residual[!_best_subframe],
  99136. encoder->private_->abs_residual_partition_sums,
  99137. encoder->private_->raw_bits_per_partition,
  99138. frame_header->blocksize,
  99139. subframe_bps,
  99140. fixed_order,
  99141. rice_parameter,
  99142. rice_parameter_limit,
  99143. min_partition_order,
  99144. max_partition_order,
  99145. encoder->protected_->do_escape_coding,
  99146. encoder->protected_->rice_parameter_search_dist,
  99147. subframe[!_best_subframe],
  99148. partitioned_rice_contents[!_best_subframe]
  99149. );
  99150. if(_candidate_bits < _best_bits) {
  99151. _best_subframe = !_best_subframe;
  99152. _best_bits = _candidate_bits;
  99153. }
  99154. }
  99155. }
  99156. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99157. /* encode lpc */
  99158. if(encoder->protected_->max_lpc_order > 0) {
  99159. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  99160. max_lpc_order = frame_header->blocksize-1;
  99161. else
  99162. max_lpc_order = encoder->protected_->max_lpc_order;
  99163. if(max_lpc_order > 0) {
  99164. unsigned a;
  99165. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  99166. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  99167. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  99168. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  99169. if(autoc[0] != 0.0) {
  99170. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  99171. if(encoder->protected_->do_exhaustive_model_search) {
  99172. min_lpc_order = 1;
  99173. }
  99174. else {
  99175. const unsigned guess_lpc_order =
  99176. FLAC__lpc_compute_best_order(
  99177. lpc_error,
  99178. max_lpc_order,
  99179. frame_header->blocksize,
  99180. subframe_bps + (
  99181. encoder->protected_->do_qlp_coeff_prec_search?
  99182. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  99183. encoder->protected_->qlp_coeff_precision
  99184. )
  99185. );
  99186. min_lpc_order = max_lpc_order = guess_lpc_order;
  99187. }
  99188. if(max_lpc_order >= frame_header->blocksize)
  99189. max_lpc_order = frame_header->blocksize - 1;
  99190. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  99191. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  99192. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  99193. continue; /* don't even try */
  99194. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  99195. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  99196. if(rice_parameter >= rice_parameter_limit) {
  99197. #ifdef DEBUG_VERBOSE
  99198. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  99199. #endif
  99200. rice_parameter = rice_parameter_limit - 1;
  99201. }
  99202. if(encoder->protected_->do_qlp_coeff_prec_search) {
  99203. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  99204. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  99205. if(subframe_bps <= 17) {
  99206. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  99207. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  99208. }
  99209. else
  99210. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  99211. }
  99212. else {
  99213. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  99214. }
  99215. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  99216. _candidate_bits =
  99217. evaluate_lpc_subframe_(
  99218. encoder,
  99219. integer_signal,
  99220. residual[!_best_subframe],
  99221. encoder->private_->abs_residual_partition_sums,
  99222. encoder->private_->raw_bits_per_partition,
  99223. encoder->private_->lp_coeff[lpc_order-1],
  99224. frame_header->blocksize,
  99225. subframe_bps,
  99226. lpc_order,
  99227. qlp_coeff_precision,
  99228. rice_parameter,
  99229. rice_parameter_limit,
  99230. min_partition_order,
  99231. max_partition_order,
  99232. encoder->protected_->do_escape_coding,
  99233. encoder->protected_->rice_parameter_search_dist,
  99234. subframe[!_best_subframe],
  99235. partitioned_rice_contents[!_best_subframe]
  99236. );
  99237. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  99238. if(_candidate_bits < _best_bits) {
  99239. _best_subframe = !_best_subframe;
  99240. _best_bits = _candidate_bits;
  99241. }
  99242. }
  99243. }
  99244. }
  99245. }
  99246. }
  99247. }
  99248. }
  99249. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  99250. }
  99251. }
  99252. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  99253. if(_best_bits == UINT_MAX) {
  99254. FLAC__ASSERT(_best_subframe == 0);
  99255. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  99256. }
  99257. *best_subframe = _best_subframe;
  99258. *best_bits = _best_bits;
  99259. return true;
  99260. }
  99261. FLAC__bool add_subframe_(
  99262. FLAC__StreamEncoder *encoder,
  99263. unsigned blocksize,
  99264. unsigned subframe_bps,
  99265. const FLAC__Subframe *subframe,
  99266. FLAC__BitWriter *frame
  99267. )
  99268. {
  99269. switch(subframe->type) {
  99270. case FLAC__SUBFRAME_TYPE_CONSTANT:
  99271. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  99272. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99273. return false;
  99274. }
  99275. break;
  99276. case FLAC__SUBFRAME_TYPE_FIXED:
  99277. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  99278. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99279. return false;
  99280. }
  99281. break;
  99282. case FLAC__SUBFRAME_TYPE_LPC:
  99283. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  99284. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99285. return false;
  99286. }
  99287. break;
  99288. case FLAC__SUBFRAME_TYPE_VERBATIM:
  99289. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  99290. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99291. return false;
  99292. }
  99293. break;
  99294. default:
  99295. FLAC__ASSERT(0);
  99296. }
  99297. return true;
  99298. }
  99299. #define SPOTCHECK_ESTIMATE 0
  99300. #if SPOTCHECK_ESTIMATE
  99301. static void spotcheck_subframe_estimate_(
  99302. FLAC__StreamEncoder *encoder,
  99303. unsigned blocksize,
  99304. unsigned subframe_bps,
  99305. const FLAC__Subframe *subframe,
  99306. unsigned estimate
  99307. )
  99308. {
  99309. FLAC__bool ret;
  99310. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  99311. if(frame == 0) {
  99312. fprintf(stderr, "EST: can't allocate frame\n");
  99313. return;
  99314. }
  99315. if(!FLAC__bitwriter_init(frame)) {
  99316. fprintf(stderr, "EST: can't init frame\n");
  99317. return;
  99318. }
  99319. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  99320. FLAC__ASSERT(ret);
  99321. {
  99322. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  99323. if(estimate != actual)
  99324. fprintf(stderr, "EST: bad, frame#%u sub#%%d type=%8s est=%u, actual=%u, delta=%d\n", encoder->private_->current_frame_number, FLAC__SubframeTypeString[subframe->type], estimate, actual, (int)actual-(int)estimate);
  99325. }
  99326. FLAC__bitwriter_delete(frame);
  99327. }
  99328. #endif
  99329. unsigned evaluate_constant_subframe_(
  99330. FLAC__StreamEncoder *encoder,
  99331. const FLAC__int32 signal,
  99332. unsigned blocksize,
  99333. unsigned subframe_bps,
  99334. FLAC__Subframe *subframe
  99335. )
  99336. {
  99337. unsigned estimate;
  99338. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  99339. subframe->data.constant.value = signal;
  99340. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  99341. #if SPOTCHECK_ESTIMATE
  99342. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  99343. #else
  99344. (void)encoder, (void)blocksize;
  99345. #endif
  99346. return estimate;
  99347. }
  99348. unsigned evaluate_fixed_subframe_(
  99349. FLAC__StreamEncoder *encoder,
  99350. const FLAC__int32 signal[],
  99351. FLAC__int32 residual[],
  99352. FLAC__uint64 abs_residual_partition_sums[],
  99353. unsigned raw_bits_per_partition[],
  99354. unsigned blocksize,
  99355. unsigned subframe_bps,
  99356. unsigned order,
  99357. unsigned rice_parameter,
  99358. unsigned rice_parameter_limit,
  99359. unsigned min_partition_order,
  99360. unsigned max_partition_order,
  99361. FLAC__bool do_escape_coding,
  99362. unsigned rice_parameter_search_dist,
  99363. FLAC__Subframe *subframe,
  99364. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  99365. )
  99366. {
  99367. unsigned i, residual_bits, estimate;
  99368. const unsigned residual_samples = blocksize - order;
  99369. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  99370. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  99371. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  99372. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  99373. subframe->data.fixed.residual = residual;
  99374. residual_bits =
  99375. find_best_partition_order_(
  99376. encoder->private_,
  99377. residual,
  99378. abs_residual_partition_sums,
  99379. raw_bits_per_partition,
  99380. residual_samples,
  99381. order,
  99382. rice_parameter,
  99383. rice_parameter_limit,
  99384. min_partition_order,
  99385. max_partition_order,
  99386. subframe_bps,
  99387. do_escape_coding,
  99388. rice_parameter_search_dist,
  99389. &subframe->data.fixed.entropy_coding_method
  99390. );
  99391. subframe->data.fixed.order = order;
  99392. for(i = 0; i < order; i++)
  99393. subframe->data.fixed.warmup[i] = signal[i];
  99394. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  99395. #if SPOTCHECK_ESTIMATE
  99396. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  99397. #endif
  99398. return estimate;
  99399. }
  99400. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99401. unsigned evaluate_lpc_subframe_(
  99402. FLAC__StreamEncoder *encoder,
  99403. const FLAC__int32 signal[],
  99404. FLAC__int32 residual[],
  99405. FLAC__uint64 abs_residual_partition_sums[],
  99406. unsigned raw_bits_per_partition[],
  99407. const FLAC__real lp_coeff[],
  99408. unsigned blocksize,
  99409. unsigned subframe_bps,
  99410. unsigned order,
  99411. unsigned qlp_coeff_precision,
  99412. unsigned rice_parameter,
  99413. unsigned rice_parameter_limit,
  99414. unsigned min_partition_order,
  99415. unsigned max_partition_order,
  99416. FLAC__bool do_escape_coding,
  99417. unsigned rice_parameter_search_dist,
  99418. FLAC__Subframe *subframe,
  99419. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  99420. )
  99421. {
  99422. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  99423. unsigned i, residual_bits, estimate;
  99424. int quantization, ret;
  99425. const unsigned residual_samples = blocksize - order;
  99426. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  99427. if(subframe_bps <= 16) {
  99428. FLAC__ASSERT(order > 0);
  99429. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  99430. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  99431. }
  99432. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  99433. if(ret != 0)
  99434. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  99435. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  99436. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  99437. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  99438. else
  99439. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  99440. else
  99441. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  99442. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  99443. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  99444. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  99445. subframe->data.lpc.residual = residual;
  99446. residual_bits =
  99447. find_best_partition_order_(
  99448. encoder->private_,
  99449. residual,
  99450. abs_residual_partition_sums,
  99451. raw_bits_per_partition,
  99452. residual_samples,
  99453. order,
  99454. rice_parameter,
  99455. rice_parameter_limit,
  99456. min_partition_order,
  99457. max_partition_order,
  99458. subframe_bps,
  99459. do_escape_coding,
  99460. rice_parameter_search_dist,
  99461. &subframe->data.lpc.entropy_coding_method
  99462. );
  99463. subframe->data.lpc.order = order;
  99464. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  99465. subframe->data.lpc.quantization_level = quantization;
  99466. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  99467. for(i = 0; i < order; i++)
  99468. subframe->data.lpc.warmup[i] = signal[i];
  99469. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits;
  99470. #if SPOTCHECK_ESTIMATE
  99471. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  99472. #endif
  99473. return estimate;
  99474. }
  99475. #endif
  99476. unsigned evaluate_verbatim_subframe_(
  99477. FLAC__StreamEncoder *encoder,
  99478. const FLAC__int32 signal[],
  99479. unsigned blocksize,
  99480. unsigned subframe_bps,
  99481. FLAC__Subframe *subframe
  99482. )
  99483. {
  99484. unsigned estimate;
  99485. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  99486. subframe->data.verbatim.data = signal;
  99487. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  99488. #if SPOTCHECK_ESTIMATE
  99489. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  99490. #else
  99491. (void)encoder;
  99492. #endif
  99493. return estimate;
  99494. }
  99495. unsigned find_best_partition_order_(
  99496. FLAC__StreamEncoderPrivate *private_,
  99497. const FLAC__int32 residual[],
  99498. FLAC__uint64 abs_residual_partition_sums[],
  99499. unsigned raw_bits_per_partition[],
  99500. unsigned residual_samples,
  99501. unsigned predictor_order,
  99502. unsigned rice_parameter,
  99503. unsigned rice_parameter_limit,
  99504. unsigned min_partition_order,
  99505. unsigned max_partition_order,
  99506. unsigned bps,
  99507. FLAC__bool do_escape_coding,
  99508. unsigned rice_parameter_search_dist,
  99509. FLAC__EntropyCodingMethod *best_ecm
  99510. )
  99511. {
  99512. unsigned residual_bits, best_residual_bits = 0;
  99513. unsigned best_parameters_index = 0;
  99514. unsigned best_partition_order = 0;
  99515. const unsigned blocksize = residual_samples + predictor_order;
  99516. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  99517. min_partition_order = min(min_partition_order, max_partition_order);
  99518. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  99519. if(do_escape_coding)
  99520. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  99521. {
  99522. int partition_order;
  99523. unsigned sum;
  99524. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  99525. if(!
  99526. set_partitioned_rice_(
  99527. #ifdef EXACT_RICE_BITS_CALCULATION
  99528. residual,
  99529. #endif
  99530. abs_residual_partition_sums+sum,
  99531. raw_bits_per_partition+sum,
  99532. residual_samples,
  99533. predictor_order,
  99534. rice_parameter,
  99535. rice_parameter_limit,
  99536. rice_parameter_search_dist,
  99537. (unsigned)partition_order,
  99538. do_escape_coding,
  99539. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  99540. &residual_bits
  99541. )
  99542. )
  99543. {
  99544. FLAC__ASSERT(best_residual_bits != 0);
  99545. break;
  99546. }
  99547. sum += 1u << partition_order;
  99548. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  99549. best_residual_bits = residual_bits;
  99550. best_parameters_index = !best_parameters_index;
  99551. best_partition_order = partition_order;
  99552. }
  99553. }
  99554. }
  99555. best_ecm->data.partitioned_rice.order = best_partition_order;
  99556. {
  99557. /*
  99558. * We are allowed to de-const the pointer based on our special
  99559. * knowledge; it is const to the outside world.
  99560. */
  99561. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  99562. unsigned partition;
  99563. /* save best parameters and raw_bits */
  99564. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  99565. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  99566. if(do_escape_coding)
  99567. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  99568. /*
  99569. * Now need to check if the type should be changed to
  99570. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  99571. * size of the rice parameters.
  99572. */
  99573. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  99574. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  99575. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  99576. break;
  99577. }
  99578. }
  99579. }
  99580. return best_residual_bits;
  99581. }
  99582. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  99583. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  99584. const FLAC__int32 residual[],
  99585. FLAC__uint64 abs_residual_partition_sums[],
  99586. unsigned blocksize,
  99587. unsigned predictor_order,
  99588. unsigned min_partition_order,
  99589. unsigned max_partition_order
  99590. );
  99591. #endif
  99592. void precompute_partition_info_sums_(
  99593. const FLAC__int32 residual[],
  99594. FLAC__uint64 abs_residual_partition_sums[],
  99595. unsigned residual_samples,
  99596. unsigned predictor_order,
  99597. unsigned min_partition_order,
  99598. unsigned max_partition_order,
  99599. unsigned bps
  99600. )
  99601. {
  99602. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  99603. unsigned partitions = 1u << max_partition_order;
  99604. FLAC__ASSERT(default_partition_samples > predictor_order);
  99605. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  99606. /* slightly pessimistic but still catches all common cases */
  99607. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  99608. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  99609. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  99610. return;
  99611. }
  99612. #endif
  99613. /* first do max_partition_order */
  99614. {
  99615. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  99616. /* slightly pessimistic but still catches all common cases */
  99617. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  99618. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  99619. FLAC__uint32 abs_residual_partition_sum;
  99620. for(partition = residual_sample = 0; partition < partitions; partition++) {
  99621. end += default_partition_samples;
  99622. abs_residual_partition_sum = 0;
  99623. for( ; residual_sample < end; residual_sample++)
  99624. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  99625. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  99626. }
  99627. }
  99628. else { /* have to pessimistically use 64 bits for accumulator */
  99629. FLAC__uint64 abs_residual_partition_sum;
  99630. for(partition = residual_sample = 0; partition < partitions; partition++) {
  99631. end += default_partition_samples;
  99632. abs_residual_partition_sum = 0;
  99633. for( ; residual_sample < end; residual_sample++)
  99634. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  99635. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  99636. }
  99637. }
  99638. }
  99639. /* now merge partitions for lower orders */
  99640. {
  99641. unsigned from_partition = 0, to_partition = partitions;
  99642. int partition_order;
  99643. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  99644. unsigned i;
  99645. partitions >>= 1;
  99646. for(i = 0; i < partitions; i++) {
  99647. abs_residual_partition_sums[to_partition++] =
  99648. abs_residual_partition_sums[from_partition ] +
  99649. abs_residual_partition_sums[from_partition+1];
  99650. from_partition += 2;
  99651. }
  99652. }
  99653. }
  99654. }
  99655. void precompute_partition_info_escapes_(
  99656. const FLAC__int32 residual[],
  99657. unsigned raw_bits_per_partition[],
  99658. unsigned residual_samples,
  99659. unsigned predictor_order,
  99660. unsigned min_partition_order,
  99661. unsigned max_partition_order
  99662. )
  99663. {
  99664. int partition_order;
  99665. unsigned from_partition, to_partition = 0;
  99666. const unsigned blocksize = residual_samples + predictor_order;
  99667. /* first do max_partition_order */
  99668. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  99669. FLAC__int32 r;
  99670. FLAC__uint32 rmax;
  99671. unsigned partition, partition_sample, partition_samples, residual_sample;
  99672. const unsigned partitions = 1u << partition_order;
  99673. const unsigned default_partition_samples = blocksize >> partition_order;
  99674. FLAC__ASSERT(default_partition_samples > predictor_order);
  99675. for(partition = residual_sample = 0; partition < partitions; partition++) {
  99676. partition_samples = default_partition_samples;
  99677. if(partition == 0)
  99678. partition_samples -= predictor_order;
  99679. rmax = 0;
  99680. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  99681. r = residual[residual_sample++];
  99682. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  99683. if(r < 0)
  99684. rmax |= ~r;
  99685. else
  99686. rmax |= r;
  99687. }
  99688. /* now we know all residual values are in the range [-rmax-1,rmax] */
  99689. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  99690. }
  99691. to_partition = partitions;
  99692. break; /*@@@ yuck, should remove the 'for' loop instead */
  99693. }
  99694. /* now merge partitions for lower orders */
  99695. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  99696. unsigned m;
  99697. unsigned i;
  99698. const unsigned partitions = 1u << partition_order;
  99699. for(i = 0; i < partitions; i++) {
  99700. m = raw_bits_per_partition[from_partition];
  99701. from_partition++;
  99702. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  99703. from_partition++;
  99704. to_partition++;
  99705. }
  99706. }
  99707. }
  99708. #ifdef EXACT_RICE_BITS_CALCULATION
  99709. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  99710. const unsigned rice_parameter,
  99711. const unsigned partition_samples,
  99712. const FLAC__int32 *residual
  99713. )
  99714. {
  99715. unsigned i, partition_bits =
  99716. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
  99717. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  99718. ;
  99719. for(i = 0; i < partition_samples; i++)
  99720. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  99721. return partition_bits;
  99722. }
  99723. #else
  99724. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  99725. const unsigned rice_parameter,
  99726. const unsigned partition_samples,
  99727. const FLAC__uint64 abs_residual_partition_sum
  99728. )
  99729. {
  99730. return
  99731. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
  99732. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  99733. (
  99734. rice_parameter?
  99735. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  99736. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  99737. )
  99738. - (partition_samples >> 1)
  99739. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  99740. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  99741. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  99742. * So the subtraction term tries to guess how many extra bits were contributed.
  99743. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  99744. */
  99745. ;
  99746. }
  99747. #endif
  99748. FLAC__bool set_partitioned_rice_(
  99749. #ifdef EXACT_RICE_BITS_CALCULATION
  99750. const FLAC__int32 residual[],
  99751. #endif
  99752. const FLAC__uint64 abs_residual_partition_sums[],
  99753. const unsigned raw_bits_per_partition[],
  99754. const unsigned residual_samples,
  99755. const unsigned predictor_order,
  99756. const unsigned suggested_rice_parameter,
  99757. const unsigned rice_parameter_limit,
  99758. const unsigned rice_parameter_search_dist,
  99759. const unsigned partition_order,
  99760. const FLAC__bool search_for_escapes,
  99761. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  99762. unsigned *bits
  99763. )
  99764. {
  99765. unsigned rice_parameter, partition_bits;
  99766. unsigned best_partition_bits, best_rice_parameter = 0;
  99767. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  99768. unsigned *parameters, *raw_bits;
  99769. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99770. unsigned min_rice_parameter, max_rice_parameter;
  99771. #else
  99772. (void)rice_parameter_search_dist;
  99773. #endif
  99774. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  99775. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  99776. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  99777. parameters = partitioned_rice_contents->parameters;
  99778. raw_bits = partitioned_rice_contents->raw_bits;
  99779. if(partition_order == 0) {
  99780. best_partition_bits = (unsigned)(-1);
  99781. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99782. if(rice_parameter_search_dist) {
  99783. if(suggested_rice_parameter < rice_parameter_search_dist)
  99784. min_rice_parameter = 0;
  99785. else
  99786. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  99787. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  99788. if(max_rice_parameter >= rice_parameter_limit) {
  99789. #ifdef DEBUG_VERBOSE
  99790. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  99791. #endif
  99792. max_rice_parameter = rice_parameter_limit - 1;
  99793. }
  99794. }
  99795. else
  99796. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  99797. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  99798. #else
  99799. rice_parameter = suggested_rice_parameter;
  99800. #endif
  99801. #ifdef EXACT_RICE_BITS_CALCULATION
  99802. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  99803. #else
  99804. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  99805. #endif
  99806. if(partition_bits < best_partition_bits) {
  99807. best_rice_parameter = rice_parameter;
  99808. best_partition_bits = partition_bits;
  99809. }
  99810. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99811. }
  99812. #endif
  99813. if(search_for_escapes) {
  99814. partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[0] * residual_samples;
  99815. if(partition_bits <= best_partition_bits) {
  99816. raw_bits[0] = raw_bits_per_partition[0];
  99817. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  99818. best_partition_bits = partition_bits;
  99819. }
  99820. else
  99821. raw_bits[0] = 0;
  99822. }
  99823. parameters[0] = best_rice_parameter;
  99824. bits_ += best_partition_bits;
  99825. }
  99826. else {
  99827. unsigned partition, residual_sample;
  99828. unsigned partition_samples;
  99829. FLAC__uint64 mean, k;
  99830. const unsigned partitions = 1u << partition_order;
  99831. for(partition = residual_sample = 0; partition < partitions; partition++) {
  99832. partition_samples = (residual_samples+predictor_order) >> partition_order;
  99833. if(partition == 0) {
  99834. if(partition_samples <= predictor_order)
  99835. return false;
  99836. else
  99837. partition_samples -= predictor_order;
  99838. }
  99839. mean = abs_residual_partition_sums[partition];
  99840. /* we are basically calculating the size in bits of the
  99841. * average residual magnitude in the partition:
  99842. * rice_parameter = floor(log2(mean/partition_samples))
  99843. * 'mean' is not a good name for the variable, it is
  99844. * actually the sum of magnitudes of all residual values
  99845. * in the partition, so the actual mean is
  99846. * mean/partition_samples
  99847. */
  99848. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  99849. ;
  99850. if(rice_parameter >= rice_parameter_limit) {
  99851. #ifdef DEBUG_VERBOSE
  99852. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  99853. #endif
  99854. rice_parameter = rice_parameter_limit - 1;
  99855. }
  99856. best_partition_bits = (unsigned)(-1);
  99857. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99858. if(rice_parameter_search_dist) {
  99859. if(rice_parameter < rice_parameter_search_dist)
  99860. min_rice_parameter = 0;
  99861. else
  99862. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  99863. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  99864. if(max_rice_parameter >= rice_parameter_limit) {
  99865. #ifdef DEBUG_VERBOSE
  99866. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  99867. #endif
  99868. max_rice_parameter = rice_parameter_limit - 1;
  99869. }
  99870. }
  99871. else
  99872. min_rice_parameter = max_rice_parameter = rice_parameter;
  99873. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  99874. #endif
  99875. #ifdef EXACT_RICE_BITS_CALCULATION
  99876. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  99877. #else
  99878. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  99879. #endif
  99880. if(partition_bits < best_partition_bits) {
  99881. best_rice_parameter = rice_parameter;
  99882. best_partition_bits = partition_bits;
  99883. }
  99884. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99885. }
  99886. #endif
  99887. if(search_for_escapes) {
  99888. partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[partition] * partition_samples;
  99889. if(partition_bits <= best_partition_bits) {
  99890. raw_bits[partition] = raw_bits_per_partition[partition];
  99891. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  99892. best_partition_bits = partition_bits;
  99893. }
  99894. else
  99895. raw_bits[partition] = 0;
  99896. }
  99897. parameters[partition] = best_rice_parameter;
  99898. bits_ += best_partition_bits;
  99899. residual_sample += partition_samples;
  99900. }
  99901. }
  99902. *bits = bits_;
  99903. return true;
  99904. }
  99905. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  99906. {
  99907. unsigned i, shift;
  99908. FLAC__int32 x = 0;
  99909. for(i = 0; i < samples && !(x&1); i++)
  99910. x |= signal[i];
  99911. if(x == 0) {
  99912. shift = 0;
  99913. }
  99914. else {
  99915. for(shift = 0; !(x&1); shift++)
  99916. x >>= 1;
  99917. }
  99918. if(shift > 0) {
  99919. for(i = 0; i < samples; i++)
  99920. signal[i] >>= shift;
  99921. }
  99922. return shift;
  99923. }
  99924. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  99925. {
  99926. unsigned channel;
  99927. for(channel = 0; channel < channels; channel++)
  99928. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  99929. fifo->tail += wide_samples;
  99930. FLAC__ASSERT(fifo->tail <= fifo->size);
  99931. }
  99932. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  99933. {
  99934. unsigned channel;
  99935. unsigned sample, wide_sample;
  99936. unsigned tail = fifo->tail;
  99937. sample = input_offset * channels;
  99938. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  99939. for(channel = 0; channel < channels; channel++)
  99940. fifo->data[channel][tail] = input[sample++];
  99941. tail++;
  99942. }
  99943. fifo->tail = tail;
  99944. FLAC__ASSERT(fifo->tail <= fifo->size);
  99945. }
  99946. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  99947. {
  99948. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  99949. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  99950. (void)decoder;
  99951. if(encoder->private_->verify.needs_magic_hack) {
  99952. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  99953. *bytes = FLAC__STREAM_SYNC_LENGTH;
  99954. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  99955. encoder->private_->verify.needs_magic_hack = false;
  99956. }
  99957. else {
  99958. if(encoded_bytes == 0) {
  99959. /*
  99960. * If we get here, a FIFO underflow has occurred,
  99961. * which means there is a bug somewhere.
  99962. */
  99963. FLAC__ASSERT(0);
  99964. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  99965. }
  99966. else if(encoded_bytes < *bytes)
  99967. *bytes = encoded_bytes;
  99968. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  99969. encoder->private_->verify.output.data += *bytes;
  99970. encoder->private_->verify.output.bytes -= *bytes;
  99971. }
  99972. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  99973. }
  99974. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  99975. {
  99976. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  99977. unsigned channel;
  99978. const unsigned channels = frame->header.channels;
  99979. const unsigned blocksize = frame->header.blocksize;
  99980. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  99981. (void)decoder;
  99982. for(channel = 0; channel < channels; channel++) {
  99983. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  99984. unsigned i, sample = 0;
  99985. FLAC__int32 expect = 0, got = 0;
  99986. for(i = 0; i < blocksize; i++) {
  99987. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  99988. sample = i;
  99989. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  99990. got = (FLAC__int32)buffer[channel][i];
  99991. break;
  99992. }
  99993. }
  99994. FLAC__ASSERT(i < blocksize);
  99995. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  99996. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  99997. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  99998. encoder->private_->verify.error_stats.channel = channel;
  99999. encoder->private_->verify.error_stats.sample = sample;
  100000. encoder->private_->verify.error_stats.expected = expect;
  100001. encoder->private_->verify.error_stats.got = got;
  100002. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  100003. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  100004. }
  100005. }
  100006. /* dequeue the frame from the fifo */
  100007. encoder->private_->verify.input_fifo.tail -= blocksize;
  100008. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  100009. for(channel = 0; channel < channels; channel++)
  100010. memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail * sizeof(encoder->private_->verify.input_fifo.data[0][0]));
  100011. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  100012. }
  100013. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  100014. {
  100015. (void)decoder, (void)metadata, (void)client_data;
  100016. }
  100017. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  100018. {
  100019. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  100020. (void)decoder, (void)status;
  100021. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  100022. }
  100023. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  100024. {
  100025. (void)client_data;
  100026. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  100027. if (*bytes == 0) {
  100028. if (feof(encoder->private_->file))
  100029. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  100030. else if (ferror(encoder->private_->file))
  100031. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  100032. }
  100033. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  100034. }
  100035. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  100036. {
  100037. (void)client_data;
  100038. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  100039. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  100040. else
  100041. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  100042. }
  100043. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  100044. {
  100045. off_t offset;
  100046. (void)client_data;
  100047. offset = ftello(encoder->private_->file);
  100048. if(offset < 0) {
  100049. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  100050. }
  100051. else {
  100052. *absolute_byte_offset = (FLAC__uint64)offset;
  100053. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  100054. }
  100055. }
  100056. #ifdef FLAC__VALGRIND_TESTING
  100057. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  100058. {
  100059. size_t ret = fwrite(ptr, size, nmemb, stream);
  100060. if(!ferror(stream))
  100061. fflush(stream);
  100062. return ret;
  100063. }
  100064. #else
  100065. #define local__fwrite fwrite
  100066. #endif
  100067. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  100068. {
  100069. (void)client_data, (void)current_frame;
  100070. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  100071. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  100072. #if FLAC__HAS_OGG
  100073. /* We would like to be able to use 'samples > 0' in the
  100074. * clause here but currently because of the nature of our
  100075. * Ogg writing implementation, 'samples' is always 0 (see
  100076. * ogg_encoder_aspect.c). The downside is extra progress
  100077. * callbacks.
  100078. */
  100079. encoder->private_->is_ogg? true :
  100080. #endif
  100081. samples > 0
  100082. );
  100083. if(call_it) {
  100084. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  100085. * because at this point in the callback chain, the stats
  100086. * have not been updated. Only after we return and control
  100087. * gets back to write_frame_() are the stats updated
  100088. */
  100089. encoder->private_->progress_callback(encoder, encoder->private_->bytes_written+bytes, encoder->private_->samples_written+samples, encoder->private_->frames_written+(samples?1:0), encoder->private_->total_frames_estimate, encoder->private_->client_data);
  100090. }
  100091. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  100092. }
  100093. else
  100094. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  100095. }
  100096. /*
  100097. * This will forcibly set stdout to binary mode (for OSes that require it)
  100098. */
  100099. FILE *get_binary_stdout_(void)
  100100. {
  100101. /* if something breaks here it is probably due to the presence or
  100102. * absence of an underscore before the identifiers 'setmode',
  100103. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100104. */
  100105. #if defined _MSC_VER || defined __MINGW32__
  100106. _setmode(_fileno(stdout), _O_BINARY);
  100107. #elif defined __CYGWIN__
  100108. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100109. setmode(_fileno(stdout), _O_BINARY);
  100110. #elif defined __EMX__
  100111. setmode(fileno(stdout), O_BINARY);
  100112. #endif
  100113. return stdout;
  100114. }
  100115. #endif
  100116. /********* End of inlined file: stream_encoder.c *********/
  100117. /********* Start of inlined file: stream_encoder_framing.c *********/
  100118. /********* Start of inlined file: juce_FlacHeader.h *********/
  100119. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  100120. // tasks..
  100121. #define VERSION "1.2.1"
  100122. #define FLAC__NO_DLL 1
  100123. #ifdef _MSC_VER
  100124. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  100125. #endif
  100126. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  100127. #define FLAC__SYS_DARWIN 1
  100128. #endif
  100129. /********* End of inlined file: juce_FlacHeader.h *********/
  100130. #if JUCE_USE_FLAC
  100131. #if HAVE_CONFIG_H
  100132. # include <config.h>
  100133. #endif
  100134. #include <stdio.h>
  100135. #include <string.h> /* for strlen() */
  100136. #ifdef max
  100137. #undef max
  100138. #endif
  100139. #define max(x,y) ((x)>(y)?(x):(y))
  100140. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  100141. static FLAC__bool add_residual_partitioned_rice_(FLAC__BitWriter *bw, const FLAC__int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameters[], const unsigned raw_bits[], const unsigned partition_order, const FLAC__bool is_extended);
  100142. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  100143. {
  100144. unsigned i, j;
  100145. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  100146. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100147. return false;
  100148. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  100149. return false;
  100150. /*
  100151. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  100152. */
  100153. i = metadata->length;
  100154. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  100155. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  100156. i -= metadata->data.vorbis_comment.vendor_string.length;
  100157. i += vendor_string_length;
  100158. }
  100159. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  100160. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  100161. return false;
  100162. switch(metadata->type) {
  100163. case FLAC__METADATA_TYPE_STREAMINFO:
  100164. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  100165. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  100166. return false;
  100167. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  100168. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100169. return false;
  100170. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  100171. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100172. return false;
  100173. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  100174. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100175. return false;
  100176. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  100177. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100178. return false;
  100179. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  100180. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  100181. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100182. return false;
  100183. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  100184. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  100185. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100186. return false;
  100187. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  100188. return false;
  100189. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  100190. return false;
  100191. break;
  100192. case FLAC__METADATA_TYPE_PADDING:
  100193. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  100194. return false;
  100195. break;
  100196. case FLAC__METADATA_TYPE_APPLICATION:
  100197. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  100198. return false;
  100199. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  100200. return false;
  100201. break;
  100202. case FLAC__METADATA_TYPE_SEEKTABLE:
  100203. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  100204. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100205. return false;
  100206. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100207. return false;
  100208. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100209. return false;
  100210. }
  100211. break;
  100212. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100213. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  100214. return false;
  100215. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  100216. return false;
  100217. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  100218. return false;
  100219. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  100220. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  100221. return false;
  100222. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  100223. return false;
  100224. }
  100225. break;
  100226. case FLAC__METADATA_TYPE_CUESHEET:
  100227. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100228. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.cue_sheet.media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8))
  100229. return false;
  100230. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100231. return false;
  100232. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100233. return false;
  100234. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100235. return false;
  100236. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100237. return false;
  100238. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  100239. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  100240. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100241. return false;
  100242. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100243. return false;
  100244. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100245. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100246. return false;
  100247. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100248. return false;
  100249. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100250. return false;
  100251. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100252. return false;
  100253. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100254. return false;
  100255. for(j = 0; j < track->num_indices; j++) {
  100256. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  100257. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100258. return false;
  100259. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100260. return false;
  100261. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100262. return false;
  100263. }
  100264. }
  100265. break;
  100266. case FLAC__METADATA_TYPE_PICTURE:
  100267. {
  100268. size_t len;
  100269. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100270. return false;
  100271. len = strlen(metadata->data.picture.mime_type);
  100272. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100273. return false;
  100274. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  100275. return false;
  100276. len = strlen((const char *)metadata->data.picture.description);
  100277. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100278. return false;
  100279. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  100280. return false;
  100281. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100282. return false;
  100283. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100284. return false;
  100285. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100286. return false;
  100287. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100288. return false;
  100289. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100290. return false;
  100291. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  100292. return false;
  100293. }
  100294. break;
  100295. default:
  100296. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  100297. return false;
  100298. break;
  100299. }
  100300. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  100301. return true;
  100302. }
  100303. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  100304. {
  100305. unsigned u, blocksize_hint, sample_rate_hint;
  100306. FLAC__byte crc;
  100307. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  100308. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  100309. return false;
  100310. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  100311. return false;
  100312. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  100313. return false;
  100314. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  100315. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  100316. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  100317. blocksize_hint = 0;
  100318. switch(header->blocksize) {
  100319. case 192: u = 1; break;
  100320. case 576: u = 2; break;
  100321. case 1152: u = 3; break;
  100322. case 2304: u = 4; break;
  100323. case 4608: u = 5; break;
  100324. case 256: u = 8; break;
  100325. case 512: u = 9; break;
  100326. case 1024: u = 10; break;
  100327. case 2048: u = 11; break;
  100328. case 4096: u = 12; break;
  100329. case 8192: u = 13; break;
  100330. case 16384: u = 14; break;
  100331. case 32768: u = 15; break;
  100332. default:
  100333. if(header->blocksize <= 0x100)
  100334. blocksize_hint = u = 6;
  100335. else
  100336. blocksize_hint = u = 7;
  100337. break;
  100338. }
  100339. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  100340. return false;
  100341. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  100342. sample_rate_hint = 0;
  100343. switch(header->sample_rate) {
  100344. case 88200: u = 1; break;
  100345. case 176400: u = 2; break;
  100346. case 192000: u = 3; break;
  100347. case 8000: u = 4; break;
  100348. case 16000: u = 5; break;
  100349. case 22050: u = 6; break;
  100350. case 24000: u = 7; break;
  100351. case 32000: u = 8; break;
  100352. case 44100: u = 9; break;
  100353. case 48000: u = 10; break;
  100354. case 96000: u = 11; break;
  100355. default:
  100356. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  100357. sample_rate_hint = u = 12;
  100358. else if(header->sample_rate % 10 == 0)
  100359. sample_rate_hint = u = 14;
  100360. else if(header->sample_rate <= 0xffff)
  100361. sample_rate_hint = u = 13;
  100362. else
  100363. u = 0;
  100364. break;
  100365. }
  100366. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  100367. return false;
  100368. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  100369. switch(header->channel_assignment) {
  100370. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100371. u = header->channels - 1;
  100372. break;
  100373. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100374. FLAC__ASSERT(header->channels == 2);
  100375. u = 8;
  100376. break;
  100377. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100378. FLAC__ASSERT(header->channels == 2);
  100379. u = 9;
  100380. break;
  100381. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100382. FLAC__ASSERT(header->channels == 2);
  100383. u = 10;
  100384. break;
  100385. default:
  100386. FLAC__ASSERT(0);
  100387. }
  100388. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  100389. return false;
  100390. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  100391. switch(header->bits_per_sample) {
  100392. case 8 : u = 1; break;
  100393. case 12: u = 2; break;
  100394. case 16: u = 4; break;
  100395. case 20: u = 5; break;
  100396. case 24: u = 6; break;
  100397. default: u = 0; break;
  100398. }
  100399. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  100400. return false;
  100401. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  100402. return false;
  100403. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  100404. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  100405. return false;
  100406. }
  100407. else {
  100408. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  100409. return false;
  100410. }
  100411. if(blocksize_hint)
  100412. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  100413. return false;
  100414. switch(sample_rate_hint) {
  100415. case 12:
  100416. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  100417. return false;
  100418. break;
  100419. case 13:
  100420. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  100421. return false;
  100422. break;
  100423. case 14:
  100424. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  100425. return false;
  100426. break;
  100427. }
  100428. /* write the CRC */
  100429. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  100430. return false;
  100431. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  100432. return false;
  100433. return true;
  100434. }
  100435. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  100436. {
  100437. FLAC__bool ok;
  100438. ok =
  100439. FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN) &&
  100440. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  100441. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  100442. ;
  100443. return ok;
  100444. }
  100445. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  100446. {
  100447. unsigned i;
  100448. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK | (subframe->order<<1) | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
  100449. return false;
  100450. if(wasted_bits)
  100451. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  100452. return false;
  100453. for(i = 0; i < subframe->order; i++)
  100454. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  100455. return false;
  100456. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  100457. return false;
  100458. switch(subframe->entropy_coding_method.type) {
  100459. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100460. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100461. if(!add_residual_partitioned_rice_(
  100462. bw,
  100463. subframe->residual,
  100464. residual_samples,
  100465. subframe->order,
  100466. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  100467. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  100468. subframe->entropy_coding_method.data.partitioned_rice.order,
  100469. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  100470. ))
  100471. return false;
  100472. break;
  100473. default:
  100474. FLAC__ASSERT(0);
  100475. }
  100476. return true;
  100477. }
  100478. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  100479. {
  100480. unsigned i;
  100481. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK | ((subframe->order-1)<<1) | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
  100482. return false;
  100483. if(wasted_bits)
  100484. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  100485. return false;
  100486. for(i = 0; i < subframe->order; i++)
  100487. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  100488. return false;
  100489. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  100490. return false;
  100491. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  100492. return false;
  100493. for(i = 0; i < subframe->order; i++)
  100494. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  100495. return false;
  100496. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  100497. return false;
  100498. switch(subframe->entropy_coding_method.type) {
  100499. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100500. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100501. if(!add_residual_partitioned_rice_(
  100502. bw,
  100503. subframe->residual,
  100504. residual_samples,
  100505. subframe->order,
  100506. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  100507. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  100508. subframe->entropy_coding_method.data.partitioned_rice.order,
  100509. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  100510. ))
  100511. return false;
  100512. break;
  100513. default:
  100514. FLAC__ASSERT(0);
  100515. }
  100516. return true;
  100517. }
  100518. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  100519. {
  100520. unsigned i;
  100521. const FLAC__int32 *signal = subframe->data;
  100522. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
  100523. return false;
  100524. if(wasted_bits)
  100525. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  100526. return false;
  100527. for(i = 0; i < samples; i++)
  100528. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  100529. return false;
  100530. return true;
  100531. }
  100532. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  100533. {
  100534. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100535. return false;
  100536. switch(method->type) {
  100537. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100538. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100539. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100540. return false;
  100541. break;
  100542. default:
  100543. FLAC__ASSERT(0);
  100544. }
  100545. return true;
  100546. }
  100547. FLAC__bool add_residual_partitioned_rice_(FLAC__BitWriter *bw, const FLAC__int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameters[], const unsigned raw_bits[], const unsigned partition_order, const FLAC__bool is_extended)
  100548. {
  100549. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  100550. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  100551. if(partition_order == 0) {
  100552. unsigned i;
  100553. if(raw_bits[0] == 0) {
  100554. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  100555. return false;
  100556. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  100557. return false;
  100558. }
  100559. else {
  100560. FLAC__ASSERT(rice_parameters[0] == 0);
  100561. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  100562. return false;
  100563. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  100564. return false;
  100565. for(i = 0; i < residual_samples; i++) {
  100566. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  100567. return false;
  100568. }
  100569. }
  100570. return true;
  100571. }
  100572. else {
  100573. unsigned i, j, k = 0, k_last = 0;
  100574. unsigned partition_samples;
  100575. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  100576. for(i = 0; i < (1u<<partition_order); i++) {
  100577. partition_samples = default_partition_samples;
  100578. if(i == 0)
  100579. partition_samples -= predictor_order;
  100580. k += partition_samples;
  100581. if(raw_bits[i] == 0) {
  100582. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  100583. return false;
  100584. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  100585. return false;
  100586. }
  100587. else {
  100588. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  100589. return false;
  100590. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  100591. return false;
  100592. for(j = k_last; j < k; j++) {
  100593. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  100594. return false;
  100595. }
  100596. }
  100597. k_last = k;
  100598. }
  100599. return true;
  100600. }
  100601. }
  100602. #endif
  100603. /********* End of inlined file: stream_encoder_framing.c *********/
  100604. /********* Start of inlined file: window_flac.c *********/
  100605. /********* Start of inlined file: juce_FlacHeader.h *********/
  100606. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  100607. // tasks..
  100608. #define VERSION "1.2.1"
  100609. #define FLAC__NO_DLL 1
  100610. #ifdef _MSC_VER
  100611. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  100612. #endif
  100613. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  100614. #define FLAC__SYS_DARWIN 1
  100615. #endif
  100616. /********* End of inlined file: juce_FlacHeader.h *********/
  100617. #if JUCE_USE_FLAC
  100618. #if HAVE_CONFIG_H
  100619. # include <config.h>
  100620. #endif
  100621. #include <math.h>
  100622. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100623. #ifndef M_PI
  100624. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  100625. #define M_PI 3.14159265358979323846
  100626. #endif
  100627. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  100628. {
  100629. const FLAC__int32 N = L - 1;
  100630. FLAC__int32 n;
  100631. if (L & 1) {
  100632. for (n = 0; n <= N/2; n++)
  100633. window[n] = 2.0f * n / (float)N;
  100634. for (; n <= N; n++)
  100635. window[n] = 2.0f - 2.0f * n / (float)N;
  100636. }
  100637. else {
  100638. for (n = 0; n <= L/2-1; n++)
  100639. window[n] = 2.0f * n / (float)N;
  100640. for (; n <= N; n++)
  100641. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  100642. }
  100643. }
  100644. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  100645. {
  100646. const FLAC__int32 N = L - 1;
  100647. FLAC__int32 n;
  100648. for (n = 0; n < L; n++)
  100649. window[n] = (FLAC__real)(0.62f - 0.48f * fabs((float)n/(float)N+0.5f) + 0.38f * cos(2.0f * M_PI * ((float)n/(float)N+0.5f)));
  100650. }
  100651. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  100652. {
  100653. const FLAC__int32 N = L - 1;
  100654. FLAC__int32 n;
  100655. for (n = 0; n < L; n++)
  100656. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  100657. }
  100658. /* 4-term -92dB side-lobe */
  100659. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  100660. {
  100661. const FLAC__int32 N = L - 1;
  100662. FLAC__int32 n;
  100663. for (n = 0; n <= N; n++)
  100664. window[n] = (FLAC__real)(0.35875f - 0.48829f * cos(2.0f * M_PI * n / N) + 0.14128f * cos(4.0f * M_PI * n / N) - 0.01168f * cos(6.0f * M_PI * n / N));
  100665. }
  100666. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  100667. {
  100668. const FLAC__int32 N = L - 1;
  100669. const double N2 = (double)N / 2.;
  100670. FLAC__int32 n;
  100671. for (n = 0; n <= N; n++) {
  100672. double k = ((double)n - N2) / N2;
  100673. k = 1.0f - k * k;
  100674. window[n] = (FLAC__real)(k * k);
  100675. }
  100676. }
  100677. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  100678. {
  100679. const FLAC__int32 N = L - 1;
  100680. FLAC__int32 n;
  100681. for (n = 0; n < L; n++)
  100682. window[n] = (FLAC__real)(1.0f - 1.93f * cos(2.0f * M_PI * n / N) + 1.29f * cos(4.0f * M_PI * n / N) - 0.388f * cos(6.0f * M_PI * n / N) + 0.0322f * cos(8.0f * M_PI * n / N));
  100683. }
  100684. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  100685. {
  100686. const FLAC__int32 N = L - 1;
  100687. const double N2 = (double)N / 2.;
  100688. FLAC__int32 n;
  100689. for (n = 0; n <= N; n++) {
  100690. const double k = ((double)n - N2) / (stddev * N2);
  100691. window[n] = (FLAC__real)exp(-0.5f * k * k);
  100692. }
  100693. }
  100694. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  100695. {
  100696. const FLAC__int32 N = L - 1;
  100697. FLAC__int32 n;
  100698. for (n = 0; n < L; n++)
  100699. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  100700. }
  100701. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  100702. {
  100703. const FLAC__int32 N = L - 1;
  100704. FLAC__int32 n;
  100705. for (n = 0; n < L; n++)
  100706. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  100707. }
  100708. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  100709. {
  100710. const FLAC__int32 N = L - 1;
  100711. FLAC__int32 n;
  100712. for (n = 0; n < L; n++)
  100713. window[n] = (FLAC__real)(0.402f - 0.498f * cos(2.0f * M_PI * n / N) + 0.098f * cos(4.0f * M_PI * n / N) - 0.001f * cos(6.0f * M_PI * n / N));
  100714. }
  100715. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  100716. {
  100717. const FLAC__int32 N = L - 1;
  100718. FLAC__int32 n;
  100719. for (n = 0; n < L; n++)
  100720. window[n] = (FLAC__real)(0.3635819f - 0.4891775f*cos(2.0f*M_PI*n/N) + 0.1365995f*cos(4.0f*M_PI*n/N) - 0.0106411f*cos(6.0f*M_PI*n/N));
  100721. }
  100722. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  100723. {
  100724. FLAC__int32 n;
  100725. for (n = 0; n < L; n++)
  100726. window[n] = 1.0f;
  100727. }
  100728. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  100729. {
  100730. FLAC__int32 n;
  100731. if (L & 1) {
  100732. for (n = 1; n <= L+1/2; n++)
  100733. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  100734. for (; n <= L; n++)
  100735. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  100736. }
  100737. else {
  100738. for (n = 1; n <= L/2; n++)
  100739. window[n-1] = 2.0f * n / (float)L;
  100740. for (; n <= L; n++)
  100741. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  100742. }
  100743. }
  100744. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  100745. {
  100746. if (p <= 0.0)
  100747. FLAC__window_rectangle(window, L);
  100748. else if (p >= 1.0)
  100749. FLAC__window_hann(window, L);
  100750. else {
  100751. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  100752. FLAC__int32 n;
  100753. /* start with rectangle... */
  100754. FLAC__window_rectangle(window, L);
  100755. /* ...replace ends with hann */
  100756. if (Np > 0) {
  100757. for (n = 0; n <= Np; n++) {
  100758. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  100759. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  100760. }
  100761. }
  100762. }
  100763. }
  100764. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  100765. {
  100766. const FLAC__int32 N = L - 1;
  100767. const double N2 = (double)N / 2.;
  100768. FLAC__int32 n;
  100769. for (n = 0; n <= N; n++) {
  100770. const double k = ((double)n - N2) / N2;
  100771. window[n] = (FLAC__real)(1.0f - k * k);
  100772. }
  100773. }
  100774. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  100775. #endif
  100776. /********* End of inlined file: window_flac.c *********/
  100777. }
  100778. #ifdef _MSC_VER
  100779. #pragma warning (pop)
  100780. #endif
  100781. BEGIN_JUCE_NAMESPACE
  100782. using namespace FlacNamespace;
  100783. #define flacFormatName TRANS("FLAC file")
  100784. static const tchar* const flacExtensions[] = { T(".flac"), 0 };
  100785. class FlacReader : public AudioFormatReader
  100786. {
  100787. FLAC__StreamDecoder* decoder;
  100788. AudioSampleBuffer reservoir;
  100789. int reservoirStart, samplesInReservoir;
  100790. bool ok, scanningForLength;
  100791. public:
  100792. FlacReader (InputStream* const in)
  100793. : AudioFormatReader (in, flacFormatName),
  100794. reservoir (2, 0),
  100795. reservoirStart (0),
  100796. samplesInReservoir (0),
  100797. scanningForLength (false)
  100798. {
  100799. using namespace FlacNamespace;
  100800. lengthInSamples = 0;
  100801. decoder = FLAC__stream_decoder_new();
  100802. ok = FLAC__stream_decoder_init_stream (decoder,
  100803. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  100804. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  100805. (void*) this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  100806. if (ok)
  100807. {
  100808. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  100809. if (lengthInSamples == 0 && sampleRate > 0)
  100810. {
  100811. // the length hasn't been stored in the metadata, so we'll need to
  100812. // work it out the length the hard way, by scanning the whole file..
  100813. scanningForLength = true;
  100814. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  100815. scanningForLength = false;
  100816. const int64 tempLength = lengthInSamples;
  100817. FLAC__stream_decoder_reset (decoder);
  100818. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  100819. lengthInSamples = tempLength;
  100820. }
  100821. }
  100822. }
  100823. ~FlacReader()
  100824. {
  100825. FLAC__stream_decoder_delete (decoder);
  100826. }
  100827. void useMetadata (const FLAC__StreamMetadata_StreamInfo& info)
  100828. {
  100829. sampleRate = info.sample_rate;
  100830. bitsPerSample = info.bits_per_sample;
  100831. lengthInSamples = (unsigned int) info.total_samples;
  100832. numChannels = info.channels;
  100833. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  100834. }
  100835. // returns the number of samples read
  100836. bool read (int** destSamples,
  100837. int64 startSampleInFile,
  100838. int numSamples)
  100839. {
  100840. using namespace FlacNamespace;
  100841. if (! ok)
  100842. return false;
  100843. int offset = 0;
  100844. if (startSampleInFile < 0)
  100845. {
  100846. const int num = (int) jmin ((int64) numSamples, -startSampleInFile);
  100847. int n = 0;
  100848. while (destSamples[n] != 0)
  100849. {
  100850. zeromem (destSamples[n], sizeof (int) * num);
  100851. ++n;
  100852. }
  100853. offset += num;
  100854. startSampleInFile += num;
  100855. numSamples -= num;
  100856. }
  100857. while (numSamples > 0)
  100858. {
  100859. if (startSampleInFile >= reservoirStart
  100860. && startSampleInFile < reservoirStart + samplesInReservoir)
  100861. {
  100862. const int num = (int) jmin ((int64) numSamples,
  100863. reservoirStart + samplesInReservoir - startSampleInFile);
  100864. jassert (num > 0);
  100865. int n = 0;
  100866. while (destSamples[n] != 0)
  100867. {
  100868. memcpy (destSamples[n] + offset,
  100869. reservoir.getSampleData (n, (int) (startSampleInFile - reservoirStart)),
  100870. sizeof (int) * num);
  100871. ++n;
  100872. }
  100873. offset += num;
  100874. startSampleInFile += num;
  100875. numSamples -= num;
  100876. }
  100877. else
  100878. {
  100879. if (startSampleInFile < reservoirStart
  100880. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  100881. {
  100882. if (startSampleInFile >= (int) lengthInSamples)
  100883. {
  100884. samplesInReservoir = 0;
  100885. break;
  100886. }
  100887. // had some problems with flac crashing if the read pos is aligned more
  100888. // accurately than this. Probably fixed in newer versions of the library, though.
  100889. reservoirStart = (int) (startSampleInFile & ~511);
  100890. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  100891. }
  100892. else
  100893. {
  100894. reservoirStart += samplesInReservoir;
  100895. }
  100896. samplesInReservoir = 0;
  100897. FLAC__stream_decoder_process_single (decoder);
  100898. if (samplesInReservoir == 0)
  100899. break;
  100900. }
  100901. }
  100902. if (numSamples > 0)
  100903. {
  100904. int n = 0;
  100905. while (destSamples[n] != 0)
  100906. {
  100907. zeromem (destSamples[n] + offset, sizeof (int) * numSamples);
  100908. ++n;
  100909. }
  100910. }
  100911. return true;
  100912. }
  100913. void useSamples (const FLAC__int32* const buffer[], int numSamples)
  100914. {
  100915. if (scanningForLength)
  100916. {
  100917. lengthInSamples += numSamples;
  100918. }
  100919. else
  100920. {
  100921. if (numSamples > reservoir.getNumSamples())
  100922. reservoir.setSize (numChannels, numSamples, false, false, true);
  100923. const int bitsToShift = 32 - bitsPerSample;
  100924. for (int i = 0; i < (int) numChannels; ++i)
  100925. {
  100926. const FLAC__int32* src = buffer[i];
  100927. int n = i;
  100928. while (src == 0 && n > 0)
  100929. src = buffer [--n];
  100930. if (src != 0)
  100931. {
  100932. int* dest = (int*) reservoir.getSampleData(i);
  100933. for (int j = 0; j < numSamples; ++j)
  100934. dest[j] = src[j] << bitsToShift;
  100935. }
  100936. }
  100937. samplesInReservoir = numSamples;
  100938. }
  100939. }
  100940. static FLAC__StreamDecoderReadStatus readCallback_ (const FLAC__StreamDecoder*, FLAC__byte buffer[], size_t* bytes, void* client_data)
  100941. {
  100942. *bytes = (unsigned int) ((const FlacReader*) client_data)->input->read (buffer, (int) *bytes);
  100943. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100944. }
  100945. static FLAC__StreamDecoderSeekStatus seekCallback_ (const FLAC__StreamDecoder*, FLAC__uint64 absolute_byte_offset, void* client_data)
  100946. {
  100947. ((const FlacReader*) client_data)->input->setPosition ((int) absolute_byte_offset);
  100948. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  100949. }
  100950. static FLAC__StreamDecoderTellStatus tellCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* absolute_byte_offset, void* client_data)
  100951. {
  100952. *absolute_byte_offset = ((const FlacReader*) client_data)->input->getPosition();
  100953. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  100954. }
  100955. static FLAC__StreamDecoderLengthStatus lengthCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* stream_length, void* client_data)
  100956. {
  100957. *stream_length = ((const FlacReader*) client_data)->input->getTotalLength();
  100958. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  100959. }
  100960. static FLAC__bool eofCallback_ (const FLAC__StreamDecoder*, void* client_data)
  100961. {
  100962. return ((const FlacReader*) client_data)->input->isExhausted();
  100963. }
  100964. static FLAC__StreamDecoderWriteStatus writeCallback_ (const FLAC__StreamDecoder*,
  100965. const FLAC__Frame* frame,
  100966. const FLAC__int32* const buffer[],
  100967. void* client_data)
  100968. {
  100969. ((FlacReader*) client_data)->useSamples (buffer, frame->header.blocksize);
  100970. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  100971. }
  100972. static void metadataCallback_ (const FLAC__StreamDecoder*,
  100973. const FLAC__StreamMetadata* metadata,
  100974. void* client_data)
  100975. {
  100976. ((FlacReader*) client_data)->useMetadata (metadata->data.stream_info);
  100977. }
  100978. static void errorCallback_ (const FLAC__StreamDecoder*, FLAC__StreamDecoderErrorStatus, void*)
  100979. {
  100980. }
  100981. juce_UseDebuggingNewOperator
  100982. };
  100983. class FlacWriter : public AudioFormatWriter
  100984. {
  100985. FLAC__StreamEncoder* encoder;
  100986. MemoryBlock temp;
  100987. public:
  100988. bool ok;
  100989. FlacWriter (OutputStream* const out,
  100990. const double sampleRate,
  100991. const int numChannels,
  100992. const int bitsPerSample_)
  100993. : AudioFormatWriter (out, flacFormatName,
  100994. sampleRate,
  100995. numChannels,
  100996. bitsPerSample_)
  100997. {
  100998. using namespace FlacNamespace;
  100999. encoder = FLAC__stream_encoder_new();
  101000. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  101001. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  101002. FLAC__stream_encoder_set_channels (encoder, numChannels);
  101003. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin (24, bitsPerSample));
  101004. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  101005. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  101006. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  101007. ok = FLAC__stream_encoder_init_stream (encoder,
  101008. encodeWriteCallback, encodeSeekCallback,
  101009. encodeTellCallback, encodeMetadataCallback,
  101010. (void*) this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  101011. }
  101012. ~FlacWriter()
  101013. {
  101014. if (ok)
  101015. {
  101016. FLAC__stream_encoder_finish (encoder);
  101017. output->flush();
  101018. }
  101019. else
  101020. {
  101021. output = 0; // to stop the base class deleting this, as it needs to be returned
  101022. // to the caller of createWriter()
  101023. }
  101024. FLAC__stream_encoder_delete (encoder);
  101025. }
  101026. bool write (const int** samplesToWrite, int numSamples)
  101027. {
  101028. if (! ok)
  101029. return false;
  101030. int* buf[3];
  101031. const int bitsToShift = 32 - bitsPerSample;
  101032. if (bitsToShift > 0)
  101033. {
  101034. const int numChannels = (samplesToWrite[1] == 0) ? 1 : 2;
  101035. temp.setSize (sizeof (int) * numSamples * numChannels);
  101036. buf[0] = (int*) temp.getData();
  101037. buf[1] = buf[0] + numSamples;
  101038. buf[2] = 0;
  101039. for (int i = numChannels; --i >= 0;)
  101040. {
  101041. if (samplesToWrite[i] != 0)
  101042. {
  101043. for (int j = 0; j < numSamples; ++j)
  101044. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  101045. }
  101046. }
  101047. samplesToWrite = (const int**) buf;
  101048. }
  101049. return FLAC__stream_encoder_process (encoder,
  101050. (const FLAC__int32**) samplesToWrite,
  101051. numSamples) != 0;
  101052. }
  101053. bool writeData (const void* const data, const int size) const
  101054. {
  101055. return output->write (data, size);
  101056. }
  101057. static void packUint32 (FLAC__uint32 val, FLAC__byte* b, const int bytes)
  101058. {
  101059. b += bytes;
  101060. for (int i = 0; i < bytes; ++i)
  101061. {
  101062. *(--b) = (FLAC__byte) (val & 0xff);
  101063. val >>= 8;
  101064. }
  101065. }
  101066. void writeMetaData (const FLAC__StreamMetadata* metadata)
  101067. {
  101068. using namespace FlacNamespace;
  101069. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  101070. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  101071. const unsigned int channelsMinus1 = info.channels - 1;
  101072. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  101073. packUint32 (info.min_blocksize, buffer, 2);
  101074. packUint32 (info.max_blocksize, buffer + 2, 2);
  101075. packUint32 (info.min_framesize, buffer + 4, 3);
  101076. packUint32 (info.max_framesize, buffer + 7, 3);
  101077. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  101078. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  101079. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  101080. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  101081. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  101082. memcpy (buffer + 18, info.md5sum, 16);
  101083. const bool ok = output->setPosition (4);
  101084. (void) ok;
  101085. // if this fails, you've given it an output stream that can't seek! It needs
  101086. // to be able to seek back to write the header
  101087. jassert (ok);
  101088. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  101089. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  101090. }
  101091. static FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FLAC__StreamEncoder*,
  101092. const FLAC__byte buffer[],
  101093. size_t bytes,
  101094. unsigned int /*samples*/,
  101095. unsigned int /*current_frame*/,
  101096. void* client_data)
  101097. {
  101098. using namespace FlacNamespace;
  101099. return ((FlacWriter*) client_data)->writeData (buffer, (int) bytes)
  101100. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  101101. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  101102. }
  101103. static FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FLAC__StreamEncoder*, FLAC__uint64, void*)
  101104. {
  101105. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  101106. }
  101107. static FLAC__StreamEncoderTellStatus encodeTellCallback (const FLAC__StreamEncoder*, FLAC__uint64*, void*)
  101108. {
  101109. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  101110. }
  101111. static void encodeMetadataCallback (const FLAC__StreamEncoder*,
  101112. const FLAC__StreamMetadata* metadata,
  101113. void* client_data)
  101114. {
  101115. ((FlacWriter*) client_data)->writeMetaData (metadata);
  101116. }
  101117. juce_UseDebuggingNewOperator
  101118. };
  101119. FlacAudioFormat::FlacAudioFormat()
  101120. : AudioFormat (flacFormatName, (const tchar**) flacExtensions)
  101121. {
  101122. }
  101123. FlacAudioFormat::~FlacAudioFormat()
  101124. {
  101125. }
  101126. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  101127. {
  101128. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  101129. return Array <int> (rates);
  101130. }
  101131. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  101132. {
  101133. const int depths[] = { 16, 24, 0 };
  101134. return Array <int> (depths);
  101135. }
  101136. bool FlacAudioFormat::canDoStereo()
  101137. {
  101138. return true;
  101139. }
  101140. bool FlacAudioFormat::canDoMono()
  101141. {
  101142. return true;
  101143. }
  101144. bool FlacAudioFormat::isCompressed()
  101145. {
  101146. return true;
  101147. }
  101148. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  101149. const bool deleteStreamIfOpeningFails)
  101150. {
  101151. FlacReader* r = new FlacReader (in);
  101152. if (r->sampleRate == 0)
  101153. {
  101154. if (! deleteStreamIfOpeningFails)
  101155. r->input = 0;
  101156. deleteAndZero (r);
  101157. }
  101158. return r;
  101159. }
  101160. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  101161. double sampleRate,
  101162. unsigned int numberOfChannels,
  101163. int bitsPerSample,
  101164. const StringPairArray& /*metadataValues*/,
  101165. int /*qualityOptionIndex*/)
  101166. {
  101167. if (getPossibleBitDepths().contains (bitsPerSample))
  101168. {
  101169. FlacWriter* w = new FlacWriter (out,
  101170. sampleRate,
  101171. numberOfChannels,
  101172. bitsPerSample);
  101173. if (! w->ok)
  101174. deleteAndZero (w);
  101175. return w;
  101176. }
  101177. return 0;
  101178. }
  101179. END_JUCE_NAMESPACE
  101180. #endif
  101181. /********* End of inlined file: juce_FlacAudioFormat.cpp *********/
  101182. /********* Start of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  101183. #if JUCE_USE_OGGVORBIS
  101184. #if JUCE_MAC
  101185. #define __MACOSX__ 1
  101186. #endif
  101187. namespace OggVorbisNamespace
  101188. {
  101189. /********* Start of inlined file: vorbisenc.h *********/
  101190. #ifndef _OV_ENC_H_
  101191. #define _OV_ENC_H_
  101192. #ifdef __cplusplus
  101193. extern "C"
  101194. {
  101195. #endif /* __cplusplus */
  101196. /********* Start of inlined file: codec.h *********/
  101197. #ifndef _vorbis_codec_h_
  101198. #define _vorbis_codec_h_
  101199. #ifdef __cplusplus
  101200. extern "C"
  101201. {
  101202. #endif /* __cplusplus */
  101203. /********* Start of inlined file: ogg.h *********/
  101204. #ifndef _OGG_H
  101205. #define _OGG_H
  101206. #ifdef __cplusplus
  101207. extern "C" {
  101208. #endif
  101209. /********* Start of inlined file: os_types.h *********/
  101210. #ifndef _OS_TYPES_H
  101211. #define _OS_TYPES_H
  101212. /* make it easy on the folks that want to compile the libs with a
  101213. different malloc than stdlib */
  101214. #define _ogg_malloc malloc
  101215. #define _ogg_calloc calloc
  101216. #define _ogg_realloc realloc
  101217. #define _ogg_free free
  101218. #if defined(_WIN32)
  101219. # if defined(__CYGWIN__)
  101220. # include <_G_config.h>
  101221. typedef _G_int64_t ogg_int64_t;
  101222. typedef _G_int32_t ogg_int32_t;
  101223. typedef _G_uint32_t ogg_uint32_t;
  101224. typedef _G_int16_t ogg_int16_t;
  101225. typedef _G_uint16_t ogg_uint16_t;
  101226. # elif defined(__MINGW32__)
  101227. typedef short ogg_int16_t;
  101228. typedef unsigned short ogg_uint16_t;
  101229. typedef int ogg_int32_t;
  101230. typedef unsigned int ogg_uint32_t;
  101231. typedef long long ogg_int64_t;
  101232. typedef unsigned long long ogg_uint64_t;
  101233. # elif defined(__MWERKS__)
  101234. typedef long long ogg_int64_t;
  101235. typedef int ogg_int32_t;
  101236. typedef unsigned int ogg_uint32_t;
  101237. typedef short ogg_int16_t;
  101238. typedef unsigned short ogg_uint16_t;
  101239. # else
  101240. /* MSVC/Borland */
  101241. typedef __int64 ogg_int64_t;
  101242. typedef __int32 ogg_int32_t;
  101243. typedef unsigned __int32 ogg_uint32_t;
  101244. typedef __int16 ogg_int16_t;
  101245. typedef unsigned __int16 ogg_uint16_t;
  101246. # endif
  101247. #elif defined(__MACOS__)
  101248. # include <sys/types.h>
  101249. typedef SInt16 ogg_int16_t;
  101250. typedef UInt16 ogg_uint16_t;
  101251. typedef SInt32 ogg_int32_t;
  101252. typedef UInt32 ogg_uint32_t;
  101253. typedef SInt64 ogg_int64_t;
  101254. #elif defined(__MACOSX__) /* MacOS X Framework build */
  101255. # include <sys/types.h>
  101256. typedef int16_t ogg_int16_t;
  101257. typedef u_int16_t ogg_uint16_t;
  101258. typedef int32_t ogg_int32_t;
  101259. typedef u_int32_t ogg_uint32_t;
  101260. typedef int64_t ogg_int64_t;
  101261. #elif defined(__BEOS__)
  101262. /* Be */
  101263. # include <inttypes.h>
  101264. typedef int16_t ogg_int16_t;
  101265. typedef u_int16_t ogg_uint16_t;
  101266. typedef int32_t ogg_int32_t;
  101267. typedef u_int32_t ogg_uint32_t;
  101268. typedef int64_t ogg_int64_t;
  101269. #elif defined (__EMX__)
  101270. /* OS/2 GCC */
  101271. typedef short ogg_int16_t;
  101272. typedef unsigned short ogg_uint16_t;
  101273. typedef int ogg_int32_t;
  101274. typedef unsigned int ogg_uint32_t;
  101275. typedef long long ogg_int64_t;
  101276. #elif defined (DJGPP)
  101277. /* DJGPP */
  101278. typedef short ogg_int16_t;
  101279. typedef int ogg_int32_t;
  101280. typedef unsigned int ogg_uint32_t;
  101281. typedef long long ogg_int64_t;
  101282. #elif defined(R5900)
  101283. /* PS2 EE */
  101284. typedef long ogg_int64_t;
  101285. typedef int ogg_int32_t;
  101286. typedef unsigned ogg_uint32_t;
  101287. typedef short ogg_int16_t;
  101288. #elif defined(__SYMBIAN32__)
  101289. /* Symbian GCC */
  101290. typedef signed short ogg_int16_t;
  101291. typedef unsigned short ogg_uint16_t;
  101292. typedef signed int ogg_int32_t;
  101293. typedef unsigned int ogg_uint32_t;
  101294. typedef long long int ogg_int64_t;
  101295. #else
  101296. # include <sys/types.h>
  101297. /********* Start of inlined file: config_types.h *********/
  101298. #ifndef __CONFIG_TYPES_H__
  101299. #define __CONFIG_TYPES_H__
  101300. typedef int16_t ogg_int16_t;
  101301. typedef unsigned short ogg_uint16_t;
  101302. typedef int32_t ogg_int32_t;
  101303. typedef unsigned int ogg_uint32_t;
  101304. typedef int64_t ogg_int64_t;
  101305. #endif
  101306. /********* End of inlined file: config_types.h *********/
  101307. #endif
  101308. #endif /* _OS_TYPES_H */
  101309. /********* End of inlined file: os_types.h *********/
  101310. typedef struct {
  101311. long endbyte;
  101312. int endbit;
  101313. unsigned char *buffer;
  101314. unsigned char *ptr;
  101315. long storage;
  101316. } oggpack_buffer;
  101317. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  101318. typedef struct {
  101319. unsigned char *header;
  101320. long header_len;
  101321. unsigned char *body;
  101322. long body_len;
  101323. } ogg_page;
  101324. ogg_uint32_t bitreverse(ogg_uint32_t x){
  101325. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  101326. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  101327. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  101328. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  101329. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  101330. }
  101331. /* ogg_stream_state contains the current encode/decode state of a logical
  101332. Ogg bitstream **********************************************************/
  101333. typedef struct {
  101334. unsigned char *body_data; /* bytes from packet bodies */
  101335. long body_storage; /* storage elements allocated */
  101336. long body_fill; /* elements stored; fill mark */
  101337. long body_returned; /* elements of fill returned */
  101338. int *lacing_vals; /* The values that will go to the segment table */
  101339. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  101340. this way, but it is simple coupled to the
  101341. lacing fifo */
  101342. long lacing_storage;
  101343. long lacing_fill;
  101344. long lacing_packet;
  101345. long lacing_returned;
  101346. unsigned char header[282]; /* working space for header encode */
  101347. int header_fill;
  101348. int e_o_s; /* set when we have buffered the last packet in the
  101349. logical bitstream */
  101350. int b_o_s; /* set after we've written the initial page
  101351. of a logical bitstream */
  101352. long serialno;
  101353. long pageno;
  101354. ogg_int64_t packetno; /* sequence number for decode; the framing
  101355. knows where there's a hole in the data,
  101356. but we need coupling so that the codec
  101357. (which is in a seperate abstraction
  101358. layer) also knows about the gap */
  101359. ogg_int64_t granulepos;
  101360. } ogg_stream_state;
  101361. /* ogg_packet is used to encapsulate the data and metadata belonging
  101362. to a single raw Ogg/Vorbis packet *************************************/
  101363. typedef struct {
  101364. unsigned char *packet;
  101365. long bytes;
  101366. long b_o_s;
  101367. long e_o_s;
  101368. ogg_int64_t granulepos;
  101369. ogg_int64_t packetno; /* sequence number for decode; the framing
  101370. knows where there's a hole in the data,
  101371. but we need coupling so that the codec
  101372. (which is in a seperate abstraction
  101373. layer) also knows about the gap */
  101374. } ogg_packet;
  101375. typedef struct {
  101376. unsigned char *data;
  101377. int storage;
  101378. int fill;
  101379. int returned;
  101380. int unsynced;
  101381. int headerbytes;
  101382. int bodybytes;
  101383. } ogg_sync_state;
  101384. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  101385. extern void oggpack_writeinit(oggpack_buffer *b);
  101386. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  101387. extern void oggpack_writealign(oggpack_buffer *b);
  101388. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  101389. extern void oggpack_reset(oggpack_buffer *b);
  101390. extern void oggpack_writeclear(oggpack_buffer *b);
  101391. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  101392. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  101393. extern long oggpack_look(oggpack_buffer *b,int bits);
  101394. extern long oggpack_look1(oggpack_buffer *b);
  101395. extern void oggpack_adv(oggpack_buffer *b,int bits);
  101396. extern void oggpack_adv1(oggpack_buffer *b);
  101397. extern long oggpack_read(oggpack_buffer *b,int bits);
  101398. extern long oggpack_read1(oggpack_buffer *b);
  101399. extern long oggpack_bytes(oggpack_buffer *b);
  101400. extern long oggpack_bits(oggpack_buffer *b);
  101401. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  101402. extern void oggpackB_writeinit(oggpack_buffer *b);
  101403. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  101404. extern void oggpackB_writealign(oggpack_buffer *b);
  101405. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  101406. extern void oggpackB_reset(oggpack_buffer *b);
  101407. extern void oggpackB_writeclear(oggpack_buffer *b);
  101408. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  101409. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  101410. extern long oggpackB_look(oggpack_buffer *b,int bits);
  101411. extern long oggpackB_look1(oggpack_buffer *b);
  101412. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  101413. extern void oggpackB_adv1(oggpack_buffer *b);
  101414. extern long oggpackB_read(oggpack_buffer *b,int bits);
  101415. extern long oggpackB_read1(oggpack_buffer *b);
  101416. extern long oggpackB_bytes(oggpack_buffer *b);
  101417. extern long oggpackB_bits(oggpack_buffer *b);
  101418. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  101419. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  101420. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  101421. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  101422. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  101423. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  101424. extern int ogg_sync_init(ogg_sync_state *oy);
  101425. extern int ogg_sync_clear(ogg_sync_state *oy);
  101426. extern int ogg_sync_reset(ogg_sync_state *oy);
  101427. extern int ogg_sync_destroy(ogg_sync_state *oy);
  101428. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  101429. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  101430. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  101431. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  101432. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  101433. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  101434. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  101435. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  101436. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  101437. extern int ogg_stream_clear(ogg_stream_state *os);
  101438. extern int ogg_stream_reset(ogg_stream_state *os);
  101439. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  101440. extern int ogg_stream_destroy(ogg_stream_state *os);
  101441. extern int ogg_stream_eos(ogg_stream_state *os);
  101442. extern void ogg_page_checksum_set(ogg_page *og);
  101443. extern int ogg_page_version(ogg_page *og);
  101444. extern int ogg_page_continued(ogg_page *og);
  101445. extern int ogg_page_bos(ogg_page *og);
  101446. extern int ogg_page_eos(ogg_page *og);
  101447. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  101448. extern int ogg_page_serialno(ogg_page *og);
  101449. extern long ogg_page_pageno(ogg_page *og);
  101450. extern int ogg_page_packets(ogg_page *og);
  101451. extern void ogg_packet_clear(ogg_packet *op);
  101452. #ifdef __cplusplus
  101453. }
  101454. #endif
  101455. #endif /* _OGG_H */
  101456. /********* End of inlined file: ogg.h *********/
  101457. typedef struct vorbis_info{
  101458. int version;
  101459. int channels;
  101460. long rate;
  101461. /* The below bitrate declarations are *hints*.
  101462. Combinations of the three values carry the following implications:
  101463. all three set to the same value:
  101464. implies a fixed rate bitstream
  101465. only nominal set:
  101466. implies a VBR stream that averages the nominal bitrate. No hard
  101467. upper/lower limit
  101468. upper and or lower set:
  101469. implies a VBR bitstream that obeys the bitrate limits. nominal
  101470. may also be set to give a nominal rate.
  101471. none set:
  101472. the coder does not care to speculate.
  101473. */
  101474. long bitrate_upper;
  101475. long bitrate_nominal;
  101476. long bitrate_lower;
  101477. long bitrate_window;
  101478. void *codec_setup;
  101479. } vorbis_info;
  101480. /* vorbis_dsp_state buffers the current vorbis audio
  101481. analysis/synthesis state. The DSP state belongs to a specific
  101482. logical bitstream ****************************************************/
  101483. typedef struct vorbis_dsp_state{
  101484. int analysisp;
  101485. vorbis_info *vi;
  101486. float **pcm;
  101487. float **pcmret;
  101488. int pcm_storage;
  101489. int pcm_current;
  101490. int pcm_returned;
  101491. int preextrapolate;
  101492. int eofflag;
  101493. long lW;
  101494. long W;
  101495. long nW;
  101496. long centerW;
  101497. ogg_int64_t granulepos;
  101498. ogg_int64_t sequence;
  101499. ogg_int64_t glue_bits;
  101500. ogg_int64_t time_bits;
  101501. ogg_int64_t floor_bits;
  101502. ogg_int64_t res_bits;
  101503. void *backend_state;
  101504. } vorbis_dsp_state;
  101505. typedef struct vorbis_block{
  101506. /* necessary stream state for linking to the framing abstraction */
  101507. float **pcm; /* this is a pointer into local storage */
  101508. oggpack_buffer opb;
  101509. long lW;
  101510. long W;
  101511. long nW;
  101512. int pcmend;
  101513. int mode;
  101514. int eofflag;
  101515. ogg_int64_t granulepos;
  101516. ogg_int64_t sequence;
  101517. vorbis_dsp_state *vd; /* For read-only access of configuration */
  101518. /* local storage to avoid remallocing; it's up to the mapping to
  101519. structure it */
  101520. void *localstore;
  101521. long localtop;
  101522. long localalloc;
  101523. long totaluse;
  101524. struct alloc_chain *reap;
  101525. /* bitmetrics for the frame */
  101526. long glue_bits;
  101527. long time_bits;
  101528. long floor_bits;
  101529. long res_bits;
  101530. void *internal;
  101531. } vorbis_block;
  101532. /* vorbis_block is a single block of data to be processed as part of
  101533. the analysis/synthesis stream; it belongs to a specific logical
  101534. bitstream, but is independant from other vorbis_blocks belonging to
  101535. that logical bitstream. *************************************************/
  101536. struct alloc_chain{
  101537. void *ptr;
  101538. struct alloc_chain *next;
  101539. };
  101540. /* vorbis_info contains all the setup information specific to the
  101541. specific compression/decompression mode in progress (eg,
  101542. psychoacoustic settings, channel setup, options, codebook
  101543. etc). vorbis_info and substructures are in backends.h.
  101544. *********************************************************************/
  101545. /* the comments are not part of vorbis_info so that vorbis_info can be
  101546. static storage */
  101547. typedef struct vorbis_comment{
  101548. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  101549. whatever vendor is set to in encode */
  101550. char **user_comments;
  101551. int *comment_lengths;
  101552. int comments;
  101553. char *vendor;
  101554. } vorbis_comment;
  101555. /* libvorbis encodes in two abstraction layers; first we perform DSP
  101556. and produce a packet (see docs/analysis.txt). The packet is then
  101557. coded into a framed OggSquish bitstream by the second layer (see
  101558. docs/framing.txt). Decode is the reverse process; we sync/frame
  101559. the bitstream and extract individual packets, then decode the
  101560. packet back into PCM audio.
  101561. The extra framing/packetizing is used in streaming formats, such as
  101562. files. Over the net (such as with UDP), the framing and
  101563. packetization aren't necessary as they're provided by the transport
  101564. and the streaming layer is not used */
  101565. /* Vorbis PRIMITIVES: general ***************************************/
  101566. extern void vorbis_info_init(vorbis_info *vi);
  101567. extern void vorbis_info_clear(vorbis_info *vi);
  101568. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  101569. extern void vorbis_comment_init(vorbis_comment *vc);
  101570. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  101571. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  101572. char *tag, char *contents);
  101573. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  101574. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  101575. extern void vorbis_comment_clear(vorbis_comment *vc);
  101576. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  101577. extern int vorbis_block_clear(vorbis_block *vb);
  101578. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  101579. extern double vorbis_granule_time(vorbis_dsp_state *v,
  101580. ogg_int64_t granulepos);
  101581. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  101582. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  101583. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  101584. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  101585. vorbis_comment *vc,
  101586. ogg_packet *op,
  101587. ogg_packet *op_comm,
  101588. ogg_packet *op_code);
  101589. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  101590. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  101591. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  101592. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  101593. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  101594. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  101595. ogg_packet *op);
  101596. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  101597. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  101598. ogg_packet *op);
  101599. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  101600. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  101601. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  101602. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  101603. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  101604. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  101605. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  101606. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  101607. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  101608. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  101609. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  101610. /* Vorbis ERRORS and return codes ***********************************/
  101611. #define OV_FALSE -1
  101612. #define OV_EOF -2
  101613. #define OV_HOLE -3
  101614. #define OV_EREAD -128
  101615. #define OV_EFAULT -129
  101616. #define OV_EIMPL -130
  101617. #define OV_EINVAL -131
  101618. #define OV_ENOTVORBIS -132
  101619. #define OV_EBADHEADER -133
  101620. #define OV_EVERSION -134
  101621. #define OV_ENOTAUDIO -135
  101622. #define OV_EBADPACKET -136
  101623. #define OV_EBADLINK -137
  101624. #define OV_ENOSEEK -138
  101625. #ifdef __cplusplus
  101626. }
  101627. #endif /* __cplusplus */
  101628. #endif
  101629. /********* End of inlined file: codec.h *********/
  101630. extern int vorbis_encode_init(vorbis_info *vi,
  101631. long channels,
  101632. long rate,
  101633. long max_bitrate,
  101634. long nominal_bitrate,
  101635. long min_bitrate);
  101636. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  101637. long channels,
  101638. long rate,
  101639. long max_bitrate,
  101640. long nominal_bitrate,
  101641. long min_bitrate);
  101642. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  101643. long channels,
  101644. long rate,
  101645. float quality /* quality level from 0. (lo) to 1. (hi) */
  101646. );
  101647. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  101648. long channels,
  101649. long rate,
  101650. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  101651. );
  101652. extern int vorbis_encode_setup_init(vorbis_info *vi);
  101653. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  101654. /* deprecated rate management supported only for compatability */
  101655. #define OV_ECTL_RATEMANAGE_GET 0x10
  101656. #define OV_ECTL_RATEMANAGE_SET 0x11
  101657. #define OV_ECTL_RATEMANAGE_AVG 0x12
  101658. #define OV_ECTL_RATEMANAGE_HARD 0x13
  101659. struct ovectl_ratemanage_arg {
  101660. int management_active;
  101661. long bitrate_hard_min;
  101662. long bitrate_hard_max;
  101663. double bitrate_hard_window;
  101664. long bitrate_av_lo;
  101665. long bitrate_av_hi;
  101666. double bitrate_av_window;
  101667. double bitrate_av_window_center;
  101668. };
  101669. /* new rate setup */
  101670. #define OV_ECTL_RATEMANAGE2_GET 0x14
  101671. #define OV_ECTL_RATEMANAGE2_SET 0x15
  101672. struct ovectl_ratemanage2_arg {
  101673. int management_active;
  101674. long bitrate_limit_min_kbps;
  101675. long bitrate_limit_max_kbps;
  101676. long bitrate_limit_reservoir_bits;
  101677. double bitrate_limit_reservoir_bias;
  101678. long bitrate_average_kbps;
  101679. double bitrate_average_damping;
  101680. };
  101681. #define OV_ECTL_LOWPASS_GET 0x20
  101682. #define OV_ECTL_LOWPASS_SET 0x21
  101683. #define OV_ECTL_IBLOCK_GET 0x30
  101684. #define OV_ECTL_IBLOCK_SET 0x31
  101685. #ifdef __cplusplus
  101686. }
  101687. #endif /* __cplusplus */
  101688. #endif
  101689. /********* End of inlined file: vorbisenc.h *********/
  101690. /********* Start of inlined file: vorbisfile.h *********/
  101691. #ifndef _OV_FILE_H_
  101692. #define _OV_FILE_H_
  101693. #ifdef __cplusplus
  101694. extern "C"
  101695. {
  101696. #endif /* __cplusplus */
  101697. #include <stdio.h>
  101698. /* The function prototypes for the callbacks are basically the same as for
  101699. * the stdio functions fread, fseek, fclose, ftell.
  101700. * The one difference is that the FILE * arguments have been replaced with
  101701. * a void * - this is to be used as a pointer to whatever internal data these
  101702. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  101703. *
  101704. * If you use other functions, check the docs for these functions and return
  101705. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  101706. * unseekable
  101707. */
  101708. typedef struct {
  101709. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  101710. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  101711. int (*close_func) (void *datasource);
  101712. long (*tell_func) (void *datasource);
  101713. } ov_callbacks;
  101714. #define NOTOPEN 0
  101715. #define PARTOPEN 1
  101716. #define OPENED 2
  101717. #define STREAMSET 3
  101718. #define INITSET 4
  101719. typedef struct OggVorbis_File {
  101720. void *datasource; /* Pointer to a FILE *, etc. */
  101721. int seekable;
  101722. ogg_int64_t offset;
  101723. ogg_int64_t end;
  101724. ogg_sync_state oy;
  101725. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  101726. stream appears */
  101727. int links;
  101728. ogg_int64_t *offsets;
  101729. ogg_int64_t *dataoffsets;
  101730. long *serialnos;
  101731. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  101732. compatability; x2 size, stores both
  101733. beginning and end values */
  101734. vorbis_info *vi;
  101735. vorbis_comment *vc;
  101736. /* Decoding working state local storage */
  101737. ogg_int64_t pcm_offset;
  101738. int ready_state;
  101739. long current_serialno;
  101740. int current_link;
  101741. double bittrack;
  101742. double samptrack;
  101743. ogg_stream_state os; /* take physical pages, weld into a logical
  101744. stream of packets */
  101745. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  101746. vorbis_block vb; /* local working space for packet->PCM decode */
  101747. ov_callbacks callbacks;
  101748. } OggVorbis_File;
  101749. extern int ov_clear(OggVorbis_File *vf);
  101750. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  101751. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  101752. char *initial, long ibytes, ov_callbacks callbacks);
  101753. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  101754. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  101755. char *initial, long ibytes, ov_callbacks callbacks);
  101756. extern int ov_test_open(OggVorbis_File *vf);
  101757. extern long ov_bitrate(OggVorbis_File *vf,int i);
  101758. extern long ov_bitrate_instant(OggVorbis_File *vf);
  101759. extern long ov_streams(OggVorbis_File *vf);
  101760. extern long ov_seekable(OggVorbis_File *vf);
  101761. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  101762. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  101763. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  101764. extern double ov_time_total(OggVorbis_File *vf,int i);
  101765. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  101766. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  101767. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  101768. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  101769. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  101770. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  101771. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  101772. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  101773. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  101774. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  101775. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  101776. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  101777. extern double ov_time_tell(OggVorbis_File *vf);
  101778. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  101779. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  101780. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  101781. int *bitstream);
  101782. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  101783. int bigendianp,int word,int sgned,int *bitstream);
  101784. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  101785. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  101786. extern int ov_halfrate_p(OggVorbis_File *vf);
  101787. #ifdef __cplusplus
  101788. }
  101789. #endif /* __cplusplus */
  101790. #endif
  101791. /********* End of inlined file: vorbisfile.h *********/
  101792. /********* Start of inlined file: bitwise.c *********/
  101793. /* We're 'LSb' endian; if we write a word but read individual bits,
  101794. then we'll read the lsb first */
  101795. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  101796. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  101797. // tasks..
  101798. #ifdef _MSC_VER
  101799. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  101800. #endif
  101801. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  101802. #if JUCE_USE_OGGVORBIS
  101803. #include <string.h>
  101804. #include <stdlib.h>
  101805. #define BUFFER_INCREMENT 256
  101806. static const unsigned long mask[]=
  101807. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  101808. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  101809. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  101810. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  101811. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  101812. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  101813. 0x3fffffff,0x7fffffff,0xffffffff };
  101814. static const unsigned int mask8B[]=
  101815. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  101816. void oggpack_writeinit(oggpack_buffer *b){
  101817. memset(b,0,sizeof(*b));
  101818. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  101819. b->buffer[0]='\0';
  101820. b->storage=BUFFER_INCREMENT;
  101821. }
  101822. void oggpackB_writeinit(oggpack_buffer *b){
  101823. oggpack_writeinit(b);
  101824. }
  101825. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  101826. long bytes=bits>>3;
  101827. bits-=bytes*8;
  101828. b->ptr=b->buffer+bytes;
  101829. b->endbit=bits;
  101830. b->endbyte=bytes;
  101831. *b->ptr&=mask[bits];
  101832. }
  101833. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  101834. long bytes=bits>>3;
  101835. bits-=bytes*8;
  101836. b->ptr=b->buffer+bytes;
  101837. b->endbit=bits;
  101838. b->endbyte=bytes;
  101839. *b->ptr&=mask8B[bits];
  101840. }
  101841. /* Takes only up to 32 bits. */
  101842. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  101843. if(b->endbyte+4>=b->storage){
  101844. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  101845. b->storage+=BUFFER_INCREMENT;
  101846. b->ptr=b->buffer+b->endbyte;
  101847. }
  101848. value&=mask[bits];
  101849. bits+=b->endbit;
  101850. b->ptr[0]|=value<<b->endbit;
  101851. if(bits>=8){
  101852. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  101853. if(bits>=16){
  101854. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  101855. if(bits>=24){
  101856. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  101857. if(bits>=32){
  101858. if(b->endbit)
  101859. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  101860. else
  101861. b->ptr[4]=0;
  101862. }
  101863. }
  101864. }
  101865. }
  101866. b->endbyte+=bits/8;
  101867. b->ptr+=bits/8;
  101868. b->endbit=bits&7;
  101869. }
  101870. /* Takes only up to 32 bits. */
  101871. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  101872. if(b->endbyte+4>=b->storage){
  101873. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  101874. b->storage+=BUFFER_INCREMENT;
  101875. b->ptr=b->buffer+b->endbyte;
  101876. }
  101877. value=(value&mask[bits])<<(32-bits);
  101878. bits+=b->endbit;
  101879. b->ptr[0]|=value>>(24+b->endbit);
  101880. if(bits>=8){
  101881. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  101882. if(bits>=16){
  101883. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  101884. if(bits>=24){
  101885. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  101886. if(bits>=32){
  101887. if(b->endbit)
  101888. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  101889. else
  101890. b->ptr[4]=0;
  101891. }
  101892. }
  101893. }
  101894. }
  101895. b->endbyte+=bits/8;
  101896. b->ptr+=bits/8;
  101897. b->endbit=bits&7;
  101898. }
  101899. void oggpack_writealign(oggpack_buffer *b){
  101900. int bits=8-b->endbit;
  101901. if(bits<8)
  101902. oggpack_write(b,0,bits);
  101903. }
  101904. void oggpackB_writealign(oggpack_buffer *b){
  101905. int bits=8-b->endbit;
  101906. if(bits<8)
  101907. oggpackB_write(b,0,bits);
  101908. }
  101909. static void oggpack_writecopy_helper(oggpack_buffer *b,
  101910. void *source,
  101911. long bits,
  101912. void (*w)(oggpack_buffer *,
  101913. unsigned long,
  101914. int),
  101915. int msb){
  101916. unsigned char *ptr=(unsigned char *)source;
  101917. long bytes=bits/8;
  101918. bits-=bytes*8;
  101919. if(b->endbit){
  101920. int i;
  101921. /* unaligned copy. Do it the hard way. */
  101922. for(i=0;i<bytes;i++)
  101923. w(b,(unsigned long)(ptr[i]),8);
  101924. }else{
  101925. /* aligned block copy */
  101926. if(b->endbyte+bytes+1>=b->storage){
  101927. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  101928. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  101929. b->ptr=b->buffer+b->endbyte;
  101930. }
  101931. memmove(b->ptr,source,bytes);
  101932. b->ptr+=bytes;
  101933. b->endbyte+=bytes;
  101934. *b->ptr=0;
  101935. }
  101936. if(bits){
  101937. if(msb)
  101938. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  101939. else
  101940. w(b,(unsigned long)(ptr[bytes]),bits);
  101941. }
  101942. }
  101943. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  101944. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  101945. }
  101946. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  101947. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  101948. }
  101949. void oggpack_reset(oggpack_buffer *b){
  101950. b->ptr=b->buffer;
  101951. b->buffer[0]=0;
  101952. b->endbit=b->endbyte=0;
  101953. }
  101954. void oggpackB_reset(oggpack_buffer *b){
  101955. oggpack_reset(b);
  101956. }
  101957. void oggpack_writeclear(oggpack_buffer *b){
  101958. _ogg_free(b->buffer);
  101959. memset(b,0,sizeof(*b));
  101960. }
  101961. void oggpackB_writeclear(oggpack_buffer *b){
  101962. oggpack_writeclear(b);
  101963. }
  101964. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  101965. memset(b,0,sizeof(*b));
  101966. b->buffer=b->ptr=buf;
  101967. b->storage=bytes;
  101968. }
  101969. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  101970. oggpack_readinit(b,buf,bytes);
  101971. }
  101972. /* Read in bits without advancing the bitptr; bits <= 32 */
  101973. long oggpack_look(oggpack_buffer *b,int bits){
  101974. unsigned long ret;
  101975. unsigned long m=mask[bits];
  101976. bits+=b->endbit;
  101977. if(b->endbyte+4>=b->storage){
  101978. /* not the main path */
  101979. if(b->endbyte*8+bits>b->storage*8)return(-1);
  101980. }
  101981. ret=b->ptr[0]>>b->endbit;
  101982. if(bits>8){
  101983. ret|=b->ptr[1]<<(8-b->endbit);
  101984. if(bits>16){
  101985. ret|=b->ptr[2]<<(16-b->endbit);
  101986. if(bits>24){
  101987. ret|=b->ptr[3]<<(24-b->endbit);
  101988. if(bits>32 && b->endbit)
  101989. ret|=b->ptr[4]<<(32-b->endbit);
  101990. }
  101991. }
  101992. }
  101993. return(m&ret);
  101994. }
  101995. /* Read in bits without advancing the bitptr; bits <= 32 */
  101996. long oggpackB_look(oggpack_buffer *b,int bits){
  101997. unsigned long ret;
  101998. int m=32-bits;
  101999. bits+=b->endbit;
  102000. if(b->endbyte+4>=b->storage){
  102001. /* not the main path */
  102002. if(b->endbyte*8+bits>b->storage*8)return(-1);
  102003. }
  102004. ret=b->ptr[0]<<(24+b->endbit);
  102005. if(bits>8){
  102006. ret|=b->ptr[1]<<(16+b->endbit);
  102007. if(bits>16){
  102008. ret|=b->ptr[2]<<(8+b->endbit);
  102009. if(bits>24){
  102010. ret|=b->ptr[3]<<(b->endbit);
  102011. if(bits>32 && b->endbit)
  102012. ret|=b->ptr[4]>>(8-b->endbit);
  102013. }
  102014. }
  102015. }
  102016. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  102017. }
  102018. long oggpack_look1(oggpack_buffer *b){
  102019. if(b->endbyte>=b->storage)return(-1);
  102020. return((b->ptr[0]>>b->endbit)&1);
  102021. }
  102022. long oggpackB_look1(oggpack_buffer *b){
  102023. if(b->endbyte>=b->storage)return(-1);
  102024. return((b->ptr[0]>>(7-b->endbit))&1);
  102025. }
  102026. void oggpack_adv(oggpack_buffer *b,int bits){
  102027. bits+=b->endbit;
  102028. b->ptr+=bits/8;
  102029. b->endbyte+=bits/8;
  102030. b->endbit=bits&7;
  102031. }
  102032. void oggpackB_adv(oggpack_buffer *b,int bits){
  102033. oggpack_adv(b,bits);
  102034. }
  102035. void oggpack_adv1(oggpack_buffer *b){
  102036. if(++(b->endbit)>7){
  102037. b->endbit=0;
  102038. b->ptr++;
  102039. b->endbyte++;
  102040. }
  102041. }
  102042. void oggpackB_adv1(oggpack_buffer *b){
  102043. oggpack_adv1(b);
  102044. }
  102045. /* bits <= 32 */
  102046. long oggpack_read(oggpack_buffer *b,int bits){
  102047. long ret;
  102048. unsigned long m=mask[bits];
  102049. bits+=b->endbit;
  102050. if(b->endbyte+4>=b->storage){
  102051. /* not the main path */
  102052. ret=-1L;
  102053. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  102054. }
  102055. ret=b->ptr[0]>>b->endbit;
  102056. if(bits>8){
  102057. ret|=b->ptr[1]<<(8-b->endbit);
  102058. if(bits>16){
  102059. ret|=b->ptr[2]<<(16-b->endbit);
  102060. if(bits>24){
  102061. ret|=b->ptr[3]<<(24-b->endbit);
  102062. if(bits>32 && b->endbit){
  102063. ret|=b->ptr[4]<<(32-b->endbit);
  102064. }
  102065. }
  102066. }
  102067. }
  102068. ret&=m;
  102069. overflow:
  102070. b->ptr+=bits/8;
  102071. b->endbyte+=bits/8;
  102072. b->endbit=bits&7;
  102073. return(ret);
  102074. }
  102075. /* bits <= 32 */
  102076. long oggpackB_read(oggpack_buffer *b,int bits){
  102077. long ret;
  102078. long m=32-bits;
  102079. bits+=b->endbit;
  102080. if(b->endbyte+4>=b->storage){
  102081. /* not the main path */
  102082. ret=-1L;
  102083. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  102084. }
  102085. ret=b->ptr[0]<<(24+b->endbit);
  102086. if(bits>8){
  102087. ret|=b->ptr[1]<<(16+b->endbit);
  102088. if(bits>16){
  102089. ret|=b->ptr[2]<<(8+b->endbit);
  102090. if(bits>24){
  102091. ret|=b->ptr[3]<<(b->endbit);
  102092. if(bits>32 && b->endbit)
  102093. ret|=b->ptr[4]>>(8-b->endbit);
  102094. }
  102095. }
  102096. }
  102097. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  102098. overflow:
  102099. b->ptr+=bits/8;
  102100. b->endbyte+=bits/8;
  102101. b->endbit=bits&7;
  102102. return(ret);
  102103. }
  102104. long oggpack_read1(oggpack_buffer *b){
  102105. long ret;
  102106. if(b->endbyte>=b->storage){
  102107. /* not the main path */
  102108. ret=-1L;
  102109. goto overflow;
  102110. }
  102111. ret=(b->ptr[0]>>b->endbit)&1;
  102112. overflow:
  102113. b->endbit++;
  102114. if(b->endbit>7){
  102115. b->endbit=0;
  102116. b->ptr++;
  102117. b->endbyte++;
  102118. }
  102119. return(ret);
  102120. }
  102121. long oggpackB_read1(oggpack_buffer *b){
  102122. long ret;
  102123. if(b->endbyte>=b->storage){
  102124. /* not the main path */
  102125. ret=-1L;
  102126. goto overflow;
  102127. }
  102128. ret=(b->ptr[0]>>(7-b->endbit))&1;
  102129. overflow:
  102130. b->endbit++;
  102131. if(b->endbit>7){
  102132. b->endbit=0;
  102133. b->ptr++;
  102134. b->endbyte++;
  102135. }
  102136. return(ret);
  102137. }
  102138. long oggpack_bytes(oggpack_buffer *b){
  102139. return(b->endbyte+(b->endbit+7)/8);
  102140. }
  102141. long oggpack_bits(oggpack_buffer *b){
  102142. return(b->endbyte*8+b->endbit);
  102143. }
  102144. long oggpackB_bytes(oggpack_buffer *b){
  102145. return oggpack_bytes(b);
  102146. }
  102147. long oggpackB_bits(oggpack_buffer *b){
  102148. return oggpack_bits(b);
  102149. }
  102150. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  102151. return(b->buffer);
  102152. }
  102153. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  102154. return oggpack_get_buffer(b);
  102155. }
  102156. /* Self test of the bitwise routines; everything else is based on
  102157. them, so they damned well better be solid. */
  102158. #ifdef _V_SELFTEST
  102159. #include <stdio.h>
  102160. static int ilog(unsigned int v){
  102161. int ret=0;
  102162. while(v){
  102163. ret++;
  102164. v>>=1;
  102165. }
  102166. return(ret);
  102167. }
  102168. oggpack_buffer o;
  102169. oggpack_buffer r;
  102170. void report(char *in){
  102171. fprintf(stderr,"%s",in);
  102172. exit(1);
  102173. }
  102174. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  102175. long bytes,i;
  102176. unsigned char *buffer;
  102177. oggpack_reset(&o);
  102178. for(i=0;i<vals;i++)
  102179. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  102180. buffer=oggpack_get_buffer(&o);
  102181. bytes=oggpack_bytes(&o);
  102182. if(bytes!=compsize)report("wrong number of bytes!\n");
  102183. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  102184. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  102185. report("wrote incorrect value!\n");
  102186. }
  102187. oggpack_readinit(&r,buffer,bytes);
  102188. for(i=0;i<vals;i++){
  102189. int tbit=bits?bits:ilog(b[i]);
  102190. if(oggpack_look(&r,tbit)==-1)
  102191. report("out of data!\n");
  102192. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  102193. report("looked at incorrect value!\n");
  102194. if(tbit==1)
  102195. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  102196. report("looked at single bit incorrect value!\n");
  102197. if(tbit==1){
  102198. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  102199. report("read incorrect single bit value!\n");
  102200. }else{
  102201. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  102202. report("read incorrect value!\n");
  102203. }
  102204. }
  102205. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  102206. }
  102207. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  102208. long bytes,i;
  102209. unsigned char *buffer;
  102210. oggpackB_reset(&o);
  102211. for(i=0;i<vals;i++)
  102212. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  102213. buffer=oggpackB_get_buffer(&o);
  102214. bytes=oggpackB_bytes(&o);
  102215. if(bytes!=compsize)report("wrong number of bytes!\n");
  102216. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  102217. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  102218. report("wrote incorrect value!\n");
  102219. }
  102220. oggpackB_readinit(&r,buffer,bytes);
  102221. for(i=0;i<vals;i++){
  102222. int tbit=bits?bits:ilog(b[i]);
  102223. if(oggpackB_look(&r,tbit)==-1)
  102224. report("out of data!\n");
  102225. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  102226. report("looked at incorrect value!\n");
  102227. if(tbit==1)
  102228. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  102229. report("looked at single bit incorrect value!\n");
  102230. if(tbit==1){
  102231. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  102232. report("read incorrect single bit value!\n");
  102233. }else{
  102234. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  102235. report("read incorrect value!\n");
  102236. }
  102237. }
  102238. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  102239. }
  102240. int main(void){
  102241. unsigned char *buffer;
  102242. long bytes,i;
  102243. static unsigned long testbuffer1[]=
  102244. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  102245. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  102246. int test1size=43;
  102247. static unsigned long testbuffer2[]=
  102248. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  102249. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  102250. 85525151,0,12321,1,349528352};
  102251. int test2size=21;
  102252. static unsigned long testbuffer3[]=
  102253. {1,0,14,0,1,0,12,0,1,0,0,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0,1,1,1,1,1,0,0,1,
  102254. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  102255. int test3size=56;
  102256. static unsigned long large[]=
  102257. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  102258. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  102259. 85525151,0,12321,1,2146528352};
  102260. int onesize=33;
  102261. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  102262. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  102263. 223,4};
  102264. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  102265. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  102266. 245,251,128};
  102267. int twosize=6;
  102268. static int two[6]={61,255,255,251,231,29};
  102269. static int twoB[6]={247,63,255,253,249,120};
  102270. int threesize=54;
  102271. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  102272. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  102273. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  102274. 100,52,4,14,18,86,77,1};
  102275. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  102276. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  102277. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  102278. 200,20,254,4,58,106,176,144,0};
  102279. int foursize=38;
  102280. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  102281. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  102282. 28,2,133,0,1};
  102283. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  102284. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  102285. 129,10,4,32};
  102286. int fivesize=45;
  102287. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  102288. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  102289. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  102290. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  102291. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  102292. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  102293. int sixsize=7;
  102294. static int six[7]={17,177,170,242,169,19,148};
  102295. static int sixB[7]={136,141,85,79,149,200,41};
  102296. /* Test read/write together */
  102297. /* Later we test against pregenerated bitstreams */
  102298. oggpack_writeinit(&o);
  102299. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  102300. cliptest(testbuffer1,test1size,0,one,onesize);
  102301. fprintf(stderr,"ok.");
  102302. fprintf(stderr,"\nNull bit call (LSb): ");
  102303. cliptest(testbuffer3,test3size,0,two,twosize);
  102304. fprintf(stderr,"ok.");
  102305. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  102306. cliptest(testbuffer2,test2size,0,three,threesize);
  102307. fprintf(stderr,"ok.");
  102308. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  102309. oggpack_reset(&o);
  102310. for(i=0;i<test2size;i++)
  102311. oggpack_write(&o,large[i],32);
  102312. buffer=oggpack_get_buffer(&o);
  102313. bytes=oggpack_bytes(&o);
  102314. oggpack_readinit(&r,buffer,bytes);
  102315. for(i=0;i<test2size;i++){
  102316. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  102317. if(oggpack_look(&r,32)!=large[i]){
  102318. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  102319. oggpack_look(&r,32),large[i]);
  102320. report("read incorrect value!\n");
  102321. }
  102322. oggpack_adv(&r,32);
  102323. }
  102324. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  102325. fprintf(stderr,"ok.");
  102326. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  102327. cliptest(testbuffer1,test1size,7,four,foursize);
  102328. fprintf(stderr,"ok.");
  102329. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  102330. cliptest(testbuffer2,test2size,17,five,fivesize);
  102331. fprintf(stderr,"ok.");
  102332. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  102333. cliptest(testbuffer3,test3size,1,six,sixsize);
  102334. fprintf(stderr,"ok.");
  102335. fprintf(stderr,"\nTesting read past end (LSb): ");
  102336. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  102337. for(i=0;i<64;i++){
  102338. if(oggpack_read(&r,1)!=0){
  102339. fprintf(stderr,"failed; got -1 prematurely.\n");
  102340. exit(1);
  102341. }
  102342. }
  102343. if(oggpack_look(&r,1)!=-1 ||
  102344. oggpack_read(&r,1)!=-1){
  102345. fprintf(stderr,"failed; read past end without -1.\n");
  102346. exit(1);
  102347. }
  102348. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  102349. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  102350. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  102351. exit(1);
  102352. }
  102353. if(oggpack_look(&r,18)!=0 ||
  102354. oggpack_look(&r,18)!=0){
  102355. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  102356. exit(1);
  102357. }
  102358. if(oggpack_look(&r,19)!=-1 ||
  102359. oggpack_look(&r,19)!=-1){
  102360. fprintf(stderr,"failed; read past end without -1.\n");
  102361. exit(1);
  102362. }
  102363. if(oggpack_look(&r,32)!=-1 ||
  102364. oggpack_look(&r,32)!=-1){
  102365. fprintf(stderr,"failed; read past end without -1.\n");
  102366. exit(1);
  102367. }
  102368. oggpack_writeclear(&o);
  102369. fprintf(stderr,"ok.\n");
  102370. /********** lazy, cut-n-paste retest with MSb packing ***********/
  102371. /* Test read/write together */
  102372. /* Later we test against pregenerated bitstreams */
  102373. oggpackB_writeinit(&o);
  102374. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  102375. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  102376. fprintf(stderr,"ok.");
  102377. fprintf(stderr,"\nNull bit call (MSb): ");
  102378. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  102379. fprintf(stderr,"ok.");
  102380. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  102381. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  102382. fprintf(stderr,"ok.");
  102383. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  102384. oggpackB_reset(&o);
  102385. for(i=0;i<test2size;i++)
  102386. oggpackB_write(&o,large[i],32);
  102387. buffer=oggpackB_get_buffer(&o);
  102388. bytes=oggpackB_bytes(&o);
  102389. oggpackB_readinit(&r,buffer,bytes);
  102390. for(i=0;i<test2size;i++){
  102391. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  102392. if(oggpackB_look(&r,32)!=large[i]){
  102393. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  102394. oggpackB_look(&r,32),large[i]);
  102395. report("read incorrect value!\n");
  102396. }
  102397. oggpackB_adv(&r,32);
  102398. }
  102399. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  102400. fprintf(stderr,"ok.");
  102401. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  102402. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  102403. fprintf(stderr,"ok.");
  102404. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  102405. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  102406. fprintf(stderr,"ok.");
  102407. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  102408. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  102409. fprintf(stderr,"ok.");
  102410. fprintf(stderr,"\nTesting read past end (MSb): ");
  102411. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  102412. for(i=0;i<64;i++){
  102413. if(oggpackB_read(&r,1)!=0){
  102414. fprintf(stderr,"failed; got -1 prematurely.\n");
  102415. exit(1);
  102416. }
  102417. }
  102418. if(oggpackB_look(&r,1)!=-1 ||
  102419. oggpackB_read(&r,1)!=-1){
  102420. fprintf(stderr,"failed; read past end without -1.\n");
  102421. exit(1);
  102422. }
  102423. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  102424. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  102425. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  102426. exit(1);
  102427. }
  102428. if(oggpackB_look(&r,18)!=0 ||
  102429. oggpackB_look(&r,18)!=0){
  102430. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  102431. exit(1);
  102432. }
  102433. if(oggpackB_look(&r,19)!=-1 ||
  102434. oggpackB_look(&r,19)!=-1){
  102435. fprintf(stderr,"failed; read past end without -1.\n");
  102436. exit(1);
  102437. }
  102438. if(oggpackB_look(&r,32)!=-1 ||
  102439. oggpackB_look(&r,32)!=-1){
  102440. fprintf(stderr,"failed; read past end without -1.\n");
  102441. exit(1);
  102442. }
  102443. oggpackB_writeclear(&o);
  102444. fprintf(stderr,"ok.\n\n");
  102445. return(0);
  102446. }
  102447. #endif /* _V_SELFTEST */
  102448. #undef BUFFER_INCREMENT
  102449. #endif
  102450. /********* End of inlined file: bitwise.c *********/
  102451. /********* Start of inlined file: framing.c *********/
  102452. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  102453. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  102454. // tasks..
  102455. #ifdef _MSC_VER
  102456. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  102457. #endif
  102458. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  102459. #if JUCE_USE_OGGVORBIS
  102460. #include <stdlib.h>
  102461. #include <string.h>
  102462. /* A complete description of Ogg framing exists in docs/framing.html */
  102463. int ogg_page_version(ogg_page *og){
  102464. return((int)(og->header[4]));
  102465. }
  102466. int ogg_page_continued(ogg_page *og){
  102467. return((int)(og->header[5]&0x01));
  102468. }
  102469. int ogg_page_bos(ogg_page *og){
  102470. return((int)(og->header[5]&0x02));
  102471. }
  102472. int ogg_page_eos(ogg_page *og){
  102473. return((int)(og->header[5]&0x04));
  102474. }
  102475. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  102476. unsigned char *page=og->header;
  102477. ogg_int64_t granulepos=page[13]&(0xff);
  102478. granulepos= (granulepos<<8)|(page[12]&0xff);
  102479. granulepos= (granulepos<<8)|(page[11]&0xff);
  102480. granulepos= (granulepos<<8)|(page[10]&0xff);
  102481. granulepos= (granulepos<<8)|(page[9]&0xff);
  102482. granulepos= (granulepos<<8)|(page[8]&0xff);
  102483. granulepos= (granulepos<<8)|(page[7]&0xff);
  102484. granulepos= (granulepos<<8)|(page[6]&0xff);
  102485. return(granulepos);
  102486. }
  102487. int ogg_page_serialno(ogg_page *og){
  102488. return(og->header[14] |
  102489. (og->header[15]<<8) |
  102490. (og->header[16]<<16) |
  102491. (og->header[17]<<24));
  102492. }
  102493. long ogg_page_pageno(ogg_page *og){
  102494. return(og->header[18] |
  102495. (og->header[19]<<8) |
  102496. (og->header[20]<<16) |
  102497. (og->header[21]<<24));
  102498. }
  102499. /* returns the number of packets that are completed on this page (if
  102500. the leading packet is begun on a previous page, but ends on this
  102501. page, it's counted */
  102502. /* NOTE:
  102503. If a page consists of a packet begun on a previous page, and a new
  102504. packet begun (but not completed) on this page, the return will be:
  102505. ogg_page_packets(page) ==1,
  102506. ogg_page_continued(page) !=0
  102507. If a page happens to be a single packet that was begun on a
  102508. previous page, and spans to the next page (in the case of a three or
  102509. more page packet), the return will be:
  102510. ogg_page_packets(page) ==0,
  102511. ogg_page_continued(page) !=0
  102512. */
  102513. int ogg_page_packets(ogg_page *og){
  102514. int i,n=og->header[26],count=0;
  102515. for(i=0;i<n;i++)
  102516. if(og->header[27+i]<255)count++;
  102517. return(count);
  102518. }
  102519. #if 0
  102520. /* helper to initialize lookup for direct-table CRC (illustrative; we
  102521. use the static init below) */
  102522. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  102523. int i;
  102524. unsigned long r;
  102525. r = index << 24;
  102526. for (i=0; i<8; i++)
  102527. if (r & 0x80000000UL)
  102528. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  102529. polynomial, although we use an
  102530. unreflected alg and an init/final
  102531. of 0, not 0xffffffff */
  102532. else
  102533. r<<=1;
  102534. return (r & 0xffffffffUL);
  102535. }
  102536. #endif
  102537. static const ogg_uint32_t crc_lookup[256]={
  102538. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  102539. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  102540. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  102541. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  102542. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  102543. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  102544. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  102545. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  102546. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  102547. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  102548. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  102549. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  102550. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  102551. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  102552. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  102553. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  102554. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  102555. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  102556. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  102557. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  102558. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  102559. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  102560. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  102561. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  102562. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  102563. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  102564. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  102565. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  102566. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  102567. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  102568. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  102569. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  102570. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  102571. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  102572. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  102573. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  102574. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  102575. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  102576. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  102577. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  102578. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  102579. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  102580. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  102581. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  102582. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  102583. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  102584. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  102585. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  102586. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  102587. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  102588. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  102589. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  102590. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  102591. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  102592. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  102593. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  102594. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  102595. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  102596. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  102597. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  102598. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  102599. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  102600. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  102601. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  102602. /* init the encode/decode logical stream state */
  102603. int ogg_stream_init(ogg_stream_state *os,int serialno){
  102604. if(os){
  102605. memset(os,0,sizeof(*os));
  102606. os->body_storage=16*1024;
  102607. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  102608. os->lacing_storage=1024;
  102609. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  102610. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  102611. os->serialno=serialno;
  102612. return(0);
  102613. }
  102614. return(-1);
  102615. }
  102616. /* _clear does not free os, only the non-flat storage within */
  102617. int ogg_stream_clear(ogg_stream_state *os){
  102618. if(os){
  102619. if(os->body_data)_ogg_free(os->body_data);
  102620. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  102621. if(os->granule_vals)_ogg_free(os->granule_vals);
  102622. memset(os,0,sizeof(*os));
  102623. }
  102624. return(0);
  102625. }
  102626. int ogg_stream_destroy(ogg_stream_state *os){
  102627. if(os){
  102628. ogg_stream_clear(os);
  102629. _ogg_free(os);
  102630. }
  102631. return(0);
  102632. }
  102633. /* Helpers for ogg_stream_encode; this keeps the structure and
  102634. what's happening fairly clear */
  102635. static void _os_body_expand(ogg_stream_state *os,int needed){
  102636. if(os->body_storage<=os->body_fill+needed){
  102637. os->body_storage+=(needed+1024);
  102638. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  102639. }
  102640. }
  102641. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  102642. if(os->lacing_storage<=os->lacing_fill+needed){
  102643. os->lacing_storage+=(needed+32);
  102644. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  102645. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  102646. }
  102647. }
  102648. /* checksum the page */
  102649. /* Direct table CRC; note that this will be faster in the future if we
  102650. perform the checksum silmultaneously with other copies */
  102651. void ogg_page_checksum_set(ogg_page *og){
  102652. if(og){
  102653. ogg_uint32_t crc_reg=0;
  102654. int i;
  102655. /* safety; needed for API behavior, but not framing code */
  102656. og->header[22]=0;
  102657. og->header[23]=0;
  102658. og->header[24]=0;
  102659. og->header[25]=0;
  102660. for(i=0;i<og->header_len;i++)
  102661. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  102662. for(i=0;i<og->body_len;i++)
  102663. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  102664. og->header[22]=(unsigned char)(crc_reg&0xff);
  102665. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  102666. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  102667. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  102668. }
  102669. }
  102670. /* submit data to the internal buffer of the framing engine */
  102671. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  102672. int lacing_vals=op->bytes/255+1,i;
  102673. if(os->body_returned){
  102674. /* advance packet data according to the body_returned pointer. We
  102675. had to keep it around to return a pointer into the buffer last
  102676. call */
  102677. os->body_fill-=os->body_returned;
  102678. if(os->body_fill)
  102679. memmove(os->body_data,os->body_data+os->body_returned,
  102680. os->body_fill);
  102681. os->body_returned=0;
  102682. }
  102683. /* make sure we have the buffer storage */
  102684. _os_body_expand(os,op->bytes);
  102685. _os_lacing_expand(os,lacing_vals);
  102686. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  102687. the liability of overly clean abstraction for the time being. It
  102688. will actually be fairly easy to eliminate the extra copy in the
  102689. future */
  102690. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  102691. os->body_fill+=op->bytes;
  102692. /* Store lacing vals for this packet */
  102693. for(i=0;i<lacing_vals-1;i++){
  102694. os->lacing_vals[os->lacing_fill+i]=255;
  102695. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  102696. }
  102697. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  102698. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  102699. /* flag the first segment as the beginning of the packet */
  102700. os->lacing_vals[os->lacing_fill]|= 0x100;
  102701. os->lacing_fill+=lacing_vals;
  102702. /* for the sake of completeness */
  102703. os->packetno++;
  102704. if(op->e_o_s)os->e_o_s=1;
  102705. return(0);
  102706. }
  102707. /* This will flush remaining packets into a page (returning nonzero),
  102708. even if there is not enough data to trigger a flush normally
  102709. (undersized page). If there are no packets or partial packets to
  102710. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  102711. try to flush a normal sized page like ogg_stream_pageout; a call to
  102712. ogg_stream_flush does not guarantee that all packets have flushed.
  102713. Only a return value of 0 from ogg_stream_flush indicates all packet
  102714. data is flushed into pages.
  102715. since ogg_stream_flush will flush the last page in a stream even if
  102716. it's undersized, you almost certainly want to use ogg_stream_pageout
  102717. (and *not* ogg_stream_flush) unless you specifically need to flush
  102718. an page regardless of size in the middle of a stream. */
  102719. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  102720. int i;
  102721. int vals=0;
  102722. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  102723. int bytes=0;
  102724. long acc=0;
  102725. ogg_int64_t granule_pos=-1;
  102726. if(maxvals==0)return(0);
  102727. /* construct a page */
  102728. /* decide how many segments to include */
  102729. /* If this is the initial header case, the first page must only include
  102730. the initial header packet */
  102731. if(os->b_o_s==0){ /* 'initial header page' case */
  102732. granule_pos=0;
  102733. for(vals=0;vals<maxvals;vals++){
  102734. if((os->lacing_vals[vals]&0x0ff)<255){
  102735. vals++;
  102736. break;
  102737. }
  102738. }
  102739. }else{
  102740. for(vals=0;vals<maxvals;vals++){
  102741. if(acc>4096)break;
  102742. acc+=os->lacing_vals[vals]&0x0ff;
  102743. if((os->lacing_vals[vals]&0xff)<255)
  102744. granule_pos=os->granule_vals[vals];
  102745. }
  102746. }
  102747. /* construct the header in temp storage */
  102748. memcpy(os->header,"OggS",4);
  102749. /* stream structure version */
  102750. os->header[4]=0x00;
  102751. /* continued packet flag? */
  102752. os->header[5]=0x00;
  102753. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  102754. /* first page flag? */
  102755. if(os->b_o_s==0)os->header[5]|=0x02;
  102756. /* last page flag? */
  102757. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  102758. os->b_o_s=1;
  102759. /* 64 bits of PCM position */
  102760. for(i=6;i<14;i++){
  102761. os->header[i]=(unsigned char)(granule_pos&0xff);
  102762. granule_pos>>=8;
  102763. }
  102764. /* 32 bits of stream serial number */
  102765. {
  102766. long serialno=os->serialno;
  102767. for(i=14;i<18;i++){
  102768. os->header[i]=(unsigned char)(serialno&0xff);
  102769. serialno>>=8;
  102770. }
  102771. }
  102772. /* 32 bits of page counter (we have both counter and page header
  102773. because this val can roll over) */
  102774. if(os->pageno==-1)os->pageno=0; /* because someone called
  102775. stream_reset; this would be a
  102776. strange thing to do in an
  102777. encode stream, but it has
  102778. plausible uses */
  102779. {
  102780. long pageno=os->pageno++;
  102781. for(i=18;i<22;i++){
  102782. os->header[i]=(unsigned char)(pageno&0xff);
  102783. pageno>>=8;
  102784. }
  102785. }
  102786. /* zero for computation; filled in later */
  102787. os->header[22]=0;
  102788. os->header[23]=0;
  102789. os->header[24]=0;
  102790. os->header[25]=0;
  102791. /* segment table */
  102792. os->header[26]=(unsigned char)(vals&0xff);
  102793. for(i=0;i<vals;i++)
  102794. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  102795. /* set pointers in the ogg_page struct */
  102796. og->header=os->header;
  102797. og->header_len=os->header_fill=vals+27;
  102798. og->body=os->body_data+os->body_returned;
  102799. og->body_len=bytes;
  102800. /* advance the lacing data and set the body_returned pointer */
  102801. os->lacing_fill-=vals;
  102802. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  102803. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  102804. os->body_returned+=bytes;
  102805. /* calculate the checksum */
  102806. ogg_page_checksum_set(og);
  102807. /* done */
  102808. return(1);
  102809. }
  102810. /* This constructs pages from buffered packet segments. The pointers
  102811. returned are to static buffers; do not free. The returned buffers are
  102812. good only until the next call (using the same ogg_stream_state) */
  102813. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  102814. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  102815. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  102816. os->lacing_fill>=255 || /* 'segment table full' case */
  102817. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  102818. return(ogg_stream_flush(os,og));
  102819. }
  102820. /* not enough data to construct a page and not end of stream */
  102821. return(0);
  102822. }
  102823. int ogg_stream_eos(ogg_stream_state *os){
  102824. return os->e_o_s;
  102825. }
  102826. /* DECODING PRIMITIVES: packet streaming layer **********************/
  102827. /* This has two layers to place more of the multi-serialno and paging
  102828. control in the application's hands. First, we expose a data buffer
  102829. using ogg_sync_buffer(). The app either copies into the
  102830. buffer, or passes it directly to read(), etc. We then call
  102831. ogg_sync_wrote() to tell how many bytes we just added.
  102832. Pages are returned (pointers into the buffer in ogg_sync_state)
  102833. by ogg_sync_pageout(). The page is then submitted to
  102834. ogg_stream_pagein() along with the appropriate
  102835. ogg_stream_state* (ie, matching serialno). We then get raw
  102836. packets out calling ogg_stream_packetout() with a
  102837. ogg_stream_state. */
  102838. /* initialize the struct to a known state */
  102839. int ogg_sync_init(ogg_sync_state *oy){
  102840. if(oy){
  102841. memset(oy,0,sizeof(*oy));
  102842. }
  102843. return(0);
  102844. }
  102845. /* clear non-flat storage within */
  102846. int ogg_sync_clear(ogg_sync_state *oy){
  102847. if(oy){
  102848. if(oy->data)_ogg_free(oy->data);
  102849. ogg_sync_init(oy);
  102850. }
  102851. return(0);
  102852. }
  102853. int ogg_sync_destroy(ogg_sync_state *oy){
  102854. if(oy){
  102855. ogg_sync_clear(oy);
  102856. _ogg_free(oy);
  102857. }
  102858. return(0);
  102859. }
  102860. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  102861. /* first, clear out any space that has been previously returned */
  102862. if(oy->returned){
  102863. oy->fill-=oy->returned;
  102864. if(oy->fill>0)
  102865. memmove(oy->data,oy->data+oy->returned,oy->fill);
  102866. oy->returned=0;
  102867. }
  102868. if(size>oy->storage-oy->fill){
  102869. /* We need to extend the internal buffer */
  102870. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  102871. if(oy->data)
  102872. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  102873. else
  102874. oy->data=(unsigned char*) _ogg_malloc(newsize);
  102875. oy->storage=newsize;
  102876. }
  102877. /* expose a segment at least as large as requested at the fill mark */
  102878. return((char *)oy->data+oy->fill);
  102879. }
  102880. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  102881. if(oy->fill+bytes>oy->storage)return(-1);
  102882. oy->fill+=bytes;
  102883. return(0);
  102884. }
  102885. /* sync the stream. This is meant to be useful for finding page
  102886. boundaries.
  102887. return values for this:
  102888. -n) skipped n bytes
  102889. 0) page not ready; more data (no bytes skipped)
  102890. n) page synced at current location; page length n bytes
  102891. */
  102892. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  102893. unsigned char *page=oy->data+oy->returned;
  102894. unsigned char *next;
  102895. long bytes=oy->fill-oy->returned;
  102896. if(oy->headerbytes==0){
  102897. int headerbytes,i;
  102898. if(bytes<27)return(0); /* not enough for a header */
  102899. /* verify capture pattern */
  102900. if(memcmp(page,"OggS",4))goto sync_fail;
  102901. headerbytes=page[26]+27;
  102902. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  102903. /* count up body length in the segment table */
  102904. for(i=0;i<page[26];i++)
  102905. oy->bodybytes+=page[27+i];
  102906. oy->headerbytes=headerbytes;
  102907. }
  102908. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  102909. /* The whole test page is buffered. Verify the checksum */
  102910. {
  102911. /* Grab the checksum bytes, set the header field to zero */
  102912. char chksum[4];
  102913. ogg_page log;
  102914. memcpy(chksum,page+22,4);
  102915. memset(page+22,0,4);
  102916. /* set up a temp page struct and recompute the checksum */
  102917. log.header=page;
  102918. log.header_len=oy->headerbytes;
  102919. log.body=page+oy->headerbytes;
  102920. log.body_len=oy->bodybytes;
  102921. ogg_page_checksum_set(&log);
  102922. /* Compare */
  102923. if(memcmp(chksum,page+22,4)){
  102924. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  102925. at all) */
  102926. /* replace the computed checksum with the one actually read in */
  102927. memcpy(page+22,chksum,4);
  102928. /* Bad checksum. Lose sync */
  102929. goto sync_fail;
  102930. }
  102931. }
  102932. /* yes, have a whole page all ready to go */
  102933. {
  102934. unsigned char *page=oy->data+oy->returned;
  102935. long bytes;
  102936. if(og){
  102937. og->header=page;
  102938. og->header_len=oy->headerbytes;
  102939. og->body=page+oy->headerbytes;
  102940. og->body_len=oy->bodybytes;
  102941. }
  102942. oy->unsynced=0;
  102943. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  102944. oy->headerbytes=0;
  102945. oy->bodybytes=0;
  102946. return(bytes);
  102947. }
  102948. sync_fail:
  102949. oy->headerbytes=0;
  102950. oy->bodybytes=0;
  102951. /* search for possible capture */
  102952. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  102953. if(!next)
  102954. next=oy->data+oy->fill;
  102955. oy->returned=next-oy->data;
  102956. return(-(next-page));
  102957. }
  102958. /* sync the stream and get a page. Keep trying until we find a page.
  102959. Supress 'sync errors' after reporting the first.
  102960. return values:
  102961. -1) recapture (hole in data)
  102962. 0) need more data
  102963. 1) page returned
  102964. Returns pointers into buffered data; invalidated by next call to
  102965. _stream, _clear, _init, or _buffer */
  102966. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  102967. /* all we need to do is verify a page at the head of the stream
  102968. buffer. If it doesn't verify, we look for the next potential
  102969. frame */
  102970. for(;;){
  102971. long ret=ogg_sync_pageseek(oy,og);
  102972. if(ret>0){
  102973. /* have a page */
  102974. return(1);
  102975. }
  102976. if(ret==0){
  102977. /* need more data */
  102978. return(0);
  102979. }
  102980. /* head did not start a synced page... skipped some bytes */
  102981. if(!oy->unsynced){
  102982. oy->unsynced=1;
  102983. return(-1);
  102984. }
  102985. /* loop. keep looking */
  102986. }
  102987. }
  102988. /* add the incoming page to the stream state; we decompose the page
  102989. into packet segments here as well. */
  102990. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  102991. unsigned char *header=og->header;
  102992. unsigned char *body=og->body;
  102993. long bodysize=og->body_len;
  102994. int segptr=0;
  102995. int version=ogg_page_version(og);
  102996. int continued=ogg_page_continued(og);
  102997. int bos=ogg_page_bos(og);
  102998. int eos=ogg_page_eos(og);
  102999. ogg_int64_t granulepos=ogg_page_granulepos(og);
  103000. int serialno=ogg_page_serialno(og);
  103001. long pageno=ogg_page_pageno(og);
  103002. int segments=header[26];
  103003. /* clean up 'returned data' */
  103004. {
  103005. long lr=os->lacing_returned;
  103006. long br=os->body_returned;
  103007. /* body data */
  103008. if(br){
  103009. os->body_fill-=br;
  103010. if(os->body_fill)
  103011. memmove(os->body_data,os->body_data+br,os->body_fill);
  103012. os->body_returned=0;
  103013. }
  103014. if(lr){
  103015. /* segment table */
  103016. if(os->lacing_fill-lr){
  103017. memmove(os->lacing_vals,os->lacing_vals+lr,
  103018. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  103019. memmove(os->granule_vals,os->granule_vals+lr,
  103020. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  103021. }
  103022. os->lacing_fill-=lr;
  103023. os->lacing_packet-=lr;
  103024. os->lacing_returned=0;
  103025. }
  103026. }
  103027. /* check the serial number */
  103028. if(serialno!=os->serialno)return(-1);
  103029. if(version>0)return(-1);
  103030. _os_lacing_expand(os,segments+1);
  103031. /* are we in sequence? */
  103032. if(pageno!=os->pageno){
  103033. int i;
  103034. /* unroll previous partial packet (if any) */
  103035. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  103036. os->body_fill-=os->lacing_vals[i]&0xff;
  103037. os->lacing_fill=os->lacing_packet;
  103038. /* make a note of dropped data in segment table */
  103039. if(os->pageno!=-1){
  103040. os->lacing_vals[os->lacing_fill++]=0x400;
  103041. os->lacing_packet++;
  103042. }
  103043. }
  103044. /* are we a 'continued packet' page? If so, we may need to skip
  103045. some segments */
  103046. if(continued){
  103047. if(os->lacing_fill<1 ||
  103048. os->lacing_vals[os->lacing_fill-1]==0x400){
  103049. bos=0;
  103050. for(;segptr<segments;segptr++){
  103051. int val=header[27+segptr];
  103052. body+=val;
  103053. bodysize-=val;
  103054. if(val<255){
  103055. segptr++;
  103056. break;
  103057. }
  103058. }
  103059. }
  103060. }
  103061. if(bodysize){
  103062. _os_body_expand(os,bodysize);
  103063. memcpy(os->body_data+os->body_fill,body,bodysize);
  103064. os->body_fill+=bodysize;
  103065. }
  103066. {
  103067. int saved=-1;
  103068. while(segptr<segments){
  103069. int val=header[27+segptr];
  103070. os->lacing_vals[os->lacing_fill]=val;
  103071. os->granule_vals[os->lacing_fill]=-1;
  103072. if(bos){
  103073. os->lacing_vals[os->lacing_fill]|=0x100;
  103074. bos=0;
  103075. }
  103076. if(val<255)saved=os->lacing_fill;
  103077. os->lacing_fill++;
  103078. segptr++;
  103079. if(val<255)os->lacing_packet=os->lacing_fill;
  103080. }
  103081. /* set the granulepos on the last granuleval of the last full packet */
  103082. if(saved!=-1){
  103083. os->granule_vals[saved]=granulepos;
  103084. }
  103085. }
  103086. if(eos){
  103087. os->e_o_s=1;
  103088. if(os->lacing_fill>0)
  103089. os->lacing_vals[os->lacing_fill-1]|=0x200;
  103090. }
  103091. os->pageno=pageno+1;
  103092. return(0);
  103093. }
  103094. /* clear things to an initial state. Good to call, eg, before seeking */
  103095. int ogg_sync_reset(ogg_sync_state *oy){
  103096. oy->fill=0;
  103097. oy->returned=0;
  103098. oy->unsynced=0;
  103099. oy->headerbytes=0;
  103100. oy->bodybytes=0;
  103101. return(0);
  103102. }
  103103. int ogg_stream_reset(ogg_stream_state *os){
  103104. os->body_fill=0;
  103105. os->body_returned=0;
  103106. os->lacing_fill=0;
  103107. os->lacing_packet=0;
  103108. os->lacing_returned=0;
  103109. os->header_fill=0;
  103110. os->e_o_s=0;
  103111. os->b_o_s=0;
  103112. os->pageno=-1;
  103113. os->packetno=0;
  103114. os->granulepos=0;
  103115. return(0);
  103116. }
  103117. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  103118. ogg_stream_reset(os);
  103119. os->serialno=serialno;
  103120. return(0);
  103121. }
  103122. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  103123. /* The last part of decode. We have the stream broken into packet
  103124. segments. Now we need to group them into packets (or return the
  103125. out of sync markers) */
  103126. int ptr=os->lacing_returned;
  103127. if(os->lacing_packet<=ptr)return(0);
  103128. if(os->lacing_vals[ptr]&0x400){
  103129. /* we need to tell the codec there's a gap; it might need to
  103130. handle previous packet dependencies. */
  103131. os->lacing_returned++;
  103132. os->packetno++;
  103133. return(-1);
  103134. }
  103135. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  103136. to ask if there's a whole packet
  103137. waiting */
  103138. /* Gather the whole packet. We'll have no holes or a partial packet */
  103139. {
  103140. int size=os->lacing_vals[ptr]&0xff;
  103141. int bytes=size;
  103142. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  103143. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  103144. while(size==255){
  103145. int val=os->lacing_vals[++ptr];
  103146. size=val&0xff;
  103147. if(val&0x200)eos=0x200;
  103148. bytes+=size;
  103149. }
  103150. if(op){
  103151. op->e_o_s=eos;
  103152. op->b_o_s=bos;
  103153. op->packet=os->body_data+os->body_returned;
  103154. op->packetno=os->packetno;
  103155. op->granulepos=os->granule_vals[ptr];
  103156. op->bytes=bytes;
  103157. }
  103158. if(adv){
  103159. os->body_returned+=bytes;
  103160. os->lacing_returned=ptr+1;
  103161. os->packetno++;
  103162. }
  103163. }
  103164. return(1);
  103165. }
  103166. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  103167. return _packetout(os,op,1);
  103168. }
  103169. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  103170. return _packetout(os,op,0);
  103171. }
  103172. void ogg_packet_clear(ogg_packet *op) {
  103173. _ogg_free(op->packet);
  103174. memset(op, 0, sizeof(*op));
  103175. }
  103176. #ifdef _V_SELFTEST
  103177. #include <stdio.h>
  103178. ogg_stream_state os_en, os_de;
  103179. ogg_sync_state oy;
  103180. void checkpacket(ogg_packet *op,int len, int no, int pos){
  103181. long j;
  103182. static int sequence=0;
  103183. static int lastno=0;
  103184. if(op->bytes!=len){
  103185. fprintf(stderr,"incorrect packet length!\n");
  103186. exit(1);
  103187. }
  103188. if(op->granulepos!=pos){
  103189. fprintf(stderr,"incorrect packet position!\n");
  103190. exit(1);
  103191. }
  103192. /* packet number just follows sequence/gap; adjust the input number
  103193. for that */
  103194. if(no==0){
  103195. sequence=0;
  103196. }else{
  103197. sequence++;
  103198. if(no>lastno+1)
  103199. sequence++;
  103200. }
  103201. lastno=no;
  103202. if(op->packetno!=sequence){
  103203. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  103204. (long)(op->packetno),sequence);
  103205. exit(1);
  103206. }
  103207. /* Test data */
  103208. for(j=0;j<op->bytes;j++)
  103209. if(op->packet[j]!=((j+no)&0xff)){
  103210. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  103211. j,op->packet[j],(j+no)&0xff);
  103212. exit(1);
  103213. }
  103214. }
  103215. void check_page(unsigned char *data,const int *header,ogg_page *og){
  103216. long j;
  103217. /* Test data */
  103218. for(j=0;j<og->body_len;j++)
  103219. if(og->body[j]!=data[j]){
  103220. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  103221. j,data[j],og->body[j]);
  103222. exit(1);
  103223. }
  103224. /* Test header */
  103225. for(j=0;j<og->header_len;j++){
  103226. if(og->header[j]!=header[j]){
  103227. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  103228. for(j=0;j<header[26]+27;j++)
  103229. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  103230. fprintf(stderr,"\n");
  103231. exit(1);
  103232. }
  103233. }
  103234. if(og->header_len!=header[26]+27){
  103235. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  103236. og->header_len,header[26]+27);
  103237. exit(1);
  103238. }
  103239. }
  103240. void print_header(ogg_page *og){
  103241. int j;
  103242. fprintf(stderr,"\nHEADER:\n");
  103243. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  103244. og->header[0],og->header[1],og->header[2],og->header[3],
  103245. (int)og->header[4],(int)og->header[5]);
  103246. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  103247. (og->header[9]<<24)|(og->header[8]<<16)|
  103248. (og->header[7]<<8)|og->header[6],
  103249. (og->header[17]<<24)|(og->header[16]<<16)|
  103250. (og->header[15]<<8)|og->header[14],
  103251. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  103252. (og->header[19]<<8)|og->header[18]);
  103253. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  103254. (int)og->header[22],(int)og->header[23],
  103255. (int)og->header[24],(int)og->header[25],
  103256. (int)og->header[26]);
  103257. for(j=27;j<og->header_len;j++)
  103258. fprintf(stderr,"%d ",(int)og->header[j]);
  103259. fprintf(stderr,")\n\n");
  103260. }
  103261. void copy_page(ogg_page *og){
  103262. unsigned char *temp=_ogg_malloc(og->header_len);
  103263. memcpy(temp,og->header,og->header_len);
  103264. og->header=temp;
  103265. temp=_ogg_malloc(og->body_len);
  103266. memcpy(temp,og->body,og->body_len);
  103267. og->body=temp;
  103268. }
  103269. void free_page(ogg_page *og){
  103270. _ogg_free (og->header);
  103271. _ogg_free (og->body);
  103272. }
  103273. void error(void){
  103274. fprintf(stderr,"error!\n");
  103275. exit(1);
  103276. }
  103277. /* 17 only */
  103278. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  103279. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103280. 0x01,0x02,0x03,0x04,0,0,0,0,
  103281. 0x15,0xed,0xec,0x91,
  103282. 1,
  103283. 17};
  103284. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  103285. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103286. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103287. 0x01,0x02,0x03,0x04,0,0,0,0,
  103288. 0x59,0x10,0x6c,0x2c,
  103289. 1,
  103290. 17};
  103291. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  103292. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  103293. 0x01,0x02,0x03,0x04,1,0,0,0,
  103294. 0x89,0x33,0x85,0xce,
  103295. 13,
  103296. 254,255,0,255,1,255,245,255,255,0,
  103297. 255,255,90};
  103298. /* nil packets; beginning,middle,end */
  103299. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103300. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103301. 0x01,0x02,0x03,0x04,0,0,0,0,
  103302. 0xff,0x7b,0x23,0x17,
  103303. 1,
  103304. 0};
  103305. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  103306. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  103307. 0x01,0x02,0x03,0x04,1,0,0,0,
  103308. 0x5c,0x3f,0x66,0xcb,
  103309. 17,
  103310. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  103311. 255,255,90,0};
  103312. /* large initial packet */
  103313. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103314. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103315. 0x01,0x02,0x03,0x04,0,0,0,0,
  103316. 0x01,0x27,0x31,0xaa,
  103317. 18,
  103318. 255,255,255,255,255,255,255,255,
  103319. 255,255,255,255,255,255,255,255,255,10};
  103320. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  103321. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  103322. 0x01,0x02,0x03,0x04,1,0,0,0,
  103323. 0x7f,0x4e,0x8a,0xd2,
  103324. 4,
  103325. 255,4,255,0};
  103326. /* continuing packet test */
  103327. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103328. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103329. 0x01,0x02,0x03,0x04,0,0,0,0,
  103330. 0xff,0x7b,0x23,0x17,
  103331. 1,
  103332. 0};
  103333. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  103334. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  103335. 0x01,0x02,0x03,0x04,1,0,0,0,
  103336. 0x54,0x05,0x51,0xc8,
  103337. 17,
  103338. 255,255,255,255,255,255,255,255,
  103339. 255,255,255,255,255,255,255,255,255};
  103340. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  103341. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  103342. 0x01,0x02,0x03,0x04,2,0,0,0,
  103343. 0xc8,0xc3,0xcb,0xed,
  103344. 5,
  103345. 10,255,4,255,0};
  103346. /* page with the 255 segment limit */
  103347. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103348. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103349. 0x01,0x02,0x03,0x04,0,0,0,0,
  103350. 0xff,0x7b,0x23,0x17,
  103351. 1,
  103352. 0};
  103353. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  103354. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  103355. 0x01,0x02,0x03,0x04,1,0,0,0,
  103356. 0xed,0x2a,0x2e,0xa7,
  103357. 255,
  103358. 10,10,10,10,10,10,10,10,
  103359. 10,10,10,10,10,10,10,10,
  103360. 10,10,10,10,10,10,10,10,
  103361. 10,10,10,10,10,10,10,10,
  103362. 10,10,10,10,10,10,10,10,
  103363. 10,10,10,10,10,10,10,10,
  103364. 10,10,10,10,10,10,10,10,
  103365. 10,10,10,10,10,10,10,10,
  103366. 10,10,10,10,10,10,10,10,
  103367. 10,10,10,10,10,10,10,10,
  103368. 10,10,10,10,10,10,10,10,
  103369. 10,10,10,10,10,10,10,10,
  103370. 10,10,10,10,10,10,10,10,
  103371. 10,10,10,10,10,10,10,10,
  103372. 10,10,10,10,10,10,10,10,
  103373. 10,10,10,10,10,10,10,10,
  103374. 10,10,10,10,10,10,10,10,
  103375. 10,10,10,10,10,10,10,10,
  103376. 10,10,10,10,10,10,10,10,
  103377. 10,10,10,10,10,10,10,10,
  103378. 10,10,10,10,10,10,10,10,
  103379. 10,10,10,10,10,10,10,10,
  103380. 10,10,10,10,10,10,10,10,
  103381. 10,10,10,10,10,10,10,10,
  103382. 10,10,10,10,10,10,10,10,
  103383. 10,10,10,10,10,10,10,10,
  103384. 10,10,10,10,10,10,10,10,
  103385. 10,10,10,10,10,10,10,10,
  103386. 10,10,10,10,10,10,10,10,
  103387. 10,10,10,10,10,10,10,10,
  103388. 10,10,10,10,10,10,10,10,
  103389. 10,10,10,10,10,10,10};
  103390. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  103391. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  103392. 0x01,0x02,0x03,0x04,2,0,0,0,
  103393. 0x6c,0x3b,0x82,0x3d,
  103394. 1,
  103395. 50};
  103396. /* packet that overspans over an entire page */
  103397. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103398. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103399. 0x01,0x02,0x03,0x04,0,0,0,0,
  103400. 0xff,0x7b,0x23,0x17,
  103401. 1,
  103402. 0};
  103403. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  103404. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  103405. 0x01,0x02,0x03,0x04,1,0,0,0,
  103406. 0x3c,0xd9,0x4d,0x3f,
  103407. 17,
  103408. 100,255,255,255,255,255,255,255,255,
  103409. 255,255,255,255,255,255,255,255};
  103410. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  103411. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  103412. 0x01,0x02,0x03,0x04,2,0,0,0,
  103413. 0x01,0xd2,0xe5,0xe5,
  103414. 17,
  103415. 255,255,255,255,255,255,255,255,
  103416. 255,255,255,255,255,255,255,255,255};
  103417. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  103418. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  103419. 0x01,0x02,0x03,0x04,3,0,0,0,
  103420. 0xef,0xdd,0x88,0xde,
  103421. 7,
  103422. 255,255,75,255,4,255,0};
  103423. /* packet that overspans over an entire page */
  103424. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103425. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103426. 0x01,0x02,0x03,0x04,0,0,0,0,
  103427. 0xff,0x7b,0x23,0x17,
  103428. 1,
  103429. 0};
  103430. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  103431. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  103432. 0x01,0x02,0x03,0x04,1,0,0,0,
  103433. 0x3c,0xd9,0x4d,0x3f,
  103434. 17,
  103435. 100,255,255,255,255,255,255,255,255,
  103436. 255,255,255,255,255,255,255,255};
  103437. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  103438. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  103439. 0x01,0x02,0x03,0x04,2,0,0,0,
  103440. 0xd4,0xe0,0x60,0xe5,
  103441. 1,0};
  103442. void test_pack(const int *pl, const int **headers, int byteskip,
  103443. int pageskip, int packetskip){
  103444. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  103445. long inptr=0;
  103446. long outptr=0;
  103447. long deptr=0;
  103448. long depacket=0;
  103449. long granule_pos=7,pageno=0;
  103450. int i,j,packets,pageout=pageskip;
  103451. int eosflag=0;
  103452. int bosflag=0;
  103453. int byteskipcount=0;
  103454. ogg_stream_reset(&os_en);
  103455. ogg_stream_reset(&os_de);
  103456. ogg_sync_reset(&oy);
  103457. for(packets=0;packets<packetskip;packets++)
  103458. depacket+=pl[packets];
  103459. for(packets=0;;packets++)if(pl[packets]==-1)break;
  103460. for(i=0;i<packets;i++){
  103461. /* construct a test packet */
  103462. ogg_packet op;
  103463. int len=pl[i];
  103464. op.packet=data+inptr;
  103465. op.bytes=len;
  103466. op.e_o_s=(pl[i+1]<0?1:0);
  103467. op.granulepos=granule_pos;
  103468. granule_pos+=1024;
  103469. for(j=0;j<len;j++)data[inptr++]=i+j;
  103470. /* submit the test packet */
  103471. ogg_stream_packetin(&os_en,&op);
  103472. /* retrieve any finished pages */
  103473. {
  103474. ogg_page og;
  103475. while(ogg_stream_pageout(&os_en,&og)){
  103476. /* We have a page. Check it carefully */
  103477. fprintf(stderr,"%ld, ",pageno);
  103478. if(headers[pageno]==NULL){
  103479. fprintf(stderr,"coded too many pages!\n");
  103480. exit(1);
  103481. }
  103482. check_page(data+outptr,headers[pageno],&og);
  103483. outptr+=og.body_len;
  103484. pageno++;
  103485. if(pageskip){
  103486. bosflag=1;
  103487. pageskip--;
  103488. deptr+=og.body_len;
  103489. }
  103490. /* have a complete page; submit it to sync/decode */
  103491. {
  103492. ogg_page og_de;
  103493. ogg_packet op_de,op_de2;
  103494. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  103495. char *next=buf;
  103496. byteskipcount+=og.header_len;
  103497. if(byteskipcount>byteskip){
  103498. memcpy(next,og.header,byteskipcount-byteskip);
  103499. next+=byteskipcount-byteskip;
  103500. byteskipcount=byteskip;
  103501. }
  103502. byteskipcount+=og.body_len;
  103503. if(byteskipcount>byteskip){
  103504. memcpy(next,og.body,byteskipcount-byteskip);
  103505. next+=byteskipcount-byteskip;
  103506. byteskipcount=byteskip;
  103507. }
  103508. ogg_sync_wrote(&oy,next-buf);
  103509. while(1){
  103510. int ret=ogg_sync_pageout(&oy,&og_de);
  103511. if(ret==0)break;
  103512. if(ret<0)continue;
  103513. /* got a page. Happy happy. Verify that it's good. */
  103514. fprintf(stderr,"(%ld), ",pageout);
  103515. check_page(data+deptr,headers[pageout],&og_de);
  103516. deptr+=og_de.body_len;
  103517. pageout++;
  103518. /* submit it to deconstitution */
  103519. ogg_stream_pagein(&os_de,&og_de);
  103520. /* packets out? */
  103521. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  103522. ogg_stream_packetpeek(&os_de,NULL);
  103523. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  103524. /* verify peek and out match */
  103525. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  103526. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  103527. depacket);
  103528. exit(1);
  103529. }
  103530. /* verify the packet! */
  103531. /* check data */
  103532. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  103533. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  103534. depacket);
  103535. exit(1);
  103536. }
  103537. /* check bos flag */
  103538. if(bosflag==0 && op_de.b_o_s==0){
  103539. fprintf(stderr,"b_o_s flag not set on packet!\n");
  103540. exit(1);
  103541. }
  103542. if(bosflag && op_de.b_o_s){
  103543. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  103544. exit(1);
  103545. }
  103546. bosflag=1;
  103547. depacket+=op_de.bytes;
  103548. /* check eos flag */
  103549. if(eosflag){
  103550. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  103551. exit(1);
  103552. }
  103553. if(op_de.e_o_s)eosflag=1;
  103554. /* check granulepos flag */
  103555. if(op_de.granulepos!=-1){
  103556. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  103557. }
  103558. }
  103559. }
  103560. }
  103561. }
  103562. }
  103563. }
  103564. _ogg_free(data);
  103565. if(headers[pageno]!=NULL){
  103566. fprintf(stderr,"did not write last page!\n");
  103567. exit(1);
  103568. }
  103569. if(headers[pageout]!=NULL){
  103570. fprintf(stderr,"did not decode last page!\n");
  103571. exit(1);
  103572. }
  103573. if(inptr!=outptr){
  103574. fprintf(stderr,"encoded page data incomplete!\n");
  103575. exit(1);
  103576. }
  103577. if(inptr!=deptr){
  103578. fprintf(stderr,"decoded page data incomplete!\n");
  103579. exit(1);
  103580. }
  103581. if(inptr!=depacket){
  103582. fprintf(stderr,"decoded packet data incomplete!\n");
  103583. exit(1);
  103584. }
  103585. if(!eosflag){
  103586. fprintf(stderr,"Never got a packet with EOS set!\n");
  103587. exit(1);
  103588. }
  103589. fprintf(stderr,"ok.\n");
  103590. }
  103591. int main(void){
  103592. ogg_stream_init(&os_en,0x04030201);
  103593. ogg_stream_init(&os_de,0x04030201);
  103594. ogg_sync_init(&oy);
  103595. /* Exercise each code path in the framing code. Also verify that
  103596. the checksums are working. */
  103597. {
  103598. /* 17 only */
  103599. const int packets[]={17, -1};
  103600. const int *headret[]={head1_0,NULL};
  103601. fprintf(stderr,"testing single page encoding... ");
  103602. test_pack(packets,headret,0,0,0);
  103603. }
  103604. {
  103605. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  103606. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  103607. const int *headret[]={head1_1,head2_1,NULL};
  103608. fprintf(stderr,"testing basic page encoding... ");
  103609. test_pack(packets,headret,0,0,0);
  103610. }
  103611. {
  103612. /* nil packets; beginning,middle,end */
  103613. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  103614. const int *headret[]={head1_2,head2_2,NULL};
  103615. fprintf(stderr,"testing basic nil packets... ");
  103616. test_pack(packets,headret,0,0,0);
  103617. }
  103618. {
  103619. /* large initial packet */
  103620. const int packets[]={4345,259,255,-1};
  103621. const int *headret[]={head1_3,head2_3,NULL};
  103622. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  103623. test_pack(packets,headret,0,0,0);
  103624. }
  103625. {
  103626. /* continuing packet test */
  103627. const int packets[]={0,4345,259,255,-1};
  103628. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  103629. fprintf(stderr,"testing single packet page span... ");
  103630. test_pack(packets,headret,0,0,0);
  103631. }
  103632. /* page with the 255 segment limit */
  103633. {
  103634. const int packets[]={0,10,10,10,10,10,10,10,10,
  103635. 10,10,10,10,10,10,10,10,
  103636. 10,10,10,10,10,10,10,10,
  103637. 10,10,10,10,10,10,10,10,
  103638. 10,10,10,10,10,10,10,10,
  103639. 10,10,10,10,10,10,10,10,
  103640. 10,10,10,10,10,10,10,10,
  103641. 10,10,10,10,10,10,10,10,
  103642. 10,10,10,10,10,10,10,10,
  103643. 10,10,10,10,10,10,10,10,
  103644. 10,10,10,10,10,10,10,10,
  103645. 10,10,10,10,10,10,10,10,
  103646. 10,10,10,10,10,10,10,10,
  103647. 10,10,10,10,10,10,10,10,
  103648. 10,10,10,10,10,10,10,10,
  103649. 10,10,10,10,10,10,10,10,
  103650. 10,10,10,10,10,10,10,10,
  103651. 10,10,10,10,10,10,10,10,
  103652. 10,10,10,10,10,10,10,10,
  103653. 10,10,10,10,10,10,10,10,
  103654. 10,10,10,10,10,10,10,10,
  103655. 10,10,10,10,10,10,10,10,
  103656. 10,10,10,10,10,10,10,10,
  103657. 10,10,10,10,10,10,10,10,
  103658. 10,10,10,10,10,10,10,10,
  103659. 10,10,10,10,10,10,10,10,
  103660. 10,10,10,10,10,10,10,10,
  103661. 10,10,10,10,10,10,10,10,
  103662. 10,10,10,10,10,10,10,10,
  103663. 10,10,10,10,10,10,10,10,
  103664. 10,10,10,10,10,10,10,10,
  103665. 10,10,10,10,10,10,10,50,-1};
  103666. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  103667. fprintf(stderr,"testing max packet segments... ");
  103668. test_pack(packets,headret,0,0,0);
  103669. }
  103670. {
  103671. /* packet that overspans over an entire page */
  103672. const int packets[]={0,100,9000,259,255,-1};
  103673. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  103674. fprintf(stderr,"testing very large packets... ");
  103675. test_pack(packets,headret,0,0,0);
  103676. }
  103677. {
  103678. /* test for the libogg 1.1.1 resync in large continuation bug
  103679. found by Josh Coalson) */
  103680. const int packets[]={0,100,9000,259,255,-1};
  103681. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  103682. fprintf(stderr,"testing continuation resync in very large packets... ");
  103683. test_pack(packets,headret,100,2,3);
  103684. }
  103685. {
  103686. /* term only page. why not? */
  103687. const int packets[]={0,100,4080,-1};
  103688. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  103689. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  103690. test_pack(packets,headret,0,0,0);
  103691. }
  103692. {
  103693. /* build a bunch of pages for testing */
  103694. unsigned char *data=_ogg_malloc(1024*1024);
  103695. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  103696. int inptr=0,i,j;
  103697. ogg_page og[5];
  103698. ogg_stream_reset(&os_en);
  103699. for(i=0;pl[i]!=-1;i++){
  103700. ogg_packet op;
  103701. int len=pl[i];
  103702. op.packet=data+inptr;
  103703. op.bytes=len;
  103704. op.e_o_s=(pl[i+1]<0?1:0);
  103705. op.granulepos=(i+1)*1000;
  103706. for(j=0;j<len;j++)data[inptr++]=i+j;
  103707. ogg_stream_packetin(&os_en,&op);
  103708. }
  103709. _ogg_free(data);
  103710. /* retrieve finished pages */
  103711. for(i=0;i<5;i++){
  103712. if(ogg_stream_pageout(&os_en,&og[i])==0){
  103713. fprintf(stderr,"Too few pages output building sync tests!\n");
  103714. exit(1);
  103715. }
  103716. copy_page(&og[i]);
  103717. }
  103718. /* Test lost pages on pagein/packetout: no rollback */
  103719. {
  103720. ogg_page temp;
  103721. ogg_packet test;
  103722. fprintf(stderr,"Testing loss of pages... ");
  103723. ogg_sync_reset(&oy);
  103724. ogg_stream_reset(&os_de);
  103725. for(i=0;i<5;i++){
  103726. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  103727. og[i].header_len);
  103728. ogg_sync_wrote(&oy,og[i].header_len);
  103729. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  103730. ogg_sync_wrote(&oy,og[i].body_len);
  103731. }
  103732. ogg_sync_pageout(&oy,&temp);
  103733. ogg_stream_pagein(&os_de,&temp);
  103734. ogg_sync_pageout(&oy,&temp);
  103735. ogg_stream_pagein(&os_de,&temp);
  103736. ogg_sync_pageout(&oy,&temp);
  103737. /* skip */
  103738. ogg_sync_pageout(&oy,&temp);
  103739. ogg_stream_pagein(&os_de,&temp);
  103740. /* do we get the expected results/packets? */
  103741. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103742. checkpacket(&test,0,0,0);
  103743. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103744. checkpacket(&test,100,1,-1);
  103745. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103746. checkpacket(&test,4079,2,3000);
  103747. if(ogg_stream_packetout(&os_de,&test)!=-1){
  103748. fprintf(stderr,"Error: loss of page did not return error\n");
  103749. exit(1);
  103750. }
  103751. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103752. checkpacket(&test,76,5,-1);
  103753. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103754. checkpacket(&test,34,6,-1);
  103755. fprintf(stderr,"ok.\n");
  103756. }
  103757. /* Test lost pages on pagein/packetout: rollback with continuation */
  103758. {
  103759. ogg_page temp;
  103760. ogg_packet test;
  103761. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  103762. ogg_sync_reset(&oy);
  103763. ogg_stream_reset(&os_de);
  103764. for(i=0;i<5;i++){
  103765. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  103766. og[i].header_len);
  103767. ogg_sync_wrote(&oy,og[i].header_len);
  103768. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  103769. ogg_sync_wrote(&oy,og[i].body_len);
  103770. }
  103771. ogg_sync_pageout(&oy,&temp);
  103772. ogg_stream_pagein(&os_de,&temp);
  103773. ogg_sync_pageout(&oy,&temp);
  103774. ogg_stream_pagein(&os_de,&temp);
  103775. ogg_sync_pageout(&oy,&temp);
  103776. ogg_stream_pagein(&os_de,&temp);
  103777. ogg_sync_pageout(&oy,&temp);
  103778. /* skip */
  103779. ogg_sync_pageout(&oy,&temp);
  103780. ogg_stream_pagein(&os_de,&temp);
  103781. /* do we get the expected results/packets? */
  103782. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103783. checkpacket(&test,0,0,0);
  103784. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103785. checkpacket(&test,100,1,-1);
  103786. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103787. checkpacket(&test,4079,2,3000);
  103788. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103789. checkpacket(&test,2956,3,4000);
  103790. if(ogg_stream_packetout(&os_de,&test)!=-1){
  103791. fprintf(stderr,"Error: loss of page did not return error\n");
  103792. exit(1);
  103793. }
  103794. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103795. checkpacket(&test,300,13,14000);
  103796. fprintf(stderr,"ok.\n");
  103797. }
  103798. /* the rest only test sync */
  103799. {
  103800. ogg_page og_de;
  103801. /* Test fractional page inputs: incomplete capture */
  103802. fprintf(stderr,"Testing sync on partial inputs... ");
  103803. ogg_sync_reset(&oy);
  103804. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103805. 3);
  103806. ogg_sync_wrote(&oy,3);
  103807. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103808. /* Test fractional page inputs: incomplete fixed header */
  103809. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  103810. 20);
  103811. ogg_sync_wrote(&oy,20);
  103812. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103813. /* Test fractional page inputs: incomplete header */
  103814. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  103815. 5);
  103816. ogg_sync_wrote(&oy,5);
  103817. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103818. /* Test fractional page inputs: incomplete body */
  103819. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  103820. og[1].header_len-28);
  103821. ogg_sync_wrote(&oy,og[1].header_len-28);
  103822. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103823. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  103824. ogg_sync_wrote(&oy,1000);
  103825. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103826. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  103827. og[1].body_len-1000);
  103828. ogg_sync_wrote(&oy,og[1].body_len-1000);
  103829. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103830. fprintf(stderr,"ok.\n");
  103831. }
  103832. /* Test fractional page inputs: page + incomplete capture */
  103833. {
  103834. ogg_page og_de;
  103835. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  103836. ogg_sync_reset(&oy);
  103837. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103838. og[1].header_len);
  103839. ogg_sync_wrote(&oy,og[1].header_len);
  103840. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103841. og[1].body_len);
  103842. ogg_sync_wrote(&oy,og[1].body_len);
  103843. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103844. 20);
  103845. ogg_sync_wrote(&oy,20);
  103846. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103847. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103848. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  103849. og[1].header_len-20);
  103850. ogg_sync_wrote(&oy,og[1].header_len-20);
  103851. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103852. og[1].body_len);
  103853. ogg_sync_wrote(&oy,og[1].body_len);
  103854. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103855. fprintf(stderr,"ok.\n");
  103856. }
  103857. /* Test recapture: garbage + page */
  103858. {
  103859. ogg_page og_de;
  103860. fprintf(stderr,"Testing search for capture... ");
  103861. ogg_sync_reset(&oy);
  103862. /* 'garbage' */
  103863. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103864. og[1].body_len);
  103865. ogg_sync_wrote(&oy,og[1].body_len);
  103866. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103867. og[1].header_len);
  103868. ogg_sync_wrote(&oy,og[1].header_len);
  103869. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103870. og[1].body_len);
  103871. ogg_sync_wrote(&oy,og[1].body_len);
  103872. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  103873. 20);
  103874. ogg_sync_wrote(&oy,20);
  103875. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103876. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103877. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103878. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  103879. og[2].header_len-20);
  103880. ogg_sync_wrote(&oy,og[2].header_len-20);
  103881. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  103882. og[2].body_len);
  103883. ogg_sync_wrote(&oy,og[2].body_len);
  103884. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103885. fprintf(stderr,"ok.\n");
  103886. }
  103887. /* Test recapture: page + garbage + page */
  103888. {
  103889. ogg_page og_de;
  103890. fprintf(stderr,"Testing recapture... ");
  103891. ogg_sync_reset(&oy);
  103892. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103893. og[1].header_len);
  103894. ogg_sync_wrote(&oy,og[1].header_len);
  103895. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103896. og[1].body_len);
  103897. ogg_sync_wrote(&oy,og[1].body_len);
  103898. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  103899. og[2].header_len);
  103900. ogg_sync_wrote(&oy,og[2].header_len);
  103901. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  103902. og[2].header_len);
  103903. ogg_sync_wrote(&oy,og[2].header_len);
  103904. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103905. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  103906. og[2].body_len-5);
  103907. ogg_sync_wrote(&oy,og[2].body_len-5);
  103908. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  103909. og[3].header_len);
  103910. ogg_sync_wrote(&oy,og[3].header_len);
  103911. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  103912. og[3].body_len);
  103913. ogg_sync_wrote(&oy,og[3].body_len);
  103914. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103915. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103916. fprintf(stderr,"ok.\n");
  103917. }
  103918. /* Free page data that was previously copied */
  103919. {
  103920. for(i=0;i<5;i++){
  103921. free_page(&og[i]);
  103922. }
  103923. }
  103924. }
  103925. return(0);
  103926. }
  103927. #endif
  103928. #endif
  103929. /********* End of inlined file: framing.c *********/
  103930. /********* Start of inlined file: analysis.c *********/
  103931. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  103932. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  103933. // tasks..
  103934. #ifdef _MSC_VER
  103935. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  103936. #endif
  103937. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  103938. #if JUCE_USE_OGGVORBIS
  103939. #include <stdio.h>
  103940. #include <string.h>
  103941. #include <math.h>
  103942. /********* Start of inlined file: codec_internal.h *********/
  103943. #ifndef _V_CODECI_H_
  103944. #define _V_CODECI_H_
  103945. /********* Start of inlined file: envelope.h *********/
  103946. #ifndef _V_ENVELOPE_
  103947. #define _V_ENVELOPE_
  103948. /********* Start of inlined file: mdct.h *********/
  103949. #ifndef _OGG_mdct_H_
  103950. #define _OGG_mdct_H_
  103951. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  103952. #ifdef MDCT_INTEGERIZED
  103953. #define DATA_TYPE int
  103954. #define REG_TYPE register int
  103955. #define TRIGBITS 14
  103956. #define cPI3_8 6270
  103957. #define cPI2_8 11585
  103958. #define cPI1_8 15137
  103959. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  103960. #define MULT_NORM(x) ((x)>>TRIGBITS)
  103961. #define HALVE(x) ((x)>>1)
  103962. #else
  103963. #define DATA_TYPE float
  103964. #define REG_TYPE float
  103965. #define cPI3_8 .38268343236508977175F
  103966. #define cPI2_8 .70710678118654752441F
  103967. #define cPI1_8 .92387953251128675613F
  103968. #define FLOAT_CONV(x) (x)
  103969. #define MULT_NORM(x) (x)
  103970. #define HALVE(x) ((x)*.5f)
  103971. #endif
  103972. typedef struct {
  103973. int n;
  103974. int log2n;
  103975. DATA_TYPE *trig;
  103976. int *bitrev;
  103977. DATA_TYPE scale;
  103978. } mdct_lookup;
  103979. extern void mdct_init(mdct_lookup *lookup,int n);
  103980. extern void mdct_clear(mdct_lookup *l);
  103981. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  103982. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  103983. #endif
  103984. /********* End of inlined file: mdct.h *********/
  103985. #define VE_PRE 16
  103986. #define VE_WIN 4
  103987. #define VE_POST 2
  103988. #define VE_AMP (VE_PRE+VE_POST-1)
  103989. #define VE_BANDS 7
  103990. #define VE_NEARDC 15
  103991. #define VE_MINSTRETCH 2 /* a bit less than short block */
  103992. #define VE_MAXSTRETCH 12 /* one-third full block */
  103993. typedef struct {
  103994. float ampbuf[VE_AMP];
  103995. int ampptr;
  103996. float nearDC[VE_NEARDC];
  103997. float nearDC_acc;
  103998. float nearDC_partialacc;
  103999. int nearptr;
  104000. } envelope_filter_state;
  104001. typedef struct {
  104002. int begin;
  104003. int end;
  104004. float *window;
  104005. float total;
  104006. } envelope_band;
  104007. typedef struct {
  104008. int ch;
  104009. int winlength;
  104010. int searchstep;
  104011. float minenergy;
  104012. mdct_lookup mdct;
  104013. float *mdct_win;
  104014. envelope_band band[VE_BANDS];
  104015. envelope_filter_state *filter;
  104016. int stretch;
  104017. int *mark;
  104018. long storage;
  104019. long current;
  104020. long curmark;
  104021. long cursor;
  104022. } envelope_lookup;
  104023. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  104024. extern void _ve_envelope_clear(envelope_lookup *e);
  104025. extern long _ve_envelope_search(vorbis_dsp_state *v);
  104026. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  104027. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  104028. #endif
  104029. /********* End of inlined file: envelope.h *********/
  104030. /********* Start of inlined file: codebook.h *********/
  104031. #ifndef _V_CODEBOOK_H_
  104032. #define _V_CODEBOOK_H_
  104033. /* This structure encapsulates huffman and VQ style encoding books; it
  104034. doesn't do anything specific to either.
  104035. valuelist/quantlist are nonNULL (and q_* significant) only if
  104036. there's entry->value mapping to be done.
  104037. If encode-side mapping must be done (and thus the entry needs to be
  104038. hunted), the auxiliary encode pointer will point to a decision
  104039. tree. This is true of both VQ and huffman, but is mostly useful
  104040. with VQ.
  104041. */
  104042. typedef struct static_codebook{
  104043. long dim; /* codebook dimensions (elements per vector) */
  104044. long entries; /* codebook entries */
  104045. long *lengthlist; /* codeword lengths in bits */
  104046. /* mapping ***************************************************************/
  104047. int maptype; /* 0=none
  104048. 1=implicitly populated values from map column
  104049. 2=listed arbitrary values */
  104050. /* The below does a linear, single monotonic sequence mapping. */
  104051. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  104052. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  104053. int q_quant; /* bits: 0 < quant <= 16 */
  104054. int q_sequencep; /* bitflag */
  104055. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  104056. map == 2: list of dim*entries quantized entry vals
  104057. */
  104058. /* encode helpers ********************************************************/
  104059. struct encode_aux_nearestmatch *nearest_tree;
  104060. struct encode_aux_threshmatch *thresh_tree;
  104061. struct encode_aux_pigeonhole *pigeon_tree;
  104062. int allocedp;
  104063. } static_codebook;
  104064. /* this structures an arbitrary trained book to quickly find the
  104065. nearest cell match */
  104066. typedef struct encode_aux_nearestmatch{
  104067. /* pre-calculated partitioning tree */
  104068. long *ptr0;
  104069. long *ptr1;
  104070. long *p; /* decision points (each is an entry) */
  104071. long *q; /* decision points (each is an entry) */
  104072. long aux; /* number of tree entries */
  104073. long alloc;
  104074. } encode_aux_nearestmatch;
  104075. /* assumes a maptype of 1; encode side only, so that's OK */
  104076. typedef struct encode_aux_threshmatch{
  104077. float *quantthresh;
  104078. long *quantmap;
  104079. int quantvals;
  104080. int threshvals;
  104081. } encode_aux_threshmatch;
  104082. typedef struct encode_aux_pigeonhole{
  104083. float min;
  104084. float del;
  104085. int mapentries;
  104086. int quantvals;
  104087. long *pigeonmap;
  104088. long fittotal;
  104089. long *fitlist;
  104090. long *fitmap;
  104091. long *fitlength;
  104092. } encode_aux_pigeonhole;
  104093. typedef struct codebook{
  104094. long dim; /* codebook dimensions (elements per vector) */
  104095. long entries; /* codebook entries */
  104096. long used_entries; /* populated codebook entries */
  104097. const static_codebook *c;
  104098. /* for encode, the below are entry-ordered, fully populated */
  104099. /* for decode, the below are ordered by bitreversed codeword and only
  104100. used entries are populated */
  104101. float *valuelist; /* list of dim*entries actual entry values */
  104102. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  104103. int *dec_index; /* only used if sparseness collapsed */
  104104. char *dec_codelengths;
  104105. ogg_uint32_t *dec_firsttable;
  104106. int dec_firsttablen;
  104107. int dec_maxlength;
  104108. } codebook;
  104109. extern void vorbis_staticbook_clear(static_codebook *b);
  104110. extern void vorbis_staticbook_destroy(static_codebook *b);
  104111. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  104112. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  104113. extern void vorbis_book_clear(codebook *b);
  104114. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  104115. extern float *_book_logdist(const static_codebook *b,float *vals);
  104116. extern float _float32_unpack(long val);
  104117. extern long _float32_pack(float val);
  104118. extern int _best(codebook *book, float *a, int step);
  104119. extern int _ilog(unsigned int v);
  104120. extern long _book_maptype1_quantvals(const static_codebook *b);
  104121. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  104122. extern long vorbis_book_codeword(codebook *book,int entry);
  104123. extern long vorbis_book_codelen(codebook *book,int entry);
  104124. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  104125. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  104126. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  104127. extern int vorbis_book_errorv(codebook *book, float *a);
  104128. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  104129. oggpack_buffer *b);
  104130. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  104131. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  104132. oggpack_buffer *b,int n);
  104133. extern long vorbis_book_decodev_set(codebook *book, float *a,
  104134. oggpack_buffer *b,int n);
  104135. extern long vorbis_book_decodev_add(codebook *book, float *a,
  104136. oggpack_buffer *b,int n);
  104137. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  104138. long off,int ch,
  104139. oggpack_buffer *b,int n);
  104140. #endif
  104141. /********* End of inlined file: codebook.h *********/
  104142. #define BLOCKTYPE_IMPULSE 0
  104143. #define BLOCKTYPE_PADDING 1
  104144. #define BLOCKTYPE_TRANSITION 0
  104145. #define BLOCKTYPE_LONG 1
  104146. #define PACKETBLOBS 15
  104147. typedef struct vorbis_block_internal{
  104148. float **pcmdelay; /* this is a pointer into local storage */
  104149. float ampmax;
  104150. int blocktype;
  104151. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  104152. blob [PACKETBLOBS/2] points to
  104153. the oggpack_buffer in the
  104154. main vorbis_block */
  104155. } vorbis_block_internal;
  104156. typedef void vorbis_look_floor;
  104157. typedef void vorbis_look_residue;
  104158. typedef void vorbis_look_transform;
  104159. /* mode ************************************************************/
  104160. typedef struct {
  104161. int blockflag;
  104162. int windowtype;
  104163. int transformtype;
  104164. int mapping;
  104165. } vorbis_info_mode;
  104166. typedef void vorbis_info_floor;
  104167. typedef void vorbis_info_residue;
  104168. typedef void vorbis_info_mapping;
  104169. /********* Start of inlined file: psy.h *********/
  104170. #ifndef _V_PSY_H_
  104171. #define _V_PSY_H_
  104172. /********* Start of inlined file: smallft.h *********/
  104173. #ifndef _V_SMFT_H_
  104174. #define _V_SMFT_H_
  104175. typedef struct {
  104176. int n;
  104177. float *trigcache;
  104178. int *splitcache;
  104179. } drft_lookup;
  104180. extern void drft_forward(drft_lookup *l,float *data);
  104181. extern void drft_backward(drft_lookup *l,float *data);
  104182. extern void drft_init(drft_lookup *l,int n);
  104183. extern void drft_clear(drft_lookup *l);
  104184. #endif
  104185. /********* End of inlined file: smallft.h *********/
  104186. /********* Start of inlined file: backends.h *********/
  104187. /* this is exposed up here because we need it for static modes.
  104188. Lookups for each backend aren't exposed because there's no reason
  104189. to do so */
  104190. #ifndef _vorbis_backend_h_
  104191. #define _vorbis_backend_h_
  104192. /* this would all be simpler/shorter with templates, but.... */
  104193. /* Floor backend generic *****************************************/
  104194. typedef struct{
  104195. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  104196. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  104197. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  104198. void (*free_info) (vorbis_info_floor *);
  104199. void (*free_look) (vorbis_look_floor *);
  104200. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  104201. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  104202. void *buffer,float *);
  104203. } vorbis_func_floor;
  104204. typedef struct{
  104205. int order;
  104206. long rate;
  104207. long barkmap;
  104208. int ampbits;
  104209. int ampdB;
  104210. int numbooks; /* <= 16 */
  104211. int books[16];
  104212. float lessthan; /* encode-only config setting hacks for libvorbis */
  104213. float greaterthan; /* encode-only config setting hacks for libvorbis */
  104214. } vorbis_info_floor0;
  104215. #define VIF_POSIT 63
  104216. #define VIF_CLASS 16
  104217. #define VIF_PARTS 31
  104218. typedef struct{
  104219. int partitions; /* 0 to 31 */
  104220. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  104221. int class_dim[VIF_CLASS]; /* 1 to 8 */
  104222. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  104223. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  104224. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  104225. int mult; /* 1 2 3 or 4 */
  104226. int postlist[VIF_POSIT+2]; /* first two implicit */
  104227. /* encode side analysis parameters */
  104228. float maxover;
  104229. float maxunder;
  104230. float maxerr;
  104231. float twofitweight;
  104232. float twofitatten;
  104233. int n;
  104234. } vorbis_info_floor1;
  104235. /* Residue backend generic *****************************************/
  104236. typedef struct{
  104237. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  104238. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  104239. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  104240. vorbis_info_residue *);
  104241. void (*free_info) (vorbis_info_residue *);
  104242. void (*free_look) (vorbis_look_residue *);
  104243. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  104244. float **,int *,int);
  104245. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  104246. vorbis_look_residue *,
  104247. float **,float **,int *,int,long **);
  104248. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  104249. float **,int *,int);
  104250. } vorbis_func_residue;
  104251. typedef struct vorbis_info_residue0{
  104252. /* block-partitioned VQ coded straight residue */
  104253. long begin;
  104254. long end;
  104255. /* first stage (lossless partitioning) */
  104256. int grouping; /* group n vectors per partition */
  104257. int partitions; /* possible codebooks for a partition */
  104258. int groupbook; /* huffbook for partitioning */
  104259. int secondstages[64]; /* expanded out to pointers in lookup */
  104260. int booklist[256]; /* list of second stage books */
  104261. float classmetric1[64];
  104262. float classmetric2[64];
  104263. } vorbis_info_residue0;
  104264. /* Mapping backend generic *****************************************/
  104265. typedef struct{
  104266. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  104267. oggpack_buffer *);
  104268. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  104269. void (*free_info) (vorbis_info_mapping *);
  104270. int (*forward) (struct vorbis_block *vb);
  104271. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  104272. } vorbis_func_mapping;
  104273. typedef struct vorbis_info_mapping0{
  104274. int submaps; /* <= 16 */
  104275. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  104276. int floorsubmap[16]; /* [mux] submap to floors */
  104277. int residuesubmap[16]; /* [mux] submap to residue */
  104278. int coupling_steps;
  104279. int coupling_mag[256];
  104280. int coupling_ang[256];
  104281. } vorbis_info_mapping0;
  104282. #endif
  104283. /********* End of inlined file: backends.h *********/
  104284. #ifndef EHMER_MAX
  104285. #define EHMER_MAX 56
  104286. #endif
  104287. /* psychoacoustic setup ********************************************/
  104288. #define P_BANDS 17 /* 62Hz to 16kHz */
  104289. #define P_LEVELS 8 /* 30dB to 100dB */
  104290. #define P_LEVEL_0 30. /* 30 dB */
  104291. #define P_NOISECURVES 3
  104292. #define NOISE_COMPAND_LEVELS 40
  104293. typedef struct vorbis_info_psy{
  104294. int blockflag;
  104295. float ath_adjatt;
  104296. float ath_maxatt;
  104297. float tone_masteratt[P_NOISECURVES];
  104298. float tone_centerboost;
  104299. float tone_decay;
  104300. float tone_abs_limit;
  104301. float toneatt[P_BANDS];
  104302. int noisemaskp;
  104303. float noisemaxsupp;
  104304. float noisewindowlo;
  104305. float noisewindowhi;
  104306. int noisewindowlomin;
  104307. int noisewindowhimin;
  104308. int noisewindowfixed;
  104309. float noiseoff[P_NOISECURVES][P_BANDS];
  104310. float noisecompand[NOISE_COMPAND_LEVELS];
  104311. float max_curve_dB;
  104312. int normal_channel_p;
  104313. int normal_point_p;
  104314. int normal_start;
  104315. int normal_partition;
  104316. double normal_thresh;
  104317. } vorbis_info_psy;
  104318. typedef struct{
  104319. int eighth_octave_lines;
  104320. /* for block long/short tuning; encode only */
  104321. float preecho_thresh[VE_BANDS];
  104322. float postecho_thresh[VE_BANDS];
  104323. float stretch_penalty;
  104324. float preecho_minenergy;
  104325. float ampmax_att_per_sec;
  104326. /* channel coupling config */
  104327. int coupling_pkHz[PACKETBLOBS];
  104328. int coupling_pointlimit[2][PACKETBLOBS];
  104329. int coupling_prepointamp[PACKETBLOBS];
  104330. int coupling_postpointamp[PACKETBLOBS];
  104331. int sliding_lowpass[2][PACKETBLOBS];
  104332. } vorbis_info_psy_global;
  104333. typedef struct {
  104334. float ampmax;
  104335. int channels;
  104336. vorbis_info_psy_global *gi;
  104337. int coupling_pointlimit[2][P_NOISECURVES];
  104338. } vorbis_look_psy_global;
  104339. typedef struct {
  104340. int n;
  104341. struct vorbis_info_psy *vi;
  104342. float ***tonecurves;
  104343. float **noiseoffset;
  104344. float *ath;
  104345. long *octave; /* in n.ocshift format */
  104346. long *bark;
  104347. long firstoc;
  104348. long shiftoc;
  104349. int eighth_octave_lines; /* power of two, please */
  104350. int total_octave_lines;
  104351. long rate; /* cache it */
  104352. float m_val; /* Masking compensation value */
  104353. } vorbis_look_psy;
  104354. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  104355. vorbis_info_psy_global *gi,int n,long rate);
  104356. extern void _vp_psy_clear(vorbis_look_psy *p);
  104357. extern void *_vi_psy_dup(void *source);
  104358. extern void _vi_psy_free(vorbis_info_psy *i);
  104359. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  104360. extern void _vp_remove_floor(vorbis_look_psy *p,
  104361. float *mdct,
  104362. int *icodedflr,
  104363. float *residue,
  104364. int sliding_lowpass);
  104365. extern void _vp_noisemask(vorbis_look_psy *p,
  104366. float *logmdct,
  104367. float *logmask);
  104368. extern void _vp_tonemask(vorbis_look_psy *p,
  104369. float *logfft,
  104370. float *logmask,
  104371. float global_specmax,
  104372. float local_specmax);
  104373. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  104374. float *noise,
  104375. float *tone,
  104376. int offset_select,
  104377. float *logmask,
  104378. float *mdct,
  104379. float *logmdct);
  104380. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  104381. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  104382. vorbis_info_psy_global *g,
  104383. vorbis_look_psy *p,
  104384. vorbis_info_mapping0 *vi,
  104385. float **mdct);
  104386. extern void _vp_couple(int blobno,
  104387. vorbis_info_psy_global *g,
  104388. vorbis_look_psy *p,
  104389. vorbis_info_mapping0 *vi,
  104390. float **res,
  104391. float **mag_memo,
  104392. int **mag_sort,
  104393. int **ifloor,
  104394. int *nonzero,
  104395. int sliding_lowpass);
  104396. extern void _vp_noise_normalize(vorbis_look_psy *p,
  104397. float *in,float *out,int *sortedindex);
  104398. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  104399. float *magnitudes,int *sortedindex);
  104400. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  104401. vorbis_look_psy *p,
  104402. vorbis_info_mapping0 *vi,
  104403. float **mags);
  104404. extern void hf_reduction(vorbis_info_psy_global *g,
  104405. vorbis_look_psy *p,
  104406. vorbis_info_mapping0 *vi,
  104407. float **mdct);
  104408. #endif
  104409. /********* End of inlined file: psy.h *********/
  104410. /********* Start of inlined file: bitrate.h *********/
  104411. #ifndef _V_BITRATE_H_
  104412. #define _V_BITRATE_H_
  104413. /********* Start of inlined file: os.h *********/
  104414. #ifndef _OS_H
  104415. #define _OS_H
  104416. /********************************************************************
  104417. * *
  104418. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  104419. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  104420. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  104421. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  104422. * *
  104423. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  104424. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  104425. * *
  104426. ********************************************************************
  104427. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  104428. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  104429. ********************************************************************/
  104430. #ifdef HAVE_CONFIG_H
  104431. #include "config.h"
  104432. #endif
  104433. #include <math.h>
  104434. /********* Start of inlined file: misc.h *********/
  104435. #ifndef _V_RANDOM_H_
  104436. #define _V_RANDOM_H_
  104437. extern int analysis_noisy;
  104438. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  104439. extern void _vorbis_block_ripcord(vorbis_block *vb);
  104440. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  104441. ogg_int64_t off);
  104442. #ifdef DEBUG_MALLOC
  104443. #define _VDBG_GRAPHFILE "malloc.m"
  104444. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  104445. extern void _VDBG_free(void *ptr,char *file,long line);
  104446. #ifndef MISC_C
  104447. #undef _ogg_malloc
  104448. #undef _ogg_calloc
  104449. #undef _ogg_realloc
  104450. #undef _ogg_free
  104451. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  104452. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  104453. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  104454. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  104455. #endif
  104456. #endif
  104457. #endif
  104458. /********* End of inlined file: misc.h *********/
  104459. #ifndef _V_IFDEFJAIL_H_
  104460. # define _V_IFDEFJAIL_H_
  104461. # ifdef __GNUC__
  104462. # define STIN static __inline__
  104463. # elif _WIN32
  104464. # define STIN static __inline
  104465. # else
  104466. # define STIN static
  104467. # endif
  104468. #ifdef DJGPP
  104469. # define rint(x) (floor((x)+0.5f))
  104470. #endif
  104471. #ifndef M_PI
  104472. # define M_PI (3.1415926536f)
  104473. #endif
  104474. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  104475. # include <malloc.h>
  104476. # define rint(x) (floor((x)+0.5f))
  104477. # define NO_FLOAT_MATH_LIB
  104478. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  104479. #endif
  104480. #if defined(__SYMBIAN32__) && defined(__WINS__)
  104481. void *_alloca(size_t size);
  104482. # define alloca _alloca
  104483. #endif
  104484. #ifndef FAST_HYPOT
  104485. # define FAST_HYPOT hypot
  104486. #endif
  104487. #endif
  104488. #ifdef HAVE_ALLOCA_H
  104489. # include <alloca.h>
  104490. #endif
  104491. #ifdef USE_MEMORY_H
  104492. # include <memory.h>
  104493. #endif
  104494. #ifndef min
  104495. # define min(x,y) ((x)>(y)?(y):(x))
  104496. #endif
  104497. #ifndef max
  104498. # define max(x,y) ((x)<(y)?(y):(x))
  104499. #endif
  104500. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  104501. # define VORBIS_FPU_CONTROL
  104502. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  104503. Because of encapsulation constraints (GCC can't see inside the asm
  104504. block and so we end up doing stupid things like a store/load that
  104505. is collectively a noop), we do it this way */
  104506. /* we must set up the fpu before this works!! */
  104507. typedef ogg_int16_t vorbis_fpu_control;
  104508. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  104509. ogg_int16_t ret;
  104510. ogg_int16_t temp;
  104511. __asm__ __volatile__("fnstcw %0\n\t"
  104512. "movw %0,%%dx\n\t"
  104513. "orw $62463,%%dx\n\t"
  104514. "movw %%dx,%1\n\t"
  104515. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  104516. *fpu=ret;
  104517. }
  104518. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  104519. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  104520. }
  104521. /* assumes the FPU is in round mode! */
  104522. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  104523. we get extra fst/fld to
  104524. truncate precision */
  104525. int i;
  104526. __asm__("fistl %0": "=m"(i) : "t"(f));
  104527. return(i);
  104528. }
  104529. #endif
  104530. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  104531. # define VORBIS_FPU_CONTROL
  104532. typedef ogg_int16_t vorbis_fpu_control;
  104533. static __inline int vorbis_ftoi(double f){
  104534. int i;
  104535. __asm{
  104536. fld f
  104537. fistp i
  104538. }
  104539. return i;
  104540. }
  104541. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  104542. }
  104543. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  104544. }
  104545. #endif
  104546. #ifndef VORBIS_FPU_CONTROL
  104547. typedef int vorbis_fpu_control;
  104548. static int vorbis_ftoi(double f){
  104549. return (int)(f+.5);
  104550. }
  104551. /* We don't have special code for this compiler/arch, so do it the slow way */
  104552. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  104553. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  104554. #endif
  104555. #endif /* _OS_H */
  104556. /********* End of inlined file: os.h *********/
  104557. /* encode side bitrate tracking */
  104558. typedef struct bitrate_manager_state {
  104559. int managed;
  104560. long avg_reservoir;
  104561. long minmax_reservoir;
  104562. long avg_bitsper;
  104563. long min_bitsper;
  104564. long max_bitsper;
  104565. long short_per_long;
  104566. double avgfloat;
  104567. vorbis_block *vb;
  104568. int choice;
  104569. } bitrate_manager_state;
  104570. typedef struct bitrate_manager_info{
  104571. long avg_rate;
  104572. long min_rate;
  104573. long max_rate;
  104574. long reservoir_bits;
  104575. double reservoir_bias;
  104576. double slew_damp;
  104577. } bitrate_manager_info;
  104578. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  104579. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  104580. extern int vorbis_bitrate_managed(vorbis_block *vb);
  104581. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  104582. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  104583. #endif
  104584. /********* End of inlined file: bitrate.h *********/
  104585. static int ilog(unsigned int v){
  104586. int ret=0;
  104587. while(v){
  104588. ret++;
  104589. v>>=1;
  104590. }
  104591. return(ret);
  104592. }
  104593. static int ilog2(unsigned int v){
  104594. int ret=0;
  104595. if(v)--v;
  104596. while(v){
  104597. ret++;
  104598. v>>=1;
  104599. }
  104600. return(ret);
  104601. }
  104602. typedef struct private_state {
  104603. /* local lookup storage */
  104604. envelope_lookup *ve; /* envelope lookup */
  104605. int window[2];
  104606. vorbis_look_transform **transform[2]; /* block, type */
  104607. drft_lookup fft_look[2];
  104608. int modebits;
  104609. vorbis_look_floor **flr;
  104610. vorbis_look_residue **residue;
  104611. vorbis_look_psy *psy;
  104612. vorbis_look_psy_global *psy_g_look;
  104613. /* local storage, only used on the encoding side. This way the
  104614. application does not need to worry about freeing some packets'
  104615. memory and not others'; packet storage is always tracked.
  104616. Cleared next call to a _dsp_ function */
  104617. unsigned char *header;
  104618. unsigned char *header1;
  104619. unsigned char *header2;
  104620. bitrate_manager_state bms;
  104621. ogg_int64_t sample_count;
  104622. } private_state;
  104623. /* codec_setup_info contains all the setup information specific to the
  104624. specific compression/decompression mode in progress (eg,
  104625. psychoacoustic settings, channel setup, options, codebook
  104626. etc).
  104627. *********************************************************************/
  104628. /********* Start of inlined file: highlevel.h *********/
  104629. typedef struct highlevel_byblocktype {
  104630. double tone_mask_setting;
  104631. double tone_peaklimit_setting;
  104632. double noise_bias_setting;
  104633. double noise_compand_setting;
  104634. } highlevel_byblocktype;
  104635. typedef struct highlevel_encode_setup {
  104636. void *setup;
  104637. int set_in_stone;
  104638. double base_setting;
  104639. double long_setting;
  104640. double short_setting;
  104641. double impulse_noisetune;
  104642. int managed;
  104643. long bitrate_min;
  104644. long bitrate_av;
  104645. double bitrate_av_damp;
  104646. long bitrate_max;
  104647. long bitrate_reservoir;
  104648. double bitrate_reservoir_bias;
  104649. int impulse_block_p;
  104650. int noise_normalize_p;
  104651. double stereo_point_setting;
  104652. double lowpass_kHz;
  104653. double ath_floating_dB;
  104654. double ath_absolute_dB;
  104655. double amplitude_track_dBpersec;
  104656. double trigger_setting;
  104657. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  104658. } highlevel_encode_setup;
  104659. /********* End of inlined file: highlevel.h *********/
  104660. typedef struct codec_setup_info {
  104661. /* Vorbis supports only short and long blocks, but allows the
  104662. encoder to choose the sizes */
  104663. long blocksizes[2];
  104664. /* modes are the primary means of supporting on-the-fly different
  104665. blocksizes, different channel mappings (LR or M/A),
  104666. different residue backends, etc. Each mode consists of a
  104667. blocksize flag and a mapping (along with the mapping setup */
  104668. int modes;
  104669. int maps;
  104670. int floors;
  104671. int residues;
  104672. int books;
  104673. int psys; /* encode only */
  104674. vorbis_info_mode *mode_param[64];
  104675. int map_type[64];
  104676. vorbis_info_mapping *map_param[64];
  104677. int floor_type[64];
  104678. vorbis_info_floor *floor_param[64];
  104679. int residue_type[64];
  104680. vorbis_info_residue *residue_param[64];
  104681. static_codebook *book_param[256];
  104682. codebook *fullbooks;
  104683. vorbis_info_psy *psy_param[4]; /* encode only */
  104684. vorbis_info_psy_global psy_g_param;
  104685. bitrate_manager_info bi;
  104686. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  104687. highly redundant structure, but
  104688. improves clarity of program flow. */
  104689. int halfrate_flag; /* painless downsample for decode */
  104690. } codec_setup_info;
  104691. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  104692. extern void _vp_global_free(vorbis_look_psy_global *look);
  104693. #endif
  104694. /********* End of inlined file: codec_internal.h *********/
  104695. /********* Start of inlined file: registry.h *********/
  104696. #ifndef _V_REG_H_
  104697. #define _V_REG_H_
  104698. #define VI_TRANSFORMB 1
  104699. #define VI_WINDOWB 1
  104700. #define VI_TIMEB 1
  104701. #define VI_FLOORB 2
  104702. #define VI_RESB 3
  104703. #define VI_MAPB 1
  104704. extern vorbis_func_floor *_floor_P[];
  104705. extern vorbis_func_residue *_residue_P[];
  104706. extern vorbis_func_mapping *_mapping_P[];
  104707. #endif
  104708. /********* End of inlined file: registry.h *********/
  104709. /********* Start of inlined file: scales.h *********/
  104710. #ifndef _V_SCALES_H_
  104711. #define _V_SCALES_H_
  104712. #include <math.h>
  104713. /* 20log10(x) */
  104714. #define VORBIS_IEEE_FLOAT32 1
  104715. #ifdef VORBIS_IEEE_FLOAT32
  104716. static float unitnorm(float x){
  104717. union {
  104718. ogg_uint32_t i;
  104719. float f;
  104720. } ix;
  104721. ix.f = x;
  104722. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  104723. return ix.f;
  104724. }
  104725. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  104726. static float todB(const float *x){
  104727. union {
  104728. ogg_uint32_t i;
  104729. float f;
  104730. } ix;
  104731. ix.f = *x;
  104732. ix.i = ix.i&0x7fffffff;
  104733. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  104734. }
  104735. #define todB_nn(x) todB(x)
  104736. #else
  104737. static float unitnorm(float x){
  104738. if(x<0)return(-1.f);
  104739. return(1.f);
  104740. }
  104741. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  104742. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  104743. #endif
  104744. #define fromdB(x) (exp((x)*.11512925f))
  104745. /* The bark scale equations are approximations, since the original
  104746. table was somewhat hand rolled. The below are chosen to have the
  104747. best possible fit to the rolled tables, thus their somewhat odd
  104748. appearance (these are more accurate and over a longer range than
  104749. the oft-quoted bark equations found in the texts I have). The
  104750. approximations are valid from 0 - 30kHz (nyquist) or so.
  104751. all f in Hz, z in Bark */
  104752. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  104753. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  104754. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  104755. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  104756. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  104757. 0.0 */
  104758. #define toOC(n) (log(n)*1.442695f-5.965784f)
  104759. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  104760. #endif
  104761. /********* End of inlined file: scales.h *********/
  104762. int analysis_noisy=1;
  104763. /* decides between modes, dispatches to the appropriate mapping. */
  104764. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  104765. int ret,i;
  104766. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  104767. vb->glue_bits=0;
  104768. vb->time_bits=0;
  104769. vb->floor_bits=0;
  104770. vb->res_bits=0;
  104771. /* first things first. Make sure encode is ready */
  104772. for(i=0;i<PACKETBLOBS;i++)
  104773. oggpack_reset(vbi->packetblob[i]);
  104774. /* we only have one mapping type (0), and we let the mapping code
  104775. itself figure out what soft mode to use. This allows easier
  104776. bitrate management */
  104777. if((ret=_mapping_P[0]->forward(vb)))
  104778. return(ret);
  104779. if(op){
  104780. if(vorbis_bitrate_managed(vb))
  104781. /* The app is using a bitmanaged mode... but not using the
  104782. bitrate management interface. */
  104783. return(OV_EINVAL);
  104784. op->packet=oggpack_get_buffer(&vb->opb);
  104785. op->bytes=oggpack_bytes(&vb->opb);
  104786. op->b_o_s=0;
  104787. op->e_o_s=vb->eofflag;
  104788. op->granulepos=vb->granulepos;
  104789. op->packetno=vb->sequence; /* for sake of completeness */
  104790. }
  104791. return(0);
  104792. }
  104793. /* there was no great place to put this.... */
  104794. void _analysis_output_always(char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  104795. int j;
  104796. FILE *of;
  104797. char buffer[80];
  104798. /* if(i==5870){*/
  104799. sprintf(buffer,"%s_%d.m",base,i);
  104800. of=fopen(buffer,"w");
  104801. if(!of)perror("failed to open data dump file");
  104802. for(j=0;j<n;j++){
  104803. if(bark){
  104804. float b=toBARK((4000.f*j/n)+.25);
  104805. fprintf(of,"%f ",b);
  104806. }else
  104807. if(off!=0)
  104808. fprintf(of,"%f ",(double)(j+off)/8000.);
  104809. else
  104810. fprintf(of,"%f ",(double)j);
  104811. if(dB){
  104812. float val;
  104813. if(v[j]==0.)
  104814. val=-140.;
  104815. else
  104816. val=todB(v+j);
  104817. fprintf(of,"%f\n",val);
  104818. }else{
  104819. fprintf(of,"%f\n",v[j]);
  104820. }
  104821. }
  104822. fclose(of);
  104823. /* } */
  104824. }
  104825. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  104826. ogg_int64_t off){
  104827. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  104828. }
  104829. #endif
  104830. /********* End of inlined file: analysis.c *********/
  104831. /********* Start of inlined file: bitrate.c *********/
  104832. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  104833. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104834. // tasks..
  104835. #ifdef _MSC_VER
  104836. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104837. #endif
  104838. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  104839. #if JUCE_USE_OGGVORBIS
  104840. #include <stdlib.h>
  104841. #include <string.h>
  104842. #include <math.h>
  104843. /* compute bitrate tracking setup */
  104844. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  104845. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  104846. bitrate_manager_info *bi=&ci->bi;
  104847. memset(bm,0,sizeof(*bm));
  104848. if(bi && (bi->reservoir_bits>0)){
  104849. long ratesamples=vi->rate;
  104850. int halfsamples=ci->blocksizes[0]>>1;
  104851. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  104852. bm->managed=1;
  104853. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  104854. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  104855. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  104856. bm->avgfloat=PACKETBLOBS/2;
  104857. /* not a necessary fix, but one that leads to a more balanced
  104858. typical initialization */
  104859. {
  104860. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  104861. bm->minmax_reservoir=desired_fill;
  104862. bm->avg_reservoir=desired_fill;
  104863. }
  104864. }
  104865. }
  104866. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  104867. memset(bm,0,sizeof(*bm));
  104868. return;
  104869. }
  104870. int vorbis_bitrate_managed(vorbis_block *vb){
  104871. vorbis_dsp_state *vd=vb->vd;
  104872. private_state *b=(private_state*)vd->backend_state;
  104873. bitrate_manager_state *bm=&b->bms;
  104874. if(bm && bm->managed)return(1);
  104875. return(0);
  104876. }
  104877. /* finish taking in the block we just processed */
  104878. int vorbis_bitrate_addblock(vorbis_block *vb){
  104879. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  104880. vorbis_dsp_state *vd=vb->vd;
  104881. private_state *b=(private_state*)vd->backend_state;
  104882. bitrate_manager_state *bm=&b->bms;
  104883. vorbis_info *vi=vd->vi;
  104884. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  104885. bitrate_manager_info *bi=&ci->bi;
  104886. int choice=rint(bm->avgfloat);
  104887. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104888. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  104889. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  104890. int samples=ci->blocksizes[vb->W]>>1;
  104891. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  104892. if(!bm->managed){
  104893. /* not a bitrate managed stream, but for API simplicity, we'll
  104894. buffer the packet to keep the code path clean */
  104895. if(bm->vb)return(-1); /* one has been submitted without
  104896. being claimed */
  104897. bm->vb=vb;
  104898. return(0);
  104899. }
  104900. bm->vb=vb;
  104901. /* look ahead for avg floater */
  104902. if(bm->avg_bitsper>0){
  104903. double slew=0.;
  104904. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  104905. double slewlimit= 15./bi->slew_damp;
  104906. /* choosing a new floater:
  104907. if we're over target, we slew down
  104908. if we're under target, we slew up
  104909. choose slew as follows: look through packetblobs of this frame
  104910. and set slew as the first in the appropriate direction that
  104911. gives us the slew we want. This may mean no slew if delta is
  104912. already favorable.
  104913. Then limit slew to slew max */
  104914. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  104915. while(choice>0 && this_bits>avg_target_bits &&
  104916. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  104917. choice--;
  104918. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104919. }
  104920. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  104921. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  104922. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  104923. choice++;
  104924. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104925. }
  104926. }
  104927. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  104928. if(slew<-slewlimit)slew=-slewlimit;
  104929. if(slew>slewlimit)slew=slewlimit;
  104930. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  104931. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104932. }
  104933. /* enforce min(if used) on the current floater (if used) */
  104934. if(bm->min_bitsper>0){
  104935. /* do we need to force the bitrate up? */
  104936. if(this_bits<min_target_bits){
  104937. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  104938. choice++;
  104939. if(choice>=PACKETBLOBS)break;
  104940. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104941. }
  104942. }
  104943. }
  104944. /* enforce max (if used) on the current floater (if used) */
  104945. if(bm->max_bitsper>0){
  104946. /* do we need to force the bitrate down? */
  104947. if(this_bits>max_target_bits){
  104948. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  104949. choice--;
  104950. if(choice<0)break;
  104951. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104952. }
  104953. }
  104954. }
  104955. /* Choice of packetblobs now made based on floater, and min/max
  104956. requirements. Now boundary check extreme choices */
  104957. if(choice<0){
  104958. /* choosing a smaller packetblob is insufficient to trim bitrate.
  104959. frame will need to be truncated */
  104960. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  104961. bm->choice=choice=0;
  104962. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  104963. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  104964. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104965. }
  104966. }else{
  104967. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  104968. if(choice>=PACKETBLOBS)
  104969. choice=PACKETBLOBS-1;
  104970. bm->choice=choice;
  104971. /* prop up bitrate according to demand. pad this frame out with zeroes */
  104972. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  104973. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  104974. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104975. }
  104976. /* now we have the final packet and the final packet size. Update statistics */
  104977. /* min and max reservoir */
  104978. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  104979. if(max_target_bits>0 && this_bits>max_target_bits){
  104980. bm->minmax_reservoir+=(this_bits-max_target_bits);
  104981. }else if(min_target_bits>0 && this_bits<min_target_bits){
  104982. bm->minmax_reservoir+=(this_bits-min_target_bits);
  104983. }else{
  104984. /* inbetween; we want to take reservoir toward but not past desired_fill */
  104985. if(bm->minmax_reservoir>desired_fill){
  104986. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  104987. bm->minmax_reservoir+=(this_bits-max_target_bits);
  104988. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  104989. }else{
  104990. bm->minmax_reservoir=desired_fill;
  104991. }
  104992. }else{
  104993. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  104994. bm->minmax_reservoir+=(this_bits-min_target_bits);
  104995. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  104996. }else{
  104997. bm->minmax_reservoir=desired_fill;
  104998. }
  104999. }
  105000. }
  105001. }
  105002. /* avg reservoir */
  105003. if(bm->avg_bitsper>0){
  105004. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  105005. bm->avg_reservoir+=this_bits-avg_target_bits;
  105006. }
  105007. return(0);
  105008. }
  105009. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  105010. private_state *b=(private_state*)vd->backend_state;
  105011. bitrate_manager_state *bm=&b->bms;
  105012. vorbis_block *vb=bm->vb;
  105013. int choice=PACKETBLOBS/2;
  105014. if(!vb)return 0;
  105015. if(op){
  105016. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  105017. if(vorbis_bitrate_managed(vb))
  105018. choice=bm->choice;
  105019. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  105020. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  105021. op->b_o_s=0;
  105022. op->e_o_s=vb->eofflag;
  105023. op->granulepos=vb->granulepos;
  105024. op->packetno=vb->sequence; /* for sake of completeness */
  105025. }
  105026. bm->vb=0;
  105027. return(1);
  105028. }
  105029. #endif
  105030. /********* End of inlined file: bitrate.c *********/
  105031. /********* Start of inlined file: block.c *********/
  105032. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105033. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105034. // tasks..
  105035. #ifdef _MSC_VER
  105036. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105037. #endif
  105038. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105039. #if JUCE_USE_OGGVORBIS
  105040. #include <stdio.h>
  105041. #include <stdlib.h>
  105042. #include <string.h>
  105043. /********* Start of inlined file: window.h *********/
  105044. #ifndef _V_WINDOW_
  105045. #define _V_WINDOW_
  105046. extern float *_vorbis_window_get(int n);
  105047. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  105048. int lW,int W,int nW);
  105049. #endif
  105050. /********* End of inlined file: window.h *********/
  105051. /********* Start of inlined file: lpc.h *********/
  105052. #ifndef _V_LPC_H_
  105053. #define _V_LPC_H_
  105054. /* simple linear scale LPC code */
  105055. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  105056. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  105057. float *data,long n);
  105058. #endif
  105059. /********* End of inlined file: lpc.h *********/
  105060. /* pcm accumulator examples (not exhaustive):
  105061. <-------------- lW ---------------->
  105062. <--------------- W ---------------->
  105063. : .....|..... _______________ |
  105064. : .''' | '''_--- | |\ |
  105065. :.....''' |_____--- '''......| | \_______|
  105066. :.................|__________________|_______|__|______|
  105067. |<------ Sl ------>| > Sr < |endW
  105068. |beginSl |endSl | |endSr
  105069. |beginW |endlW |beginSr
  105070. |< lW >|
  105071. <--------------- W ---------------->
  105072. | | .. ______________ |
  105073. | | ' `/ | ---_ |
  105074. |___.'___/`. | ---_____|
  105075. |_______|__|_______|_________________|
  105076. | >|Sl|< |<------ Sr ----->|endW
  105077. | | |endSl |beginSr |endSr
  105078. |beginW | |endlW
  105079. mult[0] |beginSl mult[n]
  105080. <-------------- lW ----------------->
  105081. |<--W-->|
  105082. : .............. ___ | |
  105083. : .''' |`/ \ | |
  105084. :.....''' |/`....\|...|
  105085. :.........................|___|___|___|
  105086. |Sl |Sr |endW
  105087. | | |endSr
  105088. | |beginSr
  105089. | |endSl
  105090. |beginSl
  105091. |beginW
  105092. */
  105093. /* block abstraction setup *********************************************/
  105094. #ifndef WORD_ALIGN
  105095. #define WORD_ALIGN 8
  105096. #endif
  105097. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  105098. int i;
  105099. memset(vb,0,sizeof(*vb));
  105100. vb->vd=v;
  105101. vb->localalloc=0;
  105102. vb->localstore=NULL;
  105103. if(v->analysisp){
  105104. vorbis_block_internal *vbi=(vorbis_block_internal*)
  105105. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  105106. vbi->ampmax=-9999;
  105107. for(i=0;i<PACKETBLOBS;i++){
  105108. if(i==PACKETBLOBS/2){
  105109. vbi->packetblob[i]=&vb->opb;
  105110. }else{
  105111. vbi->packetblob[i]=
  105112. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  105113. }
  105114. oggpack_writeinit(vbi->packetblob[i]);
  105115. }
  105116. }
  105117. return(0);
  105118. }
  105119. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  105120. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  105121. if(bytes+vb->localtop>vb->localalloc){
  105122. /* can't just _ogg_realloc... there are outstanding pointers */
  105123. if(vb->localstore){
  105124. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  105125. vb->totaluse+=vb->localtop;
  105126. link->next=vb->reap;
  105127. link->ptr=vb->localstore;
  105128. vb->reap=link;
  105129. }
  105130. /* highly conservative */
  105131. vb->localalloc=bytes;
  105132. vb->localstore=_ogg_malloc(vb->localalloc);
  105133. vb->localtop=0;
  105134. }
  105135. {
  105136. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  105137. vb->localtop+=bytes;
  105138. return ret;
  105139. }
  105140. }
  105141. /* reap the chain, pull the ripcord */
  105142. void _vorbis_block_ripcord(vorbis_block *vb){
  105143. /* reap the chain */
  105144. struct alloc_chain *reap=vb->reap;
  105145. while(reap){
  105146. struct alloc_chain *next=reap->next;
  105147. _ogg_free(reap->ptr);
  105148. memset(reap,0,sizeof(*reap));
  105149. _ogg_free(reap);
  105150. reap=next;
  105151. }
  105152. /* consolidate storage */
  105153. if(vb->totaluse){
  105154. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  105155. vb->localalloc+=vb->totaluse;
  105156. vb->totaluse=0;
  105157. }
  105158. /* pull the ripcord */
  105159. vb->localtop=0;
  105160. vb->reap=NULL;
  105161. }
  105162. int vorbis_block_clear(vorbis_block *vb){
  105163. int i;
  105164. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  105165. _vorbis_block_ripcord(vb);
  105166. if(vb->localstore)_ogg_free(vb->localstore);
  105167. if(vbi){
  105168. for(i=0;i<PACKETBLOBS;i++){
  105169. oggpack_writeclear(vbi->packetblob[i]);
  105170. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  105171. }
  105172. _ogg_free(vbi);
  105173. }
  105174. memset(vb,0,sizeof(*vb));
  105175. return(0);
  105176. }
  105177. /* Analysis side code, but directly related to blocking. Thus it's
  105178. here and not in analysis.c (which is for analysis transforms only).
  105179. The init is here because some of it is shared */
  105180. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  105181. int i;
  105182. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105183. private_state *b=NULL;
  105184. int hs;
  105185. if(ci==NULL) return 1;
  105186. hs=ci->halfrate_flag;
  105187. memset(v,0,sizeof(*v));
  105188. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  105189. v->vi=vi;
  105190. b->modebits=ilog2(ci->modes);
  105191. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  105192. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  105193. /* MDCT is tranform 0 */
  105194. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  105195. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  105196. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  105197. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  105198. /* Vorbis I uses only window type 0 */
  105199. b->window[0]=ilog2(ci->blocksizes[0])-6;
  105200. b->window[1]=ilog2(ci->blocksizes[1])-6;
  105201. if(encp){ /* encode/decode differ here */
  105202. /* analysis always needs an fft */
  105203. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  105204. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  105205. /* finish the codebooks */
  105206. if(!ci->fullbooks){
  105207. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  105208. for(i=0;i<ci->books;i++)
  105209. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  105210. }
  105211. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  105212. for(i=0;i<ci->psys;i++){
  105213. _vp_psy_init(b->psy+i,
  105214. ci->psy_param[i],
  105215. &ci->psy_g_param,
  105216. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  105217. vi->rate);
  105218. }
  105219. v->analysisp=1;
  105220. }else{
  105221. /* finish the codebooks */
  105222. if(!ci->fullbooks){
  105223. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  105224. for(i=0;i<ci->books;i++){
  105225. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  105226. /* decode codebooks are now standalone after init */
  105227. vorbis_staticbook_destroy(ci->book_param[i]);
  105228. ci->book_param[i]=NULL;
  105229. }
  105230. }
  105231. }
  105232. /* initialize the storage vectors. blocksize[1] is small for encode,
  105233. but the correct size for decode */
  105234. v->pcm_storage=ci->blocksizes[1];
  105235. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  105236. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  105237. {
  105238. int i;
  105239. for(i=0;i<vi->channels;i++)
  105240. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  105241. }
  105242. /* all 1 (large block) or 0 (small block) */
  105243. /* explicitly set for the sake of clarity */
  105244. v->lW=0; /* previous window size */
  105245. v->W=0; /* current window size */
  105246. /* all vector indexes */
  105247. v->centerW=ci->blocksizes[1]/2;
  105248. v->pcm_current=v->centerW;
  105249. /* initialize all the backend lookups */
  105250. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  105251. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  105252. for(i=0;i<ci->floors;i++)
  105253. b->flr[i]=_floor_P[ci->floor_type[i]]->
  105254. look(v,ci->floor_param[i]);
  105255. for(i=0;i<ci->residues;i++)
  105256. b->residue[i]=_residue_P[ci->residue_type[i]]->
  105257. look(v,ci->residue_param[i]);
  105258. return 0;
  105259. }
  105260. /* arbitrary settings and spec-mandated numbers get filled in here */
  105261. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  105262. private_state *b=NULL;
  105263. if(_vds_shared_init(v,vi,1))return 1;
  105264. b=(private_state*)v->backend_state;
  105265. b->psy_g_look=_vp_global_look(vi);
  105266. /* Initialize the envelope state storage */
  105267. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  105268. _ve_envelope_init(b->ve,vi);
  105269. vorbis_bitrate_init(vi,&b->bms);
  105270. /* compressed audio packets start after the headers
  105271. with sequence number 3 */
  105272. v->sequence=3;
  105273. return(0);
  105274. }
  105275. void vorbis_dsp_clear(vorbis_dsp_state *v){
  105276. int i;
  105277. if(v){
  105278. vorbis_info *vi=v->vi;
  105279. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  105280. private_state *b=(private_state*)v->backend_state;
  105281. if(b){
  105282. if(b->ve){
  105283. _ve_envelope_clear(b->ve);
  105284. _ogg_free(b->ve);
  105285. }
  105286. if(b->transform[0]){
  105287. mdct_clear((mdct_lookup*) b->transform[0][0]);
  105288. _ogg_free(b->transform[0][0]);
  105289. _ogg_free(b->transform[0]);
  105290. }
  105291. if(b->transform[1]){
  105292. mdct_clear((mdct_lookup*) b->transform[1][0]);
  105293. _ogg_free(b->transform[1][0]);
  105294. _ogg_free(b->transform[1]);
  105295. }
  105296. if(b->flr){
  105297. for(i=0;i<ci->floors;i++)
  105298. _floor_P[ci->floor_type[i]]->
  105299. free_look(b->flr[i]);
  105300. _ogg_free(b->flr);
  105301. }
  105302. if(b->residue){
  105303. for(i=0;i<ci->residues;i++)
  105304. _residue_P[ci->residue_type[i]]->
  105305. free_look(b->residue[i]);
  105306. _ogg_free(b->residue);
  105307. }
  105308. if(b->psy){
  105309. for(i=0;i<ci->psys;i++)
  105310. _vp_psy_clear(b->psy+i);
  105311. _ogg_free(b->psy);
  105312. }
  105313. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  105314. vorbis_bitrate_clear(&b->bms);
  105315. drft_clear(&b->fft_look[0]);
  105316. drft_clear(&b->fft_look[1]);
  105317. }
  105318. if(v->pcm){
  105319. for(i=0;i<vi->channels;i++)
  105320. if(v->pcm[i])_ogg_free(v->pcm[i]);
  105321. _ogg_free(v->pcm);
  105322. if(v->pcmret)_ogg_free(v->pcmret);
  105323. }
  105324. if(b){
  105325. /* free header, header1, header2 */
  105326. if(b->header)_ogg_free(b->header);
  105327. if(b->header1)_ogg_free(b->header1);
  105328. if(b->header2)_ogg_free(b->header2);
  105329. _ogg_free(b);
  105330. }
  105331. memset(v,0,sizeof(*v));
  105332. }
  105333. }
  105334. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  105335. int i;
  105336. vorbis_info *vi=v->vi;
  105337. private_state *b=(private_state*)v->backend_state;
  105338. /* free header, header1, header2 */
  105339. if(b->header)_ogg_free(b->header);b->header=NULL;
  105340. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  105341. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  105342. /* Do we have enough storage space for the requested buffer? If not,
  105343. expand the PCM (and envelope) storage */
  105344. if(v->pcm_current+vals>=v->pcm_storage){
  105345. v->pcm_storage=v->pcm_current+vals*2;
  105346. for(i=0;i<vi->channels;i++){
  105347. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  105348. }
  105349. }
  105350. for(i=0;i<vi->channels;i++)
  105351. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  105352. return(v->pcmret);
  105353. }
  105354. static void _preextrapolate_helper(vorbis_dsp_state *v){
  105355. int i;
  105356. int order=32;
  105357. float *lpc=(float*)alloca(order*sizeof(*lpc));
  105358. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  105359. long j;
  105360. v->preextrapolate=1;
  105361. if(v->pcm_current-v->centerW>order*2){ /* safety */
  105362. for(i=0;i<v->vi->channels;i++){
  105363. /* need to run the extrapolation in reverse! */
  105364. for(j=0;j<v->pcm_current;j++)
  105365. work[j]=v->pcm[i][v->pcm_current-j-1];
  105366. /* prime as above */
  105367. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  105368. /* run the predictor filter */
  105369. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  105370. order,
  105371. work+v->pcm_current-v->centerW,
  105372. v->centerW);
  105373. for(j=0;j<v->pcm_current;j++)
  105374. v->pcm[i][v->pcm_current-j-1]=work[j];
  105375. }
  105376. }
  105377. }
  105378. /* call with val<=0 to set eof */
  105379. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  105380. vorbis_info *vi=v->vi;
  105381. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105382. if(vals<=0){
  105383. int order=32;
  105384. int i;
  105385. float *lpc=(float*) alloca(order*sizeof(*lpc));
  105386. /* if it wasn't done earlier (very short sample) */
  105387. if(!v->preextrapolate)
  105388. _preextrapolate_helper(v);
  105389. /* We're encoding the end of the stream. Just make sure we have
  105390. [at least] a few full blocks of zeroes at the end. */
  105391. /* actually, we don't want zeroes; that could drop a large
  105392. amplitude off a cliff, creating spread spectrum noise that will
  105393. suck to encode. Extrapolate for the sake of cleanliness. */
  105394. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  105395. v->eofflag=v->pcm_current;
  105396. v->pcm_current+=ci->blocksizes[1]*3;
  105397. for(i=0;i<vi->channels;i++){
  105398. if(v->eofflag>order*2){
  105399. /* extrapolate with LPC to fill in */
  105400. long n;
  105401. /* make a predictor filter */
  105402. n=v->eofflag;
  105403. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  105404. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  105405. /* run the predictor filter */
  105406. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  105407. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  105408. }else{
  105409. /* not enough data to extrapolate (unlikely to happen due to
  105410. guarding the overlap, but bulletproof in case that
  105411. assumtion goes away). zeroes will do. */
  105412. memset(v->pcm[i]+v->eofflag,0,
  105413. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  105414. }
  105415. }
  105416. }else{
  105417. if(v->pcm_current+vals>v->pcm_storage)
  105418. return(OV_EINVAL);
  105419. v->pcm_current+=vals;
  105420. /* we may want to reverse extrapolate the beginning of a stream
  105421. too... in case we're beginning on a cliff! */
  105422. /* clumsy, but simple. It only runs once, so simple is good. */
  105423. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  105424. _preextrapolate_helper(v);
  105425. }
  105426. return(0);
  105427. }
  105428. /* do the deltas, envelope shaping, pre-echo and determine the size of
  105429. the next block on which to continue analysis */
  105430. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  105431. int i;
  105432. vorbis_info *vi=v->vi;
  105433. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105434. private_state *b=(private_state*)v->backend_state;
  105435. vorbis_look_psy_global *g=b->psy_g_look;
  105436. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  105437. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  105438. /* check to see if we're started... */
  105439. if(!v->preextrapolate)return(0);
  105440. /* check to see if we're done... */
  105441. if(v->eofflag==-1)return(0);
  105442. /* By our invariant, we have lW, W and centerW set. Search for
  105443. the next boundary so we can determine nW (the next window size)
  105444. which lets us compute the shape of the current block's window */
  105445. /* we do an envelope search even on a single blocksize; we may still
  105446. be throwing more bits at impulses, and envelope search handles
  105447. marking impulses too. */
  105448. {
  105449. long bp=_ve_envelope_search(v);
  105450. if(bp==-1){
  105451. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  105452. full long block */
  105453. v->nW=0;
  105454. }else{
  105455. if(ci->blocksizes[0]==ci->blocksizes[1])
  105456. v->nW=0;
  105457. else
  105458. v->nW=bp;
  105459. }
  105460. }
  105461. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  105462. {
  105463. /* center of next block + next block maximum right side. */
  105464. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  105465. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  105466. although this check is
  105467. less strict that the
  105468. _ve_envelope_search,
  105469. the search is not run
  105470. if we only use one
  105471. block size */
  105472. }
  105473. /* fill in the block. Note that for a short window, lW and nW are *short*
  105474. regardless of actual settings in the stream */
  105475. _vorbis_block_ripcord(vb);
  105476. vb->lW=v->lW;
  105477. vb->W=v->W;
  105478. vb->nW=v->nW;
  105479. if(v->W){
  105480. if(!v->lW || !v->nW){
  105481. vbi->blocktype=BLOCKTYPE_TRANSITION;
  105482. /*fprintf(stderr,"-");*/
  105483. }else{
  105484. vbi->blocktype=BLOCKTYPE_LONG;
  105485. /*fprintf(stderr,"_");*/
  105486. }
  105487. }else{
  105488. if(_ve_envelope_mark(v)){
  105489. vbi->blocktype=BLOCKTYPE_IMPULSE;
  105490. /*fprintf(stderr,"|");*/
  105491. }else{
  105492. vbi->blocktype=BLOCKTYPE_PADDING;
  105493. /*fprintf(stderr,".");*/
  105494. }
  105495. }
  105496. vb->vd=v;
  105497. vb->sequence=v->sequence++;
  105498. vb->granulepos=v->granulepos;
  105499. vb->pcmend=ci->blocksizes[v->W];
  105500. /* copy the vectors; this uses the local storage in vb */
  105501. /* this tracks 'strongest peak' for later psychoacoustics */
  105502. /* moved to the global psy state; clean this mess up */
  105503. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  105504. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  105505. vbi->ampmax=g->ampmax;
  105506. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  105507. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  105508. for(i=0;i<vi->channels;i++){
  105509. vbi->pcmdelay[i]=
  105510. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  105511. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  105512. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  105513. /* before we added the delay
  105514. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  105515. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  105516. */
  105517. }
  105518. /* handle eof detection: eof==0 means that we've not yet received EOF
  105519. eof>0 marks the last 'real' sample in pcm[]
  105520. eof<0 'no more to do'; doesn't get here */
  105521. if(v->eofflag){
  105522. if(v->centerW>=v->eofflag){
  105523. v->eofflag=-1;
  105524. vb->eofflag=1;
  105525. return(1);
  105526. }
  105527. }
  105528. /* advance storage vectors and clean up */
  105529. {
  105530. int new_centerNext=ci->blocksizes[1]/2;
  105531. int movementW=centerNext-new_centerNext;
  105532. if(movementW>0){
  105533. _ve_envelope_shift(b->ve,movementW);
  105534. v->pcm_current-=movementW;
  105535. for(i=0;i<vi->channels;i++)
  105536. memmove(v->pcm[i],v->pcm[i]+movementW,
  105537. v->pcm_current*sizeof(*v->pcm[i]));
  105538. v->lW=v->W;
  105539. v->W=v->nW;
  105540. v->centerW=new_centerNext;
  105541. if(v->eofflag){
  105542. v->eofflag-=movementW;
  105543. if(v->eofflag<=0)v->eofflag=-1;
  105544. /* do not add padding to end of stream! */
  105545. if(v->centerW>=v->eofflag){
  105546. v->granulepos+=movementW-(v->centerW-v->eofflag);
  105547. }else{
  105548. v->granulepos+=movementW;
  105549. }
  105550. }else{
  105551. v->granulepos+=movementW;
  105552. }
  105553. }
  105554. }
  105555. /* done */
  105556. return(1);
  105557. }
  105558. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  105559. vorbis_info *vi=v->vi;
  105560. codec_setup_info *ci;
  105561. int hs;
  105562. if(!v->backend_state)return -1;
  105563. if(!vi)return -1;
  105564. ci=(codec_setup_info*) vi->codec_setup;
  105565. if(!ci)return -1;
  105566. hs=ci->halfrate_flag;
  105567. v->centerW=ci->blocksizes[1]>>(hs+1);
  105568. v->pcm_current=v->centerW>>hs;
  105569. v->pcm_returned=-1;
  105570. v->granulepos=-1;
  105571. v->sequence=-1;
  105572. v->eofflag=0;
  105573. ((private_state *)(v->backend_state))->sample_count=-1;
  105574. return(0);
  105575. }
  105576. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  105577. if(_vds_shared_init(v,vi,0)) return 1;
  105578. vorbis_synthesis_restart(v);
  105579. return 0;
  105580. }
  105581. /* Unlike in analysis, the window is only partially applied for each
  105582. block. The time domain envelope is not yet handled at the point of
  105583. calling (as it relies on the previous block). */
  105584. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  105585. vorbis_info *vi=v->vi;
  105586. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105587. private_state *b=(private_state*)v->backend_state;
  105588. int hs=ci->halfrate_flag;
  105589. int i,j;
  105590. if(!vb)return(OV_EINVAL);
  105591. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  105592. v->lW=v->W;
  105593. v->W=vb->W;
  105594. v->nW=-1;
  105595. if((v->sequence==-1)||
  105596. (v->sequence+1 != vb->sequence)){
  105597. v->granulepos=-1; /* out of sequence; lose count */
  105598. b->sample_count=-1;
  105599. }
  105600. v->sequence=vb->sequence;
  105601. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  105602. was called on block */
  105603. int n=ci->blocksizes[v->W]>>(hs+1);
  105604. int n0=ci->blocksizes[0]>>(hs+1);
  105605. int n1=ci->blocksizes[1]>>(hs+1);
  105606. int thisCenter;
  105607. int prevCenter;
  105608. v->glue_bits+=vb->glue_bits;
  105609. v->time_bits+=vb->time_bits;
  105610. v->floor_bits+=vb->floor_bits;
  105611. v->res_bits+=vb->res_bits;
  105612. if(v->centerW){
  105613. thisCenter=n1;
  105614. prevCenter=0;
  105615. }else{
  105616. thisCenter=0;
  105617. prevCenter=n1;
  105618. }
  105619. /* v->pcm is now used like a two-stage double buffer. We don't want
  105620. to have to constantly shift *or* adjust memory usage. Don't
  105621. accept a new block until the old is shifted out */
  105622. for(j=0;j<vi->channels;j++){
  105623. /* the overlap/add section */
  105624. if(v->lW){
  105625. if(v->W){
  105626. /* large/large */
  105627. float *w=_vorbis_window_get(b->window[1]-hs);
  105628. float *pcm=v->pcm[j]+prevCenter;
  105629. float *p=vb->pcm[j];
  105630. for(i=0;i<n1;i++)
  105631. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  105632. }else{
  105633. /* large/small */
  105634. float *w=_vorbis_window_get(b->window[0]-hs);
  105635. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  105636. float *p=vb->pcm[j];
  105637. for(i=0;i<n0;i++)
  105638. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  105639. }
  105640. }else{
  105641. if(v->W){
  105642. /* small/large */
  105643. float *w=_vorbis_window_get(b->window[0]-hs);
  105644. float *pcm=v->pcm[j]+prevCenter;
  105645. float *p=vb->pcm[j]+n1/2-n0/2;
  105646. for(i=0;i<n0;i++)
  105647. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  105648. for(;i<n1/2+n0/2;i++)
  105649. pcm[i]=p[i];
  105650. }else{
  105651. /* small/small */
  105652. float *w=_vorbis_window_get(b->window[0]-hs);
  105653. float *pcm=v->pcm[j]+prevCenter;
  105654. float *p=vb->pcm[j];
  105655. for(i=0;i<n0;i++)
  105656. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  105657. }
  105658. }
  105659. /* the copy section */
  105660. {
  105661. float *pcm=v->pcm[j]+thisCenter;
  105662. float *p=vb->pcm[j]+n;
  105663. for(i=0;i<n;i++)
  105664. pcm[i]=p[i];
  105665. }
  105666. }
  105667. if(v->centerW)
  105668. v->centerW=0;
  105669. else
  105670. v->centerW=n1;
  105671. /* deal with initial packet state; we do this using the explicit
  105672. pcm_returned==-1 flag otherwise we're sensitive to first block
  105673. being short or long */
  105674. if(v->pcm_returned==-1){
  105675. v->pcm_returned=thisCenter;
  105676. v->pcm_current=thisCenter;
  105677. }else{
  105678. v->pcm_returned=prevCenter;
  105679. v->pcm_current=prevCenter+
  105680. ((ci->blocksizes[v->lW]/4+
  105681. ci->blocksizes[v->W]/4)>>hs);
  105682. }
  105683. }
  105684. /* track the frame number... This is for convenience, but also
  105685. making sure our last packet doesn't end with added padding. If
  105686. the last packet is partial, the number of samples we'll have to
  105687. return will be past the vb->granulepos.
  105688. This is not foolproof! It will be confused if we begin
  105689. decoding at the last page after a seek or hole. In that case,
  105690. we don't have a starting point to judge where the last frame
  105691. is. For this reason, vorbisfile will always try to make sure
  105692. it reads the last two marked pages in proper sequence */
  105693. if(b->sample_count==-1){
  105694. b->sample_count=0;
  105695. }else{
  105696. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  105697. }
  105698. if(v->granulepos==-1){
  105699. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  105700. v->granulepos=vb->granulepos;
  105701. /* is this a short page? */
  105702. if(b->sample_count>v->granulepos){
  105703. /* corner case; if this is both the first and last audio page,
  105704. then spec says the end is cut, not beginning */
  105705. if(vb->eofflag){
  105706. /* trim the end */
  105707. /* no preceeding granulepos; assume we started at zero (we'd
  105708. have to in a short single-page stream) */
  105709. /* granulepos could be -1 due to a seek, but that would result
  105710. in a long count, not short count */
  105711. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  105712. }else{
  105713. /* trim the beginning */
  105714. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  105715. if(v->pcm_returned>v->pcm_current)
  105716. v->pcm_returned=v->pcm_current;
  105717. }
  105718. }
  105719. }
  105720. }else{
  105721. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  105722. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  105723. if(v->granulepos>vb->granulepos){
  105724. long extra=v->granulepos-vb->granulepos;
  105725. if(extra)
  105726. if(vb->eofflag){
  105727. /* partial last frame. Strip the extra samples off */
  105728. v->pcm_current-=extra>>hs;
  105729. } /* else {Shouldn't happen *unless* the bitstream is out of
  105730. spec. Either way, believe the bitstream } */
  105731. } /* else {Shouldn't happen *unless* the bitstream is out of
  105732. spec. Either way, believe the bitstream } */
  105733. v->granulepos=vb->granulepos;
  105734. }
  105735. }
  105736. /* Update, cleanup */
  105737. if(vb->eofflag)v->eofflag=1;
  105738. return(0);
  105739. }
  105740. /* pcm==NULL indicates we just want the pending samples, no more */
  105741. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  105742. vorbis_info *vi=v->vi;
  105743. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  105744. if(pcm){
  105745. int i;
  105746. for(i=0;i<vi->channels;i++)
  105747. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  105748. *pcm=v->pcmret;
  105749. }
  105750. return(v->pcm_current-v->pcm_returned);
  105751. }
  105752. return(0);
  105753. }
  105754. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  105755. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  105756. v->pcm_returned+=n;
  105757. return(0);
  105758. }
  105759. /* intended for use with a specific vorbisfile feature; we want access
  105760. to the [usually synthetic/postextrapolated] buffer and lapping at
  105761. the end of a decode cycle, specifically, a half-short-block worth.
  105762. This funtion works like pcmout above, except it will also expose
  105763. this implicit buffer data not normally decoded. */
  105764. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  105765. vorbis_info *vi=v->vi;
  105766. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  105767. int hs=ci->halfrate_flag;
  105768. int n=ci->blocksizes[v->W]>>(hs+1);
  105769. int n0=ci->blocksizes[0]>>(hs+1);
  105770. int n1=ci->blocksizes[1]>>(hs+1);
  105771. int i,j;
  105772. if(v->pcm_returned<0)return 0;
  105773. /* our returned data ends at pcm_returned; because the synthesis pcm
  105774. buffer is a two-fragment ring, that means our data block may be
  105775. fragmented by buffering, wrapping or a short block not filling
  105776. out a buffer. To simplify things, we unfragment if it's at all
  105777. possibly needed. Otherwise, we'd need to call lapout more than
  105778. once as well as hold additional dsp state. Opt for
  105779. simplicity. */
  105780. /* centerW was advanced by blockin; it would be the center of the
  105781. *next* block */
  105782. if(v->centerW==n1){
  105783. /* the data buffer wraps; swap the halves */
  105784. /* slow, sure, small */
  105785. for(j=0;j<vi->channels;j++){
  105786. float *p=v->pcm[j];
  105787. for(i=0;i<n1;i++){
  105788. float temp=p[i];
  105789. p[i]=p[i+n1];
  105790. p[i+n1]=temp;
  105791. }
  105792. }
  105793. v->pcm_current-=n1;
  105794. v->pcm_returned-=n1;
  105795. v->centerW=0;
  105796. }
  105797. /* solidify buffer into contiguous space */
  105798. if((v->lW^v->W)==1){
  105799. /* long/short or short/long */
  105800. for(j=0;j<vi->channels;j++){
  105801. float *s=v->pcm[j];
  105802. float *d=v->pcm[j]+(n1-n0)/2;
  105803. for(i=(n1+n0)/2-1;i>=0;--i)
  105804. d[i]=s[i];
  105805. }
  105806. v->pcm_returned+=(n1-n0)/2;
  105807. v->pcm_current+=(n1-n0)/2;
  105808. }else{
  105809. if(v->lW==0){
  105810. /* short/short */
  105811. for(j=0;j<vi->channels;j++){
  105812. float *s=v->pcm[j];
  105813. float *d=v->pcm[j]+n1-n0;
  105814. for(i=n0-1;i>=0;--i)
  105815. d[i]=s[i];
  105816. }
  105817. v->pcm_returned+=n1-n0;
  105818. v->pcm_current+=n1-n0;
  105819. }
  105820. }
  105821. if(pcm){
  105822. int i;
  105823. for(i=0;i<vi->channels;i++)
  105824. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  105825. *pcm=v->pcmret;
  105826. }
  105827. return(n1+n-v->pcm_returned);
  105828. }
  105829. float *vorbis_window(vorbis_dsp_state *v,int W){
  105830. vorbis_info *vi=v->vi;
  105831. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  105832. int hs=ci->halfrate_flag;
  105833. private_state *b=(private_state*)v->backend_state;
  105834. if(b->window[W]-1<0)return NULL;
  105835. return _vorbis_window_get(b->window[W]-hs);
  105836. }
  105837. #endif
  105838. /********* End of inlined file: block.c *********/
  105839. /********* Start of inlined file: codebook.c *********/
  105840. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105841. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105842. // tasks..
  105843. #ifdef _MSC_VER
  105844. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105845. #endif
  105846. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105847. #if JUCE_USE_OGGVORBIS
  105848. #include <stdlib.h>
  105849. #include <string.h>
  105850. #include <math.h>
  105851. /* packs the given codebook into the bitstream **************************/
  105852. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  105853. long i,j;
  105854. int ordered=0;
  105855. /* first the basic parameters */
  105856. oggpack_write(opb,0x564342,24);
  105857. oggpack_write(opb,c->dim,16);
  105858. oggpack_write(opb,c->entries,24);
  105859. /* pack the codewords. There are two packings; length ordered and
  105860. length random. Decide between the two now. */
  105861. for(i=1;i<c->entries;i++)
  105862. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  105863. if(i==c->entries)ordered=1;
  105864. if(ordered){
  105865. /* length ordered. We only need to say how many codewords of
  105866. each length. The actual codewords are generated
  105867. deterministically */
  105868. long count=0;
  105869. oggpack_write(opb,1,1); /* ordered */
  105870. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  105871. for(i=1;i<c->entries;i++){
  105872. long thisx=c->lengthlist[i];
  105873. long last=c->lengthlist[i-1];
  105874. if(thisx>last){
  105875. for(j=last;j<thisx;j++){
  105876. oggpack_write(opb,i-count,_ilog(c->entries-count));
  105877. count=i;
  105878. }
  105879. }
  105880. }
  105881. oggpack_write(opb,i-count,_ilog(c->entries-count));
  105882. }else{
  105883. /* length random. Again, we don't code the codeword itself, just
  105884. the length. This time, though, we have to encode each length */
  105885. oggpack_write(opb,0,1); /* unordered */
  105886. /* algortihmic mapping has use for 'unused entries', which we tag
  105887. here. The algorithmic mapping happens as usual, but the unused
  105888. entry has no codeword. */
  105889. for(i=0;i<c->entries;i++)
  105890. if(c->lengthlist[i]==0)break;
  105891. if(i==c->entries){
  105892. oggpack_write(opb,0,1); /* no unused entries */
  105893. for(i=0;i<c->entries;i++)
  105894. oggpack_write(opb,c->lengthlist[i]-1,5);
  105895. }else{
  105896. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  105897. for(i=0;i<c->entries;i++){
  105898. if(c->lengthlist[i]==0){
  105899. oggpack_write(opb,0,1);
  105900. }else{
  105901. oggpack_write(opb,1,1);
  105902. oggpack_write(opb,c->lengthlist[i]-1,5);
  105903. }
  105904. }
  105905. }
  105906. }
  105907. /* is the entry number the desired return value, or do we have a
  105908. mapping? If we have a mapping, what type? */
  105909. oggpack_write(opb,c->maptype,4);
  105910. switch(c->maptype){
  105911. case 0:
  105912. /* no mapping */
  105913. break;
  105914. case 1:case 2:
  105915. /* implicitly populated value mapping */
  105916. /* explicitly populated value mapping */
  105917. if(!c->quantlist){
  105918. /* no quantlist? error */
  105919. return(-1);
  105920. }
  105921. /* values that define the dequantization */
  105922. oggpack_write(opb,c->q_min,32);
  105923. oggpack_write(opb,c->q_delta,32);
  105924. oggpack_write(opb,c->q_quant-1,4);
  105925. oggpack_write(opb,c->q_sequencep,1);
  105926. {
  105927. int quantvals;
  105928. switch(c->maptype){
  105929. case 1:
  105930. /* a single column of (c->entries/c->dim) quantized values for
  105931. building a full value list algorithmically (square lattice) */
  105932. quantvals=_book_maptype1_quantvals(c);
  105933. break;
  105934. case 2:
  105935. /* every value (c->entries*c->dim total) specified explicitly */
  105936. quantvals=c->entries*c->dim;
  105937. break;
  105938. default: /* NOT_REACHABLE */
  105939. quantvals=-1;
  105940. }
  105941. /* quantized values */
  105942. for(i=0;i<quantvals;i++)
  105943. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  105944. }
  105945. break;
  105946. default:
  105947. /* error case; we don't have any other map types now */
  105948. return(-1);
  105949. }
  105950. return(0);
  105951. }
  105952. /* unpacks a codebook from the packet buffer into the codebook struct,
  105953. readies the codebook auxiliary structures for decode *************/
  105954. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  105955. long i,j;
  105956. memset(s,0,sizeof(*s));
  105957. s->allocedp=1;
  105958. /* make sure alignment is correct */
  105959. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  105960. /* first the basic parameters */
  105961. s->dim=oggpack_read(opb,16);
  105962. s->entries=oggpack_read(opb,24);
  105963. if(s->entries==-1)goto _eofout;
  105964. /* codeword ordering.... length ordered or unordered? */
  105965. switch((int)oggpack_read(opb,1)){
  105966. case 0:
  105967. /* unordered */
  105968. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  105969. /* allocated but unused entries? */
  105970. if(oggpack_read(opb,1)){
  105971. /* yes, unused entries */
  105972. for(i=0;i<s->entries;i++){
  105973. if(oggpack_read(opb,1)){
  105974. long num=oggpack_read(opb,5);
  105975. if(num==-1)goto _eofout;
  105976. s->lengthlist[i]=num+1;
  105977. }else
  105978. s->lengthlist[i]=0;
  105979. }
  105980. }else{
  105981. /* all entries used; no tagging */
  105982. for(i=0;i<s->entries;i++){
  105983. long num=oggpack_read(opb,5);
  105984. if(num==-1)goto _eofout;
  105985. s->lengthlist[i]=num+1;
  105986. }
  105987. }
  105988. break;
  105989. case 1:
  105990. /* ordered */
  105991. {
  105992. long length=oggpack_read(opb,5)+1;
  105993. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  105994. for(i=0;i<s->entries;){
  105995. long num=oggpack_read(opb,_ilog(s->entries-i));
  105996. if(num==-1)goto _eofout;
  105997. for(j=0;j<num && i<s->entries;j++,i++)
  105998. s->lengthlist[i]=length;
  105999. length++;
  106000. }
  106001. }
  106002. break;
  106003. default:
  106004. /* EOF */
  106005. return(-1);
  106006. }
  106007. /* Do we have a mapping to unpack? */
  106008. switch((s->maptype=oggpack_read(opb,4))){
  106009. case 0:
  106010. /* no mapping */
  106011. break;
  106012. case 1: case 2:
  106013. /* implicitly populated value mapping */
  106014. /* explicitly populated value mapping */
  106015. s->q_min=oggpack_read(opb,32);
  106016. s->q_delta=oggpack_read(opb,32);
  106017. s->q_quant=oggpack_read(opb,4)+1;
  106018. s->q_sequencep=oggpack_read(opb,1);
  106019. {
  106020. int quantvals=0;
  106021. switch(s->maptype){
  106022. case 1:
  106023. quantvals=_book_maptype1_quantvals(s);
  106024. break;
  106025. case 2:
  106026. quantvals=s->entries*s->dim;
  106027. break;
  106028. }
  106029. /* quantized values */
  106030. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  106031. for(i=0;i<quantvals;i++)
  106032. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  106033. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  106034. }
  106035. break;
  106036. default:
  106037. goto _errout;
  106038. }
  106039. /* all set */
  106040. return(0);
  106041. _errout:
  106042. _eofout:
  106043. vorbis_staticbook_clear(s);
  106044. return(-1);
  106045. }
  106046. /* returns the number of bits ************************************************/
  106047. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  106048. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  106049. return(book->c->lengthlist[a]);
  106050. }
  106051. /* One the encode side, our vector writers are each designed for a
  106052. specific purpose, and the encoder is not flexible without modification:
  106053. The LSP vector coder uses a single stage nearest-match with no
  106054. interleave, so no step and no error return. This is specced by floor0
  106055. and doesn't change.
  106056. Residue0 encoding interleaves, uses multiple stages, and each stage
  106057. peels of a specific amount of resolution from a lattice (thus we want
  106058. to match by threshold, not nearest match). Residue doesn't *have* to
  106059. be encoded that way, but to change it, one will need to add more
  106060. infrastructure on the encode side (decode side is specced and simpler) */
  106061. /* floor0 LSP (single stage, non interleaved, nearest match) */
  106062. /* returns entry number and *modifies a* to the quantization value *****/
  106063. int vorbis_book_errorv(codebook *book,float *a){
  106064. int dim=book->dim,k;
  106065. int best=_best(book,a,1);
  106066. for(k=0;k<dim;k++)
  106067. a[k]=(book->valuelist+best*dim)[k];
  106068. return(best);
  106069. }
  106070. /* returns the number of bits and *modifies a* to the quantization value *****/
  106071. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  106072. int k,dim=book->dim;
  106073. for(k=0;k<dim;k++)
  106074. a[k]=(book->valuelist+best*dim)[k];
  106075. return(vorbis_book_encode(book,best,b));
  106076. }
  106077. /* the 'eliminate the decode tree' optimization actually requires the
  106078. codewords to be MSb first, not LSb. This is an annoying inelegancy
  106079. (and one of the first places where carefully thought out design
  106080. turned out to be wrong; Vorbis II and future Ogg codecs should go
  106081. to an MSb bitpacker), but not actually the huge hit it appears to
  106082. be. The first-stage decode table catches most words so that
  106083. bitreverse is not in the main execution path. */
  106084. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  106085. int read=book->dec_maxlength;
  106086. long lo,hi;
  106087. long lok = oggpack_look(b,book->dec_firsttablen);
  106088. if (lok >= 0) {
  106089. long entry = book->dec_firsttable[lok];
  106090. if(entry&0x80000000UL){
  106091. lo=(entry>>15)&0x7fff;
  106092. hi=book->used_entries-(entry&0x7fff);
  106093. }else{
  106094. oggpack_adv(b, book->dec_codelengths[entry-1]);
  106095. return(entry-1);
  106096. }
  106097. }else{
  106098. lo=0;
  106099. hi=book->used_entries;
  106100. }
  106101. lok = oggpack_look(b, read);
  106102. while(lok<0 && read>1)
  106103. lok = oggpack_look(b, --read);
  106104. if(lok<0)return -1;
  106105. /* bisect search for the codeword in the ordered list */
  106106. {
  106107. ogg_uint32_t testword=bitreverse((ogg_uint32_t)lok);
  106108. while(hi-lo>1){
  106109. long p=(hi-lo)>>1;
  106110. long test=book->codelist[lo+p]>testword;
  106111. lo+=p&(test-1);
  106112. hi-=p&(-test);
  106113. }
  106114. if(book->dec_codelengths[lo]<=read){
  106115. oggpack_adv(b, book->dec_codelengths[lo]);
  106116. return(lo);
  106117. }
  106118. }
  106119. oggpack_adv(b, read);
  106120. return(-1);
  106121. }
  106122. /* Decode side is specced and easier, because we don't need to find
  106123. matches using different criteria; we simply read and map. There are
  106124. two things we need to do 'depending':
  106125. We may need to support interleave. We don't really, but it's
  106126. convenient to do it here rather than rebuild the vector later.
  106127. Cascades may be additive or multiplicitive; this is not inherent in
  106128. the codebook, but set in the code using the codebook. Like
  106129. interleaving, it's easiest to do it here.
  106130. addmul==0 -> declarative (set the value)
  106131. addmul==1 -> additive
  106132. addmul==2 -> multiplicitive */
  106133. /* returns the [original, not compacted] entry number or -1 on eof *********/
  106134. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  106135. long packed_entry=decode_packed_entry_number(book,b);
  106136. if(packed_entry>=0)
  106137. return(book->dec_index[packed_entry]);
  106138. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  106139. return(packed_entry);
  106140. }
  106141. /* returns 0 on OK or -1 on eof *************************************/
  106142. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  106143. int step=n/book->dim;
  106144. long *entry = (long*)alloca(sizeof(*entry)*step);
  106145. float **t = (float**)alloca(sizeof(*t)*step);
  106146. int i,j,o;
  106147. for (i = 0; i < step; i++) {
  106148. entry[i]=decode_packed_entry_number(book,b);
  106149. if(entry[i]==-1)return(-1);
  106150. t[i] = book->valuelist+entry[i]*book->dim;
  106151. }
  106152. for(i=0,o=0;i<book->dim;i++,o+=step)
  106153. for (j=0;j<step;j++)
  106154. a[o+j]+=t[j][i];
  106155. return(0);
  106156. }
  106157. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  106158. int i,j,entry;
  106159. float *t;
  106160. if(book->dim>8){
  106161. for(i=0;i<n;){
  106162. entry = decode_packed_entry_number(book,b);
  106163. if(entry==-1)return(-1);
  106164. t = book->valuelist+entry*book->dim;
  106165. for (j=0;j<book->dim;)
  106166. a[i++]+=t[j++];
  106167. }
  106168. }else{
  106169. for(i=0;i<n;){
  106170. entry = decode_packed_entry_number(book,b);
  106171. if(entry==-1)return(-1);
  106172. t = book->valuelist+entry*book->dim;
  106173. j=0;
  106174. switch((int)book->dim){
  106175. case 8:
  106176. a[i++]+=t[j++];
  106177. case 7:
  106178. a[i++]+=t[j++];
  106179. case 6:
  106180. a[i++]+=t[j++];
  106181. case 5:
  106182. a[i++]+=t[j++];
  106183. case 4:
  106184. a[i++]+=t[j++];
  106185. case 3:
  106186. a[i++]+=t[j++];
  106187. case 2:
  106188. a[i++]+=t[j++];
  106189. case 1:
  106190. a[i++]+=t[j++];
  106191. case 0:
  106192. break;
  106193. }
  106194. }
  106195. }
  106196. return(0);
  106197. }
  106198. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  106199. int i,j,entry;
  106200. float *t;
  106201. for(i=0;i<n;){
  106202. entry = decode_packed_entry_number(book,b);
  106203. if(entry==-1)return(-1);
  106204. t = book->valuelist+entry*book->dim;
  106205. for (j=0;j<book->dim;)
  106206. a[i++]=t[j++];
  106207. }
  106208. return(0);
  106209. }
  106210. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  106211. oggpack_buffer *b,int n){
  106212. long i,j,entry;
  106213. int chptr=0;
  106214. for(i=offset/ch;i<(offset+n)/ch;){
  106215. entry = decode_packed_entry_number(book,b);
  106216. if(entry==-1)return(-1);
  106217. {
  106218. const float *t = book->valuelist+entry*book->dim;
  106219. for (j=0;j<book->dim;j++){
  106220. a[chptr++][i]+=t[j];
  106221. if(chptr==ch){
  106222. chptr=0;
  106223. i++;
  106224. }
  106225. }
  106226. }
  106227. }
  106228. return(0);
  106229. }
  106230. #ifdef _V_SELFTEST
  106231. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  106232. number of vectors through (keeping track of the quantized values),
  106233. and decode using the unpacked book. quantized version of in should
  106234. exactly equal out */
  106235. #include <stdio.h>
  106236. #include "vorbis/book/lsp20_0.vqh"
  106237. #include "vorbis/book/res0a_13.vqh"
  106238. #define TESTSIZE 40
  106239. float test1[TESTSIZE]={
  106240. 0.105939f,
  106241. 0.215373f,
  106242. 0.429117f,
  106243. 0.587974f,
  106244. 0.181173f,
  106245. 0.296583f,
  106246. 0.515707f,
  106247. 0.715261f,
  106248. 0.162327f,
  106249. 0.263834f,
  106250. 0.342876f,
  106251. 0.406025f,
  106252. 0.103571f,
  106253. 0.223561f,
  106254. 0.368513f,
  106255. 0.540313f,
  106256. 0.136672f,
  106257. 0.395882f,
  106258. 0.587183f,
  106259. 0.652476f,
  106260. 0.114338f,
  106261. 0.417300f,
  106262. 0.525486f,
  106263. 0.698679f,
  106264. 0.147492f,
  106265. 0.324481f,
  106266. 0.643089f,
  106267. 0.757582f,
  106268. 0.139556f,
  106269. 0.215795f,
  106270. 0.324559f,
  106271. 0.399387f,
  106272. 0.120236f,
  106273. 0.267420f,
  106274. 0.446940f,
  106275. 0.608760f,
  106276. 0.115587f,
  106277. 0.287234f,
  106278. 0.571081f,
  106279. 0.708603f,
  106280. };
  106281. float test3[TESTSIZE]={
  106282. 0,1,-2,3,4,-5,6,7,8,9,
  106283. 8,-2,7,-1,4,6,8,3,1,-9,
  106284. 10,11,12,13,14,15,26,17,18,19,
  106285. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  106286. static_codebook *testlist[]={&_vq_book_lsp20_0,
  106287. &_vq_book_res0a_13,NULL};
  106288. float *testvec[]={test1,test3};
  106289. int main(){
  106290. oggpack_buffer write;
  106291. oggpack_buffer read;
  106292. long ptr=0,i;
  106293. oggpack_writeinit(&write);
  106294. fprintf(stderr,"Testing codebook abstraction...:\n");
  106295. while(testlist[ptr]){
  106296. codebook c;
  106297. static_codebook s;
  106298. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  106299. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  106300. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  106301. memset(iv,0,sizeof(*iv)*TESTSIZE);
  106302. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  106303. /* pack the codebook, write the testvector */
  106304. oggpack_reset(&write);
  106305. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  106306. we can write */
  106307. vorbis_staticbook_pack(testlist[ptr],&write);
  106308. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  106309. for(i=0;i<TESTSIZE;i+=c.dim){
  106310. int best=_best(&c,qv+i,1);
  106311. vorbis_book_encodev(&c,best,qv+i,&write);
  106312. }
  106313. vorbis_book_clear(&c);
  106314. fprintf(stderr,"OK.\n");
  106315. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  106316. /* transfer the write data to a read buffer and unpack/read */
  106317. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  106318. if(vorbis_staticbook_unpack(&read,&s)){
  106319. fprintf(stderr,"Error unpacking codebook.\n");
  106320. exit(1);
  106321. }
  106322. if(vorbis_book_init_decode(&c,&s)){
  106323. fprintf(stderr,"Error initializing codebook.\n");
  106324. exit(1);
  106325. }
  106326. for(i=0;i<TESTSIZE;i+=c.dim)
  106327. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  106328. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  106329. exit(1);
  106330. }
  106331. for(i=0;i<TESTSIZE;i++)
  106332. if(fabs(qv[i]-iv[i])>.000001){
  106333. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  106334. iv[i],qv[i],i);
  106335. exit(1);
  106336. }
  106337. fprintf(stderr,"OK\n");
  106338. ptr++;
  106339. }
  106340. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  106341. exit(0);
  106342. }
  106343. #endif
  106344. #endif
  106345. /********* End of inlined file: codebook.c *********/
  106346. /********* Start of inlined file: envelope.c *********/
  106347. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106348. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106349. // tasks..
  106350. #ifdef _MSC_VER
  106351. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106352. #endif
  106353. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106354. #if JUCE_USE_OGGVORBIS
  106355. #include <stdlib.h>
  106356. #include <string.h>
  106357. #include <stdio.h>
  106358. #include <math.h>
  106359. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  106360. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106361. vorbis_info_psy_global *gi=&ci->psy_g_param;
  106362. int ch=vi->channels;
  106363. int i,j;
  106364. int n=e->winlength=128;
  106365. e->searchstep=64; /* not random */
  106366. e->minenergy=gi->preecho_minenergy;
  106367. e->ch=ch;
  106368. e->storage=128;
  106369. e->cursor=ci->blocksizes[1]/2;
  106370. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  106371. mdct_init(&e->mdct,n);
  106372. for(i=0;i<n;i++){
  106373. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  106374. e->mdct_win[i]*=e->mdct_win[i];
  106375. }
  106376. /* magic follows */
  106377. e->band[0].begin=2; e->band[0].end=4;
  106378. e->band[1].begin=4; e->band[1].end=5;
  106379. e->band[2].begin=6; e->band[2].end=6;
  106380. e->band[3].begin=9; e->band[3].end=8;
  106381. e->band[4].begin=13; e->band[4].end=8;
  106382. e->band[5].begin=17; e->band[5].end=8;
  106383. e->band[6].begin=22; e->band[6].end=8;
  106384. for(j=0;j<VE_BANDS;j++){
  106385. n=e->band[j].end;
  106386. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  106387. for(i=0;i<n;i++){
  106388. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  106389. e->band[j].total+=e->band[j].window[i];
  106390. }
  106391. e->band[j].total=1./e->band[j].total;
  106392. }
  106393. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  106394. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  106395. }
  106396. void _ve_envelope_clear(envelope_lookup *e){
  106397. int i;
  106398. mdct_clear(&e->mdct);
  106399. for(i=0;i<VE_BANDS;i++)
  106400. _ogg_free(e->band[i].window);
  106401. _ogg_free(e->mdct_win);
  106402. _ogg_free(e->filter);
  106403. _ogg_free(e->mark);
  106404. memset(e,0,sizeof(*e));
  106405. }
  106406. /* fairly straight threshhold-by-band based until we find something
  106407. that works better and isn't patented. */
  106408. static int _ve_amp(envelope_lookup *ve,
  106409. vorbis_info_psy_global *gi,
  106410. float *data,
  106411. envelope_band *bands,
  106412. envelope_filter_state *filters,
  106413. long pos){
  106414. long n=ve->winlength;
  106415. int ret=0;
  106416. long i,j;
  106417. float decay;
  106418. /* we want to have a 'minimum bar' for energy, else we're just
  106419. basing blocks on quantization noise that outweighs the signal
  106420. itself (for low power signals) */
  106421. float minV=ve->minenergy;
  106422. float *vec=(float*) alloca(n*sizeof(*vec));
  106423. /* stretch is used to gradually lengthen the number of windows
  106424. considered prevoius-to-potential-trigger */
  106425. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  106426. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  106427. if(penalty<0.f)penalty=0.f;
  106428. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  106429. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  106430. totalshift+pos*ve->searchstep);*/
  106431. /* window and transform */
  106432. for(i=0;i<n;i++)
  106433. vec[i]=data[i]*ve->mdct_win[i];
  106434. mdct_forward(&ve->mdct,vec,vec);
  106435. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  106436. /* near-DC spreading function; this has nothing to do with
  106437. psychoacoustics, just sidelobe leakage and window size */
  106438. {
  106439. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  106440. int ptr=filters->nearptr;
  106441. /* the accumulation is regularly refreshed from scratch to avoid
  106442. floating point creep */
  106443. if(ptr==0){
  106444. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  106445. filters->nearDC_partialacc=temp;
  106446. }else{
  106447. decay=filters->nearDC_acc+=temp;
  106448. filters->nearDC_partialacc+=temp;
  106449. }
  106450. filters->nearDC_acc-=filters->nearDC[ptr];
  106451. filters->nearDC[ptr]=temp;
  106452. decay*=(1./(VE_NEARDC+1));
  106453. filters->nearptr++;
  106454. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  106455. decay=todB(&decay)*.5-15.f;
  106456. }
  106457. /* perform spreading and limiting, also smooth the spectrum. yes,
  106458. the MDCT results in all real coefficients, but it still *behaves*
  106459. like real/imaginary pairs */
  106460. for(i=0;i<n/2;i+=2){
  106461. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  106462. val=todB(&val)*.5f;
  106463. if(val<decay)val=decay;
  106464. if(val<minV)val=minV;
  106465. vec[i>>1]=val;
  106466. decay-=8.;
  106467. }
  106468. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  106469. /* perform preecho/postecho triggering by band */
  106470. for(j=0;j<VE_BANDS;j++){
  106471. float acc=0.;
  106472. float valmax,valmin;
  106473. /* accumulate amplitude */
  106474. for(i=0;i<bands[j].end;i++)
  106475. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  106476. acc*=bands[j].total;
  106477. /* convert amplitude to delta */
  106478. {
  106479. int p,thisx=filters[j].ampptr;
  106480. float postmax,postmin,premax=-99999.f,premin=99999.f;
  106481. p=thisx;
  106482. p--;
  106483. if(p<0)p+=VE_AMP;
  106484. postmax=max(acc,filters[j].ampbuf[p]);
  106485. postmin=min(acc,filters[j].ampbuf[p]);
  106486. for(i=0;i<stretch;i++){
  106487. p--;
  106488. if(p<0)p+=VE_AMP;
  106489. premax=max(premax,filters[j].ampbuf[p]);
  106490. premin=min(premin,filters[j].ampbuf[p]);
  106491. }
  106492. valmin=postmin-premin;
  106493. valmax=postmax-premax;
  106494. /*filters[j].markers[pos]=valmax;*/
  106495. filters[j].ampbuf[thisx]=acc;
  106496. filters[j].ampptr++;
  106497. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  106498. }
  106499. /* look at min/max, decide trigger */
  106500. if(valmax>gi->preecho_thresh[j]+penalty){
  106501. ret|=1;
  106502. ret|=4;
  106503. }
  106504. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  106505. }
  106506. return(ret);
  106507. }
  106508. #if 0
  106509. static int seq=0;
  106510. static ogg_int64_t totalshift=-1024;
  106511. #endif
  106512. long _ve_envelope_search(vorbis_dsp_state *v){
  106513. vorbis_info *vi=v->vi;
  106514. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  106515. vorbis_info_psy_global *gi=&ci->psy_g_param;
  106516. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  106517. long i,j;
  106518. int first=ve->current/ve->searchstep;
  106519. int last=v->pcm_current/ve->searchstep-VE_WIN;
  106520. if(first<0)first=0;
  106521. /* make sure we have enough storage to match the PCM */
  106522. if(last+VE_WIN+VE_POST>ve->storage){
  106523. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  106524. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  106525. }
  106526. for(j=first;j<last;j++){
  106527. int ret=0;
  106528. ve->stretch++;
  106529. if(ve->stretch>VE_MAXSTRETCH*2)
  106530. ve->stretch=VE_MAXSTRETCH*2;
  106531. for(i=0;i<ve->ch;i++){
  106532. float *pcm=v->pcm[i]+ve->searchstep*(j);
  106533. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  106534. }
  106535. ve->mark[j+VE_POST]=0;
  106536. if(ret&1){
  106537. ve->mark[j]=1;
  106538. ve->mark[j+1]=1;
  106539. }
  106540. if(ret&2){
  106541. ve->mark[j]=1;
  106542. if(j>0)ve->mark[j-1]=1;
  106543. }
  106544. if(ret&4)ve->stretch=-1;
  106545. }
  106546. ve->current=last*ve->searchstep;
  106547. {
  106548. long centerW=v->centerW;
  106549. long testW=
  106550. centerW+
  106551. ci->blocksizes[v->W]/4+
  106552. ci->blocksizes[1]/2+
  106553. ci->blocksizes[0]/4;
  106554. j=ve->cursor;
  106555. while(j<ve->current-(ve->searchstep)){/* account for postecho
  106556. working back one window */
  106557. if(j>=testW)return(1);
  106558. ve->cursor=j;
  106559. if(ve->mark[j/ve->searchstep]){
  106560. if(j>centerW){
  106561. #if 0
  106562. if(j>ve->curmark){
  106563. float *marker=alloca(v->pcm_current*sizeof(*marker));
  106564. int l,m;
  106565. memset(marker,0,sizeof(*marker)*v->pcm_current);
  106566. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  106567. seq,
  106568. (totalshift+ve->cursor)/44100.,
  106569. (totalshift+j)/44100.);
  106570. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  106571. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  106572. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  106573. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  106574. for(m=0;m<VE_BANDS;m++){
  106575. char buf[80];
  106576. sprintf(buf,"delL%d",m);
  106577. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  106578. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  106579. }
  106580. for(m=0;m<VE_BANDS;m++){
  106581. char buf[80];
  106582. sprintf(buf,"delR%d",m);
  106583. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  106584. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  106585. }
  106586. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  106587. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  106588. seq++;
  106589. }
  106590. #endif
  106591. ve->curmark=j;
  106592. if(j>=testW)return(1);
  106593. return(0);
  106594. }
  106595. }
  106596. j+=ve->searchstep;
  106597. }
  106598. }
  106599. return(-1);
  106600. }
  106601. int _ve_envelope_mark(vorbis_dsp_state *v){
  106602. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  106603. vorbis_info *vi=v->vi;
  106604. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106605. long centerW=v->centerW;
  106606. long beginW=centerW-ci->blocksizes[v->W]/4;
  106607. long endW=centerW+ci->blocksizes[v->W]/4;
  106608. if(v->W){
  106609. beginW-=ci->blocksizes[v->lW]/4;
  106610. endW+=ci->blocksizes[v->nW]/4;
  106611. }else{
  106612. beginW-=ci->blocksizes[0]/4;
  106613. endW+=ci->blocksizes[0]/4;
  106614. }
  106615. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  106616. {
  106617. long first=beginW/ve->searchstep;
  106618. long last=endW/ve->searchstep;
  106619. long i;
  106620. for(i=first;i<last;i++)
  106621. if(ve->mark[i])return(1);
  106622. }
  106623. return(0);
  106624. }
  106625. void _ve_envelope_shift(envelope_lookup *e,long shift){
  106626. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  106627. ahead of ve->current */
  106628. int smallshift=shift/e->searchstep;
  106629. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  106630. #if 0
  106631. for(i=0;i<VE_BANDS*e->ch;i++)
  106632. memmove(e->filter[i].markers,
  106633. e->filter[i].markers+smallshift,
  106634. (1024-smallshift)*sizeof(*(*e->filter).markers));
  106635. totalshift+=shift;
  106636. #endif
  106637. e->current-=shift;
  106638. if(e->curmark>=0)
  106639. e->curmark-=shift;
  106640. e->cursor-=shift;
  106641. }
  106642. #endif
  106643. /********* End of inlined file: envelope.c *********/
  106644. /********* Start of inlined file: floor0.c *********/
  106645. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106646. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106647. // tasks..
  106648. #ifdef _MSC_VER
  106649. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106650. #endif
  106651. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106652. #if JUCE_USE_OGGVORBIS
  106653. #include <stdlib.h>
  106654. #include <string.h>
  106655. #include <math.h>
  106656. /********* Start of inlined file: lsp.h *********/
  106657. #ifndef _V_LSP_H_
  106658. #define _V_LSP_H_
  106659. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  106660. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  106661. float *lsp,int m,
  106662. float amp,float ampoffset);
  106663. #endif
  106664. /********* End of inlined file: lsp.h *********/
  106665. #include <stdio.h>
  106666. typedef struct {
  106667. int ln;
  106668. int m;
  106669. int **linearmap;
  106670. int n[2];
  106671. vorbis_info_floor0 *vi;
  106672. long bits;
  106673. long frames;
  106674. } vorbis_look_floor0;
  106675. /***********************************************/
  106676. static void floor0_free_info(vorbis_info_floor *i){
  106677. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  106678. if(info){
  106679. memset(info,0,sizeof(*info));
  106680. _ogg_free(info);
  106681. }
  106682. }
  106683. static void floor0_free_look(vorbis_look_floor *i){
  106684. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  106685. if(look){
  106686. if(look->linearmap){
  106687. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  106688. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  106689. _ogg_free(look->linearmap);
  106690. }
  106691. memset(look,0,sizeof(*look));
  106692. _ogg_free(look);
  106693. }
  106694. }
  106695. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  106696. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106697. int j;
  106698. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  106699. info->order=oggpack_read(opb,8);
  106700. info->rate=oggpack_read(opb,16);
  106701. info->barkmap=oggpack_read(opb,16);
  106702. info->ampbits=oggpack_read(opb,6);
  106703. info->ampdB=oggpack_read(opb,8);
  106704. info->numbooks=oggpack_read(opb,4)+1;
  106705. if(info->order<1)goto err_out;
  106706. if(info->rate<1)goto err_out;
  106707. if(info->barkmap<1)goto err_out;
  106708. if(info->numbooks<1)goto err_out;
  106709. for(j=0;j<info->numbooks;j++){
  106710. info->books[j]=oggpack_read(opb,8);
  106711. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  106712. }
  106713. return(info);
  106714. err_out:
  106715. floor0_free_info(info);
  106716. return(NULL);
  106717. }
  106718. /* initialize Bark scale and normalization lookups. We could do this
  106719. with static tables, but Vorbis allows a number of possible
  106720. combinations, so it's best to do it computationally.
  106721. The below is authoritative in terms of defining scale mapping.
  106722. Note that the scale depends on the sampling rate as well as the
  106723. linear block and mapping sizes */
  106724. static void floor0_map_lazy_init(vorbis_block *vb,
  106725. vorbis_info_floor *infoX,
  106726. vorbis_look_floor0 *look){
  106727. if(!look->linearmap[vb->W]){
  106728. vorbis_dsp_state *vd=vb->vd;
  106729. vorbis_info *vi=vd->vi;
  106730. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106731. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  106732. int W=vb->W;
  106733. int n=ci->blocksizes[W]/2,j;
  106734. /* we choose a scaling constant so that:
  106735. floor(bark(rate/2-1)*C)=mapped-1
  106736. floor(bark(rate/2)*C)=mapped */
  106737. float scale=look->ln/toBARK(info->rate/2.f);
  106738. /* the mapping from a linear scale to a smaller bark scale is
  106739. straightforward. We do *not* make sure that the linear mapping
  106740. does not skip bark-scale bins; the decoder simply skips them and
  106741. the encoder may do what it wishes in filling them. They're
  106742. necessary in some mapping combinations to keep the scale spacing
  106743. accurate */
  106744. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  106745. for(j=0;j<n;j++){
  106746. int val=floor( toBARK((info->rate/2.f)/n*j)
  106747. *scale); /* bark numbers represent band edges */
  106748. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  106749. look->linearmap[W][j]=val;
  106750. }
  106751. look->linearmap[W][j]=-1;
  106752. look->n[W]=n;
  106753. }
  106754. }
  106755. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  106756. vorbis_info_floor *i){
  106757. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  106758. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  106759. look->m=info->order;
  106760. look->ln=info->barkmap;
  106761. look->vi=info;
  106762. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  106763. return look;
  106764. }
  106765. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  106766. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  106767. vorbis_info_floor0 *info=look->vi;
  106768. int j,k;
  106769. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  106770. if(ampraw>0){ /* also handles the -1 out of data case */
  106771. long maxval=(1<<info->ampbits)-1;
  106772. float amp=(float)ampraw/maxval*info->ampdB;
  106773. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  106774. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  106775. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  106776. codebook *b=ci->fullbooks+info->books[booknum];
  106777. float last=0.f;
  106778. /* the additional b->dim is a guard against any possible stack
  106779. smash; b->dim is provably more than we can overflow the
  106780. vector */
  106781. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  106782. for(j=0;j<look->m;j+=b->dim)
  106783. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  106784. for(j=0;j<look->m;){
  106785. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  106786. last=lsp[j-1];
  106787. }
  106788. lsp[look->m]=amp;
  106789. return(lsp);
  106790. }
  106791. }
  106792. eop:
  106793. return(NULL);
  106794. }
  106795. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  106796. void *memo,float *out){
  106797. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  106798. vorbis_info_floor0 *info=look->vi;
  106799. floor0_map_lazy_init(vb,info,look);
  106800. if(memo){
  106801. float *lsp=(float *)memo;
  106802. float amp=lsp[look->m];
  106803. /* take the coefficients back to a spectral envelope curve */
  106804. vorbis_lsp_to_curve(out,
  106805. look->linearmap[vb->W],
  106806. look->n[vb->W],
  106807. look->ln,
  106808. lsp,look->m,amp,(float)info->ampdB);
  106809. return(1);
  106810. }
  106811. memset(out,0,sizeof(*out)*look->n[vb->W]);
  106812. return(0);
  106813. }
  106814. /* export hooks */
  106815. vorbis_func_floor floor0_exportbundle={
  106816. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  106817. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  106818. };
  106819. #endif
  106820. /********* End of inlined file: floor0.c *********/
  106821. /********* Start of inlined file: floor1.c *********/
  106822. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106823. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106824. // tasks..
  106825. #ifdef _MSC_VER
  106826. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106827. #endif
  106828. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106829. #if JUCE_USE_OGGVORBIS
  106830. #include <stdlib.h>
  106831. #include <string.h>
  106832. #include <math.h>
  106833. #include <stdio.h>
  106834. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  106835. typedef struct {
  106836. int sorted_index[VIF_POSIT+2];
  106837. int forward_index[VIF_POSIT+2];
  106838. int reverse_index[VIF_POSIT+2];
  106839. int hineighbor[VIF_POSIT];
  106840. int loneighbor[VIF_POSIT];
  106841. int posts;
  106842. int n;
  106843. int quant_q;
  106844. vorbis_info_floor1 *vi;
  106845. long phrasebits;
  106846. long postbits;
  106847. long frames;
  106848. } vorbis_look_floor1;
  106849. typedef struct lsfit_acc{
  106850. long x0;
  106851. long x1;
  106852. long xa;
  106853. long ya;
  106854. long x2a;
  106855. long y2a;
  106856. long xya;
  106857. long an;
  106858. } lsfit_acc;
  106859. /***********************************************/
  106860. static void floor1_free_info(vorbis_info_floor *i){
  106861. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  106862. if(info){
  106863. memset(info,0,sizeof(*info));
  106864. _ogg_free(info);
  106865. }
  106866. }
  106867. static void floor1_free_look(vorbis_look_floor *i){
  106868. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  106869. if(look){
  106870. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  106871. (float)look->phrasebits/look->frames,
  106872. (float)look->postbits/look->frames,
  106873. (float)(look->postbits+look->phrasebits)/look->frames);*/
  106874. memset(look,0,sizeof(*look));
  106875. _ogg_free(look);
  106876. }
  106877. }
  106878. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  106879. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  106880. int j,k;
  106881. int count=0;
  106882. int rangebits;
  106883. int maxposit=info->postlist[1];
  106884. int maxclass=-1;
  106885. /* save out partitions */
  106886. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  106887. for(j=0;j<info->partitions;j++){
  106888. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  106889. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  106890. }
  106891. /* save out partition classes */
  106892. for(j=0;j<maxclass+1;j++){
  106893. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  106894. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  106895. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  106896. for(k=0;k<(1<<info->class_subs[j]);k++)
  106897. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  106898. }
  106899. /* save out the post list */
  106900. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  106901. oggpack_write(opb,ilog2(maxposit),4);
  106902. rangebits=ilog2(maxposit);
  106903. for(j=0,k=0;j<info->partitions;j++){
  106904. count+=info->class_dim[info->partitionclass[j]];
  106905. for(;k<count;k++)
  106906. oggpack_write(opb,info->postlist[k+2],rangebits);
  106907. }
  106908. }
  106909. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  106910. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106911. int j,k,count=0,maxclass=-1,rangebits;
  106912. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  106913. /* read partitions */
  106914. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  106915. for(j=0;j<info->partitions;j++){
  106916. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  106917. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  106918. }
  106919. /* read partition classes */
  106920. for(j=0;j<maxclass+1;j++){
  106921. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  106922. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  106923. if(info->class_subs[j]<0)
  106924. goto err_out;
  106925. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  106926. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  106927. goto err_out;
  106928. for(k=0;k<(1<<info->class_subs[j]);k++){
  106929. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  106930. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  106931. goto err_out;
  106932. }
  106933. }
  106934. /* read the post list */
  106935. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  106936. rangebits=oggpack_read(opb,4);
  106937. for(j=0,k=0;j<info->partitions;j++){
  106938. count+=info->class_dim[info->partitionclass[j]];
  106939. for(;k<count;k++){
  106940. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  106941. if(t<0 || t>=(1<<rangebits))
  106942. goto err_out;
  106943. }
  106944. }
  106945. info->postlist[0]=0;
  106946. info->postlist[1]=1<<rangebits;
  106947. return(info);
  106948. err_out:
  106949. floor1_free_info(info);
  106950. return(NULL);
  106951. }
  106952. static int icomp(const void *a,const void *b){
  106953. return(**(int **)a-**(int **)b);
  106954. }
  106955. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  106956. vorbis_info_floor *in){
  106957. int *sortpointer[VIF_POSIT+2];
  106958. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  106959. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  106960. int i,j,n=0;
  106961. look->vi=info;
  106962. look->n=info->postlist[1];
  106963. /* we drop each position value in-between already decoded values,
  106964. and use linear interpolation to predict each new value past the
  106965. edges. The positions are read in the order of the position
  106966. list... we precompute the bounding positions in the lookup. Of
  106967. course, the neighbors can change (if a position is declined), but
  106968. this is an initial mapping */
  106969. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  106970. n+=2;
  106971. look->posts=n;
  106972. /* also store a sorted position index */
  106973. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  106974. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  106975. /* points from sort order back to range number */
  106976. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  106977. /* points from range order to sorted position */
  106978. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  106979. /* we actually need the post values too */
  106980. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  106981. /* quantize values to multiplier spec */
  106982. switch(info->mult){
  106983. case 1: /* 1024 -> 256 */
  106984. look->quant_q=256;
  106985. break;
  106986. case 2: /* 1024 -> 128 */
  106987. look->quant_q=128;
  106988. break;
  106989. case 3: /* 1024 -> 86 */
  106990. look->quant_q=86;
  106991. break;
  106992. case 4: /* 1024 -> 64 */
  106993. look->quant_q=64;
  106994. break;
  106995. }
  106996. /* discover our neighbors for decode where we don't use fit flags
  106997. (that would push the neighbors outward) */
  106998. for(i=0;i<n-2;i++){
  106999. int lo=0;
  107000. int hi=1;
  107001. int lx=0;
  107002. int hx=look->n;
  107003. int currentx=info->postlist[i+2];
  107004. for(j=0;j<i+2;j++){
  107005. int x=info->postlist[j];
  107006. if(x>lx && x<currentx){
  107007. lo=j;
  107008. lx=x;
  107009. }
  107010. if(x<hx && x>currentx){
  107011. hi=j;
  107012. hx=x;
  107013. }
  107014. }
  107015. look->loneighbor[i]=lo;
  107016. look->hineighbor[i]=hi;
  107017. }
  107018. return(look);
  107019. }
  107020. static int render_point(int x0,int x1,int y0,int y1,int x){
  107021. y0&=0x7fff; /* mask off flag */
  107022. y1&=0x7fff;
  107023. {
  107024. int dy=y1-y0;
  107025. int adx=x1-x0;
  107026. int ady=abs(dy);
  107027. int err=ady*(x-x0);
  107028. int off=err/adx;
  107029. if(dy<0)return(y0-off);
  107030. return(y0+off);
  107031. }
  107032. }
  107033. static int vorbis_dBquant(const float *x){
  107034. int i= *x*7.3142857f+1023.5f;
  107035. if(i>1023)return(1023);
  107036. if(i<0)return(0);
  107037. return i;
  107038. }
  107039. static float FLOOR1_fromdB_LOOKUP[256]={
  107040. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  107041. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  107042. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  107043. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  107044. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  107045. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  107046. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  107047. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  107048. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  107049. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  107050. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  107051. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  107052. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  107053. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  107054. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  107055. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  107056. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  107057. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  107058. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  107059. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  107060. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  107061. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  107062. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  107063. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  107064. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  107065. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  107066. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  107067. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  107068. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  107069. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  107070. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  107071. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  107072. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  107073. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  107074. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  107075. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  107076. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  107077. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  107078. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  107079. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  107080. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  107081. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  107082. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  107083. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  107084. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  107085. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  107086. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  107087. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  107088. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  107089. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  107090. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  107091. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  107092. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  107093. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  107094. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  107095. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  107096. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  107097. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  107098. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  107099. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  107100. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  107101. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  107102. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  107103. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  107104. };
  107105. static void render_line(int x0,int x1,int y0,int y1,float *d){
  107106. int dy=y1-y0;
  107107. int adx=x1-x0;
  107108. int ady=abs(dy);
  107109. int base=dy/adx;
  107110. int sy=(dy<0?base-1:base+1);
  107111. int x=x0;
  107112. int y=y0;
  107113. int err=0;
  107114. ady-=abs(base*adx);
  107115. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  107116. while(++x<x1){
  107117. err=err+ady;
  107118. if(err>=adx){
  107119. err-=adx;
  107120. y+=sy;
  107121. }else{
  107122. y+=base;
  107123. }
  107124. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  107125. }
  107126. }
  107127. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  107128. int dy=y1-y0;
  107129. int adx=x1-x0;
  107130. int ady=abs(dy);
  107131. int base=dy/adx;
  107132. int sy=(dy<0?base-1:base+1);
  107133. int x=x0;
  107134. int y=y0;
  107135. int err=0;
  107136. ady-=abs(base*adx);
  107137. d[x]=y;
  107138. while(++x<x1){
  107139. err=err+ady;
  107140. if(err>=adx){
  107141. err-=adx;
  107142. y+=sy;
  107143. }else{
  107144. y+=base;
  107145. }
  107146. d[x]=y;
  107147. }
  107148. }
  107149. /* the floor has already been filtered to only include relevant sections */
  107150. static int accumulate_fit(const float *flr,const float *mdct,
  107151. int x0, int x1,lsfit_acc *a,
  107152. int n,vorbis_info_floor1 *info){
  107153. long i;
  107154. long xa=0,ya=0,x2a=0,y2a=0,xya=0,na=0, xb=0,yb=0,x2b=0,y2b=0,xyb=0,nb=0;
  107155. memset(a,0,sizeof(*a));
  107156. a->x0=x0;
  107157. a->x1=x1;
  107158. if(x1>=n)x1=n-1;
  107159. for(i=x0;i<=x1;i++){
  107160. int quantized=vorbis_dBquant(flr+i);
  107161. if(quantized){
  107162. if(mdct[i]+info->twofitatten>=flr[i]){
  107163. xa += i;
  107164. ya += quantized;
  107165. x2a += i*i;
  107166. y2a += quantized*quantized;
  107167. xya += i*quantized;
  107168. na++;
  107169. }else{
  107170. xb += i;
  107171. yb += quantized;
  107172. x2b += i*i;
  107173. y2b += quantized*quantized;
  107174. xyb += i*quantized;
  107175. nb++;
  107176. }
  107177. }
  107178. }
  107179. xb+=xa;
  107180. yb+=ya;
  107181. x2b+=x2a;
  107182. y2b+=y2a;
  107183. xyb+=xya;
  107184. nb+=na;
  107185. /* weight toward the actually used frequencies if we meet the threshhold */
  107186. {
  107187. int weight=nb*info->twofitweight/(na+1);
  107188. a->xa=xa*weight+xb;
  107189. a->ya=ya*weight+yb;
  107190. a->x2a=x2a*weight+x2b;
  107191. a->y2a=y2a*weight+y2b;
  107192. a->xya=xya*weight+xyb;
  107193. a->an=na*weight+nb;
  107194. }
  107195. return(na);
  107196. }
  107197. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  107198. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  107199. long x0=a[0].x0;
  107200. long x1=a[fits-1].x1;
  107201. for(i=0;i<fits;i++){
  107202. x+=a[i].xa;
  107203. y+=a[i].ya;
  107204. x2+=a[i].x2a;
  107205. y2+=a[i].y2a;
  107206. xy+=a[i].xya;
  107207. an+=a[i].an;
  107208. }
  107209. if(*y0>=0){
  107210. x+= x0;
  107211. y+= *y0;
  107212. x2+= x0 * x0;
  107213. y2+= *y0 * *y0;
  107214. xy+= *y0 * x0;
  107215. an++;
  107216. }
  107217. if(*y1>=0){
  107218. x+= x1;
  107219. y+= *y1;
  107220. x2+= x1 * x1;
  107221. y2+= *y1 * *y1;
  107222. xy+= *y1 * x1;
  107223. an++;
  107224. }
  107225. if(an){
  107226. /* need 64 bit multiplies, which C doesn't give portably as int */
  107227. double fx=x;
  107228. double fy=y;
  107229. double fx2=x2;
  107230. double fxy=xy;
  107231. double denom=1./(an*fx2-fx*fx);
  107232. double a=(fy*fx2-fxy*fx)*denom;
  107233. double b=(an*fxy-fx*fy)*denom;
  107234. *y0=rint(a+b*x0);
  107235. *y1=rint(a+b*x1);
  107236. /* limit to our range! */
  107237. if(*y0>1023)*y0=1023;
  107238. if(*y1>1023)*y1=1023;
  107239. if(*y0<0)*y0=0;
  107240. if(*y1<0)*y1=0;
  107241. }else{
  107242. *y0=0;
  107243. *y1=0;
  107244. }
  107245. }
  107246. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  107247. long y=0;
  107248. int i;
  107249. for(i=0;i<fits && y==0;i++)
  107250. y+=a[i].ya;
  107251. *y0=*y1=y;
  107252. }*/
  107253. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  107254. const float *mdct,
  107255. vorbis_info_floor1 *info){
  107256. int dy=y1-y0;
  107257. int adx=x1-x0;
  107258. int ady=abs(dy);
  107259. int base=dy/adx;
  107260. int sy=(dy<0?base-1:base+1);
  107261. int x=x0;
  107262. int y=y0;
  107263. int err=0;
  107264. int val=vorbis_dBquant(mask+x);
  107265. int mse=0;
  107266. int n=0;
  107267. ady-=abs(base*adx);
  107268. mse=(y-val);
  107269. mse*=mse;
  107270. n++;
  107271. if(mdct[x]+info->twofitatten>=mask[x]){
  107272. if(y+info->maxover<val)return(1);
  107273. if(y-info->maxunder>val)return(1);
  107274. }
  107275. while(++x<x1){
  107276. err=err+ady;
  107277. if(err>=adx){
  107278. err-=adx;
  107279. y+=sy;
  107280. }else{
  107281. y+=base;
  107282. }
  107283. val=vorbis_dBquant(mask+x);
  107284. mse+=((y-val)*(y-val));
  107285. n++;
  107286. if(mdct[x]+info->twofitatten>=mask[x]){
  107287. if(val){
  107288. if(y+info->maxover<val)return(1);
  107289. if(y-info->maxunder>val)return(1);
  107290. }
  107291. }
  107292. }
  107293. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  107294. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  107295. if(mse/n>info->maxerr)return(1);
  107296. return(0);
  107297. }
  107298. static int post_Y(int *A,int *B,int pos){
  107299. if(A[pos]<0)
  107300. return B[pos];
  107301. if(B[pos]<0)
  107302. return A[pos];
  107303. return (A[pos]+B[pos])>>1;
  107304. }
  107305. int *floor1_fit(vorbis_block *vb,void *look_,
  107306. const float *logmdct, /* in */
  107307. const float *logmask){
  107308. long i,j;
  107309. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  107310. vorbis_info_floor1 *info=look->vi;
  107311. long n=look->n;
  107312. long posts=look->posts;
  107313. long nonzero=0;
  107314. lsfit_acc fits[VIF_POSIT+1];
  107315. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  107316. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  107317. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  107318. int hineighbor[VIF_POSIT+2];
  107319. int *output=NULL;
  107320. int memo[VIF_POSIT+2];
  107321. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  107322. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  107323. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  107324. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  107325. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  107326. /* quantize the relevant floor points and collect them into line fit
  107327. structures (one per minimal division) at the same time */
  107328. if(posts==0){
  107329. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  107330. }else{
  107331. for(i=0;i<posts-1;i++)
  107332. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  107333. look->sorted_index[i+1],fits+i,
  107334. n,info);
  107335. }
  107336. if(nonzero){
  107337. /* start by fitting the implicit base case.... */
  107338. int y0=-200;
  107339. int y1=-200;
  107340. fit_line(fits,posts-1,&y0,&y1);
  107341. fit_valueA[0]=y0;
  107342. fit_valueB[0]=y0;
  107343. fit_valueB[1]=y1;
  107344. fit_valueA[1]=y1;
  107345. /* Non degenerate case */
  107346. /* start progressive splitting. This is a greedy, non-optimal
  107347. algorithm, but simple and close enough to the best
  107348. answer. */
  107349. for(i=2;i<posts;i++){
  107350. int sortpos=look->reverse_index[i];
  107351. int ln=loneighbor[sortpos];
  107352. int hn=hineighbor[sortpos];
  107353. /* eliminate repeat searches of a particular range with a memo */
  107354. if(memo[ln]!=hn){
  107355. /* haven't performed this error search yet */
  107356. int lsortpos=look->reverse_index[ln];
  107357. int hsortpos=look->reverse_index[hn];
  107358. memo[ln]=hn;
  107359. {
  107360. /* A note: we want to bound/minimize *local*, not global, error */
  107361. int lx=info->postlist[ln];
  107362. int hx=info->postlist[hn];
  107363. int ly=post_Y(fit_valueA,fit_valueB,ln);
  107364. int hy=post_Y(fit_valueA,fit_valueB,hn);
  107365. if(ly==-1 || hy==-1){
  107366. exit(1);
  107367. }
  107368. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  107369. /* outside error bounds/begin search area. Split it. */
  107370. int ly0=-200;
  107371. int ly1=-200;
  107372. int hy0=-200;
  107373. int hy1=-200;
  107374. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  107375. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  107376. /* store new edge values */
  107377. fit_valueB[ln]=ly0;
  107378. if(ln==0)fit_valueA[ln]=ly0;
  107379. fit_valueA[i]=ly1;
  107380. fit_valueB[i]=hy0;
  107381. fit_valueA[hn]=hy1;
  107382. if(hn==1)fit_valueB[hn]=hy1;
  107383. if(ly1>=0 || hy0>=0){
  107384. /* store new neighbor values */
  107385. for(j=sortpos-1;j>=0;j--)
  107386. if(hineighbor[j]==hn)
  107387. hineighbor[j]=i;
  107388. else
  107389. break;
  107390. for(j=sortpos+1;j<posts;j++)
  107391. if(loneighbor[j]==ln)
  107392. loneighbor[j]=i;
  107393. else
  107394. break;
  107395. }
  107396. }else{
  107397. fit_valueA[i]=-200;
  107398. fit_valueB[i]=-200;
  107399. }
  107400. }
  107401. }
  107402. }
  107403. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  107404. output[0]=post_Y(fit_valueA,fit_valueB,0);
  107405. output[1]=post_Y(fit_valueA,fit_valueB,1);
  107406. /* fill in posts marked as not using a fit; we will zero
  107407. back out to 'unused' when encoding them so long as curve
  107408. interpolation doesn't force them into use */
  107409. for(i=2;i<posts;i++){
  107410. int ln=look->loneighbor[i-2];
  107411. int hn=look->hineighbor[i-2];
  107412. int x0=info->postlist[ln];
  107413. int x1=info->postlist[hn];
  107414. int y0=output[ln];
  107415. int y1=output[hn];
  107416. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  107417. int vx=post_Y(fit_valueA,fit_valueB,i);
  107418. if(vx>=0 && predicted!=vx){
  107419. output[i]=vx;
  107420. }else{
  107421. output[i]= predicted|0x8000;
  107422. }
  107423. }
  107424. }
  107425. return(output);
  107426. }
  107427. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  107428. int *A,int *B,
  107429. int del){
  107430. long i;
  107431. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  107432. long posts=look->posts;
  107433. int *output=NULL;
  107434. if(A && B){
  107435. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  107436. for(i=0;i<posts;i++){
  107437. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  107438. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  107439. }
  107440. }
  107441. return(output);
  107442. }
  107443. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  107444. void*look_,
  107445. int *post,int *ilogmask){
  107446. long i,j;
  107447. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  107448. vorbis_info_floor1 *info=look->vi;
  107449. long posts=look->posts;
  107450. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  107451. int out[VIF_POSIT+2];
  107452. static_codebook **sbooks=ci->book_param;
  107453. codebook *books=ci->fullbooks;
  107454. static long seq=0;
  107455. /* quantize values to multiplier spec */
  107456. if(post){
  107457. for(i=0;i<posts;i++){
  107458. int val=post[i]&0x7fff;
  107459. switch(info->mult){
  107460. case 1: /* 1024 -> 256 */
  107461. val>>=2;
  107462. break;
  107463. case 2: /* 1024 -> 128 */
  107464. val>>=3;
  107465. break;
  107466. case 3: /* 1024 -> 86 */
  107467. val/=12;
  107468. break;
  107469. case 4: /* 1024 -> 64 */
  107470. val>>=4;
  107471. break;
  107472. }
  107473. post[i]=val | (post[i]&0x8000);
  107474. }
  107475. out[0]=post[0];
  107476. out[1]=post[1];
  107477. /* find prediction values for each post and subtract them */
  107478. for(i=2;i<posts;i++){
  107479. int ln=look->loneighbor[i-2];
  107480. int hn=look->hineighbor[i-2];
  107481. int x0=info->postlist[ln];
  107482. int x1=info->postlist[hn];
  107483. int y0=post[ln];
  107484. int y1=post[hn];
  107485. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  107486. if((post[i]&0x8000) || (predicted==post[i])){
  107487. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  107488. in interpolation */
  107489. out[i]=0;
  107490. }else{
  107491. int headroom=(look->quant_q-predicted<predicted?
  107492. look->quant_q-predicted:predicted);
  107493. int val=post[i]-predicted;
  107494. /* at this point the 'deviation' value is in the range +/- max
  107495. range, but the real, unique range can always be mapped to
  107496. only [0-maxrange). So we want to wrap the deviation into
  107497. this limited range, but do it in the way that least screws
  107498. an essentially gaussian probability distribution. */
  107499. if(val<0)
  107500. if(val<-headroom)
  107501. val=headroom-val-1;
  107502. else
  107503. val=-1-(val<<1);
  107504. else
  107505. if(val>=headroom)
  107506. val= val+headroom;
  107507. else
  107508. val<<=1;
  107509. out[i]=val;
  107510. post[ln]&=0x7fff;
  107511. post[hn]&=0x7fff;
  107512. }
  107513. }
  107514. /* we have everything we need. pack it out */
  107515. /* mark nontrivial floor */
  107516. oggpack_write(opb,1,1);
  107517. /* beginning/end post */
  107518. look->frames++;
  107519. look->postbits+=ilog(look->quant_q-1)*2;
  107520. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  107521. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  107522. /* partition by partition */
  107523. for(i=0,j=2;i<info->partitions;i++){
  107524. int classx=info->partitionclass[i];
  107525. int cdim=info->class_dim[classx];
  107526. int csubbits=info->class_subs[classx];
  107527. int csub=1<<csubbits;
  107528. int bookas[8]={0,0,0,0,0,0,0,0};
  107529. int cval=0;
  107530. int cshift=0;
  107531. int k,l;
  107532. /* generate the partition's first stage cascade value */
  107533. if(csubbits){
  107534. int maxval[8];
  107535. for(k=0;k<csub;k++){
  107536. int booknum=info->class_subbook[classx][k];
  107537. if(booknum<0){
  107538. maxval[k]=1;
  107539. }else{
  107540. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  107541. }
  107542. }
  107543. for(k=0;k<cdim;k++){
  107544. for(l=0;l<csub;l++){
  107545. int val=out[j+k];
  107546. if(val<maxval[l]){
  107547. bookas[k]=l;
  107548. break;
  107549. }
  107550. }
  107551. cval|= bookas[k]<<cshift;
  107552. cshift+=csubbits;
  107553. }
  107554. /* write it */
  107555. look->phrasebits+=
  107556. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  107557. #ifdef TRAIN_FLOOR1
  107558. {
  107559. FILE *of;
  107560. char buffer[80];
  107561. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  107562. vb->pcmend/2,posts-2,class);
  107563. of=fopen(buffer,"a");
  107564. fprintf(of,"%d\n",cval);
  107565. fclose(of);
  107566. }
  107567. #endif
  107568. }
  107569. /* write post values */
  107570. for(k=0;k<cdim;k++){
  107571. int book=info->class_subbook[classx][bookas[k]];
  107572. if(book>=0){
  107573. /* hack to allow training with 'bad' books */
  107574. if(out[j+k]<(books+book)->entries)
  107575. look->postbits+=vorbis_book_encode(books+book,
  107576. out[j+k],opb);
  107577. /*else
  107578. fprintf(stderr,"+!");*/
  107579. #ifdef TRAIN_FLOOR1
  107580. {
  107581. FILE *of;
  107582. char buffer[80];
  107583. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  107584. vb->pcmend/2,posts-2,class,bookas[k]);
  107585. of=fopen(buffer,"a");
  107586. fprintf(of,"%d\n",out[j+k]);
  107587. fclose(of);
  107588. }
  107589. #endif
  107590. }
  107591. }
  107592. j+=cdim;
  107593. }
  107594. {
  107595. /* generate quantized floor equivalent to what we'd unpack in decode */
  107596. /* render the lines */
  107597. int hx=0;
  107598. int lx=0;
  107599. int ly=post[0]*info->mult;
  107600. for(j=1;j<look->posts;j++){
  107601. int current=look->forward_index[j];
  107602. int hy=post[current]&0x7fff;
  107603. if(hy==post[current]){
  107604. hy*=info->mult;
  107605. hx=info->postlist[current];
  107606. render_line0(lx,hx,ly,hy,ilogmask);
  107607. lx=hx;
  107608. ly=hy;
  107609. }
  107610. }
  107611. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  107612. seq++;
  107613. return(1);
  107614. }
  107615. }else{
  107616. oggpack_write(opb,0,1);
  107617. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  107618. seq++;
  107619. return(0);
  107620. }
  107621. }
  107622. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  107623. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  107624. vorbis_info_floor1 *info=look->vi;
  107625. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  107626. int i,j,k;
  107627. codebook *books=ci->fullbooks;
  107628. /* unpack wrapped/predicted values from stream */
  107629. if(oggpack_read(&vb->opb,1)==1){
  107630. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  107631. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  107632. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  107633. /* partition by partition */
  107634. for(i=0,j=2;i<info->partitions;i++){
  107635. int classx=info->partitionclass[i];
  107636. int cdim=info->class_dim[classx];
  107637. int csubbits=info->class_subs[classx];
  107638. int csub=1<<csubbits;
  107639. int cval=0;
  107640. /* decode the partition's first stage cascade value */
  107641. if(csubbits){
  107642. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  107643. if(cval==-1)goto eop;
  107644. }
  107645. for(k=0;k<cdim;k++){
  107646. int book=info->class_subbook[classx][cval&(csub-1)];
  107647. cval>>=csubbits;
  107648. if(book>=0){
  107649. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  107650. goto eop;
  107651. }else{
  107652. fit_value[j+k]=0;
  107653. }
  107654. }
  107655. j+=cdim;
  107656. }
  107657. /* unwrap positive values and reconsitute via linear interpolation */
  107658. for(i=2;i<look->posts;i++){
  107659. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  107660. info->postlist[look->hineighbor[i-2]],
  107661. fit_value[look->loneighbor[i-2]],
  107662. fit_value[look->hineighbor[i-2]],
  107663. info->postlist[i]);
  107664. int hiroom=look->quant_q-predicted;
  107665. int loroom=predicted;
  107666. int room=(hiroom<loroom?hiroom:loroom)<<1;
  107667. int val=fit_value[i];
  107668. if(val){
  107669. if(val>=room){
  107670. if(hiroom>loroom){
  107671. val = val-loroom;
  107672. }else{
  107673. val = -1-(val-hiroom);
  107674. }
  107675. }else{
  107676. if(val&1){
  107677. val= -((val+1)>>1);
  107678. }else{
  107679. val>>=1;
  107680. }
  107681. }
  107682. fit_value[i]=val+predicted;
  107683. fit_value[look->loneighbor[i-2]]&=0x7fff;
  107684. fit_value[look->hineighbor[i-2]]&=0x7fff;
  107685. }else{
  107686. fit_value[i]=predicted|0x8000;
  107687. }
  107688. }
  107689. return(fit_value);
  107690. }
  107691. eop:
  107692. return(NULL);
  107693. }
  107694. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  107695. float *out){
  107696. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  107697. vorbis_info_floor1 *info=look->vi;
  107698. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  107699. int n=ci->blocksizes[vb->W]/2;
  107700. int j;
  107701. if(memo){
  107702. /* render the lines */
  107703. int *fit_value=(int *)memo;
  107704. int hx=0;
  107705. int lx=0;
  107706. int ly=fit_value[0]*info->mult;
  107707. for(j=1;j<look->posts;j++){
  107708. int current=look->forward_index[j];
  107709. int hy=fit_value[current]&0x7fff;
  107710. if(hy==fit_value[current]){
  107711. hy*=info->mult;
  107712. hx=info->postlist[current];
  107713. render_line(lx,hx,ly,hy,out);
  107714. lx=hx;
  107715. ly=hy;
  107716. }
  107717. }
  107718. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  107719. return(1);
  107720. }
  107721. memset(out,0,sizeof(*out)*n);
  107722. return(0);
  107723. }
  107724. /* export hooks */
  107725. vorbis_func_floor floor1_exportbundle={
  107726. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  107727. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  107728. };
  107729. #endif
  107730. /********* End of inlined file: floor1.c *********/
  107731. /********* Start of inlined file: info.c *********/
  107732. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107733. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107734. // tasks..
  107735. #ifdef _MSC_VER
  107736. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107737. #endif
  107738. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107739. #if JUCE_USE_OGGVORBIS
  107740. /* general handling of the header and the vorbis_info structure (and
  107741. substructures) */
  107742. #include <stdlib.h>
  107743. #include <string.h>
  107744. #include <ctype.h>
  107745. static void _v_writestring(oggpack_buffer *o,char *s, int bytes){
  107746. while(bytes--){
  107747. oggpack_write(o,*s++,8);
  107748. }
  107749. }
  107750. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  107751. while(bytes--){
  107752. *buf++=oggpack_read(o,8);
  107753. }
  107754. }
  107755. void vorbis_comment_init(vorbis_comment *vc){
  107756. memset(vc,0,sizeof(*vc));
  107757. }
  107758. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  107759. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  107760. (vc->comments+2)*sizeof(*vc->user_comments));
  107761. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  107762. (vc->comments+2)*sizeof(*vc->comment_lengths));
  107763. vc->comment_lengths[vc->comments]=strlen(comment);
  107764. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  107765. strcpy(vc->user_comments[vc->comments], comment);
  107766. vc->comments++;
  107767. vc->user_comments[vc->comments]=NULL;
  107768. }
  107769. void vorbis_comment_add_tag(vorbis_comment *vc, char *tag, char *contents){
  107770. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  107771. strcpy(comment, tag);
  107772. strcat(comment, "=");
  107773. strcat(comment, contents);
  107774. vorbis_comment_add(vc, comment);
  107775. }
  107776. /* This is more or less the same as strncasecmp - but that doesn't exist
  107777. * everywhere, and this is a fairly trivial function, so we include it */
  107778. static int tagcompare(const char *s1, const char *s2, int n){
  107779. int c=0;
  107780. while(c < n){
  107781. if(toupper(s1[c]) != toupper(s2[c]))
  107782. return !0;
  107783. c++;
  107784. }
  107785. return 0;
  107786. }
  107787. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  107788. long i;
  107789. int found = 0;
  107790. int taglen = strlen(tag)+1; /* +1 for the = we append */
  107791. char *fulltag = (char*)alloca(taglen+ 1);
  107792. strcpy(fulltag, tag);
  107793. strcat(fulltag, "=");
  107794. for(i=0;i<vc->comments;i++){
  107795. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  107796. if(count == found)
  107797. /* We return a pointer to the data, not a copy */
  107798. return vc->user_comments[i] + taglen;
  107799. else
  107800. found++;
  107801. }
  107802. }
  107803. return NULL; /* didn't find anything */
  107804. }
  107805. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  107806. int i,count=0;
  107807. int taglen = strlen(tag)+1; /* +1 for the = we append */
  107808. char *fulltag = (char*)alloca(taglen+1);
  107809. strcpy(fulltag,tag);
  107810. strcat(fulltag, "=");
  107811. for(i=0;i<vc->comments;i++){
  107812. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  107813. count++;
  107814. }
  107815. return count;
  107816. }
  107817. void vorbis_comment_clear(vorbis_comment *vc){
  107818. if(vc){
  107819. long i;
  107820. for(i=0;i<vc->comments;i++)
  107821. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  107822. if(vc->user_comments)_ogg_free(vc->user_comments);
  107823. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  107824. if(vc->vendor)_ogg_free(vc->vendor);
  107825. }
  107826. memset(vc,0,sizeof(*vc));
  107827. }
  107828. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  107829. They may be equal, but short will never ge greater than long */
  107830. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  107831. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  107832. return ci ? ci->blocksizes[zo] : -1;
  107833. }
  107834. /* used by synthesis, which has a full, alloced vi */
  107835. void vorbis_info_init(vorbis_info *vi){
  107836. memset(vi,0,sizeof(*vi));
  107837. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  107838. }
  107839. void vorbis_info_clear(vorbis_info *vi){
  107840. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107841. int i;
  107842. if(ci){
  107843. for(i=0;i<ci->modes;i++)
  107844. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  107845. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  107846. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  107847. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  107848. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  107849. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  107850. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  107851. for(i=0;i<ci->books;i++){
  107852. if(ci->book_param[i]){
  107853. /* knows if the book was not alloced */
  107854. vorbis_staticbook_destroy(ci->book_param[i]);
  107855. }
  107856. if(ci->fullbooks)
  107857. vorbis_book_clear(ci->fullbooks+i);
  107858. }
  107859. if(ci->fullbooks)
  107860. _ogg_free(ci->fullbooks);
  107861. for(i=0;i<ci->psys;i++)
  107862. _vi_psy_free(ci->psy_param[i]);
  107863. _ogg_free(ci);
  107864. }
  107865. memset(vi,0,sizeof(*vi));
  107866. }
  107867. /* Header packing/unpacking ********************************************/
  107868. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  107869. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107870. if(!ci)return(OV_EFAULT);
  107871. vi->version=oggpack_read(opb,32);
  107872. if(vi->version!=0)return(OV_EVERSION);
  107873. vi->channels=oggpack_read(opb,8);
  107874. vi->rate=oggpack_read(opb,32);
  107875. vi->bitrate_upper=oggpack_read(opb,32);
  107876. vi->bitrate_nominal=oggpack_read(opb,32);
  107877. vi->bitrate_lower=oggpack_read(opb,32);
  107878. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  107879. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  107880. if(vi->rate<1)goto err_out;
  107881. if(vi->channels<1)goto err_out;
  107882. if(ci->blocksizes[0]<8)goto err_out;
  107883. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  107884. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  107885. return(0);
  107886. err_out:
  107887. vorbis_info_clear(vi);
  107888. return(OV_EBADHEADER);
  107889. }
  107890. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  107891. int i;
  107892. int vendorlen=oggpack_read(opb,32);
  107893. if(vendorlen<0)goto err_out;
  107894. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  107895. _v_readstring(opb,vc->vendor,vendorlen);
  107896. vc->comments=oggpack_read(opb,32);
  107897. if(vc->comments<0)goto err_out;
  107898. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  107899. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  107900. for(i=0;i<vc->comments;i++){
  107901. int len=oggpack_read(opb,32);
  107902. if(len<0)goto err_out;
  107903. vc->comment_lengths[i]=len;
  107904. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  107905. _v_readstring(opb,vc->user_comments[i],len);
  107906. }
  107907. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  107908. return(0);
  107909. err_out:
  107910. vorbis_comment_clear(vc);
  107911. return(OV_EBADHEADER);
  107912. }
  107913. /* all of the real encoding details are here. The modes, books,
  107914. everything */
  107915. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  107916. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107917. int i;
  107918. if(!ci)return(OV_EFAULT);
  107919. /* codebooks */
  107920. ci->books=oggpack_read(opb,8)+1;
  107921. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  107922. for(i=0;i<ci->books;i++){
  107923. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  107924. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  107925. }
  107926. /* time backend settings; hooks are unused */
  107927. {
  107928. int times=oggpack_read(opb,6)+1;
  107929. for(i=0;i<times;i++){
  107930. int test=oggpack_read(opb,16);
  107931. if(test<0 || test>=VI_TIMEB)goto err_out;
  107932. }
  107933. }
  107934. /* floor backend settings */
  107935. ci->floors=oggpack_read(opb,6)+1;
  107936. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  107937. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  107938. for(i=0;i<ci->floors;i++){
  107939. ci->floor_type[i]=oggpack_read(opb,16);
  107940. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  107941. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  107942. if(!ci->floor_param[i])goto err_out;
  107943. }
  107944. /* residue backend settings */
  107945. ci->residues=oggpack_read(opb,6)+1;
  107946. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  107947. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  107948. for(i=0;i<ci->residues;i++){
  107949. ci->residue_type[i]=oggpack_read(opb,16);
  107950. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  107951. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  107952. if(!ci->residue_param[i])goto err_out;
  107953. }
  107954. /* map backend settings */
  107955. ci->maps=oggpack_read(opb,6)+1;
  107956. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  107957. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  107958. for(i=0;i<ci->maps;i++){
  107959. ci->map_type[i]=oggpack_read(opb,16);
  107960. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  107961. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  107962. if(!ci->map_param[i])goto err_out;
  107963. }
  107964. /* mode settings */
  107965. ci->modes=oggpack_read(opb,6)+1;
  107966. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  107967. for(i=0;i<ci->modes;i++){
  107968. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  107969. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  107970. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  107971. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  107972. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  107973. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  107974. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  107975. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  107976. }
  107977. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  107978. return(0);
  107979. err_out:
  107980. vorbis_info_clear(vi);
  107981. return(OV_EBADHEADER);
  107982. }
  107983. /* The Vorbis header is in three packets; the initial small packet in
  107984. the first page that identifies basic parameters, a second packet
  107985. with bitstream comments and a third packet that holds the
  107986. codebook. */
  107987. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  107988. oggpack_buffer opb;
  107989. if(op){
  107990. oggpack_readinit(&opb,op->packet,op->bytes);
  107991. /* Which of the three types of header is this? */
  107992. /* Also verify header-ness, vorbis */
  107993. {
  107994. char buffer[6];
  107995. int packtype=oggpack_read(&opb,8);
  107996. memset(buffer,0,6);
  107997. _v_readstring(&opb,buffer,6);
  107998. if(memcmp(buffer,"vorbis",6)){
  107999. /* not a vorbis header */
  108000. return(OV_ENOTVORBIS);
  108001. }
  108002. switch(packtype){
  108003. case 0x01: /* least significant *bit* is read first */
  108004. if(!op->b_o_s){
  108005. /* Not the initial packet */
  108006. return(OV_EBADHEADER);
  108007. }
  108008. if(vi->rate!=0){
  108009. /* previously initialized info header */
  108010. return(OV_EBADHEADER);
  108011. }
  108012. return(_vorbis_unpack_info(vi,&opb));
  108013. case 0x03: /* least significant *bit* is read first */
  108014. if(vi->rate==0){
  108015. /* um... we didn't get the initial header */
  108016. return(OV_EBADHEADER);
  108017. }
  108018. return(_vorbis_unpack_comment(vc,&opb));
  108019. case 0x05: /* least significant *bit* is read first */
  108020. if(vi->rate==0 || vc->vendor==NULL){
  108021. /* um... we didn;t get the initial header or comments yet */
  108022. return(OV_EBADHEADER);
  108023. }
  108024. return(_vorbis_unpack_books(vi,&opb));
  108025. default:
  108026. /* Not a valid vorbis header type */
  108027. return(OV_EBADHEADER);
  108028. break;
  108029. }
  108030. }
  108031. }
  108032. return(OV_EBADHEADER);
  108033. }
  108034. /* pack side **********************************************************/
  108035. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  108036. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108037. if(!ci)return(OV_EFAULT);
  108038. /* preamble */
  108039. oggpack_write(opb,0x01,8);
  108040. _v_writestring(opb,"vorbis", 6);
  108041. /* basic information about the stream */
  108042. oggpack_write(opb,0x00,32);
  108043. oggpack_write(opb,vi->channels,8);
  108044. oggpack_write(opb,vi->rate,32);
  108045. oggpack_write(opb,vi->bitrate_upper,32);
  108046. oggpack_write(opb,vi->bitrate_nominal,32);
  108047. oggpack_write(opb,vi->bitrate_lower,32);
  108048. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  108049. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  108050. oggpack_write(opb,1,1);
  108051. return(0);
  108052. }
  108053. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  108054. char temp[]="Xiph.Org libVorbis I 20050304";
  108055. int bytes = strlen(temp);
  108056. /* preamble */
  108057. oggpack_write(opb,0x03,8);
  108058. _v_writestring(opb,"vorbis", 6);
  108059. /* vendor */
  108060. oggpack_write(opb,bytes,32);
  108061. _v_writestring(opb,temp, bytes);
  108062. /* comments */
  108063. oggpack_write(opb,vc->comments,32);
  108064. if(vc->comments){
  108065. int i;
  108066. for(i=0;i<vc->comments;i++){
  108067. if(vc->user_comments[i]){
  108068. oggpack_write(opb,vc->comment_lengths[i],32);
  108069. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  108070. }else{
  108071. oggpack_write(opb,0,32);
  108072. }
  108073. }
  108074. }
  108075. oggpack_write(opb,1,1);
  108076. return(0);
  108077. }
  108078. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  108079. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108080. int i;
  108081. if(!ci)return(OV_EFAULT);
  108082. oggpack_write(opb,0x05,8);
  108083. _v_writestring(opb,"vorbis", 6);
  108084. /* books */
  108085. oggpack_write(opb,ci->books-1,8);
  108086. for(i=0;i<ci->books;i++)
  108087. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  108088. /* times; hook placeholders */
  108089. oggpack_write(opb,0,6);
  108090. oggpack_write(opb,0,16);
  108091. /* floors */
  108092. oggpack_write(opb,ci->floors-1,6);
  108093. for(i=0;i<ci->floors;i++){
  108094. oggpack_write(opb,ci->floor_type[i],16);
  108095. if(_floor_P[ci->floor_type[i]]->pack)
  108096. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  108097. else
  108098. goto err_out;
  108099. }
  108100. /* residues */
  108101. oggpack_write(opb,ci->residues-1,6);
  108102. for(i=0;i<ci->residues;i++){
  108103. oggpack_write(opb,ci->residue_type[i],16);
  108104. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  108105. }
  108106. /* maps */
  108107. oggpack_write(opb,ci->maps-1,6);
  108108. for(i=0;i<ci->maps;i++){
  108109. oggpack_write(opb,ci->map_type[i],16);
  108110. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  108111. }
  108112. /* modes */
  108113. oggpack_write(opb,ci->modes-1,6);
  108114. for(i=0;i<ci->modes;i++){
  108115. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  108116. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  108117. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  108118. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  108119. }
  108120. oggpack_write(opb,1,1);
  108121. return(0);
  108122. err_out:
  108123. return(-1);
  108124. }
  108125. int vorbis_commentheader_out(vorbis_comment *vc,
  108126. ogg_packet *op){
  108127. oggpack_buffer opb;
  108128. oggpack_writeinit(&opb);
  108129. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  108130. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  108131. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  108132. op->bytes=oggpack_bytes(&opb);
  108133. op->b_o_s=0;
  108134. op->e_o_s=0;
  108135. op->granulepos=0;
  108136. op->packetno=1;
  108137. return 0;
  108138. }
  108139. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  108140. vorbis_comment *vc,
  108141. ogg_packet *op,
  108142. ogg_packet *op_comm,
  108143. ogg_packet *op_code){
  108144. int ret=OV_EIMPL;
  108145. vorbis_info *vi=v->vi;
  108146. oggpack_buffer opb;
  108147. private_state *b=(private_state*)v->backend_state;
  108148. if(!b){
  108149. ret=OV_EFAULT;
  108150. goto err_out;
  108151. }
  108152. /* first header packet **********************************************/
  108153. oggpack_writeinit(&opb);
  108154. if(_vorbis_pack_info(&opb,vi))goto err_out;
  108155. /* build the packet */
  108156. if(b->header)_ogg_free(b->header);
  108157. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  108158. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  108159. op->packet=b->header;
  108160. op->bytes=oggpack_bytes(&opb);
  108161. op->b_o_s=1;
  108162. op->e_o_s=0;
  108163. op->granulepos=0;
  108164. op->packetno=0;
  108165. /* second header packet (comments) **********************************/
  108166. oggpack_reset(&opb);
  108167. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  108168. if(b->header1)_ogg_free(b->header1);
  108169. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  108170. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  108171. op_comm->packet=b->header1;
  108172. op_comm->bytes=oggpack_bytes(&opb);
  108173. op_comm->b_o_s=0;
  108174. op_comm->e_o_s=0;
  108175. op_comm->granulepos=0;
  108176. op_comm->packetno=1;
  108177. /* third header packet (modes/codebooks) ****************************/
  108178. oggpack_reset(&opb);
  108179. if(_vorbis_pack_books(&opb,vi))goto err_out;
  108180. if(b->header2)_ogg_free(b->header2);
  108181. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  108182. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  108183. op_code->packet=b->header2;
  108184. op_code->bytes=oggpack_bytes(&opb);
  108185. op_code->b_o_s=0;
  108186. op_code->e_o_s=0;
  108187. op_code->granulepos=0;
  108188. op_code->packetno=2;
  108189. oggpack_writeclear(&opb);
  108190. return(0);
  108191. err_out:
  108192. oggpack_writeclear(&opb);
  108193. memset(op,0,sizeof(*op));
  108194. memset(op_comm,0,sizeof(*op_comm));
  108195. memset(op_code,0,sizeof(*op_code));
  108196. if(b->header)_ogg_free(b->header);
  108197. if(b->header1)_ogg_free(b->header1);
  108198. if(b->header2)_ogg_free(b->header2);
  108199. b->header=NULL;
  108200. b->header1=NULL;
  108201. b->header2=NULL;
  108202. return(ret);
  108203. }
  108204. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  108205. if(granulepos>=0)
  108206. return((double)granulepos/v->vi->rate);
  108207. return(-1);
  108208. }
  108209. #endif
  108210. /********* End of inlined file: info.c *********/
  108211. /********* Start of inlined file: lpc.c *********/
  108212. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  108213. are derived from code written by Jutta Degener and Carsten Bormann;
  108214. thus we include their copyright below. The entirety of this file
  108215. is freely redistributable on the condition that both of these
  108216. copyright notices are preserved without modification. */
  108217. /* Preserved Copyright: *********************************************/
  108218. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  108219. Technische Universita"t Berlin
  108220. Any use of this software is permitted provided that this notice is not
  108221. removed and that neither the authors nor the Technische Universita"t
  108222. Berlin are deemed to have made any representations as to the
  108223. suitability of this software for any purpose nor are held responsible
  108224. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  108225. THIS SOFTWARE.
  108226. As a matter of courtesy, the authors request to be informed about uses
  108227. this software has found, about bugs in this software, and about any
  108228. improvements that may be of general interest.
  108229. Berlin, 28.11.1994
  108230. Jutta Degener
  108231. Carsten Bormann
  108232. *********************************************************************/
  108233. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108234. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108235. // tasks..
  108236. #ifdef _MSC_VER
  108237. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108238. #endif
  108239. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108240. #if JUCE_USE_OGGVORBIS
  108241. #include <stdlib.h>
  108242. #include <string.h>
  108243. #include <math.h>
  108244. /* Autocorrelation LPC coeff generation algorithm invented by
  108245. N. Levinson in 1947, modified by J. Durbin in 1959. */
  108246. /* Input : n elements of time doamin data
  108247. Output: m lpc coefficients, excitation energy */
  108248. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  108249. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  108250. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  108251. double error;
  108252. int i,j;
  108253. /* autocorrelation, p+1 lag coefficients */
  108254. j=m+1;
  108255. while(j--){
  108256. double d=0; /* double needed for accumulator depth */
  108257. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  108258. aut[j]=d;
  108259. }
  108260. /* Generate lpc coefficients from autocorr values */
  108261. error=aut[0];
  108262. for(i=0;i<m;i++){
  108263. double r= -aut[i+1];
  108264. if(error==0){
  108265. memset(lpci,0,m*sizeof(*lpci));
  108266. return 0;
  108267. }
  108268. /* Sum up this iteration's reflection coefficient; note that in
  108269. Vorbis we don't save it. If anyone wants to recycle this code
  108270. and needs reflection coefficients, save the results of 'r' from
  108271. each iteration. */
  108272. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  108273. r/=error;
  108274. /* Update LPC coefficients and total error */
  108275. lpc[i]=r;
  108276. for(j=0;j<i/2;j++){
  108277. double tmp=lpc[j];
  108278. lpc[j]+=r*lpc[i-1-j];
  108279. lpc[i-1-j]+=r*tmp;
  108280. }
  108281. if(i%2)lpc[j]+=lpc[j]*r;
  108282. error*=1.f-r*r;
  108283. }
  108284. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  108285. /* we need the error value to know how big an impulse to hit the
  108286. filter with later */
  108287. return error;
  108288. }
  108289. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  108290. float *data,long n){
  108291. /* in: coeff[0...m-1] LPC coefficients
  108292. prime[0...m-1] initial values (allocated size of n+m-1)
  108293. out: data[0...n-1] data samples */
  108294. long i,j,o,p;
  108295. float y;
  108296. float *work=(float*)alloca(sizeof(*work)*(m+n));
  108297. if(!prime)
  108298. for(i=0;i<m;i++)
  108299. work[i]=0.f;
  108300. else
  108301. for(i=0;i<m;i++)
  108302. work[i]=prime[i];
  108303. for(i=0;i<n;i++){
  108304. y=0;
  108305. o=i;
  108306. p=m;
  108307. for(j=0;j<m;j++)
  108308. y-=work[o++]*coeff[--p];
  108309. data[i]=work[o]=y;
  108310. }
  108311. }
  108312. #endif
  108313. /********* End of inlined file: lpc.c *********/
  108314. /********* Start of inlined file: lsp.c *********/
  108315. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  108316. an iterative root polisher (CACM algorithm 283). It *is* possible
  108317. to confuse this algorithm into not converging; that should only
  108318. happen with absurdly closely spaced roots (very sharp peaks in the
  108319. LPC f response) which in turn should be impossible in our use of
  108320. the code. If this *does* happen anyway, it's a bug in the floor
  108321. finder; find the cause of the confusion (probably a single bin
  108322. spike or accidental near-float-limit resolution problems) and
  108323. correct it. */
  108324. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108325. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108326. // tasks..
  108327. #ifdef _MSC_VER
  108328. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108329. #endif
  108330. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108331. #if JUCE_USE_OGGVORBIS
  108332. #include <math.h>
  108333. #include <string.h>
  108334. #include <stdlib.h>
  108335. /********* Start of inlined file: lookup.h *********/
  108336. #ifndef _V_LOOKUP_H_
  108337. #ifdef FLOAT_LOOKUP
  108338. extern float vorbis_coslook(float a);
  108339. extern float vorbis_invsqlook(float a);
  108340. extern float vorbis_invsq2explook(int a);
  108341. extern float vorbis_fromdBlook(float a);
  108342. #endif
  108343. #ifdef INT_LOOKUP
  108344. extern long vorbis_invsqlook_i(long a,long e);
  108345. extern long vorbis_coslook_i(long a);
  108346. extern float vorbis_fromdBlook_i(long a);
  108347. #endif
  108348. #endif
  108349. /********* End of inlined file: lookup.h *********/
  108350. /* three possible LSP to f curve functions; the exact computation
  108351. (float), a lookup based float implementation, and an integer
  108352. implementation. The float lookup is likely the optimal choice on
  108353. any machine with an FPU. The integer implementation is *not* fixed
  108354. point (due to the need for a large dynamic range and thus a
  108355. seperately tracked exponent) and thus much more complex than the
  108356. relatively simple float implementations. It's mostly for future
  108357. work on a fully fixed point implementation for processors like the
  108358. ARM family. */
  108359. /* undefine both for the 'old' but more precise implementation */
  108360. #define FLOAT_LOOKUP
  108361. #undef INT_LOOKUP
  108362. #ifdef FLOAT_LOOKUP
  108363. /********* Start of inlined file: lookup.c *********/
  108364. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108365. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108366. // tasks..
  108367. #ifdef _MSC_VER
  108368. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108369. #endif
  108370. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108371. #if JUCE_USE_OGGVORBIS
  108372. #include <math.h>
  108373. /********* Start of inlined file: lookup.h *********/
  108374. #ifndef _V_LOOKUP_H_
  108375. #ifdef FLOAT_LOOKUP
  108376. extern float vorbis_coslook(float a);
  108377. extern float vorbis_invsqlook(float a);
  108378. extern float vorbis_invsq2explook(int a);
  108379. extern float vorbis_fromdBlook(float a);
  108380. #endif
  108381. #ifdef INT_LOOKUP
  108382. extern long vorbis_invsqlook_i(long a,long e);
  108383. extern long vorbis_coslook_i(long a);
  108384. extern float vorbis_fromdBlook_i(long a);
  108385. #endif
  108386. #endif
  108387. /********* End of inlined file: lookup.h *********/
  108388. /********* Start of inlined file: lookup_data.h *********/
  108389. #ifndef _V_LOOKUP_DATA_H_
  108390. #ifdef FLOAT_LOOKUP
  108391. #define COS_LOOKUP_SZ 128
  108392. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  108393. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  108394. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  108395. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  108396. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  108397. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  108398. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  108399. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  108400. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  108401. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  108402. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  108403. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  108404. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  108405. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  108406. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  108407. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  108408. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  108409. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  108410. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  108411. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  108412. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  108413. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  108414. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  108415. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  108416. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  108417. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  108418. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  108419. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  108420. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  108421. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  108422. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  108423. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  108424. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  108425. -1.0000000000000f,
  108426. };
  108427. #define INVSQ_LOOKUP_SZ 32
  108428. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  108429. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  108430. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  108431. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  108432. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  108433. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  108434. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  108435. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  108436. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  108437. 1.000000000000f,
  108438. };
  108439. #define INVSQ2EXP_LOOKUP_MIN (-32)
  108440. #define INVSQ2EXP_LOOKUP_MAX 32
  108441. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  108442. INVSQ2EXP_LOOKUP_MIN+1]={
  108443. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  108444. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  108445. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  108446. 1024.f, 724.0773439f, 512.f, 362.038672f,
  108447. 256.f, 181.019336f, 128.f, 90.50966799f,
  108448. 64.f, 45.254834f, 32.f, 22.627417f,
  108449. 16.f, 11.3137085f, 8.f, 5.656854249f,
  108450. 4.f, 2.828427125f, 2.f, 1.414213562f,
  108451. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  108452. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  108453. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  108454. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  108455. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  108456. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  108457. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  108458. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  108459. 1.525878906e-05f,
  108460. };
  108461. #endif
  108462. #define FROMdB_LOOKUP_SZ 35
  108463. #define FROMdB2_LOOKUP_SZ 32
  108464. #define FROMdB_SHIFT 5
  108465. #define FROMdB2_SHIFT 3
  108466. #define FROMdB2_MASK 31
  108467. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  108468. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  108469. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  108470. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  108471. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  108472. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  108473. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  108474. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  108475. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  108476. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  108477. };
  108478. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  108479. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  108480. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  108481. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  108482. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  108483. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  108484. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  108485. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  108486. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  108487. };
  108488. #ifdef INT_LOOKUP
  108489. #define INVSQ_LOOKUP_I_SHIFT 10
  108490. #define INVSQ_LOOKUP_I_MASK 1023
  108491. static long INVSQ_LOOKUP_I[64+1]={
  108492. 92682l, 91966l, 91267l, 90583l,
  108493. 89915l, 89261l, 88621l, 87995l,
  108494. 87381l, 86781l, 86192l, 85616l,
  108495. 85051l, 84497l, 83953l, 83420l,
  108496. 82897l, 82384l, 81880l, 81385l,
  108497. 80899l, 80422l, 79953l, 79492l,
  108498. 79039l, 78594l, 78156l, 77726l,
  108499. 77302l, 76885l, 76475l, 76072l,
  108500. 75674l, 75283l, 74898l, 74519l,
  108501. 74146l, 73778l, 73415l, 73058l,
  108502. 72706l, 72359l, 72016l, 71679l,
  108503. 71347l, 71019l, 70695l, 70376l,
  108504. 70061l, 69750l, 69444l, 69141l,
  108505. 68842l, 68548l, 68256l, 67969l,
  108506. 67685l, 67405l, 67128l, 66855l,
  108507. 66585l, 66318l, 66054l, 65794l,
  108508. 65536l,
  108509. };
  108510. #define COS_LOOKUP_I_SHIFT 9
  108511. #define COS_LOOKUP_I_MASK 511
  108512. #define COS_LOOKUP_I_SZ 128
  108513. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  108514. 16384l, 16379l, 16364l, 16340l,
  108515. 16305l, 16261l, 16207l, 16143l,
  108516. 16069l, 15986l, 15893l, 15791l,
  108517. 15679l, 15557l, 15426l, 15286l,
  108518. 15137l, 14978l, 14811l, 14635l,
  108519. 14449l, 14256l, 14053l, 13842l,
  108520. 13623l, 13395l, 13160l, 12916l,
  108521. 12665l, 12406l, 12140l, 11866l,
  108522. 11585l, 11297l, 11003l, 10702l,
  108523. 10394l, 10080l, 9760l, 9434l,
  108524. 9102l, 8765l, 8423l, 8076l,
  108525. 7723l, 7366l, 7005l, 6639l,
  108526. 6270l, 5897l, 5520l, 5139l,
  108527. 4756l, 4370l, 3981l, 3590l,
  108528. 3196l, 2801l, 2404l, 2006l,
  108529. 1606l, 1205l, 804l, 402l,
  108530. 0l, -401l, -803l, -1204l,
  108531. -1605l, -2005l, -2403l, -2800l,
  108532. -3195l, -3589l, -3980l, -4369l,
  108533. -4755l, -5138l, -5519l, -5896l,
  108534. -6269l, -6638l, -7004l, -7365l,
  108535. -7722l, -8075l, -8422l, -8764l,
  108536. -9101l, -9433l, -9759l, -10079l,
  108537. -10393l, -10701l, -11002l, -11296l,
  108538. -11584l, -11865l, -12139l, -12405l,
  108539. -12664l, -12915l, -13159l, -13394l,
  108540. -13622l, -13841l, -14052l, -14255l,
  108541. -14448l, -14634l, -14810l, -14977l,
  108542. -15136l, -15285l, -15425l, -15556l,
  108543. -15678l, -15790l, -15892l, -15985l,
  108544. -16068l, -16142l, -16206l, -16260l,
  108545. -16304l, -16339l, -16363l, -16378l,
  108546. -16383l,
  108547. };
  108548. #endif
  108549. #endif
  108550. /********* End of inlined file: lookup_data.h *********/
  108551. #ifdef FLOAT_LOOKUP
  108552. /* interpolated lookup based cos function, domain 0 to PI only */
  108553. float vorbis_coslook(float a){
  108554. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  108555. int i=vorbis_ftoi(d-.5);
  108556. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  108557. }
  108558. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  108559. float vorbis_invsqlook(float a){
  108560. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  108561. int i=vorbis_ftoi(d-.5f);
  108562. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  108563. }
  108564. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  108565. float vorbis_invsq2explook(int a){
  108566. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  108567. }
  108568. #include <stdio.h>
  108569. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  108570. float vorbis_fromdBlook(float a){
  108571. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  108572. return (i<0)?1.f:
  108573. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  108574. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  108575. }
  108576. #endif
  108577. #ifdef INT_LOOKUP
  108578. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  108579. 16.16 format
  108580. returns in m.8 format */
  108581. long vorbis_invsqlook_i(long a,long e){
  108582. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  108583. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  108584. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  108585. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  108586. d)>>16); /* result 1.16 */
  108587. e+=32;
  108588. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  108589. e=(e>>1)-8;
  108590. return(val>>e);
  108591. }
  108592. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  108593. /* a is in n.12 format */
  108594. float vorbis_fromdBlook_i(long a){
  108595. int i=(-a)>>(12-FROMdB2_SHIFT);
  108596. return (i<0)?1.f:
  108597. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  108598. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  108599. }
  108600. /* interpolated lookup based cos function, domain 0 to PI only */
  108601. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  108602. long vorbis_coslook_i(long a){
  108603. int i=a>>COS_LOOKUP_I_SHIFT;
  108604. int d=a&COS_LOOKUP_I_MASK;
  108605. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  108606. COS_LOOKUP_I_SHIFT);
  108607. }
  108608. #endif
  108609. #endif
  108610. /********* End of inlined file: lookup.c *********/
  108611. /* catch this in the build system; we #include for
  108612. compilers (like gcc) that can't inline across
  108613. modules */
  108614. /* side effect: changes *lsp to cosines of lsp */
  108615. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  108616. float amp,float ampoffset){
  108617. int i;
  108618. float wdel=M_PI/ln;
  108619. vorbis_fpu_control fpu;
  108620. (void) fpu; // to avoid an unused variable warning
  108621. vorbis_fpu_setround(&fpu);
  108622. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  108623. i=0;
  108624. while(i<n){
  108625. int k=map[i];
  108626. int qexp;
  108627. float p=.7071067812f;
  108628. float q=.7071067812f;
  108629. float w=vorbis_coslook(wdel*k);
  108630. float *ftmp=lsp;
  108631. int c=m>>1;
  108632. do{
  108633. q*=ftmp[0]-w;
  108634. p*=ftmp[1]-w;
  108635. ftmp+=2;
  108636. }while(--c);
  108637. if(m&1){
  108638. /* odd order filter; slightly assymetric */
  108639. /* the last coefficient */
  108640. q*=ftmp[0]-w;
  108641. q*=q;
  108642. p*=p*(1.f-w*w);
  108643. }else{
  108644. /* even order filter; still symmetric */
  108645. q*=q*(1.f+w);
  108646. p*=p*(1.f-w);
  108647. }
  108648. q=frexp(p+q,&qexp);
  108649. q=vorbis_fromdBlook(amp*
  108650. vorbis_invsqlook(q)*
  108651. vorbis_invsq2explook(qexp+m)-
  108652. ampoffset);
  108653. do{
  108654. curve[i++]*=q;
  108655. }while(map[i]==k);
  108656. }
  108657. vorbis_fpu_restore(fpu);
  108658. }
  108659. #else
  108660. #ifdef INT_LOOKUP
  108661. /********* Start of inlined file: lookup.c *********/
  108662. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108663. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108664. // tasks..
  108665. #ifdef _MSC_VER
  108666. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108667. #endif
  108668. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108669. #if JUCE_USE_OGGVORBIS
  108670. #include <math.h>
  108671. /********* Start of inlined file: lookup.h *********/
  108672. #ifndef _V_LOOKUP_H_
  108673. #ifdef FLOAT_LOOKUP
  108674. extern float vorbis_coslook(float a);
  108675. extern float vorbis_invsqlook(float a);
  108676. extern float vorbis_invsq2explook(int a);
  108677. extern float vorbis_fromdBlook(float a);
  108678. #endif
  108679. #ifdef INT_LOOKUP
  108680. extern long vorbis_invsqlook_i(long a,long e);
  108681. extern long vorbis_coslook_i(long a);
  108682. extern float vorbis_fromdBlook_i(long a);
  108683. #endif
  108684. #endif
  108685. /********* End of inlined file: lookup.h *********/
  108686. /********* Start of inlined file: lookup_data.h *********/
  108687. #ifndef _V_LOOKUP_DATA_H_
  108688. #ifdef FLOAT_LOOKUP
  108689. #define COS_LOOKUP_SZ 128
  108690. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  108691. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  108692. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  108693. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  108694. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  108695. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  108696. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  108697. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  108698. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  108699. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  108700. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  108701. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  108702. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  108703. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  108704. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  108705. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  108706. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  108707. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  108708. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  108709. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  108710. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  108711. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  108712. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  108713. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  108714. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  108715. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  108716. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  108717. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  108718. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  108719. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  108720. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  108721. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  108722. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  108723. -1.0000000000000f,
  108724. };
  108725. #define INVSQ_LOOKUP_SZ 32
  108726. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  108727. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  108728. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  108729. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  108730. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  108731. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  108732. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  108733. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  108734. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  108735. 1.000000000000f,
  108736. };
  108737. #define INVSQ2EXP_LOOKUP_MIN (-32)
  108738. #define INVSQ2EXP_LOOKUP_MAX 32
  108739. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  108740. INVSQ2EXP_LOOKUP_MIN+1]={
  108741. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  108742. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  108743. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  108744. 1024.f, 724.0773439f, 512.f, 362.038672f,
  108745. 256.f, 181.019336f, 128.f, 90.50966799f,
  108746. 64.f, 45.254834f, 32.f, 22.627417f,
  108747. 16.f, 11.3137085f, 8.f, 5.656854249f,
  108748. 4.f, 2.828427125f, 2.f, 1.414213562f,
  108749. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  108750. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  108751. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  108752. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  108753. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  108754. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  108755. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  108756. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  108757. 1.525878906e-05f,
  108758. };
  108759. #endif
  108760. #define FROMdB_LOOKUP_SZ 35
  108761. #define FROMdB2_LOOKUP_SZ 32
  108762. #define FROMdB_SHIFT 5
  108763. #define FROMdB2_SHIFT 3
  108764. #define FROMdB2_MASK 31
  108765. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  108766. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  108767. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  108768. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  108769. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  108770. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  108771. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  108772. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  108773. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  108774. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  108775. };
  108776. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  108777. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  108778. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  108779. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  108780. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  108781. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  108782. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  108783. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  108784. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  108785. };
  108786. #ifdef INT_LOOKUP
  108787. #define INVSQ_LOOKUP_I_SHIFT 10
  108788. #define INVSQ_LOOKUP_I_MASK 1023
  108789. static long INVSQ_LOOKUP_I[64+1]={
  108790. 92682l, 91966l, 91267l, 90583l,
  108791. 89915l, 89261l, 88621l, 87995l,
  108792. 87381l, 86781l, 86192l, 85616l,
  108793. 85051l, 84497l, 83953l, 83420l,
  108794. 82897l, 82384l, 81880l, 81385l,
  108795. 80899l, 80422l, 79953l, 79492l,
  108796. 79039l, 78594l, 78156l, 77726l,
  108797. 77302l, 76885l, 76475l, 76072l,
  108798. 75674l, 75283l, 74898l, 74519l,
  108799. 74146l, 73778l, 73415l, 73058l,
  108800. 72706l, 72359l, 72016l, 71679l,
  108801. 71347l, 71019l, 70695l, 70376l,
  108802. 70061l, 69750l, 69444l, 69141l,
  108803. 68842l, 68548l, 68256l, 67969l,
  108804. 67685l, 67405l, 67128l, 66855l,
  108805. 66585l, 66318l, 66054l, 65794l,
  108806. 65536l,
  108807. };
  108808. #define COS_LOOKUP_I_SHIFT 9
  108809. #define COS_LOOKUP_I_MASK 511
  108810. #define COS_LOOKUP_I_SZ 128
  108811. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  108812. 16384l, 16379l, 16364l, 16340l,
  108813. 16305l, 16261l, 16207l, 16143l,
  108814. 16069l, 15986l, 15893l, 15791l,
  108815. 15679l, 15557l, 15426l, 15286l,
  108816. 15137l, 14978l, 14811l, 14635l,
  108817. 14449l, 14256l, 14053l, 13842l,
  108818. 13623l, 13395l, 13160l, 12916l,
  108819. 12665l, 12406l, 12140l, 11866l,
  108820. 11585l, 11297l, 11003l, 10702l,
  108821. 10394l, 10080l, 9760l, 9434l,
  108822. 9102l, 8765l, 8423l, 8076l,
  108823. 7723l, 7366l, 7005l, 6639l,
  108824. 6270l, 5897l, 5520l, 5139l,
  108825. 4756l, 4370l, 3981l, 3590l,
  108826. 3196l, 2801l, 2404l, 2006l,
  108827. 1606l, 1205l, 804l, 402l,
  108828. 0l, -401l, -803l, -1204l,
  108829. -1605l, -2005l, -2403l, -2800l,
  108830. -3195l, -3589l, -3980l, -4369l,
  108831. -4755l, -5138l, -5519l, -5896l,
  108832. -6269l, -6638l, -7004l, -7365l,
  108833. -7722l, -8075l, -8422l, -8764l,
  108834. -9101l, -9433l, -9759l, -10079l,
  108835. -10393l, -10701l, -11002l, -11296l,
  108836. -11584l, -11865l, -12139l, -12405l,
  108837. -12664l, -12915l, -13159l, -13394l,
  108838. -13622l, -13841l, -14052l, -14255l,
  108839. -14448l, -14634l, -14810l, -14977l,
  108840. -15136l, -15285l, -15425l, -15556l,
  108841. -15678l, -15790l, -15892l, -15985l,
  108842. -16068l, -16142l, -16206l, -16260l,
  108843. -16304l, -16339l, -16363l, -16378l,
  108844. -16383l,
  108845. };
  108846. #endif
  108847. #endif
  108848. /********* End of inlined file: lookup_data.h *********/
  108849. #ifdef FLOAT_LOOKUP
  108850. /* interpolated lookup based cos function, domain 0 to PI only */
  108851. float vorbis_coslook(float a){
  108852. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  108853. int i=vorbis_ftoi(d-.5);
  108854. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  108855. }
  108856. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  108857. float vorbis_invsqlook(float a){
  108858. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  108859. int i=vorbis_ftoi(d-.5f);
  108860. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  108861. }
  108862. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  108863. float vorbis_invsq2explook(int a){
  108864. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  108865. }
  108866. #include <stdio.h>
  108867. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  108868. float vorbis_fromdBlook(float a){
  108869. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  108870. return (i<0)?1.f:
  108871. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  108872. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  108873. }
  108874. #endif
  108875. #ifdef INT_LOOKUP
  108876. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  108877. 16.16 format
  108878. returns in m.8 format */
  108879. long vorbis_invsqlook_i(long a,long e){
  108880. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  108881. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  108882. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  108883. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  108884. d)>>16); /* result 1.16 */
  108885. e+=32;
  108886. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  108887. e=(e>>1)-8;
  108888. return(val>>e);
  108889. }
  108890. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  108891. /* a is in n.12 format */
  108892. float vorbis_fromdBlook_i(long a){
  108893. int i=(-a)>>(12-FROMdB2_SHIFT);
  108894. return (i<0)?1.f:
  108895. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  108896. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  108897. }
  108898. /* interpolated lookup based cos function, domain 0 to PI only */
  108899. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  108900. long vorbis_coslook_i(long a){
  108901. int i=a>>COS_LOOKUP_I_SHIFT;
  108902. int d=a&COS_LOOKUP_I_MASK;
  108903. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  108904. COS_LOOKUP_I_SHIFT);
  108905. }
  108906. #endif
  108907. #endif
  108908. /********* End of inlined file: lookup.c *********/
  108909. /* catch this in the build system; we #include for
  108910. compilers (like gcc) that can't inline across
  108911. modules */
  108912. static int MLOOP_1[64]={
  108913. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  108914. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  108915. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  108916. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  108917. };
  108918. static int MLOOP_2[64]={
  108919. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  108920. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  108921. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  108922. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  108923. };
  108924. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  108925. /* side effect: changes *lsp to cosines of lsp */
  108926. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  108927. float amp,float ampoffset){
  108928. /* 0 <= m < 256 */
  108929. /* set up for using all int later */
  108930. int i;
  108931. int ampoffseti=rint(ampoffset*4096.f);
  108932. int ampi=rint(amp*16.f);
  108933. long *ilsp=alloca(m*sizeof(*ilsp));
  108934. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  108935. i=0;
  108936. while(i<n){
  108937. int j,k=map[i];
  108938. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  108939. unsigned long qi=46341;
  108940. int qexp=0,shift;
  108941. long wi=vorbis_coslook_i(k*65536/ln);
  108942. qi*=labs(ilsp[0]-wi);
  108943. pi*=labs(ilsp[1]-wi);
  108944. for(j=3;j<m;j+=2){
  108945. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  108946. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  108947. shift=MLOOP_3[(pi|qi)>>16];
  108948. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  108949. pi=(pi>>shift)*labs(ilsp[j]-wi);
  108950. qexp+=shift;
  108951. }
  108952. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  108953. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  108954. shift=MLOOP_3[(pi|qi)>>16];
  108955. /* pi,qi normalized collectively, both tracked using qexp */
  108956. if(m&1){
  108957. /* odd order filter; slightly assymetric */
  108958. /* the last coefficient */
  108959. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  108960. pi=(pi>>shift)<<14;
  108961. qexp+=shift;
  108962. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  108963. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  108964. shift=MLOOP_3[(pi|qi)>>16];
  108965. pi>>=shift;
  108966. qi>>=shift;
  108967. qexp+=shift-14*((m+1)>>1);
  108968. pi=((pi*pi)>>16);
  108969. qi=((qi*qi)>>16);
  108970. qexp=qexp*2+m;
  108971. pi*=(1<<14)-((wi*wi)>>14);
  108972. qi+=pi>>14;
  108973. }else{
  108974. /* even order filter; still symmetric */
  108975. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  108976. worth tracking step by step */
  108977. pi>>=shift;
  108978. qi>>=shift;
  108979. qexp+=shift-7*m;
  108980. pi=((pi*pi)>>16);
  108981. qi=((qi*qi)>>16);
  108982. qexp=qexp*2+m;
  108983. pi*=(1<<14)-wi;
  108984. qi*=(1<<14)+wi;
  108985. qi=(qi+pi)>>14;
  108986. }
  108987. /* we've let the normalization drift because it wasn't important;
  108988. however, for the lookup, things must be normalized again. We
  108989. need at most one right shift or a number of left shifts */
  108990. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  108991. qi>>=1; qexp++;
  108992. }else
  108993. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  108994. qi<<=1; qexp--;
  108995. }
  108996. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  108997. vorbis_invsqlook_i(qi,qexp)-
  108998. /* m.8, m+n<=8 */
  108999. ampoffseti); /* 8.12[0] */
  109000. curve[i]*=amp;
  109001. while(map[++i]==k)curve[i]*=amp;
  109002. }
  109003. }
  109004. #else
  109005. /* old, nonoptimized but simple version for any poor sap who needs to
  109006. figure out what the hell this code does, or wants the other
  109007. fraction of a dB precision */
  109008. /* side effect: changes *lsp to cosines of lsp */
  109009. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  109010. float amp,float ampoffset){
  109011. int i;
  109012. float wdel=M_PI/ln;
  109013. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  109014. i=0;
  109015. while(i<n){
  109016. int j,k=map[i];
  109017. float p=.5f;
  109018. float q=.5f;
  109019. float w=2.f*cos(wdel*k);
  109020. for(j=1;j<m;j+=2){
  109021. q *= w-lsp[j-1];
  109022. p *= w-lsp[j];
  109023. }
  109024. if(j==m){
  109025. /* odd order filter; slightly assymetric */
  109026. /* the last coefficient */
  109027. q*=w-lsp[j-1];
  109028. p*=p*(4.f-w*w);
  109029. q*=q;
  109030. }else{
  109031. /* even order filter; still symmetric */
  109032. p*=p*(2.f-w);
  109033. q*=q*(2.f+w);
  109034. }
  109035. q=fromdB(amp/sqrt(p+q)-ampoffset);
  109036. curve[i]*=q;
  109037. while(map[++i]==k)curve[i]*=q;
  109038. }
  109039. }
  109040. #endif
  109041. #endif
  109042. static void cheby(float *g, int ord) {
  109043. int i, j;
  109044. g[0] *= .5f;
  109045. for(i=2; i<= ord; i++) {
  109046. for(j=ord; j >= i; j--) {
  109047. g[j-2] -= g[j];
  109048. g[j] += g[j];
  109049. }
  109050. }
  109051. }
  109052. static int comp(const void *a,const void *b){
  109053. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  109054. }
  109055. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  109056. but there are root sets for which it gets into limit cycles
  109057. (exacerbated by zero suppression) and fails. We can't afford to
  109058. fail, even if the failure is 1 in 100,000,000, so we now use
  109059. Laguerre and later polish with Newton-Raphson (which can then
  109060. afford to fail) */
  109061. #define EPSILON 10e-7
  109062. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  109063. int i,m;
  109064. double lastdelta=0.f;
  109065. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  109066. for(i=0;i<=ord;i++)defl[i]=a[i];
  109067. for(m=ord;m>0;m--){
  109068. double newx=0.f,delta;
  109069. /* iterate a root */
  109070. while(1){
  109071. double p=defl[m],pp=0.f,ppp=0.f,denom;
  109072. /* eval the polynomial and its first two derivatives */
  109073. for(i=m;i>0;i--){
  109074. ppp = newx*ppp + pp;
  109075. pp = newx*pp + p;
  109076. p = newx*p + defl[i-1];
  109077. }
  109078. /* Laguerre's method */
  109079. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  109080. if(denom<0)
  109081. return(-1); /* complex root! The LPC generator handed us a bad filter */
  109082. if(pp>0){
  109083. denom = pp + sqrt(denom);
  109084. if(denom<EPSILON)denom=EPSILON;
  109085. }else{
  109086. denom = pp - sqrt(denom);
  109087. if(denom>-(EPSILON))denom=-(EPSILON);
  109088. }
  109089. delta = m*p/denom;
  109090. newx -= delta;
  109091. if(delta<0.f)delta*=-1;
  109092. if(fabs(delta/newx)<10e-12)break;
  109093. lastdelta=delta;
  109094. }
  109095. r[m-1]=newx;
  109096. /* forward deflation */
  109097. for(i=m;i>0;i--)
  109098. defl[i-1]+=newx*defl[i];
  109099. defl++;
  109100. }
  109101. return(0);
  109102. }
  109103. /* for spit-and-polish only */
  109104. static int Newton_Raphson(float *a,int ord,float *r){
  109105. int i, k, count=0;
  109106. double error=1.f;
  109107. double *root=(double*)alloca(ord*sizeof(*root));
  109108. for(i=0; i<ord;i++) root[i] = r[i];
  109109. while(error>1e-20){
  109110. error=0;
  109111. for(i=0; i<ord; i++) { /* Update each point. */
  109112. double pp=0.,delta;
  109113. double rooti=root[i];
  109114. double p=a[ord];
  109115. for(k=ord-1; k>= 0; k--) {
  109116. pp= pp* rooti + p;
  109117. p = p * rooti + a[k];
  109118. }
  109119. delta = p/pp;
  109120. root[i] -= delta;
  109121. error+= delta*delta;
  109122. }
  109123. if(count>40)return(-1);
  109124. count++;
  109125. }
  109126. /* Replaced the original bubble sort with a real sort. With your
  109127. help, we can eliminate the bubble sort in our lifetime. --Monty */
  109128. for(i=0; i<ord;i++) r[i] = root[i];
  109129. return(0);
  109130. }
  109131. /* Convert lpc coefficients to lsp coefficients */
  109132. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  109133. int order2=(m+1)>>1;
  109134. int g1_order,g2_order;
  109135. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  109136. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  109137. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  109138. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  109139. int i;
  109140. /* even and odd are slightly different base cases */
  109141. g1_order=(m+1)>>1;
  109142. g2_order=(m) >>1;
  109143. /* Compute the lengths of the x polynomials. */
  109144. /* Compute the first half of K & R F1 & F2 polynomials. */
  109145. /* Compute half of the symmetric and antisymmetric polynomials. */
  109146. /* Remove the roots at +1 and -1. */
  109147. g1[g1_order] = 1.f;
  109148. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  109149. g2[g2_order] = 1.f;
  109150. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  109151. if(g1_order>g2_order){
  109152. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  109153. }else{
  109154. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  109155. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  109156. }
  109157. /* Convert into polynomials in cos(alpha) */
  109158. cheby(g1,g1_order);
  109159. cheby(g2,g2_order);
  109160. /* Find the roots of the 2 even polynomials.*/
  109161. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  109162. Laguerre_With_Deflation(g2,g2_order,g2r))
  109163. return(-1);
  109164. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  109165. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  109166. qsort(g1r,g1_order,sizeof(*g1r),comp);
  109167. qsort(g2r,g2_order,sizeof(*g2r),comp);
  109168. for(i=0;i<g1_order;i++)
  109169. lsp[i*2] = acos(g1r[i]);
  109170. for(i=0;i<g2_order;i++)
  109171. lsp[i*2+1] = acos(g2r[i]);
  109172. return(0);
  109173. }
  109174. #endif
  109175. /********* End of inlined file: lsp.c *********/
  109176. /********* Start of inlined file: mapping0.c *********/
  109177. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109178. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109179. // tasks..
  109180. #ifdef _MSC_VER
  109181. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109182. #endif
  109183. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109184. #if JUCE_USE_OGGVORBIS
  109185. #include <stdlib.h>
  109186. #include <stdio.h>
  109187. #include <string.h>
  109188. #include <math.h>
  109189. /* simplistic, wasteful way of doing this (unique lookup for each
  109190. mode/submapping); there should be a central repository for
  109191. identical lookups. That will require minor work, so I'm putting it
  109192. off as low priority.
  109193. Why a lookup for each backend in a given mode? Because the
  109194. blocksize is set by the mode, and low backend lookups may require
  109195. parameters from other areas of the mode/mapping */
  109196. static void mapping0_free_info(vorbis_info_mapping *i){
  109197. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  109198. if(info){
  109199. memset(info,0,sizeof(*info));
  109200. _ogg_free(info);
  109201. }
  109202. }
  109203. static int ilog3(unsigned int v){
  109204. int ret=0;
  109205. if(v)--v;
  109206. while(v){
  109207. ret++;
  109208. v>>=1;
  109209. }
  109210. return(ret);
  109211. }
  109212. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  109213. oggpack_buffer *opb){
  109214. int i;
  109215. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  109216. /* another 'we meant to do it this way' hack... up to beta 4, we
  109217. packed 4 binary zeros here to signify one submapping in use. We
  109218. now redefine that to mean four bitflags that indicate use of
  109219. deeper features; bit0:submappings, bit1:coupling,
  109220. bit2,3:reserved. This is backward compatable with all actual uses
  109221. of the beta code. */
  109222. if(info->submaps>1){
  109223. oggpack_write(opb,1,1);
  109224. oggpack_write(opb,info->submaps-1,4);
  109225. }else
  109226. oggpack_write(opb,0,1);
  109227. if(info->coupling_steps>0){
  109228. oggpack_write(opb,1,1);
  109229. oggpack_write(opb,info->coupling_steps-1,8);
  109230. for(i=0;i<info->coupling_steps;i++){
  109231. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  109232. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  109233. }
  109234. }else
  109235. oggpack_write(opb,0,1);
  109236. oggpack_write(opb,0,2); /* 2,3:reserved */
  109237. /* we don't write the channel submappings if we only have one... */
  109238. if(info->submaps>1){
  109239. for(i=0;i<vi->channels;i++)
  109240. oggpack_write(opb,info->chmuxlist[i],4);
  109241. }
  109242. for(i=0;i<info->submaps;i++){
  109243. oggpack_write(opb,0,8); /* time submap unused */
  109244. oggpack_write(opb,info->floorsubmap[i],8);
  109245. oggpack_write(opb,info->residuesubmap[i],8);
  109246. }
  109247. }
  109248. /* also responsible for range checking */
  109249. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  109250. int i;
  109251. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  109252. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109253. memset(info,0,sizeof(*info));
  109254. if(oggpack_read(opb,1))
  109255. info->submaps=oggpack_read(opb,4)+1;
  109256. else
  109257. info->submaps=1;
  109258. if(oggpack_read(opb,1)){
  109259. info->coupling_steps=oggpack_read(opb,8)+1;
  109260. for(i=0;i<info->coupling_steps;i++){
  109261. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  109262. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  109263. if(testM<0 ||
  109264. testA<0 ||
  109265. testM==testA ||
  109266. testM>=vi->channels ||
  109267. testA>=vi->channels) goto err_out;
  109268. }
  109269. }
  109270. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  109271. if(info->submaps>1){
  109272. for(i=0;i<vi->channels;i++){
  109273. info->chmuxlist[i]=oggpack_read(opb,4);
  109274. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  109275. }
  109276. }
  109277. for(i=0;i<info->submaps;i++){
  109278. oggpack_read(opb,8); /* time submap unused */
  109279. info->floorsubmap[i]=oggpack_read(opb,8);
  109280. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  109281. info->residuesubmap[i]=oggpack_read(opb,8);
  109282. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  109283. }
  109284. return info;
  109285. err_out:
  109286. mapping0_free_info(info);
  109287. return(NULL);
  109288. }
  109289. #if 0
  109290. static long seq=0;
  109291. static ogg_int64_t total=0;
  109292. static float FLOOR1_fromdB_LOOKUP[256]={
  109293. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  109294. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  109295. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  109296. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  109297. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  109298. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  109299. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  109300. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  109301. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  109302. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  109303. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  109304. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  109305. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  109306. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  109307. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  109308. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  109309. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  109310. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  109311. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  109312. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  109313. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  109314. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  109315. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  109316. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  109317. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  109318. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  109319. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  109320. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  109321. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  109322. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  109323. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  109324. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  109325. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  109326. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  109327. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  109328. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  109329. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  109330. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  109331. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  109332. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  109333. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  109334. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  109335. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  109336. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  109337. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  109338. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  109339. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  109340. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  109341. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  109342. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  109343. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  109344. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  109345. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  109346. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  109347. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  109348. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  109349. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  109350. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  109351. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  109352. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  109353. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  109354. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  109355. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  109356. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  109357. };
  109358. #endif
  109359. extern int *floor1_fit(vorbis_block *vb,void *look,
  109360. const float *logmdct, /* in */
  109361. const float *logmask);
  109362. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  109363. int *A,int *B,
  109364. int del);
  109365. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  109366. void*look,
  109367. int *post,int *ilogmask);
  109368. static int mapping0_forward(vorbis_block *vb){
  109369. vorbis_dsp_state *vd=vb->vd;
  109370. vorbis_info *vi=vd->vi;
  109371. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109372. private_state *b=(private_state*)vb->vd->backend_state;
  109373. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  109374. int n=vb->pcmend;
  109375. int i,j,k;
  109376. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  109377. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  109378. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  109379. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  109380. float global_ampmax=vbi->ampmax;
  109381. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  109382. int blocktype=vbi->blocktype;
  109383. int modenumber=vb->W;
  109384. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  109385. vorbis_look_psy *psy_look=
  109386. b->psy+blocktype+(vb->W?2:0);
  109387. vb->mode=modenumber;
  109388. for(i=0;i<vi->channels;i++){
  109389. float scale=4.f/n;
  109390. float scale_dB;
  109391. float *pcm =vb->pcm[i];
  109392. float *logfft =pcm;
  109393. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  109394. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  109395. todB estimation used on IEEE 754
  109396. compliant machines had a bug that
  109397. returned dB values about a third
  109398. of a decibel too high. The bug
  109399. was harmless because tunings
  109400. implicitly took that into
  109401. account. However, fixing the bug
  109402. in the estimator requires
  109403. changing all the tunings as well.
  109404. For now, it's easier to sync
  109405. things back up here, and
  109406. recalibrate the tunings in the
  109407. next major model upgrade. */
  109408. #if 0
  109409. if(vi->channels==2)
  109410. if(i==0)
  109411. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  109412. else
  109413. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  109414. #endif
  109415. /* window the PCM data */
  109416. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  109417. #if 0
  109418. if(vi->channels==2)
  109419. if(i==0)
  109420. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  109421. else
  109422. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  109423. #endif
  109424. /* transform the PCM data */
  109425. /* only MDCT right now.... */
  109426. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  109427. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  109428. drft_forward(&b->fft_look[vb->W],pcm);
  109429. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  109430. original todB estimation used on
  109431. IEEE 754 compliant machines had a
  109432. bug that returned dB values about
  109433. a third of a decibel too high.
  109434. The bug was harmless because
  109435. tunings implicitly took that into
  109436. account. However, fixing the bug
  109437. in the estimator requires
  109438. changing all the tunings as well.
  109439. For now, it's easier to sync
  109440. things back up here, and
  109441. recalibrate the tunings in the
  109442. next major model upgrade. */
  109443. local_ampmax[i]=logfft[0];
  109444. for(j=1;j<n-1;j+=2){
  109445. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  109446. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  109447. .345 is a hack; the original todB
  109448. estimation used on IEEE 754
  109449. compliant machines had a bug that
  109450. returned dB values about a third
  109451. of a decibel too high. The bug
  109452. was harmless because tunings
  109453. implicitly took that into
  109454. account. However, fixing the bug
  109455. in the estimator requires
  109456. changing all the tunings as well.
  109457. For now, it's easier to sync
  109458. things back up here, and
  109459. recalibrate the tunings in the
  109460. next major model upgrade. */
  109461. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  109462. }
  109463. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  109464. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  109465. #if 0
  109466. if(vi->channels==2){
  109467. if(i==0){
  109468. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  109469. }else{
  109470. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  109471. }
  109472. }
  109473. #endif
  109474. }
  109475. {
  109476. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  109477. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  109478. for(i=0;i<vi->channels;i++){
  109479. /* the encoder setup assumes that all the modes used by any
  109480. specific bitrate tweaking use the same floor */
  109481. int submap=info->chmuxlist[i];
  109482. /* the following makes things clearer to *me* anyway */
  109483. float *mdct =gmdct[i];
  109484. float *logfft =vb->pcm[i];
  109485. float *logmdct =logfft+n/2;
  109486. float *logmask =logfft;
  109487. vb->mode=modenumber;
  109488. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  109489. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  109490. for(j=0;j<n/2;j++)
  109491. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  109492. todB estimation used on IEEE 754
  109493. compliant machines had a bug that
  109494. returned dB values about a third
  109495. of a decibel too high. The bug
  109496. was harmless because tunings
  109497. implicitly took that into
  109498. account. However, fixing the bug
  109499. in the estimator requires
  109500. changing all the tunings as well.
  109501. For now, it's easier to sync
  109502. things back up here, and
  109503. recalibrate the tunings in the
  109504. next major model upgrade. */
  109505. #if 0
  109506. if(vi->channels==2){
  109507. if(i==0)
  109508. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  109509. else
  109510. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  109511. }else{
  109512. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  109513. }
  109514. #endif
  109515. /* first step; noise masking. Not only does 'noise masking'
  109516. give us curves from which we can decide how much resolution
  109517. to give noise parts of the spectrum, it also implicitly hands
  109518. us a tonality estimate (the larger the value in the
  109519. 'noise_depth' vector, the more tonal that area is) */
  109520. _vp_noisemask(psy_look,
  109521. logmdct,
  109522. noise); /* noise does not have by-frequency offset
  109523. bias applied yet */
  109524. #if 0
  109525. if(vi->channels==2){
  109526. if(i==0)
  109527. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  109528. else
  109529. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  109530. }
  109531. #endif
  109532. /* second step: 'all the other crap'; all the stuff that isn't
  109533. computed/fit for bitrate management goes in the second psy
  109534. vector. This includes tone masking, peak limiting and ATH */
  109535. _vp_tonemask(psy_look,
  109536. logfft,
  109537. tone,
  109538. global_ampmax,
  109539. local_ampmax[i]);
  109540. #if 0
  109541. if(vi->channels==2){
  109542. if(i==0)
  109543. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  109544. else
  109545. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  109546. }
  109547. #endif
  109548. /* third step; we offset the noise vectors, overlay tone
  109549. masking. We then do a floor1-specific line fit. If we're
  109550. performing bitrate management, the line fit is performed
  109551. multiple times for up/down tweakage on demand. */
  109552. #if 0
  109553. {
  109554. float aotuv[psy_look->n];
  109555. #endif
  109556. _vp_offset_and_mix(psy_look,
  109557. noise,
  109558. tone,
  109559. 1,
  109560. logmask,
  109561. mdct,
  109562. logmdct);
  109563. #if 0
  109564. if(vi->channels==2){
  109565. if(i==0)
  109566. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  109567. else
  109568. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  109569. }
  109570. }
  109571. #endif
  109572. #if 0
  109573. if(vi->channels==2){
  109574. if(i==0)
  109575. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  109576. else
  109577. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  109578. }
  109579. #endif
  109580. /* this algorithm is hardwired to floor 1 for now; abort out if
  109581. we're *not* floor1. This won't happen unless someone has
  109582. broken the encode setup lib. Guard it anyway. */
  109583. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  109584. floor_posts[i][PACKETBLOBS/2]=
  109585. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  109586. logmdct,
  109587. logmask);
  109588. /* are we managing bitrate? If so, perform two more fits for
  109589. later rate tweaking (fits represent hi/lo) */
  109590. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  109591. /* higher rate by way of lower noise curve */
  109592. _vp_offset_and_mix(psy_look,
  109593. noise,
  109594. tone,
  109595. 2,
  109596. logmask,
  109597. mdct,
  109598. logmdct);
  109599. #if 0
  109600. if(vi->channels==2){
  109601. if(i==0)
  109602. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  109603. else
  109604. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  109605. }
  109606. #endif
  109607. floor_posts[i][PACKETBLOBS-1]=
  109608. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  109609. logmdct,
  109610. logmask);
  109611. /* lower rate by way of higher noise curve */
  109612. _vp_offset_and_mix(psy_look,
  109613. noise,
  109614. tone,
  109615. 0,
  109616. logmask,
  109617. mdct,
  109618. logmdct);
  109619. #if 0
  109620. if(vi->channels==2)
  109621. if(i==0)
  109622. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  109623. else
  109624. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  109625. #endif
  109626. floor_posts[i][0]=
  109627. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  109628. logmdct,
  109629. logmask);
  109630. /* we also interpolate a range of intermediate curves for
  109631. intermediate rates */
  109632. for(k=1;k<PACKETBLOBS/2;k++)
  109633. floor_posts[i][k]=
  109634. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  109635. floor_posts[i][0],
  109636. floor_posts[i][PACKETBLOBS/2],
  109637. k*65536/(PACKETBLOBS/2));
  109638. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  109639. floor_posts[i][k]=
  109640. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  109641. floor_posts[i][PACKETBLOBS/2],
  109642. floor_posts[i][PACKETBLOBS-1],
  109643. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  109644. }
  109645. }
  109646. }
  109647. vbi->ampmax=global_ampmax;
  109648. /*
  109649. the next phases are performed once for vbr-only and PACKETBLOB
  109650. times for bitrate managed modes.
  109651. 1) encode actual mode being used
  109652. 2) encode the floor for each channel, compute coded mask curve/res
  109653. 3) normalize and couple.
  109654. 4) encode residue
  109655. 5) save packet bytes to the packetblob vector
  109656. */
  109657. /* iterate over the many masking curve fits we've created */
  109658. {
  109659. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  109660. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  109661. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  109662. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  109663. float **mag_memo;
  109664. int **mag_sort;
  109665. if(info->coupling_steps){
  109666. mag_memo=_vp_quantize_couple_memo(vb,
  109667. &ci->psy_g_param,
  109668. psy_look,
  109669. info,
  109670. gmdct);
  109671. mag_sort=_vp_quantize_couple_sort(vb,
  109672. psy_look,
  109673. info,
  109674. mag_memo);
  109675. hf_reduction(&ci->psy_g_param,
  109676. psy_look,
  109677. info,
  109678. mag_memo);
  109679. }
  109680. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  109681. if(psy_look->vi->normal_channel_p){
  109682. for(i=0;i<vi->channels;i++){
  109683. float *mdct =gmdct[i];
  109684. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  109685. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  109686. }
  109687. }
  109688. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  109689. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  109690. k++){
  109691. oggpack_buffer *opb=vbi->packetblob[k];
  109692. /* start out our new packet blob with packet type and mode */
  109693. /* Encode the packet type */
  109694. oggpack_write(opb,0,1);
  109695. /* Encode the modenumber */
  109696. /* Encode frame mode, pre,post windowsize, then dispatch */
  109697. oggpack_write(opb,modenumber,b->modebits);
  109698. if(vb->W){
  109699. oggpack_write(opb,vb->lW,1);
  109700. oggpack_write(opb,vb->nW,1);
  109701. }
  109702. /* encode floor, compute masking curve, sep out residue */
  109703. for(i=0;i<vi->channels;i++){
  109704. int submap=info->chmuxlist[i];
  109705. float *mdct =gmdct[i];
  109706. float *res =vb->pcm[i];
  109707. int *ilogmask=ilogmaskch[i]=
  109708. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  109709. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  109710. floor_posts[i][k],
  109711. ilogmask);
  109712. #if 0
  109713. {
  109714. char buf[80];
  109715. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  109716. float work[n/2];
  109717. for(j=0;j<n/2;j++)
  109718. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  109719. _analysis_output(buf,seq,work,n/2,1,1,0);
  109720. }
  109721. #endif
  109722. _vp_remove_floor(psy_look,
  109723. mdct,
  109724. ilogmask,
  109725. res,
  109726. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  109727. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  109728. #if 0
  109729. {
  109730. char buf[80];
  109731. float work[n/2];
  109732. for(j=0;j<n/2;j++)
  109733. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  109734. sprintf(buf,"resI%c%d",i?'R':'L',k);
  109735. _analysis_output(buf,seq,work,n/2,1,1,0);
  109736. }
  109737. #endif
  109738. }
  109739. /* our iteration is now based on masking curve, not prequant and
  109740. coupling. Only one prequant/coupling step */
  109741. /* quantize/couple */
  109742. /* incomplete implementation that assumes the tree is all depth
  109743. one, or no tree at all */
  109744. if(info->coupling_steps){
  109745. _vp_couple(k,
  109746. &ci->psy_g_param,
  109747. psy_look,
  109748. info,
  109749. vb->pcm,
  109750. mag_memo,
  109751. mag_sort,
  109752. ilogmaskch,
  109753. nonzero,
  109754. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  109755. }
  109756. /* classify and encode by submap */
  109757. for(i=0;i<info->submaps;i++){
  109758. int ch_in_bundle=0;
  109759. long **classifications;
  109760. int resnum=info->residuesubmap[i];
  109761. for(j=0;j<vi->channels;j++){
  109762. if(info->chmuxlist[j]==i){
  109763. zerobundle[ch_in_bundle]=0;
  109764. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  109765. res_bundle[ch_in_bundle]=vb->pcm[j];
  109766. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  109767. }
  109768. }
  109769. classifications=_residue_P[ci->residue_type[resnum]]->
  109770. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  109771. _residue_P[ci->residue_type[resnum]]->
  109772. forward(opb,vb,b->residue[resnum],
  109773. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  109774. }
  109775. /* ok, done encoding. Next protopacket. */
  109776. }
  109777. }
  109778. #if 0
  109779. seq++;
  109780. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  109781. #endif
  109782. return(0);
  109783. }
  109784. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  109785. vorbis_dsp_state *vd=vb->vd;
  109786. vorbis_info *vi=vd->vi;
  109787. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  109788. private_state *b=(private_state*)vd->backend_state;
  109789. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  109790. int i,j;
  109791. long n=vb->pcmend=ci->blocksizes[vb->W];
  109792. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  109793. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  109794. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  109795. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  109796. /* recover the spectral envelope; store it in the PCM vector for now */
  109797. for(i=0;i<vi->channels;i++){
  109798. int submap=info->chmuxlist[i];
  109799. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  109800. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  109801. if(floormemo[i])
  109802. nonzero[i]=1;
  109803. else
  109804. nonzero[i]=0;
  109805. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  109806. }
  109807. /* channel coupling can 'dirty' the nonzero listing */
  109808. for(i=0;i<info->coupling_steps;i++){
  109809. if(nonzero[info->coupling_mag[i]] ||
  109810. nonzero[info->coupling_ang[i]]){
  109811. nonzero[info->coupling_mag[i]]=1;
  109812. nonzero[info->coupling_ang[i]]=1;
  109813. }
  109814. }
  109815. /* recover the residue into our working vectors */
  109816. for(i=0;i<info->submaps;i++){
  109817. int ch_in_bundle=0;
  109818. for(j=0;j<vi->channels;j++){
  109819. if(info->chmuxlist[j]==i){
  109820. if(nonzero[j])
  109821. zerobundle[ch_in_bundle]=1;
  109822. else
  109823. zerobundle[ch_in_bundle]=0;
  109824. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  109825. }
  109826. }
  109827. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  109828. inverse(vb,b->residue[info->residuesubmap[i]],
  109829. pcmbundle,zerobundle,ch_in_bundle);
  109830. }
  109831. /* channel coupling */
  109832. for(i=info->coupling_steps-1;i>=0;i--){
  109833. float *pcmM=vb->pcm[info->coupling_mag[i]];
  109834. float *pcmA=vb->pcm[info->coupling_ang[i]];
  109835. for(j=0;j<n/2;j++){
  109836. float mag=pcmM[j];
  109837. float ang=pcmA[j];
  109838. if(mag>0)
  109839. if(ang>0){
  109840. pcmM[j]=mag;
  109841. pcmA[j]=mag-ang;
  109842. }else{
  109843. pcmA[j]=mag;
  109844. pcmM[j]=mag+ang;
  109845. }
  109846. else
  109847. if(ang>0){
  109848. pcmM[j]=mag;
  109849. pcmA[j]=mag+ang;
  109850. }else{
  109851. pcmA[j]=mag;
  109852. pcmM[j]=mag-ang;
  109853. }
  109854. }
  109855. }
  109856. /* compute and apply spectral envelope */
  109857. for(i=0;i<vi->channels;i++){
  109858. float *pcm=vb->pcm[i];
  109859. int submap=info->chmuxlist[i];
  109860. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  109861. inverse2(vb,b->flr[info->floorsubmap[submap]],
  109862. floormemo[i],pcm);
  109863. }
  109864. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  109865. /* only MDCT right now.... */
  109866. for(i=0;i<vi->channels;i++){
  109867. float *pcm=vb->pcm[i];
  109868. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  109869. }
  109870. /* all done! */
  109871. return(0);
  109872. }
  109873. /* export hooks */
  109874. vorbis_func_mapping mapping0_exportbundle={
  109875. &mapping0_pack,
  109876. &mapping0_unpack,
  109877. &mapping0_free_info,
  109878. &mapping0_forward,
  109879. &mapping0_inverse
  109880. };
  109881. #endif
  109882. /********* End of inlined file: mapping0.c *********/
  109883. /********* Start of inlined file: mdct.c *********/
  109884. /* this can also be run as an integer transform by uncommenting a
  109885. define in mdct.h; the integerization is a first pass and although
  109886. it's likely stable for Vorbis, the dynamic range is constrained and
  109887. roundoff isn't done (so it's noisy). Consider it functional, but
  109888. only a starting point. There's no point on a machine with an FPU */
  109889. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109890. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109891. // tasks..
  109892. #ifdef _MSC_VER
  109893. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109894. #endif
  109895. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109896. #if JUCE_USE_OGGVORBIS
  109897. #include <stdio.h>
  109898. #include <stdlib.h>
  109899. #include <string.h>
  109900. #include <math.h>
  109901. /* build lookups for trig functions; also pre-figure scaling and
  109902. some window function algebra. */
  109903. void mdct_init(mdct_lookup *lookup,int n){
  109904. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  109905. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  109906. int i;
  109907. int n2=n>>1;
  109908. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  109909. lookup->n=n;
  109910. lookup->trig=T;
  109911. lookup->bitrev=bitrev;
  109912. /* trig lookups... */
  109913. for(i=0;i<n/4;i++){
  109914. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  109915. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  109916. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  109917. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  109918. }
  109919. for(i=0;i<n/8;i++){
  109920. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  109921. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  109922. }
  109923. /* bitreverse lookup... */
  109924. {
  109925. int mask=(1<<(log2n-1))-1,i,j;
  109926. int msb=1<<(log2n-2);
  109927. for(i=0;i<n/8;i++){
  109928. int acc=0;
  109929. for(j=0;msb>>j;j++)
  109930. if((msb>>j)&i)acc|=1<<j;
  109931. bitrev[i*2]=((~acc)&mask)-1;
  109932. bitrev[i*2+1]=acc;
  109933. }
  109934. }
  109935. lookup->scale=FLOAT_CONV(4.f/n);
  109936. }
  109937. /* 8 point butterfly (in place, 4 register) */
  109938. STIN void mdct_butterfly_8(DATA_TYPE *x){
  109939. REG_TYPE r0 = x[6] + x[2];
  109940. REG_TYPE r1 = x[6] - x[2];
  109941. REG_TYPE r2 = x[4] + x[0];
  109942. REG_TYPE r3 = x[4] - x[0];
  109943. x[6] = r0 + r2;
  109944. x[4] = r0 - r2;
  109945. r0 = x[5] - x[1];
  109946. r2 = x[7] - x[3];
  109947. x[0] = r1 + r0;
  109948. x[2] = r1 - r0;
  109949. r0 = x[5] + x[1];
  109950. r1 = x[7] + x[3];
  109951. x[3] = r2 + r3;
  109952. x[1] = r2 - r3;
  109953. x[7] = r1 + r0;
  109954. x[5] = r1 - r0;
  109955. }
  109956. /* 16 point butterfly (in place, 4 register) */
  109957. STIN void mdct_butterfly_16(DATA_TYPE *x){
  109958. REG_TYPE r0 = x[1] - x[9];
  109959. REG_TYPE r1 = x[0] - x[8];
  109960. x[8] += x[0];
  109961. x[9] += x[1];
  109962. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  109963. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  109964. r0 = x[3] - x[11];
  109965. r1 = x[10] - x[2];
  109966. x[10] += x[2];
  109967. x[11] += x[3];
  109968. x[2] = r0;
  109969. x[3] = r1;
  109970. r0 = x[12] - x[4];
  109971. r1 = x[13] - x[5];
  109972. x[12] += x[4];
  109973. x[13] += x[5];
  109974. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  109975. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  109976. r0 = x[14] - x[6];
  109977. r1 = x[15] - x[7];
  109978. x[14] += x[6];
  109979. x[15] += x[7];
  109980. x[6] = r0;
  109981. x[7] = r1;
  109982. mdct_butterfly_8(x);
  109983. mdct_butterfly_8(x+8);
  109984. }
  109985. /* 32 point butterfly (in place, 4 register) */
  109986. STIN void mdct_butterfly_32(DATA_TYPE *x){
  109987. REG_TYPE r0 = x[30] - x[14];
  109988. REG_TYPE r1 = x[31] - x[15];
  109989. x[30] += x[14];
  109990. x[31] += x[15];
  109991. x[14] = r0;
  109992. x[15] = r1;
  109993. r0 = x[28] - x[12];
  109994. r1 = x[29] - x[13];
  109995. x[28] += x[12];
  109996. x[29] += x[13];
  109997. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  109998. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  109999. r0 = x[26] - x[10];
  110000. r1 = x[27] - x[11];
  110001. x[26] += x[10];
  110002. x[27] += x[11];
  110003. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  110004. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  110005. r0 = x[24] - x[8];
  110006. r1 = x[25] - x[9];
  110007. x[24] += x[8];
  110008. x[25] += x[9];
  110009. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  110010. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  110011. r0 = x[22] - x[6];
  110012. r1 = x[7] - x[23];
  110013. x[22] += x[6];
  110014. x[23] += x[7];
  110015. x[6] = r1;
  110016. x[7] = r0;
  110017. r0 = x[4] - x[20];
  110018. r1 = x[5] - x[21];
  110019. x[20] += x[4];
  110020. x[21] += x[5];
  110021. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  110022. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  110023. r0 = x[2] - x[18];
  110024. r1 = x[3] - x[19];
  110025. x[18] += x[2];
  110026. x[19] += x[3];
  110027. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  110028. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  110029. r0 = x[0] - x[16];
  110030. r1 = x[1] - x[17];
  110031. x[16] += x[0];
  110032. x[17] += x[1];
  110033. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  110034. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  110035. mdct_butterfly_16(x);
  110036. mdct_butterfly_16(x+16);
  110037. }
  110038. /* N point first stage butterfly (in place, 2 register) */
  110039. STIN void mdct_butterfly_first(DATA_TYPE *T,
  110040. DATA_TYPE *x,
  110041. int points){
  110042. DATA_TYPE *x1 = x + points - 8;
  110043. DATA_TYPE *x2 = x + (points>>1) - 8;
  110044. REG_TYPE r0;
  110045. REG_TYPE r1;
  110046. do{
  110047. r0 = x1[6] - x2[6];
  110048. r1 = x1[7] - x2[7];
  110049. x1[6] += x2[6];
  110050. x1[7] += x2[7];
  110051. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110052. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110053. r0 = x1[4] - x2[4];
  110054. r1 = x1[5] - x2[5];
  110055. x1[4] += x2[4];
  110056. x1[5] += x2[5];
  110057. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  110058. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  110059. r0 = x1[2] - x2[2];
  110060. r1 = x1[3] - x2[3];
  110061. x1[2] += x2[2];
  110062. x1[3] += x2[3];
  110063. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  110064. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  110065. r0 = x1[0] - x2[0];
  110066. r1 = x1[1] - x2[1];
  110067. x1[0] += x2[0];
  110068. x1[1] += x2[1];
  110069. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  110070. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  110071. x1-=8;
  110072. x2-=8;
  110073. T+=16;
  110074. }while(x2>=x);
  110075. }
  110076. /* N/stage point generic N stage butterfly (in place, 2 register) */
  110077. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  110078. DATA_TYPE *x,
  110079. int points,
  110080. int trigint){
  110081. DATA_TYPE *x1 = x + points - 8;
  110082. DATA_TYPE *x2 = x + (points>>1) - 8;
  110083. REG_TYPE r0;
  110084. REG_TYPE r1;
  110085. do{
  110086. r0 = x1[6] - x2[6];
  110087. r1 = x1[7] - x2[7];
  110088. x1[6] += x2[6];
  110089. x1[7] += x2[7];
  110090. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110091. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110092. T+=trigint;
  110093. r0 = x1[4] - x2[4];
  110094. r1 = x1[5] - x2[5];
  110095. x1[4] += x2[4];
  110096. x1[5] += x2[5];
  110097. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110098. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110099. T+=trigint;
  110100. r0 = x1[2] - x2[2];
  110101. r1 = x1[3] - x2[3];
  110102. x1[2] += x2[2];
  110103. x1[3] += x2[3];
  110104. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110105. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110106. T+=trigint;
  110107. r0 = x1[0] - x2[0];
  110108. r1 = x1[1] - x2[1];
  110109. x1[0] += x2[0];
  110110. x1[1] += x2[1];
  110111. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110112. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110113. T+=trigint;
  110114. x1-=8;
  110115. x2-=8;
  110116. }while(x2>=x);
  110117. }
  110118. STIN void mdct_butterflies(mdct_lookup *init,
  110119. DATA_TYPE *x,
  110120. int points){
  110121. DATA_TYPE *T=init->trig;
  110122. int stages=init->log2n-5;
  110123. int i,j;
  110124. if(--stages>0){
  110125. mdct_butterfly_first(T,x,points);
  110126. }
  110127. for(i=1;--stages>0;i++){
  110128. for(j=0;j<(1<<i);j++)
  110129. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  110130. }
  110131. for(j=0;j<points;j+=32)
  110132. mdct_butterfly_32(x+j);
  110133. }
  110134. void mdct_clear(mdct_lookup *l){
  110135. if(l){
  110136. if(l->trig)_ogg_free(l->trig);
  110137. if(l->bitrev)_ogg_free(l->bitrev);
  110138. memset(l,0,sizeof(*l));
  110139. }
  110140. }
  110141. STIN void mdct_bitreverse(mdct_lookup *init,
  110142. DATA_TYPE *x){
  110143. int n = init->n;
  110144. int *bit = init->bitrev;
  110145. DATA_TYPE *w0 = x;
  110146. DATA_TYPE *w1 = x = w0+(n>>1);
  110147. DATA_TYPE *T = init->trig+n;
  110148. do{
  110149. DATA_TYPE *x0 = x+bit[0];
  110150. DATA_TYPE *x1 = x+bit[1];
  110151. REG_TYPE r0 = x0[1] - x1[1];
  110152. REG_TYPE r1 = x0[0] + x1[0];
  110153. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  110154. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  110155. w1 -= 4;
  110156. r0 = HALVE(x0[1] + x1[1]);
  110157. r1 = HALVE(x0[0] - x1[0]);
  110158. w0[0] = r0 + r2;
  110159. w1[2] = r0 - r2;
  110160. w0[1] = r1 + r3;
  110161. w1[3] = r3 - r1;
  110162. x0 = x+bit[2];
  110163. x1 = x+bit[3];
  110164. r0 = x0[1] - x1[1];
  110165. r1 = x0[0] + x1[0];
  110166. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  110167. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  110168. r0 = HALVE(x0[1] + x1[1]);
  110169. r1 = HALVE(x0[0] - x1[0]);
  110170. w0[2] = r0 + r2;
  110171. w1[0] = r0 - r2;
  110172. w0[3] = r1 + r3;
  110173. w1[1] = r3 - r1;
  110174. T += 4;
  110175. bit += 4;
  110176. w0 += 4;
  110177. }while(w0<w1);
  110178. }
  110179. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  110180. int n=init->n;
  110181. int n2=n>>1;
  110182. int n4=n>>2;
  110183. /* rotate */
  110184. DATA_TYPE *iX = in+n2-7;
  110185. DATA_TYPE *oX = out+n2+n4;
  110186. DATA_TYPE *T = init->trig+n4;
  110187. do{
  110188. oX -= 4;
  110189. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  110190. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  110191. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  110192. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  110193. iX -= 8;
  110194. T += 4;
  110195. }while(iX>=in);
  110196. iX = in+n2-8;
  110197. oX = out+n2+n4;
  110198. T = init->trig+n4;
  110199. do{
  110200. T -= 4;
  110201. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  110202. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  110203. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  110204. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  110205. iX -= 8;
  110206. oX += 4;
  110207. }while(iX>=in);
  110208. mdct_butterflies(init,out+n2,n2);
  110209. mdct_bitreverse(init,out);
  110210. /* roatate + window */
  110211. {
  110212. DATA_TYPE *oX1=out+n2+n4;
  110213. DATA_TYPE *oX2=out+n2+n4;
  110214. DATA_TYPE *iX =out;
  110215. T =init->trig+n2;
  110216. do{
  110217. oX1-=4;
  110218. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  110219. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  110220. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  110221. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  110222. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  110223. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  110224. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  110225. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  110226. oX2+=4;
  110227. iX += 8;
  110228. T += 8;
  110229. }while(iX<oX1);
  110230. iX=out+n2+n4;
  110231. oX1=out+n4;
  110232. oX2=oX1;
  110233. do{
  110234. oX1-=4;
  110235. iX-=4;
  110236. oX2[0] = -(oX1[3] = iX[3]);
  110237. oX2[1] = -(oX1[2] = iX[2]);
  110238. oX2[2] = -(oX1[1] = iX[1]);
  110239. oX2[3] = -(oX1[0] = iX[0]);
  110240. oX2+=4;
  110241. }while(oX2<iX);
  110242. iX=out+n2+n4;
  110243. oX1=out+n2+n4;
  110244. oX2=out+n2;
  110245. do{
  110246. oX1-=4;
  110247. oX1[0]= iX[3];
  110248. oX1[1]= iX[2];
  110249. oX1[2]= iX[1];
  110250. oX1[3]= iX[0];
  110251. iX+=4;
  110252. }while(oX1>oX2);
  110253. }
  110254. }
  110255. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  110256. int n=init->n;
  110257. int n2=n>>1;
  110258. int n4=n>>2;
  110259. int n8=n>>3;
  110260. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  110261. DATA_TYPE *w2=w+n2;
  110262. /* rotate */
  110263. /* window + rotate + step 1 */
  110264. REG_TYPE r0;
  110265. REG_TYPE r1;
  110266. DATA_TYPE *x0=in+n2+n4;
  110267. DATA_TYPE *x1=x0+1;
  110268. DATA_TYPE *T=init->trig+n2;
  110269. int i=0;
  110270. for(i=0;i<n8;i+=2){
  110271. x0 -=4;
  110272. T-=2;
  110273. r0= x0[2] + x1[0];
  110274. r1= x0[0] + x1[2];
  110275. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  110276. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  110277. x1 +=4;
  110278. }
  110279. x1=in+1;
  110280. for(;i<n2-n8;i+=2){
  110281. T-=2;
  110282. x0 -=4;
  110283. r0= x0[2] - x1[0];
  110284. r1= x0[0] - x1[2];
  110285. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  110286. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  110287. x1 +=4;
  110288. }
  110289. x0=in+n;
  110290. for(;i<n2;i+=2){
  110291. T-=2;
  110292. x0 -=4;
  110293. r0= -x0[2] - x1[0];
  110294. r1= -x0[0] - x1[2];
  110295. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  110296. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  110297. x1 +=4;
  110298. }
  110299. mdct_butterflies(init,w+n2,n2);
  110300. mdct_bitreverse(init,w);
  110301. /* roatate + window */
  110302. T=init->trig+n2;
  110303. x0=out+n2;
  110304. for(i=0;i<n4;i++){
  110305. x0--;
  110306. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  110307. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  110308. w+=2;
  110309. T+=2;
  110310. }
  110311. }
  110312. #endif
  110313. /********* End of inlined file: mdct.c *********/
  110314. /********* Start of inlined file: psy.c *********/
  110315. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110316. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110317. // tasks..
  110318. #ifdef _MSC_VER
  110319. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110320. #endif
  110321. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110322. #if JUCE_USE_OGGVORBIS
  110323. #include <stdlib.h>
  110324. #include <math.h>
  110325. #include <string.h>
  110326. /********* Start of inlined file: masking.h *********/
  110327. #ifndef _V_MASKING_H_
  110328. #define _V_MASKING_H_
  110329. /* more detailed ATH; the bass if flat to save stressing the floor
  110330. overly for only a bin or two of savings. */
  110331. #define MAX_ATH 88
  110332. static float ATH[]={
  110333. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  110334. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  110335. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  110336. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  110337. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  110338. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  110339. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  110340. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  110341. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  110342. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  110343. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  110344. };
  110345. /* The tone masking curves from Ehmer's and Fielder's papers have been
  110346. replaced by an empirically collected data set. The previously
  110347. published values were, far too often, simply on crack. */
  110348. #define EHMER_OFFSET 16
  110349. #define EHMER_MAX 56
  110350. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  110351. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  110352. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  110353. for collection of these curves) */
  110354. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  110355. /* 62.5 Hz */
  110356. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  110357. -60, -60, -60, -60, -62, -62, -65, -73,
  110358. -69, -68, -68, -67, -70, -70, -72, -74,
  110359. -75, -79, -79, -80, -83, -88, -93, -100,
  110360. -110, -999, -999, -999, -999, -999, -999, -999,
  110361. -999, -999, -999, -999, -999, -999, -999, -999,
  110362. -999, -999, -999, -999, -999, -999, -999, -999},
  110363. { -48, -48, -48, -48, -48, -48, -48, -48,
  110364. -48, -48, -48, -48, -48, -53, -61, -66,
  110365. -66, -68, -67, -70, -76, -76, -72, -73,
  110366. -75, -76, -78, -79, -83, -88, -93, -100,
  110367. -110, -999, -999, -999, -999, -999, -999, -999,
  110368. -999, -999, -999, -999, -999, -999, -999, -999,
  110369. -999, -999, -999, -999, -999, -999, -999, -999},
  110370. { -37, -37, -37, -37, -37, -37, -37, -37,
  110371. -38, -40, -42, -46, -48, -53, -55, -62,
  110372. -65, -58, -56, -56, -61, -60, -65, -67,
  110373. -69, -71, -77, -77, -78, -80, -82, -84,
  110374. -88, -93, -98, -106, -112, -999, -999, -999,
  110375. -999, -999, -999, -999, -999, -999, -999, -999,
  110376. -999, -999, -999, -999, -999, -999, -999, -999},
  110377. { -25, -25, -25, -25, -25, -25, -25, -25,
  110378. -25, -26, -27, -29, -32, -38, -48, -52,
  110379. -52, -50, -48, -48, -51, -52, -54, -60,
  110380. -67, -67, -66, -68, -69, -73, -73, -76,
  110381. -80, -81, -81, -85, -85, -86, -88, -93,
  110382. -100, -110, -999, -999, -999, -999, -999, -999,
  110383. -999, -999, -999, -999, -999, -999, -999, -999},
  110384. { -16, -16, -16, -16, -16, -16, -16, -16,
  110385. -17, -19, -20, -22, -26, -28, -31, -40,
  110386. -47, -39, -39, -40, -42, -43, -47, -51,
  110387. -57, -52, -55, -55, -60, -58, -62, -63,
  110388. -70, -67, -69, -72, -73, -77, -80, -82,
  110389. -83, -87, -90, -94, -98, -104, -115, -999,
  110390. -999, -999, -999, -999, -999, -999, -999, -999},
  110391. { -8, -8, -8, -8, -8, -8, -8, -8,
  110392. -8, -8, -10, -11, -15, -19, -25, -30,
  110393. -34, -31, -30, -31, -29, -32, -35, -42,
  110394. -48, -42, -44, -46, -50, -50, -51, -52,
  110395. -59, -54, -55, -55, -58, -62, -63, -66,
  110396. -72, -73, -76, -75, -78, -80, -80, -81,
  110397. -84, -88, -90, -94, -98, -101, -106, -110}},
  110398. /* 88Hz */
  110399. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  110400. -66, -66, -66, -66, -66, -67, -67, -67,
  110401. -76, -72, -71, -74, -76, -76, -75, -78,
  110402. -79, -79, -81, -83, -86, -89, -93, -97,
  110403. -100, -105, -110, -999, -999, -999, -999, -999,
  110404. -999, -999, -999, -999, -999, -999, -999, -999,
  110405. -999, -999, -999, -999, -999, -999, -999, -999},
  110406. { -47, -47, -47, -47, -47, -47, -47, -47,
  110407. -47, -47, -47, -48, -51, -55, -59, -66,
  110408. -66, -66, -67, -66, -68, -69, -70, -74,
  110409. -79, -77, -77, -78, -80, -81, -82, -84,
  110410. -86, -88, -91, -95, -100, -108, -116, -999,
  110411. -999, -999, -999, -999, -999, -999, -999, -999,
  110412. -999, -999, -999, -999, -999, -999, -999, -999},
  110413. { -36, -36, -36, -36, -36, -36, -36, -36,
  110414. -36, -37, -37, -41, -44, -48, -51, -58,
  110415. -62, -60, -57, -59, -59, -60, -63, -65,
  110416. -72, -71, -70, -72, -74, -77, -76, -78,
  110417. -81, -81, -80, -83, -86, -91, -96, -100,
  110418. -105, -110, -999, -999, -999, -999, -999, -999,
  110419. -999, -999, -999, -999, -999, -999, -999, -999},
  110420. { -28, -28, -28, -28, -28, -28, -28, -28,
  110421. -28, -30, -32, -32, -33, -35, -41, -49,
  110422. -50, -49, -47, -48, -48, -52, -51, -57,
  110423. -65, -61, -59, -61, -64, -69, -70, -74,
  110424. -77, -77, -78, -81, -84, -85, -87, -90,
  110425. -92, -96, -100, -107, -112, -999, -999, -999,
  110426. -999, -999, -999, -999, -999, -999, -999, -999},
  110427. { -19, -19, -19, -19, -19, -19, -19, -19,
  110428. -20, -21, -23, -27, -30, -35, -36, -41,
  110429. -46, -44, -42, -40, -41, -41, -43, -48,
  110430. -55, -53, -52, -53, -56, -59, -58, -60,
  110431. -67, -66, -69, -71, -72, -75, -79, -81,
  110432. -84, -87, -90, -93, -97, -101, -107, -114,
  110433. -999, -999, -999, -999, -999, -999, -999, -999},
  110434. { -9, -9, -9, -9, -9, -9, -9, -9,
  110435. -11, -12, -12, -15, -16, -20, -23, -30,
  110436. -37, -34, -33, -34, -31, -32, -32, -38,
  110437. -47, -44, -41, -40, -47, -49, -46, -46,
  110438. -58, -50, -50, -54, -58, -62, -64, -67,
  110439. -67, -70, -72, -76, -79, -83, -87, -91,
  110440. -96, -100, -104, -110, -999, -999, -999, -999}},
  110441. /* 125 Hz */
  110442. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  110443. -62, -62, -63, -64, -66, -67, -66, -68,
  110444. -75, -72, -76, -75, -76, -78, -79, -82,
  110445. -84, -85, -90, -94, -101, -110, -999, -999,
  110446. -999, -999, -999, -999, -999, -999, -999, -999,
  110447. -999, -999, -999, -999, -999, -999, -999, -999,
  110448. -999, -999, -999, -999, -999, -999, -999, -999},
  110449. { -59, -59, -59, -59, -59, -59, -59, -59,
  110450. -59, -59, -59, -60, -60, -61, -63, -66,
  110451. -71, -68, -70, -70, -71, -72, -72, -75,
  110452. -81, -78, -79, -82, -83, -86, -90, -97,
  110453. -103, -113, -999, -999, -999, -999, -999, -999,
  110454. -999, -999, -999, -999, -999, -999, -999, -999,
  110455. -999, -999, -999, -999, -999, -999, -999, -999},
  110456. { -53, -53, -53, -53, -53, -53, -53, -53,
  110457. -53, -54, -55, -57, -56, -57, -55, -61,
  110458. -65, -60, -60, -62, -63, -63, -66, -68,
  110459. -74, -73, -75, -75, -78, -80, -80, -82,
  110460. -85, -90, -96, -101, -108, -999, -999, -999,
  110461. -999, -999, -999, -999, -999, -999, -999, -999,
  110462. -999, -999, -999, -999, -999, -999, -999, -999},
  110463. { -46, -46, -46, -46, -46, -46, -46, -46,
  110464. -46, -46, -47, -47, -47, -47, -48, -51,
  110465. -57, -51, -49, -50, -51, -53, -54, -59,
  110466. -66, -60, -62, -67, -67, -70, -72, -75,
  110467. -76, -78, -81, -85, -88, -94, -97, -104,
  110468. -112, -999, -999, -999, -999, -999, -999, -999,
  110469. -999, -999, -999, -999, -999, -999, -999, -999},
  110470. { -36, -36, -36, -36, -36, -36, -36, -36,
  110471. -39, -41, -42, -42, -39, -38, -41, -43,
  110472. -52, -44, -40, -39, -37, -37, -40, -47,
  110473. -54, -50, -48, -50, -55, -61, -59, -62,
  110474. -66, -66, -66, -69, -69, -73, -74, -74,
  110475. -75, -77, -79, -82, -87, -91, -95, -100,
  110476. -108, -115, -999, -999, -999, -999, -999, -999},
  110477. { -28, -26, -24, -22, -20, -20, -23, -29,
  110478. -30, -31, -28, -27, -28, -28, -28, -35,
  110479. -40, -33, -32, -29, -30, -30, -30, -37,
  110480. -45, -41, -37, -38, -45, -47, -47, -48,
  110481. -53, -49, -48, -50, -49, -49, -51, -52,
  110482. -58, -56, -57, -56, -60, -61, -62, -70,
  110483. -72, -74, -78, -83, -88, -93, -100, -106}},
  110484. /* 177 Hz */
  110485. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110486. -999, -110, -105, -100, -95, -91, -87, -83,
  110487. -80, -78, -76, -78, -78, -81, -83, -85,
  110488. -86, -85, -86, -87, -90, -97, -107, -999,
  110489. -999, -999, -999, -999, -999, -999, -999, -999,
  110490. -999, -999, -999, -999, -999, -999, -999, -999,
  110491. -999, -999, -999, -999, -999, -999, -999, -999},
  110492. {-999, -999, -999, -110, -105, -100, -95, -90,
  110493. -85, -81, -77, -73, -70, -67, -67, -68,
  110494. -75, -73, -70, -69, -70, -72, -75, -79,
  110495. -84, -83, -84, -86, -88, -89, -89, -93,
  110496. -98, -105, -112, -999, -999, -999, -999, -999,
  110497. -999, -999, -999, -999, -999, -999, -999, -999,
  110498. -999, -999, -999, -999, -999, -999, -999, -999},
  110499. {-105, -100, -95, -90, -85, -80, -76, -71,
  110500. -68, -68, -65, -63, -63, -62, -62, -64,
  110501. -65, -64, -61, -62, -63, -64, -66, -68,
  110502. -73, -73, -74, -75, -76, -81, -83, -85,
  110503. -88, -89, -92, -95, -100, -108, -999, -999,
  110504. -999, -999, -999, -999, -999, -999, -999, -999,
  110505. -999, -999, -999, -999, -999, -999, -999, -999},
  110506. { -80, -75, -71, -68, -65, -63, -62, -61,
  110507. -61, -61, -61, -59, -56, -57, -53, -50,
  110508. -58, -52, -50, -50, -52, -53, -54, -58,
  110509. -67, -63, -67, -68, -72, -75, -78, -80,
  110510. -81, -81, -82, -85, -89, -90, -93, -97,
  110511. -101, -107, -114, -999, -999, -999, -999, -999,
  110512. -999, -999, -999, -999, -999, -999, -999, -999},
  110513. { -65, -61, -59, -57, -56, -55, -55, -56,
  110514. -56, -57, -55, -53, -52, -47, -44, -44,
  110515. -50, -44, -41, -39, -39, -42, -40, -46,
  110516. -51, -49, -50, -53, -54, -63, -60, -61,
  110517. -62, -66, -66, -66, -70, -73, -74, -75,
  110518. -76, -75, -79, -85, -89, -91, -96, -102,
  110519. -110, -999, -999, -999, -999, -999, -999, -999},
  110520. { -52, -50, -49, -49, -48, -48, -48, -49,
  110521. -50, -50, -49, -46, -43, -39, -35, -33,
  110522. -38, -36, -32, -29, -32, -32, -32, -35,
  110523. -44, -39, -38, -38, -46, -50, -45, -46,
  110524. -53, -50, -50, -50, -54, -54, -53, -53,
  110525. -56, -57, -59, -66, -70, -72, -74, -79,
  110526. -83, -85, -90, -97, -114, -999, -999, -999}},
  110527. /* 250 Hz */
  110528. {{-999, -999, -999, -999, -999, -999, -110, -105,
  110529. -100, -95, -90, -86, -80, -75, -75, -79,
  110530. -80, -79, -80, -81, -82, -88, -95, -103,
  110531. -110, -999, -999, -999, -999, -999, -999, -999,
  110532. -999, -999, -999, -999, -999, -999, -999, -999,
  110533. -999, -999, -999, -999, -999, -999, -999, -999,
  110534. -999, -999, -999, -999, -999, -999, -999, -999},
  110535. {-999, -999, -999, -999, -108, -103, -98, -93,
  110536. -88, -83, -79, -78, -75, -71, -67, -68,
  110537. -73, -73, -72, -73, -75, -77, -80, -82,
  110538. -88, -93, -100, -107, -114, -999, -999, -999,
  110539. -999, -999, -999, -999, -999, -999, -999, -999,
  110540. -999, -999, -999, -999, -999, -999, -999, -999,
  110541. -999, -999, -999, -999, -999, -999, -999, -999},
  110542. {-999, -999, -999, -110, -105, -101, -96, -90,
  110543. -86, -81, -77, -73, -69, -66, -61, -62,
  110544. -66, -64, -62, -65, -66, -70, -72, -76,
  110545. -81, -80, -84, -90, -95, -102, -110, -999,
  110546. -999, -999, -999, -999, -999, -999, -999, -999,
  110547. -999, -999, -999, -999, -999, -999, -999, -999,
  110548. -999, -999, -999, -999, -999, -999, -999, -999},
  110549. {-999, -999, -999, -107, -103, -97, -92, -88,
  110550. -83, -79, -74, -70, -66, -59, -53, -58,
  110551. -62, -55, -54, -54, -54, -58, -61, -62,
  110552. -72, -70, -72, -75, -78, -80, -81, -80,
  110553. -83, -83, -88, -93, -100, -107, -115, -999,
  110554. -999, -999, -999, -999, -999, -999, -999, -999,
  110555. -999, -999, -999, -999, -999, -999, -999, -999},
  110556. {-999, -999, -999, -105, -100, -95, -90, -85,
  110557. -80, -75, -70, -66, -62, -56, -48, -44,
  110558. -48, -46, -46, -43, -46, -48, -48, -51,
  110559. -58, -58, -59, -60, -62, -62, -61, -61,
  110560. -65, -64, -65, -68, -70, -74, -75, -78,
  110561. -81, -86, -95, -110, -999, -999, -999, -999,
  110562. -999, -999, -999, -999, -999, -999, -999, -999},
  110563. {-999, -999, -105, -100, -95, -90, -85, -80,
  110564. -75, -70, -65, -61, -55, -49, -39, -33,
  110565. -40, -35, -32, -38, -40, -33, -35, -37,
  110566. -46, -41, -45, -44, -46, -42, -45, -46,
  110567. -52, -50, -50, -50, -54, -54, -55, -57,
  110568. -62, -64, -66, -68, -70, -76, -81, -90,
  110569. -100, -110, -999, -999, -999, -999, -999, -999}},
  110570. /* 354 hz */
  110571. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110572. -105, -98, -90, -85, -82, -83, -80, -78,
  110573. -84, -79, -80, -83, -87, -89, -91, -93,
  110574. -99, -106, -117, -999, -999, -999, -999, -999,
  110575. -999, -999, -999, -999, -999, -999, -999, -999,
  110576. -999, -999, -999, -999, -999, -999, -999, -999,
  110577. -999, -999, -999, -999, -999, -999, -999, -999},
  110578. {-999, -999, -999, -999, -999, -999, -999, -999,
  110579. -105, -98, -90, -85, -80, -75, -70, -68,
  110580. -74, -72, -74, -77, -80, -82, -85, -87,
  110581. -92, -89, -91, -95, -100, -106, -112, -999,
  110582. -999, -999, -999, -999, -999, -999, -999, -999,
  110583. -999, -999, -999, -999, -999, -999, -999, -999,
  110584. -999, -999, -999, -999, -999, -999, -999, -999},
  110585. {-999, -999, -999, -999, -999, -999, -999, -999,
  110586. -105, -98, -90, -83, -75, -71, -63, -64,
  110587. -67, -62, -64, -67, -70, -73, -77, -81,
  110588. -84, -83, -85, -89, -90, -93, -98, -104,
  110589. -109, -114, -999, -999, -999, -999, -999, -999,
  110590. -999, -999, -999, -999, -999, -999, -999, -999,
  110591. -999, -999, -999, -999, -999, -999, -999, -999},
  110592. {-999, -999, -999, -999, -999, -999, -999, -999,
  110593. -103, -96, -88, -81, -75, -68, -58, -54,
  110594. -56, -54, -56, -56, -58, -60, -63, -66,
  110595. -74, -69, -72, -72, -75, -74, -77, -81,
  110596. -81, -82, -84, -87, -93, -96, -99, -104,
  110597. -110, -999, -999, -999, -999, -999, -999, -999,
  110598. -999, -999, -999, -999, -999, -999, -999, -999},
  110599. {-999, -999, -999, -999, -999, -108, -102, -96,
  110600. -91, -85, -80, -74, -68, -60, -51, -46,
  110601. -48, -46, -43, -45, -47, -47, -49, -48,
  110602. -56, -53, -55, -58, -57, -63, -58, -60,
  110603. -66, -64, -67, -70, -70, -74, -77, -84,
  110604. -86, -89, -91, -93, -94, -101, -109, -118,
  110605. -999, -999, -999, -999, -999, -999, -999, -999},
  110606. {-999, -999, -999, -108, -103, -98, -93, -88,
  110607. -83, -78, -73, -68, -60, -53, -44, -35,
  110608. -38, -38, -34, -34, -36, -40, -41, -44,
  110609. -51, -45, -46, -47, -46, -54, -50, -49,
  110610. -50, -50, -50, -51, -54, -57, -58, -60,
  110611. -66, -66, -66, -64, -65, -68, -77, -82,
  110612. -87, -95, -110, -999, -999, -999, -999, -999}},
  110613. /* 500 Hz */
  110614. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110615. -107, -102, -97, -92, -87, -83, -78, -75,
  110616. -82, -79, -83, -85, -89, -92, -95, -98,
  110617. -101, -105, -109, -113, -999, -999, -999, -999,
  110618. -999, -999, -999, -999, -999, -999, -999, -999,
  110619. -999, -999, -999, -999, -999, -999, -999, -999,
  110620. -999, -999, -999, -999, -999, -999, -999, -999},
  110621. {-999, -999, -999, -999, -999, -999, -999, -106,
  110622. -100, -95, -90, -86, -81, -78, -74, -69,
  110623. -74, -74, -76, -79, -83, -84, -86, -89,
  110624. -92, -97, -93, -100, -103, -107, -110, -999,
  110625. -999, -999, -999, -999, -999, -999, -999, -999,
  110626. -999, -999, -999, -999, -999, -999, -999, -999,
  110627. -999, -999, -999, -999, -999, -999, -999, -999},
  110628. {-999, -999, -999, -999, -999, -999, -106, -100,
  110629. -95, -90, -87, -83, -80, -75, -69, -60,
  110630. -66, -66, -68, -70, -74, -78, -79, -81,
  110631. -81, -83, -84, -87, -93, -96, -99, -103,
  110632. -107, -110, -999, -999, -999, -999, -999, -999,
  110633. -999, -999, -999, -999, -999, -999, -999, -999,
  110634. -999, -999, -999, -999, -999, -999, -999, -999},
  110635. {-999, -999, -999, -999, -999, -108, -103, -98,
  110636. -93, -89, -85, -82, -78, -71, -62, -55,
  110637. -58, -58, -54, -54, -55, -59, -61, -62,
  110638. -70, -66, -66, -67, -70, -72, -75, -78,
  110639. -84, -84, -84, -88, -91, -90, -95, -98,
  110640. -102, -103, -106, -110, -999, -999, -999, -999,
  110641. -999, -999, -999, -999, -999, -999, -999, -999},
  110642. {-999, -999, -999, -999, -108, -103, -98, -94,
  110643. -90, -87, -82, -79, -73, -67, -58, -47,
  110644. -50, -45, -41, -45, -48, -44, -44, -49,
  110645. -54, -51, -48, -47, -49, -50, -51, -57,
  110646. -58, -60, -63, -69, -70, -69, -71, -74,
  110647. -78, -82, -90, -95, -101, -105, -110, -999,
  110648. -999, -999, -999, -999, -999, -999, -999, -999},
  110649. {-999, -999, -999, -105, -101, -97, -93, -90,
  110650. -85, -80, -77, -72, -65, -56, -48, -37,
  110651. -40, -36, -34, -40, -50, -47, -38, -41,
  110652. -47, -38, -35, -39, -38, -43, -40, -45,
  110653. -50, -45, -44, -47, -50, -55, -48, -48,
  110654. -52, -66, -70, -76, -82, -90, -97, -105,
  110655. -110, -999, -999, -999, -999, -999, -999, -999}},
  110656. /* 707 Hz */
  110657. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110658. -999, -108, -103, -98, -93, -86, -79, -76,
  110659. -83, -81, -85, -87, -89, -93, -98, -102,
  110660. -107, -112, -999, -999, -999, -999, -999, -999,
  110661. -999, -999, -999, -999, -999, -999, -999, -999,
  110662. -999, -999, -999, -999, -999, -999, -999, -999,
  110663. -999, -999, -999, -999, -999, -999, -999, -999},
  110664. {-999, -999, -999, -999, -999, -999, -999, -999,
  110665. -999, -108, -103, -98, -93, -86, -79, -71,
  110666. -77, -74, -77, -79, -81, -84, -85, -90,
  110667. -92, -93, -92, -98, -101, -108, -112, -999,
  110668. -999, -999, -999, -999, -999, -999, -999, -999,
  110669. -999, -999, -999, -999, -999, -999, -999, -999,
  110670. -999, -999, -999, -999, -999, -999, -999, -999},
  110671. {-999, -999, -999, -999, -999, -999, -999, -999,
  110672. -108, -103, -98, -93, -87, -78, -68, -65,
  110673. -66, -62, -65, -67, -70, -73, -75, -78,
  110674. -82, -82, -83, -84, -91, -93, -98, -102,
  110675. -106, -110, -999, -999, -999, -999, -999, -999,
  110676. -999, -999, -999, -999, -999, -999, -999, -999,
  110677. -999, -999, -999, -999, -999, -999, -999, -999},
  110678. {-999, -999, -999, -999, -999, -999, -999, -999,
  110679. -105, -100, -95, -90, -82, -74, -62, -57,
  110680. -58, -56, -51, -52, -52, -54, -54, -58,
  110681. -66, -59, -60, -63, -66, -69, -73, -79,
  110682. -83, -84, -80, -81, -81, -82, -88, -92,
  110683. -98, -105, -113, -999, -999, -999, -999, -999,
  110684. -999, -999, -999, -999, -999, -999, -999, -999},
  110685. {-999, -999, -999, -999, -999, -999, -999, -107,
  110686. -102, -97, -92, -84, -79, -69, -57, -47,
  110687. -52, -47, -44, -45, -50, -52, -42, -42,
  110688. -53, -43, -43, -48, -51, -56, -55, -52,
  110689. -57, -59, -61, -62, -67, -71, -78, -83,
  110690. -86, -94, -98, -103, -110, -999, -999, -999,
  110691. -999, -999, -999, -999, -999, -999, -999, -999},
  110692. {-999, -999, -999, -999, -999, -999, -105, -100,
  110693. -95, -90, -84, -78, -70, -61, -51, -41,
  110694. -40, -38, -40, -46, -52, -51, -41, -40,
  110695. -46, -40, -38, -38, -41, -46, -41, -46,
  110696. -47, -43, -43, -45, -41, -45, -56, -67,
  110697. -68, -83, -87, -90, -95, -102, -107, -113,
  110698. -999, -999, -999, -999, -999, -999, -999, -999}},
  110699. /* 1000 Hz */
  110700. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110701. -999, -109, -105, -101, -96, -91, -84, -77,
  110702. -82, -82, -85, -89, -94, -100, -106, -110,
  110703. -999, -999, -999, -999, -999, -999, -999, -999,
  110704. -999, -999, -999, -999, -999, -999, -999, -999,
  110705. -999, -999, -999, -999, -999, -999, -999, -999,
  110706. -999, -999, -999, -999, -999, -999, -999, -999},
  110707. {-999, -999, -999, -999, -999, -999, -999, -999,
  110708. -999, -106, -103, -98, -92, -85, -80, -71,
  110709. -75, -72, -76, -80, -84, -86, -89, -93,
  110710. -100, -107, -113, -999, -999, -999, -999, -999,
  110711. -999, -999, -999, -999, -999, -999, -999, -999,
  110712. -999, -999, -999, -999, -999, -999, -999, -999,
  110713. -999, -999, -999, -999, -999, -999, -999, -999},
  110714. {-999, -999, -999, -999, -999, -999, -999, -107,
  110715. -104, -101, -97, -92, -88, -84, -80, -64,
  110716. -66, -63, -64, -66, -69, -73, -77, -83,
  110717. -83, -86, -91, -98, -104, -111, -999, -999,
  110718. -999, -999, -999, -999, -999, -999, -999, -999,
  110719. -999, -999, -999, -999, -999, -999, -999, -999,
  110720. -999, -999, -999, -999, -999, -999, -999, -999},
  110721. {-999, -999, -999, -999, -999, -999, -999, -107,
  110722. -104, -101, -97, -92, -90, -84, -74, -57,
  110723. -58, -52, -55, -54, -50, -52, -50, -52,
  110724. -63, -62, -69, -76, -77, -78, -78, -79,
  110725. -82, -88, -94, -100, -106, -111, -999, -999,
  110726. -999, -999, -999, -999, -999, -999, -999, -999,
  110727. -999, -999, -999, -999, -999, -999, -999, -999},
  110728. {-999, -999, -999, -999, -999, -999, -106, -102,
  110729. -98, -95, -90, -85, -83, -78, -70, -50,
  110730. -50, -41, -44, -49, -47, -50, -50, -44,
  110731. -55, -46, -47, -48, -48, -54, -49, -49,
  110732. -58, -62, -71, -81, -87, -92, -97, -102,
  110733. -108, -114, -999, -999, -999, -999, -999, -999,
  110734. -999, -999, -999, -999, -999, -999, -999, -999},
  110735. {-999, -999, -999, -999, -999, -999, -106, -102,
  110736. -98, -95, -90, -85, -83, -78, -70, -45,
  110737. -43, -41, -47, -50, -51, -50, -49, -45,
  110738. -47, -41, -44, -41, -39, -43, -38, -37,
  110739. -40, -41, -44, -50, -58, -65, -73, -79,
  110740. -85, -92, -97, -101, -105, -109, -113, -999,
  110741. -999, -999, -999, -999, -999, -999, -999, -999}},
  110742. /* 1414 Hz */
  110743. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110744. -999, -999, -999, -107, -100, -95, -87, -81,
  110745. -85, -83, -88, -93, -100, -107, -114, -999,
  110746. -999, -999, -999, -999, -999, -999, -999, -999,
  110747. -999, -999, -999, -999, -999, -999, -999, -999,
  110748. -999, -999, -999, -999, -999, -999, -999, -999,
  110749. -999, -999, -999, -999, -999, -999, -999, -999},
  110750. {-999, -999, -999, -999, -999, -999, -999, -999,
  110751. -999, -999, -107, -101, -95, -88, -83, -76,
  110752. -73, -72, -79, -84, -90, -95, -100, -105,
  110753. -110, -115, -999, -999, -999, -999, -999, -999,
  110754. -999, -999, -999, -999, -999, -999, -999, -999,
  110755. -999, -999, -999, -999, -999, -999, -999, -999,
  110756. -999, -999, -999, -999, -999, -999, -999, -999},
  110757. {-999, -999, -999, -999, -999, -999, -999, -999,
  110758. -999, -999, -104, -98, -92, -87, -81, -70,
  110759. -65, -62, -67, -71, -74, -80, -85, -91,
  110760. -95, -99, -103, -108, -111, -114, -999, -999,
  110761. -999, -999, -999, -999, -999, -999, -999, -999,
  110762. -999, -999, -999, -999, -999, -999, -999, -999,
  110763. -999, -999, -999, -999, -999, -999, -999, -999},
  110764. {-999, -999, -999, -999, -999, -999, -999, -999,
  110765. -999, -999, -103, -97, -90, -85, -76, -60,
  110766. -56, -54, -60, -62, -61, -56, -63, -65,
  110767. -73, -74, -77, -75, -78, -81, -86, -87,
  110768. -88, -91, -94, -98, -103, -110, -999, -999,
  110769. -999, -999, -999, -999, -999, -999, -999, -999,
  110770. -999, -999, -999, -999, -999, -999, -999, -999},
  110771. {-999, -999, -999, -999, -999, -999, -999, -105,
  110772. -100, -97, -92, -86, -81, -79, -70, -57,
  110773. -51, -47, -51, -58, -60, -56, -53, -50,
  110774. -58, -52, -50, -50, -53, -55, -64, -69,
  110775. -71, -85, -82, -78, -81, -85, -95, -102,
  110776. -112, -999, -999, -999, -999, -999, -999, -999,
  110777. -999, -999, -999, -999, -999, -999, -999, -999},
  110778. {-999, -999, -999, -999, -999, -999, -999, -105,
  110779. -100, -97, -92, -85, -83, -79, -72, -49,
  110780. -40, -43, -43, -54, -56, -51, -50, -40,
  110781. -43, -38, -36, -35, -37, -38, -37, -44,
  110782. -54, -60, -57, -60, -70, -75, -84, -92,
  110783. -103, -112, -999, -999, -999, -999, -999, -999,
  110784. -999, -999, -999, -999, -999, -999, -999, -999}},
  110785. /* 2000 Hz */
  110786. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110787. -999, -999, -999, -110, -102, -95, -89, -82,
  110788. -83, -84, -90, -92, -99, -107, -113, -999,
  110789. -999, -999, -999, -999, -999, -999, -999, -999,
  110790. -999, -999, -999, -999, -999, -999, -999, -999,
  110791. -999, -999, -999, -999, -999, -999, -999, -999,
  110792. -999, -999, -999, -999, -999, -999, -999, -999},
  110793. {-999, -999, -999, -999, -999, -999, -999, -999,
  110794. -999, -999, -107, -101, -95, -89, -83, -72,
  110795. -74, -78, -85, -88, -88, -90, -92, -98,
  110796. -105, -111, -999, -999, -999, -999, -999, -999,
  110797. -999, -999, -999, -999, -999, -999, -999, -999,
  110798. -999, -999, -999, -999, -999, -999, -999, -999,
  110799. -999, -999, -999, -999, -999, -999, -999, -999},
  110800. {-999, -999, -999, -999, -999, -999, -999, -999,
  110801. -999, -109, -103, -97, -93, -87, -81, -70,
  110802. -70, -67, -75, -73, -76, -79, -81, -83,
  110803. -88, -89, -97, -103, -110, -999, -999, -999,
  110804. -999, -999, -999, -999, -999, -999, -999, -999,
  110805. -999, -999, -999, -999, -999, -999, -999, -999,
  110806. -999, -999, -999, -999, -999, -999, -999, -999},
  110807. {-999, -999, -999, -999, -999, -999, -999, -999,
  110808. -999, -107, -100, -94, -88, -83, -75, -63,
  110809. -59, -59, -63, -66, -60, -62, -67, -67,
  110810. -77, -76, -81, -88, -86, -92, -96, -102,
  110811. -109, -116, -999, -999, -999, -999, -999, -999,
  110812. -999, -999, -999, -999, -999, -999, -999, -999,
  110813. -999, -999, -999, -999, -999, -999, -999, -999},
  110814. {-999, -999, -999, -999, -999, -999, -999, -999,
  110815. -999, -105, -98, -92, -86, -81, -73, -56,
  110816. -52, -47, -55, -60, -58, -52, -51, -45,
  110817. -49, -50, -53, -54, -61, -71, -70, -69,
  110818. -78, -79, -87, -90, -96, -104, -112, -999,
  110819. -999, -999, -999, -999, -999, -999, -999, -999,
  110820. -999, -999, -999, -999, -999, -999, -999, -999},
  110821. {-999, -999, -999, -999, -999, -999, -999, -999,
  110822. -999, -103, -96, -90, -86, -78, -70, -51,
  110823. -42, -47, -48, -55, -54, -54, -53, -42,
  110824. -35, -28, -33, -38, -37, -44, -47, -49,
  110825. -54, -63, -68, -78, -82, -89, -94, -99,
  110826. -104, -109, -114, -999, -999, -999, -999, -999,
  110827. -999, -999, -999, -999, -999, -999, -999, -999}},
  110828. /* 2828 Hz */
  110829. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110830. -999, -999, -999, -999, -110, -100, -90, -79,
  110831. -85, -81, -82, -82, -89, -94, -99, -103,
  110832. -109, -115, -999, -999, -999, -999, -999, -999,
  110833. -999, -999, -999, -999, -999, -999, -999, -999,
  110834. -999, -999, -999, -999, -999, -999, -999, -999,
  110835. -999, -999, -999, -999, -999, -999, -999, -999},
  110836. {-999, -999, -999, -999, -999, -999, -999, -999,
  110837. -999, -999, -999, -999, -105, -97, -85, -72,
  110838. -74, -70, -70, -70, -76, -85, -91, -93,
  110839. -97, -103, -109, -115, -999, -999, -999, -999,
  110840. -999, -999, -999, -999, -999, -999, -999, -999,
  110841. -999, -999, -999, -999, -999, -999, -999, -999,
  110842. -999, -999, -999, -999, -999, -999, -999, -999},
  110843. {-999, -999, -999, -999, -999, -999, -999, -999,
  110844. -999, -999, -999, -999, -112, -93, -81, -68,
  110845. -62, -60, -60, -57, -63, -70, -77, -82,
  110846. -90, -93, -98, -104, -109, -113, -999, -999,
  110847. -999, -999, -999, -999, -999, -999, -999, -999,
  110848. -999, -999, -999, -999, -999, -999, -999, -999,
  110849. -999, -999, -999, -999, -999, -999, -999, -999},
  110850. {-999, -999, -999, -999, -999, -999, -999, -999,
  110851. -999, -999, -999, -113, -100, -93, -84, -63,
  110852. -58, -48, -53, -54, -52, -52, -57, -64,
  110853. -66, -76, -83, -81, -85, -85, -90, -95,
  110854. -98, -101, -103, -106, -108, -111, -999, -999,
  110855. -999, -999, -999, -999, -999, -999, -999, -999,
  110856. -999, -999, -999, -999, -999, -999, -999, -999},
  110857. {-999, -999, -999, -999, -999, -999, -999, -999,
  110858. -999, -999, -999, -105, -95, -86, -74, -53,
  110859. -50, -38, -43, -49, -43, -42, -39, -39,
  110860. -46, -52, -57, -56, -72, -69, -74, -81,
  110861. -87, -92, -94, -97, -99, -102, -105, -108,
  110862. -999, -999, -999, -999, -999, -999, -999, -999,
  110863. -999, -999, -999, -999, -999, -999, -999, -999},
  110864. {-999, -999, -999, -999, -999, -999, -999, -999,
  110865. -999, -999, -108, -99, -90, -76, -66, -45,
  110866. -43, -41, -44, -47, -43, -47, -40, -30,
  110867. -31, -31, -39, -33, -40, -41, -43, -53,
  110868. -59, -70, -73, -77, -79, -82, -84, -87,
  110869. -999, -999, -999, -999, -999, -999, -999, -999,
  110870. -999, -999, -999, -999, -999, -999, -999, -999}},
  110871. /* 4000 Hz */
  110872. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110873. -999, -999, -999, -999, -999, -110, -91, -76,
  110874. -75, -85, -93, -98, -104, -110, -999, -999,
  110875. -999, -999, -999, -999, -999, -999, -999, -999,
  110876. -999, -999, -999, -999, -999, -999, -999, -999,
  110877. -999, -999, -999, -999, -999, -999, -999, -999,
  110878. -999, -999, -999, -999, -999, -999, -999, -999},
  110879. {-999, -999, -999, -999, -999, -999, -999, -999,
  110880. -999, -999, -999, -999, -999, -110, -91, -70,
  110881. -70, -75, -86, -89, -94, -98, -101, -106,
  110882. -110, -999, -999, -999, -999, -999, -999, -999,
  110883. -999, -999, -999, -999, -999, -999, -999, -999,
  110884. -999, -999, -999, -999, -999, -999, -999, -999,
  110885. -999, -999, -999, -999, -999, -999, -999, -999},
  110886. {-999, -999, -999, -999, -999, -999, -999, -999,
  110887. -999, -999, -999, -999, -110, -95, -80, -60,
  110888. -65, -64, -74, -83, -88, -91, -95, -99,
  110889. -103, -107, -110, -999, -999, -999, -999, -999,
  110890. -999, -999, -999, -999, -999, -999, -999, -999,
  110891. -999, -999, -999, -999, -999, -999, -999, -999,
  110892. -999, -999, -999, -999, -999, -999, -999, -999},
  110893. {-999, -999, -999, -999, -999, -999, -999, -999,
  110894. -999, -999, -999, -999, -110, -95, -80, -58,
  110895. -55, -49, -66, -68, -71, -78, -78, -80,
  110896. -88, -85, -89, -97, -100, -105, -110, -999,
  110897. -999, -999, -999, -999, -999, -999, -999, -999,
  110898. -999, -999, -999, -999, -999, -999, -999, -999,
  110899. -999, -999, -999, -999, -999, -999, -999, -999},
  110900. {-999, -999, -999, -999, -999, -999, -999, -999,
  110901. -999, -999, -999, -999, -110, -95, -80, -53,
  110902. -52, -41, -59, -59, -49, -58, -56, -63,
  110903. -86, -79, -90, -93, -98, -103, -107, -112,
  110904. -999, -999, -999, -999, -999, -999, -999, -999,
  110905. -999, -999, -999, -999, -999, -999, -999, -999,
  110906. -999, -999, -999, -999, -999, -999, -999, -999},
  110907. {-999, -999, -999, -999, -999, -999, -999, -999,
  110908. -999, -999, -999, -110, -97, -91, -73, -45,
  110909. -40, -33, -53, -61, -49, -54, -50, -50,
  110910. -60, -52, -67, -74, -81, -92, -96, -100,
  110911. -105, -110, -999, -999, -999, -999, -999, -999,
  110912. -999, -999, -999, -999, -999, -999, -999, -999,
  110913. -999, -999, -999, -999, -999, -999, -999, -999}},
  110914. /* 5657 Hz */
  110915. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110916. -999, -999, -999, -113, -106, -99, -92, -77,
  110917. -80, -88, -97, -106, -115, -999, -999, -999,
  110918. -999, -999, -999, -999, -999, -999, -999, -999,
  110919. -999, -999, -999, -999, -999, -999, -999, -999,
  110920. -999, -999, -999, -999, -999, -999, -999, -999,
  110921. -999, -999, -999, -999, -999, -999, -999, -999},
  110922. {-999, -999, -999, -999, -999, -999, -999, -999,
  110923. -999, -999, -116, -109, -102, -95, -89, -74,
  110924. -72, -88, -87, -95, -102, -109, -116, -999,
  110925. -999, -999, -999, -999, -999, -999, -999, -999,
  110926. -999, -999, -999, -999, -999, -999, -999, -999,
  110927. -999, -999, -999, -999, -999, -999, -999, -999,
  110928. -999, -999, -999, -999, -999, -999, -999, -999},
  110929. {-999, -999, -999, -999, -999, -999, -999, -999,
  110930. -999, -999, -116, -109, -102, -95, -89, -75,
  110931. -66, -74, -77, -78, -86, -87, -90, -96,
  110932. -105, -115, -999, -999, -999, -999, -999, -999,
  110933. -999, -999, -999, -999, -999, -999, -999, -999,
  110934. -999, -999, -999, -999, -999, -999, -999, -999,
  110935. -999, -999, -999, -999, -999, -999, -999, -999},
  110936. {-999, -999, -999, -999, -999, -999, -999, -999,
  110937. -999, -999, -115, -108, -101, -94, -88, -66,
  110938. -56, -61, -70, -65, -78, -72, -83, -84,
  110939. -93, -98, -105, -110, -999, -999, -999, -999,
  110940. -999, -999, -999, -999, -999, -999, -999, -999,
  110941. -999, -999, -999, -999, -999, -999, -999, -999,
  110942. -999, -999, -999, -999, -999, -999, -999, -999},
  110943. {-999, -999, -999, -999, -999, -999, -999, -999,
  110944. -999, -999, -110, -105, -95, -89, -82, -57,
  110945. -52, -52, -59, -56, -59, -58, -69, -67,
  110946. -88, -82, -82, -89, -94, -100, -108, -999,
  110947. -999, -999, -999, -999, -999, -999, -999, -999,
  110948. -999, -999, -999, -999, -999, -999, -999, -999,
  110949. -999, -999, -999, -999, -999, -999, -999, -999},
  110950. {-999, -999, -999, -999, -999, -999, -999, -999,
  110951. -999, -110, -101, -96, -90, -83, -77, -54,
  110952. -43, -38, -50, -48, -52, -48, -42, -42,
  110953. -51, -52, -53, -59, -65, -71, -78, -85,
  110954. -95, -999, -999, -999, -999, -999, -999, -999,
  110955. -999, -999, -999, -999, -999, -999, -999, -999,
  110956. -999, -999, -999, -999, -999, -999, -999, -999}},
  110957. /* 8000 Hz */
  110958. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110959. -999, -999, -999, -999, -120, -105, -86, -68,
  110960. -78, -79, -90, -100, -110, -999, -999, -999,
  110961. -999, -999, -999, -999, -999, -999, -999, -999,
  110962. -999, -999, -999, -999, -999, -999, -999, -999,
  110963. -999, -999, -999, -999, -999, -999, -999, -999,
  110964. -999, -999, -999, -999, -999, -999, -999, -999},
  110965. {-999, -999, -999, -999, -999, -999, -999, -999,
  110966. -999, -999, -999, -999, -120, -105, -86, -66,
  110967. -73, -77, -88, -96, -105, -115, -999, -999,
  110968. -999, -999, -999, -999, -999, -999, -999, -999,
  110969. -999, -999, -999, -999, -999, -999, -999, -999,
  110970. -999, -999, -999, -999, -999, -999, -999, -999,
  110971. -999, -999, -999, -999, -999, -999, -999, -999},
  110972. {-999, -999, -999, -999, -999, -999, -999, -999,
  110973. -999, -999, -999, -120, -105, -92, -80, -61,
  110974. -64, -68, -80, -87, -92, -100, -110, -999,
  110975. -999, -999, -999, -999, -999, -999, -999, -999,
  110976. -999, -999, -999, -999, -999, -999, -999, -999,
  110977. -999, -999, -999, -999, -999, -999, -999, -999,
  110978. -999, -999, -999, -999, -999, -999, -999, -999},
  110979. {-999, -999, -999, -999, -999, -999, -999, -999,
  110980. -999, -999, -999, -120, -104, -91, -79, -52,
  110981. -60, -54, -64, -69, -77, -80, -82, -84,
  110982. -85, -87, -88, -90, -999, -999, -999, -999,
  110983. -999, -999, -999, -999, -999, -999, -999, -999,
  110984. -999, -999, -999, -999, -999, -999, -999, -999,
  110985. -999, -999, -999, -999, -999, -999, -999, -999},
  110986. {-999, -999, -999, -999, -999, -999, -999, -999,
  110987. -999, -999, -999, -118, -100, -87, -77, -49,
  110988. -50, -44, -58, -61, -61, -67, -65, -62,
  110989. -62, -62, -65, -68, -999, -999, -999, -999,
  110990. -999, -999, -999, -999, -999, -999, -999, -999,
  110991. -999, -999, -999, -999, -999, -999, -999, -999,
  110992. -999, -999, -999, -999, -999, -999, -999, -999},
  110993. {-999, -999, -999, -999, -999, -999, -999, -999,
  110994. -999, -999, -999, -115, -98, -84, -62, -49,
  110995. -44, -38, -46, -49, -49, -46, -39, -37,
  110996. -39, -40, -42, -43, -999, -999, -999, -999,
  110997. -999, -999, -999, -999, -999, -999, -999, -999,
  110998. -999, -999, -999, -999, -999, -999, -999, -999,
  110999. -999, -999, -999, -999, -999, -999, -999, -999}},
  111000. /* 11314 Hz */
  111001. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111002. -999, -999, -999, -999, -999, -110, -88, -74,
  111003. -77, -82, -82, -85, -90, -94, -99, -104,
  111004. -999, -999, -999, -999, -999, -999, -999, -999,
  111005. -999, -999, -999, -999, -999, -999, -999, -999,
  111006. -999, -999, -999, -999, -999, -999, -999, -999,
  111007. -999, -999, -999, -999, -999, -999, -999, -999},
  111008. {-999, -999, -999, -999, -999, -999, -999, -999,
  111009. -999, -999, -999, -999, -999, -110, -88, -66,
  111010. -70, -81, -80, -81, -84, -88, -91, -93,
  111011. -999, -999, -999, -999, -999, -999, -999, -999,
  111012. -999, -999, -999, -999, -999, -999, -999, -999,
  111013. -999, -999, -999, -999, -999, -999, -999, -999,
  111014. -999, -999, -999, -999, -999, -999, -999, -999},
  111015. {-999, -999, -999, -999, -999, -999, -999, -999,
  111016. -999, -999, -999, -999, -999, -110, -88, -61,
  111017. -63, -70, -71, -74, -77, -80, -83, -85,
  111018. -999, -999, -999, -999, -999, -999, -999, -999,
  111019. -999, -999, -999, -999, -999, -999, -999, -999,
  111020. -999, -999, -999, -999, -999, -999, -999, -999,
  111021. -999, -999, -999, -999, -999, -999, -999, -999},
  111022. {-999, -999, -999, -999, -999, -999, -999, -999,
  111023. -999, -999, -999, -999, -999, -110, -86, -62,
  111024. -63, -62, -62, -58, -52, -50, -50, -52,
  111025. -54, -999, -999, -999, -999, -999, -999, -999,
  111026. -999, -999, -999, -999, -999, -999, -999, -999,
  111027. -999, -999, -999, -999, -999, -999, -999, -999,
  111028. -999, -999, -999, -999, -999, -999, -999, -999},
  111029. {-999, -999, -999, -999, -999, -999, -999, -999,
  111030. -999, -999, -999, -999, -118, -108, -84, -53,
  111031. -50, -50, -50, -55, -47, -45, -40, -40,
  111032. -40, -999, -999, -999, -999, -999, -999, -999,
  111033. -999, -999, -999, -999, -999, -999, -999, -999,
  111034. -999, -999, -999, -999, -999, -999, -999, -999,
  111035. -999, -999, -999, -999, -999, -999, -999, -999},
  111036. {-999, -999, -999, -999, -999, -999, -999, -999,
  111037. -999, -999, -999, -999, -118, -100, -73, -43,
  111038. -37, -42, -43, -53, -38, -37, -35, -35,
  111039. -38, -999, -999, -999, -999, -999, -999, -999,
  111040. -999, -999, -999, -999, -999, -999, -999, -999,
  111041. -999, -999, -999, -999, -999, -999, -999, -999,
  111042. -999, -999, -999, -999, -999, -999, -999, -999}},
  111043. /* 16000 Hz */
  111044. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111045. -999, -999, -999, -110, -100, -91, -84, -74,
  111046. -80, -80, -80, -80, -80, -999, -999, -999,
  111047. -999, -999, -999, -999, -999, -999, -999, -999,
  111048. -999, -999, -999, -999, -999, -999, -999, -999,
  111049. -999, -999, -999, -999, -999, -999, -999, -999,
  111050. -999, -999, -999, -999, -999, -999, -999, -999},
  111051. {-999, -999, -999, -999, -999, -999, -999, -999,
  111052. -999, -999, -999, -110, -100, -91, -84, -74,
  111053. -68, -68, -68, -68, -68, -999, -999, -999,
  111054. -999, -999, -999, -999, -999, -999, -999, -999,
  111055. -999, -999, -999, -999, -999, -999, -999, -999,
  111056. -999, -999, -999, -999, -999, -999, -999, -999,
  111057. -999, -999, -999, -999, -999, -999, -999, -999},
  111058. {-999, -999, -999, -999, -999, -999, -999, -999,
  111059. -999, -999, -999, -110, -100, -86, -78, -70,
  111060. -60, -45, -30, -21, -999, -999, -999, -999,
  111061. -999, -999, -999, -999, -999, -999, -999, -999,
  111062. -999, -999, -999, -999, -999, -999, -999, -999,
  111063. -999, -999, -999, -999, -999, -999, -999, -999,
  111064. -999, -999, -999, -999, -999, -999, -999, -999},
  111065. {-999, -999, -999, -999, -999, -999, -999, -999,
  111066. -999, -999, -999, -110, -100, -87, -78, -67,
  111067. -48, -38, -29, -21, -999, -999, -999, -999,
  111068. -999, -999, -999, -999, -999, -999, -999, -999,
  111069. -999, -999, -999, -999, -999, -999, -999, -999,
  111070. -999, -999, -999, -999, -999, -999, -999, -999,
  111071. -999, -999, -999, -999, -999, -999, -999, -999},
  111072. {-999, -999, -999, -999, -999, -999, -999, -999,
  111073. -999, -999, -999, -110, -100, -86, -69, -56,
  111074. -45, -35, -33, -29, -999, -999, -999, -999,
  111075. -999, -999, -999, -999, -999, -999, -999, -999,
  111076. -999, -999, -999, -999, -999, -999, -999, -999,
  111077. -999, -999, -999, -999, -999, -999, -999, -999,
  111078. -999, -999, -999, -999, -999, -999, -999, -999},
  111079. {-999, -999, -999, -999, -999, -999, -999, -999,
  111080. -999, -999, -999, -110, -100, -83, -71, -48,
  111081. -27, -38, -37, -34, -999, -999, -999, -999,
  111082. -999, -999, -999, -999, -999, -999, -999, -999,
  111083. -999, -999, -999, -999, -999, -999, -999, -999,
  111084. -999, -999, -999, -999, -999, -999, -999, -999,
  111085. -999, -999, -999, -999, -999, -999, -999, -999}}
  111086. };
  111087. #endif
  111088. /********* End of inlined file: masking.h *********/
  111089. #define NEGINF -9999.f
  111090. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  111091. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  111092. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  111093. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111094. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111095. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  111096. look->channels=vi->channels;
  111097. look->ampmax=-9999.;
  111098. look->gi=gi;
  111099. return(look);
  111100. }
  111101. void _vp_global_free(vorbis_look_psy_global *look){
  111102. if(look){
  111103. memset(look,0,sizeof(*look));
  111104. _ogg_free(look);
  111105. }
  111106. }
  111107. void _vi_gpsy_free(vorbis_info_psy_global *i){
  111108. if(i){
  111109. memset(i,0,sizeof(*i));
  111110. _ogg_free(i);
  111111. }
  111112. }
  111113. void _vi_psy_free(vorbis_info_psy *i){
  111114. if(i){
  111115. memset(i,0,sizeof(*i));
  111116. _ogg_free(i);
  111117. }
  111118. }
  111119. static void min_curve(float *c,
  111120. float *c2){
  111121. int i;
  111122. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  111123. }
  111124. static void max_curve(float *c,
  111125. float *c2){
  111126. int i;
  111127. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  111128. }
  111129. static void attenuate_curve(float *c,float att){
  111130. int i;
  111131. for(i=0;i<EHMER_MAX;i++)
  111132. c[i]+=att;
  111133. }
  111134. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  111135. float center_boost, float center_decay_rate){
  111136. int i,j,k,m;
  111137. float ath[EHMER_MAX];
  111138. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  111139. float athc[P_LEVELS][EHMER_MAX];
  111140. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  111141. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  111142. memset(workc,0,sizeof(workc));
  111143. for(i=0;i<P_BANDS;i++){
  111144. /* we add back in the ATH to avoid low level curves falling off to
  111145. -infinity and unnecessarily cutting off high level curves in the
  111146. curve limiting (last step). */
  111147. /* A half-band's settings must be valid over the whole band, and
  111148. it's better to mask too little than too much */
  111149. int ath_offset=i*4;
  111150. for(j=0;j<EHMER_MAX;j++){
  111151. float min=999.;
  111152. for(k=0;k<4;k++)
  111153. if(j+k+ath_offset<MAX_ATH){
  111154. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  111155. }else{
  111156. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  111157. }
  111158. ath[j]=min;
  111159. }
  111160. /* copy curves into working space, replicate the 50dB curve to 30
  111161. and 40, replicate the 100dB curve to 110 */
  111162. for(j=0;j<6;j++)
  111163. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  111164. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  111165. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  111166. /* apply centered curve boost/decay */
  111167. for(j=0;j<P_LEVELS;j++){
  111168. for(k=0;k<EHMER_MAX;k++){
  111169. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  111170. if(adj<0. && center_boost>0)adj=0.;
  111171. if(adj>0. && center_boost<0)adj=0.;
  111172. workc[i][j][k]+=adj;
  111173. }
  111174. }
  111175. /* normalize curves so the driving amplitude is 0dB */
  111176. /* make temp curves with the ATH overlayed */
  111177. for(j=0;j<P_LEVELS;j++){
  111178. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  111179. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  111180. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  111181. max_curve(athc[j],workc[i][j]);
  111182. }
  111183. /* Now limit the louder curves.
  111184. the idea is this: We don't know what the playback attenuation
  111185. will be; 0dB SL moves every time the user twiddles the volume
  111186. knob. So that means we have to use a single 'most pessimal' curve
  111187. for all masking amplitudes, right? Wrong. The *loudest* sound
  111188. can be in (we assume) a range of ...+100dB] SL. However, sounds
  111189. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  111190. etc... */
  111191. for(j=1;j<P_LEVELS;j++){
  111192. min_curve(athc[j],athc[j-1]);
  111193. min_curve(workc[i][j],athc[j]);
  111194. }
  111195. }
  111196. for(i=0;i<P_BANDS;i++){
  111197. int hi_curve,lo_curve,bin;
  111198. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  111199. /* low frequency curves are measured with greater resolution than
  111200. the MDCT/FFT will actually give us; we want the curve applied
  111201. to the tone data to be pessimistic and thus apply the minimum
  111202. masking possible for a given bin. That means that a single bin
  111203. could span more than one octave and that the curve will be a
  111204. composite of multiple octaves. It also may mean that a single
  111205. bin may span > an eighth of an octave and that the eighth
  111206. octave values may also be composited. */
  111207. /* which octave curves will we be compositing? */
  111208. bin=floor(fromOC(i*.5)/binHz);
  111209. lo_curve= ceil(toOC(bin*binHz+1)*2);
  111210. hi_curve= floor(toOC((bin+1)*binHz)*2);
  111211. if(lo_curve>i)lo_curve=i;
  111212. if(lo_curve<0)lo_curve=0;
  111213. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  111214. for(m=0;m<P_LEVELS;m++){
  111215. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  111216. for(j=0;j<n;j++)brute_buffer[j]=999.;
  111217. /* render the curve into bins, then pull values back into curve.
  111218. The point is that any inherent subsampling aliasing results in
  111219. a safe minimum */
  111220. for(k=lo_curve;k<=hi_curve;k++){
  111221. int l=0;
  111222. for(j=0;j<EHMER_MAX;j++){
  111223. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  111224. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  111225. if(lo_bin<0)lo_bin=0;
  111226. if(lo_bin>n)lo_bin=n;
  111227. if(lo_bin<l)l=lo_bin;
  111228. if(hi_bin<0)hi_bin=0;
  111229. if(hi_bin>n)hi_bin=n;
  111230. for(;l<hi_bin && l<n;l++)
  111231. if(brute_buffer[l]>workc[k][m][j])
  111232. brute_buffer[l]=workc[k][m][j];
  111233. }
  111234. for(;l<n;l++)
  111235. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  111236. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  111237. }
  111238. /* be equally paranoid about being valid up to next half ocatve */
  111239. if(i+1<P_BANDS){
  111240. int l=0;
  111241. k=i+1;
  111242. for(j=0;j<EHMER_MAX;j++){
  111243. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  111244. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  111245. if(lo_bin<0)lo_bin=0;
  111246. if(lo_bin>n)lo_bin=n;
  111247. if(lo_bin<l)l=lo_bin;
  111248. if(hi_bin<0)hi_bin=0;
  111249. if(hi_bin>n)hi_bin=n;
  111250. for(;l<hi_bin && l<n;l++)
  111251. if(brute_buffer[l]>workc[k][m][j])
  111252. brute_buffer[l]=workc[k][m][j];
  111253. }
  111254. for(;l<n;l++)
  111255. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  111256. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  111257. }
  111258. for(j=0;j<EHMER_MAX;j++){
  111259. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  111260. if(bin<0){
  111261. ret[i][m][j+2]=-999.;
  111262. }else{
  111263. if(bin>=n){
  111264. ret[i][m][j+2]=-999.;
  111265. }else{
  111266. ret[i][m][j+2]=brute_buffer[bin];
  111267. }
  111268. }
  111269. }
  111270. /* add fenceposts */
  111271. for(j=0;j<EHMER_OFFSET;j++)
  111272. if(ret[i][m][j+2]>-200.f)break;
  111273. ret[i][m][0]=j;
  111274. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  111275. if(ret[i][m][j+2]>-200.f)
  111276. break;
  111277. ret[i][m][1]=j;
  111278. }
  111279. }
  111280. return(ret);
  111281. }
  111282. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  111283. vorbis_info_psy_global *gi,int n,long rate){
  111284. long i,j,lo=-99,hi=1;
  111285. long maxoc;
  111286. memset(p,0,sizeof(*p));
  111287. p->eighth_octave_lines=gi->eighth_octave_lines;
  111288. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  111289. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  111290. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  111291. p->total_octave_lines=maxoc-p->firstoc+1;
  111292. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  111293. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  111294. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  111295. p->vi=vi;
  111296. p->n=n;
  111297. p->rate=rate;
  111298. /* AoTuV HF weighting */
  111299. p->m_val = 1.;
  111300. if(rate < 26000) p->m_val = 0;
  111301. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  111302. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  111303. /* set up the lookups for a given blocksize and sample rate */
  111304. for(i=0,j=0;i<MAX_ATH-1;i++){
  111305. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  111306. float base=ATH[i];
  111307. if(j<endpos){
  111308. float delta=(ATH[i+1]-base)/(endpos-j);
  111309. for(;j<endpos && j<n;j++){
  111310. p->ath[j]=base+100.;
  111311. base+=delta;
  111312. }
  111313. }
  111314. }
  111315. for(i=0;i<n;i++){
  111316. float bark=toBARK(rate/(2*n)*i);
  111317. for(;lo+vi->noisewindowlomin<i &&
  111318. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  111319. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  111320. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  111321. p->bark[i]=((lo-1)<<16)+(hi-1);
  111322. }
  111323. for(i=0;i<n;i++)
  111324. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  111325. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  111326. vi->tone_centerboost,vi->tone_decay);
  111327. /* set up rolling noise median */
  111328. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  111329. for(i=0;i<P_NOISECURVES;i++)
  111330. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  111331. for(i=0;i<n;i++){
  111332. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  111333. int inthalfoc;
  111334. float del;
  111335. if(halfoc<0)halfoc=0;
  111336. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  111337. inthalfoc=(int)halfoc;
  111338. del=halfoc-inthalfoc;
  111339. for(j=0;j<P_NOISECURVES;j++)
  111340. p->noiseoffset[j][i]=
  111341. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  111342. p->vi->noiseoff[j][inthalfoc+1]*del;
  111343. }
  111344. #if 0
  111345. {
  111346. static int ls=0;
  111347. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  111348. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  111349. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  111350. }
  111351. #endif
  111352. }
  111353. void _vp_psy_clear(vorbis_look_psy *p){
  111354. int i,j;
  111355. if(p){
  111356. if(p->ath)_ogg_free(p->ath);
  111357. if(p->octave)_ogg_free(p->octave);
  111358. if(p->bark)_ogg_free(p->bark);
  111359. if(p->tonecurves){
  111360. for(i=0;i<P_BANDS;i++){
  111361. for(j=0;j<P_LEVELS;j++){
  111362. _ogg_free(p->tonecurves[i][j]);
  111363. }
  111364. _ogg_free(p->tonecurves[i]);
  111365. }
  111366. _ogg_free(p->tonecurves);
  111367. }
  111368. if(p->noiseoffset){
  111369. for(i=0;i<P_NOISECURVES;i++){
  111370. _ogg_free(p->noiseoffset[i]);
  111371. }
  111372. _ogg_free(p->noiseoffset);
  111373. }
  111374. memset(p,0,sizeof(*p));
  111375. }
  111376. }
  111377. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  111378. static void seed_curve(float *seed,
  111379. const float **curves,
  111380. float amp,
  111381. int oc, int n,
  111382. int linesper,float dBoffset){
  111383. int i,post1;
  111384. int seedptr;
  111385. const float *posts,*curve;
  111386. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  111387. choice=max(choice,0);
  111388. choice=min(choice,P_LEVELS-1);
  111389. posts=curves[choice];
  111390. curve=posts+2;
  111391. post1=(int)posts[1];
  111392. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  111393. for(i=posts[0];i<post1;i++){
  111394. if(seedptr>0){
  111395. float lin=amp+curve[i];
  111396. if(seed[seedptr]<lin)seed[seedptr]=lin;
  111397. }
  111398. seedptr+=linesper;
  111399. if(seedptr>=n)break;
  111400. }
  111401. }
  111402. static void seed_loop(vorbis_look_psy *p,
  111403. const float ***curves,
  111404. const float *f,
  111405. const float *flr,
  111406. float *seed,
  111407. float specmax){
  111408. vorbis_info_psy *vi=p->vi;
  111409. long n=p->n,i;
  111410. float dBoffset=vi->max_curve_dB-specmax;
  111411. /* prime the working vector with peak values */
  111412. for(i=0;i<n;i++){
  111413. float max=f[i];
  111414. long oc=p->octave[i];
  111415. while(i+1<n && p->octave[i+1]==oc){
  111416. i++;
  111417. if(f[i]>max)max=f[i];
  111418. }
  111419. if(max+6.f>flr[i]){
  111420. oc=oc>>p->shiftoc;
  111421. if(oc>=P_BANDS)oc=P_BANDS-1;
  111422. if(oc<0)oc=0;
  111423. seed_curve(seed,
  111424. curves[oc],
  111425. max,
  111426. p->octave[i]-p->firstoc,
  111427. p->total_octave_lines,
  111428. p->eighth_octave_lines,
  111429. dBoffset);
  111430. }
  111431. }
  111432. }
  111433. static void seed_chase(float *seeds, int linesper, long n){
  111434. long *posstack=(long*)alloca(n*sizeof(*posstack));
  111435. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  111436. long stack=0;
  111437. long pos=0;
  111438. long i;
  111439. for(i=0;i<n;i++){
  111440. if(stack<2){
  111441. posstack[stack]=i;
  111442. ampstack[stack++]=seeds[i];
  111443. }else{
  111444. while(1){
  111445. if(seeds[i]<ampstack[stack-1]){
  111446. posstack[stack]=i;
  111447. ampstack[stack++]=seeds[i];
  111448. break;
  111449. }else{
  111450. if(i<posstack[stack-1]+linesper){
  111451. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  111452. i<posstack[stack-2]+linesper){
  111453. /* we completely overlap, making stack-1 irrelevant. pop it */
  111454. stack--;
  111455. continue;
  111456. }
  111457. }
  111458. posstack[stack]=i;
  111459. ampstack[stack++]=seeds[i];
  111460. break;
  111461. }
  111462. }
  111463. }
  111464. }
  111465. /* the stack now contains only the positions that are relevant. Scan
  111466. 'em straight through */
  111467. for(i=0;i<stack;i++){
  111468. long endpos;
  111469. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  111470. endpos=posstack[i+1];
  111471. }else{
  111472. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  111473. discarded in short frames */
  111474. }
  111475. if(endpos>n)endpos=n;
  111476. for(;pos<endpos;pos++)
  111477. seeds[pos]=ampstack[i];
  111478. }
  111479. /* there. Linear time. I now remember this was on a problem set I
  111480. had in Grad Skool... I didn't solve it at the time ;-) */
  111481. }
  111482. /* bleaugh, this is more complicated than it needs to be */
  111483. #include<stdio.h>
  111484. static void max_seeds(vorbis_look_psy *p,
  111485. float *seed,
  111486. float *flr){
  111487. long n=p->total_octave_lines;
  111488. int linesper=p->eighth_octave_lines;
  111489. long linpos=0;
  111490. long pos;
  111491. seed_chase(seed,linesper,n); /* for masking */
  111492. pos=p->octave[0]-p->firstoc-(linesper>>1);
  111493. while(linpos+1<p->n){
  111494. float minV=seed[pos];
  111495. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  111496. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  111497. while(pos+1<=end){
  111498. pos++;
  111499. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  111500. minV=seed[pos];
  111501. }
  111502. end=pos+p->firstoc;
  111503. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  111504. if(flr[linpos]<minV)flr[linpos]=minV;
  111505. }
  111506. {
  111507. float minV=seed[p->total_octave_lines-1];
  111508. for(;linpos<p->n;linpos++)
  111509. if(flr[linpos]<minV)flr[linpos]=minV;
  111510. }
  111511. }
  111512. static void bark_noise_hybridmp(int n,const long *b,
  111513. const float *f,
  111514. float *noise,
  111515. const float offset,
  111516. const int fixed){
  111517. float *N=(float*) alloca(n*sizeof(*N));
  111518. float *X=(float*) alloca(n*sizeof(*N));
  111519. float *XX=(float*) alloca(n*sizeof(*N));
  111520. float *Y=(float*) alloca(n*sizeof(*N));
  111521. float *XY=(float*) alloca(n*sizeof(*N));
  111522. float tN, tX, tXX, tY, tXY;
  111523. int i;
  111524. int lo, hi;
  111525. float R, A, B, D;
  111526. float w, x, y;
  111527. tN = tX = tXX = tY = tXY = 0.f;
  111528. y = f[0] + offset;
  111529. if (y < 1.f) y = 1.f;
  111530. w = y * y * .5;
  111531. tN += w;
  111532. tX += w;
  111533. tY += w * y;
  111534. N[0] = tN;
  111535. X[0] = tX;
  111536. XX[0] = tXX;
  111537. Y[0] = tY;
  111538. XY[0] = tXY;
  111539. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  111540. y = f[i] + offset;
  111541. if (y < 1.f) y = 1.f;
  111542. w = y * y;
  111543. tN += w;
  111544. tX += w * x;
  111545. tXX += w * x * x;
  111546. tY += w * y;
  111547. tXY += w * x * y;
  111548. N[i] = tN;
  111549. X[i] = tX;
  111550. XX[i] = tXX;
  111551. Y[i] = tY;
  111552. XY[i] = tXY;
  111553. }
  111554. for (i = 0, x = 0.f;; i++, x += 1.f) {
  111555. lo = b[i] >> 16;
  111556. if( lo>=0 ) break;
  111557. hi = b[i] & 0xffff;
  111558. tN = N[hi] + N[-lo];
  111559. tX = X[hi] - X[-lo];
  111560. tXX = XX[hi] + XX[-lo];
  111561. tY = Y[hi] + Y[-lo];
  111562. tXY = XY[hi] - XY[-lo];
  111563. A = tY * tXX - tX * tXY;
  111564. B = tN * tXY - tX * tY;
  111565. D = tN * tXX - tX * tX;
  111566. R = (A + x * B) / D;
  111567. if (R < 0.f)
  111568. R = 0.f;
  111569. noise[i] = R - offset;
  111570. }
  111571. for ( ;; i++, x += 1.f) {
  111572. lo = b[i] >> 16;
  111573. hi = b[i] & 0xffff;
  111574. if(hi>=n)break;
  111575. tN = N[hi] - N[lo];
  111576. tX = X[hi] - X[lo];
  111577. tXX = XX[hi] - XX[lo];
  111578. tY = Y[hi] - Y[lo];
  111579. tXY = XY[hi] - XY[lo];
  111580. A = tY * tXX - tX * tXY;
  111581. B = tN * tXY - tX * tY;
  111582. D = tN * tXX - tX * tX;
  111583. R = (A + x * B) / D;
  111584. if (R < 0.f) R = 0.f;
  111585. noise[i] = R - offset;
  111586. }
  111587. for ( ; i < n; i++, x += 1.f) {
  111588. R = (A + x * B) / D;
  111589. if (R < 0.f) R = 0.f;
  111590. noise[i] = R - offset;
  111591. }
  111592. if (fixed <= 0) return;
  111593. for (i = 0, x = 0.f;; i++, x += 1.f) {
  111594. hi = i + fixed / 2;
  111595. lo = hi - fixed;
  111596. if(lo>=0)break;
  111597. tN = N[hi] + N[-lo];
  111598. tX = X[hi] - X[-lo];
  111599. tXX = XX[hi] + XX[-lo];
  111600. tY = Y[hi] + Y[-lo];
  111601. tXY = XY[hi] - XY[-lo];
  111602. A = tY * tXX - tX * tXY;
  111603. B = tN * tXY - tX * tY;
  111604. D = tN * tXX - tX * tX;
  111605. R = (A + x * B) / D;
  111606. if (R - offset < noise[i]) noise[i] = R - offset;
  111607. }
  111608. for ( ;; i++, x += 1.f) {
  111609. hi = i + fixed / 2;
  111610. lo = hi - fixed;
  111611. if(hi>=n)break;
  111612. tN = N[hi] - N[lo];
  111613. tX = X[hi] - X[lo];
  111614. tXX = XX[hi] - XX[lo];
  111615. tY = Y[hi] - Y[lo];
  111616. tXY = XY[hi] - XY[lo];
  111617. A = tY * tXX - tX * tXY;
  111618. B = tN * tXY - tX * tY;
  111619. D = tN * tXX - tX * tX;
  111620. R = (A + x * B) / D;
  111621. if (R - offset < noise[i]) noise[i] = R - offset;
  111622. }
  111623. for ( ; i < n; i++, x += 1.f) {
  111624. R = (A + x * B) / D;
  111625. if (R - offset < noise[i]) noise[i] = R - offset;
  111626. }
  111627. }
  111628. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  111629. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  111630. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  111631. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  111632. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  111633. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  111634. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  111635. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  111636. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  111637. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  111638. 973377.F, 913981.F, 858210.F, 805842.F,
  111639. 756669.F, 710497.F, 667142.F, 626433.F,
  111640. 588208.F, 552316.F, 518613.F, 486967.F,
  111641. 457252.F, 429351.F, 403152.F, 378551.F,
  111642. 355452.F, 333762.F, 313396.F, 294273.F,
  111643. 276316.F, 259455.F, 243623.F, 228757.F,
  111644. 214798.F, 201691.F, 189384.F, 177828.F,
  111645. 166977.F, 156788.F, 147221.F, 138237.F,
  111646. 129802.F, 121881.F, 114444.F, 107461.F,
  111647. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  111648. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  111649. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  111650. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  111651. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  111652. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  111653. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  111654. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  111655. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  111656. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  111657. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  111658. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  111659. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  111660. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  111661. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  111662. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  111663. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  111664. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  111665. 1084.32F, 1018.15F, 956.024F, 897.687F,
  111666. 842.910F, 791.475F, 743.179F, 697.830F,
  111667. 655.249F, 615.265F, 577.722F, 542.469F,
  111668. 509.367F, 478.286F, 449.101F, 421.696F,
  111669. 395.964F, 371.803F, 349.115F, 327.812F,
  111670. 307.809F, 289.026F, 271.390F, 254.830F,
  111671. 239.280F, 224.679F, 210.969F, 198.096F,
  111672. 186.008F, 174.658F, 164.000F, 153.993F,
  111673. 144.596F, 135.773F, 127.488F, 119.708F,
  111674. 112.404F, 105.545F, 99.1046F, 93.0572F,
  111675. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  111676. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  111677. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  111678. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  111679. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  111680. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  111681. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  111682. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  111683. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  111684. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  111685. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  111686. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  111687. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  111688. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  111689. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  111690. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  111691. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  111692. 1.20790F, 1.13419F, 1.06499F, 1.F
  111693. };
  111694. void _vp_remove_floor(vorbis_look_psy *p,
  111695. float *mdct,
  111696. int *codedflr,
  111697. float *residue,
  111698. int sliding_lowpass){
  111699. int i,n=p->n;
  111700. if(sliding_lowpass>n)sliding_lowpass=n;
  111701. for(i=0;i<sliding_lowpass;i++){
  111702. residue[i]=
  111703. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  111704. }
  111705. for(;i<n;i++)
  111706. residue[i]=0.;
  111707. }
  111708. void _vp_noisemask(vorbis_look_psy *p,
  111709. float *logmdct,
  111710. float *logmask){
  111711. int i,n=p->n;
  111712. float *work=(float*) alloca(n*sizeof(*work));
  111713. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  111714. 140.,-1);
  111715. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  111716. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  111717. p->vi->noisewindowfixed);
  111718. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  111719. #if 0
  111720. {
  111721. static int seq=0;
  111722. float work2[n];
  111723. for(i=0;i<n;i++){
  111724. work2[i]=logmask[i]+work[i];
  111725. }
  111726. if(seq&1)
  111727. _analysis_output("median2R",seq/2,work,n,1,0,0);
  111728. else
  111729. _analysis_output("median2L",seq/2,work,n,1,0,0);
  111730. if(seq&1)
  111731. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  111732. else
  111733. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  111734. seq++;
  111735. }
  111736. #endif
  111737. for(i=0;i<n;i++){
  111738. int dB=logmask[i]+.5;
  111739. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  111740. if(dB<0)dB=0;
  111741. logmask[i]= work[i]+p->vi->noisecompand[dB];
  111742. }
  111743. }
  111744. void _vp_tonemask(vorbis_look_psy *p,
  111745. float *logfft,
  111746. float *logmask,
  111747. float global_specmax,
  111748. float local_specmax){
  111749. int i,n=p->n;
  111750. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  111751. float att=local_specmax+p->vi->ath_adjatt;
  111752. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  111753. /* set the ATH (floating below localmax, not global max by a
  111754. specified att) */
  111755. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  111756. for(i=0;i<n;i++)
  111757. logmask[i]=p->ath[i]+att;
  111758. /* tone masking */
  111759. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  111760. max_seeds(p,seed,logmask);
  111761. }
  111762. void _vp_offset_and_mix(vorbis_look_psy *p,
  111763. float *noise,
  111764. float *tone,
  111765. int offset_select,
  111766. float *logmask,
  111767. float *mdct,
  111768. float *logmdct){
  111769. int i,n=p->n;
  111770. float de, coeffi, cx;/* AoTuV */
  111771. float toneatt=p->vi->tone_masteratt[offset_select];
  111772. cx = p->m_val;
  111773. for(i=0;i<n;i++){
  111774. float val= noise[i]+p->noiseoffset[offset_select][i];
  111775. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  111776. logmask[i]=max(val,tone[i]+toneatt);
  111777. /* AoTuV */
  111778. /** @ M1 **
  111779. The following codes improve a noise problem.
  111780. A fundamental idea uses the value of masking and carries out
  111781. the relative compensation of the MDCT.
  111782. However, this code is not perfect and all noise problems cannot be solved.
  111783. by Aoyumi @ 2004/04/18
  111784. */
  111785. if(offset_select == 1) {
  111786. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  111787. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  111788. if(val > coeffi){
  111789. /* mdct value is > -17.2 dB below floor */
  111790. de = 1.0-((val-coeffi)*0.005*cx);
  111791. /* pro-rated attenuation:
  111792. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  111793. -0.77 dB boost if mdct value is 0dB (relative to floor)
  111794. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  111795. etc... */
  111796. if(de < 0) de = 0.0001;
  111797. }else
  111798. /* mdct value is <= -17.2 dB below floor */
  111799. de = 1.0-((val-coeffi)*0.0003*cx);
  111800. /* pro-rated attenuation:
  111801. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  111802. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  111803. etc... */
  111804. mdct[i] *= de;
  111805. }
  111806. }
  111807. }
  111808. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  111809. vorbis_info *vi=vd->vi;
  111810. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111811. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111812. int n=ci->blocksizes[vd->W]/2;
  111813. float secs=(float)n/vi->rate;
  111814. amp+=secs*gi->ampmax_att_per_sec;
  111815. if(amp<-9999)amp=-9999;
  111816. return(amp);
  111817. }
  111818. static void couple_lossless(float A, float B,
  111819. float *qA, float *qB){
  111820. int test1=fabs(*qA)>fabs(*qB);
  111821. test1-= fabs(*qA)<fabs(*qB);
  111822. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  111823. if(test1==1){
  111824. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  111825. }else{
  111826. float temp=*qB;
  111827. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  111828. *qA=temp;
  111829. }
  111830. if(*qB>fabs(*qA)*1.9999f){
  111831. *qB= -fabs(*qA)*2.f;
  111832. *qA= -*qA;
  111833. }
  111834. }
  111835. static float hypot_lookup[32]={
  111836. -0.009935, -0.011245, -0.012726, -0.014397,
  111837. -0.016282, -0.018407, -0.020800, -0.023494,
  111838. -0.026522, -0.029923, -0.033737, -0.038010,
  111839. -0.042787, -0.048121, -0.054064, -0.060671,
  111840. -0.068000, -0.076109, -0.085054, -0.094892,
  111841. -0.105675, -0.117451, -0.130260, -0.144134,
  111842. -0.159093, -0.175146, -0.192286, -0.210490,
  111843. -0.229718, -0.249913, -0.271001, -0.292893};
  111844. static void precomputed_couple_point(float premag,
  111845. int floorA,int floorB,
  111846. float *mag, float *ang){
  111847. int test=(floorA>floorB)-1;
  111848. int offset=31-abs(floorA-floorB);
  111849. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  111850. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  111851. *mag=premag*floormag;
  111852. *ang=0.f;
  111853. }
  111854. /* just like below, this is currently set up to only do
  111855. single-step-depth coupling. Otherwise, we'd have to do more
  111856. copying (which will be inevitable later) */
  111857. /* doing the real circular magnitude calculation is audibly superior
  111858. to (A+B)/sqrt(2) */
  111859. static float dipole_hypot(float a, float b){
  111860. if(a>0.){
  111861. if(b>0.)return sqrt(a*a+b*b);
  111862. if(a>-b)return sqrt(a*a-b*b);
  111863. return -sqrt(b*b-a*a);
  111864. }
  111865. if(b<0.)return -sqrt(a*a+b*b);
  111866. if(-a>b)return -sqrt(a*a-b*b);
  111867. return sqrt(b*b-a*a);
  111868. }
  111869. static float round_hypot(float a, float b){
  111870. if(a>0.){
  111871. if(b>0.)return sqrt(a*a+b*b);
  111872. if(a>-b)return sqrt(a*a+b*b);
  111873. return -sqrt(b*b+a*a);
  111874. }
  111875. if(b<0.)return -sqrt(a*a+b*b);
  111876. if(-a>b)return -sqrt(a*a+b*b);
  111877. return sqrt(b*b+a*a);
  111878. }
  111879. /* revert to round hypot for now */
  111880. float **_vp_quantize_couple_memo(vorbis_block *vb,
  111881. vorbis_info_psy_global *g,
  111882. vorbis_look_psy *p,
  111883. vorbis_info_mapping0 *vi,
  111884. float **mdct){
  111885. int i,j,n=p->n;
  111886. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  111887. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  111888. for(i=0;i<vi->coupling_steps;i++){
  111889. float *mdctM=mdct[vi->coupling_mag[i]];
  111890. float *mdctA=mdct[vi->coupling_ang[i]];
  111891. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  111892. for(j=0;j<limit;j++)
  111893. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  111894. for(;j<n;j++)
  111895. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  111896. }
  111897. return(ret);
  111898. }
  111899. /* this is for per-channel noise normalization */
  111900. static int apsort(const void *a, const void *b){
  111901. float f1=fabs(**(float**)a);
  111902. float f2=fabs(**(float**)b);
  111903. return (f1<f2)-(f1>f2);
  111904. }
  111905. int **_vp_quantize_couple_sort(vorbis_block *vb,
  111906. vorbis_look_psy *p,
  111907. vorbis_info_mapping0 *vi,
  111908. float **mags){
  111909. if(p->vi->normal_point_p){
  111910. int i,j,k,n=p->n;
  111911. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  111912. int partition=p->vi->normal_partition;
  111913. float **work=(float**) alloca(sizeof(*work)*partition);
  111914. for(i=0;i<vi->coupling_steps;i++){
  111915. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  111916. for(j=0;j<n;j+=partition){
  111917. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  111918. qsort(work,partition,sizeof(*work),apsort);
  111919. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  111920. }
  111921. }
  111922. return(ret);
  111923. }
  111924. return(NULL);
  111925. }
  111926. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  111927. float *magnitudes,int *sortedindex){
  111928. int i,j,n=p->n;
  111929. vorbis_info_psy *vi=p->vi;
  111930. int partition=vi->normal_partition;
  111931. float **work=(float**) alloca(sizeof(*work)*partition);
  111932. int start=vi->normal_start;
  111933. for(j=start;j<n;j+=partition){
  111934. if(j+partition>n)partition=n-j;
  111935. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  111936. qsort(work,partition,sizeof(*work),apsort);
  111937. for(i=0;i<partition;i++){
  111938. sortedindex[i+j-start]=work[i]-magnitudes;
  111939. }
  111940. }
  111941. }
  111942. void _vp_noise_normalize(vorbis_look_psy *p,
  111943. float *in,float *out,int *sortedindex){
  111944. int flag=0,i,j=0,n=p->n;
  111945. vorbis_info_psy *vi=p->vi;
  111946. int partition=vi->normal_partition;
  111947. int start=vi->normal_start;
  111948. if(start>n)start=n;
  111949. if(vi->normal_channel_p){
  111950. for(;j<start;j++)
  111951. out[j]=rint(in[j]);
  111952. for(;j+partition<=n;j+=partition){
  111953. float acc=0.;
  111954. int k;
  111955. for(i=j;i<j+partition;i++)
  111956. acc+=in[i]*in[i];
  111957. for(i=0;i<partition;i++){
  111958. k=sortedindex[i+j-start];
  111959. if(in[k]*in[k]>=.25f){
  111960. out[k]=rint(in[k]);
  111961. acc-=in[k]*in[k];
  111962. flag=1;
  111963. }else{
  111964. if(acc<vi->normal_thresh)break;
  111965. out[k]=unitnorm(in[k]);
  111966. acc-=1.;
  111967. }
  111968. }
  111969. for(;i<partition;i++){
  111970. k=sortedindex[i+j-start];
  111971. out[k]=0.;
  111972. }
  111973. }
  111974. }
  111975. for(;j<n;j++)
  111976. out[j]=rint(in[j]);
  111977. }
  111978. void _vp_couple(int blobno,
  111979. vorbis_info_psy_global *g,
  111980. vorbis_look_psy *p,
  111981. vorbis_info_mapping0 *vi,
  111982. float **res,
  111983. float **mag_memo,
  111984. int **mag_sort,
  111985. int **ifloor,
  111986. int *nonzero,
  111987. int sliding_lowpass){
  111988. int i,j,k,n=p->n;
  111989. /* perform any requested channel coupling */
  111990. /* point stereo can only be used in a first stage (in this encoder)
  111991. because of the dependency on floor lookups */
  111992. for(i=0;i<vi->coupling_steps;i++){
  111993. /* once we're doing multistage coupling in which a channel goes
  111994. through more than one coupling step, the floor vector
  111995. magnitudes will also have to be recalculated an propogated
  111996. along with PCM. Right now, we're not (that will wait until 5.1
  111997. most likely), so the code isn't here yet. The memory management
  111998. here is all assuming single depth couplings anyway. */
  111999. /* make sure coupling a zero and a nonzero channel results in two
  112000. nonzero channels. */
  112001. if(nonzero[vi->coupling_mag[i]] ||
  112002. nonzero[vi->coupling_ang[i]]){
  112003. float *rM=res[vi->coupling_mag[i]];
  112004. float *rA=res[vi->coupling_ang[i]];
  112005. float *qM=rM+n;
  112006. float *qA=rA+n;
  112007. int *floorM=ifloor[vi->coupling_mag[i]];
  112008. int *floorA=ifloor[vi->coupling_ang[i]];
  112009. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  112010. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  112011. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  112012. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  112013. int pointlimit=limit;
  112014. nonzero[vi->coupling_mag[i]]=1;
  112015. nonzero[vi->coupling_ang[i]]=1;
  112016. /* The threshold of a stereo is changed with the size of n */
  112017. if(n > 1000)
  112018. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  112019. for(j=0;j<p->n;j+=partition){
  112020. float acc=0.f;
  112021. for(k=0;k<partition;k++){
  112022. int l=k+j;
  112023. if(l<sliding_lowpass){
  112024. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  112025. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  112026. precomputed_couple_point(mag_memo[i][l],
  112027. floorM[l],floorA[l],
  112028. qM+l,qA+l);
  112029. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  112030. }else{
  112031. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  112032. }
  112033. }else{
  112034. qM[l]=0.;
  112035. qA[l]=0.;
  112036. }
  112037. }
  112038. if(p->vi->normal_point_p){
  112039. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  112040. int l=mag_sort[i][j+k];
  112041. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  112042. qM[l]=unitnorm(qM[l]);
  112043. acc-=1.f;
  112044. }
  112045. }
  112046. }
  112047. }
  112048. }
  112049. }
  112050. }
  112051. /* AoTuV */
  112052. /** @ M2 **
  112053. The boost problem by the combination of noise normalization and point stereo is eased.
  112054. However, this is a temporary patch.
  112055. by Aoyumi @ 2004/04/18
  112056. */
  112057. void hf_reduction(vorbis_info_psy_global *g,
  112058. vorbis_look_psy *p,
  112059. vorbis_info_mapping0 *vi,
  112060. float **mdct){
  112061. int i,j,n=p->n, de=0.3*p->m_val;
  112062. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  112063. for(i=0; i<vi->coupling_steps; i++){
  112064. /* for(j=start; j<limit; j++){} // ???*/
  112065. for(j=limit; j<n; j++)
  112066. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  112067. }
  112068. }
  112069. #endif
  112070. /********* End of inlined file: psy.c *********/
  112071. /********* Start of inlined file: registry.c *********/
  112072. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112073. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112074. // tasks..
  112075. #ifdef _MSC_VER
  112076. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112077. #endif
  112078. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112079. #if JUCE_USE_OGGVORBIS
  112080. /* seems like major overkill now; the backend numbers will grow into
  112081. the infrastructure soon enough */
  112082. extern vorbis_func_floor floor0_exportbundle;
  112083. extern vorbis_func_floor floor1_exportbundle;
  112084. extern vorbis_func_residue residue0_exportbundle;
  112085. extern vorbis_func_residue residue1_exportbundle;
  112086. extern vorbis_func_residue residue2_exportbundle;
  112087. extern vorbis_func_mapping mapping0_exportbundle;
  112088. vorbis_func_floor *_floor_P[]={
  112089. &floor0_exportbundle,
  112090. &floor1_exportbundle,
  112091. };
  112092. vorbis_func_residue *_residue_P[]={
  112093. &residue0_exportbundle,
  112094. &residue1_exportbundle,
  112095. &residue2_exportbundle,
  112096. };
  112097. vorbis_func_mapping *_mapping_P[]={
  112098. &mapping0_exportbundle,
  112099. };
  112100. #endif
  112101. /********* End of inlined file: registry.c *********/
  112102. /********* Start of inlined file: res0.c *********/
  112103. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  112104. encode/decode loops are coded for clarity and performance is not
  112105. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  112106. it's slow. */
  112107. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112108. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112109. // tasks..
  112110. #ifdef _MSC_VER
  112111. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112112. #endif
  112113. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112114. #if JUCE_USE_OGGVORBIS
  112115. #include <stdlib.h>
  112116. #include <string.h>
  112117. #include <math.h>
  112118. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  112119. #include <stdio.h>
  112120. #endif
  112121. typedef struct {
  112122. vorbis_info_residue0 *info;
  112123. int parts;
  112124. int stages;
  112125. codebook *fullbooks;
  112126. codebook *phrasebook;
  112127. codebook ***partbooks;
  112128. int partvals;
  112129. int **decodemap;
  112130. long postbits;
  112131. long phrasebits;
  112132. long frames;
  112133. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  112134. int train_seq;
  112135. long *training_data[8][64];
  112136. float training_max[8][64];
  112137. float training_min[8][64];
  112138. float tmin;
  112139. float tmax;
  112140. #endif
  112141. } vorbis_look_residue0;
  112142. void res0_free_info(vorbis_info_residue *i){
  112143. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  112144. if(info){
  112145. memset(info,0,sizeof(*info));
  112146. _ogg_free(info);
  112147. }
  112148. }
  112149. void res0_free_look(vorbis_look_residue *i){
  112150. int j;
  112151. if(i){
  112152. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  112153. #ifdef TRAIN_RES
  112154. {
  112155. int j,k,l;
  112156. for(j=0;j<look->parts;j++){
  112157. /*fprintf(stderr,"partition %d: ",j);*/
  112158. for(k=0;k<8;k++)
  112159. if(look->training_data[k][j]){
  112160. char buffer[80];
  112161. FILE *of;
  112162. codebook *statebook=look->partbooks[j][k];
  112163. /* long and short into the same bucket by current convention */
  112164. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  112165. of=fopen(buffer,"a");
  112166. for(l=0;l<statebook->entries;l++)
  112167. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  112168. fclose(of);
  112169. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  112170. look->training_min[k][j],look->training_max[k][j]);*/
  112171. _ogg_free(look->training_data[k][j]);
  112172. look->training_data[k][j]=NULL;
  112173. }
  112174. /*fprintf(stderr,"\n");*/
  112175. }
  112176. }
  112177. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  112178. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  112179. (float)look->phrasebits/look->frames,
  112180. (float)look->postbits/look->frames,
  112181. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112182. #endif
  112183. /*vorbis_info_residue0 *info=look->info;
  112184. fprintf(stderr,
  112185. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  112186. "(%g/frame) \n",look->frames,look->phrasebits,
  112187. look->resbitsflat,
  112188. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  112189. for(j=0;j<look->parts;j++){
  112190. long acc=0;
  112191. fprintf(stderr,"\t[%d] == ",j);
  112192. for(k=0;k<look->stages;k++)
  112193. if((info->secondstages[j]>>k)&1){
  112194. fprintf(stderr,"%ld,",look->resbits[j][k]);
  112195. acc+=look->resbits[j][k];
  112196. }
  112197. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  112198. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  112199. }
  112200. fprintf(stderr,"\n");*/
  112201. for(j=0;j<look->parts;j++)
  112202. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  112203. _ogg_free(look->partbooks);
  112204. for(j=0;j<look->partvals;j++)
  112205. _ogg_free(look->decodemap[j]);
  112206. _ogg_free(look->decodemap);
  112207. memset(look,0,sizeof(*look));
  112208. _ogg_free(look);
  112209. }
  112210. }
  112211. static int icount(unsigned int v){
  112212. int ret=0;
  112213. while(v){
  112214. ret+=v&1;
  112215. v>>=1;
  112216. }
  112217. return(ret);
  112218. }
  112219. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  112220. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  112221. int j,acc=0;
  112222. oggpack_write(opb,info->begin,24);
  112223. oggpack_write(opb,info->end,24);
  112224. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  112225. code with a partitioned book */
  112226. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  112227. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  112228. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  112229. bitmask of one indicates this partition class has bits to write
  112230. this pass */
  112231. for(j=0;j<info->partitions;j++){
  112232. if(ilog(info->secondstages[j])>3){
  112233. /* yes, this is a minor hack due to not thinking ahead */
  112234. oggpack_write(opb,info->secondstages[j],3);
  112235. oggpack_write(opb,1,1);
  112236. oggpack_write(opb,info->secondstages[j]>>3,5);
  112237. }else
  112238. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  112239. acc+=icount(info->secondstages[j]);
  112240. }
  112241. for(j=0;j<acc;j++)
  112242. oggpack_write(opb,info->booklist[j],8);
  112243. }
  112244. /* vorbis_info is for range checking */
  112245. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  112246. int j,acc=0;
  112247. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  112248. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  112249. info->begin=oggpack_read(opb,24);
  112250. info->end=oggpack_read(opb,24);
  112251. info->grouping=oggpack_read(opb,24)+1;
  112252. info->partitions=oggpack_read(opb,6)+1;
  112253. info->groupbook=oggpack_read(opb,8);
  112254. for(j=0;j<info->partitions;j++){
  112255. int cascade=oggpack_read(opb,3);
  112256. if(oggpack_read(opb,1))
  112257. cascade|=(oggpack_read(opb,5)<<3);
  112258. info->secondstages[j]=cascade;
  112259. acc+=icount(cascade);
  112260. }
  112261. for(j=0;j<acc;j++)
  112262. info->booklist[j]=oggpack_read(opb,8);
  112263. if(info->groupbook>=ci->books)goto errout;
  112264. for(j=0;j<acc;j++)
  112265. if(info->booklist[j]>=ci->books)goto errout;
  112266. return(info);
  112267. errout:
  112268. res0_free_info(info);
  112269. return(NULL);
  112270. }
  112271. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  112272. vorbis_info_residue *vr){
  112273. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  112274. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  112275. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  112276. int j,k,acc=0;
  112277. int dim;
  112278. int maxstage=0;
  112279. look->info=info;
  112280. look->parts=info->partitions;
  112281. look->fullbooks=ci->fullbooks;
  112282. look->phrasebook=ci->fullbooks+info->groupbook;
  112283. dim=look->phrasebook->dim;
  112284. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  112285. for(j=0;j<look->parts;j++){
  112286. int stages=ilog(info->secondstages[j]);
  112287. if(stages){
  112288. if(stages>maxstage)maxstage=stages;
  112289. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  112290. for(k=0;k<stages;k++)
  112291. if(info->secondstages[j]&(1<<k)){
  112292. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  112293. #ifdef TRAIN_RES
  112294. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  112295. sizeof(***look->training_data));
  112296. #endif
  112297. }
  112298. }
  112299. }
  112300. look->partvals=rint(pow((float)look->parts,(float)dim));
  112301. look->stages=maxstage;
  112302. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  112303. for(j=0;j<look->partvals;j++){
  112304. long val=j;
  112305. long mult=look->partvals/look->parts;
  112306. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  112307. for(k=0;k<dim;k++){
  112308. long deco=val/mult;
  112309. val-=deco*mult;
  112310. mult/=look->parts;
  112311. look->decodemap[j][k]=deco;
  112312. }
  112313. }
  112314. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  112315. {
  112316. static int train_seq=0;
  112317. look->train_seq=train_seq++;
  112318. }
  112319. #endif
  112320. return(look);
  112321. }
  112322. /* break an abstraction and copy some code for performance purposes */
  112323. static int local_book_besterror(codebook *book,float *a){
  112324. int dim=book->dim,i,k,o;
  112325. int best=0;
  112326. encode_aux_threshmatch *tt=book->c->thresh_tree;
  112327. /* find the quant val of each scalar */
  112328. for(k=0,o=dim;k<dim;++k){
  112329. float val=a[--o];
  112330. i=tt->threshvals>>1;
  112331. if(val<tt->quantthresh[i]){
  112332. if(val<tt->quantthresh[i-1]){
  112333. for(--i;i>0;--i)
  112334. if(val>=tt->quantthresh[i-1])
  112335. break;
  112336. }
  112337. }else{
  112338. for(++i;i<tt->threshvals-1;++i)
  112339. if(val<tt->quantthresh[i])break;
  112340. }
  112341. best=(best*tt->quantvals)+tt->quantmap[i];
  112342. }
  112343. /* regular lattices are easy :-) */
  112344. if(book->c->lengthlist[best]<=0){
  112345. const static_codebook *c=book->c;
  112346. int i,j;
  112347. float bestf=0.f;
  112348. float *e=book->valuelist;
  112349. best=-1;
  112350. for(i=0;i<book->entries;i++){
  112351. if(c->lengthlist[i]>0){
  112352. float thisx=0.f;
  112353. for(j=0;j<dim;j++){
  112354. float val=(e[j]-a[j]);
  112355. thisx+=val*val;
  112356. }
  112357. if(best==-1 || thisx<bestf){
  112358. bestf=thisx;
  112359. best=i;
  112360. }
  112361. }
  112362. e+=dim;
  112363. }
  112364. }
  112365. {
  112366. float *ptr=book->valuelist+best*dim;
  112367. for(i=0;i<dim;i++)
  112368. *a++ -= *ptr++;
  112369. }
  112370. return(best);
  112371. }
  112372. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  112373. codebook *book,long *acc){
  112374. int i,bits=0;
  112375. int dim=book->dim;
  112376. int step=n/dim;
  112377. for(i=0;i<step;i++){
  112378. int entry=local_book_besterror(book,vec+i*dim);
  112379. #ifdef TRAIN_RES
  112380. acc[entry]++;
  112381. #endif
  112382. bits+=vorbis_book_encode(book,entry,opb);
  112383. }
  112384. return(bits);
  112385. }
  112386. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  112387. float **in,int ch){
  112388. long i,j,k;
  112389. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  112390. vorbis_info_residue0 *info=look->info;
  112391. /* move all this setup out later */
  112392. int samples_per_partition=info->grouping;
  112393. int possible_partitions=info->partitions;
  112394. int n=info->end-info->begin;
  112395. int partvals=n/samples_per_partition;
  112396. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  112397. float scale=100./samples_per_partition;
  112398. /* we find the partition type for each partition of each
  112399. channel. We'll go back and do the interleaved encoding in a
  112400. bit. For now, clarity */
  112401. for(i=0;i<ch;i++){
  112402. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  112403. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  112404. }
  112405. for(i=0;i<partvals;i++){
  112406. int offset=i*samples_per_partition+info->begin;
  112407. for(j=0;j<ch;j++){
  112408. float max=0.;
  112409. float ent=0.;
  112410. for(k=0;k<samples_per_partition;k++){
  112411. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  112412. ent+=fabs(rint(in[j][offset+k]));
  112413. }
  112414. ent*=scale;
  112415. for(k=0;k<possible_partitions-1;k++)
  112416. if(max<=info->classmetric1[k] &&
  112417. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  112418. break;
  112419. partword[j][i]=k;
  112420. }
  112421. }
  112422. #ifdef TRAIN_RESAUX
  112423. {
  112424. FILE *of;
  112425. char buffer[80];
  112426. for(i=0;i<ch;i++){
  112427. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  112428. of=fopen(buffer,"a");
  112429. for(j=0;j<partvals;j++)
  112430. fprintf(of,"%ld, ",partword[i][j]);
  112431. fprintf(of,"\n");
  112432. fclose(of);
  112433. }
  112434. }
  112435. #endif
  112436. look->frames++;
  112437. return(partword);
  112438. }
  112439. /* designed for stereo or other modes where the partition size is an
  112440. integer multiple of the number of channels encoded in the current
  112441. submap */
  112442. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  112443. int ch){
  112444. long i,j,k,l;
  112445. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  112446. vorbis_info_residue0 *info=look->info;
  112447. /* move all this setup out later */
  112448. int samples_per_partition=info->grouping;
  112449. int possible_partitions=info->partitions;
  112450. int n=info->end-info->begin;
  112451. int partvals=n/samples_per_partition;
  112452. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  112453. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  112454. FILE *of;
  112455. char buffer[80];
  112456. #endif
  112457. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  112458. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  112459. for(i=0,l=info->begin/ch;i<partvals;i++){
  112460. float magmax=0.f;
  112461. float angmax=0.f;
  112462. for(j=0;j<samples_per_partition;j+=ch){
  112463. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  112464. for(k=1;k<ch;k++)
  112465. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  112466. l++;
  112467. }
  112468. for(j=0;j<possible_partitions-1;j++)
  112469. if(magmax<=info->classmetric1[j] &&
  112470. angmax<=info->classmetric2[j])
  112471. break;
  112472. partword[0][i]=j;
  112473. }
  112474. #ifdef TRAIN_RESAUX
  112475. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  112476. of=fopen(buffer,"a");
  112477. for(i=0;i<partvals;i++)
  112478. fprintf(of,"%ld, ",partword[0][i]);
  112479. fprintf(of,"\n");
  112480. fclose(of);
  112481. #endif
  112482. look->frames++;
  112483. return(partword);
  112484. }
  112485. static int _01forward(oggpack_buffer *opb,
  112486. vorbis_block *vb,vorbis_look_residue *vl,
  112487. float **in,int ch,
  112488. long **partword,
  112489. int (*encode)(oggpack_buffer *,float *,int,
  112490. codebook *,long *)){
  112491. long i,j,k,s;
  112492. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  112493. vorbis_info_residue0 *info=look->info;
  112494. /* move all this setup out later */
  112495. int samples_per_partition=info->grouping;
  112496. int possible_partitions=info->partitions;
  112497. int partitions_per_word=look->phrasebook->dim;
  112498. int n=info->end-info->begin;
  112499. int partvals=n/samples_per_partition;
  112500. long resbits[128];
  112501. long resvals[128];
  112502. #ifdef TRAIN_RES
  112503. for(i=0;i<ch;i++)
  112504. for(j=info->begin;j<info->end;j++){
  112505. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  112506. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  112507. }
  112508. #endif
  112509. memset(resbits,0,sizeof(resbits));
  112510. memset(resvals,0,sizeof(resvals));
  112511. /* we code the partition words for each channel, then the residual
  112512. words for a partition per channel until we've written all the
  112513. residual words for that partition word. Then write the next
  112514. partition channel words... */
  112515. for(s=0;s<look->stages;s++){
  112516. for(i=0;i<partvals;){
  112517. /* first we encode a partition codeword for each channel */
  112518. if(s==0){
  112519. for(j=0;j<ch;j++){
  112520. long val=partword[j][i];
  112521. for(k=1;k<partitions_per_word;k++){
  112522. val*=possible_partitions;
  112523. if(i+k<partvals)
  112524. val+=partword[j][i+k];
  112525. }
  112526. /* training hack */
  112527. if(val<look->phrasebook->entries)
  112528. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  112529. #if 0 /*def TRAIN_RES*/
  112530. else
  112531. fprintf(stderr,"!");
  112532. #endif
  112533. }
  112534. }
  112535. /* now we encode interleaved residual values for the partitions */
  112536. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  112537. long offset=i*samples_per_partition+info->begin;
  112538. for(j=0;j<ch;j++){
  112539. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  112540. if(info->secondstages[partword[j][i]]&(1<<s)){
  112541. codebook *statebook=look->partbooks[partword[j][i]][s];
  112542. if(statebook){
  112543. int ret;
  112544. long *accumulator=NULL;
  112545. #ifdef TRAIN_RES
  112546. accumulator=look->training_data[s][partword[j][i]];
  112547. {
  112548. int l;
  112549. float *samples=in[j]+offset;
  112550. for(l=0;l<samples_per_partition;l++){
  112551. if(samples[l]<look->training_min[s][partword[j][i]])
  112552. look->training_min[s][partword[j][i]]=samples[l];
  112553. if(samples[l]>look->training_max[s][partword[j][i]])
  112554. look->training_max[s][partword[j][i]]=samples[l];
  112555. }
  112556. }
  112557. #endif
  112558. ret=encode(opb,in[j]+offset,samples_per_partition,
  112559. statebook,accumulator);
  112560. look->postbits+=ret;
  112561. resbits[partword[j][i]]+=ret;
  112562. }
  112563. }
  112564. }
  112565. }
  112566. }
  112567. }
  112568. /*{
  112569. long total=0;
  112570. long totalbits=0;
  112571. fprintf(stderr,"%d :: ",vb->mode);
  112572. for(k=0;k<possible_partitions;k++){
  112573. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  112574. total+=resvals[k];
  112575. totalbits+=resbits[k];
  112576. }
  112577. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  112578. }*/
  112579. return(0);
  112580. }
  112581. /* a truncated packet here just means 'stop working'; it's not an error */
  112582. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  112583. float **in,int ch,
  112584. long (*decodepart)(codebook *, float *,
  112585. oggpack_buffer *,int)){
  112586. long i,j,k,l,s;
  112587. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  112588. vorbis_info_residue0 *info=look->info;
  112589. /* move all this setup out later */
  112590. int samples_per_partition=info->grouping;
  112591. int partitions_per_word=look->phrasebook->dim;
  112592. int n=info->end-info->begin;
  112593. int partvals=n/samples_per_partition;
  112594. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  112595. int ***partword=(int***)alloca(ch*sizeof(*partword));
  112596. for(j=0;j<ch;j++)
  112597. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  112598. for(s=0;s<look->stages;s++){
  112599. /* each loop decodes on partition codeword containing
  112600. partitions_pre_word partitions */
  112601. for(i=0,l=0;i<partvals;l++){
  112602. if(s==0){
  112603. /* fetch the partition word for each channel */
  112604. for(j=0;j<ch;j++){
  112605. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  112606. if(temp==-1)goto eopbreak;
  112607. partword[j][l]=look->decodemap[temp];
  112608. if(partword[j][l]==NULL)goto errout;
  112609. }
  112610. }
  112611. /* now we decode residual values for the partitions */
  112612. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  112613. for(j=0;j<ch;j++){
  112614. long offset=info->begin+i*samples_per_partition;
  112615. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  112616. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  112617. if(stagebook){
  112618. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  112619. samples_per_partition)==-1)goto eopbreak;
  112620. }
  112621. }
  112622. }
  112623. }
  112624. }
  112625. errout:
  112626. eopbreak:
  112627. return(0);
  112628. }
  112629. #if 0
  112630. /* residue 0 and 1 are just slight variants of one another. 0 is
  112631. interleaved, 1 is not */
  112632. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  112633. float **in,int *nonzero,int ch){
  112634. /* we encode only the nonzero parts of a bundle */
  112635. int i,used=0;
  112636. for(i=0;i<ch;i++)
  112637. if(nonzero[i])
  112638. in[used++]=in[i];
  112639. if(used)
  112640. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  112641. return(_01class(vb,vl,in,used));
  112642. else
  112643. return(0);
  112644. }
  112645. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  112646. float **in,float **out,int *nonzero,int ch,
  112647. long **partword){
  112648. /* we encode only the nonzero parts of a bundle */
  112649. int i,j,used=0,n=vb->pcmend/2;
  112650. for(i=0;i<ch;i++)
  112651. if(nonzero[i]){
  112652. if(out)
  112653. for(j=0;j<n;j++)
  112654. out[i][j]+=in[i][j];
  112655. in[used++]=in[i];
  112656. }
  112657. if(used){
  112658. int ret=_01forward(vb,vl,in,used,partword,
  112659. _interleaved_encodepart);
  112660. if(out){
  112661. used=0;
  112662. for(i=0;i<ch;i++)
  112663. if(nonzero[i]){
  112664. for(j=0;j<n;j++)
  112665. out[i][j]-=in[used][j];
  112666. used++;
  112667. }
  112668. }
  112669. return(ret);
  112670. }else{
  112671. return(0);
  112672. }
  112673. }
  112674. #endif
  112675. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  112676. float **in,int *nonzero,int ch){
  112677. int i,used=0;
  112678. for(i=0;i<ch;i++)
  112679. if(nonzero[i])
  112680. in[used++]=in[i];
  112681. if(used)
  112682. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  112683. else
  112684. return(0);
  112685. }
  112686. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  112687. float **in,float **out,int *nonzero,int ch,
  112688. long **partword){
  112689. int i,j,used=0,n=vb->pcmend/2;
  112690. for(i=0;i<ch;i++)
  112691. if(nonzero[i]){
  112692. if(out)
  112693. for(j=0;j<n;j++)
  112694. out[i][j]+=in[i][j];
  112695. in[used++]=in[i];
  112696. }
  112697. if(used){
  112698. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  112699. if(out){
  112700. used=0;
  112701. for(i=0;i<ch;i++)
  112702. if(nonzero[i]){
  112703. for(j=0;j<n;j++)
  112704. out[i][j]-=in[used][j];
  112705. used++;
  112706. }
  112707. }
  112708. return(ret);
  112709. }else{
  112710. return(0);
  112711. }
  112712. }
  112713. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  112714. float **in,int *nonzero,int ch){
  112715. int i,used=0;
  112716. for(i=0;i<ch;i++)
  112717. if(nonzero[i])
  112718. in[used++]=in[i];
  112719. if(used)
  112720. return(_01class(vb,vl,in,used));
  112721. else
  112722. return(0);
  112723. }
  112724. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  112725. float **in,int *nonzero,int ch){
  112726. int i,used=0;
  112727. for(i=0;i<ch;i++)
  112728. if(nonzero[i])
  112729. in[used++]=in[i];
  112730. if(used)
  112731. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  112732. else
  112733. return(0);
  112734. }
  112735. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  112736. float **in,int *nonzero,int ch){
  112737. int i,used=0;
  112738. for(i=0;i<ch;i++)
  112739. if(nonzero[i])used++;
  112740. if(used)
  112741. return(_2class(vb,vl,in,ch));
  112742. else
  112743. return(0);
  112744. }
  112745. /* res2 is slightly more different; all the channels are interleaved
  112746. into a single vector and encoded. */
  112747. int res2_forward(oggpack_buffer *opb,
  112748. vorbis_block *vb,vorbis_look_residue *vl,
  112749. float **in,float **out,int *nonzero,int ch,
  112750. long **partword){
  112751. long i,j,k,n=vb->pcmend/2,used=0;
  112752. /* don't duplicate the code; use a working vector hack for now and
  112753. reshape ourselves into a single channel res1 */
  112754. /* ugly; reallocs for each coupling pass :-( */
  112755. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  112756. for(i=0;i<ch;i++){
  112757. float *pcm=in[i];
  112758. if(nonzero[i])used++;
  112759. for(j=0,k=i;j<n;j++,k+=ch)
  112760. work[k]=pcm[j];
  112761. }
  112762. if(used){
  112763. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  112764. /* update the sofar vector */
  112765. if(out){
  112766. for(i=0;i<ch;i++){
  112767. float *pcm=in[i];
  112768. float *sofar=out[i];
  112769. for(j=0,k=i;j<n;j++,k+=ch)
  112770. sofar[j]+=pcm[j]-work[k];
  112771. }
  112772. }
  112773. return(ret);
  112774. }else{
  112775. return(0);
  112776. }
  112777. }
  112778. /* duplicate code here as speed is somewhat more important */
  112779. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  112780. float **in,int *nonzero,int ch){
  112781. long i,k,l,s;
  112782. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  112783. vorbis_info_residue0 *info=look->info;
  112784. /* move all this setup out later */
  112785. int samples_per_partition=info->grouping;
  112786. int partitions_per_word=look->phrasebook->dim;
  112787. int n=info->end-info->begin;
  112788. int partvals=n/samples_per_partition;
  112789. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  112790. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  112791. for(i=0;i<ch;i++)if(nonzero[i])break;
  112792. if(i==ch)return(0); /* no nonzero vectors */
  112793. for(s=0;s<look->stages;s++){
  112794. for(i=0,l=0;i<partvals;l++){
  112795. if(s==0){
  112796. /* fetch the partition word */
  112797. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  112798. if(temp==-1)goto eopbreak;
  112799. partword[l]=look->decodemap[temp];
  112800. if(partword[l]==NULL)goto errout;
  112801. }
  112802. /* now we decode residual values for the partitions */
  112803. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  112804. if(info->secondstages[partword[l][k]]&(1<<s)){
  112805. codebook *stagebook=look->partbooks[partword[l][k]][s];
  112806. if(stagebook){
  112807. if(vorbis_book_decodevv_add(stagebook,in,
  112808. i*samples_per_partition+info->begin,ch,
  112809. &vb->opb,samples_per_partition)==-1)
  112810. goto eopbreak;
  112811. }
  112812. }
  112813. }
  112814. }
  112815. errout:
  112816. eopbreak:
  112817. return(0);
  112818. }
  112819. vorbis_func_residue residue0_exportbundle={
  112820. NULL,
  112821. &res0_unpack,
  112822. &res0_look,
  112823. &res0_free_info,
  112824. &res0_free_look,
  112825. NULL,
  112826. NULL,
  112827. &res0_inverse
  112828. };
  112829. vorbis_func_residue residue1_exportbundle={
  112830. &res0_pack,
  112831. &res0_unpack,
  112832. &res0_look,
  112833. &res0_free_info,
  112834. &res0_free_look,
  112835. &res1_class,
  112836. &res1_forward,
  112837. &res1_inverse
  112838. };
  112839. vorbis_func_residue residue2_exportbundle={
  112840. &res0_pack,
  112841. &res0_unpack,
  112842. &res0_look,
  112843. &res0_free_info,
  112844. &res0_free_look,
  112845. &res2_class,
  112846. &res2_forward,
  112847. &res2_inverse
  112848. };
  112849. #endif
  112850. /********* End of inlined file: res0.c *********/
  112851. /********* Start of inlined file: sharedbook.c *********/
  112852. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112853. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112854. // tasks..
  112855. #ifdef _MSC_VER
  112856. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112857. #endif
  112858. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112859. #if JUCE_USE_OGGVORBIS
  112860. #include <stdlib.h>
  112861. #include <math.h>
  112862. #include <string.h>
  112863. /**** pack/unpack helpers ******************************************/
  112864. int _ilog(unsigned int v){
  112865. int ret=0;
  112866. while(v){
  112867. ret++;
  112868. v>>=1;
  112869. }
  112870. return(ret);
  112871. }
  112872. /* 32 bit float (not IEEE; nonnormalized mantissa +
  112873. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  112874. Why not IEEE? It's just not that important here. */
  112875. #define VQ_FEXP 10
  112876. #define VQ_FMAN 21
  112877. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  112878. /* doesn't currently guard under/overflow */
  112879. long _float32_pack(float val){
  112880. int sign=0;
  112881. long exp;
  112882. long mant;
  112883. if(val<0){
  112884. sign=0x80000000;
  112885. val= -val;
  112886. }
  112887. exp= floor(log(val)/log(2.f));
  112888. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  112889. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  112890. return(sign|exp|mant);
  112891. }
  112892. float _float32_unpack(long val){
  112893. double mant=val&0x1fffff;
  112894. int sign=val&0x80000000;
  112895. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  112896. if(sign)mant= -mant;
  112897. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  112898. }
  112899. /* given a list of word lengths, generate a list of codewords. Works
  112900. for length ordered or unordered, always assigns the lowest valued
  112901. codewords first. Extended to handle unused entries (length 0) */
  112902. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  112903. long i,j,count=0;
  112904. ogg_uint32_t marker[33];
  112905. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  112906. memset(marker,0,sizeof(marker));
  112907. for(i=0;i<n;i++){
  112908. long length=l[i];
  112909. if(length>0){
  112910. ogg_uint32_t entry=marker[length];
  112911. /* when we claim a node for an entry, we also claim the nodes
  112912. below it (pruning off the imagined tree that may have dangled
  112913. from it) as well as blocking the use of any nodes directly
  112914. above for leaves */
  112915. /* update ourself */
  112916. if(length<32 && (entry>>length)){
  112917. /* error condition; the lengths must specify an overpopulated tree */
  112918. _ogg_free(r);
  112919. return(NULL);
  112920. }
  112921. r[count++]=entry;
  112922. /* Look to see if the next shorter marker points to the node
  112923. above. if so, update it and repeat. */
  112924. {
  112925. for(j=length;j>0;j--){
  112926. if(marker[j]&1){
  112927. /* have to jump branches */
  112928. if(j==1)
  112929. marker[1]++;
  112930. else
  112931. marker[j]=marker[j-1]<<1;
  112932. break; /* invariant says next upper marker would already
  112933. have been moved if it was on the same path */
  112934. }
  112935. marker[j]++;
  112936. }
  112937. }
  112938. /* prune the tree; the implicit invariant says all the longer
  112939. markers were dangling from our just-taken node. Dangle them
  112940. from our *new* node. */
  112941. for(j=length+1;j<33;j++)
  112942. if((marker[j]>>1) == entry){
  112943. entry=marker[j];
  112944. marker[j]=marker[j-1]<<1;
  112945. }else
  112946. break;
  112947. }else
  112948. if(sparsecount==0)count++;
  112949. }
  112950. /* bitreverse the words because our bitwise packer/unpacker is LSb
  112951. endian */
  112952. for(i=0,count=0;i<n;i++){
  112953. ogg_uint32_t temp=0;
  112954. for(j=0;j<l[i];j++){
  112955. temp<<=1;
  112956. temp|=(r[count]>>j)&1;
  112957. }
  112958. if(sparsecount){
  112959. if(l[i])
  112960. r[count++]=temp;
  112961. }else
  112962. r[count++]=temp;
  112963. }
  112964. return(r);
  112965. }
  112966. /* there might be a straightforward one-line way to do the below
  112967. that's portable and totally safe against roundoff, but I haven't
  112968. thought of it. Therefore, we opt on the side of caution */
  112969. long _book_maptype1_quantvals(const static_codebook *b){
  112970. long vals=floor(pow((float)b->entries,1.f/b->dim));
  112971. /* the above *should* be reliable, but we'll not assume that FP is
  112972. ever reliable when bitstream sync is at stake; verify via integer
  112973. means that vals really is the greatest value of dim for which
  112974. vals^b->bim <= b->entries */
  112975. /* treat the above as an initial guess */
  112976. while(1){
  112977. long acc=1;
  112978. long acc1=1;
  112979. int i;
  112980. for(i=0;i<b->dim;i++){
  112981. acc*=vals;
  112982. acc1*=vals+1;
  112983. }
  112984. if(acc<=b->entries && acc1>b->entries){
  112985. return(vals);
  112986. }else{
  112987. if(acc>b->entries){
  112988. vals--;
  112989. }else{
  112990. vals++;
  112991. }
  112992. }
  112993. }
  112994. }
  112995. /* unpack the quantized list of values for encode/decode ***********/
  112996. /* we need to deal with two map types: in map type 1, the values are
  112997. generated algorithmically (each column of the vector counts through
  112998. the values in the quant vector). in map type 2, all the values came
  112999. in in an explicit list. Both value lists must be unpacked */
  113000. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  113001. long j,k,count=0;
  113002. if(b->maptype==1 || b->maptype==2){
  113003. int quantvals;
  113004. float mindel=_float32_unpack(b->q_min);
  113005. float delta=_float32_unpack(b->q_delta);
  113006. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  113007. /* maptype 1 and 2 both use a quantized value vector, but
  113008. different sizes */
  113009. switch(b->maptype){
  113010. case 1:
  113011. /* most of the time, entries%dimensions == 0, but we need to be
  113012. well defined. We define that the possible vales at each
  113013. scalar is values == entries/dim. If entries%dim != 0, we'll
  113014. have 'too few' values (values*dim<entries), which means that
  113015. we'll have 'left over' entries; left over entries use zeroed
  113016. values (and are wasted). So don't generate codebooks like
  113017. that */
  113018. quantvals=_book_maptype1_quantvals(b);
  113019. for(j=0;j<b->entries;j++){
  113020. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  113021. float last=0.f;
  113022. int indexdiv=1;
  113023. for(k=0;k<b->dim;k++){
  113024. int index= (j/indexdiv)%quantvals;
  113025. float val=b->quantlist[index];
  113026. val=fabs(val)*delta+mindel+last;
  113027. if(b->q_sequencep)last=val;
  113028. if(sparsemap)
  113029. r[sparsemap[count]*b->dim+k]=val;
  113030. else
  113031. r[count*b->dim+k]=val;
  113032. indexdiv*=quantvals;
  113033. }
  113034. count++;
  113035. }
  113036. }
  113037. break;
  113038. case 2:
  113039. for(j=0;j<b->entries;j++){
  113040. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  113041. float last=0.f;
  113042. for(k=0;k<b->dim;k++){
  113043. float val=b->quantlist[j*b->dim+k];
  113044. val=fabs(val)*delta+mindel+last;
  113045. if(b->q_sequencep)last=val;
  113046. if(sparsemap)
  113047. r[sparsemap[count]*b->dim+k]=val;
  113048. else
  113049. r[count*b->dim+k]=val;
  113050. }
  113051. count++;
  113052. }
  113053. }
  113054. break;
  113055. }
  113056. return(r);
  113057. }
  113058. return(NULL);
  113059. }
  113060. void vorbis_staticbook_clear(static_codebook *b){
  113061. if(b->allocedp){
  113062. if(b->quantlist)_ogg_free(b->quantlist);
  113063. if(b->lengthlist)_ogg_free(b->lengthlist);
  113064. if(b->nearest_tree){
  113065. _ogg_free(b->nearest_tree->ptr0);
  113066. _ogg_free(b->nearest_tree->ptr1);
  113067. _ogg_free(b->nearest_tree->p);
  113068. _ogg_free(b->nearest_tree->q);
  113069. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  113070. _ogg_free(b->nearest_tree);
  113071. }
  113072. if(b->thresh_tree){
  113073. _ogg_free(b->thresh_tree->quantthresh);
  113074. _ogg_free(b->thresh_tree->quantmap);
  113075. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  113076. _ogg_free(b->thresh_tree);
  113077. }
  113078. memset(b,0,sizeof(*b));
  113079. }
  113080. }
  113081. void vorbis_staticbook_destroy(static_codebook *b){
  113082. if(b->allocedp){
  113083. vorbis_staticbook_clear(b);
  113084. _ogg_free(b);
  113085. }
  113086. }
  113087. void vorbis_book_clear(codebook *b){
  113088. /* static book is not cleared; we're likely called on the lookup and
  113089. the static codebook belongs to the info struct */
  113090. if(b->valuelist)_ogg_free(b->valuelist);
  113091. if(b->codelist)_ogg_free(b->codelist);
  113092. if(b->dec_index)_ogg_free(b->dec_index);
  113093. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  113094. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  113095. memset(b,0,sizeof(*b));
  113096. }
  113097. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  113098. memset(c,0,sizeof(*c));
  113099. c->c=s;
  113100. c->entries=s->entries;
  113101. c->used_entries=s->entries;
  113102. c->dim=s->dim;
  113103. c->codelist=_make_words(s->lengthlist,s->entries,0);
  113104. c->valuelist=_book_unquantize(s,s->entries,NULL);
  113105. return(0);
  113106. }
  113107. static int sort32a(const void *a,const void *b){
  113108. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  113109. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  113110. }
  113111. /* decode codebook arrangement is more heavily optimized than encode */
  113112. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  113113. int i,j,n=0,tabn;
  113114. int *sortindex;
  113115. memset(c,0,sizeof(*c));
  113116. /* count actually used entries */
  113117. for(i=0;i<s->entries;i++)
  113118. if(s->lengthlist[i]>0)
  113119. n++;
  113120. c->entries=s->entries;
  113121. c->used_entries=n;
  113122. c->dim=s->dim;
  113123. /* two different remappings go on here.
  113124. First, we collapse the likely sparse codebook down only to
  113125. actually represented values/words. This collapsing needs to be
  113126. indexed as map-valueless books are used to encode original entry
  113127. positions as integers.
  113128. Second, we reorder all vectors, including the entry index above,
  113129. by sorted bitreversed codeword to allow treeless decode. */
  113130. {
  113131. /* perform sort */
  113132. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  113133. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  113134. if(codes==NULL)goto err_out;
  113135. for(i=0;i<n;i++){
  113136. codes[i]=bitreverse(codes[i]);
  113137. codep[i]=codes+i;
  113138. }
  113139. qsort(codep,n,sizeof(*codep),sort32a);
  113140. sortindex=(int*)alloca(n*sizeof(*sortindex));
  113141. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  113142. /* the index is a reverse index */
  113143. for(i=0;i<n;i++){
  113144. int position=codep[i]-codes;
  113145. sortindex[position]=i;
  113146. }
  113147. for(i=0;i<n;i++)
  113148. c->codelist[sortindex[i]]=codes[i];
  113149. _ogg_free(codes);
  113150. }
  113151. c->valuelist=_book_unquantize(s,n,sortindex);
  113152. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  113153. for(n=0,i=0;i<s->entries;i++)
  113154. if(s->lengthlist[i]>0)
  113155. c->dec_index[sortindex[n++]]=i;
  113156. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  113157. for(n=0,i=0;i<s->entries;i++)
  113158. if(s->lengthlist[i]>0)
  113159. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  113160. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  113161. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  113162. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  113163. tabn=1<<c->dec_firsttablen;
  113164. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  113165. c->dec_maxlength=0;
  113166. for(i=0;i<n;i++){
  113167. if(c->dec_maxlength<c->dec_codelengths[i])
  113168. c->dec_maxlength=c->dec_codelengths[i];
  113169. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  113170. ogg_uint32_t orig=bitreverse(c->codelist[i]);
  113171. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  113172. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  113173. }
  113174. }
  113175. /* now fill in 'unused' entries in the firsttable with hi/lo search
  113176. hints for the non-direct-hits */
  113177. {
  113178. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  113179. long lo=0,hi=0;
  113180. for(i=0;i<tabn;i++){
  113181. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  113182. if(c->dec_firsttable[bitreverse(word)]==0){
  113183. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  113184. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  113185. /* we only actually have 15 bits per hint to play with here.
  113186. In order to overflow gracefully (nothing breaks, efficiency
  113187. just drops), encode as the difference from the extremes. */
  113188. {
  113189. unsigned long loval=lo;
  113190. unsigned long hival=n-hi;
  113191. if(loval>0x7fff)loval=0x7fff;
  113192. if(hival>0x7fff)hival=0x7fff;
  113193. c->dec_firsttable[bitreverse(word)]=
  113194. 0x80000000UL | (loval<<15) | hival;
  113195. }
  113196. }
  113197. }
  113198. }
  113199. return(0);
  113200. err_out:
  113201. vorbis_book_clear(c);
  113202. return(-1);
  113203. }
  113204. static float _dist(int el,float *ref, float *b,int step){
  113205. int i;
  113206. float acc=0.f;
  113207. for(i=0;i<el;i++){
  113208. float val=(ref[i]-b[i*step]);
  113209. acc+=val*val;
  113210. }
  113211. return(acc);
  113212. }
  113213. int _best(codebook *book, float *a, int step){
  113214. encode_aux_threshmatch *tt=book->c->thresh_tree;
  113215. #if 0
  113216. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  113217. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  113218. #endif
  113219. int dim=book->dim;
  113220. int k,o;
  113221. /*int savebest=-1;
  113222. float saverr;*/
  113223. /* do we have a threshhold encode hint? */
  113224. if(tt){
  113225. int index=0,i;
  113226. /* find the quant val of each scalar */
  113227. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  113228. i=tt->threshvals>>1;
  113229. if(a[o]<tt->quantthresh[i]){
  113230. for(;i>0;i--)
  113231. if(a[o]>=tt->quantthresh[i-1])
  113232. break;
  113233. }else{
  113234. for(i++;i<tt->threshvals-1;i++)
  113235. if(a[o]<tt->quantthresh[i])break;
  113236. }
  113237. index=(index*tt->quantvals)+tt->quantmap[i];
  113238. }
  113239. /* regular lattices are easy :-) */
  113240. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  113241. use a decision tree after all
  113242. and fall through*/
  113243. return(index);
  113244. }
  113245. #if 0
  113246. /* do we have a pigeonhole encode hint? */
  113247. if(pt){
  113248. const static_codebook *c=book->c;
  113249. int i,besti=-1;
  113250. float best=0.f;
  113251. int entry=0;
  113252. /* dealing with sequentialness is a pain in the ass */
  113253. if(c->q_sequencep){
  113254. int pv;
  113255. long mul=1;
  113256. float qlast=0;
  113257. for(k=0,o=0;k<dim;k++,o+=step){
  113258. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  113259. if(pv<0 || pv>=pt->mapentries)break;
  113260. entry+=pt->pigeonmap[pv]*mul;
  113261. mul*=pt->quantvals;
  113262. qlast+=pv*pt->del+pt->min;
  113263. }
  113264. }else{
  113265. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  113266. int pv=(int)((a[o]-pt->min)/pt->del);
  113267. if(pv<0 || pv>=pt->mapentries)break;
  113268. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  113269. }
  113270. }
  113271. /* must be within the pigeonholable range; if we quant outside (or
  113272. in an entry that we define no list for), brute force it */
  113273. if(k==dim && pt->fitlength[entry]){
  113274. /* search the abbreviated list */
  113275. long *list=pt->fitlist+pt->fitmap[entry];
  113276. for(i=0;i<pt->fitlength[entry];i++){
  113277. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  113278. if(besti==-1 || this<best){
  113279. best=this;
  113280. besti=list[i];
  113281. }
  113282. }
  113283. return(besti);
  113284. }
  113285. }
  113286. if(nt){
  113287. /* optimized using the decision tree */
  113288. while(1){
  113289. float c=0.f;
  113290. float *p=book->valuelist+nt->p[ptr];
  113291. float *q=book->valuelist+nt->q[ptr];
  113292. for(k=0,o=0;k<dim;k++,o+=step)
  113293. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  113294. if(c>0.f) /* in A */
  113295. ptr= -nt->ptr0[ptr];
  113296. else /* in B */
  113297. ptr= -nt->ptr1[ptr];
  113298. if(ptr<=0)break;
  113299. }
  113300. return(-ptr);
  113301. }
  113302. #endif
  113303. /* brute force it! */
  113304. {
  113305. const static_codebook *c=book->c;
  113306. int i,besti=-1;
  113307. float best=0.f;
  113308. float *e=book->valuelist;
  113309. for(i=0;i<book->entries;i++){
  113310. if(c->lengthlist[i]>0){
  113311. float thisx=_dist(dim,e,a,step);
  113312. if(besti==-1 || thisx<best){
  113313. best=thisx;
  113314. besti=i;
  113315. }
  113316. }
  113317. e+=dim;
  113318. }
  113319. /*if(savebest!=-1 && savebest!=besti){
  113320. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  113321. "original:");
  113322. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  113323. fprintf(stderr,"\n"
  113324. "pigeonhole (entry %d, err %g):",savebest,saverr);
  113325. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  113326. (book->valuelist+savebest*dim)[i]);
  113327. fprintf(stderr,"\n"
  113328. "bruteforce (entry %d, err %g):",besti,best);
  113329. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  113330. (book->valuelist+besti*dim)[i]);
  113331. fprintf(stderr,"\n");
  113332. }*/
  113333. return(besti);
  113334. }
  113335. }
  113336. long vorbis_book_codeword(codebook *book,int entry){
  113337. if(book->c) /* only use with encode; decode optimizations are
  113338. allowed to break this */
  113339. return book->codelist[entry];
  113340. return -1;
  113341. }
  113342. long vorbis_book_codelen(codebook *book,int entry){
  113343. if(book->c) /* only use with encode; decode optimizations are
  113344. allowed to break this */
  113345. return book->c->lengthlist[entry];
  113346. return -1;
  113347. }
  113348. #ifdef _V_SELFTEST
  113349. /* Unit tests of the dequantizer; this stuff will be OK
  113350. cross-platform, I simply want to be sure that special mapping cases
  113351. actually work properly; a bug could go unnoticed for a while */
  113352. #include <stdio.h>
  113353. /* cases:
  113354. no mapping
  113355. full, explicit mapping
  113356. algorithmic mapping
  113357. nonsequential
  113358. sequential
  113359. */
  113360. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  113361. static long partial_quantlist1[]={0,7,2};
  113362. /* no mapping */
  113363. static_codebook test1={
  113364. 4,16,
  113365. NULL,
  113366. 0,
  113367. 0,0,0,0,
  113368. NULL,
  113369. NULL,NULL
  113370. };
  113371. static float *test1_result=NULL;
  113372. /* linear, full mapping, nonsequential */
  113373. static_codebook test2={
  113374. 4,3,
  113375. NULL,
  113376. 2,
  113377. -533200896,1611661312,4,0,
  113378. full_quantlist1,
  113379. NULL,NULL
  113380. };
  113381. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  113382. /* linear, full mapping, sequential */
  113383. static_codebook test3={
  113384. 4,3,
  113385. NULL,
  113386. 2,
  113387. -533200896,1611661312,4,1,
  113388. full_quantlist1,
  113389. NULL,NULL
  113390. };
  113391. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  113392. /* linear, algorithmic mapping, nonsequential */
  113393. static_codebook test4={
  113394. 3,27,
  113395. NULL,
  113396. 1,
  113397. -533200896,1611661312,4,0,
  113398. partial_quantlist1,
  113399. NULL,NULL
  113400. };
  113401. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  113402. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  113403. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  113404. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  113405. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  113406. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  113407. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  113408. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  113409. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  113410. /* linear, algorithmic mapping, sequential */
  113411. static_codebook test5={
  113412. 3,27,
  113413. NULL,
  113414. 1,
  113415. -533200896,1611661312,4,1,
  113416. partial_quantlist1,
  113417. NULL,NULL
  113418. };
  113419. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  113420. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  113421. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  113422. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  113423. -3, 1, 5, 4, 8,12, -1, 3, 7,
  113424. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  113425. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  113426. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  113427. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  113428. void run_test(static_codebook *b,float *comp){
  113429. float *out=_book_unquantize(b,b->entries,NULL);
  113430. int i;
  113431. if(comp){
  113432. if(!out){
  113433. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  113434. exit(1);
  113435. }
  113436. for(i=0;i<b->entries*b->dim;i++)
  113437. if(fabs(out[i]-comp[i])>.0001){
  113438. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  113439. "position %d, %g != %g\n",i,out[i],comp[i]);
  113440. exit(1);
  113441. }
  113442. }else{
  113443. if(out){
  113444. fprintf(stderr,"_book_unquantize returned a value array: \n"
  113445. " correct result should have been NULL\n");
  113446. exit(1);
  113447. }
  113448. }
  113449. }
  113450. int main(){
  113451. /* run the nine dequant tests, and compare to the hand-rolled results */
  113452. fprintf(stderr,"Dequant test 1... ");
  113453. run_test(&test1,test1_result);
  113454. fprintf(stderr,"OK\nDequant test 2... ");
  113455. run_test(&test2,test2_result);
  113456. fprintf(stderr,"OK\nDequant test 3... ");
  113457. run_test(&test3,test3_result);
  113458. fprintf(stderr,"OK\nDequant test 4... ");
  113459. run_test(&test4,test4_result);
  113460. fprintf(stderr,"OK\nDequant test 5... ");
  113461. run_test(&test5,test5_result);
  113462. fprintf(stderr,"OK\n\n");
  113463. return(0);
  113464. }
  113465. #endif
  113466. #endif
  113467. /********* End of inlined file: sharedbook.c *********/
  113468. /********* Start of inlined file: smallft.c *********/
  113469. /* FFT implementation from OggSquish, minus cosine transforms,
  113470. * minus all but radix 2/4 case. In Vorbis we only need this
  113471. * cut-down version.
  113472. *
  113473. * To do more than just power-of-two sized vectors, see the full
  113474. * version I wrote for NetLib.
  113475. *
  113476. * Note that the packing is a little strange; rather than the FFT r/i
  113477. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  113478. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  113479. * FORTRAN version
  113480. */
  113481. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113482. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113483. // tasks..
  113484. #ifdef _MSC_VER
  113485. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113486. #endif
  113487. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113488. #if JUCE_USE_OGGVORBIS
  113489. #include <stdlib.h>
  113490. #include <string.h>
  113491. #include <math.h>
  113492. static void drfti1(int n, float *wa, int *ifac){
  113493. static int ntryh[4] = { 4,2,3,5 };
  113494. static float tpi = 6.28318530717958648f;
  113495. float arg,argh,argld,fi;
  113496. int ntry=0,i,j=-1;
  113497. int k1, l1, l2, ib;
  113498. int ld, ii, ip, is, nq, nr;
  113499. int ido, ipm, nfm1;
  113500. int nl=n;
  113501. int nf=0;
  113502. L101:
  113503. j++;
  113504. if (j < 4)
  113505. ntry=ntryh[j];
  113506. else
  113507. ntry+=2;
  113508. L104:
  113509. nq=nl/ntry;
  113510. nr=nl-ntry*nq;
  113511. if (nr!=0) goto L101;
  113512. nf++;
  113513. ifac[nf+1]=ntry;
  113514. nl=nq;
  113515. if(ntry!=2)goto L107;
  113516. if(nf==1)goto L107;
  113517. for (i=1;i<nf;i++){
  113518. ib=nf-i+1;
  113519. ifac[ib+1]=ifac[ib];
  113520. }
  113521. ifac[2] = 2;
  113522. L107:
  113523. if(nl!=1)goto L104;
  113524. ifac[0]=n;
  113525. ifac[1]=nf;
  113526. argh=tpi/n;
  113527. is=0;
  113528. nfm1=nf-1;
  113529. l1=1;
  113530. if(nfm1==0)return;
  113531. for (k1=0;k1<nfm1;k1++){
  113532. ip=ifac[k1+2];
  113533. ld=0;
  113534. l2=l1*ip;
  113535. ido=n/l2;
  113536. ipm=ip-1;
  113537. for (j=0;j<ipm;j++){
  113538. ld+=l1;
  113539. i=is;
  113540. argld=(float)ld*argh;
  113541. fi=0.f;
  113542. for (ii=2;ii<ido;ii+=2){
  113543. fi+=1.f;
  113544. arg=fi*argld;
  113545. wa[i++]=cos(arg);
  113546. wa[i++]=sin(arg);
  113547. }
  113548. is+=ido;
  113549. }
  113550. l1=l2;
  113551. }
  113552. }
  113553. static void fdrffti(int n, float *wsave, int *ifac){
  113554. if (n == 1) return;
  113555. drfti1(n, wsave+n, ifac);
  113556. }
  113557. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  113558. int i,k;
  113559. float ti2,tr2;
  113560. int t0,t1,t2,t3,t4,t5,t6;
  113561. t1=0;
  113562. t0=(t2=l1*ido);
  113563. t3=ido<<1;
  113564. for(k=0;k<l1;k++){
  113565. ch[t1<<1]=cc[t1]+cc[t2];
  113566. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  113567. t1+=ido;
  113568. t2+=ido;
  113569. }
  113570. if(ido<2)return;
  113571. if(ido==2)goto L105;
  113572. t1=0;
  113573. t2=t0;
  113574. for(k=0;k<l1;k++){
  113575. t3=t2;
  113576. t4=(t1<<1)+(ido<<1);
  113577. t5=t1;
  113578. t6=t1+t1;
  113579. for(i=2;i<ido;i+=2){
  113580. t3+=2;
  113581. t4-=2;
  113582. t5+=2;
  113583. t6+=2;
  113584. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  113585. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  113586. ch[t6]=cc[t5]+ti2;
  113587. ch[t4]=ti2-cc[t5];
  113588. ch[t6-1]=cc[t5-1]+tr2;
  113589. ch[t4-1]=cc[t5-1]-tr2;
  113590. }
  113591. t1+=ido;
  113592. t2+=ido;
  113593. }
  113594. if(ido%2==1)return;
  113595. L105:
  113596. t3=(t2=(t1=ido)-1);
  113597. t2+=t0;
  113598. for(k=0;k<l1;k++){
  113599. ch[t1]=-cc[t2];
  113600. ch[t1-1]=cc[t3];
  113601. t1+=ido<<1;
  113602. t2+=ido;
  113603. t3+=ido;
  113604. }
  113605. }
  113606. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  113607. float *wa2,float *wa3){
  113608. static float hsqt2 = .70710678118654752f;
  113609. int i,k,t0,t1,t2,t3,t4,t5,t6;
  113610. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  113611. t0=l1*ido;
  113612. t1=t0;
  113613. t4=t1<<1;
  113614. t2=t1+(t1<<1);
  113615. t3=0;
  113616. for(k=0;k<l1;k++){
  113617. tr1=cc[t1]+cc[t2];
  113618. tr2=cc[t3]+cc[t4];
  113619. ch[t5=t3<<2]=tr1+tr2;
  113620. ch[(ido<<2)+t5-1]=tr2-tr1;
  113621. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  113622. ch[t5]=cc[t2]-cc[t1];
  113623. t1+=ido;
  113624. t2+=ido;
  113625. t3+=ido;
  113626. t4+=ido;
  113627. }
  113628. if(ido<2)return;
  113629. if(ido==2)goto L105;
  113630. t1=0;
  113631. for(k=0;k<l1;k++){
  113632. t2=t1;
  113633. t4=t1<<2;
  113634. t5=(t6=ido<<1)+t4;
  113635. for(i=2;i<ido;i+=2){
  113636. t3=(t2+=2);
  113637. t4+=2;
  113638. t5-=2;
  113639. t3+=t0;
  113640. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  113641. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  113642. t3+=t0;
  113643. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  113644. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  113645. t3+=t0;
  113646. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  113647. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  113648. tr1=cr2+cr4;
  113649. tr4=cr4-cr2;
  113650. ti1=ci2+ci4;
  113651. ti4=ci2-ci4;
  113652. ti2=cc[t2]+ci3;
  113653. ti3=cc[t2]-ci3;
  113654. tr2=cc[t2-1]+cr3;
  113655. tr3=cc[t2-1]-cr3;
  113656. ch[t4-1]=tr1+tr2;
  113657. ch[t4]=ti1+ti2;
  113658. ch[t5-1]=tr3-ti4;
  113659. ch[t5]=tr4-ti3;
  113660. ch[t4+t6-1]=ti4+tr3;
  113661. ch[t4+t6]=tr4+ti3;
  113662. ch[t5+t6-1]=tr2-tr1;
  113663. ch[t5+t6]=ti1-ti2;
  113664. }
  113665. t1+=ido;
  113666. }
  113667. if(ido&1)return;
  113668. L105:
  113669. t2=(t1=t0+ido-1)+(t0<<1);
  113670. t3=ido<<2;
  113671. t4=ido;
  113672. t5=ido<<1;
  113673. t6=ido;
  113674. for(k=0;k<l1;k++){
  113675. ti1=-hsqt2*(cc[t1]+cc[t2]);
  113676. tr1=hsqt2*(cc[t1]-cc[t2]);
  113677. ch[t4-1]=tr1+cc[t6-1];
  113678. ch[t4+t5-1]=cc[t6-1]-tr1;
  113679. ch[t4]=ti1-cc[t1+t0];
  113680. ch[t4+t5]=ti1+cc[t1+t0];
  113681. t1+=ido;
  113682. t2+=ido;
  113683. t4+=t3;
  113684. t6+=ido;
  113685. }
  113686. }
  113687. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  113688. float *c2,float *ch,float *ch2,float *wa){
  113689. static float tpi=6.283185307179586f;
  113690. int idij,ipph,i,j,k,l,ic,ik,is;
  113691. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  113692. float dc2,ai1,ai2,ar1,ar2,ds2;
  113693. int nbd;
  113694. float dcp,arg,dsp,ar1h,ar2h;
  113695. int idp2,ipp2;
  113696. arg=tpi/(float)ip;
  113697. dcp=cos(arg);
  113698. dsp=sin(arg);
  113699. ipph=(ip+1)>>1;
  113700. ipp2=ip;
  113701. idp2=ido;
  113702. nbd=(ido-1)>>1;
  113703. t0=l1*ido;
  113704. t10=ip*ido;
  113705. if(ido==1)goto L119;
  113706. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  113707. t1=0;
  113708. for(j=1;j<ip;j++){
  113709. t1+=t0;
  113710. t2=t1;
  113711. for(k=0;k<l1;k++){
  113712. ch[t2]=c1[t2];
  113713. t2+=ido;
  113714. }
  113715. }
  113716. is=-ido;
  113717. t1=0;
  113718. if(nbd>l1){
  113719. for(j=1;j<ip;j++){
  113720. t1+=t0;
  113721. is+=ido;
  113722. t2= -ido+t1;
  113723. for(k=0;k<l1;k++){
  113724. idij=is-1;
  113725. t2+=ido;
  113726. t3=t2;
  113727. for(i=2;i<ido;i+=2){
  113728. idij+=2;
  113729. t3+=2;
  113730. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  113731. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  113732. }
  113733. }
  113734. }
  113735. }else{
  113736. for(j=1;j<ip;j++){
  113737. is+=ido;
  113738. idij=is-1;
  113739. t1+=t0;
  113740. t2=t1;
  113741. for(i=2;i<ido;i+=2){
  113742. idij+=2;
  113743. t2+=2;
  113744. t3=t2;
  113745. for(k=0;k<l1;k++){
  113746. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  113747. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  113748. t3+=ido;
  113749. }
  113750. }
  113751. }
  113752. }
  113753. t1=0;
  113754. t2=ipp2*t0;
  113755. if(nbd<l1){
  113756. for(j=1;j<ipph;j++){
  113757. t1+=t0;
  113758. t2-=t0;
  113759. t3=t1;
  113760. t4=t2;
  113761. for(i=2;i<ido;i+=2){
  113762. t3+=2;
  113763. t4+=2;
  113764. t5=t3-ido;
  113765. t6=t4-ido;
  113766. for(k=0;k<l1;k++){
  113767. t5+=ido;
  113768. t6+=ido;
  113769. c1[t5-1]=ch[t5-1]+ch[t6-1];
  113770. c1[t6-1]=ch[t5]-ch[t6];
  113771. c1[t5]=ch[t5]+ch[t6];
  113772. c1[t6]=ch[t6-1]-ch[t5-1];
  113773. }
  113774. }
  113775. }
  113776. }else{
  113777. for(j=1;j<ipph;j++){
  113778. t1+=t0;
  113779. t2-=t0;
  113780. t3=t1;
  113781. t4=t2;
  113782. for(k=0;k<l1;k++){
  113783. t5=t3;
  113784. t6=t4;
  113785. for(i=2;i<ido;i+=2){
  113786. t5+=2;
  113787. t6+=2;
  113788. c1[t5-1]=ch[t5-1]+ch[t6-1];
  113789. c1[t6-1]=ch[t5]-ch[t6];
  113790. c1[t5]=ch[t5]+ch[t6];
  113791. c1[t6]=ch[t6-1]-ch[t5-1];
  113792. }
  113793. t3+=ido;
  113794. t4+=ido;
  113795. }
  113796. }
  113797. }
  113798. L119:
  113799. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  113800. t1=0;
  113801. t2=ipp2*idl1;
  113802. for(j=1;j<ipph;j++){
  113803. t1+=t0;
  113804. t2-=t0;
  113805. t3=t1-ido;
  113806. t4=t2-ido;
  113807. for(k=0;k<l1;k++){
  113808. t3+=ido;
  113809. t4+=ido;
  113810. c1[t3]=ch[t3]+ch[t4];
  113811. c1[t4]=ch[t4]-ch[t3];
  113812. }
  113813. }
  113814. ar1=1.f;
  113815. ai1=0.f;
  113816. t1=0;
  113817. t2=ipp2*idl1;
  113818. t3=(ip-1)*idl1;
  113819. for(l=1;l<ipph;l++){
  113820. t1+=idl1;
  113821. t2-=idl1;
  113822. ar1h=dcp*ar1-dsp*ai1;
  113823. ai1=dcp*ai1+dsp*ar1;
  113824. ar1=ar1h;
  113825. t4=t1;
  113826. t5=t2;
  113827. t6=t3;
  113828. t7=idl1;
  113829. for(ik=0;ik<idl1;ik++){
  113830. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  113831. ch2[t5++]=ai1*c2[t6++];
  113832. }
  113833. dc2=ar1;
  113834. ds2=ai1;
  113835. ar2=ar1;
  113836. ai2=ai1;
  113837. t4=idl1;
  113838. t5=(ipp2-1)*idl1;
  113839. for(j=2;j<ipph;j++){
  113840. t4+=idl1;
  113841. t5-=idl1;
  113842. ar2h=dc2*ar2-ds2*ai2;
  113843. ai2=dc2*ai2+ds2*ar2;
  113844. ar2=ar2h;
  113845. t6=t1;
  113846. t7=t2;
  113847. t8=t4;
  113848. t9=t5;
  113849. for(ik=0;ik<idl1;ik++){
  113850. ch2[t6++]+=ar2*c2[t8++];
  113851. ch2[t7++]+=ai2*c2[t9++];
  113852. }
  113853. }
  113854. }
  113855. t1=0;
  113856. for(j=1;j<ipph;j++){
  113857. t1+=idl1;
  113858. t2=t1;
  113859. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  113860. }
  113861. if(ido<l1)goto L132;
  113862. t1=0;
  113863. t2=0;
  113864. for(k=0;k<l1;k++){
  113865. t3=t1;
  113866. t4=t2;
  113867. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  113868. t1+=ido;
  113869. t2+=t10;
  113870. }
  113871. goto L135;
  113872. L132:
  113873. for(i=0;i<ido;i++){
  113874. t1=i;
  113875. t2=i;
  113876. for(k=0;k<l1;k++){
  113877. cc[t2]=ch[t1];
  113878. t1+=ido;
  113879. t2+=t10;
  113880. }
  113881. }
  113882. L135:
  113883. t1=0;
  113884. t2=ido<<1;
  113885. t3=0;
  113886. t4=ipp2*t0;
  113887. for(j=1;j<ipph;j++){
  113888. t1+=t2;
  113889. t3+=t0;
  113890. t4-=t0;
  113891. t5=t1;
  113892. t6=t3;
  113893. t7=t4;
  113894. for(k=0;k<l1;k++){
  113895. cc[t5-1]=ch[t6];
  113896. cc[t5]=ch[t7];
  113897. t5+=t10;
  113898. t6+=ido;
  113899. t7+=ido;
  113900. }
  113901. }
  113902. if(ido==1)return;
  113903. if(nbd<l1)goto L141;
  113904. t1=-ido;
  113905. t3=0;
  113906. t4=0;
  113907. t5=ipp2*t0;
  113908. for(j=1;j<ipph;j++){
  113909. t1+=t2;
  113910. t3+=t2;
  113911. t4+=t0;
  113912. t5-=t0;
  113913. t6=t1;
  113914. t7=t3;
  113915. t8=t4;
  113916. t9=t5;
  113917. for(k=0;k<l1;k++){
  113918. for(i=2;i<ido;i+=2){
  113919. ic=idp2-i;
  113920. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  113921. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  113922. cc[i+t7]=ch[i+t8]+ch[i+t9];
  113923. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  113924. }
  113925. t6+=t10;
  113926. t7+=t10;
  113927. t8+=ido;
  113928. t9+=ido;
  113929. }
  113930. }
  113931. return;
  113932. L141:
  113933. t1=-ido;
  113934. t3=0;
  113935. t4=0;
  113936. t5=ipp2*t0;
  113937. for(j=1;j<ipph;j++){
  113938. t1+=t2;
  113939. t3+=t2;
  113940. t4+=t0;
  113941. t5-=t0;
  113942. for(i=2;i<ido;i+=2){
  113943. t6=idp2+t1-i;
  113944. t7=i+t3;
  113945. t8=i+t4;
  113946. t9=i+t5;
  113947. for(k=0;k<l1;k++){
  113948. cc[t7-1]=ch[t8-1]+ch[t9-1];
  113949. cc[t6-1]=ch[t8-1]-ch[t9-1];
  113950. cc[t7]=ch[t8]+ch[t9];
  113951. cc[t6]=ch[t9]-ch[t8];
  113952. t6+=t10;
  113953. t7+=t10;
  113954. t8+=ido;
  113955. t9+=ido;
  113956. }
  113957. }
  113958. }
  113959. }
  113960. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  113961. int i,k1,l1,l2;
  113962. int na,kh,nf;
  113963. int ip,iw,ido,idl1,ix2,ix3;
  113964. nf=ifac[1];
  113965. na=1;
  113966. l2=n;
  113967. iw=n;
  113968. for(k1=0;k1<nf;k1++){
  113969. kh=nf-k1;
  113970. ip=ifac[kh+1];
  113971. l1=l2/ip;
  113972. ido=n/l2;
  113973. idl1=ido*l1;
  113974. iw-=(ip-1)*ido;
  113975. na=1-na;
  113976. if(ip!=4)goto L102;
  113977. ix2=iw+ido;
  113978. ix3=ix2+ido;
  113979. if(na!=0)
  113980. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  113981. else
  113982. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  113983. goto L110;
  113984. L102:
  113985. if(ip!=2)goto L104;
  113986. if(na!=0)goto L103;
  113987. dradf2(ido,l1,c,ch,wa+iw-1);
  113988. goto L110;
  113989. L103:
  113990. dradf2(ido,l1,ch,c,wa+iw-1);
  113991. goto L110;
  113992. L104:
  113993. if(ido==1)na=1-na;
  113994. if(na!=0)goto L109;
  113995. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  113996. na=1;
  113997. goto L110;
  113998. L109:
  113999. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  114000. na=0;
  114001. L110:
  114002. l2=l1;
  114003. }
  114004. if(na==1)return;
  114005. for(i=0;i<n;i++)c[i]=ch[i];
  114006. }
  114007. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  114008. int i,k,t0,t1,t2,t3,t4,t5,t6;
  114009. float ti2,tr2;
  114010. t0=l1*ido;
  114011. t1=0;
  114012. t2=0;
  114013. t3=(ido<<1)-1;
  114014. for(k=0;k<l1;k++){
  114015. ch[t1]=cc[t2]+cc[t3+t2];
  114016. ch[t1+t0]=cc[t2]-cc[t3+t2];
  114017. t2=(t1+=ido)<<1;
  114018. }
  114019. if(ido<2)return;
  114020. if(ido==2)goto L105;
  114021. t1=0;
  114022. t2=0;
  114023. for(k=0;k<l1;k++){
  114024. t3=t1;
  114025. t5=(t4=t2)+(ido<<1);
  114026. t6=t0+t1;
  114027. for(i=2;i<ido;i+=2){
  114028. t3+=2;
  114029. t4+=2;
  114030. t5-=2;
  114031. t6+=2;
  114032. ch[t3-1]=cc[t4-1]+cc[t5-1];
  114033. tr2=cc[t4-1]-cc[t5-1];
  114034. ch[t3]=cc[t4]-cc[t5];
  114035. ti2=cc[t4]+cc[t5];
  114036. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  114037. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  114038. }
  114039. t2=(t1+=ido)<<1;
  114040. }
  114041. if(ido%2==1)return;
  114042. L105:
  114043. t1=ido-1;
  114044. t2=ido-1;
  114045. for(k=0;k<l1;k++){
  114046. ch[t1]=cc[t2]+cc[t2];
  114047. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  114048. t1+=ido;
  114049. t2+=ido<<1;
  114050. }
  114051. }
  114052. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  114053. float *wa2){
  114054. static float taur = -.5f;
  114055. static float taui = .8660254037844386f;
  114056. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  114057. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  114058. t0=l1*ido;
  114059. t1=0;
  114060. t2=t0<<1;
  114061. t3=ido<<1;
  114062. t4=ido+(ido<<1);
  114063. t5=0;
  114064. for(k=0;k<l1;k++){
  114065. tr2=cc[t3-1]+cc[t3-1];
  114066. cr2=cc[t5]+(taur*tr2);
  114067. ch[t1]=cc[t5]+tr2;
  114068. ci3=taui*(cc[t3]+cc[t3]);
  114069. ch[t1+t0]=cr2-ci3;
  114070. ch[t1+t2]=cr2+ci3;
  114071. t1+=ido;
  114072. t3+=t4;
  114073. t5+=t4;
  114074. }
  114075. if(ido==1)return;
  114076. t1=0;
  114077. t3=ido<<1;
  114078. for(k=0;k<l1;k++){
  114079. t7=t1+(t1<<1);
  114080. t6=(t5=t7+t3);
  114081. t8=t1;
  114082. t10=(t9=t1+t0)+t0;
  114083. for(i=2;i<ido;i+=2){
  114084. t5+=2;
  114085. t6-=2;
  114086. t7+=2;
  114087. t8+=2;
  114088. t9+=2;
  114089. t10+=2;
  114090. tr2=cc[t5-1]+cc[t6-1];
  114091. cr2=cc[t7-1]+(taur*tr2);
  114092. ch[t8-1]=cc[t7-1]+tr2;
  114093. ti2=cc[t5]-cc[t6];
  114094. ci2=cc[t7]+(taur*ti2);
  114095. ch[t8]=cc[t7]+ti2;
  114096. cr3=taui*(cc[t5-1]-cc[t6-1]);
  114097. ci3=taui*(cc[t5]+cc[t6]);
  114098. dr2=cr2-ci3;
  114099. dr3=cr2+ci3;
  114100. di2=ci2+cr3;
  114101. di3=ci2-cr3;
  114102. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  114103. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  114104. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  114105. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  114106. }
  114107. t1+=ido;
  114108. }
  114109. }
  114110. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  114111. float *wa2,float *wa3){
  114112. static float sqrt2=1.414213562373095f;
  114113. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  114114. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  114115. t0=l1*ido;
  114116. t1=0;
  114117. t2=ido<<2;
  114118. t3=0;
  114119. t6=ido<<1;
  114120. for(k=0;k<l1;k++){
  114121. t4=t3+t6;
  114122. t5=t1;
  114123. tr3=cc[t4-1]+cc[t4-1];
  114124. tr4=cc[t4]+cc[t4];
  114125. tr1=cc[t3]-cc[(t4+=t6)-1];
  114126. tr2=cc[t3]+cc[t4-1];
  114127. ch[t5]=tr2+tr3;
  114128. ch[t5+=t0]=tr1-tr4;
  114129. ch[t5+=t0]=tr2-tr3;
  114130. ch[t5+=t0]=tr1+tr4;
  114131. t1+=ido;
  114132. t3+=t2;
  114133. }
  114134. if(ido<2)return;
  114135. if(ido==2)goto L105;
  114136. t1=0;
  114137. for(k=0;k<l1;k++){
  114138. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  114139. t7=t1;
  114140. for(i=2;i<ido;i+=2){
  114141. t2+=2;
  114142. t3+=2;
  114143. t4-=2;
  114144. t5-=2;
  114145. t7+=2;
  114146. ti1=cc[t2]+cc[t5];
  114147. ti2=cc[t2]-cc[t5];
  114148. ti3=cc[t3]-cc[t4];
  114149. tr4=cc[t3]+cc[t4];
  114150. tr1=cc[t2-1]-cc[t5-1];
  114151. tr2=cc[t2-1]+cc[t5-1];
  114152. ti4=cc[t3-1]-cc[t4-1];
  114153. tr3=cc[t3-1]+cc[t4-1];
  114154. ch[t7-1]=tr2+tr3;
  114155. cr3=tr2-tr3;
  114156. ch[t7]=ti2+ti3;
  114157. ci3=ti2-ti3;
  114158. cr2=tr1-tr4;
  114159. cr4=tr1+tr4;
  114160. ci2=ti1+ti4;
  114161. ci4=ti1-ti4;
  114162. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  114163. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  114164. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  114165. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  114166. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  114167. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  114168. }
  114169. t1+=ido;
  114170. }
  114171. if(ido%2 == 1)return;
  114172. L105:
  114173. t1=ido;
  114174. t2=ido<<2;
  114175. t3=ido-1;
  114176. t4=ido+(ido<<1);
  114177. for(k=0;k<l1;k++){
  114178. t5=t3;
  114179. ti1=cc[t1]+cc[t4];
  114180. ti2=cc[t4]-cc[t1];
  114181. tr1=cc[t1-1]-cc[t4-1];
  114182. tr2=cc[t1-1]+cc[t4-1];
  114183. ch[t5]=tr2+tr2;
  114184. ch[t5+=t0]=sqrt2*(tr1-ti1);
  114185. ch[t5+=t0]=ti2+ti2;
  114186. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  114187. t3+=ido;
  114188. t1+=t2;
  114189. t4+=t2;
  114190. }
  114191. }
  114192. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  114193. float *c2,float *ch,float *ch2,float *wa){
  114194. static float tpi=6.283185307179586f;
  114195. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  114196. t11,t12;
  114197. float dc2,ai1,ai2,ar1,ar2,ds2;
  114198. int nbd;
  114199. float dcp,arg,dsp,ar1h,ar2h;
  114200. int ipp2;
  114201. t10=ip*ido;
  114202. t0=l1*ido;
  114203. arg=tpi/(float)ip;
  114204. dcp=cos(arg);
  114205. dsp=sin(arg);
  114206. nbd=(ido-1)>>1;
  114207. ipp2=ip;
  114208. ipph=(ip+1)>>1;
  114209. if(ido<l1)goto L103;
  114210. t1=0;
  114211. t2=0;
  114212. for(k=0;k<l1;k++){
  114213. t3=t1;
  114214. t4=t2;
  114215. for(i=0;i<ido;i++){
  114216. ch[t3]=cc[t4];
  114217. t3++;
  114218. t4++;
  114219. }
  114220. t1+=ido;
  114221. t2+=t10;
  114222. }
  114223. goto L106;
  114224. L103:
  114225. t1=0;
  114226. for(i=0;i<ido;i++){
  114227. t2=t1;
  114228. t3=t1;
  114229. for(k=0;k<l1;k++){
  114230. ch[t2]=cc[t3];
  114231. t2+=ido;
  114232. t3+=t10;
  114233. }
  114234. t1++;
  114235. }
  114236. L106:
  114237. t1=0;
  114238. t2=ipp2*t0;
  114239. t7=(t5=ido<<1);
  114240. for(j=1;j<ipph;j++){
  114241. t1+=t0;
  114242. t2-=t0;
  114243. t3=t1;
  114244. t4=t2;
  114245. t6=t5;
  114246. for(k=0;k<l1;k++){
  114247. ch[t3]=cc[t6-1]+cc[t6-1];
  114248. ch[t4]=cc[t6]+cc[t6];
  114249. t3+=ido;
  114250. t4+=ido;
  114251. t6+=t10;
  114252. }
  114253. t5+=t7;
  114254. }
  114255. if (ido == 1)goto L116;
  114256. if(nbd<l1)goto L112;
  114257. t1=0;
  114258. t2=ipp2*t0;
  114259. t7=0;
  114260. for(j=1;j<ipph;j++){
  114261. t1+=t0;
  114262. t2-=t0;
  114263. t3=t1;
  114264. t4=t2;
  114265. t7+=(ido<<1);
  114266. t8=t7;
  114267. for(k=0;k<l1;k++){
  114268. t5=t3;
  114269. t6=t4;
  114270. t9=t8;
  114271. t11=t8;
  114272. for(i=2;i<ido;i+=2){
  114273. t5+=2;
  114274. t6+=2;
  114275. t9+=2;
  114276. t11-=2;
  114277. ch[t5-1]=cc[t9-1]+cc[t11-1];
  114278. ch[t6-1]=cc[t9-1]-cc[t11-1];
  114279. ch[t5]=cc[t9]-cc[t11];
  114280. ch[t6]=cc[t9]+cc[t11];
  114281. }
  114282. t3+=ido;
  114283. t4+=ido;
  114284. t8+=t10;
  114285. }
  114286. }
  114287. goto L116;
  114288. L112:
  114289. t1=0;
  114290. t2=ipp2*t0;
  114291. t7=0;
  114292. for(j=1;j<ipph;j++){
  114293. t1+=t0;
  114294. t2-=t0;
  114295. t3=t1;
  114296. t4=t2;
  114297. t7+=(ido<<1);
  114298. t8=t7;
  114299. t9=t7;
  114300. for(i=2;i<ido;i+=2){
  114301. t3+=2;
  114302. t4+=2;
  114303. t8+=2;
  114304. t9-=2;
  114305. t5=t3;
  114306. t6=t4;
  114307. t11=t8;
  114308. t12=t9;
  114309. for(k=0;k<l1;k++){
  114310. ch[t5-1]=cc[t11-1]+cc[t12-1];
  114311. ch[t6-1]=cc[t11-1]-cc[t12-1];
  114312. ch[t5]=cc[t11]-cc[t12];
  114313. ch[t6]=cc[t11]+cc[t12];
  114314. t5+=ido;
  114315. t6+=ido;
  114316. t11+=t10;
  114317. t12+=t10;
  114318. }
  114319. }
  114320. }
  114321. L116:
  114322. ar1=1.f;
  114323. ai1=0.f;
  114324. t1=0;
  114325. t9=(t2=ipp2*idl1);
  114326. t3=(ip-1)*idl1;
  114327. for(l=1;l<ipph;l++){
  114328. t1+=idl1;
  114329. t2-=idl1;
  114330. ar1h=dcp*ar1-dsp*ai1;
  114331. ai1=dcp*ai1+dsp*ar1;
  114332. ar1=ar1h;
  114333. t4=t1;
  114334. t5=t2;
  114335. t6=0;
  114336. t7=idl1;
  114337. t8=t3;
  114338. for(ik=0;ik<idl1;ik++){
  114339. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  114340. c2[t5++]=ai1*ch2[t8++];
  114341. }
  114342. dc2=ar1;
  114343. ds2=ai1;
  114344. ar2=ar1;
  114345. ai2=ai1;
  114346. t6=idl1;
  114347. t7=t9-idl1;
  114348. for(j=2;j<ipph;j++){
  114349. t6+=idl1;
  114350. t7-=idl1;
  114351. ar2h=dc2*ar2-ds2*ai2;
  114352. ai2=dc2*ai2+ds2*ar2;
  114353. ar2=ar2h;
  114354. t4=t1;
  114355. t5=t2;
  114356. t11=t6;
  114357. t12=t7;
  114358. for(ik=0;ik<idl1;ik++){
  114359. c2[t4++]+=ar2*ch2[t11++];
  114360. c2[t5++]+=ai2*ch2[t12++];
  114361. }
  114362. }
  114363. }
  114364. t1=0;
  114365. for(j=1;j<ipph;j++){
  114366. t1+=idl1;
  114367. t2=t1;
  114368. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  114369. }
  114370. t1=0;
  114371. t2=ipp2*t0;
  114372. for(j=1;j<ipph;j++){
  114373. t1+=t0;
  114374. t2-=t0;
  114375. t3=t1;
  114376. t4=t2;
  114377. for(k=0;k<l1;k++){
  114378. ch[t3]=c1[t3]-c1[t4];
  114379. ch[t4]=c1[t3]+c1[t4];
  114380. t3+=ido;
  114381. t4+=ido;
  114382. }
  114383. }
  114384. if(ido==1)goto L132;
  114385. if(nbd<l1)goto L128;
  114386. t1=0;
  114387. t2=ipp2*t0;
  114388. for(j=1;j<ipph;j++){
  114389. t1+=t0;
  114390. t2-=t0;
  114391. t3=t1;
  114392. t4=t2;
  114393. for(k=0;k<l1;k++){
  114394. t5=t3;
  114395. t6=t4;
  114396. for(i=2;i<ido;i+=2){
  114397. t5+=2;
  114398. t6+=2;
  114399. ch[t5-1]=c1[t5-1]-c1[t6];
  114400. ch[t6-1]=c1[t5-1]+c1[t6];
  114401. ch[t5]=c1[t5]+c1[t6-1];
  114402. ch[t6]=c1[t5]-c1[t6-1];
  114403. }
  114404. t3+=ido;
  114405. t4+=ido;
  114406. }
  114407. }
  114408. goto L132;
  114409. L128:
  114410. t1=0;
  114411. t2=ipp2*t0;
  114412. for(j=1;j<ipph;j++){
  114413. t1+=t0;
  114414. t2-=t0;
  114415. t3=t1;
  114416. t4=t2;
  114417. for(i=2;i<ido;i+=2){
  114418. t3+=2;
  114419. t4+=2;
  114420. t5=t3;
  114421. t6=t4;
  114422. for(k=0;k<l1;k++){
  114423. ch[t5-1]=c1[t5-1]-c1[t6];
  114424. ch[t6-1]=c1[t5-1]+c1[t6];
  114425. ch[t5]=c1[t5]+c1[t6-1];
  114426. ch[t6]=c1[t5]-c1[t6-1];
  114427. t5+=ido;
  114428. t6+=ido;
  114429. }
  114430. }
  114431. }
  114432. L132:
  114433. if(ido==1)return;
  114434. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  114435. t1=0;
  114436. for(j=1;j<ip;j++){
  114437. t2=(t1+=t0);
  114438. for(k=0;k<l1;k++){
  114439. c1[t2]=ch[t2];
  114440. t2+=ido;
  114441. }
  114442. }
  114443. if(nbd>l1)goto L139;
  114444. is= -ido-1;
  114445. t1=0;
  114446. for(j=1;j<ip;j++){
  114447. is+=ido;
  114448. t1+=t0;
  114449. idij=is;
  114450. t2=t1;
  114451. for(i=2;i<ido;i+=2){
  114452. t2+=2;
  114453. idij+=2;
  114454. t3=t2;
  114455. for(k=0;k<l1;k++){
  114456. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  114457. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  114458. t3+=ido;
  114459. }
  114460. }
  114461. }
  114462. return;
  114463. L139:
  114464. is= -ido-1;
  114465. t1=0;
  114466. for(j=1;j<ip;j++){
  114467. is+=ido;
  114468. t1+=t0;
  114469. t2=t1;
  114470. for(k=0;k<l1;k++){
  114471. idij=is;
  114472. t3=t2;
  114473. for(i=2;i<ido;i+=2){
  114474. idij+=2;
  114475. t3+=2;
  114476. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  114477. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  114478. }
  114479. t2+=ido;
  114480. }
  114481. }
  114482. }
  114483. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  114484. int i,k1,l1,l2;
  114485. int na;
  114486. int nf,ip,iw,ix2,ix3,ido,idl1;
  114487. nf=ifac[1];
  114488. na=0;
  114489. l1=1;
  114490. iw=1;
  114491. for(k1=0;k1<nf;k1++){
  114492. ip=ifac[k1 + 2];
  114493. l2=ip*l1;
  114494. ido=n/l2;
  114495. idl1=ido*l1;
  114496. if(ip!=4)goto L103;
  114497. ix2=iw+ido;
  114498. ix3=ix2+ido;
  114499. if(na!=0)
  114500. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  114501. else
  114502. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  114503. na=1-na;
  114504. goto L115;
  114505. L103:
  114506. if(ip!=2)goto L106;
  114507. if(na!=0)
  114508. dradb2(ido,l1,ch,c,wa+iw-1);
  114509. else
  114510. dradb2(ido,l1,c,ch,wa+iw-1);
  114511. na=1-na;
  114512. goto L115;
  114513. L106:
  114514. if(ip!=3)goto L109;
  114515. ix2=iw+ido;
  114516. if(na!=0)
  114517. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  114518. else
  114519. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  114520. na=1-na;
  114521. goto L115;
  114522. L109:
  114523. /* The radix five case can be translated later..... */
  114524. /* if(ip!=5)goto L112;
  114525. ix2=iw+ido;
  114526. ix3=ix2+ido;
  114527. ix4=ix3+ido;
  114528. if(na!=0)
  114529. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  114530. else
  114531. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  114532. na=1-na;
  114533. goto L115;
  114534. L112:*/
  114535. if(na!=0)
  114536. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  114537. else
  114538. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  114539. if(ido==1)na=1-na;
  114540. L115:
  114541. l1=l2;
  114542. iw+=(ip-1)*ido;
  114543. }
  114544. if(na==0)return;
  114545. for(i=0;i<n;i++)c[i]=ch[i];
  114546. }
  114547. void drft_forward(drft_lookup *l,float *data){
  114548. if(l->n==1)return;
  114549. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  114550. }
  114551. void drft_backward(drft_lookup *l,float *data){
  114552. if (l->n==1)return;
  114553. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  114554. }
  114555. void drft_init(drft_lookup *l,int n){
  114556. l->n=n;
  114557. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  114558. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  114559. fdrffti(n, l->trigcache, l->splitcache);
  114560. }
  114561. void drft_clear(drft_lookup *l){
  114562. if(l){
  114563. if(l->trigcache)_ogg_free(l->trigcache);
  114564. if(l->splitcache)_ogg_free(l->splitcache);
  114565. memset(l,0,sizeof(*l));
  114566. }
  114567. }
  114568. #endif
  114569. /********* End of inlined file: smallft.c *********/
  114570. /********* Start of inlined file: synthesis.c *********/
  114571. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  114572. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114573. // tasks..
  114574. #ifdef _MSC_VER
  114575. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114576. #endif
  114577. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  114578. #if JUCE_USE_OGGVORBIS
  114579. #include <stdio.h>
  114580. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  114581. vorbis_dsp_state *vd=vb->vd;
  114582. private_state *b=(private_state*)vd->backend_state;
  114583. vorbis_info *vi=vd->vi;
  114584. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  114585. oggpack_buffer *opb=&vb->opb;
  114586. int type,mode,i;
  114587. /* first things first. Make sure decode is ready */
  114588. _vorbis_block_ripcord(vb);
  114589. oggpack_readinit(opb,op->packet,op->bytes);
  114590. /* Check the packet type */
  114591. if(oggpack_read(opb,1)!=0){
  114592. /* Oops. This is not an audio data packet */
  114593. return(OV_ENOTAUDIO);
  114594. }
  114595. /* read our mode and pre/post windowsize */
  114596. mode=oggpack_read(opb,b->modebits);
  114597. if(mode==-1)return(OV_EBADPACKET);
  114598. vb->mode=mode;
  114599. vb->W=ci->mode_param[mode]->blockflag;
  114600. if(vb->W){
  114601. /* this doesn;t get mapped through mode selection as it's used
  114602. only for window selection */
  114603. vb->lW=oggpack_read(opb,1);
  114604. vb->nW=oggpack_read(opb,1);
  114605. if(vb->nW==-1) return(OV_EBADPACKET);
  114606. }else{
  114607. vb->lW=0;
  114608. vb->nW=0;
  114609. }
  114610. /* more setup */
  114611. vb->granulepos=op->granulepos;
  114612. vb->sequence=op->packetno;
  114613. vb->eofflag=op->e_o_s;
  114614. /* alloc pcm passback storage */
  114615. vb->pcmend=ci->blocksizes[vb->W];
  114616. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  114617. for(i=0;i<vi->channels;i++)
  114618. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  114619. /* unpack_header enforces range checking */
  114620. type=ci->map_type[ci->mode_param[mode]->mapping];
  114621. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  114622. mapping]));
  114623. }
  114624. /* used to track pcm position without actually performing decode.
  114625. Useful for sequential 'fast forward' */
  114626. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  114627. vorbis_dsp_state *vd=vb->vd;
  114628. private_state *b=(private_state*)vd->backend_state;
  114629. vorbis_info *vi=vd->vi;
  114630. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114631. oggpack_buffer *opb=&vb->opb;
  114632. int mode;
  114633. /* first things first. Make sure decode is ready */
  114634. _vorbis_block_ripcord(vb);
  114635. oggpack_readinit(opb,op->packet,op->bytes);
  114636. /* Check the packet type */
  114637. if(oggpack_read(opb,1)!=0){
  114638. /* Oops. This is not an audio data packet */
  114639. return(OV_ENOTAUDIO);
  114640. }
  114641. /* read our mode and pre/post windowsize */
  114642. mode=oggpack_read(opb,b->modebits);
  114643. if(mode==-1)return(OV_EBADPACKET);
  114644. vb->mode=mode;
  114645. vb->W=ci->mode_param[mode]->blockflag;
  114646. if(vb->W){
  114647. vb->lW=oggpack_read(opb,1);
  114648. vb->nW=oggpack_read(opb,1);
  114649. if(vb->nW==-1) return(OV_EBADPACKET);
  114650. }else{
  114651. vb->lW=0;
  114652. vb->nW=0;
  114653. }
  114654. /* more setup */
  114655. vb->granulepos=op->granulepos;
  114656. vb->sequence=op->packetno;
  114657. vb->eofflag=op->e_o_s;
  114658. /* no pcm */
  114659. vb->pcmend=0;
  114660. vb->pcm=NULL;
  114661. return(0);
  114662. }
  114663. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  114664. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114665. oggpack_buffer opb;
  114666. int mode;
  114667. oggpack_readinit(&opb,op->packet,op->bytes);
  114668. /* Check the packet type */
  114669. if(oggpack_read(&opb,1)!=0){
  114670. /* Oops. This is not an audio data packet */
  114671. return(OV_ENOTAUDIO);
  114672. }
  114673. {
  114674. int modebits=0;
  114675. int v=ci->modes;
  114676. while(v>1){
  114677. modebits++;
  114678. v>>=1;
  114679. }
  114680. /* read our mode and pre/post windowsize */
  114681. mode=oggpack_read(&opb,modebits);
  114682. }
  114683. if(mode==-1)return(OV_EBADPACKET);
  114684. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  114685. }
  114686. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  114687. /* set / clear half-sample-rate mode */
  114688. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114689. /* right now, our MDCT can't handle < 64 sample windows. */
  114690. if(ci->blocksizes[0]<=64 && flag)return -1;
  114691. ci->halfrate_flag=(flag?1:0);
  114692. return 0;
  114693. }
  114694. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  114695. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114696. return ci->halfrate_flag;
  114697. }
  114698. #endif
  114699. /********* End of inlined file: synthesis.c *********/
  114700. /********* Start of inlined file: vorbisenc.c *********/
  114701. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  114702. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114703. // tasks..
  114704. #ifdef _MSC_VER
  114705. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114706. #endif
  114707. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  114708. #if JUCE_USE_OGGVORBIS
  114709. #include <stdlib.h>
  114710. #include <string.h>
  114711. #include <math.h>
  114712. /* careful with this; it's using static array sizing to make managing
  114713. all the modes a little less annoying. If we use a residue backend
  114714. with > 12 partition types, or a different division of iteration,
  114715. this needs to be updated. */
  114716. typedef struct {
  114717. static_codebook *books[12][3];
  114718. } static_bookblock;
  114719. typedef struct {
  114720. int res_type;
  114721. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  114722. vorbis_info_residue0 *res;
  114723. static_codebook *book_aux;
  114724. static_codebook *book_aux_managed;
  114725. static_bookblock *books_base;
  114726. static_bookblock *books_base_managed;
  114727. } vorbis_residue_template;
  114728. typedef struct {
  114729. vorbis_info_mapping0 *map;
  114730. vorbis_residue_template *res;
  114731. } vorbis_mapping_template;
  114732. typedef struct vp_adjblock{
  114733. int block[P_BANDS];
  114734. } vp_adjblock;
  114735. typedef struct {
  114736. int data[NOISE_COMPAND_LEVELS];
  114737. } compandblock;
  114738. /* high level configuration information for setting things up
  114739. step-by-step with the detailed vorbis_encode_ctl interface.
  114740. There's a fair amount of redundancy such that interactive setup
  114741. does not directly deal with any vorbis_info or codec_setup_info
  114742. initialization; it's all stored (until full init) in this highlevel
  114743. setup, then flushed out to the real codec setup structs later. */
  114744. typedef struct {
  114745. int att[P_NOISECURVES];
  114746. float boost;
  114747. float decay;
  114748. } att3;
  114749. typedef struct { int data[P_NOISECURVES]; } adj3;
  114750. typedef struct {
  114751. int pre[PACKETBLOBS];
  114752. int post[PACKETBLOBS];
  114753. float kHz[PACKETBLOBS];
  114754. float lowpasskHz[PACKETBLOBS];
  114755. } adj_stereo;
  114756. typedef struct {
  114757. int lo;
  114758. int hi;
  114759. int fixed;
  114760. } noiseguard;
  114761. typedef struct {
  114762. int data[P_NOISECURVES][17];
  114763. } noise3;
  114764. typedef struct {
  114765. int mappings;
  114766. double *rate_mapping;
  114767. double *quality_mapping;
  114768. int coupling_restriction;
  114769. long samplerate_min_restriction;
  114770. long samplerate_max_restriction;
  114771. int *blocksize_short;
  114772. int *blocksize_long;
  114773. att3 *psy_tone_masteratt;
  114774. int *psy_tone_0dB;
  114775. int *psy_tone_dBsuppress;
  114776. vp_adjblock *psy_tone_adj_impulse;
  114777. vp_adjblock *psy_tone_adj_long;
  114778. vp_adjblock *psy_tone_adj_other;
  114779. noiseguard *psy_noiseguards;
  114780. noise3 *psy_noise_bias_impulse;
  114781. noise3 *psy_noise_bias_padding;
  114782. noise3 *psy_noise_bias_trans;
  114783. noise3 *psy_noise_bias_long;
  114784. int *psy_noise_dBsuppress;
  114785. compandblock *psy_noise_compand;
  114786. double *psy_noise_compand_short_mapping;
  114787. double *psy_noise_compand_long_mapping;
  114788. int *psy_noise_normal_start[2];
  114789. int *psy_noise_normal_partition[2];
  114790. double *psy_noise_normal_thresh;
  114791. int *psy_ath_float;
  114792. int *psy_ath_abs;
  114793. double *psy_lowpass;
  114794. vorbis_info_psy_global *global_params;
  114795. double *global_mapping;
  114796. adj_stereo *stereo_modes;
  114797. static_codebook ***floor_books;
  114798. vorbis_info_floor1 *floor_params;
  114799. int *floor_short_mapping;
  114800. int *floor_long_mapping;
  114801. vorbis_mapping_template *maps;
  114802. } ve_setup_data_template;
  114803. /* a few static coder conventions */
  114804. static vorbis_info_mode _mode_template[2]={
  114805. {0,0,0,0},
  114806. {1,0,0,1}
  114807. };
  114808. static vorbis_info_mapping0 _map_nominal[2]={
  114809. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  114810. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  114811. };
  114812. /********* Start of inlined file: setup_44.h *********/
  114813. /********* Start of inlined file: floor_all.h *********/
  114814. /********* Start of inlined file: floor_books.h *********/
  114815. static long _huff_lengthlist_line_256x7_0sub1[] = {
  114816. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  114817. };
  114818. static static_codebook _huff_book_line_256x7_0sub1 = {
  114819. 1, 9,
  114820. _huff_lengthlist_line_256x7_0sub1,
  114821. 0, 0, 0, 0, 0,
  114822. NULL,
  114823. NULL,
  114824. NULL,
  114825. NULL,
  114826. 0
  114827. };
  114828. static long _huff_lengthlist_line_256x7_0sub2[] = {
  114829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  114830. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  114831. };
  114832. static static_codebook _huff_book_line_256x7_0sub2 = {
  114833. 1, 25,
  114834. _huff_lengthlist_line_256x7_0sub2,
  114835. 0, 0, 0, 0, 0,
  114836. NULL,
  114837. NULL,
  114838. NULL,
  114839. NULL,
  114840. 0
  114841. };
  114842. static long _huff_lengthlist_line_256x7_0sub3[] = {
  114843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  114845. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  114846. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  114847. };
  114848. static static_codebook _huff_book_line_256x7_0sub3 = {
  114849. 1, 64,
  114850. _huff_lengthlist_line_256x7_0sub3,
  114851. 0, 0, 0, 0, 0,
  114852. NULL,
  114853. NULL,
  114854. NULL,
  114855. NULL,
  114856. 0
  114857. };
  114858. static long _huff_lengthlist_line_256x7_1sub1[] = {
  114859. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  114860. };
  114861. static static_codebook _huff_book_line_256x7_1sub1 = {
  114862. 1, 9,
  114863. _huff_lengthlist_line_256x7_1sub1,
  114864. 0, 0, 0, 0, 0,
  114865. NULL,
  114866. NULL,
  114867. NULL,
  114868. NULL,
  114869. 0
  114870. };
  114871. static long _huff_lengthlist_line_256x7_1sub2[] = {
  114872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  114873. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  114874. };
  114875. static static_codebook _huff_book_line_256x7_1sub2 = {
  114876. 1, 25,
  114877. _huff_lengthlist_line_256x7_1sub2,
  114878. 0, 0, 0, 0, 0,
  114879. NULL,
  114880. NULL,
  114881. NULL,
  114882. NULL,
  114883. 0
  114884. };
  114885. static long _huff_lengthlist_line_256x7_1sub3[] = {
  114886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  114888. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  114889. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  114890. };
  114891. static static_codebook _huff_book_line_256x7_1sub3 = {
  114892. 1, 64,
  114893. _huff_lengthlist_line_256x7_1sub3,
  114894. 0, 0, 0, 0, 0,
  114895. NULL,
  114896. NULL,
  114897. NULL,
  114898. NULL,
  114899. 0
  114900. };
  114901. static long _huff_lengthlist_line_256x7_class0[] = {
  114902. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  114903. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  114904. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  114905. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  114906. };
  114907. static static_codebook _huff_book_line_256x7_class0 = {
  114908. 1, 64,
  114909. _huff_lengthlist_line_256x7_class0,
  114910. 0, 0, 0, 0, 0,
  114911. NULL,
  114912. NULL,
  114913. NULL,
  114914. NULL,
  114915. 0
  114916. };
  114917. static long _huff_lengthlist_line_256x7_class1[] = {
  114918. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  114919. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  114920. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  114921. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  114922. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  114923. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  114924. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  114925. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  114926. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  114927. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  114928. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  114929. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  114930. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  114931. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  114932. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  114933. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  114934. };
  114935. static static_codebook _huff_book_line_256x7_class1 = {
  114936. 1, 256,
  114937. _huff_lengthlist_line_256x7_class1,
  114938. 0, 0, 0, 0, 0,
  114939. NULL,
  114940. NULL,
  114941. NULL,
  114942. NULL,
  114943. 0
  114944. };
  114945. static long _huff_lengthlist_line_512x17_0sub0[] = {
  114946. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  114947. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  114948. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  114949. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  114950. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  114951. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  114952. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  114953. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  114954. };
  114955. static static_codebook _huff_book_line_512x17_0sub0 = {
  114956. 1, 128,
  114957. _huff_lengthlist_line_512x17_0sub0,
  114958. 0, 0, 0, 0, 0,
  114959. NULL,
  114960. NULL,
  114961. NULL,
  114962. NULL,
  114963. 0
  114964. };
  114965. static long _huff_lengthlist_line_512x17_1sub0[] = {
  114966. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  114967. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  114968. };
  114969. static static_codebook _huff_book_line_512x17_1sub0 = {
  114970. 1, 32,
  114971. _huff_lengthlist_line_512x17_1sub0,
  114972. 0, 0, 0, 0, 0,
  114973. NULL,
  114974. NULL,
  114975. NULL,
  114976. NULL,
  114977. 0
  114978. };
  114979. static long _huff_lengthlist_line_512x17_1sub1[] = {
  114980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114982. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  114983. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  114984. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  114985. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  114986. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  114987. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  114988. };
  114989. static static_codebook _huff_book_line_512x17_1sub1 = {
  114990. 1, 128,
  114991. _huff_lengthlist_line_512x17_1sub1,
  114992. 0, 0, 0, 0, 0,
  114993. NULL,
  114994. NULL,
  114995. NULL,
  114996. NULL,
  114997. 0
  114998. };
  114999. static long _huff_lengthlist_line_512x17_2sub1[] = {
  115000. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  115001. 5, 3,
  115002. };
  115003. static static_codebook _huff_book_line_512x17_2sub1 = {
  115004. 1, 18,
  115005. _huff_lengthlist_line_512x17_2sub1,
  115006. 0, 0, 0, 0, 0,
  115007. NULL,
  115008. NULL,
  115009. NULL,
  115010. NULL,
  115011. 0
  115012. };
  115013. static long _huff_lengthlist_line_512x17_2sub2[] = {
  115014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115015. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  115016. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  115017. 9, 8,
  115018. };
  115019. static static_codebook _huff_book_line_512x17_2sub2 = {
  115020. 1, 50,
  115021. _huff_lengthlist_line_512x17_2sub2,
  115022. 0, 0, 0, 0, 0,
  115023. NULL,
  115024. NULL,
  115025. NULL,
  115026. NULL,
  115027. 0
  115028. };
  115029. static long _huff_lengthlist_line_512x17_2sub3[] = {
  115030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115033. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  115034. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  115035. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115036. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115037. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115038. };
  115039. static static_codebook _huff_book_line_512x17_2sub3 = {
  115040. 1, 128,
  115041. _huff_lengthlist_line_512x17_2sub3,
  115042. 0, 0, 0, 0, 0,
  115043. NULL,
  115044. NULL,
  115045. NULL,
  115046. NULL,
  115047. 0
  115048. };
  115049. static long _huff_lengthlist_line_512x17_3sub1[] = {
  115050. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  115051. 5, 5,
  115052. };
  115053. static static_codebook _huff_book_line_512x17_3sub1 = {
  115054. 1, 18,
  115055. _huff_lengthlist_line_512x17_3sub1,
  115056. 0, 0, 0, 0, 0,
  115057. NULL,
  115058. NULL,
  115059. NULL,
  115060. NULL,
  115061. 0
  115062. };
  115063. static long _huff_lengthlist_line_512x17_3sub2[] = {
  115064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115065. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  115066. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  115067. 11,14,
  115068. };
  115069. static static_codebook _huff_book_line_512x17_3sub2 = {
  115070. 1, 50,
  115071. _huff_lengthlist_line_512x17_3sub2,
  115072. 0, 0, 0, 0, 0,
  115073. NULL,
  115074. NULL,
  115075. NULL,
  115076. NULL,
  115077. 0
  115078. };
  115079. static long _huff_lengthlist_line_512x17_3sub3[] = {
  115080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115083. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  115084. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115085. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115086. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115087. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115088. };
  115089. static static_codebook _huff_book_line_512x17_3sub3 = {
  115090. 1, 128,
  115091. _huff_lengthlist_line_512x17_3sub3,
  115092. 0, 0, 0, 0, 0,
  115093. NULL,
  115094. NULL,
  115095. NULL,
  115096. NULL,
  115097. 0
  115098. };
  115099. static long _huff_lengthlist_line_512x17_class1[] = {
  115100. 1, 2, 3, 6, 5, 4, 7, 7,
  115101. };
  115102. static static_codebook _huff_book_line_512x17_class1 = {
  115103. 1, 8,
  115104. _huff_lengthlist_line_512x17_class1,
  115105. 0, 0, 0, 0, 0,
  115106. NULL,
  115107. NULL,
  115108. NULL,
  115109. NULL,
  115110. 0
  115111. };
  115112. static long _huff_lengthlist_line_512x17_class2[] = {
  115113. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  115114. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  115115. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  115116. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  115117. };
  115118. static static_codebook _huff_book_line_512x17_class2 = {
  115119. 1, 64,
  115120. _huff_lengthlist_line_512x17_class2,
  115121. 0, 0, 0, 0, 0,
  115122. NULL,
  115123. NULL,
  115124. NULL,
  115125. NULL,
  115126. 0
  115127. };
  115128. static long _huff_lengthlist_line_512x17_class3[] = {
  115129. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  115130. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  115131. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  115132. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  115133. };
  115134. static static_codebook _huff_book_line_512x17_class3 = {
  115135. 1, 64,
  115136. _huff_lengthlist_line_512x17_class3,
  115137. 0, 0, 0, 0, 0,
  115138. NULL,
  115139. NULL,
  115140. NULL,
  115141. NULL,
  115142. 0
  115143. };
  115144. static long _huff_lengthlist_line_128x4_class0[] = {
  115145. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  115146. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  115147. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  115148. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  115149. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  115150. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  115151. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  115152. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  115153. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  115154. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  115155. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  115156. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  115157. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  115158. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  115159. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  115160. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  115161. };
  115162. static static_codebook _huff_book_line_128x4_class0 = {
  115163. 1, 256,
  115164. _huff_lengthlist_line_128x4_class0,
  115165. 0, 0, 0, 0, 0,
  115166. NULL,
  115167. NULL,
  115168. NULL,
  115169. NULL,
  115170. 0
  115171. };
  115172. static long _huff_lengthlist_line_128x4_0sub0[] = {
  115173. 2, 2, 2, 2,
  115174. };
  115175. static static_codebook _huff_book_line_128x4_0sub0 = {
  115176. 1, 4,
  115177. _huff_lengthlist_line_128x4_0sub0,
  115178. 0, 0, 0, 0, 0,
  115179. NULL,
  115180. NULL,
  115181. NULL,
  115182. NULL,
  115183. 0
  115184. };
  115185. static long _huff_lengthlist_line_128x4_0sub1[] = {
  115186. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  115187. };
  115188. static static_codebook _huff_book_line_128x4_0sub1 = {
  115189. 1, 10,
  115190. _huff_lengthlist_line_128x4_0sub1,
  115191. 0, 0, 0, 0, 0,
  115192. NULL,
  115193. NULL,
  115194. NULL,
  115195. NULL,
  115196. 0
  115197. };
  115198. static long _huff_lengthlist_line_128x4_0sub2[] = {
  115199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  115200. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  115201. };
  115202. static static_codebook _huff_book_line_128x4_0sub2 = {
  115203. 1, 25,
  115204. _huff_lengthlist_line_128x4_0sub2,
  115205. 0, 0, 0, 0, 0,
  115206. NULL,
  115207. NULL,
  115208. NULL,
  115209. NULL,
  115210. 0
  115211. };
  115212. static long _huff_lengthlist_line_128x4_0sub3[] = {
  115213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  115215. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  115216. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  115217. };
  115218. static static_codebook _huff_book_line_128x4_0sub3 = {
  115219. 1, 64,
  115220. _huff_lengthlist_line_128x4_0sub3,
  115221. 0, 0, 0, 0, 0,
  115222. NULL,
  115223. NULL,
  115224. NULL,
  115225. NULL,
  115226. 0
  115227. };
  115228. static long _huff_lengthlist_line_256x4_class0[] = {
  115229. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  115230. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  115231. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  115232. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  115233. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  115234. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  115235. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  115236. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  115237. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  115238. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  115239. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  115240. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  115241. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  115242. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  115243. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  115244. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  115245. };
  115246. static static_codebook _huff_book_line_256x4_class0 = {
  115247. 1, 256,
  115248. _huff_lengthlist_line_256x4_class0,
  115249. 0, 0, 0, 0, 0,
  115250. NULL,
  115251. NULL,
  115252. NULL,
  115253. NULL,
  115254. 0
  115255. };
  115256. static long _huff_lengthlist_line_256x4_0sub0[] = {
  115257. 2, 2, 2, 2,
  115258. };
  115259. static static_codebook _huff_book_line_256x4_0sub0 = {
  115260. 1, 4,
  115261. _huff_lengthlist_line_256x4_0sub0,
  115262. 0, 0, 0, 0, 0,
  115263. NULL,
  115264. NULL,
  115265. NULL,
  115266. NULL,
  115267. 0
  115268. };
  115269. static long _huff_lengthlist_line_256x4_0sub1[] = {
  115270. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  115271. };
  115272. static static_codebook _huff_book_line_256x4_0sub1 = {
  115273. 1, 10,
  115274. _huff_lengthlist_line_256x4_0sub1,
  115275. 0, 0, 0, 0, 0,
  115276. NULL,
  115277. NULL,
  115278. NULL,
  115279. NULL,
  115280. 0
  115281. };
  115282. static long _huff_lengthlist_line_256x4_0sub2[] = {
  115283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  115284. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  115285. };
  115286. static static_codebook _huff_book_line_256x4_0sub2 = {
  115287. 1, 25,
  115288. _huff_lengthlist_line_256x4_0sub2,
  115289. 0, 0, 0, 0, 0,
  115290. NULL,
  115291. NULL,
  115292. NULL,
  115293. NULL,
  115294. 0
  115295. };
  115296. static long _huff_lengthlist_line_256x4_0sub3[] = {
  115297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  115299. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  115300. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  115301. };
  115302. static static_codebook _huff_book_line_256x4_0sub3 = {
  115303. 1, 64,
  115304. _huff_lengthlist_line_256x4_0sub3,
  115305. 0, 0, 0, 0, 0,
  115306. NULL,
  115307. NULL,
  115308. NULL,
  115309. NULL,
  115310. 0
  115311. };
  115312. static long _huff_lengthlist_line_128x7_class0[] = {
  115313. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  115314. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  115315. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  115316. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  115317. };
  115318. static static_codebook _huff_book_line_128x7_class0 = {
  115319. 1, 64,
  115320. _huff_lengthlist_line_128x7_class0,
  115321. 0, 0, 0, 0, 0,
  115322. NULL,
  115323. NULL,
  115324. NULL,
  115325. NULL,
  115326. 0
  115327. };
  115328. static long _huff_lengthlist_line_128x7_class1[] = {
  115329. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  115330. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  115331. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  115332. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  115333. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  115334. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  115335. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  115336. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  115337. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  115338. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  115339. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  115340. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  115341. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  115342. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  115343. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  115344. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  115345. };
  115346. static static_codebook _huff_book_line_128x7_class1 = {
  115347. 1, 256,
  115348. _huff_lengthlist_line_128x7_class1,
  115349. 0, 0, 0, 0, 0,
  115350. NULL,
  115351. NULL,
  115352. NULL,
  115353. NULL,
  115354. 0
  115355. };
  115356. static long _huff_lengthlist_line_128x7_0sub1[] = {
  115357. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  115358. };
  115359. static static_codebook _huff_book_line_128x7_0sub1 = {
  115360. 1, 9,
  115361. _huff_lengthlist_line_128x7_0sub1,
  115362. 0, 0, 0, 0, 0,
  115363. NULL,
  115364. NULL,
  115365. NULL,
  115366. NULL,
  115367. 0
  115368. };
  115369. static long _huff_lengthlist_line_128x7_0sub2[] = {
  115370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  115371. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  115372. };
  115373. static static_codebook _huff_book_line_128x7_0sub2 = {
  115374. 1, 25,
  115375. _huff_lengthlist_line_128x7_0sub2,
  115376. 0, 0, 0, 0, 0,
  115377. NULL,
  115378. NULL,
  115379. NULL,
  115380. NULL,
  115381. 0
  115382. };
  115383. static long _huff_lengthlist_line_128x7_0sub3[] = {
  115384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  115386. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115387. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  115388. };
  115389. static static_codebook _huff_book_line_128x7_0sub3 = {
  115390. 1, 64,
  115391. _huff_lengthlist_line_128x7_0sub3,
  115392. 0, 0, 0, 0, 0,
  115393. NULL,
  115394. NULL,
  115395. NULL,
  115396. NULL,
  115397. 0
  115398. };
  115399. static long _huff_lengthlist_line_128x7_1sub1[] = {
  115400. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  115401. };
  115402. static static_codebook _huff_book_line_128x7_1sub1 = {
  115403. 1, 9,
  115404. _huff_lengthlist_line_128x7_1sub1,
  115405. 0, 0, 0, 0, 0,
  115406. NULL,
  115407. NULL,
  115408. NULL,
  115409. NULL,
  115410. 0
  115411. };
  115412. static long _huff_lengthlist_line_128x7_1sub2[] = {
  115413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  115414. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  115415. };
  115416. static static_codebook _huff_book_line_128x7_1sub2 = {
  115417. 1, 25,
  115418. _huff_lengthlist_line_128x7_1sub2,
  115419. 0, 0, 0, 0, 0,
  115420. NULL,
  115421. NULL,
  115422. NULL,
  115423. NULL,
  115424. 0
  115425. };
  115426. static long _huff_lengthlist_line_128x7_1sub3[] = {
  115427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  115429. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  115430. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  115431. };
  115432. static static_codebook _huff_book_line_128x7_1sub3 = {
  115433. 1, 64,
  115434. _huff_lengthlist_line_128x7_1sub3,
  115435. 0, 0, 0, 0, 0,
  115436. NULL,
  115437. NULL,
  115438. NULL,
  115439. NULL,
  115440. 0
  115441. };
  115442. static long _huff_lengthlist_line_128x11_class1[] = {
  115443. 1, 6, 3, 7, 2, 4, 5, 7,
  115444. };
  115445. static static_codebook _huff_book_line_128x11_class1 = {
  115446. 1, 8,
  115447. _huff_lengthlist_line_128x11_class1,
  115448. 0, 0, 0, 0, 0,
  115449. NULL,
  115450. NULL,
  115451. NULL,
  115452. NULL,
  115453. 0
  115454. };
  115455. static long _huff_lengthlist_line_128x11_class2[] = {
  115456. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  115457. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  115458. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  115459. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  115460. };
  115461. static static_codebook _huff_book_line_128x11_class2 = {
  115462. 1, 64,
  115463. _huff_lengthlist_line_128x11_class2,
  115464. 0, 0, 0, 0, 0,
  115465. NULL,
  115466. NULL,
  115467. NULL,
  115468. NULL,
  115469. 0
  115470. };
  115471. static long _huff_lengthlist_line_128x11_class3[] = {
  115472. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  115473. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  115474. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  115475. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  115476. };
  115477. static static_codebook _huff_book_line_128x11_class3 = {
  115478. 1, 64,
  115479. _huff_lengthlist_line_128x11_class3,
  115480. 0, 0, 0, 0, 0,
  115481. NULL,
  115482. NULL,
  115483. NULL,
  115484. NULL,
  115485. 0
  115486. };
  115487. static long _huff_lengthlist_line_128x11_0sub0[] = {
  115488. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115489. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  115490. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  115491. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  115492. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  115493. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  115494. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  115495. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  115496. };
  115497. static static_codebook _huff_book_line_128x11_0sub0 = {
  115498. 1, 128,
  115499. _huff_lengthlist_line_128x11_0sub0,
  115500. 0, 0, 0, 0, 0,
  115501. NULL,
  115502. NULL,
  115503. NULL,
  115504. NULL,
  115505. 0
  115506. };
  115507. static long _huff_lengthlist_line_128x11_1sub0[] = {
  115508. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  115509. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  115510. };
  115511. static static_codebook _huff_book_line_128x11_1sub0 = {
  115512. 1, 32,
  115513. _huff_lengthlist_line_128x11_1sub0,
  115514. 0, 0, 0, 0, 0,
  115515. NULL,
  115516. NULL,
  115517. NULL,
  115518. NULL,
  115519. 0
  115520. };
  115521. static long _huff_lengthlist_line_128x11_1sub1[] = {
  115522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115524. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  115525. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  115526. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  115527. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  115528. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  115529. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  115530. };
  115531. static static_codebook _huff_book_line_128x11_1sub1 = {
  115532. 1, 128,
  115533. _huff_lengthlist_line_128x11_1sub1,
  115534. 0, 0, 0, 0, 0,
  115535. NULL,
  115536. NULL,
  115537. NULL,
  115538. NULL,
  115539. 0
  115540. };
  115541. static long _huff_lengthlist_line_128x11_2sub1[] = {
  115542. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  115543. 5, 5,
  115544. };
  115545. static static_codebook _huff_book_line_128x11_2sub1 = {
  115546. 1, 18,
  115547. _huff_lengthlist_line_128x11_2sub1,
  115548. 0, 0, 0, 0, 0,
  115549. NULL,
  115550. NULL,
  115551. NULL,
  115552. NULL,
  115553. 0
  115554. };
  115555. static long _huff_lengthlist_line_128x11_2sub2[] = {
  115556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115557. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  115558. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  115559. 8,11,
  115560. };
  115561. static static_codebook _huff_book_line_128x11_2sub2 = {
  115562. 1, 50,
  115563. _huff_lengthlist_line_128x11_2sub2,
  115564. 0, 0, 0, 0, 0,
  115565. NULL,
  115566. NULL,
  115567. NULL,
  115568. NULL,
  115569. 0
  115570. };
  115571. static long _huff_lengthlist_line_128x11_2sub3[] = {
  115572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115575. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  115576. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115577. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115578. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115579. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115580. };
  115581. static static_codebook _huff_book_line_128x11_2sub3 = {
  115582. 1, 128,
  115583. _huff_lengthlist_line_128x11_2sub3,
  115584. 0, 0, 0, 0, 0,
  115585. NULL,
  115586. NULL,
  115587. NULL,
  115588. NULL,
  115589. 0
  115590. };
  115591. static long _huff_lengthlist_line_128x11_3sub1[] = {
  115592. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  115593. 5, 4,
  115594. };
  115595. static static_codebook _huff_book_line_128x11_3sub1 = {
  115596. 1, 18,
  115597. _huff_lengthlist_line_128x11_3sub1,
  115598. 0, 0, 0, 0, 0,
  115599. NULL,
  115600. NULL,
  115601. NULL,
  115602. NULL,
  115603. 0
  115604. };
  115605. static long _huff_lengthlist_line_128x11_3sub2[] = {
  115606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115607. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  115608. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  115609. 12, 6,
  115610. };
  115611. static static_codebook _huff_book_line_128x11_3sub2 = {
  115612. 1, 50,
  115613. _huff_lengthlist_line_128x11_3sub2,
  115614. 0, 0, 0, 0, 0,
  115615. NULL,
  115616. NULL,
  115617. NULL,
  115618. NULL,
  115619. 0
  115620. };
  115621. static long _huff_lengthlist_line_128x11_3sub3[] = {
  115622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115625. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  115626. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  115627. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115628. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115629. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  115630. };
  115631. static static_codebook _huff_book_line_128x11_3sub3 = {
  115632. 1, 128,
  115633. _huff_lengthlist_line_128x11_3sub3,
  115634. 0, 0, 0, 0, 0,
  115635. NULL,
  115636. NULL,
  115637. NULL,
  115638. NULL,
  115639. 0
  115640. };
  115641. static long _huff_lengthlist_line_128x17_class1[] = {
  115642. 1, 3, 4, 7, 2, 5, 6, 7,
  115643. };
  115644. static static_codebook _huff_book_line_128x17_class1 = {
  115645. 1, 8,
  115646. _huff_lengthlist_line_128x17_class1,
  115647. 0, 0, 0, 0, 0,
  115648. NULL,
  115649. NULL,
  115650. NULL,
  115651. NULL,
  115652. 0
  115653. };
  115654. static long _huff_lengthlist_line_128x17_class2[] = {
  115655. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  115656. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  115657. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  115658. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  115659. };
  115660. static static_codebook _huff_book_line_128x17_class2 = {
  115661. 1, 64,
  115662. _huff_lengthlist_line_128x17_class2,
  115663. 0, 0, 0, 0, 0,
  115664. NULL,
  115665. NULL,
  115666. NULL,
  115667. NULL,
  115668. 0
  115669. };
  115670. static long _huff_lengthlist_line_128x17_class3[] = {
  115671. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  115672. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  115673. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  115674. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  115675. };
  115676. static static_codebook _huff_book_line_128x17_class3 = {
  115677. 1, 64,
  115678. _huff_lengthlist_line_128x17_class3,
  115679. 0, 0, 0, 0, 0,
  115680. NULL,
  115681. NULL,
  115682. NULL,
  115683. NULL,
  115684. 0
  115685. };
  115686. static long _huff_lengthlist_line_128x17_0sub0[] = {
  115687. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115688. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  115689. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  115690. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  115691. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  115692. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  115693. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  115694. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  115695. };
  115696. static static_codebook _huff_book_line_128x17_0sub0 = {
  115697. 1, 128,
  115698. _huff_lengthlist_line_128x17_0sub0,
  115699. 0, 0, 0, 0, 0,
  115700. NULL,
  115701. NULL,
  115702. NULL,
  115703. NULL,
  115704. 0
  115705. };
  115706. static long _huff_lengthlist_line_128x17_1sub0[] = {
  115707. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  115708. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  115709. };
  115710. static static_codebook _huff_book_line_128x17_1sub0 = {
  115711. 1, 32,
  115712. _huff_lengthlist_line_128x17_1sub0,
  115713. 0, 0, 0, 0, 0,
  115714. NULL,
  115715. NULL,
  115716. NULL,
  115717. NULL,
  115718. 0
  115719. };
  115720. static long _huff_lengthlist_line_128x17_1sub1[] = {
  115721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115723. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  115724. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  115725. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  115726. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  115727. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  115728. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  115729. };
  115730. static static_codebook _huff_book_line_128x17_1sub1 = {
  115731. 1, 128,
  115732. _huff_lengthlist_line_128x17_1sub1,
  115733. 0, 0, 0, 0, 0,
  115734. NULL,
  115735. NULL,
  115736. NULL,
  115737. NULL,
  115738. 0
  115739. };
  115740. static long _huff_lengthlist_line_128x17_2sub1[] = {
  115741. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  115742. 9, 4,
  115743. };
  115744. static static_codebook _huff_book_line_128x17_2sub1 = {
  115745. 1, 18,
  115746. _huff_lengthlist_line_128x17_2sub1,
  115747. 0, 0, 0, 0, 0,
  115748. NULL,
  115749. NULL,
  115750. NULL,
  115751. NULL,
  115752. 0
  115753. };
  115754. static long _huff_lengthlist_line_128x17_2sub2[] = {
  115755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115756. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  115757. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  115758. 13,13,
  115759. };
  115760. static static_codebook _huff_book_line_128x17_2sub2 = {
  115761. 1, 50,
  115762. _huff_lengthlist_line_128x17_2sub2,
  115763. 0, 0, 0, 0, 0,
  115764. NULL,
  115765. NULL,
  115766. NULL,
  115767. NULL,
  115768. 0
  115769. };
  115770. static long _huff_lengthlist_line_128x17_2sub3[] = {
  115771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115774. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115775. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  115776. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  115777. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  115778. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  115779. };
  115780. static static_codebook _huff_book_line_128x17_2sub3 = {
  115781. 1, 128,
  115782. _huff_lengthlist_line_128x17_2sub3,
  115783. 0, 0, 0, 0, 0,
  115784. NULL,
  115785. NULL,
  115786. NULL,
  115787. NULL,
  115788. 0
  115789. };
  115790. static long _huff_lengthlist_line_128x17_3sub1[] = {
  115791. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  115792. 6, 4,
  115793. };
  115794. static static_codebook _huff_book_line_128x17_3sub1 = {
  115795. 1, 18,
  115796. _huff_lengthlist_line_128x17_3sub1,
  115797. 0, 0, 0, 0, 0,
  115798. NULL,
  115799. NULL,
  115800. NULL,
  115801. NULL,
  115802. 0
  115803. };
  115804. static long _huff_lengthlist_line_128x17_3sub2[] = {
  115805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115806. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  115807. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  115808. 10, 8,
  115809. };
  115810. static static_codebook _huff_book_line_128x17_3sub2 = {
  115811. 1, 50,
  115812. _huff_lengthlist_line_128x17_3sub2,
  115813. 0, 0, 0, 0, 0,
  115814. NULL,
  115815. NULL,
  115816. NULL,
  115817. NULL,
  115818. 0
  115819. };
  115820. static long _huff_lengthlist_line_128x17_3sub3[] = {
  115821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115824. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  115825. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  115826. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115827. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115828. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115829. };
  115830. static static_codebook _huff_book_line_128x17_3sub3 = {
  115831. 1, 128,
  115832. _huff_lengthlist_line_128x17_3sub3,
  115833. 0, 0, 0, 0, 0,
  115834. NULL,
  115835. NULL,
  115836. NULL,
  115837. NULL,
  115838. 0
  115839. };
  115840. static long _huff_lengthlist_line_1024x27_class1[] = {
  115841. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  115842. };
  115843. static static_codebook _huff_book_line_1024x27_class1 = {
  115844. 1, 16,
  115845. _huff_lengthlist_line_1024x27_class1,
  115846. 0, 0, 0, 0, 0,
  115847. NULL,
  115848. NULL,
  115849. NULL,
  115850. NULL,
  115851. 0
  115852. };
  115853. static long _huff_lengthlist_line_1024x27_class2[] = {
  115854. 1, 4, 2, 6, 3, 7, 5, 7,
  115855. };
  115856. static static_codebook _huff_book_line_1024x27_class2 = {
  115857. 1, 8,
  115858. _huff_lengthlist_line_1024x27_class2,
  115859. 0, 0, 0, 0, 0,
  115860. NULL,
  115861. NULL,
  115862. NULL,
  115863. NULL,
  115864. 0
  115865. };
  115866. static long _huff_lengthlist_line_1024x27_class3[] = {
  115867. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  115868. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  115869. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  115870. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  115871. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  115872. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  115873. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  115874. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  115875. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  115876. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  115877. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  115878. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  115879. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  115880. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  115881. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  115882. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  115883. };
  115884. static static_codebook _huff_book_line_1024x27_class3 = {
  115885. 1, 256,
  115886. _huff_lengthlist_line_1024x27_class3,
  115887. 0, 0, 0, 0, 0,
  115888. NULL,
  115889. NULL,
  115890. NULL,
  115891. NULL,
  115892. 0
  115893. };
  115894. static long _huff_lengthlist_line_1024x27_class4[] = {
  115895. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  115896. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  115897. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  115898. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  115899. };
  115900. static static_codebook _huff_book_line_1024x27_class4 = {
  115901. 1, 64,
  115902. _huff_lengthlist_line_1024x27_class4,
  115903. 0, 0, 0, 0, 0,
  115904. NULL,
  115905. NULL,
  115906. NULL,
  115907. NULL,
  115908. 0
  115909. };
  115910. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  115911. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115912. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  115913. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  115914. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  115915. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  115916. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  115917. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  115918. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  115919. };
  115920. static static_codebook _huff_book_line_1024x27_0sub0 = {
  115921. 1, 128,
  115922. _huff_lengthlist_line_1024x27_0sub0,
  115923. 0, 0, 0, 0, 0,
  115924. NULL,
  115925. NULL,
  115926. NULL,
  115927. NULL,
  115928. 0
  115929. };
  115930. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  115931. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  115932. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  115933. };
  115934. static static_codebook _huff_book_line_1024x27_1sub0 = {
  115935. 1, 32,
  115936. _huff_lengthlist_line_1024x27_1sub0,
  115937. 0, 0, 0, 0, 0,
  115938. NULL,
  115939. NULL,
  115940. NULL,
  115941. NULL,
  115942. 0
  115943. };
  115944. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  115945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115947. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  115948. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  115949. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  115950. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  115951. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  115952. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  115953. };
  115954. static static_codebook _huff_book_line_1024x27_1sub1 = {
  115955. 1, 128,
  115956. _huff_lengthlist_line_1024x27_1sub1,
  115957. 0, 0, 0, 0, 0,
  115958. NULL,
  115959. NULL,
  115960. NULL,
  115961. NULL,
  115962. 0
  115963. };
  115964. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  115965. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115966. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  115967. };
  115968. static static_codebook _huff_book_line_1024x27_2sub0 = {
  115969. 1, 32,
  115970. _huff_lengthlist_line_1024x27_2sub0,
  115971. 0, 0, 0, 0, 0,
  115972. NULL,
  115973. NULL,
  115974. NULL,
  115975. NULL,
  115976. 0
  115977. };
  115978. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  115979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115981. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  115982. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  115983. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  115984. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  115985. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  115986. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  115987. };
  115988. static static_codebook _huff_book_line_1024x27_2sub1 = {
  115989. 1, 128,
  115990. _huff_lengthlist_line_1024x27_2sub1,
  115991. 0, 0, 0, 0, 0,
  115992. NULL,
  115993. NULL,
  115994. NULL,
  115995. NULL,
  115996. 0
  115997. };
  115998. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  115999. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  116000. 5, 5,
  116001. };
  116002. static static_codebook _huff_book_line_1024x27_3sub1 = {
  116003. 1, 18,
  116004. _huff_lengthlist_line_1024x27_3sub1,
  116005. 0, 0, 0, 0, 0,
  116006. NULL,
  116007. NULL,
  116008. NULL,
  116009. NULL,
  116010. 0
  116011. };
  116012. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  116013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116014. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  116015. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  116016. 9,11,
  116017. };
  116018. static static_codebook _huff_book_line_1024x27_3sub2 = {
  116019. 1, 50,
  116020. _huff_lengthlist_line_1024x27_3sub2,
  116021. 0, 0, 0, 0, 0,
  116022. NULL,
  116023. NULL,
  116024. NULL,
  116025. NULL,
  116026. 0
  116027. };
  116028. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  116029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116032. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  116033. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  116034. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  116035. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  116036. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  116037. };
  116038. static static_codebook _huff_book_line_1024x27_3sub3 = {
  116039. 1, 128,
  116040. _huff_lengthlist_line_1024x27_3sub3,
  116041. 0, 0, 0, 0, 0,
  116042. NULL,
  116043. NULL,
  116044. NULL,
  116045. NULL,
  116046. 0
  116047. };
  116048. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  116049. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  116050. 5, 4,
  116051. };
  116052. static static_codebook _huff_book_line_1024x27_4sub1 = {
  116053. 1, 18,
  116054. _huff_lengthlist_line_1024x27_4sub1,
  116055. 0, 0, 0, 0, 0,
  116056. NULL,
  116057. NULL,
  116058. NULL,
  116059. NULL,
  116060. 0
  116061. };
  116062. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  116063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116064. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  116065. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  116066. 9,12,
  116067. };
  116068. static static_codebook _huff_book_line_1024x27_4sub2 = {
  116069. 1, 50,
  116070. _huff_lengthlist_line_1024x27_4sub2,
  116071. 0, 0, 0, 0, 0,
  116072. NULL,
  116073. NULL,
  116074. NULL,
  116075. NULL,
  116076. 0
  116077. };
  116078. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  116079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116082. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  116083. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  116084. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  116085. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  116086. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  116087. };
  116088. static static_codebook _huff_book_line_1024x27_4sub3 = {
  116089. 1, 128,
  116090. _huff_lengthlist_line_1024x27_4sub3,
  116091. 0, 0, 0, 0, 0,
  116092. NULL,
  116093. NULL,
  116094. NULL,
  116095. NULL,
  116096. 0
  116097. };
  116098. static long _huff_lengthlist_line_2048x27_class1[] = {
  116099. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  116100. };
  116101. static static_codebook _huff_book_line_2048x27_class1 = {
  116102. 1, 16,
  116103. _huff_lengthlist_line_2048x27_class1,
  116104. 0, 0, 0, 0, 0,
  116105. NULL,
  116106. NULL,
  116107. NULL,
  116108. NULL,
  116109. 0
  116110. };
  116111. static long _huff_lengthlist_line_2048x27_class2[] = {
  116112. 1, 2, 3, 6, 4, 7, 5, 7,
  116113. };
  116114. static static_codebook _huff_book_line_2048x27_class2 = {
  116115. 1, 8,
  116116. _huff_lengthlist_line_2048x27_class2,
  116117. 0, 0, 0, 0, 0,
  116118. NULL,
  116119. NULL,
  116120. NULL,
  116121. NULL,
  116122. 0
  116123. };
  116124. static long _huff_lengthlist_line_2048x27_class3[] = {
  116125. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  116126. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  116127. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  116128. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  116129. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  116130. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  116131. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  116132. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  116133. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  116134. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  116135. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  116136. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  116137. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  116138. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  116139. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  116140. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  116141. };
  116142. static static_codebook _huff_book_line_2048x27_class3 = {
  116143. 1, 256,
  116144. _huff_lengthlist_line_2048x27_class3,
  116145. 0, 0, 0, 0, 0,
  116146. NULL,
  116147. NULL,
  116148. NULL,
  116149. NULL,
  116150. 0
  116151. };
  116152. static long _huff_lengthlist_line_2048x27_class4[] = {
  116153. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  116154. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  116155. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  116156. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  116157. };
  116158. static static_codebook _huff_book_line_2048x27_class4 = {
  116159. 1, 64,
  116160. _huff_lengthlist_line_2048x27_class4,
  116161. 0, 0, 0, 0, 0,
  116162. NULL,
  116163. NULL,
  116164. NULL,
  116165. NULL,
  116166. 0
  116167. };
  116168. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  116169. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  116170. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  116171. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  116172. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  116173. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  116174. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  116175. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  116176. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  116177. };
  116178. static static_codebook _huff_book_line_2048x27_0sub0 = {
  116179. 1, 128,
  116180. _huff_lengthlist_line_2048x27_0sub0,
  116181. 0, 0, 0, 0, 0,
  116182. NULL,
  116183. NULL,
  116184. NULL,
  116185. NULL,
  116186. 0
  116187. };
  116188. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  116189. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  116190. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  116191. };
  116192. static static_codebook _huff_book_line_2048x27_1sub0 = {
  116193. 1, 32,
  116194. _huff_lengthlist_line_2048x27_1sub0,
  116195. 0, 0, 0, 0, 0,
  116196. NULL,
  116197. NULL,
  116198. NULL,
  116199. NULL,
  116200. 0
  116201. };
  116202. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  116203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116205. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  116206. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  116207. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  116208. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  116209. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  116210. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  116211. };
  116212. static static_codebook _huff_book_line_2048x27_1sub1 = {
  116213. 1, 128,
  116214. _huff_lengthlist_line_2048x27_1sub1,
  116215. 0, 0, 0, 0, 0,
  116216. NULL,
  116217. NULL,
  116218. NULL,
  116219. NULL,
  116220. 0
  116221. };
  116222. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  116223. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  116224. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  116225. };
  116226. static static_codebook _huff_book_line_2048x27_2sub0 = {
  116227. 1, 32,
  116228. _huff_lengthlist_line_2048x27_2sub0,
  116229. 0, 0, 0, 0, 0,
  116230. NULL,
  116231. NULL,
  116232. NULL,
  116233. NULL,
  116234. 0
  116235. };
  116236. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  116237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116239. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  116240. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  116241. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  116242. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  116243. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  116244. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  116245. };
  116246. static static_codebook _huff_book_line_2048x27_2sub1 = {
  116247. 1, 128,
  116248. _huff_lengthlist_line_2048x27_2sub1,
  116249. 0, 0, 0, 0, 0,
  116250. NULL,
  116251. NULL,
  116252. NULL,
  116253. NULL,
  116254. 0
  116255. };
  116256. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  116257. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  116258. 5, 5,
  116259. };
  116260. static static_codebook _huff_book_line_2048x27_3sub1 = {
  116261. 1, 18,
  116262. _huff_lengthlist_line_2048x27_3sub1,
  116263. 0, 0, 0, 0, 0,
  116264. NULL,
  116265. NULL,
  116266. NULL,
  116267. NULL,
  116268. 0
  116269. };
  116270. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  116271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116272. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  116273. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  116274. 10,12,
  116275. };
  116276. static static_codebook _huff_book_line_2048x27_3sub2 = {
  116277. 1, 50,
  116278. _huff_lengthlist_line_2048x27_3sub2,
  116279. 0, 0, 0, 0, 0,
  116280. NULL,
  116281. NULL,
  116282. NULL,
  116283. NULL,
  116284. 0
  116285. };
  116286. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  116287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116290. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  116291. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116292. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116293. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116294. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116295. };
  116296. static static_codebook _huff_book_line_2048x27_3sub3 = {
  116297. 1, 128,
  116298. _huff_lengthlist_line_2048x27_3sub3,
  116299. 0, 0, 0, 0, 0,
  116300. NULL,
  116301. NULL,
  116302. NULL,
  116303. NULL,
  116304. 0
  116305. };
  116306. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  116307. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  116308. 4, 5,
  116309. };
  116310. static static_codebook _huff_book_line_2048x27_4sub1 = {
  116311. 1, 18,
  116312. _huff_lengthlist_line_2048x27_4sub1,
  116313. 0, 0, 0, 0, 0,
  116314. NULL,
  116315. NULL,
  116316. NULL,
  116317. NULL,
  116318. 0
  116319. };
  116320. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  116321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116322. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  116323. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  116324. 10,10,
  116325. };
  116326. static static_codebook _huff_book_line_2048x27_4sub2 = {
  116327. 1, 50,
  116328. _huff_lengthlist_line_2048x27_4sub2,
  116329. 0, 0, 0, 0, 0,
  116330. NULL,
  116331. NULL,
  116332. NULL,
  116333. NULL,
  116334. 0
  116335. };
  116336. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  116337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116340. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  116341. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  116342. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116343. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116344. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  116345. };
  116346. static static_codebook _huff_book_line_2048x27_4sub3 = {
  116347. 1, 128,
  116348. _huff_lengthlist_line_2048x27_4sub3,
  116349. 0, 0, 0, 0, 0,
  116350. NULL,
  116351. NULL,
  116352. NULL,
  116353. NULL,
  116354. 0
  116355. };
  116356. static long _huff_lengthlist_line_256x4low_class0[] = {
  116357. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  116358. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  116359. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  116360. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  116361. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  116362. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  116363. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  116364. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  116365. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  116366. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  116367. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  116368. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  116369. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  116370. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  116371. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  116372. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  116373. };
  116374. static static_codebook _huff_book_line_256x4low_class0 = {
  116375. 1, 256,
  116376. _huff_lengthlist_line_256x4low_class0,
  116377. 0, 0, 0, 0, 0,
  116378. NULL,
  116379. NULL,
  116380. NULL,
  116381. NULL,
  116382. 0
  116383. };
  116384. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  116385. 1, 3, 2, 3,
  116386. };
  116387. static static_codebook _huff_book_line_256x4low_0sub0 = {
  116388. 1, 4,
  116389. _huff_lengthlist_line_256x4low_0sub0,
  116390. 0, 0, 0, 0, 0,
  116391. NULL,
  116392. NULL,
  116393. NULL,
  116394. NULL,
  116395. 0
  116396. };
  116397. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  116398. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  116399. };
  116400. static static_codebook _huff_book_line_256x4low_0sub1 = {
  116401. 1, 10,
  116402. _huff_lengthlist_line_256x4low_0sub1,
  116403. 0, 0, 0, 0, 0,
  116404. NULL,
  116405. NULL,
  116406. NULL,
  116407. NULL,
  116408. 0
  116409. };
  116410. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  116411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  116412. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  116413. };
  116414. static static_codebook _huff_book_line_256x4low_0sub2 = {
  116415. 1, 25,
  116416. _huff_lengthlist_line_256x4low_0sub2,
  116417. 0, 0, 0, 0, 0,
  116418. NULL,
  116419. NULL,
  116420. NULL,
  116421. NULL,
  116422. 0
  116423. };
  116424. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  116425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  116427. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  116428. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  116429. };
  116430. static static_codebook _huff_book_line_256x4low_0sub3 = {
  116431. 1, 64,
  116432. _huff_lengthlist_line_256x4low_0sub3,
  116433. 0, 0, 0, 0, 0,
  116434. NULL,
  116435. NULL,
  116436. NULL,
  116437. NULL,
  116438. 0
  116439. };
  116440. /********* End of inlined file: floor_books.h *********/
  116441. static static_codebook *_floor_128x4_books[]={
  116442. &_huff_book_line_128x4_class0,
  116443. &_huff_book_line_128x4_0sub0,
  116444. &_huff_book_line_128x4_0sub1,
  116445. &_huff_book_line_128x4_0sub2,
  116446. &_huff_book_line_128x4_0sub3,
  116447. };
  116448. static static_codebook *_floor_256x4_books[]={
  116449. &_huff_book_line_256x4_class0,
  116450. &_huff_book_line_256x4_0sub0,
  116451. &_huff_book_line_256x4_0sub1,
  116452. &_huff_book_line_256x4_0sub2,
  116453. &_huff_book_line_256x4_0sub3,
  116454. };
  116455. static static_codebook *_floor_128x7_books[]={
  116456. &_huff_book_line_128x7_class0,
  116457. &_huff_book_line_128x7_class1,
  116458. &_huff_book_line_128x7_0sub1,
  116459. &_huff_book_line_128x7_0sub2,
  116460. &_huff_book_line_128x7_0sub3,
  116461. &_huff_book_line_128x7_1sub1,
  116462. &_huff_book_line_128x7_1sub2,
  116463. &_huff_book_line_128x7_1sub3,
  116464. };
  116465. static static_codebook *_floor_256x7_books[]={
  116466. &_huff_book_line_256x7_class0,
  116467. &_huff_book_line_256x7_class1,
  116468. &_huff_book_line_256x7_0sub1,
  116469. &_huff_book_line_256x7_0sub2,
  116470. &_huff_book_line_256x7_0sub3,
  116471. &_huff_book_line_256x7_1sub1,
  116472. &_huff_book_line_256x7_1sub2,
  116473. &_huff_book_line_256x7_1sub3,
  116474. };
  116475. static static_codebook *_floor_128x11_books[]={
  116476. &_huff_book_line_128x11_class1,
  116477. &_huff_book_line_128x11_class2,
  116478. &_huff_book_line_128x11_class3,
  116479. &_huff_book_line_128x11_0sub0,
  116480. &_huff_book_line_128x11_1sub0,
  116481. &_huff_book_line_128x11_1sub1,
  116482. &_huff_book_line_128x11_2sub1,
  116483. &_huff_book_line_128x11_2sub2,
  116484. &_huff_book_line_128x11_2sub3,
  116485. &_huff_book_line_128x11_3sub1,
  116486. &_huff_book_line_128x11_3sub2,
  116487. &_huff_book_line_128x11_3sub3,
  116488. };
  116489. static static_codebook *_floor_128x17_books[]={
  116490. &_huff_book_line_128x17_class1,
  116491. &_huff_book_line_128x17_class2,
  116492. &_huff_book_line_128x17_class3,
  116493. &_huff_book_line_128x17_0sub0,
  116494. &_huff_book_line_128x17_1sub0,
  116495. &_huff_book_line_128x17_1sub1,
  116496. &_huff_book_line_128x17_2sub1,
  116497. &_huff_book_line_128x17_2sub2,
  116498. &_huff_book_line_128x17_2sub3,
  116499. &_huff_book_line_128x17_3sub1,
  116500. &_huff_book_line_128x17_3sub2,
  116501. &_huff_book_line_128x17_3sub3,
  116502. };
  116503. static static_codebook *_floor_256x4low_books[]={
  116504. &_huff_book_line_256x4low_class0,
  116505. &_huff_book_line_256x4low_0sub0,
  116506. &_huff_book_line_256x4low_0sub1,
  116507. &_huff_book_line_256x4low_0sub2,
  116508. &_huff_book_line_256x4low_0sub3,
  116509. };
  116510. static static_codebook *_floor_1024x27_books[]={
  116511. &_huff_book_line_1024x27_class1,
  116512. &_huff_book_line_1024x27_class2,
  116513. &_huff_book_line_1024x27_class3,
  116514. &_huff_book_line_1024x27_class4,
  116515. &_huff_book_line_1024x27_0sub0,
  116516. &_huff_book_line_1024x27_1sub0,
  116517. &_huff_book_line_1024x27_1sub1,
  116518. &_huff_book_line_1024x27_2sub0,
  116519. &_huff_book_line_1024x27_2sub1,
  116520. &_huff_book_line_1024x27_3sub1,
  116521. &_huff_book_line_1024x27_3sub2,
  116522. &_huff_book_line_1024x27_3sub3,
  116523. &_huff_book_line_1024x27_4sub1,
  116524. &_huff_book_line_1024x27_4sub2,
  116525. &_huff_book_line_1024x27_4sub3,
  116526. };
  116527. static static_codebook *_floor_2048x27_books[]={
  116528. &_huff_book_line_2048x27_class1,
  116529. &_huff_book_line_2048x27_class2,
  116530. &_huff_book_line_2048x27_class3,
  116531. &_huff_book_line_2048x27_class4,
  116532. &_huff_book_line_2048x27_0sub0,
  116533. &_huff_book_line_2048x27_1sub0,
  116534. &_huff_book_line_2048x27_1sub1,
  116535. &_huff_book_line_2048x27_2sub0,
  116536. &_huff_book_line_2048x27_2sub1,
  116537. &_huff_book_line_2048x27_3sub1,
  116538. &_huff_book_line_2048x27_3sub2,
  116539. &_huff_book_line_2048x27_3sub3,
  116540. &_huff_book_line_2048x27_4sub1,
  116541. &_huff_book_line_2048x27_4sub2,
  116542. &_huff_book_line_2048x27_4sub3,
  116543. };
  116544. static static_codebook *_floor_512x17_books[]={
  116545. &_huff_book_line_512x17_class1,
  116546. &_huff_book_line_512x17_class2,
  116547. &_huff_book_line_512x17_class3,
  116548. &_huff_book_line_512x17_0sub0,
  116549. &_huff_book_line_512x17_1sub0,
  116550. &_huff_book_line_512x17_1sub1,
  116551. &_huff_book_line_512x17_2sub1,
  116552. &_huff_book_line_512x17_2sub2,
  116553. &_huff_book_line_512x17_2sub3,
  116554. &_huff_book_line_512x17_3sub1,
  116555. &_huff_book_line_512x17_3sub2,
  116556. &_huff_book_line_512x17_3sub3,
  116557. };
  116558. static static_codebook **_floor_books[10]={
  116559. _floor_128x4_books,
  116560. _floor_256x4_books,
  116561. _floor_128x7_books,
  116562. _floor_256x7_books,
  116563. _floor_128x11_books,
  116564. _floor_128x17_books,
  116565. _floor_256x4low_books,
  116566. _floor_1024x27_books,
  116567. _floor_2048x27_books,
  116568. _floor_512x17_books,
  116569. };
  116570. static vorbis_info_floor1 _floor[10]={
  116571. /* 128 x 4 */
  116572. {
  116573. 1,{0},{4},{2},{0},
  116574. {{1,2,3,4}},
  116575. 4,{0,128, 33,8,16,70},
  116576. 60,30,500, 1.,18., -1
  116577. },
  116578. /* 256 x 4 */
  116579. {
  116580. 1,{0},{4},{2},{0},
  116581. {{1,2,3,4}},
  116582. 4,{0,256, 66,16,32,140},
  116583. 60,30,500, 1.,18., -1
  116584. },
  116585. /* 128 x 7 */
  116586. {
  116587. 2,{0,1},{3,4},{2,2},{0,1},
  116588. {{-1,2,3,4},{-1,5,6,7}},
  116589. 4,{0,128, 14,4,58, 2,8,28,90},
  116590. 60,30,500, 1.,18., -1
  116591. },
  116592. /* 256 x 7 */
  116593. {
  116594. 2,{0,1},{3,4},{2,2},{0,1},
  116595. {{-1,2,3,4},{-1,5,6,7}},
  116596. 4,{0,256, 28,8,116, 4,16,56,180},
  116597. 60,30,500, 1.,18., -1
  116598. },
  116599. /* 128 x 11 */
  116600. {
  116601. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  116602. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  116603. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  116604. 60,30,500, 1,18., -1
  116605. },
  116606. /* 128 x 17 */
  116607. {
  116608. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  116609. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  116610. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  116611. 60,30,500, 1,18., -1
  116612. },
  116613. /* 256 x 4 (low bitrate version) */
  116614. {
  116615. 1,{0},{4},{2},{0},
  116616. {{1,2,3,4}},
  116617. 4,{0,256, 66,16,32,140},
  116618. 60,30,500, 1.,18., -1
  116619. },
  116620. /* 1024 x 27 */
  116621. {
  116622. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  116623. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  116624. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  116625. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  116626. 60,30,500, 3,18., -1 /* lowpass */
  116627. },
  116628. /* 2048 x 27 */
  116629. {
  116630. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  116631. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  116632. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  116633. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  116634. 60,30,500, 3,18., -1 /* lowpass */
  116635. },
  116636. /* 512 x 17 */
  116637. {
  116638. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  116639. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  116640. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  116641. 7,23,39, 55,79,110, 156,232,360},
  116642. 60,30,500, 1,18., -1 /* lowpass! */
  116643. },
  116644. };
  116645. /********* End of inlined file: floor_all.h *********/
  116646. /********* Start of inlined file: residue_44.h *********/
  116647. /********* Start of inlined file: res_books_stereo.h *********/
  116648. static long _vq_quantlist__16c0_s_p1_0[] = {
  116649. 1,
  116650. 0,
  116651. 2,
  116652. };
  116653. static long _vq_lengthlist__16c0_s_p1_0[] = {
  116654. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  116655. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116659. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  116660. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116664. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  116665. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  116700. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  116701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  116705. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  116706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  116710. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  116711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116745. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  116746. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116750. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  116751. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  116752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116755. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  116756. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  116757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117064. 0,
  117065. };
  117066. static float _vq_quantthresh__16c0_s_p1_0[] = {
  117067. -0.5, 0.5,
  117068. };
  117069. static long _vq_quantmap__16c0_s_p1_0[] = {
  117070. 1, 0, 2,
  117071. };
  117072. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  117073. _vq_quantthresh__16c0_s_p1_0,
  117074. _vq_quantmap__16c0_s_p1_0,
  117075. 3,
  117076. 3
  117077. };
  117078. static static_codebook _16c0_s_p1_0 = {
  117079. 8, 6561,
  117080. _vq_lengthlist__16c0_s_p1_0,
  117081. 1, -535822336, 1611661312, 2, 0,
  117082. _vq_quantlist__16c0_s_p1_0,
  117083. NULL,
  117084. &_vq_auxt__16c0_s_p1_0,
  117085. NULL,
  117086. 0
  117087. };
  117088. static long _vq_quantlist__16c0_s_p2_0[] = {
  117089. 2,
  117090. 1,
  117091. 3,
  117092. 0,
  117093. 4,
  117094. };
  117095. static long _vq_lengthlist__16c0_s_p2_0[] = {
  117096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117135. 0,
  117136. };
  117137. static float _vq_quantthresh__16c0_s_p2_0[] = {
  117138. -1.5, -0.5, 0.5, 1.5,
  117139. };
  117140. static long _vq_quantmap__16c0_s_p2_0[] = {
  117141. 3, 1, 0, 2, 4,
  117142. };
  117143. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  117144. _vq_quantthresh__16c0_s_p2_0,
  117145. _vq_quantmap__16c0_s_p2_0,
  117146. 5,
  117147. 5
  117148. };
  117149. static static_codebook _16c0_s_p2_0 = {
  117150. 4, 625,
  117151. _vq_lengthlist__16c0_s_p2_0,
  117152. 1, -533725184, 1611661312, 3, 0,
  117153. _vq_quantlist__16c0_s_p2_0,
  117154. NULL,
  117155. &_vq_auxt__16c0_s_p2_0,
  117156. NULL,
  117157. 0
  117158. };
  117159. static long _vq_quantlist__16c0_s_p3_0[] = {
  117160. 2,
  117161. 1,
  117162. 3,
  117163. 0,
  117164. 4,
  117165. };
  117166. static long _vq_lengthlist__16c0_s_p3_0[] = {
  117167. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  117169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117170. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  117172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117173. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  117174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117206. 0,
  117207. };
  117208. static float _vq_quantthresh__16c0_s_p3_0[] = {
  117209. -1.5, -0.5, 0.5, 1.5,
  117210. };
  117211. static long _vq_quantmap__16c0_s_p3_0[] = {
  117212. 3, 1, 0, 2, 4,
  117213. };
  117214. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  117215. _vq_quantthresh__16c0_s_p3_0,
  117216. _vq_quantmap__16c0_s_p3_0,
  117217. 5,
  117218. 5
  117219. };
  117220. static static_codebook _16c0_s_p3_0 = {
  117221. 4, 625,
  117222. _vq_lengthlist__16c0_s_p3_0,
  117223. 1, -533725184, 1611661312, 3, 0,
  117224. _vq_quantlist__16c0_s_p3_0,
  117225. NULL,
  117226. &_vq_auxt__16c0_s_p3_0,
  117227. NULL,
  117228. 0
  117229. };
  117230. static long _vq_quantlist__16c0_s_p4_0[] = {
  117231. 4,
  117232. 3,
  117233. 5,
  117234. 2,
  117235. 6,
  117236. 1,
  117237. 7,
  117238. 0,
  117239. 8,
  117240. };
  117241. static long _vq_lengthlist__16c0_s_p4_0[] = {
  117242. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  117243. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  117244. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  117245. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  117246. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117247. 0,
  117248. };
  117249. static float _vq_quantthresh__16c0_s_p4_0[] = {
  117250. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  117251. };
  117252. static long _vq_quantmap__16c0_s_p4_0[] = {
  117253. 7, 5, 3, 1, 0, 2, 4, 6,
  117254. 8,
  117255. };
  117256. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  117257. _vq_quantthresh__16c0_s_p4_0,
  117258. _vq_quantmap__16c0_s_p4_0,
  117259. 9,
  117260. 9
  117261. };
  117262. static static_codebook _16c0_s_p4_0 = {
  117263. 2, 81,
  117264. _vq_lengthlist__16c0_s_p4_0,
  117265. 1, -531628032, 1611661312, 4, 0,
  117266. _vq_quantlist__16c0_s_p4_0,
  117267. NULL,
  117268. &_vq_auxt__16c0_s_p4_0,
  117269. NULL,
  117270. 0
  117271. };
  117272. static long _vq_quantlist__16c0_s_p5_0[] = {
  117273. 4,
  117274. 3,
  117275. 5,
  117276. 2,
  117277. 6,
  117278. 1,
  117279. 7,
  117280. 0,
  117281. 8,
  117282. };
  117283. static long _vq_lengthlist__16c0_s_p5_0[] = {
  117284. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  117285. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  117286. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  117287. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  117288. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  117289. 10,
  117290. };
  117291. static float _vq_quantthresh__16c0_s_p5_0[] = {
  117292. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  117293. };
  117294. static long _vq_quantmap__16c0_s_p5_0[] = {
  117295. 7, 5, 3, 1, 0, 2, 4, 6,
  117296. 8,
  117297. };
  117298. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  117299. _vq_quantthresh__16c0_s_p5_0,
  117300. _vq_quantmap__16c0_s_p5_0,
  117301. 9,
  117302. 9
  117303. };
  117304. static static_codebook _16c0_s_p5_0 = {
  117305. 2, 81,
  117306. _vq_lengthlist__16c0_s_p5_0,
  117307. 1, -531628032, 1611661312, 4, 0,
  117308. _vq_quantlist__16c0_s_p5_0,
  117309. NULL,
  117310. &_vq_auxt__16c0_s_p5_0,
  117311. NULL,
  117312. 0
  117313. };
  117314. static long _vq_quantlist__16c0_s_p6_0[] = {
  117315. 8,
  117316. 7,
  117317. 9,
  117318. 6,
  117319. 10,
  117320. 5,
  117321. 11,
  117322. 4,
  117323. 12,
  117324. 3,
  117325. 13,
  117326. 2,
  117327. 14,
  117328. 1,
  117329. 15,
  117330. 0,
  117331. 16,
  117332. };
  117333. static long _vq_lengthlist__16c0_s_p6_0[] = {
  117334. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  117335. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  117336. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  117337. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  117338. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  117339. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  117340. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  117341. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  117342. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  117343. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  117344. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  117345. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  117346. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  117347. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  117348. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  117349. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  117350. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  117351. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  117352. 14,
  117353. };
  117354. static float _vq_quantthresh__16c0_s_p6_0[] = {
  117355. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  117356. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  117357. };
  117358. static long _vq_quantmap__16c0_s_p6_0[] = {
  117359. 15, 13, 11, 9, 7, 5, 3, 1,
  117360. 0, 2, 4, 6, 8, 10, 12, 14,
  117361. 16,
  117362. };
  117363. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  117364. _vq_quantthresh__16c0_s_p6_0,
  117365. _vq_quantmap__16c0_s_p6_0,
  117366. 17,
  117367. 17
  117368. };
  117369. static static_codebook _16c0_s_p6_0 = {
  117370. 2, 289,
  117371. _vq_lengthlist__16c0_s_p6_0,
  117372. 1, -529530880, 1611661312, 5, 0,
  117373. _vq_quantlist__16c0_s_p6_0,
  117374. NULL,
  117375. &_vq_auxt__16c0_s_p6_0,
  117376. NULL,
  117377. 0
  117378. };
  117379. static long _vq_quantlist__16c0_s_p7_0[] = {
  117380. 1,
  117381. 0,
  117382. 2,
  117383. };
  117384. static long _vq_lengthlist__16c0_s_p7_0[] = {
  117385. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  117386. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  117387. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  117388. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  117389. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  117390. 13,
  117391. };
  117392. static float _vq_quantthresh__16c0_s_p7_0[] = {
  117393. -5.5, 5.5,
  117394. };
  117395. static long _vq_quantmap__16c0_s_p7_0[] = {
  117396. 1, 0, 2,
  117397. };
  117398. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  117399. _vq_quantthresh__16c0_s_p7_0,
  117400. _vq_quantmap__16c0_s_p7_0,
  117401. 3,
  117402. 3
  117403. };
  117404. static static_codebook _16c0_s_p7_0 = {
  117405. 4, 81,
  117406. _vq_lengthlist__16c0_s_p7_0,
  117407. 1, -529137664, 1618345984, 2, 0,
  117408. _vq_quantlist__16c0_s_p7_0,
  117409. NULL,
  117410. &_vq_auxt__16c0_s_p7_0,
  117411. NULL,
  117412. 0
  117413. };
  117414. static long _vq_quantlist__16c0_s_p7_1[] = {
  117415. 5,
  117416. 4,
  117417. 6,
  117418. 3,
  117419. 7,
  117420. 2,
  117421. 8,
  117422. 1,
  117423. 9,
  117424. 0,
  117425. 10,
  117426. };
  117427. static long _vq_lengthlist__16c0_s_p7_1[] = {
  117428. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  117429. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  117430. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  117431. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  117432. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  117433. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  117434. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  117435. 11,11,11, 9, 9, 9, 9,10,10,
  117436. };
  117437. static float _vq_quantthresh__16c0_s_p7_1[] = {
  117438. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  117439. 3.5, 4.5,
  117440. };
  117441. static long _vq_quantmap__16c0_s_p7_1[] = {
  117442. 9, 7, 5, 3, 1, 0, 2, 4,
  117443. 6, 8, 10,
  117444. };
  117445. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  117446. _vq_quantthresh__16c0_s_p7_1,
  117447. _vq_quantmap__16c0_s_p7_1,
  117448. 11,
  117449. 11
  117450. };
  117451. static static_codebook _16c0_s_p7_1 = {
  117452. 2, 121,
  117453. _vq_lengthlist__16c0_s_p7_1,
  117454. 1, -531365888, 1611661312, 4, 0,
  117455. _vq_quantlist__16c0_s_p7_1,
  117456. NULL,
  117457. &_vq_auxt__16c0_s_p7_1,
  117458. NULL,
  117459. 0
  117460. };
  117461. static long _vq_quantlist__16c0_s_p8_0[] = {
  117462. 6,
  117463. 5,
  117464. 7,
  117465. 4,
  117466. 8,
  117467. 3,
  117468. 9,
  117469. 2,
  117470. 10,
  117471. 1,
  117472. 11,
  117473. 0,
  117474. 12,
  117475. };
  117476. static long _vq_lengthlist__16c0_s_p8_0[] = {
  117477. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  117478. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  117479. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  117480. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  117481. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  117482. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  117483. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  117484. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  117485. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  117486. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  117487. 0,12,13,13,12,13,14,14,14,
  117488. };
  117489. static float _vq_quantthresh__16c0_s_p8_0[] = {
  117490. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  117491. 12.5, 17.5, 22.5, 27.5,
  117492. };
  117493. static long _vq_quantmap__16c0_s_p8_0[] = {
  117494. 11, 9, 7, 5, 3, 1, 0, 2,
  117495. 4, 6, 8, 10, 12,
  117496. };
  117497. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  117498. _vq_quantthresh__16c0_s_p8_0,
  117499. _vq_quantmap__16c0_s_p8_0,
  117500. 13,
  117501. 13
  117502. };
  117503. static static_codebook _16c0_s_p8_0 = {
  117504. 2, 169,
  117505. _vq_lengthlist__16c0_s_p8_0,
  117506. 1, -526516224, 1616117760, 4, 0,
  117507. _vq_quantlist__16c0_s_p8_0,
  117508. NULL,
  117509. &_vq_auxt__16c0_s_p8_0,
  117510. NULL,
  117511. 0
  117512. };
  117513. static long _vq_quantlist__16c0_s_p8_1[] = {
  117514. 2,
  117515. 1,
  117516. 3,
  117517. 0,
  117518. 4,
  117519. };
  117520. static long _vq_lengthlist__16c0_s_p8_1[] = {
  117521. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  117522. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  117523. };
  117524. static float _vq_quantthresh__16c0_s_p8_1[] = {
  117525. -1.5, -0.5, 0.5, 1.5,
  117526. };
  117527. static long _vq_quantmap__16c0_s_p8_1[] = {
  117528. 3, 1, 0, 2, 4,
  117529. };
  117530. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  117531. _vq_quantthresh__16c0_s_p8_1,
  117532. _vq_quantmap__16c0_s_p8_1,
  117533. 5,
  117534. 5
  117535. };
  117536. static static_codebook _16c0_s_p8_1 = {
  117537. 2, 25,
  117538. _vq_lengthlist__16c0_s_p8_1,
  117539. 1, -533725184, 1611661312, 3, 0,
  117540. _vq_quantlist__16c0_s_p8_1,
  117541. NULL,
  117542. &_vq_auxt__16c0_s_p8_1,
  117543. NULL,
  117544. 0
  117545. };
  117546. static long _vq_quantlist__16c0_s_p9_0[] = {
  117547. 1,
  117548. 0,
  117549. 2,
  117550. };
  117551. static long _vq_lengthlist__16c0_s_p9_0[] = {
  117552. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117553. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117554. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117555. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117556. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117557. 7,
  117558. };
  117559. static float _vq_quantthresh__16c0_s_p9_0[] = {
  117560. -157.5, 157.5,
  117561. };
  117562. static long _vq_quantmap__16c0_s_p9_0[] = {
  117563. 1, 0, 2,
  117564. };
  117565. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  117566. _vq_quantthresh__16c0_s_p9_0,
  117567. _vq_quantmap__16c0_s_p9_0,
  117568. 3,
  117569. 3
  117570. };
  117571. static static_codebook _16c0_s_p9_0 = {
  117572. 4, 81,
  117573. _vq_lengthlist__16c0_s_p9_0,
  117574. 1, -518803456, 1628680192, 2, 0,
  117575. _vq_quantlist__16c0_s_p9_0,
  117576. NULL,
  117577. &_vq_auxt__16c0_s_p9_0,
  117578. NULL,
  117579. 0
  117580. };
  117581. static long _vq_quantlist__16c0_s_p9_1[] = {
  117582. 7,
  117583. 6,
  117584. 8,
  117585. 5,
  117586. 9,
  117587. 4,
  117588. 10,
  117589. 3,
  117590. 11,
  117591. 2,
  117592. 12,
  117593. 1,
  117594. 13,
  117595. 0,
  117596. 14,
  117597. };
  117598. static long _vq_lengthlist__16c0_s_p9_1[] = {
  117599. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  117600. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  117601. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  117602. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  117603. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117604. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117605. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117606. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117607. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117608. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117609. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117610. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117611. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117612. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117613. 10,
  117614. };
  117615. static float _vq_quantthresh__16c0_s_p9_1[] = {
  117616. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  117617. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  117618. };
  117619. static long _vq_quantmap__16c0_s_p9_1[] = {
  117620. 13, 11, 9, 7, 5, 3, 1, 0,
  117621. 2, 4, 6, 8, 10, 12, 14,
  117622. };
  117623. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  117624. _vq_quantthresh__16c0_s_p9_1,
  117625. _vq_quantmap__16c0_s_p9_1,
  117626. 15,
  117627. 15
  117628. };
  117629. static static_codebook _16c0_s_p9_1 = {
  117630. 2, 225,
  117631. _vq_lengthlist__16c0_s_p9_1,
  117632. 1, -520986624, 1620377600, 4, 0,
  117633. _vq_quantlist__16c0_s_p9_1,
  117634. NULL,
  117635. &_vq_auxt__16c0_s_p9_1,
  117636. NULL,
  117637. 0
  117638. };
  117639. static long _vq_quantlist__16c0_s_p9_2[] = {
  117640. 10,
  117641. 9,
  117642. 11,
  117643. 8,
  117644. 12,
  117645. 7,
  117646. 13,
  117647. 6,
  117648. 14,
  117649. 5,
  117650. 15,
  117651. 4,
  117652. 16,
  117653. 3,
  117654. 17,
  117655. 2,
  117656. 18,
  117657. 1,
  117658. 19,
  117659. 0,
  117660. 20,
  117661. };
  117662. static long _vq_lengthlist__16c0_s_p9_2[] = {
  117663. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  117664. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  117665. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  117666. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  117667. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  117668. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  117669. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  117670. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  117671. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  117672. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  117673. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  117674. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  117675. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  117676. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  117677. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  117678. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  117679. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  117680. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  117681. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  117682. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  117683. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  117684. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  117685. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  117686. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  117687. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  117688. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  117689. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  117690. 10,11,10,10,11, 9,10,10,10,
  117691. };
  117692. static float _vq_quantthresh__16c0_s_p9_2[] = {
  117693. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  117694. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  117695. 6.5, 7.5, 8.5, 9.5,
  117696. };
  117697. static long _vq_quantmap__16c0_s_p9_2[] = {
  117698. 19, 17, 15, 13, 11, 9, 7, 5,
  117699. 3, 1, 0, 2, 4, 6, 8, 10,
  117700. 12, 14, 16, 18, 20,
  117701. };
  117702. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  117703. _vq_quantthresh__16c0_s_p9_2,
  117704. _vq_quantmap__16c0_s_p9_2,
  117705. 21,
  117706. 21
  117707. };
  117708. static static_codebook _16c0_s_p9_2 = {
  117709. 2, 441,
  117710. _vq_lengthlist__16c0_s_p9_2,
  117711. 1, -529268736, 1611661312, 5, 0,
  117712. _vq_quantlist__16c0_s_p9_2,
  117713. NULL,
  117714. &_vq_auxt__16c0_s_p9_2,
  117715. NULL,
  117716. 0
  117717. };
  117718. static long _huff_lengthlist__16c0_s_single[] = {
  117719. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  117720. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  117721. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  117722. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  117723. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  117724. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  117725. 16,16,18,18,
  117726. };
  117727. static static_codebook _huff_book__16c0_s_single = {
  117728. 2, 100,
  117729. _huff_lengthlist__16c0_s_single,
  117730. 0, 0, 0, 0, 0,
  117731. NULL,
  117732. NULL,
  117733. NULL,
  117734. NULL,
  117735. 0
  117736. };
  117737. static long _huff_lengthlist__16c1_s_long[] = {
  117738. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  117739. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  117740. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  117741. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  117742. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  117743. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  117744. 12,11,11,13,
  117745. };
  117746. static static_codebook _huff_book__16c1_s_long = {
  117747. 2, 100,
  117748. _huff_lengthlist__16c1_s_long,
  117749. 0, 0, 0, 0, 0,
  117750. NULL,
  117751. NULL,
  117752. NULL,
  117753. NULL,
  117754. 0
  117755. };
  117756. static long _vq_quantlist__16c1_s_p1_0[] = {
  117757. 1,
  117758. 0,
  117759. 2,
  117760. };
  117761. static long _vq_lengthlist__16c1_s_p1_0[] = {
  117762. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  117763. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117767. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  117768. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117772. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  117773. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  117808. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  117809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  117813. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  117814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  117818. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  117819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117853. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  117854. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117858. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  117859. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  117860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117863. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  117864. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  117865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118172. 0,
  118173. };
  118174. static float _vq_quantthresh__16c1_s_p1_0[] = {
  118175. -0.5, 0.5,
  118176. };
  118177. static long _vq_quantmap__16c1_s_p1_0[] = {
  118178. 1, 0, 2,
  118179. };
  118180. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  118181. _vq_quantthresh__16c1_s_p1_0,
  118182. _vq_quantmap__16c1_s_p1_0,
  118183. 3,
  118184. 3
  118185. };
  118186. static static_codebook _16c1_s_p1_0 = {
  118187. 8, 6561,
  118188. _vq_lengthlist__16c1_s_p1_0,
  118189. 1, -535822336, 1611661312, 2, 0,
  118190. _vq_quantlist__16c1_s_p1_0,
  118191. NULL,
  118192. &_vq_auxt__16c1_s_p1_0,
  118193. NULL,
  118194. 0
  118195. };
  118196. static long _vq_quantlist__16c1_s_p2_0[] = {
  118197. 2,
  118198. 1,
  118199. 3,
  118200. 0,
  118201. 4,
  118202. };
  118203. static long _vq_lengthlist__16c1_s_p2_0[] = {
  118204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118243. 0,
  118244. };
  118245. static float _vq_quantthresh__16c1_s_p2_0[] = {
  118246. -1.5, -0.5, 0.5, 1.5,
  118247. };
  118248. static long _vq_quantmap__16c1_s_p2_0[] = {
  118249. 3, 1, 0, 2, 4,
  118250. };
  118251. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  118252. _vq_quantthresh__16c1_s_p2_0,
  118253. _vq_quantmap__16c1_s_p2_0,
  118254. 5,
  118255. 5
  118256. };
  118257. static static_codebook _16c1_s_p2_0 = {
  118258. 4, 625,
  118259. _vq_lengthlist__16c1_s_p2_0,
  118260. 1, -533725184, 1611661312, 3, 0,
  118261. _vq_quantlist__16c1_s_p2_0,
  118262. NULL,
  118263. &_vq_auxt__16c1_s_p2_0,
  118264. NULL,
  118265. 0
  118266. };
  118267. static long _vq_quantlist__16c1_s_p3_0[] = {
  118268. 2,
  118269. 1,
  118270. 3,
  118271. 0,
  118272. 4,
  118273. };
  118274. static long _vq_lengthlist__16c1_s_p3_0[] = {
  118275. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  118277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118278. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  118280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118281. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  118282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118314. 0,
  118315. };
  118316. static float _vq_quantthresh__16c1_s_p3_0[] = {
  118317. -1.5, -0.5, 0.5, 1.5,
  118318. };
  118319. static long _vq_quantmap__16c1_s_p3_0[] = {
  118320. 3, 1, 0, 2, 4,
  118321. };
  118322. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  118323. _vq_quantthresh__16c1_s_p3_0,
  118324. _vq_quantmap__16c1_s_p3_0,
  118325. 5,
  118326. 5
  118327. };
  118328. static static_codebook _16c1_s_p3_0 = {
  118329. 4, 625,
  118330. _vq_lengthlist__16c1_s_p3_0,
  118331. 1, -533725184, 1611661312, 3, 0,
  118332. _vq_quantlist__16c1_s_p3_0,
  118333. NULL,
  118334. &_vq_auxt__16c1_s_p3_0,
  118335. NULL,
  118336. 0
  118337. };
  118338. static long _vq_quantlist__16c1_s_p4_0[] = {
  118339. 4,
  118340. 3,
  118341. 5,
  118342. 2,
  118343. 6,
  118344. 1,
  118345. 7,
  118346. 0,
  118347. 8,
  118348. };
  118349. static long _vq_lengthlist__16c1_s_p4_0[] = {
  118350. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  118351. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  118352. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  118353. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  118354. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118355. 0,
  118356. };
  118357. static float _vq_quantthresh__16c1_s_p4_0[] = {
  118358. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118359. };
  118360. static long _vq_quantmap__16c1_s_p4_0[] = {
  118361. 7, 5, 3, 1, 0, 2, 4, 6,
  118362. 8,
  118363. };
  118364. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  118365. _vq_quantthresh__16c1_s_p4_0,
  118366. _vq_quantmap__16c1_s_p4_0,
  118367. 9,
  118368. 9
  118369. };
  118370. static static_codebook _16c1_s_p4_0 = {
  118371. 2, 81,
  118372. _vq_lengthlist__16c1_s_p4_0,
  118373. 1, -531628032, 1611661312, 4, 0,
  118374. _vq_quantlist__16c1_s_p4_0,
  118375. NULL,
  118376. &_vq_auxt__16c1_s_p4_0,
  118377. NULL,
  118378. 0
  118379. };
  118380. static long _vq_quantlist__16c1_s_p5_0[] = {
  118381. 4,
  118382. 3,
  118383. 5,
  118384. 2,
  118385. 6,
  118386. 1,
  118387. 7,
  118388. 0,
  118389. 8,
  118390. };
  118391. static long _vq_lengthlist__16c1_s_p5_0[] = {
  118392. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  118393. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  118394. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  118395. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  118396. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  118397. 10,
  118398. };
  118399. static float _vq_quantthresh__16c1_s_p5_0[] = {
  118400. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118401. };
  118402. static long _vq_quantmap__16c1_s_p5_0[] = {
  118403. 7, 5, 3, 1, 0, 2, 4, 6,
  118404. 8,
  118405. };
  118406. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  118407. _vq_quantthresh__16c1_s_p5_0,
  118408. _vq_quantmap__16c1_s_p5_0,
  118409. 9,
  118410. 9
  118411. };
  118412. static static_codebook _16c1_s_p5_0 = {
  118413. 2, 81,
  118414. _vq_lengthlist__16c1_s_p5_0,
  118415. 1, -531628032, 1611661312, 4, 0,
  118416. _vq_quantlist__16c1_s_p5_0,
  118417. NULL,
  118418. &_vq_auxt__16c1_s_p5_0,
  118419. NULL,
  118420. 0
  118421. };
  118422. static long _vq_quantlist__16c1_s_p6_0[] = {
  118423. 8,
  118424. 7,
  118425. 9,
  118426. 6,
  118427. 10,
  118428. 5,
  118429. 11,
  118430. 4,
  118431. 12,
  118432. 3,
  118433. 13,
  118434. 2,
  118435. 14,
  118436. 1,
  118437. 15,
  118438. 0,
  118439. 16,
  118440. };
  118441. static long _vq_lengthlist__16c1_s_p6_0[] = {
  118442. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  118443. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  118444. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  118445. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  118446. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  118447. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  118448. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  118449. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  118450. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  118451. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  118452. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  118453. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  118454. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  118455. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  118456. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  118457. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  118458. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  118459. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  118460. 14,
  118461. };
  118462. static float _vq_quantthresh__16c1_s_p6_0[] = {
  118463. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  118464. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  118465. };
  118466. static long _vq_quantmap__16c1_s_p6_0[] = {
  118467. 15, 13, 11, 9, 7, 5, 3, 1,
  118468. 0, 2, 4, 6, 8, 10, 12, 14,
  118469. 16,
  118470. };
  118471. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  118472. _vq_quantthresh__16c1_s_p6_0,
  118473. _vq_quantmap__16c1_s_p6_0,
  118474. 17,
  118475. 17
  118476. };
  118477. static static_codebook _16c1_s_p6_0 = {
  118478. 2, 289,
  118479. _vq_lengthlist__16c1_s_p6_0,
  118480. 1, -529530880, 1611661312, 5, 0,
  118481. _vq_quantlist__16c1_s_p6_0,
  118482. NULL,
  118483. &_vq_auxt__16c1_s_p6_0,
  118484. NULL,
  118485. 0
  118486. };
  118487. static long _vq_quantlist__16c1_s_p7_0[] = {
  118488. 1,
  118489. 0,
  118490. 2,
  118491. };
  118492. static long _vq_lengthlist__16c1_s_p7_0[] = {
  118493. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  118494. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  118495. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  118496. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  118497. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  118498. 11,
  118499. };
  118500. static float _vq_quantthresh__16c1_s_p7_0[] = {
  118501. -5.5, 5.5,
  118502. };
  118503. static long _vq_quantmap__16c1_s_p7_0[] = {
  118504. 1, 0, 2,
  118505. };
  118506. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  118507. _vq_quantthresh__16c1_s_p7_0,
  118508. _vq_quantmap__16c1_s_p7_0,
  118509. 3,
  118510. 3
  118511. };
  118512. static static_codebook _16c1_s_p7_0 = {
  118513. 4, 81,
  118514. _vq_lengthlist__16c1_s_p7_0,
  118515. 1, -529137664, 1618345984, 2, 0,
  118516. _vq_quantlist__16c1_s_p7_0,
  118517. NULL,
  118518. &_vq_auxt__16c1_s_p7_0,
  118519. NULL,
  118520. 0
  118521. };
  118522. static long _vq_quantlist__16c1_s_p7_1[] = {
  118523. 5,
  118524. 4,
  118525. 6,
  118526. 3,
  118527. 7,
  118528. 2,
  118529. 8,
  118530. 1,
  118531. 9,
  118532. 0,
  118533. 10,
  118534. };
  118535. static long _vq_lengthlist__16c1_s_p7_1[] = {
  118536. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  118537. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  118538. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  118539. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  118540. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  118541. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  118542. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  118543. 10,10,10, 8, 8, 8, 8, 9, 9,
  118544. };
  118545. static float _vq_quantthresh__16c1_s_p7_1[] = {
  118546. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  118547. 3.5, 4.5,
  118548. };
  118549. static long _vq_quantmap__16c1_s_p7_1[] = {
  118550. 9, 7, 5, 3, 1, 0, 2, 4,
  118551. 6, 8, 10,
  118552. };
  118553. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  118554. _vq_quantthresh__16c1_s_p7_1,
  118555. _vq_quantmap__16c1_s_p7_1,
  118556. 11,
  118557. 11
  118558. };
  118559. static static_codebook _16c1_s_p7_1 = {
  118560. 2, 121,
  118561. _vq_lengthlist__16c1_s_p7_1,
  118562. 1, -531365888, 1611661312, 4, 0,
  118563. _vq_quantlist__16c1_s_p7_1,
  118564. NULL,
  118565. &_vq_auxt__16c1_s_p7_1,
  118566. NULL,
  118567. 0
  118568. };
  118569. static long _vq_quantlist__16c1_s_p8_0[] = {
  118570. 6,
  118571. 5,
  118572. 7,
  118573. 4,
  118574. 8,
  118575. 3,
  118576. 9,
  118577. 2,
  118578. 10,
  118579. 1,
  118580. 11,
  118581. 0,
  118582. 12,
  118583. };
  118584. static long _vq_lengthlist__16c1_s_p8_0[] = {
  118585. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  118586. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  118587. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  118588. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  118589. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  118590. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  118591. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  118592. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  118593. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  118594. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  118595. 0,12,12,12,12,13,13,14,15,
  118596. };
  118597. static float _vq_quantthresh__16c1_s_p8_0[] = {
  118598. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  118599. 12.5, 17.5, 22.5, 27.5,
  118600. };
  118601. static long _vq_quantmap__16c1_s_p8_0[] = {
  118602. 11, 9, 7, 5, 3, 1, 0, 2,
  118603. 4, 6, 8, 10, 12,
  118604. };
  118605. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  118606. _vq_quantthresh__16c1_s_p8_0,
  118607. _vq_quantmap__16c1_s_p8_0,
  118608. 13,
  118609. 13
  118610. };
  118611. static static_codebook _16c1_s_p8_0 = {
  118612. 2, 169,
  118613. _vq_lengthlist__16c1_s_p8_0,
  118614. 1, -526516224, 1616117760, 4, 0,
  118615. _vq_quantlist__16c1_s_p8_0,
  118616. NULL,
  118617. &_vq_auxt__16c1_s_p8_0,
  118618. NULL,
  118619. 0
  118620. };
  118621. static long _vq_quantlist__16c1_s_p8_1[] = {
  118622. 2,
  118623. 1,
  118624. 3,
  118625. 0,
  118626. 4,
  118627. };
  118628. static long _vq_lengthlist__16c1_s_p8_1[] = {
  118629. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  118630. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  118631. };
  118632. static float _vq_quantthresh__16c1_s_p8_1[] = {
  118633. -1.5, -0.5, 0.5, 1.5,
  118634. };
  118635. static long _vq_quantmap__16c1_s_p8_1[] = {
  118636. 3, 1, 0, 2, 4,
  118637. };
  118638. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  118639. _vq_quantthresh__16c1_s_p8_1,
  118640. _vq_quantmap__16c1_s_p8_1,
  118641. 5,
  118642. 5
  118643. };
  118644. static static_codebook _16c1_s_p8_1 = {
  118645. 2, 25,
  118646. _vq_lengthlist__16c1_s_p8_1,
  118647. 1, -533725184, 1611661312, 3, 0,
  118648. _vq_quantlist__16c1_s_p8_1,
  118649. NULL,
  118650. &_vq_auxt__16c1_s_p8_1,
  118651. NULL,
  118652. 0
  118653. };
  118654. static long _vq_quantlist__16c1_s_p9_0[] = {
  118655. 6,
  118656. 5,
  118657. 7,
  118658. 4,
  118659. 8,
  118660. 3,
  118661. 9,
  118662. 2,
  118663. 10,
  118664. 1,
  118665. 11,
  118666. 0,
  118667. 12,
  118668. };
  118669. static long _vq_lengthlist__16c1_s_p9_0[] = {
  118670. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118671. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118672. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118673. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118674. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118675. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118676. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118677. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118678. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118679. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118680. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118681. };
  118682. static float _vq_quantthresh__16c1_s_p9_0[] = {
  118683. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  118684. 787.5, 1102.5, 1417.5, 1732.5,
  118685. };
  118686. static long _vq_quantmap__16c1_s_p9_0[] = {
  118687. 11, 9, 7, 5, 3, 1, 0, 2,
  118688. 4, 6, 8, 10, 12,
  118689. };
  118690. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  118691. _vq_quantthresh__16c1_s_p9_0,
  118692. _vq_quantmap__16c1_s_p9_0,
  118693. 13,
  118694. 13
  118695. };
  118696. static static_codebook _16c1_s_p9_0 = {
  118697. 2, 169,
  118698. _vq_lengthlist__16c1_s_p9_0,
  118699. 1, -513964032, 1628680192, 4, 0,
  118700. _vq_quantlist__16c1_s_p9_0,
  118701. NULL,
  118702. &_vq_auxt__16c1_s_p9_0,
  118703. NULL,
  118704. 0
  118705. };
  118706. static long _vq_quantlist__16c1_s_p9_1[] = {
  118707. 7,
  118708. 6,
  118709. 8,
  118710. 5,
  118711. 9,
  118712. 4,
  118713. 10,
  118714. 3,
  118715. 11,
  118716. 2,
  118717. 12,
  118718. 1,
  118719. 13,
  118720. 0,
  118721. 14,
  118722. };
  118723. static long _vq_lengthlist__16c1_s_p9_1[] = {
  118724. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  118725. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  118726. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  118727. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  118728. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  118729. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  118730. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  118731. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  118732. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118733. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  118734. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118735. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118736. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  118737. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118738. 13,
  118739. };
  118740. static float _vq_quantthresh__16c1_s_p9_1[] = {
  118741. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  118742. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  118743. };
  118744. static long _vq_quantmap__16c1_s_p9_1[] = {
  118745. 13, 11, 9, 7, 5, 3, 1, 0,
  118746. 2, 4, 6, 8, 10, 12, 14,
  118747. };
  118748. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  118749. _vq_quantthresh__16c1_s_p9_1,
  118750. _vq_quantmap__16c1_s_p9_1,
  118751. 15,
  118752. 15
  118753. };
  118754. static static_codebook _16c1_s_p9_1 = {
  118755. 2, 225,
  118756. _vq_lengthlist__16c1_s_p9_1,
  118757. 1, -520986624, 1620377600, 4, 0,
  118758. _vq_quantlist__16c1_s_p9_1,
  118759. NULL,
  118760. &_vq_auxt__16c1_s_p9_1,
  118761. NULL,
  118762. 0
  118763. };
  118764. static long _vq_quantlist__16c1_s_p9_2[] = {
  118765. 10,
  118766. 9,
  118767. 11,
  118768. 8,
  118769. 12,
  118770. 7,
  118771. 13,
  118772. 6,
  118773. 14,
  118774. 5,
  118775. 15,
  118776. 4,
  118777. 16,
  118778. 3,
  118779. 17,
  118780. 2,
  118781. 18,
  118782. 1,
  118783. 19,
  118784. 0,
  118785. 20,
  118786. };
  118787. static long _vq_lengthlist__16c1_s_p9_2[] = {
  118788. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  118789. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  118790. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  118791. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  118792. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  118793. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  118794. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  118795. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  118796. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  118797. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  118798. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  118799. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  118800. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  118801. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  118802. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  118803. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  118804. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  118805. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  118806. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  118807. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  118808. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  118809. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  118810. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  118811. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  118812. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  118813. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  118814. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  118815. 11,11,11,11,12,11,11,12,11,
  118816. };
  118817. static float _vq_quantthresh__16c1_s_p9_2[] = {
  118818. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  118819. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  118820. 6.5, 7.5, 8.5, 9.5,
  118821. };
  118822. static long _vq_quantmap__16c1_s_p9_2[] = {
  118823. 19, 17, 15, 13, 11, 9, 7, 5,
  118824. 3, 1, 0, 2, 4, 6, 8, 10,
  118825. 12, 14, 16, 18, 20,
  118826. };
  118827. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  118828. _vq_quantthresh__16c1_s_p9_2,
  118829. _vq_quantmap__16c1_s_p9_2,
  118830. 21,
  118831. 21
  118832. };
  118833. static static_codebook _16c1_s_p9_2 = {
  118834. 2, 441,
  118835. _vq_lengthlist__16c1_s_p9_2,
  118836. 1, -529268736, 1611661312, 5, 0,
  118837. _vq_quantlist__16c1_s_p9_2,
  118838. NULL,
  118839. &_vq_auxt__16c1_s_p9_2,
  118840. NULL,
  118841. 0
  118842. };
  118843. static long _huff_lengthlist__16c1_s_short[] = {
  118844. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  118845. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  118846. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  118847. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  118848. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  118849. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  118850. 9, 9,10,13,
  118851. };
  118852. static static_codebook _huff_book__16c1_s_short = {
  118853. 2, 100,
  118854. _huff_lengthlist__16c1_s_short,
  118855. 0, 0, 0, 0, 0,
  118856. NULL,
  118857. NULL,
  118858. NULL,
  118859. NULL,
  118860. 0
  118861. };
  118862. static long _huff_lengthlist__16c2_s_long[] = {
  118863. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  118864. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  118865. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  118866. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  118867. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  118868. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  118869. 14,14,16,18,
  118870. };
  118871. static static_codebook _huff_book__16c2_s_long = {
  118872. 2, 100,
  118873. _huff_lengthlist__16c2_s_long,
  118874. 0, 0, 0, 0, 0,
  118875. NULL,
  118876. NULL,
  118877. NULL,
  118878. NULL,
  118879. 0
  118880. };
  118881. static long _vq_quantlist__16c2_s_p1_0[] = {
  118882. 1,
  118883. 0,
  118884. 2,
  118885. };
  118886. static long _vq_lengthlist__16c2_s_p1_0[] = {
  118887. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  118888. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118892. 0,
  118893. };
  118894. static float _vq_quantthresh__16c2_s_p1_0[] = {
  118895. -0.5, 0.5,
  118896. };
  118897. static long _vq_quantmap__16c2_s_p1_0[] = {
  118898. 1, 0, 2,
  118899. };
  118900. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  118901. _vq_quantthresh__16c2_s_p1_0,
  118902. _vq_quantmap__16c2_s_p1_0,
  118903. 3,
  118904. 3
  118905. };
  118906. static static_codebook _16c2_s_p1_0 = {
  118907. 4, 81,
  118908. _vq_lengthlist__16c2_s_p1_0,
  118909. 1, -535822336, 1611661312, 2, 0,
  118910. _vq_quantlist__16c2_s_p1_0,
  118911. NULL,
  118912. &_vq_auxt__16c2_s_p1_0,
  118913. NULL,
  118914. 0
  118915. };
  118916. static long _vq_quantlist__16c2_s_p2_0[] = {
  118917. 2,
  118918. 1,
  118919. 3,
  118920. 0,
  118921. 4,
  118922. };
  118923. static long _vq_lengthlist__16c2_s_p2_0[] = {
  118924. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  118925. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  118926. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  118927. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  118928. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  118929. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  118930. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  118931. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  118932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118936. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  118937. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  118938. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  118939. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  118940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118944. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  118945. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  118946. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  118947. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118952. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  118953. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  118954. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  118955. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  118960. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  118961. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  118962. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  118963. 13,
  118964. };
  118965. static float _vq_quantthresh__16c2_s_p2_0[] = {
  118966. -1.5, -0.5, 0.5, 1.5,
  118967. };
  118968. static long _vq_quantmap__16c2_s_p2_0[] = {
  118969. 3, 1, 0, 2, 4,
  118970. };
  118971. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  118972. _vq_quantthresh__16c2_s_p2_0,
  118973. _vq_quantmap__16c2_s_p2_0,
  118974. 5,
  118975. 5
  118976. };
  118977. static static_codebook _16c2_s_p2_0 = {
  118978. 4, 625,
  118979. _vq_lengthlist__16c2_s_p2_0,
  118980. 1, -533725184, 1611661312, 3, 0,
  118981. _vq_quantlist__16c2_s_p2_0,
  118982. NULL,
  118983. &_vq_auxt__16c2_s_p2_0,
  118984. NULL,
  118985. 0
  118986. };
  118987. static long _vq_quantlist__16c2_s_p3_0[] = {
  118988. 4,
  118989. 3,
  118990. 5,
  118991. 2,
  118992. 6,
  118993. 1,
  118994. 7,
  118995. 0,
  118996. 8,
  118997. };
  118998. static long _vq_lengthlist__16c2_s_p3_0[] = {
  118999. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  119000. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  119001. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  119002. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  119003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119004. 0,
  119005. };
  119006. static float _vq_quantthresh__16c2_s_p3_0[] = {
  119007. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119008. };
  119009. static long _vq_quantmap__16c2_s_p3_0[] = {
  119010. 7, 5, 3, 1, 0, 2, 4, 6,
  119011. 8,
  119012. };
  119013. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  119014. _vq_quantthresh__16c2_s_p3_0,
  119015. _vq_quantmap__16c2_s_p3_0,
  119016. 9,
  119017. 9
  119018. };
  119019. static static_codebook _16c2_s_p3_0 = {
  119020. 2, 81,
  119021. _vq_lengthlist__16c2_s_p3_0,
  119022. 1, -531628032, 1611661312, 4, 0,
  119023. _vq_quantlist__16c2_s_p3_0,
  119024. NULL,
  119025. &_vq_auxt__16c2_s_p3_0,
  119026. NULL,
  119027. 0
  119028. };
  119029. static long _vq_quantlist__16c2_s_p4_0[] = {
  119030. 8,
  119031. 7,
  119032. 9,
  119033. 6,
  119034. 10,
  119035. 5,
  119036. 11,
  119037. 4,
  119038. 12,
  119039. 3,
  119040. 13,
  119041. 2,
  119042. 14,
  119043. 1,
  119044. 15,
  119045. 0,
  119046. 16,
  119047. };
  119048. static long _vq_lengthlist__16c2_s_p4_0[] = {
  119049. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  119050. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  119051. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  119052. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  119053. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  119054. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  119055. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  119056. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  119057. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  119058. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  119059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119067. 0,
  119068. };
  119069. static float _vq_quantthresh__16c2_s_p4_0[] = {
  119070. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  119071. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  119072. };
  119073. static long _vq_quantmap__16c2_s_p4_0[] = {
  119074. 15, 13, 11, 9, 7, 5, 3, 1,
  119075. 0, 2, 4, 6, 8, 10, 12, 14,
  119076. 16,
  119077. };
  119078. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  119079. _vq_quantthresh__16c2_s_p4_0,
  119080. _vq_quantmap__16c2_s_p4_0,
  119081. 17,
  119082. 17
  119083. };
  119084. static static_codebook _16c2_s_p4_0 = {
  119085. 2, 289,
  119086. _vq_lengthlist__16c2_s_p4_0,
  119087. 1, -529530880, 1611661312, 5, 0,
  119088. _vq_quantlist__16c2_s_p4_0,
  119089. NULL,
  119090. &_vq_auxt__16c2_s_p4_0,
  119091. NULL,
  119092. 0
  119093. };
  119094. static long _vq_quantlist__16c2_s_p5_0[] = {
  119095. 1,
  119096. 0,
  119097. 2,
  119098. };
  119099. static long _vq_lengthlist__16c2_s_p5_0[] = {
  119100. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  119101. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  119102. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  119103. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  119104. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  119105. 12,
  119106. };
  119107. static float _vq_quantthresh__16c2_s_p5_0[] = {
  119108. -5.5, 5.5,
  119109. };
  119110. static long _vq_quantmap__16c2_s_p5_0[] = {
  119111. 1, 0, 2,
  119112. };
  119113. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  119114. _vq_quantthresh__16c2_s_p5_0,
  119115. _vq_quantmap__16c2_s_p5_0,
  119116. 3,
  119117. 3
  119118. };
  119119. static static_codebook _16c2_s_p5_0 = {
  119120. 4, 81,
  119121. _vq_lengthlist__16c2_s_p5_0,
  119122. 1, -529137664, 1618345984, 2, 0,
  119123. _vq_quantlist__16c2_s_p5_0,
  119124. NULL,
  119125. &_vq_auxt__16c2_s_p5_0,
  119126. NULL,
  119127. 0
  119128. };
  119129. static long _vq_quantlist__16c2_s_p5_1[] = {
  119130. 5,
  119131. 4,
  119132. 6,
  119133. 3,
  119134. 7,
  119135. 2,
  119136. 8,
  119137. 1,
  119138. 9,
  119139. 0,
  119140. 10,
  119141. };
  119142. static long _vq_lengthlist__16c2_s_p5_1[] = {
  119143. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  119144. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  119145. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  119146. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  119147. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  119148. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  119149. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  119150. 11,11,11, 7, 7, 8, 8, 8, 8,
  119151. };
  119152. static float _vq_quantthresh__16c2_s_p5_1[] = {
  119153. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119154. 3.5, 4.5,
  119155. };
  119156. static long _vq_quantmap__16c2_s_p5_1[] = {
  119157. 9, 7, 5, 3, 1, 0, 2, 4,
  119158. 6, 8, 10,
  119159. };
  119160. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  119161. _vq_quantthresh__16c2_s_p5_1,
  119162. _vq_quantmap__16c2_s_p5_1,
  119163. 11,
  119164. 11
  119165. };
  119166. static static_codebook _16c2_s_p5_1 = {
  119167. 2, 121,
  119168. _vq_lengthlist__16c2_s_p5_1,
  119169. 1, -531365888, 1611661312, 4, 0,
  119170. _vq_quantlist__16c2_s_p5_1,
  119171. NULL,
  119172. &_vq_auxt__16c2_s_p5_1,
  119173. NULL,
  119174. 0
  119175. };
  119176. static long _vq_quantlist__16c2_s_p6_0[] = {
  119177. 6,
  119178. 5,
  119179. 7,
  119180. 4,
  119181. 8,
  119182. 3,
  119183. 9,
  119184. 2,
  119185. 10,
  119186. 1,
  119187. 11,
  119188. 0,
  119189. 12,
  119190. };
  119191. static long _vq_lengthlist__16c2_s_p6_0[] = {
  119192. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  119193. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  119194. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  119195. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  119196. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  119197. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  119198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119202. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119203. };
  119204. static float _vq_quantthresh__16c2_s_p6_0[] = {
  119205. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  119206. 12.5, 17.5, 22.5, 27.5,
  119207. };
  119208. static long _vq_quantmap__16c2_s_p6_0[] = {
  119209. 11, 9, 7, 5, 3, 1, 0, 2,
  119210. 4, 6, 8, 10, 12,
  119211. };
  119212. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  119213. _vq_quantthresh__16c2_s_p6_0,
  119214. _vq_quantmap__16c2_s_p6_0,
  119215. 13,
  119216. 13
  119217. };
  119218. static static_codebook _16c2_s_p6_0 = {
  119219. 2, 169,
  119220. _vq_lengthlist__16c2_s_p6_0,
  119221. 1, -526516224, 1616117760, 4, 0,
  119222. _vq_quantlist__16c2_s_p6_0,
  119223. NULL,
  119224. &_vq_auxt__16c2_s_p6_0,
  119225. NULL,
  119226. 0
  119227. };
  119228. static long _vq_quantlist__16c2_s_p6_1[] = {
  119229. 2,
  119230. 1,
  119231. 3,
  119232. 0,
  119233. 4,
  119234. };
  119235. static long _vq_lengthlist__16c2_s_p6_1[] = {
  119236. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  119237. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  119238. };
  119239. static float _vq_quantthresh__16c2_s_p6_1[] = {
  119240. -1.5, -0.5, 0.5, 1.5,
  119241. };
  119242. static long _vq_quantmap__16c2_s_p6_1[] = {
  119243. 3, 1, 0, 2, 4,
  119244. };
  119245. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  119246. _vq_quantthresh__16c2_s_p6_1,
  119247. _vq_quantmap__16c2_s_p6_1,
  119248. 5,
  119249. 5
  119250. };
  119251. static static_codebook _16c2_s_p6_1 = {
  119252. 2, 25,
  119253. _vq_lengthlist__16c2_s_p6_1,
  119254. 1, -533725184, 1611661312, 3, 0,
  119255. _vq_quantlist__16c2_s_p6_1,
  119256. NULL,
  119257. &_vq_auxt__16c2_s_p6_1,
  119258. NULL,
  119259. 0
  119260. };
  119261. static long _vq_quantlist__16c2_s_p7_0[] = {
  119262. 6,
  119263. 5,
  119264. 7,
  119265. 4,
  119266. 8,
  119267. 3,
  119268. 9,
  119269. 2,
  119270. 10,
  119271. 1,
  119272. 11,
  119273. 0,
  119274. 12,
  119275. };
  119276. static long _vq_lengthlist__16c2_s_p7_0[] = {
  119277. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  119278. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  119279. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  119280. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  119281. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  119282. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  119283. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  119284. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  119285. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  119286. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  119287. 18,13,14,13,13,14,13,15,14,
  119288. };
  119289. static float _vq_quantthresh__16c2_s_p7_0[] = {
  119290. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  119291. 27.5, 38.5, 49.5, 60.5,
  119292. };
  119293. static long _vq_quantmap__16c2_s_p7_0[] = {
  119294. 11, 9, 7, 5, 3, 1, 0, 2,
  119295. 4, 6, 8, 10, 12,
  119296. };
  119297. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  119298. _vq_quantthresh__16c2_s_p7_0,
  119299. _vq_quantmap__16c2_s_p7_0,
  119300. 13,
  119301. 13
  119302. };
  119303. static static_codebook _16c2_s_p7_0 = {
  119304. 2, 169,
  119305. _vq_lengthlist__16c2_s_p7_0,
  119306. 1, -523206656, 1618345984, 4, 0,
  119307. _vq_quantlist__16c2_s_p7_0,
  119308. NULL,
  119309. &_vq_auxt__16c2_s_p7_0,
  119310. NULL,
  119311. 0
  119312. };
  119313. static long _vq_quantlist__16c2_s_p7_1[] = {
  119314. 5,
  119315. 4,
  119316. 6,
  119317. 3,
  119318. 7,
  119319. 2,
  119320. 8,
  119321. 1,
  119322. 9,
  119323. 0,
  119324. 10,
  119325. };
  119326. static long _vq_lengthlist__16c2_s_p7_1[] = {
  119327. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  119328. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  119329. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  119330. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  119331. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  119332. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  119333. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  119334. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  119335. };
  119336. static float _vq_quantthresh__16c2_s_p7_1[] = {
  119337. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119338. 3.5, 4.5,
  119339. };
  119340. static long _vq_quantmap__16c2_s_p7_1[] = {
  119341. 9, 7, 5, 3, 1, 0, 2, 4,
  119342. 6, 8, 10,
  119343. };
  119344. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  119345. _vq_quantthresh__16c2_s_p7_1,
  119346. _vq_quantmap__16c2_s_p7_1,
  119347. 11,
  119348. 11
  119349. };
  119350. static static_codebook _16c2_s_p7_1 = {
  119351. 2, 121,
  119352. _vq_lengthlist__16c2_s_p7_1,
  119353. 1, -531365888, 1611661312, 4, 0,
  119354. _vq_quantlist__16c2_s_p7_1,
  119355. NULL,
  119356. &_vq_auxt__16c2_s_p7_1,
  119357. NULL,
  119358. 0
  119359. };
  119360. static long _vq_quantlist__16c2_s_p8_0[] = {
  119361. 7,
  119362. 6,
  119363. 8,
  119364. 5,
  119365. 9,
  119366. 4,
  119367. 10,
  119368. 3,
  119369. 11,
  119370. 2,
  119371. 12,
  119372. 1,
  119373. 13,
  119374. 0,
  119375. 14,
  119376. };
  119377. static long _vq_lengthlist__16c2_s_p8_0[] = {
  119378. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  119379. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  119380. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  119381. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  119382. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  119383. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  119384. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  119385. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  119386. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  119387. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  119388. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  119389. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  119390. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  119391. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  119392. 13,
  119393. };
  119394. static float _vq_quantthresh__16c2_s_p8_0[] = {
  119395. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  119396. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  119397. };
  119398. static long _vq_quantmap__16c2_s_p8_0[] = {
  119399. 13, 11, 9, 7, 5, 3, 1, 0,
  119400. 2, 4, 6, 8, 10, 12, 14,
  119401. };
  119402. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  119403. _vq_quantthresh__16c2_s_p8_0,
  119404. _vq_quantmap__16c2_s_p8_0,
  119405. 15,
  119406. 15
  119407. };
  119408. static static_codebook _16c2_s_p8_0 = {
  119409. 2, 225,
  119410. _vq_lengthlist__16c2_s_p8_0,
  119411. 1, -520986624, 1620377600, 4, 0,
  119412. _vq_quantlist__16c2_s_p8_0,
  119413. NULL,
  119414. &_vq_auxt__16c2_s_p8_0,
  119415. NULL,
  119416. 0
  119417. };
  119418. static long _vq_quantlist__16c2_s_p8_1[] = {
  119419. 10,
  119420. 9,
  119421. 11,
  119422. 8,
  119423. 12,
  119424. 7,
  119425. 13,
  119426. 6,
  119427. 14,
  119428. 5,
  119429. 15,
  119430. 4,
  119431. 16,
  119432. 3,
  119433. 17,
  119434. 2,
  119435. 18,
  119436. 1,
  119437. 19,
  119438. 0,
  119439. 20,
  119440. };
  119441. static long _vq_lengthlist__16c2_s_p8_1[] = {
  119442. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  119443. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  119444. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  119445. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  119446. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  119447. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  119448. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  119449. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  119450. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  119451. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  119452. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  119453. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  119454. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  119455. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  119456. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  119457. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  119458. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  119459. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  119460. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  119461. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  119462. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  119463. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  119464. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  119465. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  119466. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  119467. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  119468. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  119469. 10,11,10,10,10,10,10,10,10,
  119470. };
  119471. static float _vq_quantthresh__16c2_s_p8_1[] = {
  119472. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  119473. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  119474. 6.5, 7.5, 8.5, 9.5,
  119475. };
  119476. static long _vq_quantmap__16c2_s_p8_1[] = {
  119477. 19, 17, 15, 13, 11, 9, 7, 5,
  119478. 3, 1, 0, 2, 4, 6, 8, 10,
  119479. 12, 14, 16, 18, 20,
  119480. };
  119481. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  119482. _vq_quantthresh__16c2_s_p8_1,
  119483. _vq_quantmap__16c2_s_p8_1,
  119484. 21,
  119485. 21
  119486. };
  119487. static static_codebook _16c2_s_p8_1 = {
  119488. 2, 441,
  119489. _vq_lengthlist__16c2_s_p8_1,
  119490. 1, -529268736, 1611661312, 5, 0,
  119491. _vq_quantlist__16c2_s_p8_1,
  119492. NULL,
  119493. &_vq_auxt__16c2_s_p8_1,
  119494. NULL,
  119495. 0
  119496. };
  119497. static long _vq_quantlist__16c2_s_p9_0[] = {
  119498. 6,
  119499. 5,
  119500. 7,
  119501. 4,
  119502. 8,
  119503. 3,
  119504. 9,
  119505. 2,
  119506. 10,
  119507. 1,
  119508. 11,
  119509. 0,
  119510. 12,
  119511. };
  119512. static long _vq_lengthlist__16c2_s_p9_0[] = {
  119513. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119514. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119515. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119516. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119517. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119518. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119519. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119520. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119521. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119522. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119523. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119524. };
  119525. static float _vq_quantthresh__16c2_s_p9_0[] = {
  119526. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  119527. 2327.5, 3258.5, 4189.5, 5120.5,
  119528. };
  119529. static long _vq_quantmap__16c2_s_p9_0[] = {
  119530. 11, 9, 7, 5, 3, 1, 0, 2,
  119531. 4, 6, 8, 10, 12,
  119532. };
  119533. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  119534. _vq_quantthresh__16c2_s_p9_0,
  119535. _vq_quantmap__16c2_s_p9_0,
  119536. 13,
  119537. 13
  119538. };
  119539. static static_codebook _16c2_s_p9_0 = {
  119540. 2, 169,
  119541. _vq_lengthlist__16c2_s_p9_0,
  119542. 1, -510275072, 1631393792, 4, 0,
  119543. _vq_quantlist__16c2_s_p9_0,
  119544. NULL,
  119545. &_vq_auxt__16c2_s_p9_0,
  119546. NULL,
  119547. 0
  119548. };
  119549. static long _vq_quantlist__16c2_s_p9_1[] = {
  119550. 8,
  119551. 7,
  119552. 9,
  119553. 6,
  119554. 10,
  119555. 5,
  119556. 11,
  119557. 4,
  119558. 12,
  119559. 3,
  119560. 13,
  119561. 2,
  119562. 14,
  119563. 1,
  119564. 15,
  119565. 0,
  119566. 16,
  119567. };
  119568. static long _vq_lengthlist__16c2_s_p9_1[] = {
  119569. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  119570. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  119571. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  119572. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  119573. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  119574. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  119575. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  119576. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  119577. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  119578. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  119579. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119580. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119581. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119582. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119583. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119584. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  119585. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  119586. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119587. 10,
  119588. };
  119589. static float _vq_quantthresh__16c2_s_p9_1[] = {
  119590. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  119591. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  119592. };
  119593. static long _vq_quantmap__16c2_s_p9_1[] = {
  119594. 15, 13, 11, 9, 7, 5, 3, 1,
  119595. 0, 2, 4, 6, 8, 10, 12, 14,
  119596. 16,
  119597. };
  119598. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  119599. _vq_quantthresh__16c2_s_p9_1,
  119600. _vq_quantmap__16c2_s_p9_1,
  119601. 17,
  119602. 17
  119603. };
  119604. static static_codebook _16c2_s_p9_1 = {
  119605. 2, 289,
  119606. _vq_lengthlist__16c2_s_p9_1,
  119607. 1, -518488064, 1622704128, 5, 0,
  119608. _vq_quantlist__16c2_s_p9_1,
  119609. NULL,
  119610. &_vq_auxt__16c2_s_p9_1,
  119611. NULL,
  119612. 0
  119613. };
  119614. static long _vq_quantlist__16c2_s_p9_2[] = {
  119615. 13,
  119616. 12,
  119617. 14,
  119618. 11,
  119619. 15,
  119620. 10,
  119621. 16,
  119622. 9,
  119623. 17,
  119624. 8,
  119625. 18,
  119626. 7,
  119627. 19,
  119628. 6,
  119629. 20,
  119630. 5,
  119631. 21,
  119632. 4,
  119633. 22,
  119634. 3,
  119635. 23,
  119636. 2,
  119637. 24,
  119638. 1,
  119639. 25,
  119640. 0,
  119641. 26,
  119642. };
  119643. static long _vq_lengthlist__16c2_s_p9_2[] = {
  119644. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  119645. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  119646. };
  119647. static float _vq_quantthresh__16c2_s_p9_2[] = {
  119648. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  119649. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119650. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  119651. 11.5, 12.5,
  119652. };
  119653. static long _vq_quantmap__16c2_s_p9_2[] = {
  119654. 25, 23, 21, 19, 17, 15, 13, 11,
  119655. 9, 7, 5, 3, 1, 0, 2, 4,
  119656. 6, 8, 10, 12, 14, 16, 18, 20,
  119657. 22, 24, 26,
  119658. };
  119659. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  119660. _vq_quantthresh__16c2_s_p9_2,
  119661. _vq_quantmap__16c2_s_p9_2,
  119662. 27,
  119663. 27
  119664. };
  119665. static static_codebook _16c2_s_p9_2 = {
  119666. 1, 27,
  119667. _vq_lengthlist__16c2_s_p9_2,
  119668. 1, -528875520, 1611661312, 5, 0,
  119669. _vq_quantlist__16c2_s_p9_2,
  119670. NULL,
  119671. &_vq_auxt__16c2_s_p9_2,
  119672. NULL,
  119673. 0
  119674. };
  119675. static long _huff_lengthlist__16c2_s_short[] = {
  119676. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  119677. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  119678. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  119679. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  119680. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  119681. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  119682. 15,12,14,14,
  119683. };
  119684. static static_codebook _huff_book__16c2_s_short = {
  119685. 2, 100,
  119686. _huff_lengthlist__16c2_s_short,
  119687. 0, 0, 0, 0, 0,
  119688. NULL,
  119689. NULL,
  119690. NULL,
  119691. NULL,
  119692. 0
  119693. };
  119694. static long _vq_quantlist__8c0_s_p1_0[] = {
  119695. 1,
  119696. 0,
  119697. 2,
  119698. };
  119699. static long _vq_lengthlist__8c0_s_p1_0[] = {
  119700. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  119701. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119705. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  119706. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119710. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119711. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  119746. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  119747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  119751. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  119752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  119756. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  119757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119791. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  119792. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119796. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  119797. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  119798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119801. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  119802. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  119803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120110. 0,
  120111. };
  120112. static float _vq_quantthresh__8c0_s_p1_0[] = {
  120113. -0.5, 0.5,
  120114. };
  120115. static long _vq_quantmap__8c0_s_p1_0[] = {
  120116. 1, 0, 2,
  120117. };
  120118. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  120119. _vq_quantthresh__8c0_s_p1_0,
  120120. _vq_quantmap__8c0_s_p1_0,
  120121. 3,
  120122. 3
  120123. };
  120124. static static_codebook _8c0_s_p1_0 = {
  120125. 8, 6561,
  120126. _vq_lengthlist__8c0_s_p1_0,
  120127. 1, -535822336, 1611661312, 2, 0,
  120128. _vq_quantlist__8c0_s_p1_0,
  120129. NULL,
  120130. &_vq_auxt__8c0_s_p1_0,
  120131. NULL,
  120132. 0
  120133. };
  120134. static long _vq_quantlist__8c0_s_p2_0[] = {
  120135. 2,
  120136. 1,
  120137. 3,
  120138. 0,
  120139. 4,
  120140. };
  120141. static long _vq_lengthlist__8c0_s_p2_0[] = {
  120142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120181. 0,
  120182. };
  120183. static float _vq_quantthresh__8c0_s_p2_0[] = {
  120184. -1.5, -0.5, 0.5, 1.5,
  120185. };
  120186. static long _vq_quantmap__8c0_s_p2_0[] = {
  120187. 3, 1, 0, 2, 4,
  120188. };
  120189. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  120190. _vq_quantthresh__8c0_s_p2_0,
  120191. _vq_quantmap__8c0_s_p2_0,
  120192. 5,
  120193. 5
  120194. };
  120195. static static_codebook _8c0_s_p2_0 = {
  120196. 4, 625,
  120197. _vq_lengthlist__8c0_s_p2_0,
  120198. 1, -533725184, 1611661312, 3, 0,
  120199. _vq_quantlist__8c0_s_p2_0,
  120200. NULL,
  120201. &_vq_auxt__8c0_s_p2_0,
  120202. NULL,
  120203. 0
  120204. };
  120205. static long _vq_quantlist__8c0_s_p3_0[] = {
  120206. 2,
  120207. 1,
  120208. 3,
  120209. 0,
  120210. 4,
  120211. };
  120212. static long _vq_lengthlist__8c0_s_p3_0[] = {
  120213. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  120215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120216. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  120218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120219. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  120220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120252. 0,
  120253. };
  120254. static float _vq_quantthresh__8c0_s_p3_0[] = {
  120255. -1.5, -0.5, 0.5, 1.5,
  120256. };
  120257. static long _vq_quantmap__8c0_s_p3_0[] = {
  120258. 3, 1, 0, 2, 4,
  120259. };
  120260. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  120261. _vq_quantthresh__8c0_s_p3_0,
  120262. _vq_quantmap__8c0_s_p3_0,
  120263. 5,
  120264. 5
  120265. };
  120266. static static_codebook _8c0_s_p3_0 = {
  120267. 4, 625,
  120268. _vq_lengthlist__8c0_s_p3_0,
  120269. 1, -533725184, 1611661312, 3, 0,
  120270. _vq_quantlist__8c0_s_p3_0,
  120271. NULL,
  120272. &_vq_auxt__8c0_s_p3_0,
  120273. NULL,
  120274. 0
  120275. };
  120276. static long _vq_quantlist__8c0_s_p4_0[] = {
  120277. 4,
  120278. 3,
  120279. 5,
  120280. 2,
  120281. 6,
  120282. 1,
  120283. 7,
  120284. 0,
  120285. 8,
  120286. };
  120287. static long _vq_lengthlist__8c0_s_p4_0[] = {
  120288. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  120289. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  120290. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  120291. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  120292. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120293. 0,
  120294. };
  120295. static float _vq_quantthresh__8c0_s_p4_0[] = {
  120296. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120297. };
  120298. static long _vq_quantmap__8c0_s_p4_0[] = {
  120299. 7, 5, 3, 1, 0, 2, 4, 6,
  120300. 8,
  120301. };
  120302. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  120303. _vq_quantthresh__8c0_s_p4_0,
  120304. _vq_quantmap__8c0_s_p4_0,
  120305. 9,
  120306. 9
  120307. };
  120308. static static_codebook _8c0_s_p4_0 = {
  120309. 2, 81,
  120310. _vq_lengthlist__8c0_s_p4_0,
  120311. 1, -531628032, 1611661312, 4, 0,
  120312. _vq_quantlist__8c0_s_p4_0,
  120313. NULL,
  120314. &_vq_auxt__8c0_s_p4_0,
  120315. NULL,
  120316. 0
  120317. };
  120318. static long _vq_quantlist__8c0_s_p5_0[] = {
  120319. 4,
  120320. 3,
  120321. 5,
  120322. 2,
  120323. 6,
  120324. 1,
  120325. 7,
  120326. 0,
  120327. 8,
  120328. };
  120329. static long _vq_lengthlist__8c0_s_p5_0[] = {
  120330. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  120331. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  120332. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  120333. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  120334. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  120335. 10,
  120336. };
  120337. static float _vq_quantthresh__8c0_s_p5_0[] = {
  120338. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120339. };
  120340. static long _vq_quantmap__8c0_s_p5_0[] = {
  120341. 7, 5, 3, 1, 0, 2, 4, 6,
  120342. 8,
  120343. };
  120344. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  120345. _vq_quantthresh__8c0_s_p5_0,
  120346. _vq_quantmap__8c0_s_p5_0,
  120347. 9,
  120348. 9
  120349. };
  120350. static static_codebook _8c0_s_p5_0 = {
  120351. 2, 81,
  120352. _vq_lengthlist__8c0_s_p5_0,
  120353. 1, -531628032, 1611661312, 4, 0,
  120354. _vq_quantlist__8c0_s_p5_0,
  120355. NULL,
  120356. &_vq_auxt__8c0_s_p5_0,
  120357. NULL,
  120358. 0
  120359. };
  120360. static long _vq_quantlist__8c0_s_p6_0[] = {
  120361. 8,
  120362. 7,
  120363. 9,
  120364. 6,
  120365. 10,
  120366. 5,
  120367. 11,
  120368. 4,
  120369. 12,
  120370. 3,
  120371. 13,
  120372. 2,
  120373. 14,
  120374. 1,
  120375. 15,
  120376. 0,
  120377. 16,
  120378. };
  120379. static long _vq_lengthlist__8c0_s_p6_0[] = {
  120380. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  120381. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  120382. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  120383. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  120384. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  120385. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  120386. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  120387. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  120388. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  120389. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  120390. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  120391. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  120392. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  120393. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  120394. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  120395. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  120396. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  120397. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  120398. 14,
  120399. };
  120400. static float _vq_quantthresh__8c0_s_p6_0[] = {
  120401. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  120402. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  120403. };
  120404. static long _vq_quantmap__8c0_s_p6_0[] = {
  120405. 15, 13, 11, 9, 7, 5, 3, 1,
  120406. 0, 2, 4, 6, 8, 10, 12, 14,
  120407. 16,
  120408. };
  120409. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  120410. _vq_quantthresh__8c0_s_p6_0,
  120411. _vq_quantmap__8c0_s_p6_0,
  120412. 17,
  120413. 17
  120414. };
  120415. static static_codebook _8c0_s_p6_0 = {
  120416. 2, 289,
  120417. _vq_lengthlist__8c0_s_p6_0,
  120418. 1, -529530880, 1611661312, 5, 0,
  120419. _vq_quantlist__8c0_s_p6_0,
  120420. NULL,
  120421. &_vq_auxt__8c0_s_p6_0,
  120422. NULL,
  120423. 0
  120424. };
  120425. static long _vq_quantlist__8c0_s_p7_0[] = {
  120426. 1,
  120427. 0,
  120428. 2,
  120429. };
  120430. static long _vq_lengthlist__8c0_s_p7_0[] = {
  120431. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  120432. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  120433. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  120434. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  120435. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  120436. 10,
  120437. };
  120438. static float _vq_quantthresh__8c0_s_p7_0[] = {
  120439. -5.5, 5.5,
  120440. };
  120441. static long _vq_quantmap__8c0_s_p7_0[] = {
  120442. 1, 0, 2,
  120443. };
  120444. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  120445. _vq_quantthresh__8c0_s_p7_0,
  120446. _vq_quantmap__8c0_s_p7_0,
  120447. 3,
  120448. 3
  120449. };
  120450. static static_codebook _8c0_s_p7_0 = {
  120451. 4, 81,
  120452. _vq_lengthlist__8c0_s_p7_0,
  120453. 1, -529137664, 1618345984, 2, 0,
  120454. _vq_quantlist__8c0_s_p7_0,
  120455. NULL,
  120456. &_vq_auxt__8c0_s_p7_0,
  120457. NULL,
  120458. 0
  120459. };
  120460. static long _vq_quantlist__8c0_s_p7_1[] = {
  120461. 5,
  120462. 4,
  120463. 6,
  120464. 3,
  120465. 7,
  120466. 2,
  120467. 8,
  120468. 1,
  120469. 9,
  120470. 0,
  120471. 10,
  120472. };
  120473. static long _vq_lengthlist__8c0_s_p7_1[] = {
  120474. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  120475. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  120476. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  120477. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  120478. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  120479. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  120480. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  120481. 10,10,10, 9, 9, 9,10,10,10,
  120482. };
  120483. static float _vq_quantthresh__8c0_s_p7_1[] = {
  120484. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120485. 3.5, 4.5,
  120486. };
  120487. static long _vq_quantmap__8c0_s_p7_1[] = {
  120488. 9, 7, 5, 3, 1, 0, 2, 4,
  120489. 6, 8, 10,
  120490. };
  120491. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  120492. _vq_quantthresh__8c0_s_p7_1,
  120493. _vq_quantmap__8c0_s_p7_1,
  120494. 11,
  120495. 11
  120496. };
  120497. static static_codebook _8c0_s_p7_1 = {
  120498. 2, 121,
  120499. _vq_lengthlist__8c0_s_p7_1,
  120500. 1, -531365888, 1611661312, 4, 0,
  120501. _vq_quantlist__8c0_s_p7_1,
  120502. NULL,
  120503. &_vq_auxt__8c0_s_p7_1,
  120504. NULL,
  120505. 0
  120506. };
  120507. static long _vq_quantlist__8c0_s_p8_0[] = {
  120508. 6,
  120509. 5,
  120510. 7,
  120511. 4,
  120512. 8,
  120513. 3,
  120514. 9,
  120515. 2,
  120516. 10,
  120517. 1,
  120518. 11,
  120519. 0,
  120520. 12,
  120521. };
  120522. static long _vq_lengthlist__8c0_s_p8_0[] = {
  120523. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  120524. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  120525. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  120526. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  120527. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  120528. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  120529. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  120530. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  120531. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  120532. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  120533. 0, 0,13,13,11,13,13,11,12,
  120534. };
  120535. static float _vq_quantthresh__8c0_s_p8_0[] = {
  120536. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  120537. 12.5, 17.5, 22.5, 27.5,
  120538. };
  120539. static long _vq_quantmap__8c0_s_p8_0[] = {
  120540. 11, 9, 7, 5, 3, 1, 0, 2,
  120541. 4, 6, 8, 10, 12,
  120542. };
  120543. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  120544. _vq_quantthresh__8c0_s_p8_0,
  120545. _vq_quantmap__8c0_s_p8_0,
  120546. 13,
  120547. 13
  120548. };
  120549. static static_codebook _8c0_s_p8_0 = {
  120550. 2, 169,
  120551. _vq_lengthlist__8c0_s_p8_0,
  120552. 1, -526516224, 1616117760, 4, 0,
  120553. _vq_quantlist__8c0_s_p8_0,
  120554. NULL,
  120555. &_vq_auxt__8c0_s_p8_0,
  120556. NULL,
  120557. 0
  120558. };
  120559. static long _vq_quantlist__8c0_s_p8_1[] = {
  120560. 2,
  120561. 1,
  120562. 3,
  120563. 0,
  120564. 4,
  120565. };
  120566. static long _vq_lengthlist__8c0_s_p8_1[] = {
  120567. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  120568. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  120569. };
  120570. static float _vq_quantthresh__8c0_s_p8_1[] = {
  120571. -1.5, -0.5, 0.5, 1.5,
  120572. };
  120573. static long _vq_quantmap__8c0_s_p8_1[] = {
  120574. 3, 1, 0, 2, 4,
  120575. };
  120576. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  120577. _vq_quantthresh__8c0_s_p8_1,
  120578. _vq_quantmap__8c0_s_p8_1,
  120579. 5,
  120580. 5
  120581. };
  120582. static static_codebook _8c0_s_p8_1 = {
  120583. 2, 25,
  120584. _vq_lengthlist__8c0_s_p8_1,
  120585. 1, -533725184, 1611661312, 3, 0,
  120586. _vq_quantlist__8c0_s_p8_1,
  120587. NULL,
  120588. &_vq_auxt__8c0_s_p8_1,
  120589. NULL,
  120590. 0
  120591. };
  120592. static long _vq_quantlist__8c0_s_p9_0[] = {
  120593. 1,
  120594. 0,
  120595. 2,
  120596. };
  120597. static long _vq_lengthlist__8c0_s_p9_0[] = {
  120598. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120599. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120600. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120601. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120602. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120603. 7,
  120604. };
  120605. static float _vq_quantthresh__8c0_s_p9_0[] = {
  120606. -157.5, 157.5,
  120607. };
  120608. static long _vq_quantmap__8c0_s_p9_0[] = {
  120609. 1, 0, 2,
  120610. };
  120611. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  120612. _vq_quantthresh__8c0_s_p9_0,
  120613. _vq_quantmap__8c0_s_p9_0,
  120614. 3,
  120615. 3
  120616. };
  120617. static static_codebook _8c0_s_p9_0 = {
  120618. 4, 81,
  120619. _vq_lengthlist__8c0_s_p9_0,
  120620. 1, -518803456, 1628680192, 2, 0,
  120621. _vq_quantlist__8c0_s_p9_0,
  120622. NULL,
  120623. &_vq_auxt__8c0_s_p9_0,
  120624. NULL,
  120625. 0
  120626. };
  120627. static long _vq_quantlist__8c0_s_p9_1[] = {
  120628. 7,
  120629. 6,
  120630. 8,
  120631. 5,
  120632. 9,
  120633. 4,
  120634. 10,
  120635. 3,
  120636. 11,
  120637. 2,
  120638. 12,
  120639. 1,
  120640. 13,
  120641. 0,
  120642. 14,
  120643. };
  120644. static long _vq_lengthlist__8c0_s_p9_1[] = {
  120645. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  120646. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  120647. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  120648. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  120649. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  120650. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  120651. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120652. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120653. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120654. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120655. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120656. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120657. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120658. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120659. 11,
  120660. };
  120661. static float _vq_quantthresh__8c0_s_p9_1[] = {
  120662. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  120663. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  120664. };
  120665. static long _vq_quantmap__8c0_s_p9_1[] = {
  120666. 13, 11, 9, 7, 5, 3, 1, 0,
  120667. 2, 4, 6, 8, 10, 12, 14,
  120668. };
  120669. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  120670. _vq_quantthresh__8c0_s_p9_1,
  120671. _vq_quantmap__8c0_s_p9_1,
  120672. 15,
  120673. 15
  120674. };
  120675. static static_codebook _8c0_s_p9_1 = {
  120676. 2, 225,
  120677. _vq_lengthlist__8c0_s_p9_1,
  120678. 1, -520986624, 1620377600, 4, 0,
  120679. _vq_quantlist__8c0_s_p9_1,
  120680. NULL,
  120681. &_vq_auxt__8c0_s_p9_1,
  120682. NULL,
  120683. 0
  120684. };
  120685. static long _vq_quantlist__8c0_s_p9_2[] = {
  120686. 10,
  120687. 9,
  120688. 11,
  120689. 8,
  120690. 12,
  120691. 7,
  120692. 13,
  120693. 6,
  120694. 14,
  120695. 5,
  120696. 15,
  120697. 4,
  120698. 16,
  120699. 3,
  120700. 17,
  120701. 2,
  120702. 18,
  120703. 1,
  120704. 19,
  120705. 0,
  120706. 20,
  120707. };
  120708. static long _vq_lengthlist__8c0_s_p9_2[] = {
  120709. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  120710. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  120711. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  120712. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  120713. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  120714. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  120715. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  120716. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  120717. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  120718. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  120719. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  120720. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  120721. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  120722. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  120723. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  120724. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  120725. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  120726. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  120727. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  120728. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  120729. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  120730. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  120731. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  120732. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  120733. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  120734. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  120735. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  120736. 10,11, 9,11,10, 9,10, 9,10,
  120737. };
  120738. static float _vq_quantthresh__8c0_s_p9_2[] = {
  120739. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  120740. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  120741. 6.5, 7.5, 8.5, 9.5,
  120742. };
  120743. static long _vq_quantmap__8c0_s_p9_2[] = {
  120744. 19, 17, 15, 13, 11, 9, 7, 5,
  120745. 3, 1, 0, 2, 4, 6, 8, 10,
  120746. 12, 14, 16, 18, 20,
  120747. };
  120748. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  120749. _vq_quantthresh__8c0_s_p9_2,
  120750. _vq_quantmap__8c0_s_p9_2,
  120751. 21,
  120752. 21
  120753. };
  120754. static static_codebook _8c0_s_p9_2 = {
  120755. 2, 441,
  120756. _vq_lengthlist__8c0_s_p9_2,
  120757. 1, -529268736, 1611661312, 5, 0,
  120758. _vq_quantlist__8c0_s_p9_2,
  120759. NULL,
  120760. &_vq_auxt__8c0_s_p9_2,
  120761. NULL,
  120762. 0
  120763. };
  120764. static long _huff_lengthlist__8c0_s_single[] = {
  120765. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  120766. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  120767. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  120768. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  120769. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  120770. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  120771. 17,16,17,17,
  120772. };
  120773. static static_codebook _huff_book__8c0_s_single = {
  120774. 2, 100,
  120775. _huff_lengthlist__8c0_s_single,
  120776. 0, 0, 0, 0, 0,
  120777. NULL,
  120778. NULL,
  120779. NULL,
  120780. NULL,
  120781. 0
  120782. };
  120783. static long _vq_quantlist__8c1_s_p1_0[] = {
  120784. 1,
  120785. 0,
  120786. 2,
  120787. };
  120788. static long _vq_lengthlist__8c1_s_p1_0[] = {
  120789. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  120790. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120794. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  120795. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120799. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  120800. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  120835. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  120836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  120840. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  120841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  120845. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  120846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120880. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  120881. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120885. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  120886. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  120887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120890. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  120891. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  120892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121199. 0,
  121200. };
  121201. static float _vq_quantthresh__8c1_s_p1_0[] = {
  121202. -0.5, 0.5,
  121203. };
  121204. static long _vq_quantmap__8c1_s_p1_0[] = {
  121205. 1, 0, 2,
  121206. };
  121207. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  121208. _vq_quantthresh__8c1_s_p1_0,
  121209. _vq_quantmap__8c1_s_p1_0,
  121210. 3,
  121211. 3
  121212. };
  121213. static static_codebook _8c1_s_p1_0 = {
  121214. 8, 6561,
  121215. _vq_lengthlist__8c1_s_p1_0,
  121216. 1, -535822336, 1611661312, 2, 0,
  121217. _vq_quantlist__8c1_s_p1_0,
  121218. NULL,
  121219. &_vq_auxt__8c1_s_p1_0,
  121220. NULL,
  121221. 0
  121222. };
  121223. static long _vq_quantlist__8c1_s_p2_0[] = {
  121224. 2,
  121225. 1,
  121226. 3,
  121227. 0,
  121228. 4,
  121229. };
  121230. static long _vq_lengthlist__8c1_s_p2_0[] = {
  121231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121270. 0,
  121271. };
  121272. static float _vq_quantthresh__8c1_s_p2_0[] = {
  121273. -1.5, -0.5, 0.5, 1.5,
  121274. };
  121275. static long _vq_quantmap__8c1_s_p2_0[] = {
  121276. 3, 1, 0, 2, 4,
  121277. };
  121278. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  121279. _vq_quantthresh__8c1_s_p2_0,
  121280. _vq_quantmap__8c1_s_p2_0,
  121281. 5,
  121282. 5
  121283. };
  121284. static static_codebook _8c1_s_p2_0 = {
  121285. 4, 625,
  121286. _vq_lengthlist__8c1_s_p2_0,
  121287. 1, -533725184, 1611661312, 3, 0,
  121288. _vq_quantlist__8c1_s_p2_0,
  121289. NULL,
  121290. &_vq_auxt__8c1_s_p2_0,
  121291. NULL,
  121292. 0
  121293. };
  121294. static long _vq_quantlist__8c1_s_p3_0[] = {
  121295. 2,
  121296. 1,
  121297. 3,
  121298. 0,
  121299. 4,
  121300. };
  121301. static long _vq_lengthlist__8c1_s_p3_0[] = {
  121302. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  121304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121305. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  121307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121308. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  121309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121341. 0,
  121342. };
  121343. static float _vq_quantthresh__8c1_s_p3_0[] = {
  121344. -1.5, -0.5, 0.5, 1.5,
  121345. };
  121346. static long _vq_quantmap__8c1_s_p3_0[] = {
  121347. 3, 1, 0, 2, 4,
  121348. };
  121349. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  121350. _vq_quantthresh__8c1_s_p3_0,
  121351. _vq_quantmap__8c1_s_p3_0,
  121352. 5,
  121353. 5
  121354. };
  121355. static static_codebook _8c1_s_p3_0 = {
  121356. 4, 625,
  121357. _vq_lengthlist__8c1_s_p3_0,
  121358. 1, -533725184, 1611661312, 3, 0,
  121359. _vq_quantlist__8c1_s_p3_0,
  121360. NULL,
  121361. &_vq_auxt__8c1_s_p3_0,
  121362. NULL,
  121363. 0
  121364. };
  121365. static long _vq_quantlist__8c1_s_p4_0[] = {
  121366. 4,
  121367. 3,
  121368. 5,
  121369. 2,
  121370. 6,
  121371. 1,
  121372. 7,
  121373. 0,
  121374. 8,
  121375. };
  121376. static long _vq_lengthlist__8c1_s_p4_0[] = {
  121377. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  121378. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  121379. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  121380. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  121381. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121382. 0,
  121383. };
  121384. static float _vq_quantthresh__8c1_s_p4_0[] = {
  121385. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121386. };
  121387. static long _vq_quantmap__8c1_s_p4_0[] = {
  121388. 7, 5, 3, 1, 0, 2, 4, 6,
  121389. 8,
  121390. };
  121391. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  121392. _vq_quantthresh__8c1_s_p4_0,
  121393. _vq_quantmap__8c1_s_p4_0,
  121394. 9,
  121395. 9
  121396. };
  121397. static static_codebook _8c1_s_p4_0 = {
  121398. 2, 81,
  121399. _vq_lengthlist__8c1_s_p4_0,
  121400. 1, -531628032, 1611661312, 4, 0,
  121401. _vq_quantlist__8c1_s_p4_0,
  121402. NULL,
  121403. &_vq_auxt__8c1_s_p4_0,
  121404. NULL,
  121405. 0
  121406. };
  121407. static long _vq_quantlist__8c1_s_p5_0[] = {
  121408. 4,
  121409. 3,
  121410. 5,
  121411. 2,
  121412. 6,
  121413. 1,
  121414. 7,
  121415. 0,
  121416. 8,
  121417. };
  121418. static long _vq_lengthlist__8c1_s_p5_0[] = {
  121419. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  121420. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  121421. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  121422. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  121423. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  121424. 10,
  121425. };
  121426. static float _vq_quantthresh__8c1_s_p5_0[] = {
  121427. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121428. };
  121429. static long _vq_quantmap__8c1_s_p5_0[] = {
  121430. 7, 5, 3, 1, 0, 2, 4, 6,
  121431. 8,
  121432. };
  121433. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  121434. _vq_quantthresh__8c1_s_p5_0,
  121435. _vq_quantmap__8c1_s_p5_0,
  121436. 9,
  121437. 9
  121438. };
  121439. static static_codebook _8c1_s_p5_0 = {
  121440. 2, 81,
  121441. _vq_lengthlist__8c1_s_p5_0,
  121442. 1, -531628032, 1611661312, 4, 0,
  121443. _vq_quantlist__8c1_s_p5_0,
  121444. NULL,
  121445. &_vq_auxt__8c1_s_p5_0,
  121446. NULL,
  121447. 0
  121448. };
  121449. static long _vq_quantlist__8c1_s_p6_0[] = {
  121450. 8,
  121451. 7,
  121452. 9,
  121453. 6,
  121454. 10,
  121455. 5,
  121456. 11,
  121457. 4,
  121458. 12,
  121459. 3,
  121460. 13,
  121461. 2,
  121462. 14,
  121463. 1,
  121464. 15,
  121465. 0,
  121466. 16,
  121467. };
  121468. static long _vq_lengthlist__8c1_s_p6_0[] = {
  121469. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  121470. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  121471. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  121472. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  121473. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  121474. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  121475. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  121476. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  121477. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  121478. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  121479. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  121480. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  121481. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  121482. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  121483. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  121484. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  121485. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  121486. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  121487. 14,
  121488. };
  121489. static float _vq_quantthresh__8c1_s_p6_0[] = {
  121490. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  121491. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  121492. };
  121493. static long _vq_quantmap__8c1_s_p6_0[] = {
  121494. 15, 13, 11, 9, 7, 5, 3, 1,
  121495. 0, 2, 4, 6, 8, 10, 12, 14,
  121496. 16,
  121497. };
  121498. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  121499. _vq_quantthresh__8c1_s_p6_0,
  121500. _vq_quantmap__8c1_s_p6_0,
  121501. 17,
  121502. 17
  121503. };
  121504. static static_codebook _8c1_s_p6_0 = {
  121505. 2, 289,
  121506. _vq_lengthlist__8c1_s_p6_0,
  121507. 1, -529530880, 1611661312, 5, 0,
  121508. _vq_quantlist__8c1_s_p6_0,
  121509. NULL,
  121510. &_vq_auxt__8c1_s_p6_0,
  121511. NULL,
  121512. 0
  121513. };
  121514. static long _vq_quantlist__8c1_s_p7_0[] = {
  121515. 1,
  121516. 0,
  121517. 2,
  121518. };
  121519. static long _vq_lengthlist__8c1_s_p7_0[] = {
  121520. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  121521. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  121522. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  121523. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  121524. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  121525. 9,
  121526. };
  121527. static float _vq_quantthresh__8c1_s_p7_0[] = {
  121528. -5.5, 5.5,
  121529. };
  121530. static long _vq_quantmap__8c1_s_p7_0[] = {
  121531. 1, 0, 2,
  121532. };
  121533. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  121534. _vq_quantthresh__8c1_s_p7_0,
  121535. _vq_quantmap__8c1_s_p7_0,
  121536. 3,
  121537. 3
  121538. };
  121539. static static_codebook _8c1_s_p7_0 = {
  121540. 4, 81,
  121541. _vq_lengthlist__8c1_s_p7_0,
  121542. 1, -529137664, 1618345984, 2, 0,
  121543. _vq_quantlist__8c1_s_p7_0,
  121544. NULL,
  121545. &_vq_auxt__8c1_s_p7_0,
  121546. NULL,
  121547. 0
  121548. };
  121549. static long _vq_quantlist__8c1_s_p7_1[] = {
  121550. 5,
  121551. 4,
  121552. 6,
  121553. 3,
  121554. 7,
  121555. 2,
  121556. 8,
  121557. 1,
  121558. 9,
  121559. 0,
  121560. 10,
  121561. };
  121562. static long _vq_lengthlist__8c1_s_p7_1[] = {
  121563. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  121564. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  121565. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  121566. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  121567. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  121568. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  121569. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  121570. 10,10,10, 8, 8, 8, 8, 8, 8,
  121571. };
  121572. static float _vq_quantthresh__8c1_s_p7_1[] = {
  121573. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  121574. 3.5, 4.5,
  121575. };
  121576. static long _vq_quantmap__8c1_s_p7_1[] = {
  121577. 9, 7, 5, 3, 1, 0, 2, 4,
  121578. 6, 8, 10,
  121579. };
  121580. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  121581. _vq_quantthresh__8c1_s_p7_1,
  121582. _vq_quantmap__8c1_s_p7_1,
  121583. 11,
  121584. 11
  121585. };
  121586. static static_codebook _8c1_s_p7_1 = {
  121587. 2, 121,
  121588. _vq_lengthlist__8c1_s_p7_1,
  121589. 1, -531365888, 1611661312, 4, 0,
  121590. _vq_quantlist__8c1_s_p7_1,
  121591. NULL,
  121592. &_vq_auxt__8c1_s_p7_1,
  121593. NULL,
  121594. 0
  121595. };
  121596. static long _vq_quantlist__8c1_s_p8_0[] = {
  121597. 6,
  121598. 5,
  121599. 7,
  121600. 4,
  121601. 8,
  121602. 3,
  121603. 9,
  121604. 2,
  121605. 10,
  121606. 1,
  121607. 11,
  121608. 0,
  121609. 12,
  121610. };
  121611. static long _vq_lengthlist__8c1_s_p8_0[] = {
  121612. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  121613. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  121614. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  121615. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  121616. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  121617. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  121618. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  121619. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  121620. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  121621. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  121622. 0,12,12,11,10,12,11,13,12,
  121623. };
  121624. static float _vq_quantthresh__8c1_s_p8_0[] = {
  121625. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  121626. 12.5, 17.5, 22.5, 27.5,
  121627. };
  121628. static long _vq_quantmap__8c1_s_p8_0[] = {
  121629. 11, 9, 7, 5, 3, 1, 0, 2,
  121630. 4, 6, 8, 10, 12,
  121631. };
  121632. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  121633. _vq_quantthresh__8c1_s_p8_0,
  121634. _vq_quantmap__8c1_s_p8_0,
  121635. 13,
  121636. 13
  121637. };
  121638. static static_codebook _8c1_s_p8_0 = {
  121639. 2, 169,
  121640. _vq_lengthlist__8c1_s_p8_0,
  121641. 1, -526516224, 1616117760, 4, 0,
  121642. _vq_quantlist__8c1_s_p8_0,
  121643. NULL,
  121644. &_vq_auxt__8c1_s_p8_0,
  121645. NULL,
  121646. 0
  121647. };
  121648. static long _vq_quantlist__8c1_s_p8_1[] = {
  121649. 2,
  121650. 1,
  121651. 3,
  121652. 0,
  121653. 4,
  121654. };
  121655. static long _vq_lengthlist__8c1_s_p8_1[] = {
  121656. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  121657. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  121658. };
  121659. static float _vq_quantthresh__8c1_s_p8_1[] = {
  121660. -1.5, -0.5, 0.5, 1.5,
  121661. };
  121662. static long _vq_quantmap__8c1_s_p8_1[] = {
  121663. 3, 1, 0, 2, 4,
  121664. };
  121665. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  121666. _vq_quantthresh__8c1_s_p8_1,
  121667. _vq_quantmap__8c1_s_p8_1,
  121668. 5,
  121669. 5
  121670. };
  121671. static static_codebook _8c1_s_p8_1 = {
  121672. 2, 25,
  121673. _vq_lengthlist__8c1_s_p8_1,
  121674. 1, -533725184, 1611661312, 3, 0,
  121675. _vq_quantlist__8c1_s_p8_1,
  121676. NULL,
  121677. &_vq_auxt__8c1_s_p8_1,
  121678. NULL,
  121679. 0
  121680. };
  121681. static long _vq_quantlist__8c1_s_p9_0[] = {
  121682. 6,
  121683. 5,
  121684. 7,
  121685. 4,
  121686. 8,
  121687. 3,
  121688. 9,
  121689. 2,
  121690. 10,
  121691. 1,
  121692. 11,
  121693. 0,
  121694. 12,
  121695. };
  121696. static long _vq_lengthlist__8c1_s_p9_0[] = {
  121697. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  121698. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  121699. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121700. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121701. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121702. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121703. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121704. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121705. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121706. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121707. 10,10,10,10,10, 9, 9, 9, 9,
  121708. };
  121709. static float _vq_quantthresh__8c1_s_p9_0[] = {
  121710. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  121711. 787.5, 1102.5, 1417.5, 1732.5,
  121712. };
  121713. static long _vq_quantmap__8c1_s_p9_0[] = {
  121714. 11, 9, 7, 5, 3, 1, 0, 2,
  121715. 4, 6, 8, 10, 12,
  121716. };
  121717. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  121718. _vq_quantthresh__8c1_s_p9_0,
  121719. _vq_quantmap__8c1_s_p9_0,
  121720. 13,
  121721. 13
  121722. };
  121723. static static_codebook _8c1_s_p9_0 = {
  121724. 2, 169,
  121725. _vq_lengthlist__8c1_s_p9_0,
  121726. 1, -513964032, 1628680192, 4, 0,
  121727. _vq_quantlist__8c1_s_p9_0,
  121728. NULL,
  121729. &_vq_auxt__8c1_s_p9_0,
  121730. NULL,
  121731. 0
  121732. };
  121733. static long _vq_quantlist__8c1_s_p9_1[] = {
  121734. 7,
  121735. 6,
  121736. 8,
  121737. 5,
  121738. 9,
  121739. 4,
  121740. 10,
  121741. 3,
  121742. 11,
  121743. 2,
  121744. 12,
  121745. 1,
  121746. 13,
  121747. 0,
  121748. 14,
  121749. };
  121750. static long _vq_lengthlist__8c1_s_p9_1[] = {
  121751. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  121752. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  121753. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  121754. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  121755. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  121756. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  121757. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  121758. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  121759. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  121760. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  121761. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  121762. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  121763. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  121764. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  121765. 15,
  121766. };
  121767. static float _vq_quantthresh__8c1_s_p9_1[] = {
  121768. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  121769. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  121770. };
  121771. static long _vq_quantmap__8c1_s_p9_1[] = {
  121772. 13, 11, 9, 7, 5, 3, 1, 0,
  121773. 2, 4, 6, 8, 10, 12, 14,
  121774. };
  121775. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  121776. _vq_quantthresh__8c1_s_p9_1,
  121777. _vq_quantmap__8c1_s_p9_1,
  121778. 15,
  121779. 15
  121780. };
  121781. static static_codebook _8c1_s_p9_1 = {
  121782. 2, 225,
  121783. _vq_lengthlist__8c1_s_p9_1,
  121784. 1, -520986624, 1620377600, 4, 0,
  121785. _vq_quantlist__8c1_s_p9_1,
  121786. NULL,
  121787. &_vq_auxt__8c1_s_p9_1,
  121788. NULL,
  121789. 0
  121790. };
  121791. static long _vq_quantlist__8c1_s_p9_2[] = {
  121792. 10,
  121793. 9,
  121794. 11,
  121795. 8,
  121796. 12,
  121797. 7,
  121798. 13,
  121799. 6,
  121800. 14,
  121801. 5,
  121802. 15,
  121803. 4,
  121804. 16,
  121805. 3,
  121806. 17,
  121807. 2,
  121808. 18,
  121809. 1,
  121810. 19,
  121811. 0,
  121812. 20,
  121813. };
  121814. static long _vq_lengthlist__8c1_s_p9_2[] = {
  121815. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  121816. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  121817. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  121818. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  121819. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  121820. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  121821. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  121822. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  121823. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  121824. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  121825. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  121826. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  121827. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  121828. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  121829. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  121830. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  121831. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121832. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  121833. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  121834. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  121835. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121836. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  121837. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  121838. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  121839. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  121840. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  121841. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  121842. 10,10,10,10,10,10,10,10,10,
  121843. };
  121844. static float _vq_quantthresh__8c1_s_p9_2[] = {
  121845. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  121846. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  121847. 6.5, 7.5, 8.5, 9.5,
  121848. };
  121849. static long _vq_quantmap__8c1_s_p9_2[] = {
  121850. 19, 17, 15, 13, 11, 9, 7, 5,
  121851. 3, 1, 0, 2, 4, 6, 8, 10,
  121852. 12, 14, 16, 18, 20,
  121853. };
  121854. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  121855. _vq_quantthresh__8c1_s_p9_2,
  121856. _vq_quantmap__8c1_s_p9_2,
  121857. 21,
  121858. 21
  121859. };
  121860. static static_codebook _8c1_s_p9_2 = {
  121861. 2, 441,
  121862. _vq_lengthlist__8c1_s_p9_2,
  121863. 1, -529268736, 1611661312, 5, 0,
  121864. _vq_quantlist__8c1_s_p9_2,
  121865. NULL,
  121866. &_vq_auxt__8c1_s_p9_2,
  121867. NULL,
  121868. 0
  121869. };
  121870. static long _huff_lengthlist__8c1_s_single[] = {
  121871. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  121872. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  121873. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  121874. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  121875. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  121876. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  121877. 9, 7, 7, 8,
  121878. };
  121879. static static_codebook _huff_book__8c1_s_single = {
  121880. 2, 100,
  121881. _huff_lengthlist__8c1_s_single,
  121882. 0, 0, 0, 0, 0,
  121883. NULL,
  121884. NULL,
  121885. NULL,
  121886. NULL,
  121887. 0
  121888. };
  121889. static long _huff_lengthlist__44c2_s_long[] = {
  121890. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  121891. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  121892. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  121893. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  121894. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  121895. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  121896. 10, 8, 8, 9,
  121897. };
  121898. static static_codebook _huff_book__44c2_s_long = {
  121899. 2, 100,
  121900. _huff_lengthlist__44c2_s_long,
  121901. 0, 0, 0, 0, 0,
  121902. NULL,
  121903. NULL,
  121904. NULL,
  121905. NULL,
  121906. 0
  121907. };
  121908. static long _vq_quantlist__44c2_s_p1_0[] = {
  121909. 1,
  121910. 0,
  121911. 2,
  121912. };
  121913. static long _vq_lengthlist__44c2_s_p1_0[] = {
  121914. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  121915. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121919. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  121920. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121924. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  121925. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  121960. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  121961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  121965. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  121966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  121970. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  121971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122005. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  122006. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122010. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  122011. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  122012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122015. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  122016. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  122017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122324. 0,
  122325. };
  122326. static float _vq_quantthresh__44c2_s_p1_0[] = {
  122327. -0.5, 0.5,
  122328. };
  122329. static long _vq_quantmap__44c2_s_p1_0[] = {
  122330. 1, 0, 2,
  122331. };
  122332. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  122333. _vq_quantthresh__44c2_s_p1_0,
  122334. _vq_quantmap__44c2_s_p1_0,
  122335. 3,
  122336. 3
  122337. };
  122338. static static_codebook _44c2_s_p1_0 = {
  122339. 8, 6561,
  122340. _vq_lengthlist__44c2_s_p1_0,
  122341. 1, -535822336, 1611661312, 2, 0,
  122342. _vq_quantlist__44c2_s_p1_0,
  122343. NULL,
  122344. &_vq_auxt__44c2_s_p1_0,
  122345. NULL,
  122346. 0
  122347. };
  122348. static long _vq_quantlist__44c2_s_p2_0[] = {
  122349. 2,
  122350. 1,
  122351. 3,
  122352. 0,
  122353. 4,
  122354. };
  122355. static long _vq_lengthlist__44c2_s_p2_0[] = {
  122356. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  122357. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  122358. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  122359. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  122360. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122365. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  122366. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  122367. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  122368. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122373. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  122374. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  122375. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  122376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122381. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  122382. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  122383. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  122384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122395. 0,
  122396. };
  122397. static float _vq_quantthresh__44c2_s_p2_0[] = {
  122398. -1.5, -0.5, 0.5, 1.5,
  122399. };
  122400. static long _vq_quantmap__44c2_s_p2_0[] = {
  122401. 3, 1, 0, 2, 4,
  122402. };
  122403. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  122404. _vq_quantthresh__44c2_s_p2_0,
  122405. _vq_quantmap__44c2_s_p2_0,
  122406. 5,
  122407. 5
  122408. };
  122409. static static_codebook _44c2_s_p2_0 = {
  122410. 4, 625,
  122411. _vq_lengthlist__44c2_s_p2_0,
  122412. 1, -533725184, 1611661312, 3, 0,
  122413. _vq_quantlist__44c2_s_p2_0,
  122414. NULL,
  122415. &_vq_auxt__44c2_s_p2_0,
  122416. NULL,
  122417. 0
  122418. };
  122419. static long _vq_quantlist__44c2_s_p3_0[] = {
  122420. 2,
  122421. 1,
  122422. 3,
  122423. 0,
  122424. 4,
  122425. };
  122426. static long _vq_lengthlist__44c2_s_p3_0[] = {
  122427. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  122429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122430. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  122432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122433. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  122434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122466. 0,
  122467. };
  122468. static float _vq_quantthresh__44c2_s_p3_0[] = {
  122469. -1.5, -0.5, 0.5, 1.5,
  122470. };
  122471. static long _vq_quantmap__44c2_s_p3_0[] = {
  122472. 3, 1, 0, 2, 4,
  122473. };
  122474. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  122475. _vq_quantthresh__44c2_s_p3_0,
  122476. _vq_quantmap__44c2_s_p3_0,
  122477. 5,
  122478. 5
  122479. };
  122480. static static_codebook _44c2_s_p3_0 = {
  122481. 4, 625,
  122482. _vq_lengthlist__44c2_s_p3_0,
  122483. 1, -533725184, 1611661312, 3, 0,
  122484. _vq_quantlist__44c2_s_p3_0,
  122485. NULL,
  122486. &_vq_auxt__44c2_s_p3_0,
  122487. NULL,
  122488. 0
  122489. };
  122490. static long _vq_quantlist__44c2_s_p4_0[] = {
  122491. 4,
  122492. 3,
  122493. 5,
  122494. 2,
  122495. 6,
  122496. 1,
  122497. 7,
  122498. 0,
  122499. 8,
  122500. };
  122501. static long _vq_lengthlist__44c2_s_p4_0[] = {
  122502. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  122503. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  122504. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  122505. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  122506. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122507. 0,
  122508. };
  122509. static float _vq_quantthresh__44c2_s_p4_0[] = {
  122510. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122511. };
  122512. static long _vq_quantmap__44c2_s_p4_0[] = {
  122513. 7, 5, 3, 1, 0, 2, 4, 6,
  122514. 8,
  122515. };
  122516. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  122517. _vq_quantthresh__44c2_s_p4_0,
  122518. _vq_quantmap__44c2_s_p4_0,
  122519. 9,
  122520. 9
  122521. };
  122522. static static_codebook _44c2_s_p4_0 = {
  122523. 2, 81,
  122524. _vq_lengthlist__44c2_s_p4_0,
  122525. 1, -531628032, 1611661312, 4, 0,
  122526. _vq_quantlist__44c2_s_p4_0,
  122527. NULL,
  122528. &_vq_auxt__44c2_s_p4_0,
  122529. NULL,
  122530. 0
  122531. };
  122532. static long _vq_quantlist__44c2_s_p5_0[] = {
  122533. 4,
  122534. 3,
  122535. 5,
  122536. 2,
  122537. 6,
  122538. 1,
  122539. 7,
  122540. 0,
  122541. 8,
  122542. };
  122543. static long _vq_lengthlist__44c2_s_p5_0[] = {
  122544. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  122545. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  122546. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  122547. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  122548. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  122549. 11,
  122550. };
  122551. static float _vq_quantthresh__44c2_s_p5_0[] = {
  122552. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122553. };
  122554. static long _vq_quantmap__44c2_s_p5_0[] = {
  122555. 7, 5, 3, 1, 0, 2, 4, 6,
  122556. 8,
  122557. };
  122558. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  122559. _vq_quantthresh__44c2_s_p5_0,
  122560. _vq_quantmap__44c2_s_p5_0,
  122561. 9,
  122562. 9
  122563. };
  122564. static static_codebook _44c2_s_p5_0 = {
  122565. 2, 81,
  122566. _vq_lengthlist__44c2_s_p5_0,
  122567. 1, -531628032, 1611661312, 4, 0,
  122568. _vq_quantlist__44c2_s_p5_0,
  122569. NULL,
  122570. &_vq_auxt__44c2_s_p5_0,
  122571. NULL,
  122572. 0
  122573. };
  122574. static long _vq_quantlist__44c2_s_p6_0[] = {
  122575. 8,
  122576. 7,
  122577. 9,
  122578. 6,
  122579. 10,
  122580. 5,
  122581. 11,
  122582. 4,
  122583. 12,
  122584. 3,
  122585. 13,
  122586. 2,
  122587. 14,
  122588. 1,
  122589. 15,
  122590. 0,
  122591. 16,
  122592. };
  122593. static long _vq_lengthlist__44c2_s_p6_0[] = {
  122594. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  122595. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  122596. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  122597. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  122598. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  122599. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  122600. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  122601. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  122602. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  122603. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122604. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  122605. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  122606. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  122607. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  122608. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  122609. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  122610. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  122611. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  122612. 14,
  122613. };
  122614. static float _vq_quantthresh__44c2_s_p6_0[] = {
  122615. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122616. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122617. };
  122618. static long _vq_quantmap__44c2_s_p6_0[] = {
  122619. 15, 13, 11, 9, 7, 5, 3, 1,
  122620. 0, 2, 4, 6, 8, 10, 12, 14,
  122621. 16,
  122622. };
  122623. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  122624. _vq_quantthresh__44c2_s_p6_0,
  122625. _vq_quantmap__44c2_s_p6_0,
  122626. 17,
  122627. 17
  122628. };
  122629. static static_codebook _44c2_s_p6_0 = {
  122630. 2, 289,
  122631. _vq_lengthlist__44c2_s_p6_0,
  122632. 1, -529530880, 1611661312, 5, 0,
  122633. _vq_quantlist__44c2_s_p6_0,
  122634. NULL,
  122635. &_vq_auxt__44c2_s_p6_0,
  122636. NULL,
  122637. 0
  122638. };
  122639. static long _vq_quantlist__44c2_s_p7_0[] = {
  122640. 1,
  122641. 0,
  122642. 2,
  122643. };
  122644. static long _vq_lengthlist__44c2_s_p7_0[] = {
  122645. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  122646. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  122647. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  122648. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  122649. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  122650. 11,
  122651. };
  122652. static float _vq_quantthresh__44c2_s_p7_0[] = {
  122653. -5.5, 5.5,
  122654. };
  122655. static long _vq_quantmap__44c2_s_p7_0[] = {
  122656. 1, 0, 2,
  122657. };
  122658. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  122659. _vq_quantthresh__44c2_s_p7_0,
  122660. _vq_quantmap__44c2_s_p7_0,
  122661. 3,
  122662. 3
  122663. };
  122664. static static_codebook _44c2_s_p7_0 = {
  122665. 4, 81,
  122666. _vq_lengthlist__44c2_s_p7_0,
  122667. 1, -529137664, 1618345984, 2, 0,
  122668. _vq_quantlist__44c2_s_p7_0,
  122669. NULL,
  122670. &_vq_auxt__44c2_s_p7_0,
  122671. NULL,
  122672. 0
  122673. };
  122674. static long _vq_quantlist__44c2_s_p7_1[] = {
  122675. 5,
  122676. 4,
  122677. 6,
  122678. 3,
  122679. 7,
  122680. 2,
  122681. 8,
  122682. 1,
  122683. 9,
  122684. 0,
  122685. 10,
  122686. };
  122687. static long _vq_lengthlist__44c2_s_p7_1[] = {
  122688. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  122689. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  122690. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  122691. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  122692. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  122693. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  122694. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  122695. 10,10,10, 8, 8, 8, 8, 8, 8,
  122696. };
  122697. static float _vq_quantthresh__44c2_s_p7_1[] = {
  122698. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122699. 3.5, 4.5,
  122700. };
  122701. static long _vq_quantmap__44c2_s_p7_1[] = {
  122702. 9, 7, 5, 3, 1, 0, 2, 4,
  122703. 6, 8, 10,
  122704. };
  122705. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  122706. _vq_quantthresh__44c2_s_p7_1,
  122707. _vq_quantmap__44c2_s_p7_1,
  122708. 11,
  122709. 11
  122710. };
  122711. static static_codebook _44c2_s_p7_1 = {
  122712. 2, 121,
  122713. _vq_lengthlist__44c2_s_p7_1,
  122714. 1, -531365888, 1611661312, 4, 0,
  122715. _vq_quantlist__44c2_s_p7_1,
  122716. NULL,
  122717. &_vq_auxt__44c2_s_p7_1,
  122718. NULL,
  122719. 0
  122720. };
  122721. static long _vq_quantlist__44c2_s_p8_0[] = {
  122722. 6,
  122723. 5,
  122724. 7,
  122725. 4,
  122726. 8,
  122727. 3,
  122728. 9,
  122729. 2,
  122730. 10,
  122731. 1,
  122732. 11,
  122733. 0,
  122734. 12,
  122735. };
  122736. static long _vq_lengthlist__44c2_s_p8_0[] = {
  122737. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  122738. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  122739. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  122740. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  122741. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  122742. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  122743. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  122744. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  122745. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  122746. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  122747. 0,12,12,12,12,13,12,14,14,
  122748. };
  122749. static float _vq_quantthresh__44c2_s_p8_0[] = {
  122750. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122751. 12.5, 17.5, 22.5, 27.5,
  122752. };
  122753. static long _vq_quantmap__44c2_s_p8_0[] = {
  122754. 11, 9, 7, 5, 3, 1, 0, 2,
  122755. 4, 6, 8, 10, 12,
  122756. };
  122757. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  122758. _vq_quantthresh__44c2_s_p8_0,
  122759. _vq_quantmap__44c2_s_p8_0,
  122760. 13,
  122761. 13
  122762. };
  122763. static static_codebook _44c2_s_p8_0 = {
  122764. 2, 169,
  122765. _vq_lengthlist__44c2_s_p8_0,
  122766. 1, -526516224, 1616117760, 4, 0,
  122767. _vq_quantlist__44c2_s_p8_0,
  122768. NULL,
  122769. &_vq_auxt__44c2_s_p8_0,
  122770. NULL,
  122771. 0
  122772. };
  122773. static long _vq_quantlist__44c2_s_p8_1[] = {
  122774. 2,
  122775. 1,
  122776. 3,
  122777. 0,
  122778. 4,
  122779. };
  122780. static long _vq_lengthlist__44c2_s_p8_1[] = {
  122781. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  122782. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  122783. };
  122784. static float _vq_quantthresh__44c2_s_p8_1[] = {
  122785. -1.5, -0.5, 0.5, 1.5,
  122786. };
  122787. static long _vq_quantmap__44c2_s_p8_1[] = {
  122788. 3, 1, 0, 2, 4,
  122789. };
  122790. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  122791. _vq_quantthresh__44c2_s_p8_1,
  122792. _vq_quantmap__44c2_s_p8_1,
  122793. 5,
  122794. 5
  122795. };
  122796. static static_codebook _44c2_s_p8_1 = {
  122797. 2, 25,
  122798. _vq_lengthlist__44c2_s_p8_1,
  122799. 1, -533725184, 1611661312, 3, 0,
  122800. _vq_quantlist__44c2_s_p8_1,
  122801. NULL,
  122802. &_vq_auxt__44c2_s_p8_1,
  122803. NULL,
  122804. 0
  122805. };
  122806. static long _vq_quantlist__44c2_s_p9_0[] = {
  122807. 6,
  122808. 5,
  122809. 7,
  122810. 4,
  122811. 8,
  122812. 3,
  122813. 9,
  122814. 2,
  122815. 10,
  122816. 1,
  122817. 11,
  122818. 0,
  122819. 12,
  122820. };
  122821. static long _vq_lengthlist__44c2_s_p9_0[] = {
  122822. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  122823. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  122824. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122825. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  122826. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122827. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122828. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122829. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122830. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122831. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122832. 11,11,11,11,11,11,11,11,11,
  122833. };
  122834. static float _vq_quantthresh__44c2_s_p9_0[] = {
  122835. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  122836. 552.5, 773.5, 994.5, 1215.5,
  122837. };
  122838. static long _vq_quantmap__44c2_s_p9_0[] = {
  122839. 11, 9, 7, 5, 3, 1, 0, 2,
  122840. 4, 6, 8, 10, 12,
  122841. };
  122842. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  122843. _vq_quantthresh__44c2_s_p9_0,
  122844. _vq_quantmap__44c2_s_p9_0,
  122845. 13,
  122846. 13
  122847. };
  122848. static static_codebook _44c2_s_p9_0 = {
  122849. 2, 169,
  122850. _vq_lengthlist__44c2_s_p9_0,
  122851. 1, -514541568, 1627103232, 4, 0,
  122852. _vq_quantlist__44c2_s_p9_0,
  122853. NULL,
  122854. &_vq_auxt__44c2_s_p9_0,
  122855. NULL,
  122856. 0
  122857. };
  122858. static long _vq_quantlist__44c2_s_p9_1[] = {
  122859. 6,
  122860. 5,
  122861. 7,
  122862. 4,
  122863. 8,
  122864. 3,
  122865. 9,
  122866. 2,
  122867. 10,
  122868. 1,
  122869. 11,
  122870. 0,
  122871. 12,
  122872. };
  122873. static long _vq_lengthlist__44c2_s_p9_1[] = {
  122874. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  122875. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  122876. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  122877. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  122878. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  122879. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  122880. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  122881. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  122882. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  122883. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  122884. 17,13,12,12,10,13,11,14,14,
  122885. };
  122886. static float _vq_quantthresh__44c2_s_p9_1[] = {
  122887. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  122888. 42.5, 59.5, 76.5, 93.5,
  122889. };
  122890. static long _vq_quantmap__44c2_s_p9_1[] = {
  122891. 11, 9, 7, 5, 3, 1, 0, 2,
  122892. 4, 6, 8, 10, 12,
  122893. };
  122894. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  122895. _vq_quantthresh__44c2_s_p9_1,
  122896. _vq_quantmap__44c2_s_p9_1,
  122897. 13,
  122898. 13
  122899. };
  122900. static static_codebook _44c2_s_p9_1 = {
  122901. 2, 169,
  122902. _vq_lengthlist__44c2_s_p9_1,
  122903. 1, -522616832, 1620115456, 4, 0,
  122904. _vq_quantlist__44c2_s_p9_1,
  122905. NULL,
  122906. &_vq_auxt__44c2_s_p9_1,
  122907. NULL,
  122908. 0
  122909. };
  122910. static long _vq_quantlist__44c2_s_p9_2[] = {
  122911. 8,
  122912. 7,
  122913. 9,
  122914. 6,
  122915. 10,
  122916. 5,
  122917. 11,
  122918. 4,
  122919. 12,
  122920. 3,
  122921. 13,
  122922. 2,
  122923. 14,
  122924. 1,
  122925. 15,
  122926. 0,
  122927. 16,
  122928. };
  122929. static long _vq_lengthlist__44c2_s_p9_2[] = {
  122930. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  122931. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  122932. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  122933. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  122934. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  122935. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  122936. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  122937. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  122938. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  122939. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  122940. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  122941. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  122942. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  122943. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  122944. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  122945. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  122946. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  122947. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  122948. 10,
  122949. };
  122950. static float _vq_quantthresh__44c2_s_p9_2[] = {
  122951. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122952. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122953. };
  122954. static long _vq_quantmap__44c2_s_p9_2[] = {
  122955. 15, 13, 11, 9, 7, 5, 3, 1,
  122956. 0, 2, 4, 6, 8, 10, 12, 14,
  122957. 16,
  122958. };
  122959. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  122960. _vq_quantthresh__44c2_s_p9_2,
  122961. _vq_quantmap__44c2_s_p9_2,
  122962. 17,
  122963. 17
  122964. };
  122965. static static_codebook _44c2_s_p9_2 = {
  122966. 2, 289,
  122967. _vq_lengthlist__44c2_s_p9_2,
  122968. 1, -529530880, 1611661312, 5, 0,
  122969. _vq_quantlist__44c2_s_p9_2,
  122970. NULL,
  122971. &_vq_auxt__44c2_s_p9_2,
  122972. NULL,
  122973. 0
  122974. };
  122975. static long _huff_lengthlist__44c2_s_short[] = {
  122976. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  122977. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  122978. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  122979. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  122980. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  122981. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  122982. 6, 8, 9,12,
  122983. };
  122984. static static_codebook _huff_book__44c2_s_short = {
  122985. 2, 100,
  122986. _huff_lengthlist__44c2_s_short,
  122987. 0, 0, 0, 0, 0,
  122988. NULL,
  122989. NULL,
  122990. NULL,
  122991. NULL,
  122992. 0
  122993. };
  122994. static long _huff_lengthlist__44c3_s_long[] = {
  122995. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  122996. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  122997. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  122998. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  122999. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  123000. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  123001. 9, 8, 8, 8,
  123002. };
  123003. static static_codebook _huff_book__44c3_s_long = {
  123004. 2, 100,
  123005. _huff_lengthlist__44c3_s_long,
  123006. 0, 0, 0, 0, 0,
  123007. NULL,
  123008. NULL,
  123009. NULL,
  123010. NULL,
  123011. 0
  123012. };
  123013. static long _vq_quantlist__44c3_s_p1_0[] = {
  123014. 1,
  123015. 0,
  123016. 2,
  123017. };
  123018. static long _vq_lengthlist__44c3_s_p1_0[] = {
  123019. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  123020. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  123025. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  123030. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123065. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  123066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  123070. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  123071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  123075. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  123076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123110. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  123111. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123115. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  123116. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  123117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123120. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  123121. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  123122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123429. 0,
  123430. };
  123431. static float _vq_quantthresh__44c3_s_p1_0[] = {
  123432. -0.5, 0.5,
  123433. };
  123434. static long _vq_quantmap__44c3_s_p1_0[] = {
  123435. 1, 0, 2,
  123436. };
  123437. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  123438. _vq_quantthresh__44c3_s_p1_0,
  123439. _vq_quantmap__44c3_s_p1_0,
  123440. 3,
  123441. 3
  123442. };
  123443. static static_codebook _44c3_s_p1_0 = {
  123444. 8, 6561,
  123445. _vq_lengthlist__44c3_s_p1_0,
  123446. 1, -535822336, 1611661312, 2, 0,
  123447. _vq_quantlist__44c3_s_p1_0,
  123448. NULL,
  123449. &_vq_auxt__44c3_s_p1_0,
  123450. NULL,
  123451. 0
  123452. };
  123453. static long _vq_quantlist__44c3_s_p2_0[] = {
  123454. 2,
  123455. 1,
  123456. 3,
  123457. 0,
  123458. 4,
  123459. };
  123460. static long _vq_lengthlist__44c3_s_p2_0[] = {
  123461. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  123462. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  123463. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  123464. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  123465. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123470. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  123471. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  123472. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  123473. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123478. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  123479. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  123480. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  123481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123486. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  123487. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  123488. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  123489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123500. 0,
  123501. };
  123502. static float _vq_quantthresh__44c3_s_p2_0[] = {
  123503. -1.5, -0.5, 0.5, 1.5,
  123504. };
  123505. static long _vq_quantmap__44c3_s_p2_0[] = {
  123506. 3, 1, 0, 2, 4,
  123507. };
  123508. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  123509. _vq_quantthresh__44c3_s_p2_0,
  123510. _vq_quantmap__44c3_s_p2_0,
  123511. 5,
  123512. 5
  123513. };
  123514. static static_codebook _44c3_s_p2_0 = {
  123515. 4, 625,
  123516. _vq_lengthlist__44c3_s_p2_0,
  123517. 1, -533725184, 1611661312, 3, 0,
  123518. _vq_quantlist__44c3_s_p2_0,
  123519. NULL,
  123520. &_vq_auxt__44c3_s_p2_0,
  123521. NULL,
  123522. 0
  123523. };
  123524. static long _vq_quantlist__44c3_s_p3_0[] = {
  123525. 2,
  123526. 1,
  123527. 3,
  123528. 0,
  123529. 4,
  123530. };
  123531. static long _vq_lengthlist__44c3_s_p3_0[] = {
  123532. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  123534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123535. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123538. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123571. 0,
  123572. };
  123573. static float _vq_quantthresh__44c3_s_p3_0[] = {
  123574. -1.5, -0.5, 0.5, 1.5,
  123575. };
  123576. static long _vq_quantmap__44c3_s_p3_0[] = {
  123577. 3, 1, 0, 2, 4,
  123578. };
  123579. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  123580. _vq_quantthresh__44c3_s_p3_0,
  123581. _vq_quantmap__44c3_s_p3_0,
  123582. 5,
  123583. 5
  123584. };
  123585. static static_codebook _44c3_s_p3_0 = {
  123586. 4, 625,
  123587. _vq_lengthlist__44c3_s_p3_0,
  123588. 1, -533725184, 1611661312, 3, 0,
  123589. _vq_quantlist__44c3_s_p3_0,
  123590. NULL,
  123591. &_vq_auxt__44c3_s_p3_0,
  123592. NULL,
  123593. 0
  123594. };
  123595. static long _vq_quantlist__44c3_s_p4_0[] = {
  123596. 4,
  123597. 3,
  123598. 5,
  123599. 2,
  123600. 6,
  123601. 1,
  123602. 7,
  123603. 0,
  123604. 8,
  123605. };
  123606. static long _vq_lengthlist__44c3_s_p4_0[] = {
  123607. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  123608. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  123609. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  123610. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  123611. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123612. 0,
  123613. };
  123614. static float _vq_quantthresh__44c3_s_p4_0[] = {
  123615. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123616. };
  123617. static long _vq_quantmap__44c3_s_p4_0[] = {
  123618. 7, 5, 3, 1, 0, 2, 4, 6,
  123619. 8,
  123620. };
  123621. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  123622. _vq_quantthresh__44c3_s_p4_0,
  123623. _vq_quantmap__44c3_s_p4_0,
  123624. 9,
  123625. 9
  123626. };
  123627. static static_codebook _44c3_s_p4_0 = {
  123628. 2, 81,
  123629. _vq_lengthlist__44c3_s_p4_0,
  123630. 1, -531628032, 1611661312, 4, 0,
  123631. _vq_quantlist__44c3_s_p4_0,
  123632. NULL,
  123633. &_vq_auxt__44c3_s_p4_0,
  123634. NULL,
  123635. 0
  123636. };
  123637. static long _vq_quantlist__44c3_s_p5_0[] = {
  123638. 4,
  123639. 3,
  123640. 5,
  123641. 2,
  123642. 6,
  123643. 1,
  123644. 7,
  123645. 0,
  123646. 8,
  123647. };
  123648. static long _vq_lengthlist__44c3_s_p5_0[] = {
  123649. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  123650. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  123651. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  123652. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  123653. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  123654. 11,
  123655. };
  123656. static float _vq_quantthresh__44c3_s_p5_0[] = {
  123657. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123658. };
  123659. static long _vq_quantmap__44c3_s_p5_0[] = {
  123660. 7, 5, 3, 1, 0, 2, 4, 6,
  123661. 8,
  123662. };
  123663. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  123664. _vq_quantthresh__44c3_s_p5_0,
  123665. _vq_quantmap__44c3_s_p5_0,
  123666. 9,
  123667. 9
  123668. };
  123669. static static_codebook _44c3_s_p5_0 = {
  123670. 2, 81,
  123671. _vq_lengthlist__44c3_s_p5_0,
  123672. 1, -531628032, 1611661312, 4, 0,
  123673. _vq_quantlist__44c3_s_p5_0,
  123674. NULL,
  123675. &_vq_auxt__44c3_s_p5_0,
  123676. NULL,
  123677. 0
  123678. };
  123679. static long _vq_quantlist__44c3_s_p6_0[] = {
  123680. 8,
  123681. 7,
  123682. 9,
  123683. 6,
  123684. 10,
  123685. 5,
  123686. 11,
  123687. 4,
  123688. 12,
  123689. 3,
  123690. 13,
  123691. 2,
  123692. 14,
  123693. 1,
  123694. 15,
  123695. 0,
  123696. 16,
  123697. };
  123698. static long _vq_lengthlist__44c3_s_p6_0[] = {
  123699. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123700. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  123701. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  123702. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123703. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123704. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  123705. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  123706. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  123707. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  123708. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  123709. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  123710. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  123711. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  123712. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  123713. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  123714. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  123715. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  123716. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  123717. 13,
  123718. };
  123719. static float _vq_quantthresh__44c3_s_p6_0[] = {
  123720. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123721. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123722. };
  123723. static long _vq_quantmap__44c3_s_p6_0[] = {
  123724. 15, 13, 11, 9, 7, 5, 3, 1,
  123725. 0, 2, 4, 6, 8, 10, 12, 14,
  123726. 16,
  123727. };
  123728. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  123729. _vq_quantthresh__44c3_s_p6_0,
  123730. _vq_quantmap__44c3_s_p6_0,
  123731. 17,
  123732. 17
  123733. };
  123734. static static_codebook _44c3_s_p6_0 = {
  123735. 2, 289,
  123736. _vq_lengthlist__44c3_s_p6_0,
  123737. 1, -529530880, 1611661312, 5, 0,
  123738. _vq_quantlist__44c3_s_p6_0,
  123739. NULL,
  123740. &_vq_auxt__44c3_s_p6_0,
  123741. NULL,
  123742. 0
  123743. };
  123744. static long _vq_quantlist__44c3_s_p7_0[] = {
  123745. 1,
  123746. 0,
  123747. 2,
  123748. };
  123749. static long _vq_lengthlist__44c3_s_p7_0[] = {
  123750. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  123751. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  123752. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  123753. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  123754. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  123755. 10,
  123756. };
  123757. static float _vq_quantthresh__44c3_s_p7_0[] = {
  123758. -5.5, 5.5,
  123759. };
  123760. static long _vq_quantmap__44c3_s_p7_0[] = {
  123761. 1, 0, 2,
  123762. };
  123763. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  123764. _vq_quantthresh__44c3_s_p7_0,
  123765. _vq_quantmap__44c3_s_p7_0,
  123766. 3,
  123767. 3
  123768. };
  123769. static static_codebook _44c3_s_p7_0 = {
  123770. 4, 81,
  123771. _vq_lengthlist__44c3_s_p7_0,
  123772. 1, -529137664, 1618345984, 2, 0,
  123773. _vq_quantlist__44c3_s_p7_0,
  123774. NULL,
  123775. &_vq_auxt__44c3_s_p7_0,
  123776. NULL,
  123777. 0
  123778. };
  123779. static long _vq_quantlist__44c3_s_p7_1[] = {
  123780. 5,
  123781. 4,
  123782. 6,
  123783. 3,
  123784. 7,
  123785. 2,
  123786. 8,
  123787. 1,
  123788. 9,
  123789. 0,
  123790. 10,
  123791. };
  123792. static long _vq_lengthlist__44c3_s_p7_1[] = {
  123793. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  123794. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  123795. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  123796. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  123797. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  123798. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  123799. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  123800. 10,10,10, 8, 8, 8, 8, 8, 8,
  123801. };
  123802. static float _vq_quantthresh__44c3_s_p7_1[] = {
  123803. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123804. 3.5, 4.5,
  123805. };
  123806. static long _vq_quantmap__44c3_s_p7_1[] = {
  123807. 9, 7, 5, 3, 1, 0, 2, 4,
  123808. 6, 8, 10,
  123809. };
  123810. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  123811. _vq_quantthresh__44c3_s_p7_1,
  123812. _vq_quantmap__44c3_s_p7_1,
  123813. 11,
  123814. 11
  123815. };
  123816. static static_codebook _44c3_s_p7_1 = {
  123817. 2, 121,
  123818. _vq_lengthlist__44c3_s_p7_1,
  123819. 1, -531365888, 1611661312, 4, 0,
  123820. _vq_quantlist__44c3_s_p7_1,
  123821. NULL,
  123822. &_vq_auxt__44c3_s_p7_1,
  123823. NULL,
  123824. 0
  123825. };
  123826. static long _vq_quantlist__44c3_s_p8_0[] = {
  123827. 6,
  123828. 5,
  123829. 7,
  123830. 4,
  123831. 8,
  123832. 3,
  123833. 9,
  123834. 2,
  123835. 10,
  123836. 1,
  123837. 11,
  123838. 0,
  123839. 12,
  123840. };
  123841. static long _vq_lengthlist__44c3_s_p8_0[] = {
  123842. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  123843. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  123844. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  123845. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  123846. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  123847. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  123848. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  123849. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  123850. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  123851. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  123852. 0,13,13,12,12,13,12,14,13,
  123853. };
  123854. static float _vq_quantthresh__44c3_s_p8_0[] = {
  123855. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123856. 12.5, 17.5, 22.5, 27.5,
  123857. };
  123858. static long _vq_quantmap__44c3_s_p8_0[] = {
  123859. 11, 9, 7, 5, 3, 1, 0, 2,
  123860. 4, 6, 8, 10, 12,
  123861. };
  123862. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  123863. _vq_quantthresh__44c3_s_p8_0,
  123864. _vq_quantmap__44c3_s_p8_0,
  123865. 13,
  123866. 13
  123867. };
  123868. static static_codebook _44c3_s_p8_0 = {
  123869. 2, 169,
  123870. _vq_lengthlist__44c3_s_p8_0,
  123871. 1, -526516224, 1616117760, 4, 0,
  123872. _vq_quantlist__44c3_s_p8_0,
  123873. NULL,
  123874. &_vq_auxt__44c3_s_p8_0,
  123875. NULL,
  123876. 0
  123877. };
  123878. static long _vq_quantlist__44c3_s_p8_1[] = {
  123879. 2,
  123880. 1,
  123881. 3,
  123882. 0,
  123883. 4,
  123884. };
  123885. static long _vq_lengthlist__44c3_s_p8_1[] = {
  123886. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  123887. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  123888. };
  123889. static float _vq_quantthresh__44c3_s_p8_1[] = {
  123890. -1.5, -0.5, 0.5, 1.5,
  123891. };
  123892. static long _vq_quantmap__44c3_s_p8_1[] = {
  123893. 3, 1, 0, 2, 4,
  123894. };
  123895. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  123896. _vq_quantthresh__44c3_s_p8_1,
  123897. _vq_quantmap__44c3_s_p8_1,
  123898. 5,
  123899. 5
  123900. };
  123901. static static_codebook _44c3_s_p8_1 = {
  123902. 2, 25,
  123903. _vq_lengthlist__44c3_s_p8_1,
  123904. 1, -533725184, 1611661312, 3, 0,
  123905. _vq_quantlist__44c3_s_p8_1,
  123906. NULL,
  123907. &_vq_auxt__44c3_s_p8_1,
  123908. NULL,
  123909. 0
  123910. };
  123911. static long _vq_quantlist__44c3_s_p9_0[] = {
  123912. 6,
  123913. 5,
  123914. 7,
  123915. 4,
  123916. 8,
  123917. 3,
  123918. 9,
  123919. 2,
  123920. 10,
  123921. 1,
  123922. 11,
  123923. 0,
  123924. 12,
  123925. };
  123926. static long _vq_lengthlist__44c3_s_p9_0[] = {
  123927. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  123928. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  123929. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123930. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  123931. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123932. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123933. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123934. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123935. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  123936. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123937. 11,11,11,11,11,11,11,11,11,
  123938. };
  123939. static float _vq_quantthresh__44c3_s_p9_0[] = {
  123940. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  123941. 637.5, 892.5, 1147.5, 1402.5,
  123942. };
  123943. static long _vq_quantmap__44c3_s_p9_0[] = {
  123944. 11, 9, 7, 5, 3, 1, 0, 2,
  123945. 4, 6, 8, 10, 12,
  123946. };
  123947. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  123948. _vq_quantthresh__44c3_s_p9_0,
  123949. _vq_quantmap__44c3_s_p9_0,
  123950. 13,
  123951. 13
  123952. };
  123953. static static_codebook _44c3_s_p9_0 = {
  123954. 2, 169,
  123955. _vq_lengthlist__44c3_s_p9_0,
  123956. 1, -514332672, 1627381760, 4, 0,
  123957. _vq_quantlist__44c3_s_p9_0,
  123958. NULL,
  123959. &_vq_auxt__44c3_s_p9_0,
  123960. NULL,
  123961. 0
  123962. };
  123963. static long _vq_quantlist__44c3_s_p9_1[] = {
  123964. 7,
  123965. 6,
  123966. 8,
  123967. 5,
  123968. 9,
  123969. 4,
  123970. 10,
  123971. 3,
  123972. 11,
  123973. 2,
  123974. 12,
  123975. 1,
  123976. 13,
  123977. 0,
  123978. 14,
  123979. };
  123980. static long _vq_lengthlist__44c3_s_p9_1[] = {
  123981. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  123982. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  123983. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  123984. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  123985. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  123986. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  123987. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  123988. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  123989. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  123990. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  123991. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  123992. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  123993. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  123994. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  123995. 15,
  123996. };
  123997. static float _vq_quantthresh__44c3_s_p9_1[] = {
  123998. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  123999. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  124000. };
  124001. static long _vq_quantmap__44c3_s_p9_1[] = {
  124002. 13, 11, 9, 7, 5, 3, 1, 0,
  124003. 2, 4, 6, 8, 10, 12, 14,
  124004. };
  124005. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  124006. _vq_quantthresh__44c3_s_p9_1,
  124007. _vq_quantmap__44c3_s_p9_1,
  124008. 15,
  124009. 15
  124010. };
  124011. static static_codebook _44c3_s_p9_1 = {
  124012. 2, 225,
  124013. _vq_lengthlist__44c3_s_p9_1,
  124014. 1, -522338304, 1620115456, 4, 0,
  124015. _vq_quantlist__44c3_s_p9_1,
  124016. NULL,
  124017. &_vq_auxt__44c3_s_p9_1,
  124018. NULL,
  124019. 0
  124020. };
  124021. static long _vq_quantlist__44c3_s_p9_2[] = {
  124022. 8,
  124023. 7,
  124024. 9,
  124025. 6,
  124026. 10,
  124027. 5,
  124028. 11,
  124029. 4,
  124030. 12,
  124031. 3,
  124032. 13,
  124033. 2,
  124034. 14,
  124035. 1,
  124036. 15,
  124037. 0,
  124038. 16,
  124039. };
  124040. static long _vq_lengthlist__44c3_s_p9_2[] = {
  124041. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  124042. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  124043. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  124044. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  124045. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  124046. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  124047. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  124048. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  124049. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  124050. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  124051. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  124052. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  124053. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  124054. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  124055. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  124056. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  124057. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  124058. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  124059. 10,
  124060. };
  124061. static float _vq_quantthresh__44c3_s_p9_2[] = {
  124062. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124063. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124064. };
  124065. static long _vq_quantmap__44c3_s_p9_2[] = {
  124066. 15, 13, 11, 9, 7, 5, 3, 1,
  124067. 0, 2, 4, 6, 8, 10, 12, 14,
  124068. 16,
  124069. };
  124070. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  124071. _vq_quantthresh__44c3_s_p9_2,
  124072. _vq_quantmap__44c3_s_p9_2,
  124073. 17,
  124074. 17
  124075. };
  124076. static static_codebook _44c3_s_p9_2 = {
  124077. 2, 289,
  124078. _vq_lengthlist__44c3_s_p9_2,
  124079. 1, -529530880, 1611661312, 5, 0,
  124080. _vq_quantlist__44c3_s_p9_2,
  124081. NULL,
  124082. &_vq_auxt__44c3_s_p9_2,
  124083. NULL,
  124084. 0
  124085. };
  124086. static long _huff_lengthlist__44c3_s_short[] = {
  124087. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  124088. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  124089. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  124090. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  124091. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  124092. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  124093. 6, 8, 9,11,
  124094. };
  124095. static static_codebook _huff_book__44c3_s_short = {
  124096. 2, 100,
  124097. _huff_lengthlist__44c3_s_short,
  124098. 0, 0, 0, 0, 0,
  124099. NULL,
  124100. NULL,
  124101. NULL,
  124102. NULL,
  124103. 0
  124104. };
  124105. static long _huff_lengthlist__44c4_s_long[] = {
  124106. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  124107. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  124108. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  124109. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  124110. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  124111. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  124112. 9, 8, 7, 7,
  124113. };
  124114. static static_codebook _huff_book__44c4_s_long = {
  124115. 2, 100,
  124116. _huff_lengthlist__44c4_s_long,
  124117. 0, 0, 0, 0, 0,
  124118. NULL,
  124119. NULL,
  124120. NULL,
  124121. NULL,
  124122. 0
  124123. };
  124124. static long _vq_quantlist__44c4_s_p1_0[] = {
  124125. 1,
  124126. 0,
  124127. 2,
  124128. };
  124129. static long _vq_lengthlist__44c4_s_p1_0[] = {
  124130. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  124131. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124135. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124136. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124140. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  124141. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  124176. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124181. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  124186. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124221. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124222. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124226. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124227. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  124228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124231. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124232. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124540. 0,
  124541. };
  124542. static float _vq_quantthresh__44c4_s_p1_0[] = {
  124543. -0.5, 0.5,
  124544. };
  124545. static long _vq_quantmap__44c4_s_p1_0[] = {
  124546. 1, 0, 2,
  124547. };
  124548. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  124549. _vq_quantthresh__44c4_s_p1_0,
  124550. _vq_quantmap__44c4_s_p1_0,
  124551. 3,
  124552. 3
  124553. };
  124554. static static_codebook _44c4_s_p1_0 = {
  124555. 8, 6561,
  124556. _vq_lengthlist__44c4_s_p1_0,
  124557. 1, -535822336, 1611661312, 2, 0,
  124558. _vq_quantlist__44c4_s_p1_0,
  124559. NULL,
  124560. &_vq_auxt__44c4_s_p1_0,
  124561. NULL,
  124562. 0
  124563. };
  124564. static long _vq_quantlist__44c4_s_p2_0[] = {
  124565. 2,
  124566. 1,
  124567. 3,
  124568. 0,
  124569. 4,
  124570. };
  124571. static long _vq_lengthlist__44c4_s_p2_0[] = {
  124572. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  124573. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  124574. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  124575. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  124576. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124581. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  124582. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  124583. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  124584. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124589. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  124590. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  124591. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  124592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124597. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  124598. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  124599. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  124600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124611. 0,
  124612. };
  124613. static float _vq_quantthresh__44c4_s_p2_0[] = {
  124614. -1.5, -0.5, 0.5, 1.5,
  124615. };
  124616. static long _vq_quantmap__44c4_s_p2_0[] = {
  124617. 3, 1, 0, 2, 4,
  124618. };
  124619. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  124620. _vq_quantthresh__44c4_s_p2_0,
  124621. _vq_quantmap__44c4_s_p2_0,
  124622. 5,
  124623. 5
  124624. };
  124625. static static_codebook _44c4_s_p2_0 = {
  124626. 4, 625,
  124627. _vq_lengthlist__44c4_s_p2_0,
  124628. 1, -533725184, 1611661312, 3, 0,
  124629. _vq_quantlist__44c4_s_p2_0,
  124630. NULL,
  124631. &_vq_auxt__44c4_s_p2_0,
  124632. NULL,
  124633. 0
  124634. };
  124635. static long _vq_quantlist__44c4_s_p3_0[] = {
  124636. 2,
  124637. 1,
  124638. 3,
  124639. 0,
  124640. 4,
  124641. };
  124642. static long _vq_lengthlist__44c4_s_p3_0[] = {
  124643. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  124645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124646. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  124648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124649. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124682. 0,
  124683. };
  124684. static float _vq_quantthresh__44c4_s_p3_0[] = {
  124685. -1.5, -0.5, 0.5, 1.5,
  124686. };
  124687. static long _vq_quantmap__44c4_s_p3_0[] = {
  124688. 3, 1, 0, 2, 4,
  124689. };
  124690. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  124691. _vq_quantthresh__44c4_s_p3_0,
  124692. _vq_quantmap__44c4_s_p3_0,
  124693. 5,
  124694. 5
  124695. };
  124696. static static_codebook _44c4_s_p3_0 = {
  124697. 4, 625,
  124698. _vq_lengthlist__44c4_s_p3_0,
  124699. 1, -533725184, 1611661312, 3, 0,
  124700. _vq_quantlist__44c4_s_p3_0,
  124701. NULL,
  124702. &_vq_auxt__44c4_s_p3_0,
  124703. NULL,
  124704. 0
  124705. };
  124706. static long _vq_quantlist__44c4_s_p4_0[] = {
  124707. 4,
  124708. 3,
  124709. 5,
  124710. 2,
  124711. 6,
  124712. 1,
  124713. 7,
  124714. 0,
  124715. 8,
  124716. };
  124717. static long _vq_lengthlist__44c4_s_p4_0[] = {
  124718. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  124719. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  124720. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  124721. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  124722. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124723. 0,
  124724. };
  124725. static float _vq_quantthresh__44c4_s_p4_0[] = {
  124726. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124727. };
  124728. static long _vq_quantmap__44c4_s_p4_0[] = {
  124729. 7, 5, 3, 1, 0, 2, 4, 6,
  124730. 8,
  124731. };
  124732. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  124733. _vq_quantthresh__44c4_s_p4_0,
  124734. _vq_quantmap__44c4_s_p4_0,
  124735. 9,
  124736. 9
  124737. };
  124738. static static_codebook _44c4_s_p4_0 = {
  124739. 2, 81,
  124740. _vq_lengthlist__44c4_s_p4_0,
  124741. 1, -531628032, 1611661312, 4, 0,
  124742. _vq_quantlist__44c4_s_p4_0,
  124743. NULL,
  124744. &_vq_auxt__44c4_s_p4_0,
  124745. NULL,
  124746. 0
  124747. };
  124748. static long _vq_quantlist__44c4_s_p5_0[] = {
  124749. 4,
  124750. 3,
  124751. 5,
  124752. 2,
  124753. 6,
  124754. 1,
  124755. 7,
  124756. 0,
  124757. 8,
  124758. };
  124759. static long _vq_lengthlist__44c4_s_p5_0[] = {
  124760. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  124761. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  124762. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  124763. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  124764. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  124765. 10,
  124766. };
  124767. static float _vq_quantthresh__44c4_s_p5_0[] = {
  124768. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124769. };
  124770. static long _vq_quantmap__44c4_s_p5_0[] = {
  124771. 7, 5, 3, 1, 0, 2, 4, 6,
  124772. 8,
  124773. };
  124774. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  124775. _vq_quantthresh__44c4_s_p5_0,
  124776. _vq_quantmap__44c4_s_p5_0,
  124777. 9,
  124778. 9
  124779. };
  124780. static static_codebook _44c4_s_p5_0 = {
  124781. 2, 81,
  124782. _vq_lengthlist__44c4_s_p5_0,
  124783. 1, -531628032, 1611661312, 4, 0,
  124784. _vq_quantlist__44c4_s_p5_0,
  124785. NULL,
  124786. &_vq_auxt__44c4_s_p5_0,
  124787. NULL,
  124788. 0
  124789. };
  124790. static long _vq_quantlist__44c4_s_p6_0[] = {
  124791. 8,
  124792. 7,
  124793. 9,
  124794. 6,
  124795. 10,
  124796. 5,
  124797. 11,
  124798. 4,
  124799. 12,
  124800. 3,
  124801. 13,
  124802. 2,
  124803. 14,
  124804. 1,
  124805. 15,
  124806. 0,
  124807. 16,
  124808. };
  124809. static long _vq_lengthlist__44c4_s_p6_0[] = {
  124810. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  124811. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124812. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  124813. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  124814. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  124815. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124816. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  124817. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  124818. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  124819. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  124820. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  124821. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  124822. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  124823. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  124824. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  124825. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  124826. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  124827. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  124828. 13,
  124829. };
  124830. static float _vq_quantthresh__44c4_s_p6_0[] = {
  124831. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124832. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124833. };
  124834. static long _vq_quantmap__44c4_s_p6_0[] = {
  124835. 15, 13, 11, 9, 7, 5, 3, 1,
  124836. 0, 2, 4, 6, 8, 10, 12, 14,
  124837. 16,
  124838. };
  124839. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  124840. _vq_quantthresh__44c4_s_p6_0,
  124841. _vq_quantmap__44c4_s_p6_0,
  124842. 17,
  124843. 17
  124844. };
  124845. static static_codebook _44c4_s_p6_0 = {
  124846. 2, 289,
  124847. _vq_lengthlist__44c4_s_p6_0,
  124848. 1, -529530880, 1611661312, 5, 0,
  124849. _vq_quantlist__44c4_s_p6_0,
  124850. NULL,
  124851. &_vq_auxt__44c4_s_p6_0,
  124852. NULL,
  124853. 0
  124854. };
  124855. static long _vq_quantlist__44c4_s_p7_0[] = {
  124856. 1,
  124857. 0,
  124858. 2,
  124859. };
  124860. static long _vq_lengthlist__44c4_s_p7_0[] = {
  124861. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  124862. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  124863. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  124864. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  124865. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  124866. 10,
  124867. };
  124868. static float _vq_quantthresh__44c4_s_p7_0[] = {
  124869. -5.5, 5.5,
  124870. };
  124871. static long _vq_quantmap__44c4_s_p7_0[] = {
  124872. 1, 0, 2,
  124873. };
  124874. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  124875. _vq_quantthresh__44c4_s_p7_0,
  124876. _vq_quantmap__44c4_s_p7_0,
  124877. 3,
  124878. 3
  124879. };
  124880. static static_codebook _44c4_s_p7_0 = {
  124881. 4, 81,
  124882. _vq_lengthlist__44c4_s_p7_0,
  124883. 1, -529137664, 1618345984, 2, 0,
  124884. _vq_quantlist__44c4_s_p7_0,
  124885. NULL,
  124886. &_vq_auxt__44c4_s_p7_0,
  124887. NULL,
  124888. 0
  124889. };
  124890. static long _vq_quantlist__44c4_s_p7_1[] = {
  124891. 5,
  124892. 4,
  124893. 6,
  124894. 3,
  124895. 7,
  124896. 2,
  124897. 8,
  124898. 1,
  124899. 9,
  124900. 0,
  124901. 10,
  124902. };
  124903. static long _vq_lengthlist__44c4_s_p7_1[] = {
  124904. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  124905. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  124906. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  124907. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  124908. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124909. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  124910. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  124911. 10,10,10, 8, 8, 8, 8, 9, 9,
  124912. };
  124913. static float _vq_quantthresh__44c4_s_p7_1[] = {
  124914. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124915. 3.5, 4.5,
  124916. };
  124917. static long _vq_quantmap__44c4_s_p7_1[] = {
  124918. 9, 7, 5, 3, 1, 0, 2, 4,
  124919. 6, 8, 10,
  124920. };
  124921. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  124922. _vq_quantthresh__44c4_s_p7_1,
  124923. _vq_quantmap__44c4_s_p7_1,
  124924. 11,
  124925. 11
  124926. };
  124927. static static_codebook _44c4_s_p7_1 = {
  124928. 2, 121,
  124929. _vq_lengthlist__44c4_s_p7_1,
  124930. 1, -531365888, 1611661312, 4, 0,
  124931. _vq_quantlist__44c4_s_p7_1,
  124932. NULL,
  124933. &_vq_auxt__44c4_s_p7_1,
  124934. NULL,
  124935. 0
  124936. };
  124937. static long _vq_quantlist__44c4_s_p8_0[] = {
  124938. 6,
  124939. 5,
  124940. 7,
  124941. 4,
  124942. 8,
  124943. 3,
  124944. 9,
  124945. 2,
  124946. 10,
  124947. 1,
  124948. 11,
  124949. 0,
  124950. 12,
  124951. };
  124952. static long _vq_lengthlist__44c4_s_p8_0[] = {
  124953. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  124954. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  124955. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124956. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  124957. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  124958. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  124959. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  124960. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  124961. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  124962. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  124963. 0,13,12,12,12,12,12,13,13,
  124964. };
  124965. static float _vq_quantthresh__44c4_s_p8_0[] = {
  124966. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124967. 12.5, 17.5, 22.5, 27.5,
  124968. };
  124969. static long _vq_quantmap__44c4_s_p8_0[] = {
  124970. 11, 9, 7, 5, 3, 1, 0, 2,
  124971. 4, 6, 8, 10, 12,
  124972. };
  124973. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  124974. _vq_quantthresh__44c4_s_p8_0,
  124975. _vq_quantmap__44c4_s_p8_0,
  124976. 13,
  124977. 13
  124978. };
  124979. static static_codebook _44c4_s_p8_0 = {
  124980. 2, 169,
  124981. _vq_lengthlist__44c4_s_p8_0,
  124982. 1, -526516224, 1616117760, 4, 0,
  124983. _vq_quantlist__44c4_s_p8_0,
  124984. NULL,
  124985. &_vq_auxt__44c4_s_p8_0,
  124986. NULL,
  124987. 0
  124988. };
  124989. static long _vq_quantlist__44c4_s_p8_1[] = {
  124990. 2,
  124991. 1,
  124992. 3,
  124993. 0,
  124994. 4,
  124995. };
  124996. static long _vq_lengthlist__44c4_s_p8_1[] = {
  124997. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  124998. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  124999. };
  125000. static float _vq_quantthresh__44c4_s_p8_1[] = {
  125001. -1.5, -0.5, 0.5, 1.5,
  125002. };
  125003. static long _vq_quantmap__44c4_s_p8_1[] = {
  125004. 3, 1, 0, 2, 4,
  125005. };
  125006. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  125007. _vq_quantthresh__44c4_s_p8_1,
  125008. _vq_quantmap__44c4_s_p8_1,
  125009. 5,
  125010. 5
  125011. };
  125012. static static_codebook _44c4_s_p8_1 = {
  125013. 2, 25,
  125014. _vq_lengthlist__44c4_s_p8_1,
  125015. 1, -533725184, 1611661312, 3, 0,
  125016. _vq_quantlist__44c4_s_p8_1,
  125017. NULL,
  125018. &_vq_auxt__44c4_s_p8_1,
  125019. NULL,
  125020. 0
  125021. };
  125022. static long _vq_quantlist__44c4_s_p9_0[] = {
  125023. 6,
  125024. 5,
  125025. 7,
  125026. 4,
  125027. 8,
  125028. 3,
  125029. 9,
  125030. 2,
  125031. 10,
  125032. 1,
  125033. 11,
  125034. 0,
  125035. 12,
  125036. };
  125037. static long _vq_lengthlist__44c4_s_p9_0[] = {
  125038. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  125039. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  125040. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125041. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125042. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125043. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125044. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125045. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125046. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125047. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125048. 12,12,12,12,12,12,12,12,12,
  125049. };
  125050. static float _vq_quantthresh__44c4_s_p9_0[] = {
  125051. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  125052. 787.5, 1102.5, 1417.5, 1732.5,
  125053. };
  125054. static long _vq_quantmap__44c4_s_p9_0[] = {
  125055. 11, 9, 7, 5, 3, 1, 0, 2,
  125056. 4, 6, 8, 10, 12,
  125057. };
  125058. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  125059. _vq_quantthresh__44c4_s_p9_0,
  125060. _vq_quantmap__44c4_s_p9_0,
  125061. 13,
  125062. 13
  125063. };
  125064. static static_codebook _44c4_s_p9_0 = {
  125065. 2, 169,
  125066. _vq_lengthlist__44c4_s_p9_0,
  125067. 1, -513964032, 1628680192, 4, 0,
  125068. _vq_quantlist__44c4_s_p9_0,
  125069. NULL,
  125070. &_vq_auxt__44c4_s_p9_0,
  125071. NULL,
  125072. 0
  125073. };
  125074. static long _vq_quantlist__44c4_s_p9_1[] = {
  125075. 7,
  125076. 6,
  125077. 8,
  125078. 5,
  125079. 9,
  125080. 4,
  125081. 10,
  125082. 3,
  125083. 11,
  125084. 2,
  125085. 12,
  125086. 1,
  125087. 13,
  125088. 0,
  125089. 14,
  125090. };
  125091. static long _vq_lengthlist__44c4_s_p9_1[] = {
  125092. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  125093. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  125094. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  125095. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  125096. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  125097. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  125098. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  125099. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  125100. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  125101. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  125102. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  125103. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  125104. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  125105. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  125106. 15,
  125107. };
  125108. static float _vq_quantthresh__44c4_s_p9_1[] = {
  125109. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125110. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125111. };
  125112. static long _vq_quantmap__44c4_s_p9_1[] = {
  125113. 13, 11, 9, 7, 5, 3, 1, 0,
  125114. 2, 4, 6, 8, 10, 12, 14,
  125115. };
  125116. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  125117. _vq_quantthresh__44c4_s_p9_1,
  125118. _vq_quantmap__44c4_s_p9_1,
  125119. 15,
  125120. 15
  125121. };
  125122. static static_codebook _44c4_s_p9_1 = {
  125123. 2, 225,
  125124. _vq_lengthlist__44c4_s_p9_1,
  125125. 1, -520986624, 1620377600, 4, 0,
  125126. _vq_quantlist__44c4_s_p9_1,
  125127. NULL,
  125128. &_vq_auxt__44c4_s_p9_1,
  125129. NULL,
  125130. 0
  125131. };
  125132. static long _vq_quantlist__44c4_s_p9_2[] = {
  125133. 10,
  125134. 9,
  125135. 11,
  125136. 8,
  125137. 12,
  125138. 7,
  125139. 13,
  125140. 6,
  125141. 14,
  125142. 5,
  125143. 15,
  125144. 4,
  125145. 16,
  125146. 3,
  125147. 17,
  125148. 2,
  125149. 18,
  125150. 1,
  125151. 19,
  125152. 0,
  125153. 20,
  125154. };
  125155. static long _vq_lengthlist__44c4_s_p9_2[] = {
  125156. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  125157. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  125158. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  125159. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  125160. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  125161. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  125162. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  125163. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125164. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  125165. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  125166. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  125167. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  125168. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  125169. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  125170. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  125171. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  125172. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  125173. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  125174. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  125175. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  125176. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125177. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  125178. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  125179. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  125180. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  125181. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  125182. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  125183. 10,10,10,10,10,10,10,10,10,
  125184. };
  125185. static float _vq_quantthresh__44c4_s_p9_2[] = {
  125186. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125187. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125188. 6.5, 7.5, 8.5, 9.5,
  125189. };
  125190. static long _vq_quantmap__44c4_s_p9_2[] = {
  125191. 19, 17, 15, 13, 11, 9, 7, 5,
  125192. 3, 1, 0, 2, 4, 6, 8, 10,
  125193. 12, 14, 16, 18, 20,
  125194. };
  125195. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  125196. _vq_quantthresh__44c4_s_p9_2,
  125197. _vq_quantmap__44c4_s_p9_2,
  125198. 21,
  125199. 21
  125200. };
  125201. static static_codebook _44c4_s_p9_2 = {
  125202. 2, 441,
  125203. _vq_lengthlist__44c4_s_p9_2,
  125204. 1, -529268736, 1611661312, 5, 0,
  125205. _vq_quantlist__44c4_s_p9_2,
  125206. NULL,
  125207. &_vq_auxt__44c4_s_p9_2,
  125208. NULL,
  125209. 0
  125210. };
  125211. static long _huff_lengthlist__44c4_s_short[] = {
  125212. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  125213. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  125214. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  125215. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  125216. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  125217. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  125218. 7, 9,12,17,
  125219. };
  125220. static static_codebook _huff_book__44c4_s_short = {
  125221. 2, 100,
  125222. _huff_lengthlist__44c4_s_short,
  125223. 0, 0, 0, 0, 0,
  125224. NULL,
  125225. NULL,
  125226. NULL,
  125227. NULL,
  125228. 0
  125229. };
  125230. static long _huff_lengthlist__44c5_s_long[] = {
  125231. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  125232. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  125233. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  125234. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  125235. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  125236. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  125237. 9, 8, 7, 7,
  125238. };
  125239. static static_codebook _huff_book__44c5_s_long = {
  125240. 2, 100,
  125241. _huff_lengthlist__44c5_s_long,
  125242. 0, 0, 0, 0, 0,
  125243. NULL,
  125244. NULL,
  125245. NULL,
  125246. NULL,
  125247. 0
  125248. };
  125249. static long _vq_quantlist__44c5_s_p1_0[] = {
  125250. 1,
  125251. 0,
  125252. 2,
  125253. };
  125254. static long _vq_lengthlist__44c5_s_p1_0[] = {
  125255. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  125256. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125260. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  125261. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125265. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  125266. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  125301. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  125306. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  125307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125311. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  125312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125346. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125347. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125351. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  125352. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  125353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125356. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  125357. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  125358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125665. 0,
  125666. };
  125667. static float _vq_quantthresh__44c5_s_p1_0[] = {
  125668. -0.5, 0.5,
  125669. };
  125670. static long _vq_quantmap__44c5_s_p1_0[] = {
  125671. 1, 0, 2,
  125672. };
  125673. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  125674. _vq_quantthresh__44c5_s_p1_0,
  125675. _vq_quantmap__44c5_s_p1_0,
  125676. 3,
  125677. 3
  125678. };
  125679. static static_codebook _44c5_s_p1_0 = {
  125680. 8, 6561,
  125681. _vq_lengthlist__44c5_s_p1_0,
  125682. 1, -535822336, 1611661312, 2, 0,
  125683. _vq_quantlist__44c5_s_p1_0,
  125684. NULL,
  125685. &_vq_auxt__44c5_s_p1_0,
  125686. NULL,
  125687. 0
  125688. };
  125689. static long _vq_quantlist__44c5_s_p2_0[] = {
  125690. 2,
  125691. 1,
  125692. 3,
  125693. 0,
  125694. 4,
  125695. };
  125696. static long _vq_lengthlist__44c5_s_p2_0[] = {
  125697. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  125698. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  125699. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125700. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  125701. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125706. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  125707. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  125708. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  125709. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125714. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  125715. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  125716. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  125717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  125723. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  125724. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  125725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0,
  125737. };
  125738. static float _vq_quantthresh__44c5_s_p2_0[] = {
  125739. -1.5, -0.5, 0.5, 1.5,
  125740. };
  125741. static long _vq_quantmap__44c5_s_p2_0[] = {
  125742. 3, 1, 0, 2, 4,
  125743. };
  125744. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  125745. _vq_quantthresh__44c5_s_p2_0,
  125746. _vq_quantmap__44c5_s_p2_0,
  125747. 5,
  125748. 5
  125749. };
  125750. static static_codebook _44c5_s_p2_0 = {
  125751. 4, 625,
  125752. _vq_lengthlist__44c5_s_p2_0,
  125753. 1, -533725184, 1611661312, 3, 0,
  125754. _vq_quantlist__44c5_s_p2_0,
  125755. NULL,
  125756. &_vq_auxt__44c5_s_p2_0,
  125757. NULL,
  125758. 0
  125759. };
  125760. static long _vq_quantlist__44c5_s_p3_0[] = {
  125761. 2,
  125762. 1,
  125763. 3,
  125764. 0,
  125765. 4,
  125766. };
  125767. static long _vq_lengthlist__44c5_s_p3_0[] = {
  125768. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  125770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125771. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  125773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125774. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  125775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0,
  125808. };
  125809. static float _vq_quantthresh__44c5_s_p3_0[] = {
  125810. -1.5, -0.5, 0.5, 1.5,
  125811. };
  125812. static long _vq_quantmap__44c5_s_p3_0[] = {
  125813. 3, 1, 0, 2, 4,
  125814. };
  125815. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  125816. _vq_quantthresh__44c5_s_p3_0,
  125817. _vq_quantmap__44c5_s_p3_0,
  125818. 5,
  125819. 5
  125820. };
  125821. static static_codebook _44c5_s_p3_0 = {
  125822. 4, 625,
  125823. _vq_lengthlist__44c5_s_p3_0,
  125824. 1, -533725184, 1611661312, 3, 0,
  125825. _vq_quantlist__44c5_s_p3_0,
  125826. NULL,
  125827. &_vq_auxt__44c5_s_p3_0,
  125828. NULL,
  125829. 0
  125830. };
  125831. static long _vq_quantlist__44c5_s_p4_0[] = {
  125832. 4,
  125833. 3,
  125834. 5,
  125835. 2,
  125836. 6,
  125837. 1,
  125838. 7,
  125839. 0,
  125840. 8,
  125841. };
  125842. static long _vq_lengthlist__44c5_s_p4_0[] = {
  125843. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  125844. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  125845. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  125846. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  125847. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125848. 0,
  125849. };
  125850. static float _vq_quantthresh__44c5_s_p4_0[] = {
  125851. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125852. };
  125853. static long _vq_quantmap__44c5_s_p4_0[] = {
  125854. 7, 5, 3, 1, 0, 2, 4, 6,
  125855. 8,
  125856. };
  125857. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  125858. _vq_quantthresh__44c5_s_p4_0,
  125859. _vq_quantmap__44c5_s_p4_0,
  125860. 9,
  125861. 9
  125862. };
  125863. static static_codebook _44c5_s_p4_0 = {
  125864. 2, 81,
  125865. _vq_lengthlist__44c5_s_p4_0,
  125866. 1, -531628032, 1611661312, 4, 0,
  125867. _vq_quantlist__44c5_s_p4_0,
  125868. NULL,
  125869. &_vq_auxt__44c5_s_p4_0,
  125870. NULL,
  125871. 0
  125872. };
  125873. static long _vq_quantlist__44c5_s_p5_0[] = {
  125874. 4,
  125875. 3,
  125876. 5,
  125877. 2,
  125878. 6,
  125879. 1,
  125880. 7,
  125881. 0,
  125882. 8,
  125883. };
  125884. static long _vq_lengthlist__44c5_s_p5_0[] = {
  125885. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  125886. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  125887. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  125888. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  125889. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125890. 10,
  125891. };
  125892. static float _vq_quantthresh__44c5_s_p5_0[] = {
  125893. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125894. };
  125895. static long _vq_quantmap__44c5_s_p5_0[] = {
  125896. 7, 5, 3, 1, 0, 2, 4, 6,
  125897. 8,
  125898. };
  125899. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  125900. _vq_quantthresh__44c5_s_p5_0,
  125901. _vq_quantmap__44c5_s_p5_0,
  125902. 9,
  125903. 9
  125904. };
  125905. static static_codebook _44c5_s_p5_0 = {
  125906. 2, 81,
  125907. _vq_lengthlist__44c5_s_p5_0,
  125908. 1, -531628032, 1611661312, 4, 0,
  125909. _vq_quantlist__44c5_s_p5_0,
  125910. NULL,
  125911. &_vq_auxt__44c5_s_p5_0,
  125912. NULL,
  125913. 0
  125914. };
  125915. static long _vq_quantlist__44c5_s_p6_0[] = {
  125916. 8,
  125917. 7,
  125918. 9,
  125919. 6,
  125920. 10,
  125921. 5,
  125922. 11,
  125923. 4,
  125924. 12,
  125925. 3,
  125926. 13,
  125927. 2,
  125928. 14,
  125929. 1,
  125930. 15,
  125931. 0,
  125932. 16,
  125933. };
  125934. static long _vq_lengthlist__44c5_s_p6_0[] = {
  125935. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  125936. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125937. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  125938. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  125939. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  125940. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  125941. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  125942. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  125943. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  125944. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  125945. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  125946. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  125947. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  125948. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  125949. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  125950. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  125951. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  125952. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  125953. 13,
  125954. };
  125955. static float _vq_quantthresh__44c5_s_p6_0[] = {
  125956. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125957. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125958. };
  125959. static long _vq_quantmap__44c5_s_p6_0[] = {
  125960. 15, 13, 11, 9, 7, 5, 3, 1,
  125961. 0, 2, 4, 6, 8, 10, 12, 14,
  125962. 16,
  125963. };
  125964. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  125965. _vq_quantthresh__44c5_s_p6_0,
  125966. _vq_quantmap__44c5_s_p6_0,
  125967. 17,
  125968. 17
  125969. };
  125970. static static_codebook _44c5_s_p6_0 = {
  125971. 2, 289,
  125972. _vq_lengthlist__44c5_s_p6_0,
  125973. 1, -529530880, 1611661312, 5, 0,
  125974. _vq_quantlist__44c5_s_p6_0,
  125975. NULL,
  125976. &_vq_auxt__44c5_s_p6_0,
  125977. NULL,
  125978. 0
  125979. };
  125980. static long _vq_quantlist__44c5_s_p7_0[] = {
  125981. 1,
  125982. 0,
  125983. 2,
  125984. };
  125985. static long _vq_lengthlist__44c5_s_p7_0[] = {
  125986. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  125987. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  125988. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  125989. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  125990. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  125991. 10,
  125992. };
  125993. static float _vq_quantthresh__44c5_s_p7_0[] = {
  125994. -5.5, 5.5,
  125995. };
  125996. static long _vq_quantmap__44c5_s_p7_0[] = {
  125997. 1, 0, 2,
  125998. };
  125999. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  126000. _vq_quantthresh__44c5_s_p7_0,
  126001. _vq_quantmap__44c5_s_p7_0,
  126002. 3,
  126003. 3
  126004. };
  126005. static static_codebook _44c5_s_p7_0 = {
  126006. 4, 81,
  126007. _vq_lengthlist__44c5_s_p7_0,
  126008. 1, -529137664, 1618345984, 2, 0,
  126009. _vq_quantlist__44c5_s_p7_0,
  126010. NULL,
  126011. &_vq_auxt__44c5_s_p7_0,
  126012. NULL,
  126013. 0
  126014. };
  126015. static long _vq_quantlist__44c5_s_p7_1[] = {
  126016. 5,
  126017. 4,
  126018. 6,
  126019. 3,
  126020. 7,
  126021. 2,
  126022. 8,
  126023. 1,
  126024. 9,
  126025. 0,
  126026. 10,
  126027. };
  126028. static long _vq_lengthlist__44c5_s_p7_1[] = {
  126029. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  126030. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  126031. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  126032. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  126033. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  126034. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  126035. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  126036. 10,10,10, 8, 8, 8, 8, 8, 8,
  126037. };
  126038. static float _vq_quantthresh__44c5_s_p7_1[] = {
  126039. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126040. 3.5, 4.5,
  126041. };
  126042. static long _vq_quantmap__44c5_s_p7_1[] = {
  126043. 9, 7, 5, 3, 1, 0, 2, 4,
  126044. 6, 8, 10,
  126045. };
  126046. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  126047. _vq_quantthresh__44c5_s_p7_1,
  126048. _vq_quantmap__44c5_s_p7_1,
  126049. 11,
  126050. 11
  126051. };
  126052. static static_codebook _44c5_s_p7_1 = {
  126053. 2, 121,
  126054. _vq_lengthlist__44c5_s_p7_1,
  126055. 1, -531365888, 1611661312, 4, 0,
  126056. _vq_quantlist__44c5_s_p7_1,
  126057. NULL,
  126058. &_vq_auxt__44c5_s_p7_1,
  126059. NULL,
  126060. 0
  126061. };
  126062. static long _vq_quantlist__44c5_s_p8_0[] = {
  126063. 6,
  126064. 5,
  126065. 7,
  126066. 4,
  126067. 8,
  126068. 3,
  126069. 9,
  126070. 2,
  126071. 10,
  126072. 1,
  126073. 11,
  126074. 0,
  126075. 12,
  126076. };
  126077. static long _vq_lengthlist__44c5_s_p8_0[] = {
  126078. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  126079. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  126080. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126081. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126082. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  126083. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  126084. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  126085. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  126086. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  126087. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  126088. 0,12,12,12,12,12,12,13,13,
  126089. };
  126090. static float _vq_quantthresh__44c5_s_p8_0[] = {
  126091. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126092. 12.5, 17.5, 22.5, 27.5,
  126093. };
  126094. static long _vq_quantmap__44c5_s_p8_0[] = {
  126095. 11, 9, 7, 5, 3, 1, 0, 2,
  126096. 4, 6, 8, 10, 12,
  126097. };
  126098. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  126099. _vq_quantthresh__44c5_s_p8_0,
  126100. _vq_quantmap__44c5_s_p8_0,
  126101. 13,
  126102. 13
  126103. };
  126104. static static_codebook _44c5_s_p8_0 = {
  126105. 2, 169,
  126106. _vq_lengthlist__44c5_s_p8_0,
  126107. 1, -526516224, 1616117760, 4, 0,
  126108. _vq_quantlist__44c5_s_p8_0,
  126109. NULL,
  126110. &_vq_auxt__44c5_s_p8_0,
  126111. NULL,
  126112. 0
  126113. };
  126114. static long _vq_quantlist__44c5_s_p8_1[] = {
  126115. 2,
  126116. 1,
  126117. 3,
  126118. 0,
  126119. 4,
  126120. };
  126121. static long _vq_lengthlist__44c5_s_p8_1[] = {
  126122. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  126123. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126124. };
  126125. static float _vq_quantthresh__44c5_s_p8_1[] = {
  126126. -1.5, -0.5, 0.5, 1.5,
  126127. };
  126128. static long _vq_quantmap__44c5_s_p8_1[] = {
  126129. 3, 1, 0, 2, 4,
  126130. };
  126131. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  126132. _vq_quantthresh__44c5_s_p8_1,
  126133. _vq_quantmap__44c5_s_p8_1,
  126134. 5,
  126135. 5
  126136. };
  126137. static static_codebook _44c5_s_p8_1 = {
  126138. 2, 25,
  126139. _vq_lengthlist__44c5_s_p8_1,
  126140. 1, -533725184, 1611661312, 3, 0,
  126141. _vq_quantlist__44c5_s_p8_1,
  126142. NULL,
  126143. &_vq_auxt__44c5_s_p8_1,
  126144. NULL,
  126145. 0
  126146. };
  126147. static long _vq_quantlist__44c5_s_p9_0[] = {
  126148. 7,
  126149. 6,
  126150. 8,
  126151. 5,
  126152. 9,
  126153. 4,
  126154. 10,
  126155. 3,
  126156. 11,
  126157. 2,
  126158. 12,
  126159. 1,
  126160. 13,
  126161. 0,
  126162. 14,
  126163. };
  126164. static long _vq_lengthlist__44c5_s_p9_0[] = {
  126165. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  126166. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  126167. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126168. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126169. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126170. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126171. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126172. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126173. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126174. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126175. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126176. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126177. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126178. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  126179. 12,
  126180. };
  126181. static float _vq_quantthresh__44c5_s_p9_0[] = {
  126182. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  126183. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  126184. };
  126185. static long _vq_quantmap__44c5_s_p9_0[] = {
  126186. 13, 11, 9, 7, 5, 3, 1, 0,
  126187. 2, 4, 6, 8, 10, 12, 14,
  126188. };
  126189. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  126190. _vq_quantthresh__44c5_s_p9_0,
  126191. _vq_quantmap__44c5_s_p9_0,
  126192. 15,
  126193. 15
  126194. };
  126195. static static_codebook _44c5_s_p9_0 = {
  126196. 2, 225,
  126197. _vq_lengthlist__44c5_s_p9_0,
  126198. 1, -512522752, 1628852224, 4, 0,
  126199. _vq_quantlist__44c5_s_p9_0,
  126200. NULL,
  126201. &_vq_auxt__44c5_s_p9_0,
  126202. NULL,
  126203. 0
  126204. };
  126205. static long _vq_quantlist__44c5_s_p9_1[] = {
  126206. 8,
  126207. 7,
  126208. 9,
  126209. 6,
  126210. 10,
  126211. 5,
  126212. 11,
  126213. 4,
  126214. 12,
  126215. 3,
  126216. 13,
  126217. 2,
  126218. 14,
  126219. 1,
  126220. 15,
  126221. 0,
  126222. 16,
  126223. };
  126224. static long _vq_lengthlist__44c5_s_p9_1[] = {
  126225. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  126226. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  126227. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  126228. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  126229. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  126230. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  126231. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  126232. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  126233. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  126234. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  126235. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  126236. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  126237. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  126238. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  126239. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  126240. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  126241. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  126242. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  126243. 15,
  126244. };
  126245. static float _vq_quantthresh__44c5_s_p9_1[] = {
  126246. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  126247. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  126248. };
  126249. static long _vq_quantmap__44c5_s_p9_1[] = {
  126250. 15, 13, 11, 9, 7, 5, 3, 1,
  126251. 0, 2, 4, 6, 8, 10, 12, 14,
  126252. 16,
  126253. };
  126254. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  126255. _vq_quantthresh__44c5_s_p9_1,
  126256. _vq_quantmap__44c5_s_p9_1,
  126257. 17,
  126258. 17
  126259. };
  126260. static static_codebook _44c5_s_p9_1 = {
  126261. 2, 289,
  126262. _vq_lengthlist__44c5_s_p9_1,
  126263. 1, -520814592, 1620377600, 5, 0,
  126264. _vq_quantlist__44c5_s_p9_1,
  126265. NULL,
  126266. &_vq_auxt__44c5_s_p9_1,
  126267. NULL,
  126268. 0
  126269. };
  126270. static long _vq_quantlist__44c5_s_p9_2[] = {
  126271. 10,
  126272. 9,
  126273. 11,
  126274. 8,
  126275. 12,
  126276. 7,
  126277. 13,
  126278. 6,
  126279. 14,
  126280. 5,
  126281. 15,
  126282. 4,
  126283. 16,
  126284. 3,
  126285. 17,
  126286. 2,
  126287. 18,
  126288. 1,
  126289. 19,
  126290. 0,
  126291. 20,
  126292. };
  126293. static long _vq_lengthlist__44c5_s_p9_2[] = {
  126294. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  126295. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  126296. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  126297. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  126298. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  126299. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  126300. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  126301. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  126302. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  126303. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126304. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  126305. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  126306. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  126307. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  126308. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  126309. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  126310. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  126311. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  126312. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  126313. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  126314. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126315. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  126316. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  126317. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  126318. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  126319. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  126320. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  126321. 10,10,10,10,10,10,10,10,10,
  126322. };
  126323. static float _vq_quantthresh__44c5_s_p9_2[] = {
  126324. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126325. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126326. 6.5, 7.5, 8.5, 9.5,
  126327. };
  126328. static long _vq_quantmap__44c5_s_p9_2[] = {
  126329. 19, 17, 15, 13, 11, 9, 7, 5,
  126330. 3, 1, 0, 2, 4, 6, 8, 10,
  126331. 12, 14, 16, 18, 20,
  126332. };
  126333. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  126334. _vq_quantthresh__44c5_s_p9_2,
  126335. _vq_quantmap__44c5_s_p9_2,
  126336. 21,
  126337. 21
  126338. };
  126339. static static_codebook _44c5_s_p9_2 = {
  126340. 2, 441,
  126341. _vq_lengthlist__44c5_s_p9_2,
  126342. 1, -529268736, 1611661312, 5, 0,
  126343. _vq_quantlist__44c5_s_p9_2,
  126344. NULL,
  126345. &_vq_auxt__44c5_s_p9_2,
  126346. NULL,
  126347. 0
  126348. };
  126349. static long _huff_lengthlist__44c5_s_short[] = {
  126350. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  126351. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  126352. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  126353. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  126354. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  126355. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  126356. 6, 8,11,16,
  126357. };
  126358. static static_codebook _huff_book__44c5_s_short = {
  126359. 2, 100,
  126360. _huff_lengthlist__44c5_s_short,
  126361. 0, 0, 0, 0, 0,
  126362. NULL,
  126363. NULL,
  126364. NULL,
  126365. NULL,
  126366. 0
  126367. };
  126368. static long _huff_lengthlist__44c6_s_long[] = {
  126369. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  126370. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  126371. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  126372. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  126373. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  126374. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  126375. 11,10,10,12,
  126376. };
  126377. static static_codebook _huff_book__44c6_s_long = {
  126378. 2, 100,
  126379. _huff_lengthlist__44c6_s_long,
  126380. 0, 0, 0, 0, 0,
  126381. NULL,
  126382. NULL,
  126383. NULL,
  126384. NULL,
  126385. 0
  126386. };
  126387. static long _vq_quantlist__44c6_s_p1_0[] = {
  126388. 1,
  126389. 0,
  126390. 2,
  126391. };
  126392. static long _vq_lengthlist__44c6_s_p1_0[] = {
  126393. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  126394. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  126395. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  126396. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  126397. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  126398. 8,
  126399. };
  126400. static float _vq_quantthresh__44c6_s_p1_0[] = {
  126401. -0.5, 0.5,
  126402. };
  126403. static long _vq_quantmap__44c6_s_p1_0[] = {
  126404. 1, 0, 2,
  126405. };
  126406. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  126407. _vq_quantthresh__44c6_s_p1_0,
  126408. _vq_quantmap__44c6_s_p1_0,
  126409. 3,
  126410. 3
  126411. };
  126412. static static_codebook _44c6_s_p1_0 = {
  126413. 4, 81,
  126414. _vq_lengthlist__44c6_s_p1_0,
  126415. 1, -535822336, 1611661312, 2, 0,
  126416. _vq_quantlist__44c6_s_p1_0,
  126417. NULL,
  126418. &_vq_auxt__44c6_s_p1_0,
  126419. NULL,
  126420. 0
  126421. };
  126422. static long _vq_quantlist__44c6_s_p2_0[] = {
  126423. 2,
  126424. 1,
  126425. 3,
  126426. 0,
  126427. 4,
  126428. };
  126429. static long _vq_lengthlist__44c6_s_p2_0[] = {
  126430. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  126431. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  126432. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  126433. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  126434. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  126435. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  126436. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  126437. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  126438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126439. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  126440. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  126441. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  126442. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  126443. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  126444. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  126445. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  126446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126447. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  126448. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  126449. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  126450. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  126451. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  126452. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  126453. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126455. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  126456. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  126457. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  126458. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  126459. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  126460. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  126461. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  126466. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  126467. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  126468. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  126469. 13,
  126470. };
  126471. static float _vq_quantthresh__44c6_s_p2_0[] = {
  126472. -1.5, -0.5, 0.5, 1.5,
  126473. };
  126474. static long _vq_quantmap__44c6_s_p2_0[] = {
  126475. 3, 1, 0, 2, 4,
  126476. };
  126477. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  126478. _vq_quantthresh__44c6_s_p2_0,
  126479. _vq_quantmap__44c6_s_p2_0,
  126480. 5,
  126481. 5
  126482. };
  126483. static static_codebook _44c6_s_p2_0 = {
  126484. 4, 625,
  126485. _vq_lengthlist__44c6_s_p2_0,
  126486. 1, -533725184, 1611661312, 3, 0,
  126487. _vq_quantlist__44c6_s_p2_0,
  126488. NULL,
  126489. &_vq_auxt__44c6_s_p2_0,
  126490. NULL,
  126491. 0
  126492. };
  126493. static long _vq_quantlist__44c6_s_p3_0[] = {
  126494. 4,
  126495. 3,
  126496. 5,
  126497. 2,
  126498. 6,
  126499. 1,
  126500. 7,
  126501. 0,
  126502. 8,
  126503. };
  126504. static long _vq_lengthlist__44c6_s_p3_0[] = {
  126505. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  126506. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  126507. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  126508. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  126509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126510. 0,
  126511. };
  126512. static float _vq_quantthresh__44c6_s_p3_0[] = {
  126513. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126514. };
  126515. static long _vq_quantmap__44c6_s_p3_0[] = {
  126516. 7, 5, 3, 1, 0, 2, 4, 6,
  126517. 8,
  126518. };
  126519. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  126520. _vq_quantthresh__44c6_s_p3_0,
  126521. _vq_quantmap__44c6_s_p3_0,
  126522. 9,
  126523. 9
  126524. };
  126525. static static_codebook _44c6_s_p3_0 = {
  126526. 2, 81,
  126527. _vq_lengthlist__44c6_s_p3_0,
  126528. 1, -531628032, 1611661312, 4, 0,
  126529. _vq_quantlist__44c6_s_p3_0,
  126530. NULL,
  126531. &_vq_auxt__44c6_s_p3_0,
  126532. NULL,
  126533. 0
  126534. };
  126535. static long _vq_quantlist__44c6_s_p4_0[] = {
  126536. 8,
  126537. 7,
  126538. 9,
  126539. 6,
  126540. 10,
  126541. 5,
  126542. 11,
  126543. 4,
  126544. 12,
  126545. 3,
  126546. 13,
  126547. 2,
  126548. 14,
  126549. 1,
  126550. 15,
  126551. 0,
  126552. 16,
  126553. };
  126554. static long _vq_lengthlist__44c6_s_p4_0[] = {
  126555. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  126556. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  126557. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  126558. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  126559. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  126560. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  126561. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  126562. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  126563. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  126564. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  126565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126573. 0,
  126574. };
  126575. static float _vq_quantthresh__44c6_s_p4_0[] = {
  126576. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126577. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126578. };
  126579. static long _vq_quantmap__44c6_s_p4_0[] = {
  126580. 15, 13, 11, 9, 7, 5, 3, 1,
  126581. 0, 2, 4, 6, 8, 10, 12, 14,
  126582. 16,
  126583. };
  126584. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  126585. _vq_quantthresh__44c6_s_p4_0,
  126586. _vq_quantmap__44c6_s_p4_0,
  126587. 17,
  126588. 17
  126589. };
  126590. static static_codebook _44c6_s_p4_0 = {
  126591. 2, 289,
  126592. _vq_lengthlist__44c6_s_p4_0,
  126593. 1, -529530880, 1611661312, 5, 0,
  126594. _vq_quantlist__44c6_s_p4_0,
  126595. NULL,
  126596. &_vq_auxt__44c6_s_p4_0,
  126597. NULL,
  126598. 0
  126599. };
  126600. static long _vq_quantlist__44c6_s_p5_0[] = {
  126601. 1,
  126602. 0,
  126603. 2,
  126604. };
  126605. static long _vq_lengthlist__44c6_s_p5_0[] = {
  126606. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  126607. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  126608. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  126609. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  126610. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  126611. 12,
  126612. };
  126613. static float _vq_quantthresh__44c6_s_p5_0[] = {
  126614. -5.5, 5.5,
  126615. };
  126616. static long _vq_quantmap__44c6_s_p5_0[] = {
  126617. 1, 0, 2,
  126618. };
  126619. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  126620. _vq_quantthresh__44c6_s_p5_0,
  126621. _vq_quantmap__44c6_s_p5_0,
  126622. 3,
  126623. 3
  126624. };
  126625. static static_codebook _44c6_s_p5_0 = {
  126626. 4, 81,
  126627. _vq_lengthlist__44c6_s_p5_0,
  126628. 1, -529137664, 1618345984, 2, 0,
  126629. _vq_quantlist__44c6_s_p5_0,
  126630. NULL,
  126631. &_vq_auxt__44c6_s_p5_0,
  126632. NULL,
  126633. 0
  126634. };
  126635. static long _vq_quantlist__44c6_s_p5_1[] = {
  126636. 5,
  126637. 4,
  126638. 6,
  126639. 3,
  126640. 7,
  126641. 2,
  126642. 8,
  126643. 1,
  126644. 9,
  126645. 0,
  126646. 10,
  126647. };
  126648. static long _vq_lengthlist__44c6_s_p5_1[] = {
  126649. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  126650. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  126651. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  126652. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  126653. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  126654. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  126655. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  126656. 11,10,10, 7, 7, 8, 8, 8, 8,
  126657. };
  126658. static float _vq_quantthresh__44c6_s_p5_1[] = {
  126659. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126660. 3.5, 4.5,
  126661. };
  126662. static long _vq_quantmap__44c6_s_p5_1[] = {
  126663. 9, 7, 5, 3, 1, 0, 2, 4,
  126664. 6, 8, 10,
  126665. };
  126666. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  126667. _vq_quantthresh__44c6_s_p5_1,
  126668. _vq_quantmap__44c6_s_p5_1,
  126669. 11,
  126670. 11
  126671. };
  126672. static static_codebook _44c6_s_p5_1 = {
  126673. 2, 121,
  126674. _vq_lengthlist__44c6_s_p5_1,
  126675. 1, -531365888, 1611661312, 4, 0,
  126676. _vq_quantlist__44c6_s_p5_1,
  126677. NULL,
  126678. &_vq_auxt__44c6_s_p5_1,
  126679. NULL,
  126680. 0
  126681. };
  126682. static long _vq_quantlist__44c6_s_p6_0[] = {
  126683. 6,
  126684. 5,
  126685. 7,
  126686. 4,
  126687. 8,
  126688. 3,
  126689. 9,
  126690. 2,
  126691. 10,
  126692. 1,
  126693. 11,
  126694. 0,
  126695. 12,
  126696. };
  126697. static long _vq_lengthlist__44c6_s_p6_0[] = {
  126698. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  126699. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  126700. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  126701. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  126702. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  126703. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  126704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126708. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126709. };
  126710. static float _vq_quantthresh__44c6_s_p6_0[] = {
  126711. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126712. 12.5, 17.5, 22.5, 27.5,
  126713. };
  126714. static long _vq_quantmap__44c6_s_p6_0[] = {
  126715. 11, 9, 7, 5, 3, 1, 0, 2,
  126716. 4, 6, 8, 10, 12,
  126717. };
  126718. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  126719. _vq_quantthresh__44c6_s_p6_0,
  126720. _vq_quantmap__44c6_s_p6_0,
  126721. 13,
  126722. 13
  126723. };
  126724. static static_codebook _44c6_s_p6_0 = {
  126725. 2, 169,
  126726. _vq_lengthlist__44c6_s_p6_0,
  126727. 1, -526516224, 1616117760, 4, 0,
  126728. _vq_quantlist__44c6_s_p6_0,
  126729. NULL,
  126730. &_vq_auxt__44c6_s_p6_0,
  126731. NULL,
  126732. 0
  126733. };
  126734. static long _vq_quantlist__44c6_s_p6_1[] = {
  126735. 2,
  126736. 1,
  126737. 3,
  126738. 0,
  126739. 4,
  126740. };
  126741. static long _vq_lengthlist__44c6_s_p6_1[] = {
  126742. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  126743. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126744. };
  126745. static float _vq_quantthresh__44c6_s_p6_1[] = {
  126746. -1.5, -0.5, 0.5, 1.5,
  126747. };
  126748. static long _vq_quantmap__44c6_s_p6_1[] = {
  126749. 3, 1, 0, 2, 4,
  126750. };
  126751. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  126752. _vq_quantthresh__44c6_s_p6_1,
  126753. _vq_quantmap__44c6_s_p6_1,
  126754. 5,
  126755. 5
  126756. };
  126757. static static_codebook _44c6_s_p6_1 = {
  126758. 2, 25,
  126759. _vq_lengthlist__44c6_s_p6_1,
  126760. 1, -533725184, 1611661312, 3, 0,
  126761. _vq_quantlist__44c6_s_p6_1,
  126762. NULL,
  126763. &_vq_auxt__44c6_s_p6_1,
  126764. NULL,
  126765. 0
  126766. };
  126767. static long _vq_quantlist__44c6_s_p7_0[] = {
  126768. 6,
  126769. 5,
  126770. 7,
  126771. 4,
  126772. 8,
  126773. 3,
  126774. 9,
  126775. 2,
  126776. 10,
  126777. 1,
  126778. 11,
  126779. 0,
  126780. 12,
  126781. };
  126782. static long _vq_lengthlist__44c6_s_p7_0[] = {
  126783. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  126784. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  126785. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  126786. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  126787. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  126788. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  126789. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  126790. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  126791. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  126792. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  126793. 20,13,13,13,13,13,13,14,14,
  126794. };
  126795. static float _vq_quantthresh__44c6_s_p7_0[] = {
  126796. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  126797. 27.5, 38.5, 49.5, 60.5,
  126798. };
  126799. static long _vq_quantmap__44c6_s_p7_0[] = {
  126800. 11, 9, 7, 5, 3, 1, 0, 2,
  126801. 4, 6, 8, 10, 12,
  126802. };
  126803. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  126804. _vq_quantthresh__44c6_s_p7_0,
  126805. _vq_quantmap__44c6_s_p7_0,
  126806. 13,
  126807. 13
  126808. };
  126809. static static_codebook _44c6_s_p7_0 = {
  126810. 2, 169,
  126811. _vq_lengthlist__44c6_s_p7_0,
  126812. 1, -523206656, 1618345984, 4, 0,
  126813. _vq_quantlist__44c6_s_p7_0,
  126814. NULL,
  126815. &_vq_auxt__44c6_s_p7_0,
  126816. NULL,
  126817. 0
  126818. };
  126819. static long _vq_quantlist__44c6_s_p7_1[] = {
  126820. 5,
  126821. 4,
  126822. 6,
  126823. 3,
  126824. 7,
  126825. 2,
  126826. 8,
  126827. 1,
  126828. 9,
  126829. 0,
  126830. 10,
  126831. };
  126832. static long _vq_lengthlist__44c6_s_p7_1[] = {
  126833. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  126834. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  126835. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  126836. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  126837. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  126838. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  126839. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  126840. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  126841. };
  126842. static float _vq_quantthresh__44c6_s_p7_1[] = {
  126843. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126844. 3.5, 4.5,
  126845. };
  126846. static long _vq_quantmap__44c6_s_p7_1[] = {
  126847. 9, 7, 5, 3, 1, 0, 2, 4,
  126848. 6, 8, 10,
  126849. };
  126850. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  126851. _vq_quantthresh__44c6_s_p7_1,
  126852. _vq_quantmap__44c6_s_p7_1,
  126853. 11,
  126854. 11
  126855. };
  126856. static static_codebook _44c6_s_p7_1 = {
  126857. 2, 121,
  126858. _vq_lengthlist__44c6_s_p7_1,
  126859. 1, -531365888, 1611661312, 4, 0,
  126860. _vq_quantlist__44c6_s_p7_1,
  126861. NULL,
  126862. &_vq_auxt__44c6_s_p7_1,
  126863. NULL,
  126864. 0
  126865. };
  126866. static long _vq_quantlist__44c6_s_p8_0[] = {
  126867. 7,
  126868. 6,
  126869. 8,
  126870. 5,
  126871. 9,
  126872. 4,
  126873. 10,
  126874. 3,
  126875. 11,
  126876. 2,
  126877. 12,
  126878. 1,
  126879. 13,
  126880. 0,
  126881. 14,
  126882. };
  126883. static long _vq_lengthlist__44c6_s_p8_0[] = {
  126884. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  126885. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  126886. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  126887. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  126888. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  126889. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  126890. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  126891. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  126892. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  126893. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  126894. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  126895. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  126896. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  126897. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  126898. 14,
  126899. };
  126900. static float _vq_quantthresh__44c6_s_p8_0[] = {
  126901. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126902. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126903. };
  126904. static long _vq_quantmap__44c6_s_p8_0[] = {
  126905. 13, 11, 9, 7, 5, 3, 1, 0,
  126906. 2, 4, 6, 8, 10, 12, 14,
  126907. };
  126908. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  126909. _vq_quantthresh__44c6_s_p8_0,
  126910. _vq_quantmap__44c6_s_p8_0,
  126911. 15,
  126912. 15
  126913. };
  126914. static static_codebook _44c6_s_p8_0 = {
  126915. 2, 225,
  126916. _vq_lengthlist__44c6_s_p8_0,
  126917. 1, -520986624, 1620377600, 4, 0,
  126918. _vq_quantlist__44c6_s_p8_0,
  126919. NULL,
  126920. &_vq_auxt__44c6_s_p8_0,
  126921. NULL,
  126922. 0
  126923. };
  126924. static long _vq_quantlist__44c6_s_p8_1[] = {
  126925. 10,
  126926. 9,
  126927. 11,
  126928. 8,
  126929. 12,
  126930. 7,
  126931. 13,
  126932. 6,
  126933. 14,
  126934. 5,
  126935. 15,
  126936. 4,
  126937. 16,
  126938. 3,
  126939. 17,
  126940. 2,
  126941. 18,
  126942. 1,
  126943. 19,
  126944. 0,
  126945. 20,
  126946. };
  126947. static long _vq_lengthlist__44c6_s_p8_1[] = {
  126948. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  126949. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  126950. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  126951. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  126952. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126953. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  126954. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  126955. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  126956. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126957. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126958. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  126959. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  126960. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  126961. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  126962. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  126963. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  126964. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  126965. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  126966. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  126967. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  126968. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  126969. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  126970. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  126971. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  126972. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  126973. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  126974. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  126975. 10,10,10,10,10,10,10,10,10,
  126976. };
  126977. static float _vq_quantthresh__44c6_s_p8_1[] = {
  126978. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126979. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126980. 6.5, 7.5, 8.5, 9.5,
  126981. };
  126982. static long _vq_quantmap__44c6_s_p8_1[] = {
  126983. 19, 17, 15, 13, 11, 9, 7, 5,
  126984. 3, 1, 0, 2, 4, 6, 8, 10,
  126985. 12, 14, 16, 18, 20,
  126986. };
  126987. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  126988. _vq_quantthresh__44c6_s_p8_1,
  126989. _vq_quantmap__44c6_s_p8_1,
  126990. 21,
  126991. 21
  126992. };
  126993. static static_codebook _44c6_s_p8_1 = {
  126994. 2, 441,
  126995. _vq_lengthlist__44c6_s_p8_1,
  126996. 1, -529268736, 1611661312, 5, 0,
  126997. _vq_quantlist__44c6_s_p8_1,
  126998. NULL,
  126999. &_vq_auxt__44c6_s_p8_1,
  127000. NULL,
  127001. 0
  127002. };
  127003. static long _vq_quantlist__44c6_s_p9_0[] = {
  127004. 6,
  127005. 5,
  127006. 7,
  127007. 4,
  127008. 8,
  127009. 3,
  127010. 9,
  127011. 2,
  127012. 10,
  127013. 1,
  127014. 11,
  127015. 0,
  127016. 12,
  127017. };
  127018. static long _vq_lengthlist__44c6_s_p9_0[] = {
  127019. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  127020. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  127021. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127022. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  127023. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127024. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127025. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127026. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127027. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127028. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127029. 10,10,10,10,10,10,10,10,10,
  127030. };
  127031. static float _vq_quantthresh__44c6_s_p9_0[] = {
  127032. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  127033. 1592.5, 2229.5, 2866.5, 3503.5,
  127034. };
  127035. static long _vq_quantmap__44c6_s_p9_0[] = {
  127036. 11, 9, 7, 5, 3, 1, 0, 2,
  127037. 4, 6, 8, 10, 12,
  127038. };
  127039. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  127040. _vq_quantthresh__44c6_s_p9_0,
  127041. _vq_quantmap__44c6_s_p9_0,
  127042. 13,
  127043. 13
  127044. };
  127045. static static_codebook _44c6_s_p9_0 = {
  127046. 2, 169,
  127047. _vq_lengthlist__44c6_s_p9_0,
  127048. 1, -511845376, 1630791680, 4, 0,
  127049. _vq_quantlist__44c6_s_p9_0,
  127050. NULL,
  127051. &_vq_auxt__44c6_s_p9_0,
  127052. NULL,
  127053. 0
  127054. };
  127055. static long _vq_quantlist__44c6_s_p9_1[] = {
  127056. 6,
  127057. 5,
  127058. 7,
  127059. 4,
  127060. 8,
  127061. 3,
  127062. 9,
  127063. 2,
  127064. 10,
  127065. 1,
  127066. 11,
  127067. 0,
  127068. 12,
  127069. };
  127070. static long _vq_lengthlist__44c6_s_p9_1[] = {
  127071. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  127072. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  127073. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  127074. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  127075. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  127076. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  127077. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  127078. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  127079. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  127080. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  127081. 15,12,10,11,11,13,11,12,13,
  127082. };
  127083. static float _vq_quantthresh__44c6_s_p9_1[] = {
  127084. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  127085. 122.5, 171.5, 220.5, 269.5,
  127086. };
  127087. static long _vq_quantmap__44c6_s_p9_1[] = {
  127088. 11, 9, 7, 5, 3, 1, 0, 2,
  127089. 4, 6, 8, 10, 12,
  127090. };
  127091. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  127092. _vq_quantthresh__44c6_s_p9_1,
  127093. _vq_quantmap__44c6_s_p9_1,
  127094. 13,
  127095. 13
  127096. };
  127097. static static_codebook _44c6_s_p9_1 = {
  127098. 2, 169,
  127099. _vq_lengthlist__44c6_s_p9_1,
  127100. 1, -518889472, 1622704128, 4, 0,
  127101. _vq_quantlist__44c6_s_p9_1,
  127102. NULL,
  127103. &_vq_auxt__44c6_s_p9_1,
  127104. NULL,
  127105. 0
  127106. };
  127107. static long _vq_quantlist__44c6_s_p9_2[] = {
  127108. 24,
  127109. 23,
  127110. 25,
  127111. 22,
  127112. 26,
  127113. 21,
  127114. 27,
  127115. 20,
  127116. 28,
  127117. 19,
  127118. 29,
  127119. 18,
  127120. 30,
  127121. 17,
  127122. 31,
  127123. 16,
  127124. 32,
  127125. 15,
  127126. 33,
  127127. 14,
  127128. 34,
  127129. 13,
  127130. 35,
  127131. 12,
  127132. 36,
  127133. 11,
  127134. 37,
  127135. 10,
  127136. 38,
  127137. 9,
  127138. 39,
  127139. 8,
  127140. 40,
  127141. 7,
  127142. 41,
  127143. 6,
  127144. 42,
  127145. 5,
  127146. 43,
  127147. 4,
  127148. 44,
  127149. 3,
  127150. 45,
  127151. 2,
  127152. 46,
  127153. 1,
  127154. 47,
  127155. 0,
  127156. 48,
  127157. };
  127158. static long _vq_lengthlist__44c6_s_p9_2[] = {
  127159. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  127160. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  127161. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  127162. 7,
  127163. };
  127164. static float _vq_quantthresh__44c6_s_p9_2[] = {
  127165. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  127166. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  127167. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127168. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127169. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  127170. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  127171. };
  127172. static long _vq_quantmap__44c6_s_p9_2[] = {
  127173. 47, 45, 43, 41, 39, 37, 35, 33,
  127174. 31, 29, 27, 25, 23, 21, 19, 17,
  127175. 15, 13, 11, 9, 7, 5, 3, 1,
  127176. 0, 2, 4, 6, 8, 10, 12, 14,
  127177. 16, 18, 20, 22, 24, 26, 28, 30,
  127178. 32, 34, 36, 38, 40, 42, 44, 46,
  127179. 48,
  127180. };
  127181. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  127182. _vq_quantthresh__44c6_s_p9_2,
  127183. _vq_quantmap__44c6_s_p9_2,
  127184. 49,
  127185. 49
  127186. };
  127187. static static_codebook _44c6_s_p9_2 = {
  127188. 1, 49,
  127189. _vq_lengthlist__44c6_s_p9_2,
  127190. 1, -526909440, 1611661312, 6, 0,
  127191. _vq_quantlist__44c6_s_p9_2,
  127192. NULL,
  127193. &_vq_auxt__44c6_s_p9_2,
  127194. NULL,
  127195. 0
  127196. };
  127197. static long _huff_lengthlist__44c6_s_short[] = {
  127198. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  127199. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  127200. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  127201. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  127202. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  127203. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  127204. 9,10,17,18,
  127205. };
  127206. static static_codebook _huff_book__44c6_s_short = {
  127207. 2, 100,
  127208. _huff_lengthlist__44c6_s_short,
  127209. 0, 0, 0, 0, 0,
  127210. NULL,
  127211. NULL,
  127212. NULL,
  127213. NULL,
  127214. 0
  127215. };
  127216. static long _huff_lengthlist__44c7_s_long[] = {
  127217. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  127218. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  127219. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  127220. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  127221. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  127222. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  127223. 11,10,10,12,
  127224. };
  127225. static static_codebook _huff_book__44c7_s_long = {
  127226. 2, 100,
  127227. _huff_lengthlist__44c7_s_long,
  127228. 0, 0, 0, 0, 0,
  127229. NULL,
  127230. NULL,
  127231. NULL,
  127232. NULL,
  127233. 0
  127234. };
  127235. static long _vq_quantlist__44c7_s_p1_0[] = {
  127236. 1,
  127237. 0,
  127238. 2,
  127239. };
  127240. static long _vq_lengthlist__44c7_s_p1_0[] = {
  127241. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  127242. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  127243. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  127244. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  127245. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  127246. 8,
  127247. };
  127248. static float _vq_quantthresh__44c7_s_p1_0[] = {
  127249. -0.5, 0.5,
  127250. };
  127251. static long _vq_quantmap__44c7_s_p1_0[] = {
  127252. 1, 0, 2,
  127253. };
  127254. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  127255. _vq_quantthresh__44c7_s_p1_0,
  127256. _vq_quantmap__44c7_s_p1_0,
  127257. 3,
  127258. 3
  127259. };
  127260. static static_codebook _44c7_s_p1_0 = {
  127261. 4, 81,
  127262. _vq_lengthlist__44c7_s_p1_0,
  127263. 1, -535822336, 1611661312, 2, 0,
  127264. _vq_quantlist__44c7_s_p1_0,
  127265. NULL,
  127266. &_vq_auxt__44c7_s_p1_0,
  127267. NULL,
  127268. 0
  127269. };
  127270. static long _vq_quantlist__44c7_s_p2_0[] = {
  127271. 2,
  127272. 1,
  127273. 3,
  127274. 0,
  127275. 4,
  127276. };
  127277. static long _vq_lengthlist__44c7_s_p2_0[] = {
  127278. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  127279. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  127280. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  127281. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  127282. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  127283. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  127284. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  127285. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  127286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127287. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  127288. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  127289. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  127290. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  127291. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  127292. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  127293. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  127294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127295. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  127296. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  127297. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  127298. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  127299. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  127300. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  127301. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127303. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  127304. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  127305. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  127306. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  127307. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  127308. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  127309. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  127314. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  127315. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  127316. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  127317. 13,
  127318. };
  127319. static float _vq_quantthresh__44c7_s_p2_0[] = {
  127320. -1.5, -0.5, 0.5, 1.5,
  127321. };
  127322. static long _vq_quantmap__44c7_s_p2_0[] = {
  127323. 3, 1, 0, 2, 4,
  127324. };
  127325. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  127326. _vq_quantthresh__44c7_s_p2_0,
  127327. _vq_quantmap__44c7_s_p2_0,
  127328. 5,
  127329. 5
  127330. };
  127331. static static_codebook _44c7_s_p2_0 = {
  127332. 4, 625,
  127333. _vq_lengthlist__44c7_s_p2_0,
  127334. 1, -533725184, 1611661312, 3, 0,
  127335. _vq_quantlist__44c7_s_p2_0,
  127336. NULL,
  127337. &_vq_auxt__44c7_s_p2_0,
  127338. NULL,
  127339. 0
  127340. };
  127341. static long _vq_quantlist__44c7_s_p3_0[] = {
  127342. 4,
  127343. 3,
  127344. 5,
  127345. 2,
  127346. 6,
  127347. 1,
  127348. 7,
  127349. 0,
  127350. 8,
  127351. };
  127352. static long _vq_lengthlist__44c7_s_p3_0[] = {
  127353. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  127354. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  127355. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  127356. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  127357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127358. 0,
  127359. };
  127360. static float _vq_quantthresh__44c7_s_p3_0[] = {
  127361. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127362. };
  127363. static long _vq_quantmap__44c7_s_p3_0[] = {
  127364. 7, 5, 3, 1, 0, 2, 4, 6,
  127365. 8,
  127366. };
  127367. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  127368. _vq_quantthresh__44c7_s_p3_0,
  127369. _vq_quantmap__44c7_s_p3_0,
  127370. 9,
  127371. 9
  127372. };
  127373. static static_codebook _44c7_s_p3_0 = {
  127374. 2, 81,
  127375. _vq_lengthlist__44c7_s_p3_0,
  127376. 1, -531628032, 1611661312, 4, 0,
  127377. _vq_quantlist__44c7_s_p3_0,
  127378. NULL,
  127379. &_vq_auxt__44c7_s_p3_0,
  127380. NULL,
  127381. 0
  127382. };
  127383. static long _vq_quantlist__44c7_s_p4_0[] = {
  127384. 8,
  127385. 7,
  127386. 9,
  127387. 6,
  127388. 10,
  127389. 5,
  127390. 11,
  127391. 4,
  127392. 12,
  127393. 3,
  127394. 13,
  127395. 2,
  127396. 14,
  127397. 1,
  127398. 15,
  127399. 0,
  127400. 16,
  127401. };
  127402. static long _vq_lengthlist__44c7_s_p4_0[] = {
  127403. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  127404. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  127405. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  127406. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  127407. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  127408. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  127409. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  127410. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  127411. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  127412. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  127413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127421. 0,
  127422. };
  127423. static float _vq_quantthresh__44c7_s_p4_0[] = {
  127424. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127425. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127426. };
  127427. static long _vq_quantmap__44c7_s_p4_0[] = {
  127428. 15, 13, 11, 9, 7, 5, 3, 1,
  127429. 0, 2, 4, 6, 8, 10, 12, 14,
  127430. 16,
  127431. };
  127432. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  127433. _vq_quantthresh__44c7_s_p4_0,
  127434. _vq_quantmap__44c7_s_p4_0,
  127435. 17,
  127436. 17
  127437. };
  127438. static static_codebook _44c7_s_p4_0 = {
  127439. 2, 289,
  127440. _vq_lengthlist__44c7_s_p4_0,
  127441. 1, -529530880, 1611661312, 5, 0,
  127442. _vq_quantlist__44c7_s_p4_0,
  127443. NULL,
  127444. &_vq_auxt__44c7_s_p4_0,
  127445. NULL,
  127446. 0
  127447. };
  127448. static long _vq_quantlist__44c7_s_p5_0[] = {
  127449. 1,
  127450. 0,
  127451. 2,
  127452. };
  127453. static long _vq_lengthlist__44c7_s_p5_0[] = {
  127454. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  127455. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  127456. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  127457. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  127458. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  127459. 12,
  127460. };
  127461. static float _vq_quantthresh__44c7_s_p5_0[] = {
  127462. -5.5, 5.5,
  127463. };
  127464. static long _vq_quantmap__44c7_s_p5_0[] = {
  127465. 1, 0, 2,
  127466. };
  127467. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  127468. _vq_quantthresh__44c7_s_p5_0,
  127469. _vq_quantmap__44c7_s_p5_0,
  127470. 3,
  127471. 3
  127472. };
  127473. static static_codebook _44c7_s_p5_0 = {
  127474. 4, 81,
  127475. _vq_lengthlist__44c7_s_p5_0,
  127476. 1, -529137664, 1618345984, 2, 0,
  127477. _vq_quantlist__44c7_s_p5_0,
  127478. NULL,
  127479. &_vq_auxt__44c7_s_p5_0,
  127480. NULL,
  127481. 0
  127482. };
  127483. static long _vq_quantlist__44c7_s_p5_1[] = {
  127484. 5,
  127485. 4,
  127486. 6,
  127487. 3,
  127488. 7,
  127489. 2,
  127490. 8,
  127491. 1,
  127492. 9,
  127493. 0,
  127494. 10,
  127495. };
  127496. static long _vq_lengthlist__44c7_s_p5_1[] = {
  127497. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  127498. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  127499. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  127500. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  127501. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  127502. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  127503. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  127504. 11,11,11, 7, 7, 8, 8, 8, 8,
  127505. };
  127506. static float _vq_quantthresh__44c7_s_p5_1[] = {
  127507. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127508. 3.5, 4.5,
  127509. };
  127510. static long _vq_quantmap__44c7_s_p5_1[] = {
  127511. 9, 7, 5, 3, 1, 0, 2, 4,
  127512. 6, 8, 10,
  127513. };
  127514. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  127515. _vq_quantthresh__44c7_s_p5_1,
  127516. _vq_quantmap__44c7_s_p5_1,
  127517. 11,
  127518. 11
  127519. };
  127520. static static_codebook _44c7_s_p5_1 = {
  127521. 2, 121,
  127522. _vq_lengthlist__44c7_s_p5_1,
  127523. 1, -531365888, 1611661312, 4, 0,
  127524. _vq_quantlist__44c7_s_p5_1,
  127525. NULL,
  127526. &_vq_auxt__44c7_s_p5_1,
  127527. NULL,
  127528. 0
  127529. };
  127530. static long _vq_quantlist__44c7_s_p6_0[] = {
  127531. 6,
  127532. 5,
  127533. 7,
  127534. 4,
  127535. 8,
  127536. 3,
  127537. 9,
  127538. 2,
  127539. 10,
  127540. 1,
  127541. 11,
  127542. 0,
  127543. 12,
  127544. };
  127545. static long _vq_lengthlist__44c7_s_p6_0[] = {
  127546. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  127547. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127548. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  127549. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  127550. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  127551. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  127552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127556. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127557. };
  127558. static float _vq_quantthresh__44c7_s_p6_0[] = {
  127559. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127560. 12.5, 17.5, 22.5, 27.5,
  127561. };
  127562. static long _vq_quantmap__44c7_s_p6_0[] = {
  127563. 11, 9, 7, 5, 3, 1, 0, 2,
  127564. 4, 6, 8, 10, 12,
  127565. };
  127566. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  127567. _vq_quantthresh__44c7_s_p6_0,
  127568. _vq_quantmap__44c7_s_p6_0,
  127569. 13,
  127570. 13
  127571. };
  127572. static static_codebook _44c7_s_p6_0 = {
  127573. 2, 169,
  127574. _vq_lengthlist__44c7_s_p6_0,
  127575. 1, -526516224, 1616117760, 4, 0,
  127576. _vq_quantlist__44c7_s_p6_0,
  127577. NULL,
  127578. &_vq_auxt__44c7_s_p6_0,
  127579. NULL,
  127580. 0
  127581. };
  127582. static long _vq_quantlist__44c7_s_p6_1[] = {
  127583. 2,
  127584. 1,
  127585. 3,
  127586. 0,
  127587. 4,
  127588. };
  127589. static long _vq_lengthlist__44c7_s_p6_1[] = {
  127590. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  127591. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127592. };
  127593. static float _vq_quantthresh__44c7_s_p6_1[] = {
  127594. -1.5, -0.5, 0.5, 1.5,
  127595. };
  127596. static long _vq_quantmap__44c7_s_p6_1[] = {
  127597. 3, 1, 0, 2, 4,
  127598. };
  127599. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  127600. _vq_quantthresh__44c7_s_p6_1,
  127601. _vq_quantmap__44c7_s_p6_1,
  127602. 5,
  127603. 5
  127604. };
  127605. static static_codebook _44c7_s_p6_1 = {
  127606. 2, 25,
  127607. _vq_lengthlist__44c7_s_p6_1,
  127608. 1, -533725184, 1611661312, 3, 0,
  127609. _vq_quantlist__44c7_s_p6_1,
  127610. NULL,
  127611. &_vq_auxt__44c7_s_p6_1,
  127612. NULL,
  127613. 0
  127614. };
  127615. static long _vq_quantlist__44c7_s_p7_0[] = {
  127616. 6,
  127617. 5,
  127618. 7,
  127619. 4,
  127620. 8,
  127621. 3,
  127622. 9,
  127623. 2,
  127624. 10,
  127625. 1,
  127626. 11,
  127627. 0,
  127628. 12,
  127629. };
  127630. static long _vq_lengthlist__44c7_s_p7_0[] = {
  127631. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  127632. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  127633. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  127634. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  127635. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  127636. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  127637. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  127638. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  127639. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  127640. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  127641. 19,13,13,13,13,14,14,15,15,
  127642. };
  127643. static float _vq_quantthresh__44c7_s_p7_0[] = {
  127644. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  127645. 27.5, 38.5, 49.5, 60.5,
  127646. };
  127647. static long _vq_quantmap__44c7_s_p7_0[] = {
  127648. 11, 9, 7, 5, 3, 1, 0, 2,
  127649. 4, 6, 8, 10, 12,
  127650. };
  127651. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  127652. _vq_quantthresh__44c7_s_p7_0,
  127653. _vq_quantmap__44c7_s_p7_0,
  127654. 13,
  127655. 13
  127656. };
  127657. static static_codebook _44c7_s_p7_0 = {
  127658. 2, 169,
  127659. _vq_lengthlist__44c7_s_p7_0,
  127660. 1, -523206656, 1618345984, 4, 0,
  127661. _vq_quantlist__44c7_s_p7_0,
  127662. NULL,
  127663. &_vq_auxt__44c7_s_p7_0,
  127664. NULL,
  127665. 0
  127666. };
  127667. static long _vq_quantlist__44c7_s_p7_1[] = {
  127668. 5,
  127669. 4,
  127670. 6,
  127671. 3,
  127672. 7,
  127673. 2,
  127674. 8,
  127675. 1,
  127676. 9,
  127677. 0,
  127678. 10,
  127679. };
  127680. static long _vq_lengthlist__44c7_s_p7_1[] = {
  127681. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  127682. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  127683. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  127684. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  127685. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  127686. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  127687. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  127688. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  127689. };
  127690. static float _vq_quantthresh__44c7_s_p7_1[] = {
  127691. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127692. 3.5, 4.5,
  127693. };
  127694. static long _vq_quantmap__44c7_s_p7_1[] = {
  127695. 9, 7, 5, 3, 1, 0, 2, 4,
  127696. 6, 8, 10,
  127697. };
  127698. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  127699. _vq_quantthresh__44c7_s_p7_1,
  127700. _vq_quantmap__44c7_s_p7_1,
  127701. 11,
  127702. 11
  127703. };
  127704. static static_codebook _44c7_s_p7_1 = {
  127705. 2, 121,
  127706. _vq_lengthlist__44c7_s_p7_1,
  127707. 1, -531365888, 1611661312, 4, 0,
  127708. _vq_quantlist__44c7_s_p7_1,
  127709. NULL,
  127710. &_vq_auxt__44c7_s_p7_1,
  127711. NULL,
  127712. 0
  127713. };
  127714. static long _vq_quantlist__44c7_s_p8_0[] = {
  127715. 7,
  127716. 6,
  127717. 8,
  127718. 5,
  127719. 9,
  127720. 4,
  127721. 10,
  127722. 3,
  127723. 11,
  127724. 2,
  127725. 12,
  127726. 1,
  127727. 13,
  127728. 0,
  127729. 14,
  127730. };
  127731. static long _vq_lengthlist__44c7_s_p8_0[] = {
  127732. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  127733. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  127734. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  127735. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  127736. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  127737. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  127738. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  127739. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  127740. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  127741. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  127742. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  127743. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  127744. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  127745. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  127746. 14,
  127747. };
  127748. static float _vq_quantthresh__44c7_s_p8_0[] = {
  127749. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127750. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127751. };
  127752. static long _vq_quantmap__44c7_s_p8_0[] = {
  127753. 13, 11, 9, 7, 5, 3, 1, 0,
  127754. 2, 4, 6, 8, 10, 12, 14,
  127755. };
  127756. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  127757. _vq_quantthresh__44c7_s_p8_0,
  127758. _vq_quantmap__44c7_s_p8_0,
  127759. 15,
  127760. 15
  127761. };
  127762. static static_codebook _44c7_s_p8_0 = {
  127763. 2, 225,
  127764. _vq_lengthlist__44c7_s_p8_0,
  127765. 1, -520986624, 1620377600, 4, 0,
  127766. _vq_quantlist__44c7_s_p8_0,
  127767. NULL,
  127768. &_vq_auxt__44c7_s_p8_0,
  127769. NULL,
  127770. 0
  127771. };
  127772. static long _vq_quantlist__44c7_s_p8_1[] = {
  127773. 10,
  127774. 9,
  127775. 11,
  127776. 8,
  127777. 12,
  127778. 7,
  127779. 13,
  127780. 6,
  127781. 14,
  127782. 5,
  127783. 15,
  127784. 4,
  127785. 16,
  127786. 3,
  127787. 17,
  127788. 2,
  127789. 18,
  127790. 1,
  127791. 19,
  127792. 0,
  127793. 20,
  127794. };
  127795. static long _vq_lengthlist__44c7_s_p8_1[] = {
  127796. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  127797. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  127798. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  127799. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  127800. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127801. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  127802. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  127803. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  127804. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127805. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127806. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  127807. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  127808. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  127809. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  127810. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  127811. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  127812. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  127813. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  127814. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  127815. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  127816. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  127817. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  127818. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  127819. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  127820. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  127821. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  127822. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  127823. 10,10,10,10,10,10,10,10,10,
  127824. };
  127825. static float _vq_quantthresh__44c7_s_p8_1[] = {
  127826. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127827. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127828. 6.5, 7.5, 8.5, 9.5,
  127829. };
  127830. static long _vq_quantmap__44c7_s_p8_1[] = {
  127831. 19, 17, 15, 13, 11, 9, 7, 5,
  127832. 3, 1, 0, 2, 4, 6, 8, 10,
  127833. 12, 14, 16, 18, 20,
  127834. };
  127835. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  127836. _vq_quantthresh__44c7_s_p8_1,
  127837. _vq_quantmap__44c7_s_p8_1,
  127838. 21,
  127839. 21
  127840. };
  127841. static static_codebook _44c7_s_p8_1 = {
  127842. 2, 441,
  127843. _vq_lengthlist__44c7_s_p8_1,
  127844. 1, -529268736, 1611661312, 5, 0,
  127845. _vq_quantlist__44c7_s_p8_1,
  127846. NULL,
  127847. &_vq_auxt__44c7_s_p8_1,
  127848. NULL,
  127849. 0
  127850. };
  127851. static long _vq_quantlist__44c7_s_p9_0[] = {
  127852. 6,
  127853. 5,
  127854. 7,
  127855. 4,
  127856. 8,
  127857. 3,
  127858. 9,
  127859. 2,
  127860. 10,
  127861. 1,
  127862. 11,
  127863. 0,
  127864. 12,
  127865. };
  127866. static long _vq_lengthlist__44c7_s_p9_0[] = {
  127867. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  127868. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  127869. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127870. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127871. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127872. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127873. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127874. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127875. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127876. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127877. 11,11,11,11,11,11,11,11,11,
  127878. };
  127879. static float _vq_quantthresh__44c7_s_p9_0[] = {
  127880. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  127881. 1592.5, 2229.5, 2866.5, 3503.5,
  127882. };
  127883. static long _vq_quantmap__44c7_s_p9_0[] = {
  127884. 11, 9, 7, 5, 3, 1, 0, 2,
  127885. 4, 6, 8, 10, 12,
  127886. };
  127887. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  127888. _vq_quantthresh__44c7_s_p9_0,
  127889. _vq_quantmap__44c7_s_p9_0,
  127890. 13,
  127891. 13
  127892. };
  127893. static static_codebook _44c7_s_p9_0 = {
  127894. 2, 169,
  127895. _vq_lengthlist__44c7_s_p9_0,
  127896. 1, -511845376, 1630791680, 4, 0,
  127897. _vq_quantlist__44c7_s_p9_0,
  127898. NULL,
  127899. &_vq_auxt__44c7_s_p9_0,
  127900. NULL,
  127901. 0
  127902. };
  127903. static long _vq_quantlist__44c7_s_p9_1[] = {
  127904. 6,
  127905. 5,
  127906. 7,
  127907. 4,
  127908. 8,
  127909. 3,
  127910. 9,
  127911. 2,
  127912. 10,
  127913. 1,
  127914. 11,
  127915. 0,
  127916. 12,
  127917. };
  127918. static long _vq_lengthlist__44c7_s_p9_1[] = {
  127919. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  127920. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  127921. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  127922. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  127923. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  127924. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  127925. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  127926. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  127927. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  127928. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  127929. 15,11,11,10,10,12,12,12,12,
  127930. };
  127931. static float _vq_quantthresh__44c7_s_p9_1[] = {
  127932. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  127933. 122.5, 171.5, 220.5, 269.5,
  127934. };
  127935. static long _vq_quantmap__44c7_s_p9_1[] = {
  127936. 11, 9, 7, 5, 3, 1, 0, 2,
  127937. 4, 6, 8, 10, 12,
  127938. };
  127939. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  127940. _vq_quantthresh__44c7_s_p9_1,
  127941. _vq_quantmap__44c7_s_p9_1,
  127942. 13,
  127943. 13
  127944. };
  127945. static static_codebook _44c7_s_p9_1 = {
  127946. 2, 169,
  127947. _vq_lengthlist__44c7_s_p9_1,
  127948. 1, -518889472, 1622704128, 4, 0,
  127949. _vq_quantlist__44c7_s_p9_1,
  127950. NULL,
  127951. &_vq_auxt__44c7_s_p9_1,
  127952. NULL,
  127953. 0
  127954. };
  127955. static long _vq_quantlist__44c7_s_p9_2[] = {
  127956. 24,
  127957. 23,
  127958. 25,
  127959. 22,
  127960. 26,
  127961. 21,
  127962. 27,
  127963. 20,
  127964. 28,
  127965. 19,
  127966. 29,
  127967. 18,
  127968. 30,
  127969. 17,
  127970. 31,
  127971. 16,
  127972. 32,
  127973. 15,
  127974. 33,
  127975. 14,
  127976. 34,
  127977. 13,
  127978. 35,
  127979. 12,
  127980. 36,
  127981. 11,
  127982. 37,
  127983. 10,
  127984. 38,
  127985. 9,
  127986. 39,
  127987. 8,
  127988. 40,
  127989. 7,
  127990. 41,
  127991. 6,
  127992. 42,
  127993. 5,
  127994. 43,
  127995. 4,
  127996. 44,
  127997. 3,
  127998. 45,
  127999. 2,
  128000. 46,
  128001. 1,
  128002. 47,
  128003. 0,
  128004. 48,
  128005. };
  128006. static long _vq_lengthlist__44c7_s_p9_2[] = {
  128007. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  128008. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128009. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128010. 7,
  128011. };
  128012. static float _vq_quantthresh__44c7_s_p9_2[] = {
  128013. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  128014. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  128015. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128016. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128017. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  128018. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  128019. };
  128020. static long _vq_quantmap__44c7_s_p9_2[] = {
  128021. 47, 45, 43, 41, 39, 37, 35, 33,
  128022. 31, 29, 27, 25, 23, 21, 19, 17,
  128023. 15, 13, 11, 9, 7, 5, 3, 1,
  128024. 0, 2, 4, 6, 8, 10, 12, 14,
  128025. 16, 18, 20, 22, 24, 26, 28, 30,
  128026. 32, 34, 36, 38, 40, 42, 44, 46,
  128027. 48,
  128028. };
  128029. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  128030. _vq_quantthresh__44c7_s_p9_2,
  128031. _vq_quantmap__44c7_s_p9_2,
  128032. 49,
  128033. 49
  128034. };
  128035. static static_codebook _44c7_s_p9_2 = {
  128036. 1, 49,
  128037. _vq_lengthlist__44c7_s_p9_2,
  128038. 1, -526909440, 1611661312, 6, 0,
  128039. _vq_quantlist__44c7_s_p9_2,
  128040. NULL,
  128041. &_vq_auxt__44c7_s_p9_2,
  128042. NULL,
  128043. 0
  128044. };
  128045. static long _huff_lengthlist__44c7_s_short[] = {
  128046. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  128047. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  128048. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  128049. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  128050. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  128051. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  128052. 10, 9,11,14,
  128053. };
  128054. static static_codebook _huff_book__44c7_s_short = {
  128055. 2, 100,
  128056. _huff_lengthlist__44c7_s_short,
  128057. 0, 0, 0, 0, 0,
  128058. NULL,
  128059. NULL,
  128060. NULL,
  128061. NULL,
  128062. 0
  128063. };
  128064. static long _huff_lengthlist__44c8_s_long[] = {
  128065. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  128066. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  128067. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  128068. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  128069. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  128070. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  128071. 11, 9, 9,10,
  128072. };
  128073. static static_codebook _huff_book__44c8_s_long = {
  128074. 2, 100,
  128075. _huff_lengthlist__44c8_s_long,
  128076. 0, 0, 0, 0, 0,
  128077. NULL,
  128078. NULL,
  128079. NULL,
  128080. NULL,
  128081. 0
  128082. };
  128083. static long _vq_quantlist__44c8_s_p1_0[] = {
  128084. 1,
  128085. 0,
  128086. 2,
  128087. };
  128088. static long _vq_lengthlist__44c8_s_p1_0[] = {
  128089. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  128090. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128091. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  128092. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128093. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  128094. 8,
  128095. };
  128096. static float _vq_quantthresh__44c8_s_p1_0[] = {
  128097. -0.5, 0.5,
  128098. };
  128099. static long _vq_quantmap__44c8_s_p1_0[] = {
  128100. 1, 0, 2,
  128101. };
  128102. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  128103. _vq_quantthresh__44c8_s_p1_0,
  128104. _vq_quantmap__44c8_s_p1_0,
  128105. 3,
  128106. 3
  128107. };
  128108. static static_codebook _44c8_s_p1_0 = {
  128109. 4, 81,
  128110. _vq_lengthlist__44c8_s_p1_0,
  128111. 1, -535822336, 1611661312, 2, 0,
  128112. _vq_quantlist__44c8_s_p1_0,
  128113. NULL,
  128114. &_vq_auxt__44c8_s_p1_0,
  128115. NULL,
  128116. 0
  128117. };
  128118. static long _vq_quantlist__44c8_s_p2_0[] = {
  128119. 2,
  128120. 1,
  128121. 3,
  128122. 0,
  128123. 4,
  128124. };
  128125. static long _vq_lengthlist__44c8_s_p2_0[] = {
  128126. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  128127. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  128128. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  128129. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  128130. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  128131. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  128132. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  128133. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  128134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128135. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  128136. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  128137. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  128138. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  128139. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  128140. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  128141. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  128144. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  128145. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  128146. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  128147. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  128148. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  128149. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128151. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  128152. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  128153. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  128154. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  128155. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  128156. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  128157. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  128162. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  128163. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  128164. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  128165. 13,
  128166. };
  128167. static float _vq_quantthresh__44c8_s_p2_0[] = {
  128168. -1.5, -0.5, 0.5, 1.5,
  128169. };
  128170. static long _vq_quantmap__44c8_s_p2_0[] = {
  128171. 3, 1, 0, 2, 4,
  128172. };
  128173. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  128174. _vq_quantthresh__44c8_s_p2_0,
  128175. _vq_quantmap__44c8_s_p2_0,
  128176. 5,
  128177. 5
  128178. };
  128179. static static_codebook _44c8_s_p2_0 = {
  128180. 4, 625,
  128181. _vq_lengthlist__44c8_s_p2_0,
  128182. 1, -533725184, 1611661312, 3, 0,
  128183. _vq_quantlist__44c8_s_p2_0,
  128184. NULL,
  128185. &_vq_auxt__44c8_s_p2_0,
  128186. NULL,
  128187. 0
  128188. };
  128189. static long _vq_quantlist__44c8_s_p3_0[] = {
  128190. 4,
  128191. 3,
  128192. 5,
  128193. 2,
  128194. 6,
  128195. 1,
  128196. 7,
  128197. 0,
  128198. 8,
  128199. };
  128200. static long _vq_lengthlist__44c8_s_p3_0[] = {
  128201. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  128202. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  128203. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  128204. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0,
  128207. };
  128208. static float _vq_quantthresh__44c8_s_p3_0[] = {
  128209. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128210. };
  128211. static long _vq_quantmap__44c8_s_p3_0[] = {
  128212. 7, 5, 3, 1, 0, 2, 4, 6,
  128213. 8,
  128214. };
  128215. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  128216. _vq_quantthresh__44c8_s_p3_0,
  128217. _vq_quantmap__44c8_s_p3_0,
  128218. 9,
  128219. 9
  128220. };
  128221. static static_codebook _44c8_s_p3_0 = {
  128222. 2, 81,
  128223. _vq_lengthlist__44c8_s_p3_0,
  128224. 1, -531628032, 1611661312, 4, 0,
  128225. _vq_quantlist__44c8_s_p3_0,
  128226. NULL,
  128227. &_vq_auxt__44c8_s_p3_0,
  128228. NULL,
  128229. 0
  128230. };
  128231. static long _vq_quantlist__44c8_s_p4_0[] = {
  128232. 8,
  128233. 7,
  128234. 9,
  128235. 6,
  128236. 10,
  128237. 5,
  128238. 11,
  128239. 4,
  128240. 12,
  128241. 3,
  128242. 13,
  128243. 2,
  128244. 14,
  128245. 1,
  128246. 15,
  128247. 0,
  128248. 16,
  128249. };
  128250. static long _vq_lengthlist__44c8_s_p4_0[] = {
  128251. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  128252. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  128253. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  128254. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  128255. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  128256. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  128257. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  128258. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  128259. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  128260. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  128261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0,
  128270. };
  128271. static float _vq_quantthresh__44c8_s_p4_0[] = {
  128272. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128273. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128274. };
  128275. static long _vq_quantmap__44c8_s_p4_0[] = {
  128276. 15, 13, 11, 9, 7, 5, 3, 1,
  128277. 0, 2, 4, 6, 8, 10, 12, 14,
  128278. 16,
  128279. };
  128280. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  128281. _vq_quantthresh__44c8_s_p4_0,
  128282. _vq_quantmap__44c8_s_p4_0,
  128283. 17,
  128284. 17
  128285. };
  128286. static static_codebook _44c8_s_p4_0 = {
  128287. 2, 289,
  128288. _vq_lengthlist__44c8_s_p4_0,
  128289. 1, -529530880, 1611661312, 5, 0,
  128290. _vq_quantlist__44c8_s_p4_0,
  128291. NULL,
  128292. &_vq_auxt__44c8_s_p4_0,
  128293. NULL,
  128294. 0
  128295. };
  128296. static long _vq_quantlist__44c8_s_p5_0[] = {
  128297. 1,
  128298. 0,
  128299. 2,
  128300. };
  128301. static long _vq_lengthlist__44c8_s_p5_0[] = {
  128302. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  128303. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  128304. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  128305. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  128306. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  128307. 12,
  128308. };
  128309. static float _vq_quantthresh__44c8_s_p5_0[] = {
  128310. -5.5, 5.5,
  128311. };
  128312. static long _vq_quantmap__44c8_s_p5_0[] = {
  128313. 1, 0, 2,
  128314. };
  128315. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  128316. _vq_quantthresh__44c8_s_p5_0,
  128317. _vq_quantmap__44c8_s_p5_0,
  128318. 3,
  128319. 3
  128320. };
  128321. static static_codebook _44c8_s_p5_0 = {
  128322. 4, 81,
  128323. _vq_lengthlist__44c8_s_p5_0,
  128324. 1, -529137664, 1618345984, 2, 0,
  128325. _vq_quantlist__44c8_s_p5_0,
  128326. NULL,
  128327. &_vq_auxt__44c8_s_p5_0,
  128328. NULL,
  128329. 0
  128330. };
  128331. static long _vq_quantlist__44c8_s_p5_1[] = {
  128332. 5,
  128333. 4,
  128334. 6,
  128335. 3,
  128336. 7,
  128337. 2,
  128338. 8,
  128339. 1,
  128340. 9,
  128341. 0,
  128342. 10,
  128343. };
  128344. static long _vq_lengthlist__44c8_s_p5_1[] = {
  128345. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  128346. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  128347. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  128348. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  128349. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  128350. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  128351. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  128352. 11,11,11, 7, 7, 7, 7, 8, 8,
  128353. };
  128354. static float _vq_quantthresh__44c8_s_p5_1[] = {
  128355. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128356. 3.5, 4.5,
  128357. };
  128358. static long _vq_quantmap__44c8_s_p5_1[] = {
  128359. 9, 7, 5, 3, 1, 0, 2, 4,
  128360. 6, 8, 10,
  128361. };
  128362. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  128363. _vq_quantthresh__44c8_s_p5_1,
  128364. _vq_quantmap__44c8_s_p5_1,
  128365. 11,
  128366. 11
  128367. };
  128368. static static_codebook _44c8_s_p5_1 = {
  128369. 2, 121,
  128370. _vq_lengthlist__44c8_s_p5_1,
  128371. 1, -531365888, 1611661312, 4, 0,
  128372. _vq_quantlist__44c8_s_p5_1,
  128373. NULL,
  128374. &_vq_auxt__44c8_s_p5_1,
  128375. NULL,
  128376. 0
  128377. };
  128378. static long _vq_quantlist__44c8_s_p6_0[] = {
  128379. 6,
  128380. 5,
  128381. 7,
  128382. 4,
  128383. 8,
  128384. 3,
  128385. 9,
  128386. 2,
  128387. 10,
  128388. 1,
  128389. 11,
  128390. 0,
  128391. 12,
  128392. };
  128393. static long _vq_lengthlist__44c8_s_p6_0[] = {
  128394. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  128395. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  128396. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  128397. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  128398. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  128399. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  128400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128404. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128405. };
  128406. static float _vq_quantthresh__44c8_s_p6_0[] = {
  128407. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128408. 12.5, 17.5, 22.5, 27.5,
  128409. };
  128410. static long _vq_quantmap__44c8_s_p6_0[] = {
  128411. 11, 9, 7, 5, 3, 1, 0, 2,
  128412. 4, 6, 8, 10, 12,
  128413. };
  128414. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  128415. _vq_quantthresh__44c8_s_p6_0,
  128416. _vq_quantmap__44c8_s_p6_0,
  128417. 13,
  128418. 13
  128419. };
  128420. static static_codebook _44c8_s_p6_0 = {
  128421. 2, 169,
  128422. _vq_lengthlist__44c8_s_p6_0,
  128423. 1, -526516224, 1616117760, 4, 0,
  128424. _vq_quantlist__44c8_s_p6_0,
  128425. NULL,
  128426. &_vq_auxt__44c8_s_p6_0,
  128427. NULL,
  128428. 0
  128429. };
  128430. static long _vq_quantlist__44c8_s_p6_1[] = {
  128431. 2,
  128432. 1,
  128433. 3,
  128434. 0,
  128435. 4,
  128436. };
  128437. static long _vq_lengthlist__44c8_s_p6_1[] = {
  128438. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  128439. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128440. };
  128441. static float _vq_quantthresh__44c8_s_p6_1[] = {
  128442. -1.5, -0.5, 0.5, 1.5,
  128443. };
  128444. static long _vq_quantmap__44c8_s_p6_1[] = {
  128445. 3, 1, 0, 2, 4,
  128446. };
  128447. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  128448. _vq_quantthresh__44c8_s_p6_1,
  128449. _vq_quantmap__44c8_s_p6_1,
  128450. 5,
  128451. 5
  128452. };
  128453. static static_codebook _44c8_s_p6_1 = {
  128454. 2, 25,
  128455. _vq_lengthlist__44c8_s_p6_1,
  128456. 1, -533725184, 1611661312, 3, 0,
  128457. _vq_quantlist__44c8_s_p6_1,
  128458. NULL,
  128459. &_vq_auxt__44c8_s_p6_1,
  128460. NULL,
  128461. 0
  128462. };
  128463. static long _vq_quantlist__44c8_s_p7_0[] = {
  128464. 6,
  128465. 5,
  128466. 7,
  128467. 4,
  128468. 8,
  128469. 3,
  128470. 9,
  128471. 2,
  128472. 10,
  128473. 1,
  128474. 11,
  128475. 0,
  128476. 12,
  128477. };
  128478. static long _vq_lengthlist__44c8_s_p7_0[] = {
  128479. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  128480. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  128481. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  128482. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  128483. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  128484. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  128485. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  128486. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  128487. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  128488. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  128489. 20,13,13,13,13,14,13,15,15,
  128490. };
  128491. static float _vq_quantthresh__44c8_s_p7_0[] = {
  128492. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  128493. 27.5, 38.5, 49.5, 60.5,
  128494. };
  128495. static long _vq_quantmap__44c8_s_p7_0[] = {
  128496. 11, 9, 7, 5, 3, 1, 0, 2,
  128497. 4, 6, 8, 10, 12,
  128498. };
  128499. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  128500. _vq_quantthresh__44c8_s_p7_0,
  128501. _vq_quantmap__44c8_s_p7_0,
  128502. 13,
  128503. 13
  128504. };
  128505. static static_codebook _44c8_s_p7_0 = {
  128506. 2, 169,
  128507. _vq_lengthlist__44c8_s_p7_0,
  128508. 1, -523206656, 1618345984, 4, 0,
  128509. _vq_quantlist__44c8_s_p7_0,
  128510. NULL,
  128511. &_vq_auxt__44c8_s_p7_0,
  128512. NULL,
  128513. 0
  128514. };
  128515. static long _vq_quantlist__44c8_s_p7_1[] = {
  128516. 5,
  128517. 4,
  128518. 6,
  128519. 3,
  128520. 7,
  128521. 2,
  128522. 8,
  128523. 1,
  128524. 9,
  128525. 0,
  128526. 10,
  128527. };
  128528. static long _vq_lengthlist__44c8_s_p7_1[] = {
  128529. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  128530. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  128531. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  128532. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  128533. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  128534. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  128535. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  128536. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  128537. };
  128538. static float _vq_quantthresh__44c8_s_p7_1[] = {
  128539. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128540. 3.5, 4.5,
  128541. };
  128542. static long _vq_quantmap__44c8_s_p7_1[] = {
  128543. 9, 7, 5, 3, 1, 0, 2, 4,
  128544. 6, 8, 10,
  128545. };
  128546. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  128547. _vq_quantthresh__44c8_s_p7_1,
  128548. _vq_quantmap__44c8_s_p7_1,
  128549. 11,
  128550. 11
  128551. };
  128552. static static_codebook _44c8_s_p7_1 = {
  128553. 2, 121,
  128554. _vq_lengthlist__44c8_s_p7_1,
  128555. 1, -531365888, 1611661312, 4, 0,
  128556. _vq_quantlist__44c8_s_p7_1,
  128557. NULL,
  128558. &_vq_auxt__44c8_s_p7_1,
  128559. NULL,
  128560. 0
  128561. };
  128562. static long _vq_quantlist__44c8_s_p8_0[] = {
  128563. 7,
  128564. 6,
  128565. 8,
  128566. 5,
  128567. 9,
  128568. 4,
  128569. 10,
  128570. 3,
  128571. 11,
  128572. 2,
  128573. 12,
  128574. 1,
  128575. 13,
  128576. 0,
  128577. 14,
  128578. };
  128579. static long _vq_lengthlist__44c8_s_p8_0[] = {
  128580. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  128581. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  128582. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  128583. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  128584. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  128585. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  128586. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  128587. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  128588. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  128589. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  128590. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  128591. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  128592. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  128593. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  128594. 15,
  128595. };
  128596. static float _vq_quantthresh__44c8_s_p8_0[] = {
  128597. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  128598. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  128599. };
  128600. static long _vq_quantmap__44c8_s_p8_0[] = {
  128601. 13, 11, 9, 7, 5, 3, 1, 0,
  128602. 2, 4, 6, 8, 10, 12, 14,
  128603. };
  128604. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  128605. _vq_quantthresh__44c8_s_p8_0,
  128606. _vq_quantmap__44c8_s_p8_0,
  128607. 15,
  128608. 15
  128609. };
  128610. static static_codebook _44c8_s_p8_0 = {
  128611. 2, 225,
  128612. _vq_lengthlist__44c8_s_p8_0,
  128613. 1, -520986624, 1620377600, 4, 0,
  128614. _vq_quantlist__44c8_s_p8_0,
  128615. NULL,
  128616. &_vq_auxt__44c8_s_p8_0,
  128617. NULL,
  128618. 0
  128619. };
  128620. static long _vq_quantlist__44c8_s_p8_1[] = {
  128621. 10,
  128622. 9,
  128623. 11,
  128624. 8,
  128625. 12,
  128626. 7,
  128627. 13,
  128628. 6,
  128629. 14,
  128630. 5,
  128631. 15,
  128632. 4,
  128633. 16,
  128634. 3,
  128635. 17,
  128636. 2,
  128637. 18,
  128638. 1,
  128639. 19,
  128640. 0,
  128641. 20,
  128642. };
  128643. static long _vq_lengthlist__44c8_s_p8_1[] = {
  128644. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  128645. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  128646. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  128647. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  128648. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128649. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  128650. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  128651. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  128652. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128653. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128654. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  128655. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  128656. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  128657. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128658. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  128659. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  128660. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  128661. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  128662. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  128663. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  128664. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  128665. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  128666. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  128667. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  128668. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  128669. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  128670. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  128671. 10, 9, 9,10,10, 9,10, 9, 9,
  128672. };
  128673. static float _vq_quantthresh__44c8_s_p8_1[] = {
  128674. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128675. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128676. 6.5, 7.5, 8.5, 9.5,
  128677. };
  128678. static long _vq_quantmap__44c8_s_p8_1[] = {
  128679. 19, 17, 15, 13, 11, 9, 7, 5,
  128680. 3, 1, 0, 2, 4, 6, 8, 10,
  128681. 12, 14, 16, 18, 20,
  128682. };
  128683. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  128684. _vq_quantthresh__44c8_s_p8_1,
  128685. _vq_quantmap__44c8_s_p8_1,
  128686. 21,
  128687. 21
  128688. };
  128689. static static_codebook _44c8_s_p8_1 = {
  128690. 2, 441,
  128691. _vq_lengthlist__44c8_s_p8_1,
  128692. 1, -529268736, 1611661312, 5, 0,
  128693. _vq_quantlist__44c8_s_p8_1,
  128694. NULL,
  128695. &_vq_auxt__44c8_s_p8_1,
  128696. NULL,
  128697. 0
  128698. };
  128699. static long _vq_quantlist__44c8_s_p9_0[] = {
  128700. 8,
  128701. 7,
  128702. 9,
  128703. 6,
  128704. 10,
  128705. 5,
  128706. 11,
  128707. 4,
  128708. 12,
  128709. 3,
  128710. 13,
  128711. 2,
  128712. 14,
  128713. 1,
  128714. 15,
  128715. 0,
  128716. 16,
  128717. };
  128718. static long _vq_lengthlist__44c8_s_p9_0[] = {
  128719. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128720. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  128721. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  128722. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128723. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128724. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128725. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128726. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128727. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128728. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128729. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128730. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128731. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128732. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128733. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128734. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128735. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128736. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128737. 10,
  128738. };
  128739. static float _vq_quantthresh__44c8_s_p9_0[] = {
  128740. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  128741. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  128742. };
  128743. static long _vq_quantmap__44c8_s_p9_0[] = {
  128744. 15, 13, 11, 9, 7, 5, 3, 1,
  128745. 0, 2, 4, 6, 8, 10, 12, 14,
  128746. 16,
  128747. };
  128748. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  128749. _vq_quantthresh__44c8_s_p9_0,
  128750. _vq_quantmap__44c8_s_p9_0,
  128751. 17,
  128752. 17
  128753. };
  128754. static static_codebook _44c8_s_p9_0 = {
  128755. 2, 289,
  128756. _vq_lengthlist__44c8_s_p9_0,
  128757. 1, -509798400, 1631393792, 5, 0,
  128758. _vq_quantlist__44c8_s_p9_0,
  128759. NULL,
  128760. &_vq_auxt__44c8_s_p9_0,
  128761. NULL,
  128762. 0
  128763. };
  128764. static long _vq_quantlist__44c8_s_p9_1[] = {
  128765. 9,
  128766. 8,
  128767. 10,
  128768. 7,
  128769. 11,
  128770. 6,
  128771. 12,
  128772. 5,
  128773. 13,
  128774. 4,
  128775. 14,
  128776. 3,
  128777. 15,
  128778. 2,
  128779. 16,
  128780. 1,
  128781. 17,
  128782. 0,
  128783. 18,
  128784. };
  128785. static long _vq_lengthlist__44c8_s_p9_1[] = {
  128786. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  128787. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  128788. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  128789. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  128790. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  128791. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  128792. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  128793. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  128794. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  128795. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  128796. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  128797. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  128798. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  128799. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  128800. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  128801. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  128802. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  128803. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  128804. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  128805. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  128806. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  128807. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  128808. 14,13,13,14,14,15,14,15,14,
  128809. };
  128810. static float _vq_quantthresh__44c8_s_p9_1[] = {
  128811. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  128812. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  128813. 367.5, 416.5,
  128814. };
  128815. static long _vq_quantmap__44c8_s_p9_1[] = {
  128816. 17, 15, 13, 11, 9, 7, 5, 3,
  128817. 1, 0, 2, 4, 6, 8, 10, 12,
  128818. 14, 16, 18,
  128819. };
  128820. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  128821. _vq_quantthresh__44c8_s_p9_1,
  128822. _vq_quantmap__44c8_s_p9_1,
  128823. 19,
  128824. 19
  128825. };
  128826. static static_codebook _44c8_s_p9_1 = {
  128827. 2, 361,
  128828. _vq_lengthlist__44c8_s_p9_1,
  128829. 1, -518287360, 1622704128, 5, 0,
  128830. _vq_quantlist__44c8_s_p9_1,
  128831. NULL,
  128832. &_vq_auxt__44c8_s_p9_1,
  128833. NULL,
  128834. 0
  128835. };
  128836. static long _vq_quantlist__44c8_s_p9_2[] = {
  128837. 24,
  128838. 23,
  128839. 25,
  128840. 22,
  128841. 26,
  128842. 21,
  128843. 27,
  128844. 20,
  128845. 28,
  128846. 19,
  128847. 29,
  128848. 18,
  128849. 30,
  128850. 17,
  128851. 31,
  128852. 16,
  128853. 32,
  128854. 15,
  128855. 33,
  128856. 14,
  128857. 34,
  128858. 13,
  128859. 35,
  128860. 12,
  128861. 36,
  128862. 11,
  128863. 37,
  128864. 10,
  128865. 38,
  128866. 9,
  128867. 39,
  128868. 8,
  128869. 40,
  128870. 7,
  128871. 41,
  128872. 6,
  128873. 42,
  128874. 5,
  128875. 43,
  128876. 4,
  128877. 44,
  128878. 3,
  128879. 45,
  128880. 2,
  128881. 46,
  128882. 1,
  128883. 47,
  128884. 0,
  128885. 48,
  128886. };
  128887. static long _vq_lengthlist__44c8_s_p9_2[] = {
  128888. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  128889. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128890. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128891. 7,
  128892. };
  128893. static float _vq_quantthresh__44c8_s_p9_2[] = {
  128894. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  128895. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  128896. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128897. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128898. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  128899. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  128900. };
  128901. static long _vq_quantmap__44c8_s_p9_2[] = {
  128902. 47, 45, 43, 41, 39, 37, 35, 33,
  128903. 31, 29, 27, 25, 23, 21, 19, 17,
  128904. 15, 13, 11, 9, 7, 5, 3, 1,
  128905. 0, 2, 4, 6, 8, 10, 12, 14,
  128906. 16, 18, 20, 22, 24, 26, 28, 30,
  128907. 32, 34, 36, 38, 40, 42, 44, 46,
  128908. 48,
  128909. };
  128910. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  128911. _vq_quantthresh__44c8_s_p9_2,
  128912. _vq_quantmap__44c8_s_p9_2,
  128913. 49,
  128914. 49
  128915. };
  128916. static static_codebook _44c8_s_p9_2 = {
  128917. 1, 49,
  128918. _vq_lengthlist__44c8_s_p9_2,
  128919. 1, -526909440, 1611661312, 6, 0,
  128920. _vq_quantlist__44c8_s_p9_2,
  128921. NULL,
  128922. &_vq_auxt__44c8_s_p9_2,
  128923. NULL,
  128924. 0
  128925. };
  128926. static long _huff_lengthlist__44c8_s_short[] = {
  128927. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  128928. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  128929. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  128930. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  128931. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  128932. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  128933. 10, 9,11,14,
  128934. };
  128935. static static_codebook _huff_book__44c8_s_short = {
  128936. 2, 100,
  128937. _huff_lengthlist__44c8_s_short,
  128938. 0, 0, 0, 0, 0,
  128939. NULL,
  128940. NULL,
  128941. NULL,
  128942. NULL,
  128943. 0
  128944. };
  128945. static long _huff_lengthlist__44c9_s_long[] = {
  128946. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  128947. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  128948. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  128949. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  128950. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  128951. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  128952. 10, 9, 8, 9,
  128953. };
  128954. static static_codebook _huff_book__44c9_s_long = {
  128955. 2, 100,
  128956. _huff_lengthlist__44c9_s_long,
  128957. 0, 0, 0, 0, 0,
  128958. NULL,
  128959. NULL,
  128960. NULL,
  128961. NULL,
  128962. 0
  128963. };
  128964. static long _vq_quantlist__44c9_s_p1_0[] = {
  128965. 1,
  128966. 0,
  128967. 2,
  128968. };
  128969. static long _vq_lengthlist__44c9_s_p1_0[] = {
  128970. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  128971. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128972. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  128973. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128974. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  128975. 7,
  128976. };
  128977. static float _vq_quantthresh__44c9_s_p1_0[] = {
  128978. -0.5, 0.5,
  128979. };
  128980. static long _vq_quantmap__44c9_s_p1_0[] = {
  128981. 1, 0, 2,
  128982. };
  128983. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  128984. _vq_quantthresh__44c9_s_p1_0,
  128985. _vq_quantmap__44c9_s_p1_0,
  128986. 3,
  128987. 3
  128988. };
  128989. static static_codebook _44c9_s_p1_0 = {
  128990. 4, 81,
  128991. _vq_lengthlist__44c9_s_p1_0,
  128992. 1, -535822336, 1611661312, 2, 0,
  128993. _vq_quantlist__44c9_s_p1_0,
  128994. NULL,
  128995. &_vq_auxt__44c9_s_p1_0,
  128996. NULL,
  128997. 0
  128998. };
  128999. static long _vq_quantlist__44c9_s_p2_0[] = {
  129000. 2,
  129001. 1,
  129002. 3,
  129003. 0,
  129004. 4,
  129005. };
  129006. static long _vq_lengthlist__44c9_s_p2_0[] = {
  129007. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  129008. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  129009. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  129010. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  129011. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  129012. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  129013. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  129014. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  129015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129016. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  129017. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  129018. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  129019. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  129020. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  129021. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  129022. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  129023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129024. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  129025. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  129026. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  129027. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  129028. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  129029. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  129030. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129032. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  129033. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  129034. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  129035. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  129036. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  129037. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  129038. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  129043. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  129044. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  129045. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  129046. 12,
  129047. };
  129048. static float _vq_quantthresh__44c9_s_p2_0[] = {
  129049. -1.5, -0.5, 0.5, 1.5,
  129050. };
  129051. static long _vq_quantmap__44c9_s_p2_0[] = {
  129052. 3, 1, 0, 2, 4,
  129053. };
  129054. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  129055. _vq_quantthresh__44c9_s_p2_0,
  129056. _vq_quantmap__44c9_s_p2_0,
  129057. 5,
  129058. 5
  129059. };
  129060. static static_codebook _44c9_s_p2_0 = {
  129061. 4, 625,
  129062. _vq_lengthlist__44c9_s_p2_0,
  129063. 1, -533725184, 1611661312, 3, 0,
  129064. _vq_quantlist__44c9_s_p2_0,
  129065. NULL,
  129066. &_vq_auxt__44c9_s_p2_0,
  129067. NULL,
  129068. 0
  129069. };
  129070. static long _vq_quantlist__44c9_s_p3_0[] = {
  129071. 4,
  129072. 3,
  129073. 5,
  129074. 2,
  129075. 6,
  129076. 1,
  129077. 7,
  129078. 0,
  129079. 8,
  129080. };
  129081. static long _vq_lengthlist__44c9_s_p3_0[] = {
  129082. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  129083. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  129084. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  129085. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  129086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129087. 0,
  129088. };
  129089. static float _vq_quantthresh__44c9_s_p3_0[] = {
  129090. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129091. };
  129092. static long _vq_quantmap__44c9_s_p3_0[] = {
  129093. 7, 5, 3, 1, 0, 2, 4, 6,
  129094. 8,
  129095. };
  129096. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  129097. _vq_quantthresh__44c9_s_p3_0,
  129098. _vq_quantmap__44c9_s_p3_0,
  129099. 9,
  129100. 9
  129101. };
  129102. static static_codebook _44c9_s_p3_0 = {
  129103. 2, 81,
  129104. _vq_lengthlist__44c9_s_p3_0,
  129105. 1, -531628032, 1611661312, 4, 0,
  129106. _vq_quantlist__44c9_s_p3_0,
  129107. NULL,
  129108. &_vq_auxt__44c9_s_p3_0,
  129109. NULL,
  129110. 0
  129111. };
  129112. static long _vq_quantlist__44c9_s_p4_0[] = {
  129113. 8,
  129114. 7,
  129115. 9,
  129116. 6,
  129117. 10,
  129118. 5,
  129119. 11,
  129120. 4,
  129121. 12,
  129122. 3,
  129123. 13,
  129124. 2,
  129125. 14,
  129126. 1,
  129127. 15,
  129128. 0,
  129129. 16,
  129130. };
  129131. static long _vq_lengthlist__44c9_s_p4_0[] = {
  129132. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  129133. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  129134. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  129135. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  129136. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  129137. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  129138. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  129139. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  129140. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  129141. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  129142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129150. 0,
  129151. };
  129152. static float _vq_quantthresh__44c9_s_p4_0[] = {
  129153. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129154. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129155. };
  129156. static long _vq_quantmap__44c9_s_p4_0[] = {
  129157. 15, 13, 11, 9, 7, 5, 3, 1,
  129158. 0, 2, 4, 6, 8, 10, 12, 14,
  129159. 16,
  129160. };
  129161. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  129162. _vq_quantthresh__44c9_s_p4_0,
  129163. _vq_quantmap__44c9_s_p4_0,
  129164. 17,
  129165. 17
  129166. };
  129167. static static_codebook _44c9_s_p4_0 = {
  129168. 2, 289,
  129169. _vq_lengthlist__44c9_s_p4_0,
  129170. 1, -529530880, 1611661312, 5, 0,
  129171. _vq_quantlist__44c9_s_p4_0,
  129172. NULL,
  129173. &_vq_auxt__44c9_s_p4_0,
  129174. NULL,
  129175. 0
  129176. };
  129177. static long _vq_quantlist__44c9_s_p5_0[] = {
  129178. 1,
  129179. 0,
  129180. 2,
  129181. };
  129182. static long _vq_lengthlist__44c9_s_p5_0[] = {
  129183. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  129184. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  129185. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  129186. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  129187. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  129188. 12,
  129189. };
  129190. static float _vq_quantthresh__44c9_s_p5_0[] = {
  129191. -5.5, 5.5,
  129192. };
  129193. static long _vq_quantmap__44c9_s_p5_0[] = {
  129194. 1, 0, 2,
  129195. };
  129196. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  129197. _vq_quantthresh__44c9_s_p5_0,
  129198. _vq_quantmap__44c9_s_p5_0,
  129199. 3,
  129200. 3
  129201. };
  129202. static static_codebook _44c9_s_p5_0 = {
  129203. 4, 81,
  129204. _vq_lengthlist__44c9_s_p5_0,
  129205. 1, -529137664, 1618345984, 2, 0,
  129206. _vq_quantlist__44c9_s_p5_0,
  129207. NULL,
  129208. &_vq_auxt__44c9_s_p5_0,
  129209. NULL,
  129210. 0
  129211. };
  129212. static long _vq_quantlist__44c9_s_p5_1[] = {
  129213. 5,
  129214. 4,
  129215. 6,
  129216. 3,
  129217. 7,
  129218. 2,
  129219. 8,
  129220. 1,
  129221. 9,
  129222. 0,
  129223. 10,
  129224. };
  129225. static long _vq_lengthlist__44c9_s_p5_1[] = {
  129226. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  129227. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  129228. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  129229. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  129230. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  129231. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  129232. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  129233. 11,11,11, 7, 7, 7, 7, 7, 7,
  129234. };
  129235. static float _vq_quantthresh__44c9_s_p5_1[] = {
  129236. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129237. 3.5, 4.5,
  129238. };
  129239. static long _vq_quantmap__44c9_s_p5_1[] = {
  129240. 9, 7, 5, 3, 1, 0, 2, 4,
  129241. 6, 8, 10,
  129242. };
  129243. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  129244. _vq_quantthresh__44c9_s_p5_1,
  129245. _vq_quantmap__44c9_s_p5_1,
  129246. 11,
  129247. 11
  129248. };
  129249. static static_codebook _44c9_s_p5_1 = {
  129250. 2, 121,
  129251. _vq_lengthlist__44c9_s_p5_1,
  129252. 1, -531365888, 1611661312, 4, 0,
  129253. _vq_quantlist__44c9_s_p5_1,
  129254. NULL,
  129255. &_vq_auxt__44c9_s_p5_1,
  129256. NULL,
  129257. 0
  129258. };
  129259. static long _vq_quantlist__44c9_s_p6_0[] = {
  129260. 6,
  129261. 5,
  129262. 7,
  129263. 4,
  129264. 8,
  129265. 3,
  129266. 9,
  129267. 2,
  129268. 10,
  129269. 1,
  129270. 11,
  129271. 0,
  129272. 12,
  129273. };
  129274. static long _vq_lengthlist__44c9_s_p6_0[] = {
  129275. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  129276. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  129277. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  129278. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  129279. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  129280. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  129281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129285. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129286. };
  129287. static float _vq_quantthresh__44c9_s_p6_0[] = {
  129288. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129289. 12.5, 17.5, 22.5, 27.5,
  129290. };
  129291. static long _vq_quantmap__44c9_s_p6_0[] = {
  129292. 11, 9, 7, 5, 3, 1, 0, 2,
  129293. 4, 6, 8, 10, 12,
  129294. };
  129295. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  129296. _vq_quantthresh__44c9_s_p6_0,
  129297. _vq_quantmap__44c9_s_p6_0,
  129298. 13,
  129299. 13
  129300. };
  129301. static static_codebook _44c9_s_p6_0 = {
  129302. 2, 169,
  129303. _vq_lengthlist__44c9_s_p6_0,
  129304. 1, -526516224, 1616117760, 4, 0,
  129305. _vq_quantlist__44c9_s_p6_0,
  129306. NULL,
  129307. &_vq_auxt__44c9_s_p6_0,
  129308. NULL,
  129309. 0
  129310. };
  129311. static long _vq_quantlist__44c9_s_p6_1[] = {
  129312. 2,
  129313. 1,
  129314. 3,
  129315. 0,
  129316. 4,
  129317. };
  129318. static long _vq_lengthlist__44c9_s_p6_1[] = {
  129319. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  129320. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  129321. };
  129322. static float _vq_quantthresh__44c9_s_p6_1[] = {
  129323. -1.5, -0.5, 0.5, 1.5,
  129324. };
  129325. static long _vq_quantmap__44c9_s_p6_1[] = {
  129326. 3, 1, 0, 2, 4,
  129327. };
  129328. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  129329. _vq_quantthresh__44c9_s_p6_1,
  129330. _vq_quantmap__44c9_s_p6_1,
  129331. 5,
  129332. 5
  129333. };
  129334. static static_codebook _44c9_s_p6_1 = {
  129335. 2, 25,
  129336. _vq_lengthlist__44c9_s_p6_1,
  129337. 1, -533725184, 1611661312, 3, 0,
  129338. _vq_quantlist__44c9_s_p6_1,
  129339. NULL,
  129340. &_vq_auxt__44c9_s_p6_1,
  129341. NULL,
  129342. 0
  129343. };
  129344. static long _vq_quantlist__44c9_s_p7_0[] = {
  129345. 6,
  129346. 5,
  129347. 7,
  129348. 4,
  129349. 8,
  129350. 3,
  129351. 9,
  129352. 2,
  129353. 10,
  129354. 1,
  129355. 11,
  129356. 0,
  129357. 12,
  129358. };
  129359. static long _vq_lengthlist__44c9_s_p7_0[] = {
  129360. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  129361. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  129362. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  129363. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  129364. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  129365. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  129366. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  129367. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  129368. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  129369. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  129370. 19,12,12,12,12,13,13,14,14,
  129371. };
  129372. static float _vq_quantthresh__44c9_s_p7_0[] = {
  129373. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  129374. 27.5, 38.5, 49.5, 60.5,
  129375. };
  129376. static long _vq_quantmap__44c9_s_p7_0[] = {
  129377. 11, 9, 7, 5, 3, 1, 0, 2,
  129378. 4, 6, 8, 10, 12,
  129379. };
  129380. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  129381. _vq_quantthresh__44c9_s_p7_0,
  129382. _vq_quantmap__44c9_s_p7_0,
  129383. 13,
  129384. 13
  129385. };
  129386. static static_codebook _44c9_s_p7_0 = {
  129387. 2, 169,
  129388. _vq_lengthlist__44c9_s_p7_0,
  129389. 1, -523206656, 1618345984, 4, 0,
  129390. _vq_quantlist__44c9_s_p7_0,
  129391. NULL,
  129392. &_vq_auxt__44c9_s_p7_0,
  129393. NULL,
  129394. 0
  129395. };
  129396. static long _vq_quantlist__44c9_s_p7_1[] = {
  129397. 5,
  129398. 4,
  129399. 6,
  129400. 3,
  129401. 7,
  129402. 2,
  129403. 8,
  129404. 1,
  129405. 9,
  129406. 0,
  129407. 10,
  129408. };
  129409. static long _vq_lengthlist__44c9_s_p7_1[] = {
  129410. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  129411. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  129412. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  129413. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129414. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  129415. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  129416. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  129417. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129418. };
  129419. static float _vq_quantthresh__44c9_s_p7_1[] = {
  129420. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129421. 3.5, 4.5,
  129422. };
  129423. static long _vq_quantmap__44c9_s_p7_1[] = {
  129424. 9, 7, 5, 3, 1, 0, 2, 4,
  129425. 6, 8, 10,
  129426. };
  129427. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  129428. _vq_quantthresh__44c9_s_p7_1,
  129429. _vq_quantmap__44c9_s_p7_1,
  129430. 11,
  129431. 11
  129432. };
  129433. static static_codebook _44c9_s_p7_1 = {
  129434. 2, 121,
  129435. _vq_lengthlist__44c9_s_p7_1,
  129436. 1, -531365888, 1611661312, 4, 0,
  129437. _vq_quantlist__44c9_s_p7_1,
  129438. NULL,
  129439. &_vq_auxt__44c9_s_p7_1,
  129440. NULL,
  129441. 0
  129442. };
  129443. static long _vq_quantlist__44c9_s_p8_0[] = {
  129444. 7,
  129445. 6,
  129446. 8,
  129447. 5,
  129448. 9,
  129449. 4,
  129450. 10,
  129451. 3,
  129452. 11,
  129453. 2,
  129454. 12,
  129455. 1,
  129456. 13,
  129457. 0,
  129458. 14,
  129459. };
  129460. static long _vq_lengthlist__44c9_s_p8_0[] = {
  129461. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  129462. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  129463. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  129464. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  129465. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  129466. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  129467. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  129468. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  129469. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  129470. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  129471. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  129472. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  129473. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  129474. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  129475. 14,
  129476. };
  129477. static float _vq_quantthresh__44c9_s_p8_0[] = {
  129478. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  129479. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  129480. };
  129481. static long _vq_quantmap__44c9_s_p8_0[] = {
  129482. 13, 11, 9, 7, 5, 3, 1, 0,
  129483. 2, 4, 6, 8, 10, 12, 14,
  129484. };
  129485. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  129486. _vq_quantthresh__44c9_s_p8_0,
  129487. _vq_quantmap__44c9_s_p8_0,
  129488. 15,
  129489. 15
  129490. };
  129491. static static_codebook _44c9_s_p8_0 = {
  129492. 2, 225,
  129493. _vq_lengthlist__44c9_s_p8_0,
  129494. 1, -520986624, 1620377600, 4, 0,
  129495. _vq_quantlist__44c9_s_p8_0,
  129496. NULL,
  129497. &_vq_auxt__44c9_s_p8_0,
  129498. NULL,
  129499. 0
  129500. };
  129501. static long _vq_quantlist__44c9_s_p8_1[] = {
  129502. 10,
  129503. 9,
  129504. 11,
  129505. 8,
  129506. 12,
  129507. 7,
  129508. 13,
  129509. 6,
  129510. 14,
  129511. 5,
  129512. 15,
  129513. 4,
  129514. 16,
  129515. 3,
  129516. 17,
  129517. 2,
  129518. 18,
  129519. 1,
  129520. 19,
  129521. 0,
  129522. 20,
  129523. };
  129524. static long _vq_lengthlist__44c9_s_p8_1[] = {
  129525. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  129526. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  129527. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  129528. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  129529. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129530. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  129531. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  129532. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  129533. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129534. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129535. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  129536. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  129537. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129538. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129539. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  129540. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  129541. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  129542. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  129543. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  129544. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  129545. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  129546. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  129547. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  129548. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  129549. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  129550. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  129551. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  129552. 9, 9, 9,10, 9, 9, 9, 9, 9,
  129553. };
  129554. static float _vq_quantthresh__44c9_s_p8_1[] = {
  129555. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  129556. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  129557. 6.5, 7.5, 8.5, 9.5,
  129558. };
  129559. static long _vq_quantmap__44c9_s_p8_1[] = {
  129560. 19, 17, 15, 13, 11, 9, 7, 5,
  129561. 3, 1, 0, 2, 4, 6, 8, 10,
  129562. 12, 14, 16, 18, 20,
  129563. };
  129564. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  129565. _vq_quantthresh__44c9_s_p8_1,
  129566. _vq_quantmap__44c9_s_p8_1,
  129567. 21,
  129568. 21
  129569. };
  129570. static static_codebook _44c9_s_p8_1 = {
  129571. 2, 441,
  129572. _vq_lengthlist__44c9_s_p8_1,
  129573. 1, -529268736, 1611661312, 5, 0,
  129574. _vq_quantlist__44c9_s_p8_1,
  129575. NULL,
  129576. &_vq_auxt__44c9_s_p8_1,
  129577. NULL,
  129578. 0
  129579. };
  129580. static long _vq_quantlist__44c9_s_p9_0[] = {
  129581. 9,
  129582. 8,
  129583. 10,
  129584. 7,
  129585. 11,
  129586. 6,
  129587. 12,
  129588. 5,
  129589. 13,
  129590. 4,
  129591. 14,
  129592. 3,
  129593. 15,
  129594. 2,
  129595. 16,
  129596. 1,
  129597. 17,
  129598. 0,
  129599. 18,
  129600. };
  129601. static long _vq_lengthlist__44c9_s_p9_0[] = {
  129602. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129603. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  129604. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  129605. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  129606. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129607. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129608. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129609. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129610. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129611. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129612. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129613. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129614. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129615. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129616. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129617. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129618. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129619. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129620. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129621. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129622. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129623. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129624. 11,11,11,11,11,11,11,11,11,
  129625. };
  129626. static float _vq_quantthresh__44c9_s_p9_0[] = {
  129627. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  129628. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  129629. 6982.5, 7913.5,
  129630. };
  129631. static long _vq_quantmap__44c9_s_p9_0[] = {
  129632. 17, 15, 13, 11, 9, 7, 5, 3,
  129633. 1, 0, 2, 4, 6, 8, 10, 12,
  129634. 14, 16, 18,
  129635. };
  129636. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  129637. _vq_quantthresh__44c9_s_p9_0,
  129638. _vq_quantmap__44c9_s_p9_0,
  129639. 19,
  129640. 19
  129641. };
  129642. static static_codebook _44c9_s_p9_0 = {
  129643. 2, 361,
  129644. _vq_lengthlist__44c9_s_p9_0,
  129645. 1, -508535424, 1631393792, 5, 0,
  129646. _vq_quantlist__44c9_s_p9_0,
  129647. NULL,
  129648. &_vq_auxt__44c9_s_p9_0,
  129649. NULL,
  129650. 0
  129651. };
  129652. static long _vq_quantlist__44c9_s_p9_1[] = {
  129653. 9,
  129654. 8,
  129655. 10,
  129656. 7,
  129657. 11,
  129658. 6,
  129659. 12,
  129660. 5,
  129661. 13,
  129662. 4,
  129663. 14,
  129664. 3,
  129665. 15,
  129666. 2,
  129667. 16,
  129668. 1,
  129669. 17,
  129670. 0,
  129671. 18,
  129672. };
  129673. static long _vq_lengthlist__44c9_s_p9_1[] = {
  129674. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  129675. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  129676. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  129677. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  129678. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  129679. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  129680. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  129681. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  129682. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  129683. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  129684. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  129685. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  129686. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  129687. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  129688. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  129689. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  129690. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  129691. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  129692. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  129693. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  129694. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  129695. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  129696. 13,13,13,14,13,14,15,15,15,
  129697. };
  129698. static float _vq_quantthresh__44c9_s_p9_1[] = {
  129699. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  129700. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  129701. 367.5, 416.5,
  129702. };
  129703. static long _vq_quantmap__44c9_s_p9_1[] = {
  129704. 17, 15, 13, 11, 9, 7, 5, 3,
  129705. 1, 0, 2, 4, 6, 8, 10, 12,
  129706. 14, 16, 18,
  129707. };
  129708. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  129709. _vq_quantthresh__44c9_s_p9_1,
  129710. _vq_quantmap__44c9_s_p9_1,
  129711. 19,
  129712. 19
  129713. };
  129714. static static_codebook _44c9_s_p9_1 = {
  129715. 2, 361,
  129716. _vq_lengthlist__44c9_s_p9_1,
  129717. 1, -518287360, 1622704128, 5, 0,
  129718. _vq_quantlist__44c9_s_p9_1,
  129719. NULL,
  129720. &_vq_auxt__44c9_s_p9_1,
  129721. NULL,
  129722. 0
  129723. };
  129724. static long _vq_quantlist__44c9_s_p9_2[] = {
  129725. 24,
  129726. 23,
  129727. 25,
  129728. 22,
  129729. 26,
  129730. 21,
  129731. 27,
  129732. 20,
  129733. 28,
  129734. 19,
  129735. 29,
  129736. 18,
  129737. 30,
  129738. 17,
  129739. 31,
  129740. 16,
  129741. 32,
  129742. 15,
  129743. 33,
  129744. 14,
  129745. 34,
  129746. 13,
  129747. 35,
  129748. 12,
  129749. 36,
  129750. 11,
  129751. 37,
  129752. 10,
  129753. 38,
  129754. 9,
  129755. 39,
  129756. 8,
  129757. 40,
  129758. 7,
  129759. 41,
  129760. 6,
  129761. 42,
  129762. 5,
  129763. 43,
  129764. 4,
  129765. 44,
  129766. 3,
  129767. 45,
  129768. 2,
  129769. 46,
  129770. 1,
  129771. 47,
  129772. 0,
  129773. 48,
  129774. };
  129775. static long _vq_lengthlist__44c9_s_p9_2[] = {
  129776. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  129777. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  129778. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129779. 7,
  129780. };
  129781. static float _vq_quantthresh__44c9_s_p9_2[] = {
  129782. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  129783. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  129784. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129785. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129786. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  129787. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  129788. };
  129789. static long _vq_quantmap__44c9_s_p9_2[] = {
  129790. 47, 45, 43, 41, 39, 37, 35, 33,
  129791. 31, 29, 27, 25, 23, 21, 19, 17,
  129792. 15, 13, 11, 9, 7, 5, 3, 1,
  129793. 0, 2, 4, 6, 8, 10, 12, 14,
  129794. 16, 18, 20, 22, 24, 26, 28, 30,
  129795. 32, 34, 36, 38, 40, 42, 44, 46,
  129796. 48,
  129797. };
  129798. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  129799. _vq_quantthresh__44c9_s_p9_2,
  129800. _vq_quantmap__44c9_s_p9_2,
  129801. 49,
  129802. 49
  129803. };
  129804. static static_codebook _44c9_s_p9_2 = {
  129805. 1, 49,
  129806. _vq_lengthlist__44c9_s_p9_2,
  129807. 1, -526909440, 1611661312, 6, 0,
  129808. _vq_quantlist__44c9_s_p9_2,
  129809. NULL,
  129810. &_vq_auxt__44c9_s_p9_2,
  129811. NULL,
  129812. 0
  129813. };
  129814. static long _huff_lengthlist__44c9_s_short[] = {
  129815. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  129816. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  129817. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  129818. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  129819. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  129820. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  129821. 9, 8,10,13,
  129822. };
  129823. static static_codebook _huff_book__44c9_s_short = {
  129824. 2, 100,
  129825. _huff_lengthlist__44c9_s_short,
  129826. 0, 0, 0, 0, 0,
  129827. NULL,
  129828. NULL,
  129829. NULL,
  129830. NULL,
  129831. 0
  129832. };
  129833. static long _huff_lengthlist__44c0_s_long[] = {
  129834. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  129835. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  129836. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  129837. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  129838. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  129839. 12,
  129840. };
  129841. static static_codebook _huff_book__44c0_s_long = {
  129842. 2, 81,
  129843. _huff_lengthlist__44c0_s_long,
  129844. 0, 0, 0, 0, 0,
  129845. NULL,
  129846. NULL,
  129847. NULL,
  129848. NULL,
  129849. 0
  129850. };
  129851. static long _vq_quantlist__44c0_s_p1_0[] = {
  129852. 1,
  129853. 0,
  129854. 2,
  129855. };
  129856. static long _vq_lengthlist__44c0_s_p1_0[] = {
  129857. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129858. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129862. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  129863. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129867. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  129868. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129903. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  129904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  129908. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  129909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  129913. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  129914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129948. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  129949. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129953. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  129954. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  129955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129958. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  129959. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  129960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130267. 0,
  130268. };
  130269. static float _vq_quantthresh__44c0_s_p1_0[] = {
  130270. -0.5, 0.5,
  130271. };
  130272. static long _vq_quantmap__44c0_s_p1_0[] = {
  130273. 1, 0, 2,
  130274. };
  130275. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  130276. _vq_quantthresh__44c0_s_p1_0,
  130277. _vq_quantmap__44c0_s_p1_0,
  130278. 3,
  130279. 3
  130280. };
  130281. static static_codebook _44c0_s_p1_0 = {
  130282. 8, 6561,
  130283. _vq_lengthlist__44c0_s_p1_0,
  130284. 1, -535822336, 1611661312, 2, 0,
  130285. _vq_quantlist__44c0_s_p1_0,
  130286. NULL,
  130287. &_vq_auxt__44c0_s_p1_0,
  130288. NULL,
  130289. 0
  130290. };
  130291. static long _vq_quantlist__44c0_s_p2_0[] = {
  130292. 2,
  130293. 1,
  130294. 3,
  130295. 0,
  130296. 4,
  130297. };
  130298. static long _vq_lengthlist__44c0_s_p2_0[] = {
  130299. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  130304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130305. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130338. 0,
  130339. };
  130340. static float _vq_quantthresh__44c0_s_p2_0[] = {
  130341. -1.5, -0.5, 0.5, 1.5,
  130342. };
  130343. static long _vq_quantmap__44c0_s_p2_0[] = {
  130344. 3, 1, 0, 2, 4,
  130345. };
  130346. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  130347. _vq_quantthresh__44c0_s_p2_0,
  130348. _vq_quantmap__44c0_s_p2_0,
  130349. 5,
  130350. 5
  130351. };
  130352. static static_codebook _44c0_s_p2_0 = {
  130353. 4, 625,
  130354. _vq_lengthlist__44c0_s_p2_0,
  130355. 1, -533725184, 1611661312, 3, 0,
  130356. _vq_quantlist__44c0_s_p2_0,
  130357. NULL,
  130358. &_vq_auxt__44c0_s_p2_0,
  130359. NULL,
  130360. 0
  130361. };
  130362. static long _vq_quantlist__44c0_s_p3_0[] = {
  130363. 4,
  130364. 3,
  130365. 5,
  130366. 2,
  130367. 6,
  130368. 1,
  130369. 7,
  130370. 0,
  130371. 8,
  130372. };
  130373. static long _vq_lengthlist__44c0_s_p3_0[] = {
  130374. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  130375. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  130376. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  130377. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  130378. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130379. 0,
  130380. };
  130381. static float _vq_quantthresh__44c0_s_p3_0[] = {
  130382. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130383. };
  130384. static long _vq_quantmap__44c0_s_p3_0[] = {
  130385. 7, 5, 3, 1, 0, 2, 4, 6,
  130386. 8,
  130387. };
  130388. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  130389. _vq_quantthresh__44c0_s_p3_0,
  130390. _vq_quantmap__44c0_s_p3_0,
  130391. 9,
  130392. 9
  130393. };
  130394. static static_codebook _44c0_s_p3_0 = {
  130395. 2, 81,
  130396. _vq_lengthlist__44c0_s_p3_0,
  130397. 1, -531628032, 1611661312, 4, 0,
  130398. _vq_quantlist__44c0_s_p3_0,
  130399. NULL,
  130400. &_vq_auxt__44c0_s_p3_0,
  130401. NULL,
  130402. 0
  130403. };
  130404. static long _vq_quantlist__44c0_s_p4_0[] = {
  130405. 4,
  130406. 3,
  130407. 5,
  130408. 2,
  130409. 6,
  130410. 1,
  130411. 7,
  130412. 0,
  130413. 8,
  130414. };
  130415. static long _vq_lengthlist__44c0_s_p4_0[] = {
  130416. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  130417. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  130418. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  130419. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  130420. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  130421. 10,
  130422. };
  130423. static float _vq_quantthresh__44c0_s_p4_0[] = {
  130424. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130425. };
  130426. static long _vq_quantmap__44c0_s_p4_0[] = {
  130427. 7, 5, 3, 1, 0, 2, 4, 6,
  130428. 8,
  130429. };
  130430. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  130431. _vq_quantthresh__44c0_s_p4_0,
  130432. _vq_quantmap__44c0_s_p4_0,
  130433. 9,
  130434. 9
  130435. };
  130436. static static_codebook _44c0_s_p4_0 = {
  130437. 2, 81,
  130438. _vq_lengthlist__44c0_s_p4_0,
  130439. 1, -531628032, 1611661312, 4, 0,
  130440. _vq_quantlist__44c0_s_p4_0,
  130441. NULL,
  130442. &_vq_auxt__44c0_s_p4_0,
  130443. NULL,
  130444. 0
  130445. };
  130446. static long _vq_quantlist__44c0_s_p5_0[] = {
  130447. 8,
  130448. 7,
  130449. 9,
  130450. 6,
  130451. 10,
  130452. 5,
  130453. 11,
  130454. 4,
  130455. 12,
  130456. 3,
  130457. 13,
  130458. 2,
  130459. 14,
  130460. 1,
  130461. 15,
  130462. 0,
  130463. 16,
  130464. };
  130465. static long _vq_lengthlist__44c0_s_p5_0[] = {
  130466. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  130467. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  130468. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  130469. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130470. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130471. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  130472. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  130473. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130474. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130475. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130476. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  130477. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  130478. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  130479. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  130480. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  130481. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  130482. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  130483. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  130484. 14,
  130485. };
  130486. static float _vq_quantthresh__44c0_s_p5_0[] = {
  130487. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130488. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130489. };
  130490. static long _vq_quantmap__44c0_s_p5_0[] = {
  130491. 15, 13, 11, 9, 7, 5, 3, 1,
  130492. 0, 2, 4, 6, 8, 10, 12, 14,
  130493. 16,
  130494. };
  130495. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  130496. _vq_quantthresh__44c0_s_p5_0,
  130497. _vq_quantmap__44c0_s_p5_0,
  130498. 17,
  130499. 17
  130500. };
  130501. static static_codebook _44c0_s_p5_0 = {
  130502. 2, 289,
  130503. _vq_lengthlist__44c0_s_p5_0,
  130504. 1, -529530880, 1611661312, 5, 0,
  130505. _vq_quantlist__44c0_s_p5_0,
  130506. NULL,
  130507. &_vq_auxt__44c0_s_p5_0,
  130508. NULL,
  130509. 0
  130510. };
  130511. static long _vq_quantlist__44c0_s_p6_0[] = {
  130512. 1,
  130513. 0,
  130514. 2,
  130515. };
  130516. static long _vq_lengthlist__44c0_s_p6_0[] = {
  130517. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  130518. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130519. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  130520. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  130521. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  130522. 10,
  130523. };
  130524. static float _vq_quantthresh__44c0_s_p6_0[] = {
  130525. -5.5, 5.5,
  130526. };
  130527. static long _vq_quantmap__44c0_s_p6_0[] = {
  130528. 1, 0, 2,
  130529. };
  130530. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  130531. _vq_quantthresh__44c0_s_p6_0,
  130532. _vq_quantmap__44c0_s_p6_0,
  130533. 3,
  130534. 3
  130535. };
  130536. static static_codebook _44c0_s_p6_0 = {
  130537. 4, 81,
  130538. _vq_lengthlist__44c0_s_p6_0,
  130539. 1, -529137664, 1618345984, 2, 0,
  130540. _vq_quantlist__44c0_s_p6_0,
  130541. NULL,
  130542. &_vq_auxt__44c0_s_p6_0,
  130543. NULL,
  130544. 0
  130545. };
  130546. static long _vq_quantlist__44c0_s_p6_1[] = {
  130547. 5,
  130548. 4,
  130549. 6,
  130550. 3,
  130551. 7,
  130552. 2,
  130553. 8,
  130554. 1,
  130555. 9,
  130556. 0,
  130557. 10,
  130558. };
  130559. static long _vq_lengthlist__44c0_s_p6_1[] = {
  130560. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  130561. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  130562. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  130563. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130564. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130565. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130566. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  130567. 10,10,10, 8, 8, 8, 8, 8, 8,
  130568. };
  130569. static float _vq_quantthresh__44c0_s_p6_1[] = {
  130570. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130571. 3.5, 4.5,
  130572. };
  130573. static long _vq_quantmap__44c0_s_p6_1[] = {
  130574. 9, 7, 5, 3, 1, 0, 2, 4,
  130575. 6, 8, 10,
  130576. };
  130577. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  130578. _vq_quantthresh__44c0_s_p6_1,
  130579. _vq_quantmap__44c0_s_p6_1,
  130580. 11,
  130581. 11
  130582. };
  130583. static static_codebook _44c0_s_p6_1 = {
  130584. 2, 121,
  130585. _vq_lengthlist__44c0_s_p6_1,
  130586. 1, -531365888, 1611661312, 4, 0,
  130587. _vq_quantlist__44c0_s_p6_1,
  130588. NULL,
  130589. &_vq_auxt__44c0_s_p6_1,
  130590. NULL,
  130591. 0
  130592. };
  130593. static long _vq_quantlist__44c0_s_p7_0[] = {
  130594. 6,
  130595. 5,
  130596. 7,
  130597. 4,
  130598. 8,
  130599. 3,
  130600. 9,
  130601. 2,
  130602. 10,
  130603. 1,
  130604. 11,
  130605. 0,
  130606. 12,
  130607. };
  130608. static long _vq_lengthlist__44c0_s_p7_0[] = {
  130609. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  130610. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  130611. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130612. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130613. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  130614. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130615. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  130616. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  130617. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  130618. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  130619. 0,12,12,11,11,12,12,13,13,
  130620. };
  130621. static float _vq_quantthresh__44c0_s_p7_0[] = {
  130622. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130623. 12.5, 17.5, 22.5, 27.5,
  130624. };
  130625. static long _vq_quantmap__44c0_s_p7_0[] = {
  130626. 11, 9, 7, 5, 3, 1, 0, 2,
  130627. 4, 6, 8, 10, 12,
  130628. };
  130629. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  130630. _vq_quantthresh__44c0_s_p7_0,
  130631. _vq_quantmap__44c0_s_p7_0,
  130632. 13,
  130633. 13
  130634. };
  130635. static static_codebook _44c0_s_p7_0 = {
  130636. 2, 169,
  130637. _vq_lengthlist__44c0_s_p7_0,
  130638. 1, -526516224, 1616117760, 4, 0,
  130639. _vq_quantlist__44c0_s_p7_0,
  130640. NULL,
  130641. &_vq_auxt__44c0_s_p7_0,
  130642. NULL,
  130643. 0
  130644. };
  130645. static long _vq_quantlist__44c0_s_p7_1[] = {
  130646. 2,
  130647. 1,
  130648. 3,
  130649. 0,
  130650. 4,
  130651. };
  130652. static long _vq_lengthlist__44c0_s_p7_1[] = {
  130653. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  130654. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  130655. };
  130656. static float _vq_quantthresh__44c0_s_p7_1[] = {
  130657. -1.5, -0.5, 0.5, 1.5,
  130658. };
  130659. static long _vq_quantmap__44c0_s_p7_1[] = {
  130660. 3, 1, 0, 2, 4,
  130661. };
  130662. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  130663. _vq_quantthresh__44c0_s_p7_1,
  130664. _vq_quantmap__44c0_s_p7_1,
  130665. 5,
  130666. 5
  130667. };
  130668. static static_codebook _44c0_s_p7_1 = {
  130669. 2, 25,
  130670. _vq_lengthlist__44c0_s_p7_1,
  130671. 1, -533725184, 1611661312, 3, 0,
  130672. _vq_quantlist__44c0_s_p7_1,
  130673. NULL,
  130674. &_vq_auxt__44c0_s_p7_1,
  130675. NULL,
  130676. 0
  130677. };
  130678. static long _vq_quantlist__44c0_s_p8_0[] = {
  130679. 2,
  130680. 1,
  130681. 3,
  130682. 0,
  130683. 4,
  130684. };
  130685. static long _vq_lengthlist__44c0_s_p8_0[] = {
  130686. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  130687. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130688. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130689. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130690. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130691. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130692. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130693. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  130694. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130695. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130696. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130697. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130698. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  130699. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130700. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130701. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  130702. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130703. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130704. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130705. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130706. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130707. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130708. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130709. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130710. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130711. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130712. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130713. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130714. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130715. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130716. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130717. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130718. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130719. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130720. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130721. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130722. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130723. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130724. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130725. 11,
  130726. };
  130727. static float _vq_quantthresh__44c0_s_p8_0[] = {
  130728. -331.5, -110.5, 110.5, 331.5,
  130729. };
  130730. static long _vq_quantmap__44c0_s_p8_0[] = {
  130731. 3, 1, 0, 2, 4,
  130732. };
  130733. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  130734. _vq_quantthresh__44c0_s_p8_0,
  130735. _vq_quantmap__44c0_s_p8_0,
  130736. 5,
  130737. 5
  130738. };
  130739. static static_codebook _44c0_s_p8_0 = {
  130740. 4, 625,
  130741. _vq_lengthlist__44c0_s_p8_0,
  130742. 1, -518283264, 1627103232, 3, 0,
  130743. _vq_quantlist__44c0_s_p8_0,
  130744. NULL,
  130745. &_vq_auxt__44c0_s_p8_0,
  130746. NULL,
  130747. 0
  130748. };
  130749. static long _vq_quantlist__44c0_s_p8_1[] = {
  130750. 6,
  130751. 5,
  130752. 7,
  130753. 4,
  130754. 8,
  130755. 3,
  130756. 9,
  130757. 2,
  130758. 10,
  130759. 1,
  130760. 11,
  130761. 0,
  130762. 12,
  130763. };
  130764. static long _vq_lengthlist__44c0_s_p8_1[] = {
  130765. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  130766. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  130767. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  130768. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  130769. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  130770. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  130771. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  130772. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  130773. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  130774. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  130775. 16,13,13,12,12,14,14,15,13,
  130776. };
  130777. static float _vq_quantthresh__44c0_s_p8_1[] = {
  130778. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  130779. 42.5, 59.5, 76.5, 93.5,
  130780. };
  130781. static long _vq_quantmap__44c0_s_p8_1[] = {
  130782. 11, 9, 7, 5, 3, 1, 0, 2,
  130783. 4, 6, 8, 10, 12,
  130784. };
  130785. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  130786. _vq_quantthresh__44c0_s_p8_1,
  130787. _vq_quantmap__44c0_s_p8_1,
  130788. 13,
  130789. 13
  130790. };
  130791. static static_codebook _44c0_s_p8_1 = {
  130792. 2, 169,
  130793. _vq_lengthlist__44c0_s_p8_1,
  130794. 1, -522616832, 1620115456, 4, 0,
  130795. _vq_quantlist__44c0_s_p8_1,
  130796. NULL,
  130797. &_vq_auxt__44c0_s_p8_1,
  130798. NULL,
  130799. 0
  130800. };
  130801. static long _vq_quantlist__44c0_s_p8_2[] = {
  130802. 8,
  130803. 7,
  130804. 9,
  130805. 6,
  130806. 10,
  130807. 5,
  130808. 11,
  130809. 4,
  130810. 12,
  130811. 3,
  130812. 13,
  130813. 2,
  130814. 14,
  130815. 1,
  130816. 15,
  130817. 0,
  130818. 16,
  130819. };
  130820. static long _vq_lengthlist__44c0_s_p8_2[] = {
  130821. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130822. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  130823. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130824. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130825. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  130826. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  130827. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  130828. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  130829. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  130830. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  130831. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  130832. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  130833. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  130834. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130835. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  130836. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  130837. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  130838. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  130839. 10,
  130840. };
  130841. static float _vq_quantthresh__44c0_s_p8_2[] = {
  130842. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130843. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130844. };
  130845. static long _vq_quantmap__44c0_s_p8_2[] = {
  130846. 15, 13, 11, 9, 7, 5, 3, 1,
  130847. 0, 2, 4, 6, 8, 10, 12, 14,
  130848. 16,
  130849. };
  130850. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  130851. _vq_quantthresh__44c0_s_p8_2,
  130852. _vq_quantmap__44c0_s_p8_2,
  130853. 17,
  130854. 17
  130855. };
  130856. static static_codebook _44c0_s_p8_2 = {
  130857. 2, 289,
  130858. _vq_lengthlist__44c0_s_p8_2,
  130859. 1, -529530880, 1611661312, 5, 0,
  130860. _vq_quantlist__44c0_s_p8_2,
  130861. NULL,
  130862. &_vq_auxt__44c0_s_p8_2,
  130863. NULL,
  130864. 0
  130865. };
  130866. static long _huff_lengthlist__44c0_s_short[] = {
  130867. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  130868. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  130869. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  130870. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  130871. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  130872. 12,
  130873. };
  130874. static static_codebook _huff_book__44c0_s_short = {
  130875. 2, 81,
  130876. _huff_lengthlist__44c0_s_short,
  130877. 0, 0, 0, 0, 0,
  130878. NULL,
  130879. NULL,
  130880. NULL,
  130881. NULL,
  130882. 0
  130883. };
  130884. static long _huff_lengthlist__44c0_sm_long[] = {
  130885. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  130886. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  130887. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  130888. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  130889. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  130890. 13,
  130891. };
  130892. static static_codebook _huff_book__44c0_sm_long = {
  130893. 2, 81,
  130894. _huff_lengthlist__44c0_sm_long,
  130895. 0, 0, 0, 0, 0,
  130896. NULL,
  130897. NULL,
  130898. NULL,
  130899. NULL,
  130900. 0
  130901. };
  130902. static long _vq_quantlist__44c0_sm_p1_0[] = {
  130903. 1,
  130904. 0,
  130905. 2,
  130906. };
  130907. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  130908. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130909. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130913. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130914. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130918. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  130919. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  130954. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  130955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130959. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  130960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130964. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  130965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130999. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131000. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131004. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131005. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  131006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131009. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131010. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  131011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131318. 0,
  131319. };
  131320. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  131321. -0.5, 0.5,
  131322. };
  131323. static long _vq_quantmap__44c0_sm_p1_0[] = {
  131324. 1, 0, 2,
  131325. };
  131326. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  131327. _vq_quantthresh__44c0_sm_p1_0,
  131328. _vq_quantmap__44c0_sm_p1_0,
  131329. 3,
  131330. 3
  131331. };
  131332. static static_codebook _44c0_sm_p1_0 = {
  131333. 8, 6561,
  131334. _vq_lengthlist__44c0_sm_p1_0,
  131335. 1, -535822336, 1611661312, 2, 0,
  131336. _vq_quantlist__44c0_sm_p1_0,
  131337. NULL,
  131338. &_vq_auxt__44c0_sm_p1_0,
  131339. NULL,
  131340. 0
  131341. };
  131342. static long _vq_quantlist__44c0_sm_p2_0[] = {
  131343. 2,
  131344. 1,
  131345. 3,
  131346. 0,
  131347. 4,
  131348. };
  131349. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  131350. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  131352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131353. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  131355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131356. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  131357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131389. 0,
  131390. };
  131391. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  131392. -1.5, -0.5, 0.5, 1.5,
  131393. };
  131394. static long _vq_quantmap__44c0_sm_p2_0[] = {
  131395. 3, 1, 0, 2, 4,
  131396. };
  131397. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  131398. _vq_quantthresh__44c0_sm_p2_0,
  131399. _vq_quantmap__44c0_sm_p2_0,
  131400. 5,
  131401. 5
  131402. };
  131403. static static_codebook _44c0_sm_p2_0 = {
  131404. 4, 625,
  131405. _vq_lengthlist__44c0_sm_p2_0,
  131406. 1, -533725184, 1611661312, 3, 0,
  131407. _vq_quantlist__44c0_sm_p2_0,
  131408. NULL,
  131409. &_vq_auxt__44c0_sm_p2_0,
  131410. NULL,
  131411. 0
  131412. };
  131413. static long _vq_quantlist__44c0_sm_p3_0[] = {
  131414. 4,
  131415. 3,
  131416. 5,
  131417. 2,
  131418. 6,
  131419. 1,
  131420. 7,
  131421. 0,
  131422. 8,
  131423. };
  131424. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  131425. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  131426. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  131427. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131428. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  131429. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131430. 0,
  131431. };
  131432. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  131433. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131434. };
  131435. static long _vq_quantmap__44c0_sm_p3_0[] = {
  131436. 7, 5, 3, 1, 0, 2, 4, 6,
  131437. 8,
  131438. };
  131439. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  131440. _vq_quantthresh__44c0_sm_p3_0,
  131441. _vq_quantmap__44c0_sm_p3_0,
  131442. 9,
  131443. 9
  131444. };
  131445. static static_codebook _44c0_sm_p3_0 = {
  131446. 2, 81,
  131447. _vq_lengthlist__44c0_sm_p3_0,
  131448. 1, -531628032, 1611661312, 4, 0,
  131449. _vq_quantlist__44c0_sm_p3_0,
  131450. NULL,
  131451. &_vq_auxt__44c0_sm_p3_0,
  131452. NULL,
  131453. 0
  131454. };
  131455. static long _vq_quantlist__44c0_sm_p4_0[] = {
  131456. 4,
  131457. 3,
  131458. 5,
  131459. 2,
  131460. 6,
  131461. 1,
  131462. 7,
  131463. 0,
  131464. 8,
  131465. };
  131466. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  131467. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  131468. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  131469. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  131470. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  131471. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  131472. 11,
  131473. };
  131474. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  131475. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131476. };
  131477. static long _vq_quantmap__44c0_sm_p4_0[] = {
  131478. 7, 5, 3, 1, 0, 2, 4, 6,
  131479. 8,
  131480. };
  131481. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  131482. _vq_quantthresh__44c0_sm_p4_0,
  131483. _vq_quantmap__44c0_sm_p4_0,
  131484. 9,
  131485. 9
  131486. };
  131487. static static_codebook _44c0_sm_p4_0 = {
  131488. 2, 81,
  131489. _vq_lengthlist__44c0_sm_p4_0,
  131490. 1, -531628032, 1611661312, 4, 0,
  131491. _vq_quantlist__44c0_sm_p4_0,
  131492. NULL,
  131493. &_vq_auxt__44c0_sm_p4_0,
  131494. NULL,
  131495. 0
  131496. };
  131497. static long _vq_quantlist__44c0_sm_p5_0[] = {
  131498. 8,
  131499. 7,
  131500. 9,
  131501. 6,
  131502. 10,
  131503. 5,
  131504. 11,
  131505. 4,
  131506. 12,
  131507. 3,
  131508. 13,
  131509. 2,
  131510. 14,
  131511. 1,
  131512. 15,
  131513. 0,
  131514. 16,
  131515. };
  131516. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  131517. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  131518. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  131519. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  131520. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  131521. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  131522. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  131523. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  131524. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  131525. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  131526. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  131527. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  131528. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  131529. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  131530. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  131531. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  131532. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  131533. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  131534. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  131535. 14,
  131536. };
  131537. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  131538. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131539. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131540. };
  131541. static long _vq_quantmap__44c0_sm_p5_0[] = {
  131542. 15, 13, 11, 9, 7, 5, 3, 1,
  131543. 0, 2, 4, 6, 8, 10, 12, 14,
  131544. 16,
  131545. };
  131546. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  131547. _vq_quantthresh__44c0_sm_p5_0,
  131548. _vq_quantmap__44c0_sm_p5_0,
  131549. 17,
  131550. 17
  131551. };
  131552. static static_codebook _44c0_sm_p5_0 = {
  131553. 2, 289,
  131554. _vq_lengthlist__44c0_sm_p5_0,
  131555. 1, -529530880, 1611661312, 5, 0,
  131556. _vq_quantlist__44c0_sm_p5_0,
  131557. NULL,
  131558. &_vq_auxt__44c0_sm_p5_0,
  131559. NULL,
  131560. 0
  131561. };
  131562. static long _vq_quantlist__44c0_sm_p6_0[] = {
  131563. 1,
  131564. 0,
  131565. 2,
  131566. };
  131567. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  131568. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131569. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  131570. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  131571. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  131572. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  131573. 11,
  131574. };
  131575. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  131576. -5.5, 5.5,
  131577. };
  131578. static long _vq_quantmap__44c0_sm_p6_0[] = {
  131579. 1, 0, 2,
  131580. };
  131581. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  131582. _vq_quantthresh__44c0_sm_p6_0,
  131583. _vq_quantmap__44c0_sm_p6_0,
  131584. 3,
  131585. 3
  131586. };
  131587. static static_codebook _44c0_sm_p6_0 = {
  131588. 4, 81,
  131589. _vq_lengthlist__44c0_sm_p6_0,
  131590. 1, -529137664, 1618345984, 2, 0,
  131591. _vq_quantlist__44c0_sm_p6_0,
  131592. NULL,
  131593. &_vq_auxt__44c0_sm_p6_0,
  131594. NULL,
  131595. 0
  131596. };
  131597. static long _vq_quantlist__44c0_sm_p6_1[] = {
  131598. 5,
  131599. 4,
  131600. 6,
  131601. 3,
  131602. 7,
  131603. 2,
  131604. 8,
  131605. 1,
  131606. 9,
  131607. 0,
  131608. 10,
  131609. };
  131610. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  131611. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  131612. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131613. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  131614. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  131615. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  131616. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  131617. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131618. 10,10,10, 8, 8, 8, 8, 8, 8,
  131619. };
  131620. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  131621. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131622. 3.5, 4.5,
  131623. };
  131624. static long _vq_quantmap__44c0_sm_p6_1[] = {
  131625. 9, 7, 5, 3, 1, 0, 2, 4,
  131626. 6, 8, 10,
  131627. };
  131628. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  131629. _vq_quantthresh__44c0_sm_p6_1,
  131630. _vq_quantmap__44c0_sm_p6_1,
  131631. 11,
  131632. 11
  131633. };
  131634. static static_codebook _44c0_sm_p6_1 = {
  131635. 2, 121,
  131636. _vq_lengthlist__44c0_sm_p6_1,
  131637. 1, -531365888, 1611661312, 4, 0,
  131638. _vq_quantlist__44c0_sm_p6_1,
  131639. NULL,
  131640. &_vq_auxt__44c0_sm_p6_1,
  131641. NULL,
  131642. 0
  131643. };
  131644. static long _vq_quantlist__44c0_sm_p7_0[] = {
  131645. 6,
  131646. 5,
  131647. 7,
  131648. 4,
  131649. 8,
  131650. 3,
  131651. 9,
  131652. 2,
  131653. 10,
  131654. 1,
  131655. 11,
  131656. 0,
  131657. 12,
  131658. };
  131659. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  131660. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  131661. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  131662. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131663. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131664. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  131665. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  131666. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  131667. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  131668. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  131669. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  131670. 0,12,12,11,11,13,12,14,14,
  131671. };
  131672. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  131673. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131674. 12.5, 17.5, 22.5, 27.5,
  131675. };
  131676. static long _vq_quantmap__44c0_sm_p7_0[] = {
  131677. 11, 9, 7, 5, 3, 1, 0, 2,
  131678. 4, 6, 8, 10, 12,
  131679. };
  131680. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  131681. _vq_quantthresh__44c0_sm_p7_0,
  131682. _vq_quantmap__44c0_sm_p7_0,
  131683. 13,
  131684. 13
  131685. };
  131686. static static_codebook _44c0_sm_p7_0 = {
  131687. 2, 169,
  131688. _vq_lengthlist__44c0_sm_p7_0,
  131689. 1, -526516224, 1616117760, 4, 0,
  131690. _vq_quantlist__44c0_sm_p7_0,
  131691. NULL,
  131692. &_vq_auxt__44c0_sm_p7_0,
  131693. NULL,
  131694. 0
  131695. };
  131696. static long _vq_quantlist__44c0_sm_p7_1[] = {
  131697. 2,
  131698. 1,
  131699. 3,
  131700. 0,
  131701. 4,
  131702. };
  131703. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  131704. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  131705. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  131706. };
  131707. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  131708. -1.5, -0.5, 0.5, 1.5,
  131709. };
  131710. static long _vq_quantmap__44c0_sm_p7_1[] = {
  131711. 3, 1, 0, 2, 4,
  131712. };
  131713. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  131714. _vq_quantthresh__44c0_sm_p7_1,
  131715. _vq_quantmap__44c0_sm_p7_1,
  131716. 5,
  131717. 5
  131718. };
  131719. static static_codebook _44c0_sm_p7_1 = {
  131720. 2, 25,
  131721. _vq_lengthlist__44c0_sm_p7_1,
  131722. 1, -533725184, 1611661312, 3, 0,
  131723. _vq_quantlist__44c0_sm_p7_1,
  131724. NULL,
  131725. &_vq_auxt__44c0_sm_p7_1,
  131726. NULL,
  131727. 0
  131728. };
  131729. static long _vq_quantlist__44c0_sm_p8_0[] = {
  131730. 4,
  131731. 3,
  131732. 5,
  131733. 2,
  131734. 6,
  131735. 1,
  131736. 7,
  131737. 0,
  131738. 8,
  131739. };
  131740. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  131741. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  131742. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  131743. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131744. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131745. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131746. 12,
  131747. };
  131748. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  131749. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  131750. };
  131751. static long _vq_quantmap__44c0_sm_p8_0[] = {
  131752. 7, 5, 3, 1, 0, 2, 4, 6,
  131753. 8,
  131754. };
  131755. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  131756. _vq_quantthresh__44c0_sm_p8_0,
  131757. _vq_quantmap__44c0_sm_p8_0,
  131758. 9,
  131759. 9
  131760. };
  131761. static static_codebook _44c0_sm_p8_0 = {
  131762. 2, 81,
  131763. _vq_lengthlist__44c0_sm_p8_0,
  131764. 1, -516186112, 1627103232, 4, 0,
  131765. _vq_quantlist__44c0_sm_p8_0,
  131766. NULL,
  131767. &_vq_auxt__44c0_sm_p8_0,
  131768. NULL,
  131769. 0
  131770. };
  131771. static long _vq_quantlist__44c0_sm_p8_1[] = {
  131772. 6,
  131773. 5,
  131774. 7,
  131775. 4,
  131776. 8,
  131777. 3,
  131778. 9,
  131779. 2,
  131780. 10,
  131781. 1,
  131782. 11,
  131783. 0,
  131784. 12,
  131785. };
  131786. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  131787. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  131788. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  131789. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  131790. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  131791. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  131792. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  131793. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  131794. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  131795. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  131796. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  131797. 20,13,13,12,12,16,13,15,13,
  131798. };
  131799. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  131800. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  131801. 42.5, 59.5, 76.5, 93.5,
  131802. };
  131803. static long _vq_quantmap__44c0_sm_p8_1[] = {
  131804. 11, 9, 7, 5, 3, 1, 0, 2,
  131805. 4, 6, 8, 10, 12,
  131806. };
  131807. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  131808. _vq_quantthresh__44c0_sm_p8_1,
  131809. _vq_quantmap__44c0_sm_p8_1,
  131810. 13,
  131811. 13
  131812. };
  131813. static static_codebook _44c0_sm_p8_1 = {
  131814. 2, 169,
  131815. _vq_lengthlist__44c0_sm_p8_1,
  131816. 1, -522616832, 1620115456, 4, 0,
  131817. _vq_quantlist__44c0_sm_p8_1,
  131818. NULL,
  131819. &_vq_auxt__44c0_sm_p8_1,
  131820. NULL,
  131821. 0
  131822. };
  131823. static long _vq_quantlist__44c0_sm_p8_2[] = {
  131824. 8,
  131825. 7,
  131826. 9,
  131827. 6,
  131828. 10,
  131829. 5,
  131830. 11,
  131831. 4,
  131832. 12,
  131833. 3,
  131834. 13,
  131835. 2,
  131836. 14,
  131837. 1,
  131838. 15,
  131839. 0,
  131840. 16,
  131841. };
  131842. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  131843. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131844. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  131845. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  131846. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  131847. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  131848. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  131849. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  131850. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  131851. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  131852. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  131853. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  131854. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  131855. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  131856. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  131857. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  131858. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  131859. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  131860. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  131861. 9,
  131862. };
  131863. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  131864. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131865. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131866. };
  131867. static long _vq_quantmap__44c0_sm_p8_2[] = {
  131868. 15, 13, 11, 9, 7, 5, 3, 1,
  131869. 0, 2, 4, 6, 8, 10, 12, 14,
  131870. 16,
  131871. };
  131872. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  131873. _vq_quantthresh__44c0_sm_p8_2,
  131874. _vq_quantmap__44c0_sm_p8_2,
  131875. 17,
  131876. 17
  131877. };
  131878. static static_codebook _44c0_sm_p8_2 = {
  131879. 2, 289,
  131880. _vq_lengthlist__44c0_sm_p8_2,
  131881. 1, -529530880, 1611661312, 5, 0,
  131882. _vq_quantlist__44c0_sm_p8_2,
  131883. NULL,
  131884. &_vq_auxt__44c0_sm_p8_2,
  131885. NULL,
  131886. 0
  131887. };
  131888. static long _huff_lengthlist__44c0_sm_short[] = {
  131889. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  131890. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  131891. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  131892. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  131893. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  131894. 12,
  131895. };
  131896. static static_codebook _huff_book__44c0_sm_short = {
  131897. 2, 81,
  131898. _huff_lengthlist__44c0_sm_short,
  131899. 0, 0, 0, 0, 0,
  131900. NULL,
  131901. NULL,
  131902. NULL,
  131903. NULL,
  131904. 0
  131905. };
  131906. static long _huff_lengthlist__44c1_s_long[] = {
  131907. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  131908. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  131909. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  131910. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  131911. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  131912. 11,
  131913. };
  131914. static static_codebook _huff_book__44c1_s_long = {
  131915. 2, 81,
  131916. _huff_lengthlist__44c1_s_long,
  131917. 0, 0, 0, 0, 0,
  131918. NULL,
  131919. NULL,
  131920. NULL,
  131921. NULL,
  131922. 0
  131923. };
  131924. static long _vq_quantlist__44c1_s_p1_0[] = {
  131925. 1,
  131926. 0,
  131927. 2,
  131928. };
  131929. static long _vq_lengthlist__44c1_s_p1_0[] = {
  131930. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  131931. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131935. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  131936. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131940. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  131941. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131976. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  131977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  131981. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  131982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  131986. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  131987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132021. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  132022. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132026. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  132027. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  132028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132031. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  132032. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  132033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132340. 0,
  132341. };
  132342. static float _vq_quantthresh__44c1_s_p1_0[] = {
  132343. -0.5, 0.5,
  132344. };
  132345. static long _vq_quantmap__44c1_s_p1_0[] = {
  132346. 1, 0, 2,
  132347. };
  132348. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  132349. _vq_quantthresh__44c1_s_p1_0,
  132350. _vq_quantmap__44c1_s_p1_0,
  132351. 3,
  132352. 3
  132353. };
  132354. static static_codebook _44c1_s_p1_0 = {
  132355. 8, 6561,
  132356. _vq_lengthlist__44c1_s_p1_0,
  132357. 1, -535822336, 1611661312, 2, 0,
  132358. _vq_quantlist__44c1_s_p1_0,
  132359. NULL,
  132360. &_vq_auxt__44c1_s_p1_0,
  132361. NULL,
  132362. 0
  132363. };
  132364. static long _vq_quantlist__44c1_s_p2_0[] = {
  132365. 2,
  132366. 1,
  132367. 3,
  132368. 0,
  132369. 4,
  132370. };
  132371. static long _vq_lengthlist__44c1_s_p2_0[] = {
  132372. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  132374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132375. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  132377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132378. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  132379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132411. 0,
  132412. };
  132413. static float _vq_quantthresh__44c1_s_p2_0[] = {
  132414. -1.5, -0.5, 0.5, 1.5,
  132415. };
  132416. static long _vq_quantmap__44c1_s_p2_0[] = {
  132417. 3, 1, 0, 2, 4,
  132418. };
  132419. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  132420. _vq_quantthresh__44c1_s_p2_0,
  132421. _vq_quantmap__44c1_s_p2_0,
  132422. 5,
  132423. 5
  132424. };
  132425. static static_codebook _44c1_s_p2_0 = {
  132426. 4, 625,
  132427. _vq_lengthlist__44c1_s_p2_0,
  132428. 1, -533725184, 1611661312, 3, 0,
  132429. _vq_quantlist__44c1_s_p2_0,
  132430. NULL,
  132431. &_vq_auxt__44c1_s_p2_0,
  132432. NULL,
  132433. 0
  132434. };
  132435. static long _vq_quantlist__44c1_s_p3_0[] = {
  132436. 4,
  132437. 3,
  132438. 5,
  132439. 2,
  132440. 6,
  132441. 1,
  132442. 7,
  132443. 0,
  132444. 8,
  132445. };
  132446. static long _vq_lengthlist__44c1_s_p3_0[] = {
  132447. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  132448. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  132449. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  132450. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  132451. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132452. 0,
  132453. };
  132454. static float _vq_quantthresh__44c1_s_p3_0[] = {
  132455. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132456. };
  132457. static long _vq_quantmap__44c1_s_p3_0[] = {
  132458. 7, 5, 3, 1, 0, 2, 4, 6,
  132459. 8,
  132460. };
  132461. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  132462. _vq_quantthresh__44c1_s_p3_0,
  132463. _vq_quantmap__44c1_s_p3_0,
  132464. 9,
  132465. 9
  132466. };
  132467. static static_codebook _44c1_s_p3_0 = {
  132468. 2, 81,
  132469. _vq_lengthlist__44c1_s_p3_0,
  132470. 1, -531628032, 1611661312, 4, 0,
  132471. _vq_quantlist__44c1_s_p3_0,
  132472. NULL,
  132473. &_vq_auxt__44c1_s_p3_0,
  132474. NULL,
  132475. 0
  132476. };
  132477. static long _vq_quantlist__44c1_s_p4_0[] = {
  132478. 4,
  132479. 3,
  132480. 5,
  132481. 2,
  132482. 6,
  132483. 1,
  132484. 7,
  132485. 0,
  132486. 8,
  132487. };
  132488. static long _vq_lengthlist__44c1_s_p4_0[] = {
  132489. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  132490. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  132491. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  132492. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  132493. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  132494. 11,
  132495. };
  132496. static float _vq_quantthresh__44c1_s_p4_0[] = {
  132497. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132498. };
  132499. static long _vq_quantmap__44c1_s_p4_0[] = {
  132500. 7, 5, 3, 1, 0, 2, 4, 6,
  132501. 8,
  132502. };
  132503. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  132504. _vq_quantthresh__44c1_s_p4_0,
  132505. _vq_quantmap__44c1_s_p4_0,
  132506. 9,
  132507. 9
  132508. };
  132509. static static_codebook _44c1_s_p4_0 = {
  132510. 2, 81,
  132511. _vq_lengthlist__44c1_s_p4_0,
  132512. 1, -531628032, 1611661312, 4, 0,
  132513. _vq_quantlist__44c1_s_p4_0,
  132514. NULL,
  132515. &_vq_auxt__44c1_s_p4_0,
  132516. NULL,
  132517. 0
  132518. };
  132519. static long _vq_quantlist__44c1_s_p5_0[] = {
  132520. 8,
  132521. 7,
  132522. 9,
  132523. 6,
  132524. 10,
  132525. 5,
  132526. 11,
  132527. 4,
  132528. 12,
  132529. 3,
  132530. 13,
  132531. 2,
  132532. 14,
  132533. 1,
  132534. 15,
  132535. 0,
  132536. 16,
  132537. };
  132538. static long _vq_lengthlist__44c1_s_p5_0[] = {
  132539. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132540. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132541. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  132542. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132543. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132544. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  132545. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  132546. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  132547. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132548. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  132549. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  132550. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132551. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  132552. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  132553. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  132554. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  132555. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  132556. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  132557. 14,
  132558. };
  132559. static float _vq_quantthresh__44c1_s_p5_0[] = {
  132560. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132561. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132562. };
  132563. static long _vq_quantmap__44c1_s_p5_0[] = {
  132564. 15, 13, 11, 9, 7, 5, 3, 1,
  132565. 0, 2, 4, 6, 8, 10, 12, 14,
  132566. 16,
  132567. };
  132568. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  132569. _vq_quantthresh__44c1_s_p5_0,
  132570. _vq_quantmap__44c1_s_p5_0,
  132571. 17,
  132572. 17
  132573. };
  132574. static static_codebook _44c1_s_p5_0 = {
  132575. 2, 289,
  132576. _vq_lengthlist__44c1_s_p5_0,
  132577. 1, -529530880, 1611661312, 5, 0,
  132578. _vq_quantlist__44c1_s_p5_0,
  132579. NULL,
  132580. &_vq_auxt__44c1_s_p5_0,
  132581. NULL,
  132582. 0
  132583. };
  132584. static long _vq_quantlist__44c1_s_p6_0[] = {
  132585. 1,
  132586. 0,
  132587. 2,
  132588. };
  132589. static long _vq_lengthlist__44c1_s_p6_0[] = {
  132590. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132591. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  132592. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  132593. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  132594. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  132595. 11,
  132596. };
  132597. static float _vq_quantthresh__44c1_s_p6_0[] = {
  132598. -5.5, 5.5,
  132599. };
  132600. static long _vq_quantmap__44c1_s_p6_0[] = {
  132601. 1, 0, 2,
  132602. };
  132603. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  132604. _vq_quantthresh__44c1_s_p6_0,
  132605. _vq_quantmap__44c1_s_p6_0,
  132606. 3,
  132607. 3
  132608. };
  132609. static static_codebook _44c1_s_p6_0 = {
  132610. 4, 81,
  132611. _vq_lengthlist__44c1_s_p6_0,
  132612. 1, -529137664, 1618345984, 2, 0,
  132613. _vq_quantlist__44c1_s_p6_0,
  132614. NULL,
  132615. &_vq_auxt__44c1_s_p6_0,
  132616. NULL,
  132617. 0
  132618. };
  132619. static long _vq_quantlist__44c1_s_p6_1[] = {
  132620. 5,
  132621. 4,
  132622. 6,
  132623. 3,
  132624. 7,
  132625. 2,
  132626. 8,
  132627. 1,
  132628. 9,
  132629. 0,
  132630. 10,
  132631. };
  132632. static long _vq_lengthlist__44c1_s_p6_1[] = {
  132633. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  132634. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  132635. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  132636. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132637. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132638. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  132639. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132640. 10,10,10, 8, 8, 8, 8, 8, 8,
  132641. };
  132642. static float _vq_quantthresh__44c1_s_p6_1[] = {
  132643. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132644. 3.5, 4.5,
  132645. };
  132646. static long _vq_quantmap__44c1_s_p6_1[] = {
  132647. 9, 7, 5, 3, 1, 0, 2, 4,
  132648. 6, 8, 10,
  132649. };
  132650. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  132651. _vq_quantthresh__44c1_s_p6_1,
  132652. _vq_quantmap__44c1_s_p6_1,
  132653. 11,
  132654. 11
  132655. };
  132656. static static_codebook _44c1_s_p6_1 = {
  132657. 2, 121,
  132658. _vq_lengthlist__44c1_s_p6_1,
  132659. 1, -531365888, 1611661312, 4, 0,
  132660. _vq_quantlist__44c1_s_p6_1,
  132661. NULL,
  132662. &_vq_auxt__44c1_s_p6_1,
  132663. NULL,
  132664. 0
  132665. };
  132666. static long _vq_quantlist__44c1_s_p7_0[] = {
  132667. 6,
  132668. 5,
  132669. 7,
  132670. 4,
  132671. 8,
  132672. 3,
  132673. 9,
  132674. 2,
  132675. 10,
  132676. 1,
  132677. 11,
  132678. 0,
  132679. 12,
  132680. };
  132681. static long _vq_lengthlist__44c1_s_p7_0[] = {
  132682. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  132683. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  132684. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132685. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132686. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  132687. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132688. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  132689. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  132690. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  132691. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  132692. 0,12,11,11,11,13,10,14,13,
  132693. };
  132694. static float _vq_quantthresh__44c1_s_p7_0[] = {
  132695. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132696. 12.5, 17.5, 22.5, 27.5,
  132697. };
  132698. static long _vq_quantmap__44c1_s_p7_0[] = {
  132699. 11, 9, 7, 5, 3, 1, 0, 2,
  132700. 4, 6, 8, 10, 12,
  132701. };
  132702. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  132703. _vq_quantthresh__44c1_s_p7_0,
  132704. _vq_quantmap__44c1_s_p7_0,
  132705. 13,
  132706. 13
  132707. };
  132708. static static_codebook _44c1_s_p7_0 = {
  132709. 2, 169,
  132710. _vq_lengthlist__44c1_s_p7_0,
  132711. 1, -526516224, 1616117760, 4, 0,
  132712. _vq_quantlist__44c1_s_p7_0,
  132713. NULL,
  132714. &_vq_auxt__44c1_s_p7_0,
  132715. NULL,
  132716. 0
  132717. };
  132718. static long _vq_quantlist__44c1_s_p7_1[] = {
  132719. 2,
  132720. 1,
  132721. 3,
  132722. 0,
  132723. 4,
  132724. };
  132725. static long _vq_lengthlist__44c1_s_p7_1[] = {
  132726. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  132727. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  132728. };
  132729. static float _vq_quantthresh__44c1_s_p7_1[] = {
  132730. -1.5, -0.5, 0.5, 1.5,
  132731. };
  132732. static long _vq_quantmap__44c1_s_p7_1[] = {
  132733. 3, 1, 0, 2, 4,
  132734. };
  132735. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  132736. _vq_quantthresh__44c1_s_p7_1,
  132737. _vq_quantmap__44c1_s_p7_1,
  132738. 5,
  132739. 5
  132740. };
  132741. static static_codebook _44c1_s_p7_1 = {
  132742. 2, 25,
  132743. _vq_lengthlist__44c1_s_p7_1,
  132744. 1, -533725184, 1611661312, 3, 0,
  132745. _vq_quantlist__44c1_s_p7_1,
  132746. NULL,
  132747. &_vq_auxt__44c1_s_p7_1,
  132748. NULL,
  132749. 0
  132750. };
  132751. static long _vq_quantlist__44c1_s_p8_0[] = {
  132752. 6,
  132753. 5,
  132754. 7,
  132755. 4,
  132756. 8,
  132757. 3,
  132758. 9,
  132759. 2,
  132760. 10,
  132761. 1,
  132762. 11,
  132763. 0,
  132764. 12,
  132765. };
  132766. static long _vq_lengthlist__44c1_s_p8_0[] = {
  132767. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  132768. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  132769. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132770. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132771. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132772. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132773. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132774. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132775. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132776. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132777. 10,10,10,10,10,10,10,10,10,
  132778. };
  132779. static float _vq_quantthresh__44c1_s_p8_0[] = {
  132780. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  132781. 552.5, 773.5, 994.5, 1215.5,
  132782. };
  132783. static long _vq_quantmap__44c1_s_p8_0[] = {
  132784. 11, 9, 7, 5, 3, 1, 0, 2,
  132785. 4, 6, 8, 10, 12,
  132786. };
  132787. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  132788. _vq_quantthresh__44c1_s_p8_0,
  132789. _vq_quantmap__44c1_s_p8_0,
  132790. 13,
  132791. 13
  132792. };
  132793. static static_codebook _44c1_s_p8_0 = {
  132794. 2, 169,
  132795. _vq_lengthlist__44c1_s_p8_0,
  132796. 1, -514541568, 1627103232, 4, 0,
  132797. _vq_quantlist__44c1_s_p8_0,
  132798. NULL,
  132799. &_vq_auxt__44c1_s_p8_0,
  132800. NULL,
  132801. 0
  132802. };
  132803. static long _vq_quantlist__44c1_s_p8_1[] = {
  132804. 6,
  132805. 5,
  132806. 7,
  132807. 4,
  132808. 8,
  132809. 3,
  132810. 9,
  132811. 2,
  132812. 10,
  132813. 1,
  132814. 11,
  132815. 0,
  132816. 12,
  132817. };
  132818. static long _vq_lengthlist__44c1_s_p8_1[] = {
  132819. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  132820. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  132821. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  132822. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  132823. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  132824. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  132825. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  132826. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  132827. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  132828. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  132829. 16,13,12,12,11,14,12,15,13,
  132830. };
  132831. static float _vq_quantthresh__44c1_s_p8_1[] = {
  132832. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  132833. 42.5, 59.5, 76.5, 93.5,
  132834. };
  132835. static long _vq_quantmap__44c1_s_p8_1[] = {
  132836. 11, 9, 7, 5, 3, 1, 0, 2,
  132837. 4, 6, 8, 10, 12,
  132838. };
  132839. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  132840. _vq_quantthresh__44c1_s_p8_1,
  132841. _vq_quantmap__44c1_s_p8_1,
  132842. 13,
  132843. 13
  132844. };
  132845. static static_codebook _44c1_s_p8_1 = {
  132846. 2, 169,
  132847. _vq_lengthlist__44c1_s_p8_1,
  132848. 1, -522616832, 1620115456, 4, 0,
  132849. _vq_quantlist__44c1_s_p8_1,
  132850. NULL,
  132851. &_vq_auxt__44c1_s_p8_1,
  132852. NULL,
  132853. 0
  132854. };
  132855. static long _vq_quantlist__44c1_s_p8_2[] = {
  132856. 8,
  132857. 7,
  132858. 9,
  132859. 6,
  132860. 10,
  132861. 5,
  132862. 11,
  132863. 4,
  132864. 12,
  132865. 3,
  132866. 13,
  132867. 2,
  132868. 14,
  132869. 1,
  132870. 15,
  132871. 0,
  132872. 16,
  132873. };
  132874. static long _vq_lengthlist__44c1_s_p8_2[] = {
  132875. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132876. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  132877. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  132878. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  132879. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  132880. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  132881. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  132882. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  132883. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  132884. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  132885. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  132886. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  132887. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  132888. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  132889. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  132890. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  132891. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  132892. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  132893. 9,
  132894. };
  132895. static float _vq_quantthresh__44c1_s_p8_2[] = {
  132896. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132897. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132898. };
  132899. static long _vq_quantmap__44c1_s_p8_2[] = {
  132900. 15, 13, 11, 9, 7, 5, 3, 1,
  132901. 0, 2, 4, 6, 8, 10, 12, 14,
  132902. 16,
  132903. };
  132904. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  132905. _vq_quantthresh__44c1_s_p8_2,
  132906. _vq_quantmap__44c1_s_p8_2,
  132907. 17,
  132908. 17
  132909. };
  132910. static static_codebook _44c1_s_p8_2 = {
  132911. 2, 289,
  132912. _vq_lengthlist__44c1_s_p8_2,
  132913. 1, -529530880, 1611661312, 5, 0,
  132914. _vq_quantlist__44c1_s_p8_2,
  132915. NULL,
  132916. &_vq_auxt__44c1_s_p8_2,
  132917. NULL,
  132918. 0
  132919. };
  132920. static long _huff_lengthlist__44c1_s_short[] = {
  132921. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  132922. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  132923. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  132924. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  132925. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  132926. 11,
  132927. };
  132928. static static_codebook _huff_book__44c1_s_short = {
  132929. 2, 81,
  132930. _huff_lengthlist__44c1_s_short,
  132931. 0, 0, 0, 0, 0,
  132932. NULL,
  132933. NULL,
  132934. NULL,
  132935. NULL,
  132936. 0
  132937. };
  132938. static long _huff_lengthlist__44c1_sm_long[] = {
  132939. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  132940. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  132941. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  132942. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  132943. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  132944. 11,
  132945. };
  132946. static static_codebook _huff_book__44c1_sm_long = {
  132947. 2, 81,
  132948. _huff_lengthlist__44c1_sm_long,
  132949. 0, 0, 0, 0, 0,
  132950. NULL,
  132951. NULL,
  132952. NULL,
  132953. NULL,
  132954. 0
  132955. };
  132956. static long _vq_quantlist__44c1_sm_p1_0[] = {
  132957. 1,
  132958. 0,
  132959. 2,
  132960. };
  132961. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  132962. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  132963. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132967. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132968. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132972. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  132973. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  133008. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  133009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  133013. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  133014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  133018. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  133019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133053. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  133054. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133058. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  133059. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  133060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133063. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  133064. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  133065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133372. 0,
  133373. };
  133374. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  133375. -0.5, 0.5,
  133376. };
  133377. static long _vq_quantmap__44c1_sm_p1_0[] = {
  133378. 1, 0, 2,
  133379. };
  133380. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  133381. _vq_quantthresh__44c1_sm_p1_0,
  133382. _vq_quantmap__44c1_sm_p1_0,
  133383. 3,
  133384. 3
  133385. };
  133386. static static_codebook _44c1_sm_p1_0 = {
  133387. 8, 6561,
  133388. _vq_lengthlist__44c1_sm_p1_0,
  133389. 1, -535822336, 1611661312, 2, 0,
  133390. _vq_quantlist__44c1_sm_p1_0,
  133391. NULL,
  133392. &_vq_auxt__44c1_sm_p1_0,
  133393. NULL,
  133394. 0
  133395. };
  133396. static long _vq_quantlist__44c1_sm_p2_0[] = {
  133397. 2,
  133398. 1,
  133399. 3,
  133400. 0,
  133401. 4,
  133402. };
  133403. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  133404. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  133406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133407. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  133409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133410. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  133411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133443. 0,
  133444. };
  133445. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  133446. -1.5, -0.5, 0.5, 1.5,
  133447. };
  133448. static long _vq_quantmap__44c1_sm_p2_0[] = {
  133449. 3, 1, 0, 2, 4,
  133450. };
  133451. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  133452. _vq_quantthresh__44c1_sm_p2_0,
  133453. _vq_quantmap__44c1_sm_p2_0,
  133454. 5,
  133455. 5
  133456. };
  133457. static static_codebook _44c1_sm_p2_0 = {
  133458. 4, 625,
  133459. _vq_lengthlist__44c1_sm_p2_0,
  133460. 1, -533725184, 1611661312, 3, 0,
  133461. _vq_quantlist__44c1_sm_p2_0,
  133462. NULL,
  133463. &_vq_auxt__44c1_sm_p2_0,
  133464. NULL,
  133465. 0
  133466. };
  133467. static long _vq_quantlist__44c1_sm_p3_0[] = {
  133468. 4,
  133469. 3,
  133470. 5,
  133471. 2,
  133472. 6,
  133473. 1,
  133474. 7,
  133475. 0,
  133476. 8,
  133477. };
  133478. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  133479. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  133480. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  133481. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  133482. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  133483. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133484. 0,
  133485. };
  133486. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  133487. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133488. };
  133489. static long _vq_quantmap__44c1_sm_p3_0[] = {
  133490. 7, 5, 3, 1, 0, 2, 4, 6,
  133491. 8,
  133492. };
  133493. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  133494. _vq_quantthresh__44c1_sm_p3_0,
  133495. _vq_quantmap__44c1_sm_p3_0,
  133496. 9,
  133497. 9
  133498. };
  133499. static static_codebook _44c1_sm_p3_0 = {
  133500. 2, 81,
  133501. _vq_lengthlist__44c1_sm_p3_0,
  133502. 1, -531628032, 1611661312, 4, 0,
  133503. _vq_quantlist__44c1_sm_p3_0,
  133504. NULL,
  133505. &_vq_auxt__44c1_sm_p3_0,
  133506. NULL,
  133507. 0
  133508. };
  133509. static long _vq_quantlist__44c1_sm_p4_0[] = {
  133510. 4,
  133511. 3,
  133512. 5,
  133513. 2,
  133514. 6,
  133515. 1,
  133516. 7,
  133517. 0,
  133518. 8,
  133519. };
  133520. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  133521. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  133522. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  133523. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  133524. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  133525. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  133526. 11,
  133527. };
  133528. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  133529. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133530. };
  133531. static long _vq_quantmap__44c1_sm_p4_0[] = {
  133532. 7, 5, 3, 1, 0, 2, 4, 6,
  133533. 8,
  133534. };
  133535. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  133536. _vq_quantthresh__44c1_sm_p4_0,
  133537. _vq_quantmap__44c1_sm_p4_0,
  133538. 9,
  133539. 9
  133540. };
  133541. static static_codebook _44c1_sm_p4_0 = {
  133542. 2, 81,
  133543. _vq_lengthlist__44c1_sm_p4_0,
  133544. 1, -531628032, 1611661312, 4, 0,
  133545. _vq_quantlist__44c1_sm_p4_0,
  133546. NULL,
  133547. &_vq_auxt__44c1_sm_p4_0,
  133548. NULL,
  133549. 0
  133550. };
  133551. static long _vq_quantlist__44c1_sm_p5_0[] = {
  133552. 8,
  133553. 7,
  133554. 9,
  133555. 6,
  133556. 10,
  133557. 5,
  133558. 11,
  133559. 4,
  133560. 12,
  133561. 3,
  133562. 13,
  133563. 2,
  133564. 14,
  133565. 1,
  133566. 15,
  133567. 0,
  133568. 16,
  133569. };
  133570. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  133571. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133572. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  133573. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  133574. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  133575. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  133576. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  133577. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  133578. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  133579. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  133580. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  133581. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  133582. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  133583. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  133584. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  133585. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  133586. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  133587. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  133588. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  133589. 14,
  133590. };
  133591. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  133592. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133593. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133594. };
  133595. static long _vq_quantmap__44c1_sm_p5_0[] = {
  133596. 15, 13, 11, 9, 7, 5, 3, 1,
  133597. 0, 2, 4, 6, 8, 10, 12, 14,
  133598. 16,
  133599. };
  133600. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  133601. _vq_quantthresh__44c1_sm_p5_0,
  133602. _vq_quantmap__44c1_sm_p5_0,
  133603. 17,
  133604. 17
  133605. };
  133606. static static_codebook _44c1_sm_p5_0 = {
  133607. 2, 289,
  133608. _vq_lengthlist__44c1_sm_p5_0,
  133609. 1, -529530880, 1611661312, 5, 0,
  133610. _vq_quantlist__44c1_sm_p5_0,
  133611. NULL,
  133612. &_vq_auxt__44c1_sm_p5_0,
  133613. NULL,
  133614. 0
  133615. };
  133616. static long _vq_quantlist__44c1_sm_p6_0[] = {
  133617. 1,
  133618. 0,
  133619. 2,
  133620. };
  133621. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  133622. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  133623. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  133624. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  133625. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  133626. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  133627. 11,
  133628. };
  133629. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  133630. -5.5, 5.5,
  133631. };
  133632. static long _vq_quantmap__44c1_sm_p6_0[] = {
  133633. 1, 0, 2,
  133634. };
  133635. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  133636. _vq_quantthresh__44c1_sm_p6_0,
  133637. _vq_quantmap__44c1_sm_p6_0,
  133638. 3,
  133639. 3
  133640. };
  133641. static static_codebook _44c1_sm_p6_0 = {
  133642. 4, 81,
  133643. _vq_lengthlist__44c1_sm_p6_0,
  133644. 1, -529137664, 1618345984, 2, 0,
  133645. _vq_quantlist__44c1_sm_p6_0,
  133646. NULL,
  133647. &_vq_auxt__44c1_sm_p6_0,
  133648. NULL,
  133649. 0
  133650. };
  133651. static long _vq_quantlist__44c1_sm_p6_1[] = {
  133652. 5,
  133653. 4,
  133654. 6,
  133655. 3,
  133656. 7,
  133657. 2,
  133658. 8,
  133659. 1,
  133660. 9,
  133661. 0,
  133662. 10,
  133663. };
  133664. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  133665. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  133666. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133667. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  133668. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  133669. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  133670. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  133671. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  133672. 10,10,10, 8, 8, 8, 8, 8, 8,
  133673. };
  133674. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  133675. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133676. 3.5, 4.5,
  133677. };
  133678. static long _vq_quantmap__44c1_sm_p6_1[] = {
  133679. 9, 7, 5, 3, 1, 0, 2, 4,
  133680. 6, 8, 10,
  133681. };
  133682. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  133683. _vq_quantthresh__44c1_sm_p6_1,
  133684. _vq_quantmap__44c1_sm_p6_1,
  133685. 11,
  133686. 11
  133687. };
  133688. static static_codebook _44c1_sm_p6_1 = {
  133689. 2, 121,
  133690. _vq_lengthlist__44c1_sm_p6_1,
  133691. 1, -531365888, 1611661312, 4, 0,
  133692. _vq_quantlist__44c1_sm_p6_1,
  133693. NULL,
  133694. &_vq_auxt__44c1_sm_p6_1,
  133695. NULL,
  133696. 0
  133697. };
  133698. static long _vq_quantlist__44c1_sm_p7_0[] = {
  133699. 6,
  133700. 5,
  133701. 7,
  133702. 4,
  133703. 8,
  133704. 3,
  133705. 9,
  133706. 2,
  133707. 10,
  133708. 1,
  133709. 11,
  133710. 0,
  133711. 12,
  133712. };
  133713. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  133714. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  133715. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  133716. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  133717. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  133718. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  133719. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  133720. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  133721. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  133722. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  133723. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  133724. 0,12,12,11,11,13,12,14,13,
  133725. };
  133726. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  133727. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133728. 12.5, 17.5, 22.5, 27.5,
  133729. };
  133730. static long _vq_quantmap__44c1_sm_p7_0[] = {
  133731. 11, 9, 7, 5, 3, 1, 0, 2,
  133732. 4, 6, 8, 10, 12,
  133733. };
  133734. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  133735. _vq_quantthresh__44c1_sm_p7_0,
  133736. _vq_quantmap__44c1_sm_p7_0,
  133737. 13,
  133738. 13
  133739. };
  133740. static static_codebook _44c1_sm_p7_0 = {
  133741. 2, 169,
  133742. _vq_lengthlist__44c1_sm_p7_0,
  133743. 1, -526516224, 1616117760, 4, 0,
  133744. _vq_quantlist__44c1_sm_p7_0,
  133745. NULL,
  133746. &_vq_auxt__44c1_sm_p7_0,
  133747. NULL,
  133748. 0
  133749. };
  133750. static long _vq_quantlist__44c1_sm_p7_1[] = {
  133751. 2,
  133752. 1,
  133753. 3,
  133754. 0,
  133755. 4,
  133756. };
  133757. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  133758. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  133759. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133760. };
  133761. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  133762. -1.5, -0.5, 0.5, 1.5,
  133763. };
  133764. static long _vq_quantmap__44c1_sm_p7_1[] = {
  133765. 3, 1, 0, 2, 4,
  133766. };
  133767. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  133768. _vq_quantthresh__44c1_sm_p7_1,
  133769. _vq_quantmap__44c1_sm_p7_1,
  133770. 5,
  133771. 5
  133772. };
  133773. static static_codebook _44c1_sm_p7_1 = {
  133774. 2, 25,
  133775. _vq_lengthlist__44c1_sm_p7_1,
  133776. 1, -533725184, 1611661312, 3, 0,
  133777. _vq_quantlist__44c1_sm_p7_1,
  133778. NULL,
  133779. &_vq_auxt__44c1_sm_p7_1,
  133780. NULL,
  133781. 0
  133782. };
  133783. static long _vq_quantlist__44c1_sm_p8_0[] = {
  133784. 6,
  133785. 5,
  133786. 7,
  133787. 4,
  133788. 8,
  133789. 3,
  133790. 9,
  133791. 2,
  133792. 10,
  133793. 1,
  133794. 11,
  133795. 0,
  133796. 12,
  133797. };
  133798. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  133799. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  133800. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  133801. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133802. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133803. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133804. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133805. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133806. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133807. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133808. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133809. 13,13,13,13,13,13,13,13,13,
  133810. };
  133811. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  133812. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  133813. 552.5, 773.5, 994.5, 1215.5,
  133814. };
  133815. static long _vq_quantmap__44c1_sm_p8_0[] = {
  133816. 11, 9, 7, 5, 3, 1, 0, 2,
  133817. 4, 6, 8, 10, 12,
  133818. };
  133819. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  133820. _vq_quantthresh__44c1_sm_p8_0,
  133821. _vq_quantmap__44c1_sm_p8_0,
  133822. 13,
  133823. 13
  133824. };
  133825. static static_codebook _44c1_sm_p8_0 = {
  133826. 2, 169,
  133827. _vq_lengthlist__44c1_sm_p8_0,
  133828. 1, -514541568, 1627103232, 4, 0,
  133829. _vq_quantlist__44c1_sm_p8_0,
  133830. NULL,
  133831. &_vq_auxt__44c1_sm_p8_0,
  133832. NULL,
  133833. 0
  133834. };
  133835. static long _vq_quantlist__44c1_sm_p8_1[] = {
  133836. 6,
  133837. 5,
  133838. 7,
  133839. 4,
  133840. 8,
  133841. 3,
  133842. 9,
  133843. 2,
  133844. 10,
  133845. 1,
  133846. 11,
  133847. 0,
  133848. 12,
  133849. };
  133850. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  133851. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  133852. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  133853. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  133854. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  133855. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  133856. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  133857. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  133858. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  133859. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  133860. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  133861. 20,13,12,12,12,14,12,14,13,
  133862. };
  133863. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  133864. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  133865. 42.5, 59.5, 76.5, 93.5,
  133866. };
  133867. static long _vq_quantmap__44c1_sm_p8_1[] = {
  133868. 11, 9, 7, 5, 3, 1, 0, 2,
  133869. 4, 6, 8, 10, 12,
  133870. };
  133871. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  133872. _vq_quantthresh__44c1_sm_p8_1,
  133873. _vq_quantmap__44c1_sm_p8_1,
  133874. 13,
  133875. 13
  133876. };
  133877. static static_codebook _44c1_sm_p8_1 = {
  133878. 2, 169,
  133879. _vq_lengthlist__44c1_sm_p8_1,
  133880. 1, -522616832, 1620115456, 4, 0,
  133881. _vq_quantlist__44c1_sm_p8_1,
  133882. NULL,
  133883. &_vq_auxt__44c1_sm_p8_1,
  133884. NULL,
  133885. 0
  133886. };
  133887. static long _vq_quantlist__44c1_sm_p8_2[] = {
  133888. 8,
  133889. 7,
  133890. 9,
  133891. 6,
  133892. 10,
  133893. 5,
  133894. 11,
  133895. 4,
  133896. 12,
  133897. 3,
  133898. 13,
  133899. 2,
  133900. 14,
  133901. 1,
  133902. 15,
  133903. 0,
  133904. 16,
  133905. };
  133906. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  133907. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  133908. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  133909. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133910. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  133911. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  133912. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  133913. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  133914. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  133915. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  133916. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  133917. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  133918. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  133919. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  133920. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  133921. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  133922. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  133923. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  133924. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  133925. 9,
  133926. };
  133927. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  133928. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133929. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133930. };
  133931. static long _vq_quantmap__44c1_sm_p8_2[] = {
  133932. 15, 13, 11, 9, 7, 5, 3, 1,
  133933. 0, 2, 4, 6, 8, 10, 12, 14,
  133934. 16,
  133935. };
  133936. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  133937. _vq_quantthresh__44c1_sm_p8_2,
  133938. _vq_quantmap__44c1_sm_p8_2,
  133939. 17,
  133940. 17
  133941. };
  133942. static static_codebook _44c1_sm_p8_2 = {
  133943. 2, 289,
  133944. _vq_lengthlist__44c1_sm_p8_2,
  133945. 1, -529530880, 1611661312, 5, 0,
  133946. _vq_quantlist__44c1_sm_p8_2,
  133947. NULL,
  133948. &_vq_auxt__44c1_sm_p8_2,
  133949. NULL,
  133950. 0
  133951. };
  133952. static long _huff_lengthlist__44c1_sm_short[] = {
  133953. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  133954. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  133955. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  133956. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  133957. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  133958. 11,
  133959. };
  133960. static static_codebook _huff_book__44c1_sm_short = {
  133961. 2, 81,
  133962. _huff_lengthlist__44c1_sm_short,
  133963. 0, 0, 0, 0, 0,
  133964. NULL,
  133965. NULL,
  133966. NULL,
  133967. NULL,
  133968. 0
  133969. };
  133970. static long _huff_lengthlist__44cn1_s_long[] = {
  133971. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  133972. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  133973. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  133974. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  133975. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  133976. 20,
  133977. };
  133978. static static_codebook _huff_book__44cn1_s_long = {
  133979. 2, 81,
  133980. _huff_lengthlist__44cn1_s_long,
  133981. 0, 0, 0, 0, 0,
  133982. NULL,
  133983. NULL,
  133984. NULL,
  133985. NULL,
  133986. 0
  133987. };
  133988. static long _vq_quantlist__44cn1_s_p1_0[] = {
  133989. 1,
  133990. 0,
  133991. 2,
  133992. };
  133993. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  133994. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  133995. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133999. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  134000. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134004. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  134005. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  134040. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  134041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  134045. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  134046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  134050. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  134051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134085. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  134086. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134090. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  134091. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  134092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134095. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  134096. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  134097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134404. 0,
  134405. };
  134406. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  134407. -0.5, 0.5,
  134408. };
  134409. static long _vq_quantmap__44cn1_s_p1_0[] = {
  134410. 1, 0, 2,
  134411. };
  134412. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  134413. _vq_quantthresh__44cn1_s_p1_0,
  134414. _vq_quantmap__44cn1_s_p1_0,
  134415. 3,
  134416. 3
  134417. };
  134418. static static_codebook _44cn1_s_p1_0 = {
  134419. 8, 6561,
  134420. _vq_lengthlist__44cn1_s_p1_0,
  134421. 1, -535822336, 1611661312, 2, 0,
  134422. _vq_quantlist__44cn1_s_p1_0,
  134423. NULL,
  134424. &_vq_auxt__44cn1_s_p1_0,
  134425. NULL,
  134426. 0
  134427. };
  134428. static long _vq_quantlist__44cn1_s_p2_0[] = {
  134429. 2,
  134430. 1,
  134431. 3,
  134432. 0,
  134433. 4,
  134434. };
  134435. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  134436. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  134438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134439. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  134441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134442. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  134443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134475. 0,
  134476. };
  134477. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  134478. -1.5, -0.5, 0.5, 1.5,
  134479. };
  134480. static long _vq_quantmap__44cn1_s_p2_0[] = {
  134481. 3, 1, 0, 2, 4,
  134482. };
  134483. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  134484. _vq_quantthresh__44cn1_s_p2_0,
  134485. _vq_quantmap__44cn1_s_p2_0,
  134486. 5,
  134487. 5
  134488. };
  134489. static static_codebook _44cn1_s_p2_0 = {
  134490. 4, 625,
  134491. _vq_lengthlist__44cn1_s_p2_0,
  134492. 1, -533725184, 1611661312, 3, 0,
  134493. _vq_quantlist__44cn1_s_p2_0,
  134494. NULL,
  134495. &_vq_auxt__44cn1_s_p2_0,
  134496. NULL,
  134497. 0
  134498. };
  134499. static long _vq_quantlist__44cn1_s_p3_0[] = {
  134500. 4,
  134501. 3,
  134502. 5,
  134503. 2,
  134504. 6,
  134505. 1,
  134506. 7,
  134507. 0,
  134508. 8,
  134509. };
  134510. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  134511. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  134512. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  134513. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  134514. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  134515. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134516. 0,
  134517. };
  134518. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  134519. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134520. };
  134521. static long _vq_quantmap__44cn1_s_p3_0[] = {
  134522. 7, 5, 3, 1, 0, 2, 4, 6,
  134523. 8,
  134524. };
  134525. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  134526. _vq_quantthresh__44cn1_s_p3_0,
  134527. _vq_quantmap__44cn1_s_p3_0,
  134528. 9,
  134529. 9
  134530. };
  134531. static static_codebook _44cn1_s_p3_0 = {
  134532. 2, 81,
  134533. _vq_lengthlist__44cn1_s_p3_0,
  134534. 1, -531628032, 1611661312, 4, 0,
  134535. _vq_quantlist__44cn1_s_p3_0,
  134536. NULL,
  134537. &_vq_auxt__44cn1_s_p3_0,
  134538. NULL,
  134539. 0
  134540. };
  134541. static long _vq_quantlist__44cn1_s_p4_0[] = {
  134542. 4,
  134543. 3,
  134544. 5,
  134545. 2,
  134546. 6,
  134547. 1,
  134548. 7,
  134549. 0,
  134550. 8,
  134551. };
  134552. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  134553. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  134554. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  134555. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  134556. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  134557. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  134558. 11,
  134559. };
  134560. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  134561. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134562. };
  134563. static long _vq_quantmap__44cn1_s_p4_0[] = {
  134564. 7, 5, 3, 1, 0, 2, 4, 6,
  134565. 8,
  134566. };
  134567. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  134568. _vq_quantthresh__44cn1_s_p4_0,
  134569. _vq_quantmap__44cn1_s_p4_0,
  134570. 9,
  134571. 9
  134572. };
  134573. static static_codebook _44cn1_s_p4_0 = {
  134574. 2, 81,
  134575. _vq_lengthlist__44cn1_s_p4_0,
  134576. 1, -531628032, 1611661312, 4, 0,
  134577. _vq_quantlist__44cn1_s_p4_0,
  134578. NULL,
  134579. &_vq_auxt__44cn1_s_p4_0,
  134580. NULL,
  134581. 0
  134582. };
  134583. static long _vq_quantlist__44cn1_s_p5_0[] = {
  134584. 8,
  134585. 7,
  134586. 9,
  134587. 6,
  134588. 10,
  134589. 5,
  134590. 11,
  134591. 4,
  134592. 12,
  134593. 3,
  134594. 13,
  134595. 2,
  134596. 14,
  134597. 1,
  134598. 15,
  134599. 0,
  134600. 16,
  134601. };
  134602. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  134603. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  134604. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  134605. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  134606. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  134607. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  134608. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  134609. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  134610. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  134611. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  134612. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  134613. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  134614. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  134615. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  134616. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  134617. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  134618. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  134619. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  134620. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  134621. 14,
  134622. };
  134623. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  134624. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134625. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134626. };
  134627. static long _vq_quantmap__44cn1_s_p5_0[] = {
  134628. 15, 13, 11, 9, 7, 5, 3, 1,
  134629. 0, 2, 4, 6, 8, 10, 12, 14,
  134630. 16,
  134631. };
  134632. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  134633. _vq_quantthresh__44cn1_s_p5_0,
  134634. _vq_quantmap__44cn1_s_p5_0,
  134635. 17,
  134636. 17
  134637. };
  134638. static static_codebook _44cn1_s_p5_0 = {
  134639. 2, 289,
  134640. _vq_lengthlist__44cn1_s_p5_0,
  134641. 1, -529530880, 1611661312, 5, 0,
  134642. _vq_quantlist__44cn1_s_p5_0,
  134643. NULL,
  134644. &_vq_auxt__44cn1_s_p5_0,
  134645. NULL,
  134646. 0
  134647. };
  134648. static long _vq_quantlist__44cn1_s_p6_0[] = {
  134649. 1,
  134650. 0,
  134651. 2,
  134652. };
  134653. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  134654. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  134655. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  134656. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  134657. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  134658. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  134659. 10,
  134660. };
  134661. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  134662. -5.5, 5.5,
  134663. };
  134664. static long _vq_quantmap__44cn1_s_p6_0[] = {
  134665. 1, 0, 2,
  134666. };
  134667. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  134668. _vq_quantthresh__44cn1_s_p6_0,
  134669. _vq_quantmap__44cn1_s_p6_0,
  134670. 3,
  134671. 3
  134672. };
  134673. static static_codebook _44cn1_s_p6_0 = {
  134674. 4, 81,
  134675. _vq_lengthlist__44cn1_s_p6_0,
  134676. 1, -529137664, 1618345984, 2, 0,
  134677. _vq_quantlist__44cn1_s_p6_0,
  134678. NULL,
  134679. &_vq_auxt__44cn1_s_p6_0,
  134680. NULL,
  134681. 0
  134682. };
  134683. static long _vq_quantlist__44cn1_s_p6_1[] = {
  134684. 5,
  134685. 4,
  134686. 6,
  134687. 3,
  134688. 7,
  134689. 2,
  134690. 8,
  134691. 1,
  134692. 9,
  134693. 0,
  134694. 10,
  134695. };
  134696. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  134697. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  134698. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  134699. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  134700. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  134701. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  134702. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134703. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  134704. 10,10,10, 9, 9, 9, 9, 9, 9,
  134705. };
  134706. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  134707. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134708. 3.5, 4.5,
  134709. };
  134710. static long _vq_quantmap__44cn1_s_p6_1[] = {
  134711. 9, 7, 5, 3, 1, 0, 2, 4,
  134712. 6, 8, 10,
  134713. };
  134714. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  134715. _vq_quantthresh__44cn1_s_p6_1,
  134716. _vq_quantmap__44cn1_s_p6_1,
  134717. 11,
  134718. 11
  134719. };
  134720. static static_codebook _44cn1_s_p6_1 = {
  134721. 2, 121,
  134722. _vq_lengthlist__44cn1_s_p6_1,
  134723. 1, -531365888, 1611661312, 4, 0,
  134724. _vq_quantlist__44cn1_s_p6_1,
  134725. NULL,
  134726. &_vq_auxt__44cn1_s_p6_1,
  134727. NULL,
  134728. 0
  134729. };
  134730. static long _vq_quantlist__44cn1_s_p7_0[] = {
  134731. 6,
  134732. 5,
  134733. 7,
  134734. 4,
  134735. 8,
  134736. 3,
  134737. 9,
  134738. 2,
  134739. 10,
  134740. 1,
  134741. 11,
  134742. 0,
  134743. 12,
  134744. };
  134745. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  134746. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134747. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  134748. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  134749. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  134750. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  134751. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  134752. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  134753. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  134754. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  134755. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  134756. 0,13,13,12,12,13,13,13,14,
  134757. };
  134758. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  134759. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134760. 12.5, 17.5, 22.5, 27.5,
  134761. };
  134762. static long _vq_quantmap__44cn1_s_p7_0[] = {
  134763. 11, 9, 7, 5, 3, 1, 0, 2,
  134764. 4, 6, 8, 10, 12,
  134765. };
  134766. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  134767. _vq_quantthresh__44cn1_s_p7_0,
  134768. _vq_quantmap__44cn1_s_p7_0,
  134769. 13,
  134770. 13
  134771. };
  134772. static static_codebook _44cn1_s_p7_0 = {
  134773. 2, 169,
  134774. _vq_lengthlist__44cn1_s_p7_0,
  134775. 1, -526516224, 1616117760, 4, 0,
  134776. _vq_quantlist__44cn1_s_p7_0,
  134777. NULL,
  134778. &_vq_auxt__44cn1_s_p7_0,
  134779. NULL,
  134780. 0
  134781. };
  134782. static long _vq_quantlist__44cn1_s_p7_1[] = {
  134783. 2,
  134784. 1,
  134785. 3,
  134786. 0,
  134787. 4,
  134788. };
  134789. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  134790. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  134791. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  134792. };
  134793. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  134794. -1.5, -0.5, 0.5, 1.5,
  134795. };
  134796. static long _vq_quantmap__44cn1_s_p7_1[] = {
  134797. 3, 1, 0, 2, 4,
  134798. };
  134799. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  134800. _vq_quantthresh__44cn1_s_p7_1,
  134801. _vq_quantmap__44cn1_s_p7_1,
  134802. 5,
  134803. 5
  134804. };
  134805. static static_codebook _44cn1_s_p7_1 = {
  134806. 2, 25,
  134807. _vq_lengthlist__44cn1_s_p7_1,
  134808. 1, -533725184, 1611661312, 3, 0,
  134809. _vq_quantlist__44cn1_s_p7_1,
  134810. NULL,
  134811. &_vq_auxt__44cn1_s_p7_1,
  134812. NULL,
  134813. 0
  134814. };
  134815. static long _vq_quantlist__44cn1_s_p8_0[] = {
  134816. 2,
  134817. 1,
  134818. 3,
  134819. 0,
  134820. 4,
  134821. };
  134822. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  134823. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  134824. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  134825. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134826. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  134827. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134828. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134829. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134830. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  134831. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134832. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  134833. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  134834. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134835. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134836. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134837. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134838. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  134839. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134840. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134841. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134842. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134843. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134844. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134845. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134846. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134847. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134848. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134849. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134850. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134851. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134852. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134853. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134854. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134855. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134856. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  134857. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134858. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134859. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134860. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134861. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134862. 12,
  134863. };
  134864. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  134865. -331.5, -110.5, 110.5, 331.5,
  134866. };
  134867. static long _vq_quantmap__44cn1_s_p8_0[] = {
  134868. 3, 1, 0, 2, 4,
  134869. };
  134870. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  134871. _vq_quantthresh__44cn1_s_p8_0,
  134872. _vq_quantmap__44cn1_s_p8_0,
  134873. 5,
  134874. 5
  134875. };
  134876. static static_codebook _44cn1_s_p8_0 = {
  134877. 4, 625,
  134878. _vq_lengthlist__44cn1_s_p8_0,
  134879. 1, -518283264, 1627103232, 3, 0,
  134880. _vq_quantlist__44cn1_s_p8_0,
  134881. NULL,
  134882. &_vq_auxt__44cn1_s_p8_0,
  134883. NULL,
  134884. 0
  134885. };
  134886. static long _vq_quantlist__44cn1_s_p8_1[] = {
  134887. 6,
  134888. 5,
  134889. 7,
  134890. 4,
  134891. 8,
  134892. 3,
  134893. 9,
  134894. 2,
  134895. 10,
  134896. 1,
  134897. 11,
  134898. 0,
  134899. 12,
  134900. };
  134901. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  134902. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  134903. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  134904. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  134905. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  134906. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  134907. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  134908. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  134909. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  134910. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  134911. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  134912. 15,12,12,11,11,14,12,13,14,
  134913. };
  134914. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  134915. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  134916. 42.5, 59.5, 76.5, 93.5,
  134917. };
  134918. static long _vq_quantmap__44cn1_s_p8_1[] = {
  134919. 11, 9, 7, 5, 3, 1, 0, 2,
  134920. 4, 6, 8, 10, 12,
  134921. };
  134922. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  134923. _vq_quantthresh__44cn1_s_p8_1,
  134924. _vq_quantmap__44cn1_s_p8_1,
  134925. 13,
  134926. 13
  134927. };
  134928. static static_codebook _44cn1_s_p8_1 = {
  134929. 2, 169,
  134930. _vq_lengthlist__44cn1_s_p8_1,
  134931. 1, -522616832, 1620115456, 4, 0,
  134932. _vq_quantlist__44cn1_s_p8_1,
  134933. NULL,
  134934. &_vq_auxt__44cn1_s_p8_1,
  134935. NULL,
  134936. 0
  134937. };
  134938. static long _vq_quantlist__44cn1_s_p8_2[] = {
  134939. 8,
  134940. 7,
  134941. 9,
  134942. 6,
  134943. 10,
  134944. 5,
  134945. 11,
  134946. 4,
  134947. 12,
  134948. 3,
  134949. 13,
  134950. 2,
  134951. 14,
  134952. 1,
  134953. 15,
  134954. 0,
  134955. 16,
  134956. };
  134957. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  134958. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  134959. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  134960. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  134961. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  134962. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  134963. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  134964. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  134965. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  134966. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  134967. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  134968. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  134969. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  134970. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  134971. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  134972. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  134973. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  134974. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  134975. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  134976. 9,
  134977. };
  134978. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  134979. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134980. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134981. };
  134982. static long _vq_quantmap__44cn1_s_p8_2[] = {
  134983. 15, 13, 11, 9, 7, 5, 3, 1,
  134984. 0, 2, 4, 6, 8, 10, 12, 14,
  134985. 16,
  134986. };
  134987. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  134988. _vq_quantthresh__44cn1_s_p8_2,
  134989. _vq_quantmap__44cn1_s_p8_2,
  134990. 17,
  134991. 17
  134992. };
  134993. static static_codebook _44cn1_s_p8_2 = {
  134994. 2, 289,
  134995. _vq_lengthlist__44cn1_s_p8_2,
  134996. 1, -529530880, 1611661312, 5, 0,
  134997. _vq_quantlist__44cn1_s_p8_2,
  134998. NULL,
  134999. &_vq_auxt__44cn1_s_p8_2,
  135000. NULL,
  135001. 0
  135002. };
  135003. static long _huff_lengthlist__44cn1_s_short[] = {
  135004. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  135005. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  135006. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  135007. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  135008. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  135009. 10,
  135010. };
  135011. static static_codebook _huff_book__44cn1_s_short = {
  135012. 2, 81,
  135013. _huff_lengthlist__44cn1_s_short,
  135014. 0, 0, 0, 0, 0,
  135015. NULL,
  135016. NULL,
  135017. NULL,
  135018. NULL,
  135019. 0
  135020. };
  135021. static long _huff_lengthlist__44cn1_sm_long[] = {
  135022. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  135023. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  135024. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  135025. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  135026. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  135027. 17,
  135028. };
  135029. static static_codebook _huff_book__44cn1_sm_long = {
  135030. 2, 81,
  135031. _huff_lengthlist__44cn1_sm_long,
  135032. 0, 0, 0, 0, 0,
  135033. NULL,
  135034. NULL,
  135035. NULL,
  135036. NULL,
  135037. 0
  135038. };
  135039. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  135040. 1,
  135041. 0,
  135042. 2,
  135043. };
  135044. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  135045. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135046. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135050. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  135051. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135055. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  135056. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  135091. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  135092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  135096. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  135097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135101. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  135102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135136. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  135137. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135141. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  135142. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  135143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135146. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  135147. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  135148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135455. 0,
  135456. };
  135457. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  135458. -0.5, 0.5,
  135459. };
  135460. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  135461. 1, 0, 2,
  135462. };
  135463. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  135464. _vq_quantthresh__44cn1_sm_p1_0,
  135465. _vq_quantmap__44cn1_sm_p1_0,
  135466. 3,
  135467. 3
  135468. };
  135469. static static_codebook _44cn1_sm_p1_0 = {
  135470. 8, 6561,
  135471. _vq_lengthlist__44cn1_sm_p1_0,
  135472. 1, -535822336, 1611661312, 2, 0,
  135473. _vq_quantlist__44cn1_sm_p1_0,
  135474. NULL,
  135475. &_vq_auxt__44cn1_sm_p1_0,
  135476. NULL,
  135477. 0
  135478. };
  135479. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  135480. 2,
  135481. 1,
  135482. 3,
  135483. 0,
  135484. 4,
  135485. };
  135486. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  135487. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  135489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135490. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135493. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135526. 0,
  135527. };
  135528. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  135529. -1.5, -0.5, 0.5, 1.5,
  135530. };
  135531. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  135532. 3, 1, 0, 2, 4,
  135533. };
  135534. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  135535. _vq_quantthresh__44cn1_sm_p2_0,
  135536. _vq_quantmap__44cn1_sm_p2_0,
  135537. 5,
  135538. 5
  135539. };
  135540. static static_codebook _44cn1_sm_p2_0 = {
  135541. 4, 625,
  135542. _vq_lengthlist__44cn1_sm_p2_0,
  135543. 1, -533725184, 1611661312, 3, 0,
  135544. _vq_quantlist__44cn1_sm_p2_0,
  135545. NULL,
  135546. &_vq_auxt__44cn1_sm_p2_0,
  135547. NULL,
  135548. 0
  135549. };
  135550. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  135551. 4,
  135552. 3,
  135553. 5,
  135554. 2,
  135555. 6,
  135556. 1,
  135557. 7,
  135558. 0,
  135559. 8,
  135560. };
  135561. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  135562. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  135563. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  135564. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  135565. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  135566. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135567. 0,
  135568. };
  135569. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  135570. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135571. };
  135572. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  135573. 7, 5, 3, 1, 0, 2, 4, 6,
  135574. 8,
  135575. };
  135576. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  135577. _vq_quantthresh__44cn1_sm_p3_0,
  135578. _vq_quantmap__44cn1_sm_p3_0,
  135579. 9,
  135580. 9
  135581. };
  135582. static static_codebook _44cn1_sm_p3_0 = {
  135583. 2, 81,
  135584. _vq_lengthlist__44cn1_sm_p3_0,
  135585. 1, -531628032, 1611661312, 4, 0,
  135586. _vq_quantlist__44cn1_sm_p3_0,
  135587. NULL,
  135588. &_vq_auxt__44cn1_sm_p3_0,
  135589. NULL,
  135590. 0
  135591. };
  135592. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  135593. 4,
  135594. 3,
  135595. 5,
  135596. 2,
  135597. 6,
  135598. 1,
  135599. 7,
  135600. 0,
  135601. 8,
  135602. };
  135603. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  135604. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  135605. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  135606. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  135607. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  135608. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  135609. 11,
  135610. };
  135611. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  135612. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135613. };
  135614. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  135615. 7, 5, 3, 1, 0, 2, 4, 6,
  135616. 8,
  135617. };
  135618. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  135619. _vq_quantthresh__44cn1_sm_p4_0,
  135620. _vq_quantmap__44cn1_sm_p4_0,
  135621. 9,
  135622. 9
  135623. };
  135624. static static_codebook _44cn1_sm_p4_0 = {
  135625. 2, 81,
  135626. _vq_lengthlist__44cn1_sm_p4_0,
  135627. 1, -531628032, 1611661312, 4, 0,
  135628. _vq_quantlist__44cn1_sm_p4_0,
  135629. NULL,
  135630. &_vq_auxt__44cn1_sm_p4_0,
  135631. NULL,
  135632. 0
  135633. };
  135634. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  135635. 8,
  135636. 7,
  135637. 9,
  135638. 6,
  135639. 10,
  135640. 5,
  135641. 11,
  135642. 4,
  135643. 12,
  135644. 3,
  135645. 13,
  135646. 2,
  135647. 14,
  135648. 1,
  135649. 15,
  135650. 0,
  135651. 16,
  135652. };
  135653. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  135654. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  135655. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  135656. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  135657. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135658. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  135659. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  135660. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  135661. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  135662. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  135663. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  135664. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  135665. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  135666. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  135667. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  135668. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  135669. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  135670. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  135671. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  135672. 14,
  135673. };
  135674. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  135675. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135676. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135677. };
  135678. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  135679. 15, 13, 11, 9, 7, 5, 3, 1,
  135680. 0, 2, 4, 6, 8, 10, 12, 14,
  135681. 16,
  135682. };
  135683. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  135684. _vq_quantthresh__44cn1_sm_p5_0,
  135685. _vq_quantmap__44cn1_sm_p5_0,
  135686. 17,
  135687. 17
  135688. };
  135689. static static_codebook _44cn1_sm_p5_0 = {
  135690. 2, 289,
  135691. _vq_lengthlist__44cn1_sm_p5_0,
  135692. 1, -529530880, 1611661312, 5, 0,
  135693. _vq_quantlist__44cn1_sm_p5_0,
  135694. NULL,
  135695. &_vq_auxt__44cn1_sm_p5_0,
  135696. NULL,
  135697. 0
  135698. };
  135699. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  135700. 1,
  135701. 0,
  135702. 2,
  135703. };
  135704. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  135705. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  135706. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  135707. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  135708. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  135709. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  135710. 10,
  135711. };
  135712. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  135713. -5.5, 5.5,
  135714. };
  135715. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  135716. 1, 0, 2,
  135717. };
  135718. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  135719. _vq_quantthresh__44cn1_sm_p6_0,
  135720. _vq_quantmap__44cn1_sm_p6_0,
  135721. 3,
  135722. 3
  135723. };
  135724. static static_codebook _44cn1_sm_p6_0 = {
  135725. 4, 81,
  135726. _vq_lengthlist__44cn1_sm_p6_0,
  135727. 1, -529137664, 1618345984, 2, 0,
  135728. _vq_quantlist__44cn1_sm_p6_0,
  135729. NULL,
  135730. &_vq_auxt__44cn1_sm_p6_0,
  135731. NULL,
  135732. 0
  135733. };
  135734. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  135735. 5,
  135736. 4,
  135737. 6,
  135738. 3,
  135739. 7,
  135740. 2,
  135741. 8,
  135742. 1,
  135743. 9,
  135744. 0,
  135745. 10,
  135746. };
  135747. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  135748. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  135749. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  135750. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  135751. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  135752. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  135753. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  135754. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  135755. 10,10,10, 8, 9, 8, 8, 9, 8,
  135756. };
  135757. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  135758. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135759. 3.5, 4.5,
  135760. };
  135761. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  135762. 9, 7, 5, 3, 1, 0, 2, 4,
  135763. 6, 8, 10,
  135764. };
  135765. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  135766. _vq_quantthresh__44cn1_sm_p6_1,
  135767. _vq_quantmap__44cn1_sm_p6_1,
  135768. 11,
  135769. 11
  135770. };
  135771. static static_codebook _44cn1_sm_p6_1 = {
  135772. 2, 121,
  135773. _vq_lengthlist__44cn1_sm_p6_1,
  135774. 1, -531365888, 1611661312, 4, 0,
  135775. _vq_quantlist__44cn1_sm_p6_1,
  135776. NULL,
  135777. &_vq_auxt__44cn1_sm_p6_1,
  135778. NULL,
  135779. 0
  135780. };
  135781. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  135782. 6,
  135783. 5,
  135784. 7,
  135785. 4,
  135786. 8,
  135787. 3,
  135788. 9,
  135789. 2,
  135790. 10,
  135791. 1,
  135792. 11,
  135793. 0,
  135794. 12,
  135795. };
  135796. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  135797. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  135798. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  135799. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135800. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135801. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  135802. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  135803. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  135804. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  135805. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  135806. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  135807. 0,13,12,12,12,13,13,13,14,
  135808. };
  135809. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  135810. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135811. 12.5, 17.5, 22.5, 27.5,
  135812. };
  135813. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  135814. 11, 9, 7, 5, 3, 1, 0, 2,
  135815. 4, 6, 8, 10, 12,
  135816. };
  135817. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  135818. _vq_quantthresh__44cn1_sm_p7_0,
  135819. _vq_quantmap__44cn1_sm_p7_0,
  135820. 13,
  135821. 13
  135822. };
  135823. static static_codebook _44cn1_sm_p7_0 = {
  135824. 2, 169,
  135825. _vq_lengthlist__44cn1_sm_p7_0,
  135826. 1, -526516224, 1616117760, 4, 0,
  135827. _vq_quantlist__44cn1_sm_p7_0,
  135828. NULL,
  135829. &_vq_auxt__44cn1_sm_p7_0,
  135830. NULL,
  135831. 0
  135832. };
  135833. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  135834. 2,
  135835. 1,
  135836. 3,
  135837. 0,
  135838. 4,
  135839. };
  135840. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  135841. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  135842. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  135843. };
  135844. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  135845. -1.5, -0.5, 0.5, 1.5,
  135846. };
  135847. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  135848. 3, 1, 0, 2, 4,
  135849. };
  135850. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  135851. _vq_quantthresh__44cn1_sm_p7_1,
  135852. _vq_quantmap__44cn1_sm_p7_1,
  135853. 5,
  135854. 5
  135855. };
  135856. static static_codebook _44cn1_sm_p7_1 = {
  135857. 2, 25,
  135858. _vq_lengthlist__44cn1_sm_p7_1,
  135859. 1, -533725184, 1611661312, 3, 0,
  135860. _vq_quantlist__44cn1_sm_p7_1,
  135861. NULL,
  135862. &_vq_auxt__44cn1_sm_p7_1,
  135863. NULL,
  135864. 0
  135865. };
  135866. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  135867. 4,
  135868. 3,
  135869. 5,
  135870. 2,
  135871. 6,
  135872. 1,
  135873. 7,
  135874. 0,
  135875. 8,
  135876. };
  135877. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  135878. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  135879. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  135880. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  135881. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  135882. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  135883. 14,
  135884. };
  135885. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  135886. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  135887. };
  135888. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  135889. 7, 5, 3, 1, 0, 2, 4, 6,
  135890. 8,
  135891. };
  135892. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  135893. _vq_quantthresh__44cn1_sm_p8_0,
  135894. _vq_quantmap__44cn1_sm_p8_0,
  135895. 9,
  135896. 9
  135897. };
  135898. static static_codebook _44cn1_sm_p8_0 = {
  135899. 2, 81,
  135900. _vq_lengthlist__44cn1_sm_p8_0,
  135901. 1, -516186112, 1627103232, 4, 0,
  135902. _vq_quantlist__44cn1_sm_p8_0,
  135903. NULL,
  135904. &_vq_auxt__44cn1_sm_p8_0,
  135905. NULL,
  135906. 0
  135907. };
  135908. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  135909. 6,
  135910. 5,
  135911. 7,
  135912. 4,
  135913. 8,
  135914. 3,
  135915. 9,
  135916. 2,
  135917. 10,
  135918. 1,
  135919. 11,
  135920. 0,
  135921. 12,
  135922. };
  135923. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  135924. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  135925. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  135926. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  135927. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  135928. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  135929. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  135930. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  135931. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  135932. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  135933. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  135934. 17,12,12,11,10,13,11,13,13,
  135935. };
  135936. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  135937. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135938. 42.5, 59.5, 76.5, 93.5,
  135939. };
  135940. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  135941. 11, 9, 7, 5, 3, 1, 0, 2,
  135942. 4, 6, 8, 10, 12,
  135943. };
  135944. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  135945. _vq_quantthresh__44cn1_sm_p8_1,
  135946. _vq_quantmap__44cn1_sm_p8_1,
  135947. 13,
  135948. 13
  135949. };
  135950. static static_codebook _44cn1_sm_p8_1 = {
  135951. 2, 169,
  135952. _vq_lengthlist__44cn1_sm_p8_1,
  135953. 1, -522616832, 1620115456, 4, 0,
  135954. _vq_quantlist__44cn1_sm_p8_1,
  135955. NULL,
  135956. &_vq_auxt__44cn1_sm_p8_1,
  135957. NULL,
  135958. 0
  135959. };
  135960. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  135961. 8,
  135962. 7,
  135963. 9,
  135964. 6,
  135965. 10,
  135966. 5,
  135967. 11,
  135968. 4,
  135969. 12,
  135970. 3,
  135971. 13,
  135972. 2,
  135973. 14,
  135974. 1,
  135975. 15,
  135976. 0,
  135977. 16,
  135978. };
  135979. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  135980. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135981. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  135982. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  135983. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  135984. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  135985. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  135986. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  135987. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  135988. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  135989. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  135990. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  135991. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  135992. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  135993. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  135994. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  135995. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  135996. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135997. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  135998. 9,
  135999. };
  136000. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  136001. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136002. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136003. };
  136004. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  136005. 15, 13, 11, 9, 7, 5, 3, 1,
  136006. 0, 2, 4, 6, 8, 10, 12, 14,
  136007. 16,
  136008. };
  136009. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  136010. _vq_quantthresh__44cn1_sm_p8_2,
  136011. _vq_quantmap__44cn1_sm_p8_2,
  136012. 17,
  136013. 17
  136014. };
  136015. static static_codebook _44cn1_sm_p8_2 = {
  136016. 2, 289,
  136017. _vq_lengthlist__44cn1_sm_p8_2,
  136018. 1, -529530880, 1611661312, 5, 0,
  136019. _vq_quantlist__44cn1_sm_p8_2,
  136020. NULL,
  136021. &_vq_auxt__44cn1_sm_p8_2,
  136022. NULL,
  136023. 0
  136024. };
  136025. static long _huff_lengthlist__44cn1_sm_short[] = {
  136026. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  136027. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  136028. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  136029. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  136030. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  136031. 9,
  136032. };
  136033. static static_codebook _huff_book__44cn1_sm_short = {
  136034. 2, 81,
  136035. _huff_lengthlist__44cn1_sm_short,
  136036. 0, 0, 0, 0, 0,
  136037. NULL,
  136038. NULL,
  136039. NULL,
  136040. NULL,
  136041. 0
  136042. };
  136043. /********* End of inlined file: res_books_stereo.h *********/
  136044. /***** residue backends *********************************************/
  136045. static vorbis_info_residue0 _residue_44_low={
  136046. 0,-1, -1, 9,-1,
  136047. /* 0 1 2 3 4 5 6 7 */
  136048. {0},
  136049. {-1},
  136050. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  136051. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  136052. };
  136053. static vorbis_info_residue0 _residue_44_mid={
  136054. 0,-1, -1, 10,-1,
  136055. /* 0 1 2 3 4 5 6 7 8 */
  136056. {0},
  136057. {-1},
  136058. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  136059. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  136060. };
  136061. static vorbis_info_residue0 _residue_44_high={
  136062. 0,-1, -1, 10,-1,
  136063. /* 0 1 2 3 4 5 6 7 8 */
  136064. {0},
  136065. {-1},
  136066. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  136067. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  136068. };
  136069. static static_bookblock _resbook_44s_n1={
  136070. {
  136071. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  136072. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  136073. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  136074. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  136075. }
  136076. };
  136077. static static_bookblock _resbook_44sm_n1={
  136078. {
  136079. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  136080. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  136081. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  136082. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  136083. }
  136084. };
  136085. static static_bookblock _resbook_44s_0={
  136086. {
  136087. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  136088. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  136089. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  136090. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  136091. }
  136092. };
  136093. static static_bookblock _resbook_44sm_0={
  136094. {
  136095. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  136096. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  136097. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  136098. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  136099. }
  136100. };
  136101. static static_bookblock _resbook_44s_1={
  136102. {
  136103. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  136104. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  136105. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  136106. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  136107. }
  136108. };
  136109. static static_bookblock _resbook_44sm_1={
  136110. {
  136111. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  136112. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  136113. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  136114. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  136115. }
  136116. };
  136117. static static_bookblock _resbook_44s_2={
  136118. {
  136119. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  136120. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  136121. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  136122. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  136123. }
  136124. };
  136125. static static_bookblock _resbook_44s_3={
  136126. {
  136127. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  136128. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  136129. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  136130. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  136131. }
  136132. };
  136133. static static_bookblock _resbook_44s_4={
  136134. {
  136135. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  136136. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  136137. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  136138. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  136139. }
  136140. };
  136141. static static_bookblock _resbook_44s_5={
  136142. {
  136143. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  136144. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  136145. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  136146. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  136147. }
  136148. };
  136149. static static_bookblock _resbook_44s_6={
  136150. {
  136151. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  136152. {0,0,&_44c6_s_p4_0},
  136153. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  136154. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  136155. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  136156. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  136157. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  136158. }
  136159. };
  136160. static static_bookblock _resbook_44s_7={
  136161. {
  136162. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  136163. {0,0,&_44c7_s_p4_0},
  136164. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  136165. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  136166. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  136167. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  136168. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  136169. }
  136170. };
  136171. static static_bookblock _resbook_44s_8={
  136172. {
  136173. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  136174. {0,0,&_44c8_s_p4_0},
  136175. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  136176. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  136177. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  136178. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  136179. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  136180. }
  136181. };
  136182. static static_bookblock _resbook_44s_9={
  136183. {
  136184. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  136185. {0,0,&_44c9_s_p4_0},
  136186. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  136187. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  136188. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  136189. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  136190. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  136191. }
  136192. };
  136193. static vorbis_residue_template _res_44s_n1[]={
  136194. {2,0, &_residue_44_low,
  136195. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  136196. &_resbook_44s_n1,&_resbook_44sm_n1},
  136197. {2,0, &_residue_44_low,
  136198. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  136199. &_resbook_44s_n1,&_resbook_44sm_n1}
  136200. };
  136201. static vorbis_residue_template _res_44s_0[]={
  136202. {2,0, &_residue_44_low,
  136203. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  136204. &_resbook_44s_0,&_resbook_44sm_0},
  136205. {2,0, &_residue_44_low,
  136206. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  136207. &_resbook_44s_0,&_resbook_44sm_0}
  136208. };
  136209. static vorbis_residue_template _res_44s_1[]={
  136210. {2,0, &_residue_44_low,
  136211. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  136212. &_resbook_44s_1,&_resbook_44sm_1},
  136213. {2,0, &_residue_44_low,
  136214. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  136215. &_resbook_44s_1,&_resbook_44sm_1}
  136216. };
  136217. static vorbis_residue_template _res_44s_2[]={
  136218. {2,0, &_residue_44_mid,
  136219. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  136220. &_resbook_44s_2,&_resbook_44s_2},
  136221. {2,0, &_residue_44_mid,
  136222. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  136223. &_resbook_44s_2,&_resbook_44s_2}
  136224. };
  136225. static vorbis_residue_template _res_44s_3[]={
  136226. {2,0, &_residue_44_mid,
  136227. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  136228. &_resbook_44s_3,&_resbook_44s_3},
  136229. {2,0, &_residue_44_mid,
  136230. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  136231. &_resbook_44s_3,&_resbook_44s_3}
  136232. };
  136233. static vorbis_residue_template _res_44s_4[]={
  136234. {2,0, &_residue_44_mid,
  136235. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  136236. &_resbook_44s_4,&_resbook_44s_4},
  136237. {2,0, &_residue_44_mid,
  136238. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  136239. &_resbook_44s_4,&_resbook_44s_4}
  136240. };
  136241. static vorbis_residue_template _res_44s_5[]={
  136242. {2,0, &_residue_44_mid,
  136243. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  136244. &_resbook_44s_5,&_resbook_44s_5},
  136245. {2,0, &_residue_44_mid,
  136246. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  136247. &_resbook_44s_5,&_resbook_44s_5}
  136248. };
  136249. static vorbis_residue_template _res_44s_6[]={
  136250. {2,0, &_residue_44_high,
  136251. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  136252. &_resbook_44s_6,&_resbook_44s_6},
  136253. {2,0, &_residue_44_high,
  136254. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  136255. &_resbook_44s_6,&_resbook_44s_6}
  136256. };
  136257. static vorbis_residue_template _res_44s_7[]={
  136258. {2,0, &_residue_44_high,
  136259. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  136260. &_resbook_44s_7,&_resbook_44s_7},
  136261. {2,0, &_residue_44_high,
  136262. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  136263. &_resbook_44s_7,&_resbook_44s_7}
  136264. };
  136265. static vorbis_residue_template _res_44s_8[]={
  136266. {2,0, &_residue_44_high,
  136267. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  136268. &_resbook_44s_8,&_resbook_44s_8},
  136269. {2,0, &_residue_44_high,
  136270. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  136271. &_resbook_44s_8,&_resbook_44s_8}
  136272. };
  136273. static vorbis_residue_template _res_44s_9[]={
  136274. {2,0, &_residue_44_high,
  136275. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  136276. &_resbook_44s_9,&_resbook_44s_9},
  136277. {2,0, &_residue_44_high,
  136278. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  136279. &_resbook_44s_9,&_resbook_44s_9}
  136280. };
  136281. static vorbis_mapping_template _mapres_template_44_stereo[]={
  136282. { _map_nominal, _res_44s_n1 }, /* -1 */
  136283. { _map_nominal, _res_44s_0 }, /* 0 */
  136284. { _map_nominal, _res_44s_1 }, /* 1 */
  136285. { _map_nominal, _res_44s_2 }, /* 2 */
  136286. { _map_nominal, _res_44s_3 }, /* 3 */
  136287. { _map_nominal, _res_44s_4 }, /* 4 */
  136288. { _map_nominal, _res_44s_5 }, /* 5 */
  136289. { _map_nominal, _res_44s_6 }, /* 6 */
  136290. { _map_nominal, _res_44s_7 }, /* 7 */
  136291. { _map_nominal, _res_44s_8 }, /* 8 */
  136292. { _map_nominal, _res_44s_9 }, /* 9 */
  136293. };
  136294. /********* End of inlined file: residue_44.h *********/
  136295. /********* Start of inlined file: psych_44.h *********/
  136296. /* preecho trigger settings *****************************************/
  136297. static vorbis_info_psy_global _psy_global_44[5]={
  136298. {8, /* lines per eighth octave */
  136299. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  136300. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  136301. -6.f,
  136302. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  136303. },
  136304. {8, /* lines per eighth octave */
  136305. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  136306. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  136307. -6.f,
  136308. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  136309. },
  136310. {8, /* lines per eighth octave */
  136311. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  136312. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  136313. -6.f,
  136314. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  136315. },
  136316. {8, /* lines per eighth octave */
  136317. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  136318. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  136319. -6.f,
  136320. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  136321. },
  136322. {8, /* lines per eighth octave */
  136323. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  136324. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  136325. -6.f,
  136326. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  136327. },
  136328. };
  136329. /* noise compander lookups * low, mid, high quality ****************/
  136330. static compandblock _psy_compand_44[6]={
  136331. /* sub-mode Z short */
  136332. {{
  136333. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  136334. 8, 9,10,11,12,13,14, 15, /* 15dB */
  136335. 16,17,18,19,20,21,22, 23, /* 23dB */
  136336. 24,25,26,27,28,29,30, 31, /* 31dB */
  136337. 32,33,34,35,36,37,38, 39, /* 39dB */
  136338. }},
  136339. /* mode_Z nominal short */
  136340. {{
  136341. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  136342. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  136343. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  136344. 15,16,17,17,17,18,18, 19, /* 31dB */
  136345. 19,19,20,21,22,23,24, 25, /* 39dB */
  136346. }},
  136347. /* mode A short */
  136348. {{
  136349. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  136350. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  136351. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  136352. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  136353. 11,12,13,14,15,16,17, 18, /* 39dB */
  136354. }},
  136355. /* sub-mode Z long */
  136356. {{
  136357. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  136358. 8, 9,10,11,12,13,14, 15, /* 15dB */
  136359. 16,17,18,19,20,21,22, 23, /* 23dB */
  136360. 24,25,26,27,28,29,30, 31, /* 31dB */
  136361. 32,33,34,35,36,37,38, 39, /* 39dB */
  136362. }},
  136363. /* mode_Z nominal long */
  136364. {{
  136365. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  136366. 8, 9,10,11,12,12,13, 13, /* 15dB */
  136367. 13,14,14,14,15,15,15, 15, /* 23dB */
  136368. 16,16,17,17,17,18,18, 19, /* 31dB */
  136369. 19,19,20,21,22,23,24, 25, /* 39dB */
  136370. }},
  136371. /* mode A long */
  136372. {{
  136373. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  136374. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  136375. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  136376. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  136377. 11,12,13,14,15,16,17, 18, /* 39dB */
  136378. }}
  136379. };
  136380. /* tonal masking curve level adjustments *************************/
  136381. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  136382. /* 63 125 250 500 1 2 4 8 16 */
  136383. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  136384. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  136385. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  136386. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  136387. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  136388. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  136389. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  136390. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  136391. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  136392. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  136393. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  136394. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  136395. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  136396. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  136397. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  136398. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  136399. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  136400. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  136401. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  136402. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  136403. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  136404. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  136405. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  136406. };
  136407. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  136408. /* 63 125 250 500 1 2 4 8 16 */
  136409. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  136410. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  136411. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  136412. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  136413. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  136414. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  136415. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  136416. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  136417. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  136418. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  136419. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  136420. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  136421. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  136422. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  136423. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  136424. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  136425. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  136426. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  136427. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  136428. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  136429. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  136430. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  136431. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  136432. };
  136433. /* noise bias (transition block) */
  136434. static noise3 _psy_noisebias_trans[12]={
  136435. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  136436. /* -1 */
  136437. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  136438. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  136439. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  136440. /* 0
  136441. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136442. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  136443. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  136444. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136445. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  136446. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  136447. /* 1
  136448. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136449. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  136450. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  136451. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136452. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  136453. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  136454. /* 2
  136455. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  136456. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  136457. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  136458. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  136459. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  136460. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  136461. /* 3
  136462. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  136463. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  136464. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  136465. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  136466. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  136467. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  136468. /* 4
  136469. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136470. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  136471. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  136472. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136473. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  136474. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  136475. /* 5
  136476. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136477. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  136478. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  136479. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136480. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  136481. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  136482. /* 6
  136483. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136484. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  136485. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  136486. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136487. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  136488. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  136489. /* 7
  136490. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136491. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  136492. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  136493. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136494. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  136495. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  136496. /* 8
  136497. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  136498. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  136499. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  136500. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  136501. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  136502. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  136503. /* 9
  136504. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  136505. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  136506. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  136507. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  136508. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  136509. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  136510. /* 10 */
  136511. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  136512. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  136513. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  136514. };
  136515. /* noise bias (long block) */
  136516. static noise3 _psy_noisebias_long[12]={
  136517. /*63 125 250 500 1k 2k 4k 8k 16k*/
  136518. /* -1 */
  136519. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  136520. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  136521. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  136522. /* 0 */
  136523. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  136524. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  136525. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  136526. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  136527. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  136528. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  136529. /* 1 */
  136530. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136531. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  136532. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  136533. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136534. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  136535. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  136536. /* 2 */
  136537. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  136538. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  136539. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  136540. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  136541. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  136542. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  136543. /* 3 */
  136544. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  136545. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  136546. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  136547. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  136548. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  136549. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  136550. /* 4 */
  136551. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136552. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  136553. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  136554. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136555. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  136556. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  136557. /* 5 */
  136558. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136559. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  136560. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  136561. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136562. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  136563. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  136564. /* 6 */
  136565. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136566. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  136567. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  136568. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136569. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  136570. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  136571. /* 7 */
  136572. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136573. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  136574. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  136575. /* 8 */
  136576. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  136577. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  136578. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  136579. /* 9 */
  136580. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  136581. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  136582. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  136583. /* 10 */
  136584. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  136585. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  136586. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  136587. };
  136588. /* noise bias (impulse block) */
  136589. static noise3 _psy_noisebias_impulse[12]={
  136590. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  136591. /* -1 */
  136592. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  136593. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  136594. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  136595. /* 0 */
  136596. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  136597. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  136598. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  136599. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  136600. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  136601. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  136602. /* 1 */
  136603. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  136604. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  136605. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  136606. /* 2 */
  136607. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  136608. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  136609. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  136610. /* 3 */
  136611. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  136612. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  136613. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  136614. /* 4 */
  136615. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  136616. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  136617. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  136618. /* 5 */
  136619. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  136620. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  136621. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  136622. /* 6
  136623. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  136624. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  136625. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  136626. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  136627. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  136628. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  136629. /* 7 */
  136630. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  136631. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  136632. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  136633. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  136634. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  136635. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  136636. /* 8 */
  136637. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  136638. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  136639. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  136640. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  136641. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  136642. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  136643. /* 9 */
  136644. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  136645. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  136646. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  136647. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  136648. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  136649. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  136650. /* 10 */
  136651. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  136652. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  136653. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  136654. };
  136655. /* noise bias (padding block) */
  136656. static noise3 _psy_noisebias_padding[12]={
  136657. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  136658. /* -1 */
  136659. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  136660. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  136661. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  136662. /* 0 */
  136663. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  136664. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  136665. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  136666. /* 1 */
  136667. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  136668. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  136669. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  136670. /* 2 */
  136671. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  136672. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  136673. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  136674. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  136675. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  136676. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  136677. /* 3 */
  136678. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  136679. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  136680. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  136681. /* 4 */
  136682. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  136683. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  136684. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  136685. /* 5 */
  136686. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  136687. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  136688. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  136689. /* 6 */
  136690. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  136691. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  136692. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  136693. /* 7 */
  136694. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  136695. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  136696. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  136697. /* 8 */
  136698. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  136699. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  136700. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  136701. /* 9 */
  136702. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  136703. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  136704. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  136705. /* 10 */
  136706. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  136707. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  136708. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  136709. };
  136710. static noiseguard _psy_noiseguards_44[4]={
  136711. {3,3,15},
  136712. {3,3,15},
  136713. {10,10,100},
  136714. {10,10,100},
  136715. };
  136716. static int _psy_tone_suppress[12]={
  136717. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  136718. };
  136719. static int _psy_tone_0dB[12]={
  136720. 90,90,95,95,95,95,105,105,105,105,105,105,
  136721. };
  136722. static int _psy_noise_suppress[12]={
  136723. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  136724. };
  136725. static vorbis_info_psy _psy_info_template={
  136726. /* blockflag */
  136727. -1,
  136728. /* ath_adjatt, ath_maxatt */
  136729. -140.,-140.,
  136730. /* tonemask att boost/decay,suppr,curves */
  136731. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  136732. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  136733. 1, -0.f, .5f, .5f, 0,0,0,
  136734. /* noiseoffset*3, noisecompand, max_curve_dB */
  136735. {{-1},{-1},{-1}},{-1},105.f,
  136736. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  136737. 0,0,-1,-1,0.,
  136738. };
  136739. /* ath ****************/
  136740. static int _psy_ath_floater[12]={
  136741. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  136742. };
  136743. static int _psy_ath_abs[12]={
  136744. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  136745. };
  136746. /* stereo setup. These don't map directly to quality level, there's
  136747. an additional indirection as several of the below may be used in a
  136748. single bitmanaged stream
  136749. ****************/
  136750. /* various stereo possibilities */
  136751. /* stereo mode by base quality level */
  136752. static adj_stereo _psy_stereo_modes_44[12]={
  136753. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  136754. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  136755. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  136756. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  136757. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  136758. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  136759. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  136760. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  136761. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  136762. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136763. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  136764. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  136765. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136766. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  136767. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  136768. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  136769. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  136770. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136771. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136772. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  136773. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  136774. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  136775. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136776. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  136777. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  136778. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  136779. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136780. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136781. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  136782. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  136783. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  136784. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  136785. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136786. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  136787. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136788. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  136789. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  136790. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136791. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  136792. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136793. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  136794. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136795. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136796. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136797. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  136798. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  136799. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136800. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  136801. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136802. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136803. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136804. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  136805. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136806. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136807. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  136808. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136809. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  136810. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136811. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136812. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136813. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136814. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136815. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136816. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  136817. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136818. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  136819. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136820. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136821. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136822. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136823. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136824. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136825. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  136826. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136827. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  136828. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136829. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136830. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  136831. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136832. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  136833. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136834. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136835. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  136836. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136837. };
  136838. /* tone master attenuation by base quality mode and bitrate tweak */
  136839. static att3 _psy_tone_masteratt_44[12]={
  136840. {{ 35, 21, 9}, 0, 0}, /* -1 */
  136841. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  136842. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  136843. {{ 25, 12, 2}, 0, 0}, /* 1 */
  136844. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  136845. {{ 20, 9, -3}, 0, 0}, /* 2 */
  136846. {{ 20, 9, -4}, 0, 0}, /* 3 */
  136847. {{ 20, 9, -4}, 0, 0}, /* 4 */
  136848. {{ 20, 6, -6}, 0, 0}, /* 5 */
  136849. {{ 20, 3, -10}, 0, 0}, /* 6 */
  136850. {{ 18, 1, -14}, 0, 0}, /* 7 */
  136851. {{ 18, 0, -16}, 0, 0}, /* 8 */
  136852. {{ 18, -2, -16}, 0, 0}, /* 9 */
  136853. {{ 12, -2, -20}, 0, 0}, /* 10 */
  136854. };
  136855. /* lowpass by mode **************/
  136856. static double _psy_lowpass_44[12]={
  136857. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  136858. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  136859. };
  136860. /* noise normalization **********/
  136861. static int _noise_start_short_44[11]={
  136862. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  136863. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  136864. };
  136865. static int _noise_start_long_44[11]={
  136866. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  136867. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  136868. };
  136869. static int _noise_part_short_44[11]={
  136870. 8,8,8,8,8,8,8,8,8,8,8
  136871. };
  136872. static int _noise_part_long_44[11]={
  136873. 32,32,32,32,32,32,32,32,32,32,32
  136874. };
  136875. static double _noise_thresh_44[11]={
  136876. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  136877. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  136878. };
  136879. static double _noise_thresh_5only[2]={
  136880. .5,.5,
  136881. };
  136882. /********* End of inlined file: psych_44.h *********/
  136883. static double rate_mapping_44_stereo[12]={
  136884. 22500.,32000.,40000.,48000.,56000.,64000.,
  136885. 80000.,96000.,112000.,128000.,160000.,250001.
  136886. };
  136887. static double quality_mapping_44[12]={
  136888. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  136889. };
  136890. static int blocksize_short_44[11]={
  136891. 512,256,256,256,256,256,256,256,256,256,256
  136892. };
  136893. static int blocksize_long_44[11]={
  136894. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  136895. };
  136896. static double _psy_compand_short_mapping[12]={
  136897. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  136898. };
  136899. static double _psy_compand_long_mapping[12]={
  136900. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  136901. };
  136902. static double _global_mapping_44[12]={
  136903. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  136904. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  136905. };
  136906. static int _floor_short_mapping_44[11]={
  136907. 1,0,0,2,2,4,5,5,5,5,5
  136908. };
  136909. static int _floor_long_mapping_44[11]={
  136910. 8,7,7,7,7,7,7,7,7,7,7
  136911. };
  136912. ve_setup_data_template ve_setup_44_stereo={
  136913. 11,
  136914. rate_mapping_44_stereo,
  136915. quality_mapping_44,
  136916. 2,
  136917. 40000,
  136918. 50000,
  136919. blocksize_short_44,
  136920. blocksize_long_44,
  136921. _psy_tone_masteratt_44,
  136922. _psy_tone_0dB,
  136923. _psy_tone_suppress,
  136924. _vp_tonemask_adj_otherblock,
  136925. _vp_tonemask_adj_longblock,
  136926. _vp_tonemask_adj_otherblock,
  136927. _psy_noiseguards_44,
  136928. _psy_noisebias_impulse,
  136929. _psy_noisebias_padding,
  136930. _psy_noisebias_trans,
  136931. _psy_noisebias_long,
  136932. _psy_noise_suppress,
  136933. _psy_compand_44,
  136934. _psy_compand_short_mapping,
  136935. _psy_compand_long_mapping,
  136936. {_noise_start_short_44,_noise_start_long_44},
  136937. {_noise_part_short_44,_noise_part_long_44},
  136938. _noise_thresh_44,
  136939. _psy_ath_floater,
  136940. _psy_ath_abs,
  136941. _psy_lowpass_44,
  136942. _psy_global_44,
  136943. _global_mapping_44,
  136944. _psy_stereo_modes_44,
  136945. _floor_books,
  136946. _floor,
  136947. _floor_short_mapping_44,
  136948. _floor_long_mapping_44,
  136949. _mapres_template_44_stereo
  136950. };
  136951. /********* End of inlined file: setup_44.h *********/
  136952. /********* Start of inlined file: setup_44u.h *********/
  136953. /********* Start of inlined file: residue_44u.h *********/
  136954. /********* Start of inlined file: res_books_uncoupled.h *********/
  136955. static long _vq_quantlist__16u0__p1_0[] = {
  136956. 1,
  136957. 0,
  136958. 2,
  136959. };
  136960. static long _vq_lengthlist__16u0__p1_0[] = {
  136961. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  136962. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  136963. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  136964. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  136965. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  136966. 12,
  136967. };
  136968. static float _vq_quantthresh__16u0__p1_0[] = {
  136969. -0.5, 0.5,
  136970. };
  136971. static long _vq_quantmap__16u0__p1_0[] = {
  136972. 1, 0, 2,
  136973. };
  136974. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  136975. _vq_quantthresh__16u0__p1_0,
  136976. _vq_quantmap__16u0__p1_0,
  136977. 3,
  136978. 3
  136979. };
  136980. static static_codebook _16u0__p1_0 = {
  136981. 4, 81,
  136982. _vq_lengthlist__16u0__p1_0,
  136983. 1, -535822336, 1611661312, 2, 0,
  136984. _vq_quantlist__16u0__p1_0,
  136985. NULL,
  136986. &_vq_auxt__16u0__p1_0,
  136987. NULL,
  136988. 0
  136989. };
  136990. static long _vq_quantlist__16u0__p2_0[] = {
  136991. 1,
  136992. 0,
  136993. 2,
  136994. };
  136995. static long _vq_lengthlist__16u0__p2_0[] = {
  136996. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  136997. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  136998. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  136999. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  137000. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  137001. 8,
  137002. };
  137003. static float _vq_quantthresh__16u0__p2_0[] = {
  137004. -0.5, 0.5,
  137005. };
  137006. static long _vq_quantmap__16u0__p2_0[] = {
  137007. 1, 0, 2,
  137008. };
  137009. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  137010. _vq_quantthresh__16u0__p2_0,
  137011. _vq_quantmap__16u0__p2_0,
  137012. 3,
  137013. 3
  137014. };
  137015. static static_codebook _16u0__p2_0 = {
  137016. 4, 81,
  137017. _vq_lengthlist__16u0__p2_0,
  137018. 1, -535822336, 1611661312, 2, 0,
  137019. _vq_quantlist__16u0__p2_0,
  137020. NULL,
  137021. &_vq_auxt__16u0__p2_0,
  137022. NULL,
  137023. 0
  137024. };
  137025. static long _vq_quantlist__16u0__p3_0[] = {
  137026. 2,
  137027. 1,
  137028. 3,
  137029. 0,
  137030. 4,
  137031. };
  137032. static long _vq_lengthlist__16u0__p3_0[] = {
  137033. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  137034. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  137035. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  137036. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  137037. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  137038. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  137039. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  137040. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  137041. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  137042. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  137043. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  137044. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  137045. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  137046. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  137047. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  137048. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  137049. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  137050. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  137051. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  137052. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  137053. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  137054. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  137055. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  137056. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  137057. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  137058. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  137059. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  137060. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  137061. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  137062. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  137063. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  137064. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  137065. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  137066. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  137067. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  137068. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  137069. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  137070. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  137071. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  137072. 18,
  137073. };
  137074. static float _vq_quantthresh__16u0__p3_0[] = {
  137075. -1.5, -0.5, 0.5, 1.5,
  137076. };
  137077. static long _vq_quantmap__16u0__p3_0[] = {
  137078. 3, 1, 0, 2, 4,
  137079. };
  137080. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  137081. _vq_quantthresh__16u0__p3_0,
  137082. _vq_quantmap__16u0__p3_0,
  137083. 5,
  137084. 5
  137085. };
  137086. static static_codebook _16u0__p3_0 = {
  137087. 4, 625,
  137088. _vq_lengthlist__16u0__p3_0,
  137089. 1, -533725184, 1611661312, 3, 0,
  137090. _vq_quantlist__16u0__p3_0,
  137091. NULL,
  137092. &_vq_auxt__16u0__p3_0,
  137093. NULL,
  137094. 0
  137095. };
  137096. static long _vq_quantlist__16u0__p4_0[] = {
  137097. 2,
  137098. 1,
  137099. 3,
  137100. 0,
  137101. 4,
  137102. };
  137103. static long _vq_lengthlist__16u0__p4_0[] = {
  137104. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  137105. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  137106. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  137107. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  137108. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  137109. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  137110. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  137111. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  137112. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  137113. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  137114. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  137115. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  137116. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  137117. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  137118. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  137119. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  137120. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  137121. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  137122. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  137123. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  137124. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  137125. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  137126. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  137127. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  137128. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  137129. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  137130. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  137131. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  137132. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  137133. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  137134. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  137135. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  137136. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  137137. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  137138. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  137139. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  137140. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  137141. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  137142. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  137143. 11,
  137144. };
  137145. static float _vq_quantthresh__16u0__p4_0[] = {
  137146. -1.5, -0.5, 0.5, 1.5,
  137147. };
  137148. static long _vq_quantmap__16u0__p4_0[] = {
  137149. 3, 1, 0, 2, 4,
  137150. };
  137151. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  137152. _vq_quantthresh__16u0__p4_0,
  137153. _vq_quantmap__16u0__p4_0,
  137154. 5,
  137155. 5
  137156. };
  137157. static static_codebook _16u0__p4_0 = {
  137158. 4, 625,
  137159. _vq_lengthlist__16u0__p4_0,
  137160. 1, -533725184, 1611661312, 3, 0,
  137161. _vq_quantlist__16u0__p4_0,
  137162. NULL,
  137163. &_vq_auxt__16u0__p4_0,
  137164. NULL,
  137165. 0
  137166. };
  137167. static long _vq_quantlist__16u0__p5_0[] = {
  137168. 4,
  137169. 3,
  137170. 5,
  137171. 2,
  137172. 6,
  137173. 1,
  137174. 7,
  137175. 0,
  137176. 8,
  137177. };
  137178. static long _vq_lengthlist__16u0__p5_0[] = {
  137179. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  137180. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  137181. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  137182. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  137183. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  137184. 12,
  137185. };
  137186. static float _vq_quantthresh__16u0__p5_0[] = {
  137187. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137188. };
  137189. static long _vq_quantmap__16u0__p5_0[] = {
  137190. 7, 5, 3, 1, 0, 2, 4, 6,
  137191. 8,
  137192. };
  137193. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  137194. _vq_quantthresh__16u0__p5_0,
  137195. _vq_quantmap__16u0__p5_0,
  137196. 9,
  137197. 9
  137198. };
  137199. static static_codebook _16u0__p5_0 = {
  137200. 2, 81,
  137201. _vq_lengthlist__16u0__p5_0,
  137202. 1, -531628032, 1611661312, 4, 0,
  137203. _vq_quantlist__16u0__p5_0,
  137204. NULL,
  137205. &_vq_auxt__16u0__p5_0,
  137206. NULL,
  137207. 0
  137208. };
  137209. static long _vq_quantlist__16u0__p6_0[] = {
  137210. 6,
  137211. 5,
  137212. 7,
  137213. 4,
  137214. 8,
  137215. 3,
  137216. 9,
  137217. 2,
  137218. 10,
  137219. 1,
  137220. 11,
  137221. 0,
  137222. 12,
  137223. };
  137224. static long _vq_lengthlist__16u0__p6_0[] = {
  137225. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  137226. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  137227. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  137228. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  137229. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  137230. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  137231. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  137232. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  137233. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  137234. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  137235. 18, 0,19, 0, 0, 0, 0, 0, 0,
  137236. };
  137237. static float _vq_quantthresh__16u0__p6_0[] = {
  137238. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137239. 12.5, 17.5, 22.5, 27.5,
  137240. };
  137241. static long _vq_quantmap__16u0__p6_0[] = {
  137242. 11, 9, 7, 5, 3, 1, 0, 2,
  137243. 4, 6, 8, 10, 12,
  137244. };
  137245. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  137246. _vq_quantthresh__16u0__p6_0,
  137247. _vq_quantmap__16u0__p6_0,
  137248. 13,
  137249. 13
  137250. };
  137251. static static_codebook _16u0__p6_0 = {
  137252. 2, 169,
  137253. _vq_lengthlist__16u0__p6_0,
  137254. 1, -526516224, 1616117760, 4, 0,
  137255. _vq_quantlist__16u0__p6_0,
  137256. NULL,
  137257. &_vq_auxt__16u0__p6_0,
  137258. NULL,
  137259. 0
  137260. };
  137261. static long _vq_quantlist__16u0__p6_1[] = {
  137262. 2,
  137263. 1,
  137264. 3,
  137265. 0,
  137266. 4,
  137267. };
  137268. static long _vq_lengthlist__16u0__p6_1[] = {
  137269. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  137270. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  137271. };
  137272. static float _vq_quantthresh__16u0__p6_1[] = {
  137273. -1.5, -0.5, 0.5, 1.5,
  137274. };
  137275. static long _vq_quantmap__16u0__p6_1[] = {
  137276. 3, 1, 0, 2, 4,
  137277. };
  137278. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  137279. _vq_quantthresh__16u0__p6_1,
  137280. _vq_quantmap__16u0__p6_1,
  137281. 5,
  137282. 5
  137283. };
  137284. static static_codebook _16u0__p6_1 = {
  137285. 2, 25,
  137286. _vq_lengthlist__16u0__p6_1,
  137287. 1, -533725184, 1611661312, 3, 0,
  137288. _vq_quantlist__16u0__p6_1,
  137289. NULL,
  137290. &_vq_auxt__16u0__p6_1,
  137291. NULL,
  137292. 0
  137293. };
  137294. static long _vq_quantlist__16u0__p7_0[] = {
  137295. 1,
  137296. 0,
  137297. 2,
  137298. };
  137299. static long _vq_lengthlist__16u0__p7_0[] = {
  137300. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  137301. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  137302. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  137303. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  137304. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  137305. 7,
  137306. };
  137307. static float _vq_quantthresh__16u0__p7_0[] = {
  137308. -157.5, 157.5,
  137309. };
  137310. static long _vq_quantmap__16u0__p7_0[] = {
  137311. 1, 0, 2,
  137312. };
  137313. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  137314. _vq_quantthresh__16u0__p7_0,
  137315. _vq_quantmap__16u0__p7_0,
  137316. 3,
  137317. 3
  137318. };
  137319. static static_codebook _16u0__p7_0 = {
  137320. 4, 81,
  137321. _vq_lengthlist__16u0__p7_0,
  137322. 1, -518803456, 1628680192, 2, 0,
  137323. _vq_quantlist__16u0__p7_0,
  137324. NULL,
  137325. &_vq_auxt__16u0__p7_0,
  137326. NULL,
  137327. 0
  137328. };
  137329. static long _vq_quantlist__16u0__p7_1[] = {
  137330. 7,
  137331. 6,
  137332. 8,
  137333. 5,
  137334. 9,
  137335. 4,
  137336. 10,
  137337. 3,
  137338. 11,
  137339. 2,
  137340. 12,
  137341. 1,
  137342. 13,
  137343. 0,
  137344. 14,
  137345. };
  137346. static long _vq_lengthlist__16u0__p7_1[] = {
  137347. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  137348. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  137349. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  137350. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  137351. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  137352. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  137353. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137354. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137355. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137356. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137357. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137358. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137359. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137360. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137361. 10,
  137362. };
  137363. static float _vq_quantthresh__16u0__p7_1[] = {
  137364. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  137365. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  137366. };
  137367. static long _vq_quantmap__16u0__p7_1[] = {
  137368. 13, 11, 9, 7, 5, 3, 1, 0,
  137369. 2, 4, 6, 8, 10, 12, 14,
  137370. };
  137371. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  137372. _vq_quantthresh__16u0__p7_1,
  137373. _vq_quantmap__16u0__p7_1,
  137374. 15,
  137375. 15
  137376. };
  137377. static static_codebook _16u0__p7_1 = {
  137378. 2, 225,
  137379. _vq_lengthlist__16u0__p7_1,
  137380. 1, -520986624, 1620377600, 4, 0,
  137381. _vq_quantlist__16u0__p7_1,
  137382. NULL,
  137383. &_vq_auxt__16u0__p7_1,
  137384. NULL,
  137385. 0
  137386. };
  137387. static long _vq_quantlist__16u0__p7_2[] = {
  137388. 10,
  137389. 9,
  137390. 11,
  137391. 8,
  137392. 12,
  137393. 7,
  137394. 13,
  137395. 6,
  137396. 14,
  137397. 5,
  137398. 15,
  137399. 4,
  137400. 16,
  137401. 3,
  137402. 17,
  137403. 2,
  137404. 18,
  137405. 1,
  137406. 19,
  137407. 0,
  137408. 20,
  137409. };
  137410. static long _vq_lengthlist__16u0__p7_2[] = {
  137411. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  137412. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  137413. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  137414. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  137415. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  137416. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  137417. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  137418. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  137419. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  137420. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  137421. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  137422. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  137423. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  137424. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  137425. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  137426. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  137427. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  137428. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  137429. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  137430. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  137431. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  137432. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  137433. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  137434. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  137435. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  137436. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  137437. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  137438. 10,10,12,11,10,11,11,11,10,
  137439. };
  137440. static float _vq_quantthresh__16u0__p7_2[] = {
  137441. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  137442. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  137443. 6.5, 7.5, 8.5, 9.5,
  137444. };
  137445. static long _vq_quantmap__16u0__p7_2[] = {
  137446. 19, 17, 15, 13, 11, 9, 7, 5,
  137447. 3, 1, 0, 2, 4, 6, 8, 10,
  137448. 12, 14, 16, 18, 20,
  137449. };
  137450. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  137451. _vq_quantthresh__16u0__p7_2,
  137452. _vq_quantmap__16u0__p7_2,
  137453. 21,
  137454. 21
  137455. };
  137456. static static_codebook _16u0__p7_2 = {
  137457. 2, 441,
  137458. _vq_lengthlist__16u0__p7_2,
  137459. 1, -529268736, 1611661312, 5, 0,
  137460. _vq_quantlist__16u0__p7_2,
  137461. NULL,
  137462. &_vq_auxt__16u0__p7_2,
  137463. NULL,
  137464. 0
  137465. };
  137466. static long _huff_lengthlist__16u0__single[] = {
  137467. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  137468. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  137469. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  137470. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  137471. };
  137472. static static_codebook _huff_book__16u0__single = {
  137473. 2, 64,
  137474. _huff_lengthlist__16u0__single,
  137475. 0, 0, 0, 0, 0,
  137476. NULL,
  137477. NULL,
  137478. NULL,
  137479. NULL,
  137480. 0
  137481. };
  137482. static long _huff_lengthlist__16u1__long[] = {
  137483. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  137484. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  137485. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  137486. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  137487. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  137488. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  137489. 16,13,16,18,
  137490. };
  137491. static static_codebook _huff_book__16u1__long = {
  137492. 2, 100,
  137493. _huff_lengthlist__16u1__long,
  137494. 0, 0, 0, 0, 0,
  137495. NULL,
  137496. NULL,
  137497. NULL,
  137498. NULL,
  137499. 0
  137500. };
  137501. static long _vq_quantlist__16u1__p1_0[] = {
  137502. 1,
  137503. 0,
  137504. 2,
  137505. };
  137506. static long _vq_lengthlist__16u1__p1_0[] = {
  137507. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  137508. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  137509. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  137510. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  137511. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  137512. 11,
  137513. };
  137514. static float _vq_quantthresh__16u1__p1_0[] = {
  137515. -0.5, 0.5,
  137516. };
  137517. static long _vq_quantmap__16u1__p1_0[] = {
  137518. 1, 0, 2,
  137519. };
  137520. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  137521. _vq_quantthresh__16u1__p1_0,
  137522. _vq_quantmap__16u1__p1_0,
  137523. 3,
  137524. 3
  137525. };
  137526. static static_codebook _16u1__p1_0 = {
  137527. 4, 81,
  137528. _vq_lengthlist__16u1__p1_0,
  137529. 1, -535822336, 1611661312, 2, 0,
  137530. _vq_quantlist__16u1__p1_0,
  137531. NULL,
  137532. &_vq_auxt__16u1__p1_0,
  137533. NULL,
  137534. 0
  137535. };
  137536. static long _vq_quantlist__16u1__p2_0[] = {
  137537. 1,
  137538. 0,
  137539. 2,
  137540. };
  137541. static long _vq_lengthlist__16u1__p2_0[] = {
  137542. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  137543. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  137544. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  137545. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  137546. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  137547. 8,
  137548. };
  137549. static float _vq_quantthresh__16u1__p2_0[] = {
  137550. -0.5, 0.5,
  137551. };
  137552. static long _vq_quantmap__16u1__p2_0[] = {
  137553. 1, 0, 2,
  137554. };
  137555. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  137556. _vq_quantthresh__16u1__p2_0,
  137557. _vq_quantmap__16u1__p2_0,
  137558. 3,
  137559. 3
  137560. };
  137561. static static_codebook _16u1__p2_0 = {
  137562. 4, 81,
  137563. _vq_lengthlist__16u1__p2_0,
  137564. 1, -535822336, 1611661312, 2, 0,
  137565. _vq_quantlist__16u1__p2_0,
  137566. NULL,
  137567. &_vq_auxt__16u1__p2_0,
  137568. NULL,
  137569. 0
  137570. };
  137571. static long _vq_quantlist__16u1__p3_0[] = {
  137572. 2,
  137573. 1,
  137574. 3,
  137575. 0,
  137576. 4,
  137577. };
  137578. static long _vq_lengthlist__16u1__p3_0[] = {
  137579. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  137580. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  137581. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  137582. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  137583. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  137584. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  137585. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  137586. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  137587. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  137588. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  137589. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  137590. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  137591. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  137592. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  137593. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  137594. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  137595. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  137596. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  137597. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  137598. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  137599. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  137600. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  137601. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  137602. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  137603. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  137604. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  137605. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  137606. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  137607. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  137608. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  137609. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  137610. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  137611. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  137612. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  137613. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  137614. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  137615. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  137616. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  137617. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  137618. 16,
  137619. };
  137620. static float _vq_quantthresh__16u1__p3_0[] = {
  137621. -1.5, -0.5, 0.5, 1.5,
  137622. };
  137623. static long _vq_quantmap__16u1__p3_0[] = {
  137624. 3, 1, 0, 2, 4,
  137625. };
  137626. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  137627. _vq_quantthresh__16u1__p3_0,
  137628. _vq_quantmap__16u1__p3_0,
  137629. 5,
  137630. 5
  137631. };
  137632. static static_codebook _16u1__p3_0 = {
  137633. 4, 625,
  137634. _vq_lengthlist__16u1__p3_0,
  137635. 1, -533725184, 1611661312, 3, 0,
  137636. _vq_quantlist__16u1__p3_0,
  137637. NULL,
  137638. &_vq_auxt__16u1__p3_0,
  137639. NULL,
  137640. 0
  137641. };
  137642. static long _vq_quantlist__16u1__p4_0[] = {
  137643. 2,
  137644. 1,
  137645. 3,
  137646. 0,
  137647. 4,
  137648. };
  137649. static long _vq_lengthlist__16u1__p4_0[] = {
  137650. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  137651. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  137652. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  137653. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  137654. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  137655. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  137656. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  137657. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  137658. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  137659. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  137660. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  137661. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  137662. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  137663. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  137664. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  137665. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  137666. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  137667. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  137668. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  137669. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  137670. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  137671. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  137672. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  137673. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  137674. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  137675. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  137676. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  137677. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  137678. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  137679. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  137680. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  137681. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  137682. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  137683. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  137684. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  137685. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  137686. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  137687. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  137688. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  137689. 11,
  137690. };
  137691. static float _vq_quantthresh__16u1__p4_0[] = {
  137692. -1.5, -0.5, 0.5, 1.5,
  137693. };
  137694. static long _vq_quantmap__16u1__p4_0[] = {
  137695. 3, 1, 0, 2, 4,
  137696. };
  137697. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  137698. _vq_quantthresh__16u1__p4_0,
  137699. _vq_quantmap__16u1__p4_0,
  137700. 5,
  137701. 5
  137702. };
  137703. static static_codebook _16u1__p4_0 = {
  137704. 4, 625,
  137705. _vq_lengthlist__16u1__p4_0,
  137706. 1, -533725184, 1611661312, 3, 0,
  137707. _vq_quantlist__16u1__p4_0,
  137708. NULL,
  137709. &_vq_auxt__16u1__p4_0,
  137710. NULL,
  137711. 0
  137712. };
  137713. static long _vq_quantlist__16u1__p5_0[] = {
  137714. 4,
  137715. 3,
  137716. 5,
  137717. 2,
  137718. 6,
  137719. 1,
  137720. 7,
  137721. 0,
  137722. 8,
  137723. };
  137724. static long _vq_lengthlist__16u1__p5_0[] = {
  137725. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  137726. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  137727. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  137728. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  137729. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  137730. 13,
  137731. };
  137732. static float _vq_quantthresh__16u1__p5_0[] = {
  137733. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137734. };
  137735. static long _vq_quantmap__16u1__p5_0[] = {
  137736. 7, 5, 3, 1, 0, 2, 4, 6,
  137737. 8,
  137738. };
  137739. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  137740. _vq_quantthresh__16u1__p5_0,
  137741. _vq_quantmap__16u1__p5_0,
  137742. 9,
  137743. 9
  137744. };
  137745. static static_codebook _16u1__p5_0 = {
  137746. 2, 81,
  137747. _vq_lengthlist__16u1__p5_0,
  137748. 1, -531628032, 1611661312, 4, 0,
  137749. _vq_quantlist__16u1__p5_0,
  137750. NULL,
  137751. &_vq_auxt__16u1__p5_0,
  137752. NULL,
  137753. 0
  137754. };
  137755. static long _vq_quantlist__16u1__p6_0[] = {
  137756. 4,
  137757. 3,
  137758. 5,
  137759. 2,
  137760. 6,
  137761. 1,
  137762. 7,
  137763. 0,
  137764. 8,
  137765. };
  137766. static long _vq_lengthlist__16u1__p6_0[] = {
  137767. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  137768. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  137769. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  137770. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  137771. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  137772. 11,
  137773. };
  137774. static float _vq_quantthresh__16u1__p6_0[] = {
  137775. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137776. };
  137777. static long _vq_quantmap__16u1__p6_0[] = {
  137778. 7, 5, 3, 1, 0, 2, 4, 6,
  137779. 8,
  137780. };
  137781. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  137782. _vq_quantthresh__16u1__p6_0,
  137783. _vq_quantmap__16u1__p6_0,
  137784. 9,
  137785. 9
  137786. };
  137787. static static_codebook _16u1__p6_0 = {
  137788. 2, 81,
  137789. _vq_lengthlist__16u1__p6_0,
  137790. 1, -531628032, 1611661312, 4, 0,
  137791. _vq_quantlist__16u1__p6_0,
  137792. NULL,
  137793. &_vq_auxt__16u1__p6_0,
  137794. NULL,
  137795. 0
  137796. };
  137797. static long _vq_quantlist__16u1__p7_0[] = {
  137798. 1,
  137799. 0,
  137800. 2,
  137801. };
  137802. static long _vq_lengthlist__16u1__p7_0[] = {
  137803. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  137804. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  137805. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  137806. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  137807. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  137808. 13,
  137809. };
  137810. static float _vq_quantthresh__16u1__p7_0[] = {
  137811. -5.5, 5.5,
  137812. };
  137813. static long _vq_quantmap__16u1__p7_0[] = {
  137814. 1, 0, 2,
  137815. };
  137816. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  137817. _vq_quantthresh__16u1__p7_0,
  137818. _vq_quantmap__16u1__p7_0,
  137819. 3,
  137820. 3
  137821. };
  137822. static static_codebook _16u1__p7_0 = {
  137823. 4, 81,
  137824. _vq_lengthlist__16u1__p7_0,
  137825. 1, -529137664, 1618345984, 2, 0,
  137826. _vq_quantlist__16u1__p7_0,
  137827. NULL,
  137828. &_vq_auxt__16u1__p7_0,
  137829. NULL,
  137830. 0
  137831. };
  137832. static long _vq_quantlist__16u1__p7_1[] = {
  137833. 5,
  137834. 4,
  137835. 6,
  137836. 3,
  137837. 7,
  137838. 2,
  137839. 8,
  137840. 1,
  137841. 9,
  137842. 0,
  137843. 10,
  137844. };
  137845. static long _vq_lengthlist__16u1__p7_1[] = {
  137846. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  137847. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  137848. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  137849. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  137850. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  137851. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  137852. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  137853. 8, 9, 9,10,10,10,10,10,10,
  137854. };
  137855. static float _vq_quantthresh__16u1__p7_1[] = {
  137856. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137857. 3.5, 4.5,
  137858. };
  137859. static long _vq_quantmap__16u1__p7_1[] = {
  137860. 9, 7, 5, 3, 1, 0, 2, 4,
  137861. 6, 8, 10,
  137862. };
  137863. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  137864. _vq_quantthresh__16u1__p7_1,
  137865. _vq_quantmap__16u1__p7_1,
  137866. 11,
  137867. 11
  137868. };
  137869. static static_codebook _16u1__p7_1 = {
  137870. 2, 121,
  137871. _vq_lengthlist__16u1__p7_1,
  137872. 1, -531365888, 1611661312, 4, 0,
  137873. _vq_quantlist__16u1__p7_1,
  137874. NULL,
  137875. &_vq_auxt__16u1__p7_1,
  137876. NULL,
  137877. 0
  137878. };
  137879. static long _vq_quantlist__16u1__p8_0[] = {
  137880. 5,
  137881. 4,
  137882. 6,
  137883. 3,
  137884. 7,
  137885. 2,
  137886. 8,
  137887. 1,
  137888. 9,
  137889. 0,
  137890. 10,
  137891. };
  137892. static long _vq_lengthlist__16u1__p8_0[] = {
  137893. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  137894. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  137895. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  137896. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  137897. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  137898. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  137899. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  137900. 13,14,14,15,15,16,16,15,16,
  137901. };
  137902. static float _vq_quantthresh__16u1__p8_0[] = {
  137903. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  137904. 38.5, 49.5,
  137905. };
  137906. static long _vq_quantmap__16u1__p8_0[] = {
  137907. 9, 7, 5, 3, 1, 0, 2, 4,
  137908. 6, 8, 10,
  137909. };
  137910. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  137911. _vq_quantthresh__16u1__p8_0,
  137912. _vq_quantmap__16u1__p8_0,
  137913. 11,
  137914. 11
  137915. };
  137916. static static_codebook _16u1__p8_0 = {
  137917. 2, 121,
  137918. _vq_lengthlist__16u1__p8_0,
  137919. 1, -524582912, 1618345984, 4, 0,
  137920. _vq_quantlist__16u1__p8_0,
  137921. NULL,
  137922. &_vq_auxt__16u1__p8_0,
  137923. NULL,
  137924. 0
  137925. };
  137926. static long _vq_quantlist__16u1__p8_1[] = {
  137927. 5,
  137928. 4,
  137929. 6,
  137930. 3,
  137931. 7,
  137932. 2,
  137933. 8,
  137934. 1,
  137935. 9,
  137936. 0,
  137937. 10,
  137938. };
  137939. static long _vq_lengthlist__16u1__p8_1[] = {
  137940. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  137941. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  137942. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  137943. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  137944. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  137945. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  137946. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  137947. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  137948. };
  137949. static float _vq_quantthresh__16u1__p8_1[] = {
  137950. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137951. 3.5, 4.5,
  137952. };
  137953. static long _vq_quantmap__16u1__p8_1[] = {
  137954. 9, 7, 5, 3, 1, 0, 2, 4,
  137955. 6, 8, 10,
  137956. };
  137957. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  137958. _vq_quantthresh__16u1__p8_1,
  137959. _vq_quantmap__16u1__p8_1,
  137960. 11,
  137961. 11
  137962. };
  137963. static static_codebook _16u1__p8_1 = {
  137964. 2, 121,
  137965. _vq_lengthlist__16u1__p8_1,
  137966. 1, -531365888, 1611661312, 4, 0,
  137967. _vq_quantlist__16u1__p8_1,
  137968. NULL,
  137969. &_vq_auxt__16u1__p8_1,
  137970. NULL,
  137971. 0
  137972. };
  137973. static long _vq_quantlist__16u1__p9_0[] = {
  137974. 7,
  137975. 6,
  137976. 8,
  137977. 5,
  137978. 9,
  137979. 4,
  137980. 10,
  137981. 3,
  137982. 11,
  137983. 2,
  137984. 12,
  137985. 1,
  137986. 13,
  137987. 0,
  137988. 14,
  137989. };
  137990. static long _vq_lengthlist__16u1__p9_0[] = {
  137991. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137992. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137993. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137994. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137995. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137996. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137997. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137998. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137999. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138000. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138001. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138002. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138003. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138004. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138005. 8,
  138006. };
  138007. static float _vq_quantthresh__16u1__p9_0[] = {
  138008. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  138009. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  138010. };
  138011. static long _vq_quantmap__16u1__p9_0[] = {
  138012. 13, 11, 9, 7, 5, 3, 1, 0,
  138013. 2, 4, 6, 8, 10, 12, 14,
  138014. };
  138015. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  138016. _vq_quantthresh__16u1__p9_0,
  138017. _vq_quantmap__16u1__p9_0,
  138018. 15,
  138019. 15
  138020. };
  138021. static static_codebook _16u1__p9_0 = {
  138022. 2, 225,
  138023. _vq_lengthlist__16u1__p9_0,
  138024. 1, -514071552, 1627381760, 4, 0,
  138025. _vq_quantlist__16u1__p9_0,
  138026. NULL,
  138027. &_vq_auxt__16u1__p9_0,
  138028. NULL,
  138029. 0
  138030. };
  138031. static long _vq_quantlist__16u1__p9_1[] = {
  138032. 7,
  138033. 6,
  138034. 8,
  138035. 5,
  138036. 9,
  138037. 4,
  138038. 10,
  138039. 3,
  138040. 11,
  138041. 2,
  138042. 12,
  138043. 1,
  138044. 13,
  138045. 0,
  138046. 14,
  138047. };
  138048. static long _vq_lengthlist__16u1__p9_1[] = {
  138049. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  138050. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  138051. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  138052. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  138053. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  138054. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  138055. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  138056. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  138057. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  138058. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138059. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  138060. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138061. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138062. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138063. 9,
  138064. };
  138065. static float _vq_quantthresh__16u1__p9_1[] = {
  138066. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  138067. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  138068. };
  138069. static long _vq_quantmap__16u1__p9_1[] = {
  138070. 13, 11, 9, 7, 5, 3, 1, 0,
  138071. 2, 4, 6, 8, 10, 12, 14,
  138072. };
  138073. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  138074. _vq_quantthresh__16u1__p9_1,
  138075. _vq_quantmap__16u1__p9_1,
  138076. 15,
  138077. 15
  138078. };
  138079. static static_codebook _16u1__p9_1 = {
  138080. 2, 225,
  138081. _vq_lengthlist__16u1__p9_1,
  138082. 1, -522338304, 1620115456, 4, 0,
  138083. _vq_quantlist__16u1__p9_1,
  138084. NULL,
  138085. &_vq_auxt__16u1__p9_1,
  138086. NULL,
  138087. 0
  138088. };
  138089. static long _vq_quantlist__16u1__p9_2[] = {
  138090. 8,
  138091. 7,
  138092. 9,
  138093. 6,
  138094. 10,
  138095. 5,
  138096. 11,
  138097. 4,
  138098. 12,
  138099. 3,
  138100. 13,
  138101. 2,
  138102. 14,
  138103. 1,
  138104. 15,
  138105. 0,
  138106. 16,
  138107. };
  138108. static long _vq_lengthlist__16u1__p9_2[] = {
  138109. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  138110. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  138111. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  138112. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  138113. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  138114. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  138115. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  138116. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  138117. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  138118. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  138119. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  138120. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  138121. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  138122. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  138123. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  138124. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  138125. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  138126. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  138127. 10,
  138128. };
  138129. static float _vq_quantthresh__16u1__p9_2[] = {
  138130. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138131. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138132. };
  138133. static long _vq_quantmap__16u1__p9_2[] = {
  138134. 15, 13, 11, 9, 7, 5, 3, 1,
  138135. 0, 2, 4, 6, 8, 10, 12, 14,
  138136. 16,
  138137. };
  138138. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  138139. _vq_quantthresh__16u1__p9_2,
  138140. _vq_quantmap__16u1__p9_2,
  138141. 17,
  138142. 17
  138143. };
  138144. static static_codebook _16u1__p9_2 = {
  138145. 2, 289,
  138146. _vq_lengthlist__16u1__p9_2,
  138147. 1, -529530880, 1611661312, 5, 0,
  138148. _vq_quantlist__16u1__p9_2,
  138149. NULL,
  138150. &_vq_auxt__16u1__p9_2,
  138151. NULL,
  138152. 0
  138153. };
  138154. static long _huff_lengthlist__16u1__short[] = {
  138155. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  138156. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  138157. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  138158. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  138159. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  138160. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  138161. 16,16,16,16,
  138162. };
  138163. static static_codebook _huff_book__16u1__short = {
  138164. 2, 100,
  138165. _huff_lengthlist__16u1__short,
  138166. 0, 0, 0, 0, 0,
  138167. NULL,
  138168. NULL,
  138169. NULL,
  138170. NULL,
  138171. 0
  138172. };
  138173. static long _huff_lengthlist__16u2__long[] = {
  138174. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  138175. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  138176. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  138177. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  138178. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  138179. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  138180. 13,14,18,18,
  138181. };
  138182. static static_codebook _huff_book__16u2__long = {
  138183. 2, 100,
  138184. _huff_lengthlist__16u2__long,
  138185. 0, 0, 0, 0, 0,
  138186. NULL,
  138187. NULL,
  138188. NULL,
  138189. NULL,
  138190. 0
  138191. };
  138192. static long _huff_lengthlist__16u2__short[] = {
  138193. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  138194. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  138195. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  138196. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  138197. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  138198. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  138199. 16,16,16,16,
  138200. };
  138201. static static_codebook _huff_book__16u2__short = {
  138202. 2, 100,
  138203. _huff_lengthlist__16u2__short,
  138204. 0, 0, 0, 0, 0,
  138205. NULL,
  138206. NULL,
  138207. NULL,
  138208. NULL,
  138209. 0
  138210. };
  138211. static long _vq_quantlist__16u2_p1_0[] = {
  138212. 1,
  138213. 0,
  138214. 2,
  138215. };
  138216. static long _vq_lengthlist__16u2_p1_0[] = {
  138217. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  138218. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  138219. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  138220. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  138221. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  138222. 10,
  138223. };
  138224. static float _vq_quantthresh__16u2_p1_0[] = {
  138225. -0.5, 0.5,
  138226. };
  138227. static long _vq_quantmap__16u2_p1_0[] = {
  138228. 1, 0, 2,
  138229. };
  138230. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  138231. _vq_quantthresh__16u2_p1_0,
  138232. _vq_quantmap__16u2_p1_0,
  138233. 3,
  138234. 3
  138235. };
  138236. static static_codebook _16u2_p1_0 = {
  138237. 4, 81,
  138238. _vq_lengthlist__16u2_p1_0,
  138239. 1, -535822336, 1611661312, 2, 0,
  138240. _vq_quantlist__16u2_p1_0,
  138241. NULL,
  138242. &_vq_auxt__16u2_p1_0,
  138243. NULL,
  138244. 0
  138245. };
  138246. static long _vq_quantlist__16u2_p2_0[] = {
  138247. 2,
  138248. 1,
  138249. 3,
  138250. 0,
  138251. 4,
  138252. };
  138253. static long _vq_lengthlist__16u2_p2_0[] = {
  138254. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  138255. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  138256. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  138257. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  138258. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  138259. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  138260. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  138261. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  138262. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  138263. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  138264. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  138265. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  138266. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  138267. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  138268. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  138269. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  138270. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  138271. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  138272. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  138273. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  138274. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  138275. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  138276. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  138277. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  138278. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  138279. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  138280. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  138281. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  138282. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  138283. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  138284. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  138285. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  138286. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  138287. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  138288. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  138289. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  138290. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  138291. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  138292. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  138293. 13,
  138294. };
  138295. static float _vq_quantthresh__16u2_p2_0[] = {
  138296. -1.5, -0.5, 0.5, 1.5,
  138297. };
  138298. static long _vq_quantmap__16u2_p2_0[] = {
  138299. 3, 1, 0, 2, 4,
  138300. };
  138301. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  138302. _vq_quantthresh__16u2_p2_0,
  138303. _vq_quantmap__16u2_p2_0,
  138304. 5,
  138305. 5
  138306. };
  138307. static static_codebook _16u2_p2_0 = {
  138308. 4, 625,
  138309. _vq_lengthlist__16u2_p2_0,
  138310. 1, -533725184, 1611661312, 3, 0,
  138311. _vq_quantlist__16u2_p2_0,
  138312. NULL,
  138313. &_vq_auxt__16u2_p2_0,
  138314. NULL,
  138315. 0
  138316. };
  138317. static long _vq_quantlist__16u2_p3_0[] = {
  138318. 4,
  138319. 3,
  138320. 5,
  138321. 2,
  138322. 6,
  138323. 1,
  138324. 7,
  138325. 0,
  138326. 8,
  138327. };
  138328. static long _vq_lengthlist__16u2_p3_0[] = {
  138329. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  138330. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  138331. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  138332. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  138333. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  138334. 11,
  138335. };
  138336. static float _vq_quantthresh__16u2_p3_0[] = {
  138337. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138338. };
  138339. static long _vq_quantmap__16u2_p3_0[] = {
  138340. 7, 5, 3, 1, 0, 2, 4, 6,
  138341. 8,
  138342. };
  138343. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  138344. _vq_quantthresh__16u2_p3_0,
  138345. _vq_quantmap__16u2_p3_0,
  138346. 9,
  138347. 9
  138348. };
  138349. static static_codebook _16u2_p3_0 = {
  138350. 2, 81,
  138351. _vq_lengthlist__16u2_p3_0,
  138352. 1, -531628032, 1611661312, 4, 0,
  138353. _vq_quantlist__16u2_p3_0,
  138354. NULL,
  138355. &_vq_auxt__16u2_p3_0,
  138356. NULL,
  138357. 0
  138358. };
  138359. static long _vq_quantlist__16u2_p4_0[] = {
  138360. 8,
  138361. 7,
  138362. 9,
  138363. 6,
  138364. 10,
  138365. 5,
  138366. 11,
  138367. 4,
  138368. 12,
  138369. 3,
  138370. 13,
  138371. 2,
  138372. 14,
  138373. 1,
  138374. 15,
  138375. 0,
  138376. 16,
  138377. };
  138378. static long _vq_lengthlist__16u2_p4_0[] = {
  138379. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  138380. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  138381. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  138382. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138383. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138384. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  138385. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  138386. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  138387. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  138388. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  138389. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  138390. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  138391. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  138392. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  138393. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  138394. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  138395. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  138396. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  138397. 14,
  138398. };
  138399. static float _vq_quantthresh__16u2_p4_0[] = {
  138400. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138401. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138402. };
  138403. static long _vq_quantmap__16u2_p4_0[] = {
  138404. 15, 13, 11, 9, 7, 5, 3, 1,
  138405. 0, 2, 4, 6, 8, 10, 12, 14,
  138406. 16,
  138407. };
  138408. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  138409. _vq_quantthresh__16u2_p4_0,
  138410. _vq_quantmap__16u2_p4_0,
  138411. 17,
  138412. 17
  138413. };
  138414. static static_codebook _16u2_p4_0 = {
  138415. 2, 289,
  138416. _vq_lengthlist__16u2_p4_0,
  138417. 1, -529530880, 1611661312, 5, 0,
  138418. _vq_quantlist__16u2_p4_0,
  138419. NULL,
  138420. &_vq_auxt__16u2_p4_0,
  138421. NULL,
  138422. 0
  138423. };
  138424. static long _vq_quantlist__16u2_p5_0[] = {
  138425. 1,
  138426. 0,
  138427. 2,
  138428. };
  138429. static long _vq_lengthlist__16u2_p5_0[] = {
  138430. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  138431. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  138432. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  138433. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  138434. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  138435. 10,
  138436. };
  138437. static float _vq_quantthresh__16u2_p5_0[] = {
  138438. -5.5, 5.5,
  138439. };
  138440. static long _vq_quantmap__16u2_p5_0[] = {
  138441. 1, 0, 2,
  138442. };
  138443. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  138444. _vq_quantthresh__16u2_p5_0,
  138445. _vq_quantmap__16u2_p5_0,
  138446. 3,
  138447. 3
  138448. };
  138449. static static_codebook _16u2_p5_0 = {
  138450. 4, 81,
  138451. _vq_lengthlist__16u2_p5_0,
  138452. 1, -529137664, 1618345984, 2, 0,
  138453. _vq_quantlist__16u2_p5_0,
  138454. NULL,
  138455. &_vq_auxt__16u2_p5_0,
  138456. NULL,
  138457. 0
  138458. };
  138459. static long _vq_quantlist__16u2_p5_1[] = {
  138460. 5,
  138461. 4,
  138462. 6,
  138463. 3,
  138464. 7,
  138465. 2,
  138466. 8,
  138467. 1,
  138468. 9,
  138469. 0,
  138470. 10,
  138471. };
  138472. static long _vq_lengthlist__16u2_p5_1[] = {
  138473. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  138474. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  138475. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  138476. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  138477. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  138478. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  138479. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  138480. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  138481. };
  138482. static float _vq_quantthresh__16u2_p5_1[] = {
  138483. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138484. 3.5, 4.5,
  138485. };
  138486. static long _vq_quantmap__16u2_p5_1[] = {
  138487. 9, 7, 5, 3, 1, 0, 2, 4,
  138488. 6, 8, 10,
  138489. };
  138490. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  138491. _vq_quantthresh__16u2_p5_1,
  138492. _vq_quantmap__16u2_p5_1,
  138493. 11,
  138494. 11
  138495. };
  138496. static static_codebook _16u2_p5_1 = {
  138497. 2, 121,
  138498. _vq_lengthlist__16u2_p5_1,
  138499. 1, -531365888, 1611661312, 4, 0,
  138500. _vq_quantlist__16u2_p5_1,
  138501. NULL,
  138502. &_vq_auxt__16u2_p5_1,
  138503. NULL,
  138504. 0
  138505. };
  138506. static long _vq_quantlist__16u2_p6_0[] = {
  138507. 6,
  138508. 5,
  138509. 7,
  138510. 4,
  138511. 8,
  138512. 3,
  138513. 9,
  138514. 2,
  138515. 10,
  138516. 1,
  138517. 11,
  138518. 0,
  138519. 12,
  138520. };
  138521. static long _vq_lengthlist__16u2_p6_0[] = {
  138522. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  138523. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  138524. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  138525. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  138526. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  138527. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  138528. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  138529. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  138530. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  138531. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  138532. 12,13,13,14,14,14,14,15,15,
  138533. };
  138534. static float _vq_quantthresh__16u2_p6_0[] = {
  138535. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138536. 12.5, 17.5, 22.5, 27.5,
  138537. };
  138538. static long _vq_quantmap__16u2_p6_0[] = {
  138539. 11, 9, 7, 5, 3, 1, 0, 2,
  138540. 4, 6, 8, 10, 12,
  138541. };
  138542. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  138543. _vq_quantthresh__16u2_p6_0,
  138544. _vq_quantmap__16u2_p6_0,
  138545. 13,
  138546. 13
  138547. };
  138548. static static_codebook _16u2_p6_0 = {
  138549. 2, 169,
  138550. _vq_lengthlist__16u2_p6_0,
  138551. 1, -526516224, 1616117760, 4, 0,
  138552. _vq_quantlist__16u2_p6_0,
  138553. NULL,
  138554. &_vq_auxt__16u2_p6_0,
  138555. NULL,
  138556. 0
  138557. };
  138558. static long _vq_quantlist__16u2_p6_1[] = {
  138559. 2,
  138560. 1,
  138561. 3,
  138562. 0,
  138563. 4,
  138564. };
  138565. static long _vq_lengthlist__16u2_p6_1[] = {
  138566. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  138567. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  138568. };
  138569. static float _vq_quantthresh__16u2_p6_1[] = {
  138570. -1.5, -0.5, 0.5, 1.5,
  138571. };
  138572. static long _vq_quantmap__16u2_p6_1[] = {
  138573. 3, 1, 0, 2, 4,
  138574. };
  138575. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  138576. _vq_quantthresh__16u2_p6_1,
  138577. _vq_quantmap__16u2_p6_1,
  138578. 5,
  138579. 5
  138580. };
  138581. static static_codebook _16u2_p6_1 = {
  138582. 2, 25,
  138583. _vq_lengthlist__16u2_p6_1,
  138584. 1, -533725184, 1611661312, 3, 0,
  138585. _vq_quantlist__16u2_p6_1,
  138586. NULL,
  138587. &_vq_auxt__16u2_p6_1,
  138588. NULL,
  138589. 0
  138590. };
  138591. static long _vq_quantlist__16u2_p7_0[] = {
  138592. 6,
  138593. 5,
  138594. 7,
  138595. 4,
  138596. 8,
  138597. 3,
  138598. 9,
  138599. 2,
  138600. 10,
  138601. 1,
  138602. 11,
  138603. 0,
  138604. 12,
  138605. };
  138606. static long _vq_lengthlist__16u2_p7_0[] = {
  138607. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  138608. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  138609. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  138610. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  138611. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  138612. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  138613. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  138614. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  138615. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  138616. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  138617. 12,13,13,13,14,14,14,15,14,
  138618. };
  138619. static float _vq_quantthresh__16u2_p7_0[] = {
  138620. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  138621. 27.5, 38.5, 49.5, 60.5,
  138622. };
  138623. static long _vq_quantmap__16u2_p7_0[] = {
  138624. 11, 9, 7, 5, 3, 1, 0, 2,
  138625. 4, 6, 8, 10, 12,
  138626. };
  138627. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  138628. _vq_quantthresh__16u2_p7_0,
  138629. _vq_quantmap__16u2_p7_0,
  138630. 13,
  138631. 13
  138632. };
  138633. static static_codebook _16u2_p7_0 = {
  138634. 2, 169,
  138635. _vq_lengthlist__16u2_p7_0,
  138636. 1, -523206656, 1618345984, 4, 0,
  138637. _vq_quantlist__16u2_p7_0,
  138638. NULL,
  138639. &_vq_auxt__16u2_p7_0,
  138640. NULL,
  138641. 0
  138642. };
  138643. static long _vq_quantlist__16u2_p7_1[] = {
  138644. 5,
  138645. 4,
  138646. 6,
  138647. 3,
  138648. 7,
  138649. 2,
  138650. 8,
  138651. 1,
  138652. 9,
  138653. 0,
  138654. 10,
  138655. };
  138656. static long _vq_lengthlist__16u2_p7_1[] = {
  138657. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  138658. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  138659. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  138660. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  138661. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  138662. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  138663. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  138664. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138665. };
  138666. static float _vq_quantthresh__16u2_p7_1[] = {
  138667. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138668. 3.5, 4.5,
  138669. };
  138670. static long _vq_quantmap__16u2_p7_1[] = {
  138671. 9, 7, 5, 3, 1, 0, 2, 4,
  138672. 6, 8, 10,
  138673. };
  138674. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  138675. _vq_quantthresh__16u2_p7_1,
  138676. _vq_quantmap__16u2_p7_1,
  138677. 11,
  138678. 11
  138679. };
  138680. static static_codebook _16u2_p7_1 = {
  138681. 2, 121,
  138682. _vq_lengthlist__16u2_p7_1,
  138683. 1, -531365888, 1611661312, 4, 0,
  138684. _vq_quantlist__16u2_p7_1,
  138685. NULL,
  138686. &_vq_auxt__16u2_p7_1,
  138687. NULL,
  138688. 0
  138689. };
  138690. static long _vq_quantlist__16u2_p8_0[] = {
  138691. 7,
  138692. 6,
  138693. 8,
  138694. 5,
  138695. 9,
  138696. 4,
  138697. 10,
  138698. 3,
  138699. 11,
  138700. 2,
  138701. 12,
  138702. 1,
  138703. 13,
  138704. 0,
  138705. 14,
  138706. };
  138707. static long _vq_lengthlist__16u2_p8_0[] = {
  138708. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  138709. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  138710. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  138711. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  138712. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  138713. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  138714. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  138715. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  138716. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  138717. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  138718. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  138719. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  138720. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  138721. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  138722. 14,
  138723. };
  138724. static float _vq_quantthresh__16u2_p8_0[] = {
  138725. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  138726. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  138727. };
  138728. static long _vq_quantmap__16u2_p8_0[] = {
  138729. 13, 11, 9, 7, 5, 3, 1, 0,
  138730. 2, 4, 6, 8, 10, 12, 14,
  138731. };
  138732. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  138733. _vq_quantthresh__16u2_p8_0,
  138734. _vq_quantmap__16u2_p8_0,
  138735. 15,
  138736. 15
  138737. };
  138738. static static_codebook _16u2_p8_0 = {
  138739. 2, 225,
  138740. _vq_lengthlist__16u2_p8_0,
  138741. 1, -520986624, 1620377600, 4, 0,
  138742. _vq_quantlist__16u2_p8_0,
  138743. NULL,
  138744. &_vq_auxt__16u2_p8_0,
  138745. NULL,
  138746. 0
  138747. };
  138748. static long _vq_quantlist__16u2_p8_1[] = {
  138749. 10,
  138750. 9,
  138751. 11,
  138752. 8,
  138753. 12,
  138754. 7,
  138755. 13,
  138756. 6,
  138757. 14,
  138758. 5,
  138759. 15,
  138760. 4,
  138761. 16,
  138762. 3,
  138763. 17,
  138764. 2,
  138765. 18,
  138766. 1,
  138767. 19,
  138768. 0,
  138769. 20,
  138770. };
  138771. static long _vq_lengthlist__16u2_p8_1[] = {
  138772. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  138773. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  138774. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  138775. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  138776. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  138777. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  138778. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  138779. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  138780. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  138781. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  138782. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  138783. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  138784. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  138785. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  138786. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  138787. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  138788. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  138789. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  138790. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  138791. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  138792. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  138793. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  138794. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  138795. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  138796. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  138797. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  138798. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  138799. 11,11,10,11,11,11,10,11,11,
  138800. };
  138801. static float _vq_quantthresh__16u2_p8_1[] = {
  138802. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  138803. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  138804. 6.5, 7.5, 8.5, 9.5,
  138805. };
  138806. static long _vq_quantmap__16u2_p8_1[] = {
  138807. 19, 17, 15, 13, 11, 9, 7, 5,
  138808. 3, 1, 0, 2, 4, 6, 8, 10,
  138809. 12, 14, 16, 18, 20,
  138810. };
  138811. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  138812. _vq_quantthresh__16u2_p8_1,
  138813. _vq_quantmap__16u2_p8_1,
  138814. 21,
  138815. 21
  138816. };
  138817. static static_codebook _16u2_p8_1 = {
  138818. 2, 441,
  138819. _vq_lengthlist__16u2_p8_1,
  138820. 1, -529268736, 1611661312, 5, 0,
  138821. _vq_quantlist__16u2_p8_1,
  138822. NULL,
  138823. &_vq_auxt__16u2_p8_1,
  138824. NULL,
  138825. 0
  138826. };
  138827. static long _vq_quantlist__16u2_p9_0[] = {
  138828. 5586,
  138829. 4655,
  138830. 6517,
  138831. 3724,
  138832. 7448,
  138833. 2793,
  138834. 8379,
  138835. 1862,
  138836. 9310,
  138837. 931,
  138838. 10241,
  138839. 0,
  138840. 11172,
  138841. 5521,
  138842. 5651,
  138843. };
  138844. static long _vq_lengthlist__16u2_p9_0[] = {
  138845. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  138846. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138847. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138848. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138849. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138850. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138851. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138852. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138853. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138854. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138855. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138856. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138857. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  138858. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  138859. 5,
  138860. };
  138861. static float _vq_quantthresh__16u2_p9_0[] = {
  138862. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  138863. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  138864. };
  138865. static long _vq_quantmap__16u2_p9_0[] = {
  138866. 11, 9, 7, 5, 3, 1, 13, 0,
  138867. 14, 2, 4, 6, 8, 10, 12,
  138868. };
  138869. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  138870. _vq_quantthresh__16u2_p9_0,
  138871. _vq_quantmap__16u2_p9_0,
  138872. 15,
  138873. 15
  138874. };
  138875. static static_codebook _16u2_p9_0 = {
  138876. 2, 225,
  138877. _vq_lengthlist__16u2_p9_0,
  138878. 1, -510275072, 1611661312, 14, 0,
  138879. _vq_quantlist__16u2_p9_0,
  138880. NULL,
  138881. &_vq_auxt__16u2_p9_0,
  138882. NULL,
  138883. 0
  138884. };
  138885. static long _vq_quantlist__16u2_p9_1[] = {
  138886. 392,
  138887. 343,
  138888. 441,
  138889. 294,
  138890. 490,
  138891. 245,
  138892. 539,
  138893. 196,
  138894. 588,
  138895. 147,
  138896. 637,
  138897. 98,
  138898. 686,
  138899. 49,
  138900. 735,
  138901. 0,
  138902. 784,
  138903. 388,
  138904. 396,
  138905. };
  138906. static long _vq_lengthlist__16u2_p9_1[] = {
  138907. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  138908. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  138909. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  138910. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  138911. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  138912. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  138913. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138914. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  138915. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  138916. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138917. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138918. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138919. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138920. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138921. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  138922. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138923. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138924. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138925. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138926. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138927. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  138928. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  138929. 11,11,11,11,11,11,11, 5, 4,
  138930. };
  138931. static float _vq_quantthresh__16u2_p9_1[] = {
  138932. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  138933. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  138934. 318.5, 367.5,
  138935. };
  138936. static long _vq_quantmap__16u2_p9_1[] = {
  138937. 15, 13, 11, 9, 7, 5, 3, 1,
  138938. 17, 0, 18, 2, 4, 6, 8, 10,
  138939. 12, 14, 16,
  138940. };
  138941. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  138942. _vq_quantthresh__16u2_p9_1,
  138943. _vq_quantmap__16u2_p9_1,
  138944. 19,
  138945. 19
  138946. };
  138947. static static_codebook _16u2_p9_1 = {
  138948. 2, 361,
  138949. _vq_lengthlist__16u2_p9_1,
  138950. 1, -518488064, 1611661312, 10, 0,
  138951. _vq_quantlist__16u2_p9_1,
  138952. NULL,
  138953. &_vq_auxt__16u2_p9_1,
  138954. NULL,
  138955. 0
  138956. };
  138957. static long _vq_quantlist__16u2_p9_2[] = {
  138958. 24,
  138959. 23,
  138960. 25,
  138961. 22,
  138962. 26,
  138963. 21,
  138964. 27,
  138965. 20,
  138966. 28,
  138967. 19,
  138968. 29,
  138969. 18,
  138970. 30,
  138971. 17,
  138972. 31,
  138973. 16,
  138974. 32,
  138975. 15,
  138976. 33,
  138977. 14,
  138978. 34,
  138979. 13,
  138980. 35,
  138981. 12,
  138982. 36,
  138983. 11,
  138984. 37,
  138985. 10,
  138986. 38,
  138987. 9,
  138988. 39,
  138989. 8,
  138990. 40,
  138991. 7,
  138992. 41,
  138993. 6,
  138994. 42,
  138995. 5,
  138996. 43,
  138997. 4,
  138998. 44,
  138999. 3,
  139000. 45,
  139001. 2,
  139002. 46,
  139003. 1,
  139004. 47,
  139005. 0,
  139006. 48,
  139007. };
  139008. static long _vq_lengthlist__16u2_p9_2[] = {
  139009. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  139010. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  139011. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  139012. 11,
  139013. };
  139014. static float _vq_quantthresh__16u2_p9_2[] = {
  139015. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  139016. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  139017. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139018. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139019. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  139020. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  139021. };
  139022. static long _vq_quantmap__16u2_p9_2[] = {
  139023. 47, 45, 43, 41, 39, 37, 35, 33,
  139024. 31, 29, 27, 25, 23, 21, 19, 17,
  139025. 15, 13, 11, 9, 7, 5, 3, 1,
  139026. 0, 2, 4, 6, 8, 10, 12, 14,
  139027. 16, 18, 20, 22, 24, 26, 28, 30,
  139028. 32, 34, 36, 38, 40, 42, 44, 46,
  139029. 48,
  139030. };
  139031. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  139032. _vq_quantthresh__16u2_p9_2,
  139033. _vq_quantmap__16u2_p9_2,
  139034. 49,
  139035. 49
  139036. };
  139037. static static_codebook _16u2_p9_2 = {
  139038. 1, 49,
  139039. _vq_lengthlist__16u2_p9_2,
  139040. 1, -526909440, 1611661312, 6, 0,
  139041. _vq_quantlist__16u2_p9_2,
  139042. NULL,
  139043. &_vq_auxt__16u2_p9_2,
  139044. NULL,
  139045. 0
  139046. };
  139047. static long _vq_quantlist__8u0__p1_0[] = {
  139048. 1,
  139049. 0,
  139050. 2,
  139051. };
  139052. static long _vq_lengthlist__8u0__p1_0[] = {
  139053. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  139054. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  139055. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  139056. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  139057. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  139058. 11,
  139059. };
  139060. static float _vq_quantthresh__8u0__p1_0[] = {
  139061. -0.5, 0.5,
  139062. };
  139063. static long _vq_quantmap__8u0__p1_0[] = {
  139064. 1, 0, 2,
  139065. };
  139066. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  139067. _vq_quantthresh__8u0__p1_0,
  139068. _vq_quantmap__8u0__p1_0,
  139069. 3,
  139070. 3
  139071. };
  139072. static static_codebook _8u0__p1_0 = {
  139073. 4, 81,
  139074. _vq_lengthlist__8u0__p1_0,
  139075. 1, -535822336, 1611661312, 2, 0,
  139076. _vq_quantlist__8u0__p1_0,
  139077. NULL,
  139078. &_vq_auxt__8u0__p1_0,
  139079. NULL,
  139080. 0
  139081. };
  139082. static long _vq_quantlist__8u0__p2_0[] = {
  139083. 1,
  139084. 0,
  139085. 2,
  139086. };
  139087. static long _vq_lengthlist__8u0__p2_0[] = {
  139088. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  139089. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  139090. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  139091. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  139092. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  139093. 8,
  139094. };
  139095. static float _vq_quantthresh__8u0__p2_0[] = {
  139096. -0.5, 0.5,
  139097. };
  139098. static long _vq_quantmap__8u0__p2_0[] = {
  139099. 1, 0, 2,
  139100. };
  139101. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  139102. _vq_quantthresh__8u0__p2_0,
  139103. _vq_quantmap__8u0__p2_0,
  139104. 3,
  139105. 3
  139106. };
  139107. static static_codebook _8u0__p2_0 = {
  139108. 4, 81,
  139109. _vq_lengthlist__8u0__p2_0,
  139110. 1, -535822336, 1611661312, 2, 0,
  139111. _vq_quantlist__8u0__p2_0,
  139112. NULL,
  139113. &_vq_auxt__8u0__p2_0,
  139114. NULL,
  139115. 0
  139116. };
  139117. static long _vq_quantlist__8u0__p3_0[] = {
  139118. 2,
  139119. 1,
  139120. 3,
  139121. 0,
  139122. 4,
  139123. };
  139124. static long _vq_lengthlist__8u0__p3_0[] = {
  139125. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  139126. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  139127. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  139128. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  139129. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  139130. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  139131. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  139132. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  139133. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  139134. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  139135. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  139136. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  139137. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  139138. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  139139. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  139140. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  139141. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  139142. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  139143. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  139144. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  139145. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  139146. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  139147. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  139148. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  139149. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  139150. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  139151. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  139152. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  139153. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  139154. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  139155. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  139156. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  139157. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  139158. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  139159. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  139160. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  139161. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  139162. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  139163. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  139164. 16,
  139165. };
  139166. static float _vq_quantthresh__8u0__p3_0[] = {
  139167. -1.5, -0.5, 0.5, 1.5,
  139168. };
  139169. static long _vq_quantmap__8u0__p3_0[] = {
  139170. 3, 1, 0, 2, 4,
  139171. };
  139172. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  139173. _vq_quantthresh__8u0__p3_0,
  139174. _vq_quantmap__8u0__p3_0,
  139175. 5,
  139176. 5
  139177. };
  139178. static static_codebook _8u0__p3_0 = {
  139179. 4, 625,
  139180. _vq_lengthlist__8u0__p3_0,
  139181. 1, -533725184, 1611661312, 3, 0,
  139182. _vq_quantlist__8u0__p3_0,
  139183. NULL,
  139184. &_vq_auxt__8u0__p3_0,
  139185. NULL,
  139186. 0
  139187. };
  139188. static long _vq_quantlist__8u0__p4_0[] = {
  139189. 2,
  139190. 1,
  139191. 3,
  139192. 0,
  139193. 4,
  139194. };
  139195. static long _vq_lengthlist__8u0__p4_0[] = {
  139196. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  139197. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  139198. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  139199. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  139200. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  139201. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  139202. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  139203. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  139204. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  139205. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  139206. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  139207. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  139208. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  139209. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  139210. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  139211. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  139212. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  139213. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  139214. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  139215. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  139216. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  139217. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  139218. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  139219. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  139220. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  139221. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  139222. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  139223. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  139224. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  139225. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  139226. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  139227. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  139228. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  139229. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  139230. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  139231. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  139232. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  139233. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  139234. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  139235. 12,
  139236. };
  139237. static float _vq_quantthresh__8u0__p4_0[] = {
  139238. -1.5, -0.5, 0.5, 1.5,
  139239. };
  139240. static long _vq_quantmap__8u0__p4_0[] = {
  139241. 3, 1, 0, 2, 4,
  139242. };
  139243. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  139244. _vq_quantthresh__8u0__p4_0,
  139245. _vq_quantmap__8u0__p4_0,
  139246. 5,
  139247. 5
  139248. };
  139249. static static_codebook _8u0__p4_0 = {
  139250. 4, 625,
  139251. _vq_lengthlist__8u0__p4_0,
  139252. 1, -533725184, 1611661312, 3, 0,
  139253. _vq_quantlist__8u0__p4_0,
  139254. NULL,
  139255. &_vq_auxt__8u0__p4_0,
  139256. NULL,
  139257. 0
  139258. };
  139259. static long _vq_quantlist__8u0__p5_0[] = {
  139260. 4,
  139261. 3,
  139262. 5,
  139263. 2,
  139264. 6,
  139265. 1,
  139266. 7,
  139267. 0,
  139268. 8,
  139269. };
  139270. static long _vq_lengthlist__8u0__p5_0[] = {
  139271. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  139272. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  139273. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  139274. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  139275. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  139276. 12,
  139277. };
  139278. static float _vq_quantthresh__8u0__p5_0[] = {
  139279. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139280. };
  139281. static long _vq_quantmap__8u0__p5_0[] = {
  139282. 7, 5, 3, 1, 0, 2, 4, 6,
  139283. 8,
  139284. };
  139285. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  139286. _vq_quantthresh__8u0__p5_0,
  139287. _vq_quantmap__8u0__p5_0,
  139288. 9,
  139289. 9
  139290. };
  139291. static static_codebook _8u0__p5_0 = {
  139292. 2, 81,
  139293. _vq_lengthlist__8u0__p5_0,
  139294. 1, -531628032, 1611661312, 4, 0,
  139295. _vq_quantlist__8u0__p5_0,
  139296. NULL,
  139297. &_vq_auxt__8u0__p5_0,
  139298. NULL,
  139299. 0
  139300. };
  139301. static long _vq_quantlist__8u0__p6_0[] = {
  139302. 6,
  139303. 5,
  139304. 7,
  139305. 4,
  139306. 8,
  139307. 3,
  139308. 9,
  139309. 2,
  139310. 10,
  139311. 1,
  139312. 11,
  139313. 0,
  139314. 12,
  139315. };
  139316. static long _vq_lengthlist__8u0__p6_0[] = {
  139317. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  139318. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  139319. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  139320. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  139321. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  139322. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  139323. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  139324. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  139325. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  139326. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  139327. 16, 0,15, 0,17, 0, 0, 0, 0,
  139328. };
  139329. static float _vq_quantthresh__8u0__p6_0[] = {
  139330. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139331. 12.5, 17.5, 22.5, 27.5,
  139332. };
  139333. static long _vq_quantmap__8u0__p6_0[] = {
  139334. 11, 9, 7, 5, 3, 1, 0, 2,
  139335. 4, 6, 8, 10, 12,
  139336. };
  139337. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  139338. _vq_quantthresh__8u0__p6_0,
  139339. _vq_quantmap__8u0__p6_0,
  139340. 13,
  139341. 13
  139342. };
  139343. static static_codebook _8u0__p6_0 = {
  139344. 2, 169,
  139345. _vq_lengthlist__8u0__p6_0,
  139346. 1, -526516224, 1616117760, 4, 0,
  139347. _vq_quantlist__8u0__p6_0,
  139348. NULL,
  139349. &_vq_auxt__8u0__p6_0,
  139350. NULL,
  139351. 0
  139352. };
  139353. static long _vq_quantlist__8u0__p6_1[] = {
  139354. 2,
  139355. 1,
  139356. 3,
  139357. 0,
  139358. 4,
  139359. };
  139360. static long _vq_lengthlist__8u0__p6_1[] = {
  139361. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  139362. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  139363. };
  139364. static float _vq_quantthresh__8u0__p6_1[] = {
  139365. -1.5, -0.5, 0.5, 1.5,
  139366. };
  139367. static long _vq_quantmap__8u0__p6_1[] = {
  139368. 3, 1, 0, 2, 4,
  139369. };
  139370. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  139371. _vq_quantthresh__8u0__p6_1,
  139372. _vq_quantmap__8u0__p6_1,
  139373. 5,
  139374. 5
  139375. };
  139376. static static_codebook _8u0__p6_1 = {
  139377. 2, 25,
  139378. _vq_lengthlist__8u0__p6_1,
  139379. 1, -533725184, 1611661312, 3, 0,
  139380. _vq_quantlist__8u0__p6_1,
  139381. NULL,
  139382. &_vq_auxt__8u0__p6_1,
  139383. NULL,
  139384. 0
  139385. };
  139386. static long _vq_quantlist__8u0__p7_0[] = {
  139387. 1,
  139388. 0,
  139389. 2,
  139390. };
  139391. static long _vq_lengthlist__8u0__p7_0[] = {
  139392. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139393. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139394. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139395. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139396. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139397. 7,
  139398. };
  139399. static float _vq_quantthresh__8u0__p7_0[] = {
  139400. -157.5, 157.5,
  139401. };
  139402. static long _vq_quantmap__8u0__p7_0[] = {
  139403. 1, 0, 2,
  139404. };
  139405. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  139406. _vq_quantthresh__8u0__p7_0,
  139407. _vq_quantmap__8u0__p7_0,
  139408. 3,
  139409. 3
  139410. };
  139411. static static_codebook _8u0__p7_0 = {
  139412. 4, 81,
  139413. _vq_lengthlist__8u0__p7_0,
  139414. 1, -518803456, 1628680192, 2, 0,
  139415. _vq_quantlist__8u0__p7_0,
  139416. NULL,
  139417. &_vq_auxt__8u0__p7_0,
  139418. NULL,
  139419. 0
  139420. };
  139421. static long _vq_quantlist__8u0__p7_1[] = {
  139422. 7,
  139423. 6,
  139424. 8,
  139425. 5,
  139426. 9,
  139427. 4,
  139428. 10,
  139429. 3,
  139430. 11,
  139431. 2,
  139432. 12,
  139433. 1,
  139434. 13,
  139435. 0,
  139436. 14,
  139437. };
  139438. static long _vq_lengthlist__8u0__p7_1[] = {
  139439. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  139440. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  139441. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  139442. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  139443. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  139444. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  139445. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139446. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139447. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139448. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139449. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139450. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139451. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  139452. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139453. 10,
  139454. };
  139455. static float _vq_quantthresh__8u0__p7_1[] = {
  139456. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  139457. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  139458. };
  139459. static long _vq_quantmap__8u0__p7_1[] = {
  139460. 13, 11, 9, 7, 5, 3, 1, 0,
  139461. 2, 4, 6, 8, 10, 12, 14,
  139462. };
  139463. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  139464. _vq_quantthresh__8u0__p7_1,
  139465. _vq_quantmap__8u0__p7_1,
  139466. 15,
  139467. 15
  139468. };
  139469. static static_codebook _8u0__p7_1 = {
  139470. 2, 225,
  139471. _vq_lengthlist__8u0__p7_1,
  139472. 1, -520986624, 1620377600, 4, 0,
  139473. _vq_quantlist__8u0__p7_1,
  139474. NULL,
  139475. &_vq_auxt__8u0__p7_1,
  139476. NULL,
  139477. 0
  139478. };
  139479. static long _vq_quantlist__8u0__p7_2[] = {
  139480. 10,
  139481. 9,
  139482. 11,
  139483. 8,
  139484. 12,
  139485. 7,
  139486. 13,
  139487. 6,
  139488. 14,
  139489. 5,
  139490. 15,
  139491. 4,
  139492. 16,
  139493. 3,
  139494. 17,
  139495. 2,
  139496. 18,
  139497. 1,
  139498. 19,
  139499. 0,
  139500. 20,
  139501. };
  139502. static long _vq_lengthlist__8u0__p7_2[] = {
  139503. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  139504. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  139505. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  139506. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  139507. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  139508. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  139509. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  139510. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  139511. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  139512. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  139513. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  139514. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  139515. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  139516. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  139517. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  139518. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  139519. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  139520. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  139521. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  139522. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  139523. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  139524. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  139525. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  139526. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  139527. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  139528. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  139529. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  139530. 11,12,11,11,11,10,10,11,11,
  139531. };
  139532. static float _vq_quantthresh__8u0__p7_2[] = {
  139533. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  139534. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  139535. 6.5, 7.5, 8.5, 9.5,
  139536. };
  139537. static long _vq_quantmap__8u0__p7_2[] = {
  139538. 19, 17, 15, 13, 11, 9, 7, 5,
  139539. 3, 1, 0, 2, 4, 6, 8, 10,
  139540. 12, 14, 16, 18, 20,
  139541. };
  139542. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  139543. _vq_quantthresh__8u0__p7_2,
  139544. _vq_quantmap__8u0__p7_2,
  139545. 21,
  139546. 21
  139547. };
  139548. static static_codebook _8u0__p7_2 = {
  139549. 2, 441,
  139550. _vq_lengthlist__8u0__p7_2,
  139551. 1, -529268736, 1611661312, 5, 0,
  139552. _vq_quantlist__8u0__p7_2,
  139553. NULL,
  139554. &_vq_auxt__8u0__p7_2,
  139555. NULL,
  139556. 0
  139557. };
  139558. static long _huff_lengthlist__8u0__single[] = {
  139559. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  139560. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  139561. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  139562. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  139563. };
  139564. static static_codebook _huff_book__8u0__single = {
  139565. 2, 64,
  139566. _huff_lengthlist__8u0__single,
  139567. 0, 0, 0, 0, 0,
  139568. NULL,
  139569. NULL,
  139570. NULL,
  139571. NULL,
  139572. 0
  139573. };
  139574. static long _vq_quantlist__8u1__p1_0[] = {
  139575. 1,
  139576. 0,
  139577. 2,
  139578. };
  139579. static long _vq_lengthlist__8u1__p1_0[] = {
  139580. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  139581. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  139582. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  139583. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  139584. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  139585. 10,
  139586. };
  139587. static float _vq_quantthresh__8u1__p1_0[] = {
  139588. -0.5, 0.5,
  139589. };
  139590. static long _vq_quantmap__8u1__p1_0[] = {
  139591. 1, 0, 2,
  139592. };
  139593. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  139594. _vq_quantthresh__8u1__p1_0,
  139595. _vq_quantmap__8u1__p1_0,
  139596. 3,
  139597. 3
  139598. };
  139599. static static_codebook _8u1__p1_0 = {
  139600. 4, 81,
  139601. _vq_lengthlist__8u1__p1_0,
  139602. 1, -535822336, 1611661312, 2, 0,
  139603. _vq_quantlist__8u1__p1_0,
  139604. NULL,
  139605. &_vq_auxt__8u1__p1_0,
  139606. NULL,
  139607. 0
  139608. };
  139609. static long _vq_quantlist__8u1__p2_0[] = {
  139610. 1,
  139611. 0,
  139612. 2,
  139613. };
  139614. static long _vq_lengthlist__8u1__p2_0[] = {
  139615. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  139616. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  139617. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  139618. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  139619. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  139620. 7,
  139621. };
  139622. static float _vq_quantthresh__8u1__p2_0[] = {
  139623. -0.5, 0.5,
  139624. };
  139625. static long _vq_quantmap__8u1__p2_0[] = {
  139626. 1, 0, 2,
  139627. };
  139628. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  139629. _vq_quantthresh__8u1__p2_0,
  139630. _vq_quantmap__8u1__p2_0,
  139631. 3,
  139632. 3
  139633. };
  139634. static static_codebook _8u1__p2_0 = {
  139635. 4, 81,
  139636. _vq_lengthlist__8u1__p2_0,
  139637. 1, -535822336, 1611661312, 2, 0,
  139638. _vq_quantlist__8u1__p2_0,
  139639. NULL,
  139640. &_vq_auxt__8u1__p2_0,
  139641. NULL,
  139642. 0
  139643. };
  139644. static long _vq_quantlist__8u1__p3_0[] = {
  139645. 2,
  139646. 1,
  139647. 3,
  139648. 0,
  139649. 4,
  139650. };
  139651. static long _vq_lengthlist__8u1__p3_0[] = {
  139652. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  139653. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  139654. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  139655. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  139656. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  139657. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  139658. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  139659. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  139660. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  139661. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  139662. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  139663. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  139664. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  139665. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  139666. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  139667. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  139668. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  139669. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  139670. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  139671. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  139672. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  139673. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  139674. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  139675. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  139676. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  139677. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  139678. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  139679. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  139680. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  139681. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  139682. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  139683. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  139684. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  139685. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  139686. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  139687. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  139688. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  139689. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  139690. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  139691. 16,
  139692. };
  139693. static float _vq_quantthresh__8u1__p3_0[] = {
  139694. -1.5, -0.5, 0.5, 1.5,
  139695. };
  139696. static long _vq_quantmap__8u1__p3_0[] = {
  139697. 3, 1, 0, 2, 4,
  139698. };
  139699. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  139700. _vq_quantthresh__8u1__p3_0,
  139701. _vq_quantmap__8u1__p3_0,
  139702. 5,
  139703. 5
  139704. };
  139705. static static_codebook _8u1__p3_0 = {
  139706. 4, 625,
  139707. _vq_lengthlist__8u1__p3_0,
  139708. 1, -533725184, 1611661312, 3, 0,
  139709. _vq_quantlist__8u1__p3_0,
  139710. NULL,
  139711. &_vq_auxt__8u1__p3_0,
  139712. NULL,
  139713. 0
  139714. };
  139715. static long _vq_quantlist__8u1__p4_0[] = {
  139716. 2,
  139717. 1,
  139718. 3,
  139719. 0,
  139720. 4,
  139721. };
  139722. static long _vq_lengthlist__8u1__p4_0[] = {
  139723. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  139724. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  139725. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  139726. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  139727. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  139728. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  139729. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  139730. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  139731. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  139732. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  139733. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  139734. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  139735. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  139736. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  139737. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  139738. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  139739. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  139740. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  139741. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  139742. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  139743. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  139744. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  139745. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  139746. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  139747. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  139748. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  139749. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  139750. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  139751. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  139752. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  139753. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  139754. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  139755. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  139756. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  139757. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  139758. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  139759. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  139760. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  139761. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  139762. 10,
  139763. };
  139764. static float _vq_quantthresh__8u1__p4_0[] = {
  139765. -1.5, -0.5, 0.5, 1.5,
  139766. };
  139767. static long _vq_quantmap__8u1__p4_0[] = {
  139768. 3, 1, 0, 2, 4,
  139769. };
  139770. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  139771. _vq_quantthresh__8u1__p4_0,
  139772. _vq_quantmap__8u1__p4_0,
  139773. 5,
  139774. 5
  139775. };
  139776. static static_codebook _8u1__p4_0 = {
  139777. 4, 625,
  139778. _vq_lengthlist__8u1__p4_0,
  139779. 1, -533725184, 1611661312, 3, 0,
  139780. _vq_quantlist__8u1__p4_0,
  139781. NULL,
  139782. &_vq_auxt__8u1__p4_0,
  139783. NULL,
  139784. 0
  139785. };
  139786. static long _vq_quantlist__8u1__p5_0[] = {
  139787. 4,
  139788. 3,
  139789. 5,
  139790. 2,
  139791. 6,
  139792. 1,
  139793. 7,
  139794. 0,
  139795. 8,
  139796. };
  139797. static long _vq_lengthlist__8u1__p5_0[] = {
  139798. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  139799. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  139800. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  139801. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  139802. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  139803. 13,
  139804. };
  139805. static float _vq_quantthresh__8u1__p5_0[] = {
  139806. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139807. };
  139808. static long _vq_quantmap__8u1__p5_0[] = {
  139809. 7, 5, 3, 1, 0, 2, 4, 6,
  139810. 8,
  139811. };
  139812. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  139813. _vq_quantthresh__8u1__p5_0,
  139814. _vq_quantmap__8u1__p5_0,
  139815. 9,
  139816. 9
  139817. };
  139818. static static_codebook _8u1__p5_0 = {
  139819. 2, 81,
  139820. _vq_lengthlist__8u1__p5_0,
  139821. 1, -531628032, 1611661312, 4, 0,
  139822. _vq_quantlist__8u1__p5_0,
  139823. NULL,
  139824. &_vq_auxt__8u1__p5_0,
  139825. NULL,
  139826. 0
  139827. };
  139828. static long _vq_quantlist__8u1__p6_0[] = {
  139829. 4,
  139830. 3,
  139831. 5,
  139832. 2,
  139833. 6,
  139834. 1,
  139835. 7,
  139836. 0,
  139837. 8,
  139838. };
  139839. static long _vq_lengthlist__8u1__p6_0[] = {
  139840. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  139841. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  139842. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  139843. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  139844. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  139845. 10,
  139846. };
  139847. static float _vq_quantthresh__8u1__p6_0[] = {
  139848. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139849. };
  139850. static long _vq_quantmap__8u1__p6_0[] = {
  139851. 7, 5, 3, 1, 0, 2, 4, 6,
  139852. 8,
  139853. };
  139854. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  139855. _vq_quantthresh__8u1__p6_0,
  139856. _vq_quantmap__8u1__p6_0,
  139857. 9,
  139858. 9
  139859. };
  139860. static static_codebook _8u1__p6_0 = {
  139861. 2, 81,
  139862. _vq_lengthlist__8u1__p6_0,
  139863. 1, -531628032, 1611661312, 4, 0,
  139864. _vq_quantlist__8u1__p6_0,
  139865. NULL,
  139866. &_vq_auxt__8u1__p6_0,
  139867. NULL,
  139868. 0
  139869. };
  139870. static long _vq_quantlist__8u1__p7_0[] = {
  139871. 1,
  139872. 0,
  139873. 2,
  139874. };
  139875. static long _vq_lengthlist__8u1__p7_0[] = {
  139876. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  139877. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  139878. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  139879. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  139880. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  139881. 11,
  139882. };
  139883. static float _vq_quantthresh__8u1__p7_0[] = {
  139884. -5.5, 5.5,
  139885. };
  139886. static long _vq_quantmap__8u1__p7_0[] = {
  139887. 1, 0, 2,
  139888. };
  139889. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  139890. _vq_quantthresh__8u1__p7_0,
  139891. _vq_quantmap__8u1__p7_0,
  139892. 3,
  139893. 3
  139894. };
  139895. static static_codebook _8u1__p7_0 = {
  139896. 4, 81,
  139897. _vq_lengthlist__8u1__p7_0,
  139898. 1, -529137664, 1618345984, 2, 0,
  139899. _vq_quantlist__8u1__p7_0,
  139900. NULL,
  139901. &_vq_auxt__8u1__p7_0,
  139902. NULL,
  139903. 0
  139904. };
  139905. static long _vq_quantlist__8u1__p7_1[] = {
  139906. 5,
  139907. 4,
  139908. 6,
  139909. 3,
  139910. 7,
  139911. 2,
  139912. 8,
  139913. 1,
  139914. 9,
  139915. 0,
  139916. 10,
  139917. };
  139918. static long _vq_lengthlist__8u1__p7_1[] = {
  139919. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  139920. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  139921. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  139922. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  139923. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  139924. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  139925. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  139926. 9, 9, 9, 9, 9,10,10,10,10,
  139927. };
  139928. static float _vq_quantthresh__8u1__p7_1[] = {
  139929. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139930. 3.5, 4.5,
  139931. };
  139932. static long _vq_quantmap__8u1__p7_1[] = {
  139933. 9, 7, 5, 3, 1, 0, 2, 4,
  139934. 6, 8, 10,
  139935. };
  139936. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  139937. _vq_quantthresh__8u1__p7_1,
  139938. _vq_quantmap__8u1__p7_1,
  139939. 11,
  139940. 11
  139941. };
  139942. static static_codebook _8u1__p7_1 = {
  139943. 2, 121,
  139944. _vq_lengthlist__8u1__p7_1,
  139945. 1, -531365888, 1611661312, 4, 0,
  139946. _vq_quantlist__8u1__p7_1,
  139947. NULL,
  139948. &_vq_auxt__8u1__p7_1,
  139949. NULL,
  139950. 0
  139951. };
  139952. static long _vq_quantlist__8u1__p8_0[] = {
  139953. 5,
  139954. 4,
  139955. 6,
  139956. 3,
  139957. 7,
  139958. 2,
  139959. 8,
  139960. 1,
  139961. 9,
  139962. 0,
  139963. 10,
  139964. };
  139965. static long _vq_lengthlist__8u1__p8_0[] = {
  139966. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  139967. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  139968. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  139969. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  139970. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  139971. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  139972. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  139973. 12,13,13,14,14,15,15,15,15,
  139974. };
  139975. static float _vq_quantthresh__8u1__p8_0[] = {
  139976. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  139977. 38.5, 49.5,
  139978. };
  139979. static long _vq_quantmap__8u1__p8_0[] = {
  139980. 9, 7, 5, 3, 1, 0, 2, 4,
  139981. 6, 8, 10,
  139982. };
  139983. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  139984. _vq_quantthresh__8u1__p8_0,
  139985. _vq_quantmap__8u1__p8_0,
  139986. 11,
  139987. 11
  139988. };
  139989. static static_codebook _8u1__p8_0 = {
  139990. 2, 121,
  139991. _vq_lengthlist__8u1__p8_0,
  139992. 1, -524582912, 1618345984, 4, 0,
  139993. _vq_quantlist__8u1__p8_0,
  139994. NULL,
  139995. &_vq_auxt__8u1__p8_0,
  139996. NULL,
  139997. 0
  139998. };
  139999. static long _vq_quantlist__8u1__p8_1[] = {
  140000. 5,
  140001. 4,
  140002. 6,
  140003. 3,
  140004. 7,
  140005. 2,
  140006. 8,
  140007. 1,
  140008. 9,
  140009. 0,
  140010. 10,
  140011. };
  140012. static long _vq_lengthlist__8u1__p8_1[] = {
  140013. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  140014. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  140015. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  140016. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  140017. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140018. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  140019. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  140020. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  140021. };
  140022. static float _vq_quantthresh__8u1__p8_1[] = {
  140023. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140024. 3.5, 4.5,
  140025. };
  140026. static long _vq_quantmap__8u1__p8_1[] = {
  140027. 9, 7, 5, 3, 1, 0, 2, 4,
  140028. 6, 8, 10,
  140029. };
  140030. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  140031. _vq_quantthresh__8u1__p8_1,
  140032. _vq_quantmap__8u1__p8_1,
  140033. 11,
  140034. 11
  140035. };
  140036. static static_codebook _8u1__p8_1 = {
  140037. 2, 121,
  140038. _vq_lengthlist__8u1__p8_1,
  140039. 1, -531365888, 1611661312, 4, 0,
  140040. _vq_quantlist__8u1__p8_1,
  140041. NULL,
  140042. &_vq_auxt__8u1__p8_1,
  140043. NULL,
  140044. 0
  140045. };
  140046. static long _vq_quantlist__8u1__p9_0[] = {
  140047. 7,
  140048. 6,
  140049. 8,
  140050. 5,
  140051. 9,
  140052. 4,
  140053. 10,
  140054. 3,
  140055. 11,
  140056. 2,
  140057. 12,
  140058. 1,
  140059. 13,
  140060. 0,
  140061. 14,
  140062. };
  140063. static long _vq_lengthlist__8u1__p9_0[] = {
  140064. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  140065. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  140066. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140067. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140068. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140069. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140070. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140071. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140072. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140073. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140074. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140075. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140076. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  140077. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140078. 10,
  140079. };
  140080. static float _vq_quantthresh__8u1__p9_0[] = {
  140081. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  140082. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  140083. };
  140084. static long _vq_quantmap__8u1__p9_0[] = {
  140085. 13, 11, 9, 7, 5, 3, 1, 0,
  140086. 2, 4, 6, 8, 10, 12, 14,
  140087. };
  140088. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  140089. _vq_quantthresh__8u1__p9_0,
  140090. _vq_quantmap__8u1__p9_0,
  140091. 15,
  140092. 15
  140093. };
  140094. static static_codebook _8u1__p9_0 = {
  140095. 2, 225,
  140096. _vq_lengthlist__8u1__p9_0,
  140097. 1, -514071552, 1627381760, 4, 0,
  140098. _vq_quantlist__8u1__p9_0,
  140099. NULL,
  140100. &_vq_auxt__8u1__p9_0,
  140101. NULL,
  140102. 0
  140103. };
  140104. static long _vq_quantlist__8u1__p9_1[] = {
  140105. 7,
  140106. 6,
  140107. 8,
  140108. 5,
  140109. 9,
  140110. 4,
  140111. 10,
  140112. 3,
  140113. 11,
  140114. 2,
  140115. 12,
  140116. 1,
  140117. 13,
  140118. 0,
  140119. 14,
  140120. };
  140121. static long _vq_lengthlist__8u1__p9_1[] = {
  140122. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  140123. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  140124. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  140125. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  140126. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  140127. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  140128. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  140129. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  140130. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  140131. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  140132. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  140133. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  140134. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  140135. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  140136. 13,
  140137. };
  140138. static float _vq_quantthresh__8u1__p9_1[] = {
  140139. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  140140. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  140141. };
  140142. static long _vq_quantmap__8u1__p9_1[] = {
  140143. 13, 11, 9, 7, 5, 3, 1, 0,
  140144. 2, 4, 6, 8, 10, 12, 14,
  140145. };
  140146. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  140147. _vq_quantthresh__8u1__p9_1,
  140148. _vq_quantmap__8u1__p9_1,
  140149. 15,
  140150. 15
  140151. };
  140152. static static_codebook _8u1__p9_1 = {
  140153. 2, 225,
  140154. _vq_lengthlist__8u1__p9_1,
  140155. 1, -522338304, 1620115456, 4, 0,
  140156. _vq_quantlist__8u1__p9_1,
  140157. NULL,
  140158. &_vq_auxt__8u1__p9_1,
  140159. NULL,
  140160. 0
  140161. };
  140162. static long _vq_quantlist__8u1__p9_2[] = {
  140163. 8,
  140164. 7,
  140165. 9,
  140166. 6,
  140167. 10,
  140168. 5,
  140169. 11,
  140170. 4,
  140171. 12,
  140172. 3,
  140173. 13,
  140174. 2,
  140175. 14,
  140176. 1,
  140177. 15,
  140178. 0,
  140179. 16,
  140180. };
  140181. static long _vq_lengthlist__8u1__p9_2[] = {
  140182. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  140183. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  140184. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  140185. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  140186. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140187. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  140188. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140189. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  140190. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  140191. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  140192. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  140193. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  140194. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  140195. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  140196. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  140197. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  140198. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140199. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140200. 10,
  140201. };
  140202. static float _vq_quantthresh__8u1__p9_2[] = {
  140203. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140204. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140205. };
  140206. static long _vq_quantmap__8u1__p9_2[] = {
  140207. 15, 13, 11, 9, 7, 5, 3, 1,
  140208. 0, 2, 4, 6, 8, 10, 12, 14,
  140209. 16,
  140210. };
  140211. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  140212. _vq_quantthresh__8u1__p9_2,
  140213. _vq_quantmap__8u1__p9_2,
  140214. 17,
  140215. 17
  140216. };
  140217. static static_codebook _8u1__p9_2 = {
  140218. 2, 289,
  140219. _vq_lengthlist__8u1__p9_2,
  140220. 1, -529530880, 1611661312, 5, 0,
  140221. _vq_quantlist__8u1__p9_2,
  140222. NULL,
  140223. &_vq_auxt__8u1__p9_2,
  140224. NULL,
  140225. 0
  140226. };
  140227. static long _huff_lengthlist__8u1__single[] = {
  140228. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  140229. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  140230. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  140231. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  140232. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  140233. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  140234. 13, 8, 8,15,
  140235. };
  140236. static static_codebook _huff_book__8u1__single = {
  140237. 2, 100,
  140238. _huff_lengthlist__8u1__single,
  140239. 0, 0, 0, 0, 0,
  140240. NULL,
  140241. NULL,
  140242. NULL,
  140243. NULL,
  140244. 0
  140245. };
  140246. static long _huff_lengthlist__44u0__long[] = {
  140247. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  140248. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  140249. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  140250. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  140251. };
  140252. static static_codebook _huff_book__44u0__long = {
  140253. 2, 64,
  140254. _huff_lengthlist__44u0__long,
  140255. 0, 0, 0, 0, 0,
  140256. NULL,
  140257. NULL,
  140258. NULL,
  140259. NULL,
  140260. 0
  140261. };
  140262. static long _vq_quantlist__44u0__p1_0[] = {
  140263. 1,
  140264. 0,
  140265. 2,
  140266. };
  140267. static long _vq_lengthlist__44u0__p1_0[] = {
  140268. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  140269. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  140270. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  140271. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  140272. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  140273. 13,
  140274. };
  140275. static float _vq_quantthresh__44u0__p1_0[] = {
  140276. -0.5, 0.5,
  140277. };
  140278. static long _vq_quantmap__44u0__p1_0[] = {
  140279. 1, 0, 2,
  140280. };
  140281. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  140282. _vq_quantthresh__44u0__p1_0,
  140283. _vq_quantmap__44u0__p1_0,
  140284. 3,
  140285. 3
  140286. };
  140287. static static_codebook _44u0__p1_0 = {
  140288. 4, 81,
  140289. _vq_lengthlist__44u0__p1_0,
  140290. 1, -535822336, 1611661312, 2, 0,
  140291. _vq_quantlist__44u0__p1_0,
  140292. NULL,
  140293. &_vq_auxt__44u0__p1_0,
  140294. NULL,
  140295. 0
  140296. };
  140297. static long _vq_quantlist__44u0__p2_0[] = {
  140298. 1,
  140299. 0,
  140300. 2,
  140301. };
  140302. static long _vq_lengthlist__44u0__p2_0[] = {
  140303. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  140304. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  140305. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  140306. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  140307. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  140308. 9,
  140309. };
  140310. static float _vq_quantthresh__44u0__p2_0[] = {
  140311. -0.5, 0.5,
  140312. };
  140313. static long _vq_quantmap__44u0__p2_0[] = {
  140314. 1, 0, 2,
  140315. };
  140316. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  140317. _vq_quantthresh__44u0__p2_0,
  140318. _vq_quantmap__44u0__p2_0,
  140319. 3,
  140320. 3
  140321. };
  140322. static static_codebook _44u0__p2_0 = {
  140323. 4, 81,
  140324. _vq_lengthlist__44u0__p2_0,
  140325. 1, -535822336, 1611661312, 2, 0,
  140326. _vq_quantlist__44u0__p2_0,
  140327. NULL,
  140328. &_vq_auxt__44u0__p2_0,
  140329. NULL,
  140330. 0
  140331. };
  140332. static long _vq_quantlist__44u0__p3_0[] = {
  140333. 2,
  140334. 1,
  140335. 3,
  140336. 0,
  140337. 4,
  140338. };
  140339. static long _vq_lengthlist__44u0__p3_0[] = {
  140340. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  140341. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  140342. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  140343. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  140344. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  140345. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  140346. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  140347. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  140348. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  140349. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  140350. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  140351. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  140352. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  140353. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  140354. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  140355. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  140356. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  140357. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  140358. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  140359. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  140360. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  140361. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  140362. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  140363. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  140364. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  140365. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  140366. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  140367. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  140368. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  140369. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  140370. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  140371. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  140372. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  140373. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  140374. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  140375. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  140376. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  140377. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  140378. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  140379. 19,
  140380. };
  140381. static float _vq_quantthresh__44u0__p3_0[] = {
  140382. -1.5, -0.5, 0.5, 1.5,
  140383. };
  140384. static long _vq_quantmap__44u0__p3_0[] = {
  140385. 3, 1, 0, 2, 4,
  140386. };
  140387. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  140388. _vq_quantthresh__44u0__p3_0,
  140389. _vq_quantmap__44u0__p3_0,
  140390. 5,
  140391. 5
  140392. };
  140393. static static_codebook _44u0__p3_0 = {
  140394. 4, 625,
  140395. _vq_lengthlist__44u0__p3_0,
  140396. 1, -533725184, 1611661312, 3, 0,
  140397. _vq_quantlist__44u0__p3_0,
  140398. NULL,
  140399. &_vq_auxt__44u0__p3_0,
  140400. NULL,
  140401. 0
  140402. };
  140403. static long _vq_quantlist__44u0__p4_0[] = {
  140404. 2,
  140405. 1,
  140406. 3,
  140407. 0,
  140408. 4,
  140409. };
  140410. static long _vq_lengthlist__44u0__p4_0[] = {
  140411. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  140412. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  140413. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  140414. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  140415. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  140416. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  140417. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  140418. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  140419. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  140420. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  140421. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  140422. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  140423. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  140424. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  140425. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  140426. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  140427. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  140428. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  140429. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  140430. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  140431. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  140432. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  140433. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  140434. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  140435. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  140436. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  140437. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  140438. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  140439. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  140440. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  140441. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  140442. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  140443. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  140444. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  140445. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  140446. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  140447. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  140448. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  140449. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  140450. 12,
  140451. };
  140452. static float _vq_quantthresh__44u0__p4_0[] = {
  140453. -1.5, -0.5, 0.5, 1.5,
  140454. };
  140455. static long _vq_quantmap__44u0__p4_0[] = {
  140456. 3, 1, 0, 2, 4,
  140457. };
  140458. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  140459. _vq_quantthresh__44u0__p4_0,
  140460. _vq_quantmap__44u0__p4_0,
  140461. 5,
  140462. 5
  140463. };
  140464. static static_codebook _44u0__p4_0 = {
  140465. 4, 625,
  140466. _vq_lengthlist__44u0__p4_0,
  140467. 1, -533725184, 1611661312, 3, 0,
  140468. _vq_quantlist__44u0__p4_0,
  140469. NULL,
  140470. &_vq_auxt__44u0__p4_0,
  140471. NULL,
  140472. 0
  140473. };
  140474. static long _vq_quantlist__44u0__p5_0[] = {
  140475. 4,
  140476. 3,
  140477. 5,
  140478. 2,
  140479. 6,
  140480. 1,
  140481. 7,
  140482. 0,
  140483. 8,
  140484. };
  140485. static long _vq_lengthlist__44u0__p5_0[] = {
  140486. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  140487. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  140488. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  140489. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  140490. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  140491. 12,
  140492. };
  140493. static float _vq_quantthresh__44u0__p5_0[] = {
  140494. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140495. };
  140496. static long _vq_quantmap__44u0__p5_0[] = {
  140497. 7, 5, 3, 1, 0, 2, 4, 6,
  140498. 8,
  140499. };
  140500. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  140501. _vq_quantthresh__44u0__p5_0,
  140502. _vq_quantmap__44u0__p5_0,
  140503. 9,
  140504. 9
  140505. };
  140506. static static_codebook _44u0__p5_0 = {
  140507. 2, 81,
  140508. _vq_lengthlist__44u0__p5_0,
  140509. 1, -531628032, 1611661312, 4, 0,
  140510. _vq_quantlist__44u0__p5_0,
  140511. NULL,
  140512. &_vq_auxt__44u0__p5_0,
  140513. NULL,
  140514. 0
  140515. };
  140516. static long _vq_quantlist__44u0__p6_0[] = {
  140517. 6,
  140518. 5,
  140519. 7,
  140520. 4,
  140521. 8,
  140522. 3,
  140523. 9,
  140524. 2,
  140525. 10,
  140526. 1,
  140527. 11,
  140528. 0,
  140529. 12,
  140530. };
  140531. static long _vq_lengthlist__44u0__p6_0[] = {
  140532. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  140533. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  140534. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  140535. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  140536. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  140537. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  140538. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  140539. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  140540. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  140541. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  140542. 15,17,16,17,18,17,17,18, 0,
  140543. };
  140544. static float _vq_quantthresh__44u0__p6_0[] = {
  140545. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140546. 12.5, 17.5, 22.5, 27.5,
  140547. };
  140548. static long _vq_quantmap__44u0__p6_0[] = {
  140549. 11, 9, 7, 5, 3, 1, 0, 2,
  140550. 4, 6, 8, 10, 12,
  140551. };
  140552. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  140553. _vq_quantthresh__44u0__p6_0,
  140554. _vq_quantmap__44u0__p6_0,
  140555. 13,
  140556. 13
  140557. };
  140558. static static_codebook _44u0__p6_0 = {
  140559. 2, 169,
  140560. _vq_lengthlist__44u0__p6_0,
  140561. 1, -526516224, 1616117760, 4, 0,
  140562. _vq_quantlist__44u0__p6_0,
  140563. NULL,
  140564. &_vq_auxt__44u0__p6_0,
  140565. NULL,
  140566. 0
  140567. };
  140568. static long _vq_quantlist__44u0__p6_1[] = {
  140569. 2,
  140570. 1,
  140571. 3,
  140572. 0,
  140573. 4,
  140574. };
  140575. static long _vq_lengthlist__44u0__p6_1[] = {
  140576. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  140577. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  140578. };
  140579. static float _vq_quantthresh__44u0__p6_1[] = {
  140580. -1.5, -0.5, 0.5, 1.5,
  140581. };
  140582. static long _vq_quantmap__44u0__p6_1[] = {
  140583. 3, 1, 0, 2, 4,
  140584. };
  140585. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  140586. _vq_quantthresh__44u0__p6_1,
  140587. _vq_quantmap__44u0__p6_1,
  140588. 5,
  140589. 5
  140590. };
  140591. static static_codebook _44u0__p6_1 = {
  140592. 2, 25,
  140593. _vq_lengthlist__44u0__p6_1,
  140594. 1, -533725184, 1611661312, 3, 0,
  140595. _vq_quantlist__44u0__p6_1,
  140596. NULL,
  140597. &_vq_auxt__44u0__p6_1,
  140598. NULL,
  140599. 0
  140600. };
  140601. static long _vq_quantlist__44u0__p7_0[] = {
  140602. 2,
  140603. 1,
  140604. 3,
  140605. 0,
  140606. 4,
  140607. };
  140608. static long _vq_lengthlist__44u0__p7_0[] = {
  140609. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  140610. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140611. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140612. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140613. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140614. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140615. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140616. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  140617. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140618. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140619. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140620. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140621. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140622. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140623. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140624. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140625. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140626. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140627. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140628. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140629. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140630. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140631. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140632. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140633. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140634. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140635. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140636. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140637. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140638. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140639. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  140640. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140641. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140642. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140643. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140644. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140645. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140646. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140647. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140648. 10,
  140649. };
  140650. static float _vq_quantthresh__44u0__p7_0[] = {
  140651. -253.5, -84.5, 84.5, 253.5,
  140652. };
  140653. static long _vq_quantmap__44u0__p7_0[] = {
  140654. 3, 1, 0, 2, 4,
  140655. };
  140656. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  140657. _vq_quantthresh__44u0__p7_0,
  140658. _vq_quantmap__44u0__p7_0,
  140659. 5,
  140660. 5
  140661. };
  140662. static static_codebook _44u0__p7_0 = {
  140663. 4, 625,
  140664. _vq_lengthlist__44u0__p7_0,
  140665. 1, -518709248, 1626677248, 3, 0,
  140666. _vq_quantlist__44u0__p7_0,
  140667. NULL,
  140668. &_vq_auxt__44u0__p7_0,
  140669. NULL,
  140670. 0
  140671. };
  140672. static long _vq_quantlist__44u0__p7_1[] = {
  140673. 6,
  140674. 5,
  140675. 7,
  140676. 4,
  140677. 8,
  140678. 3,
  140679. 9,
  140680. 2,
  140681. 10,
  140682. 1,
  140683. 11,
  140684. 0,
  140685. 12,
  140686. };
  140687. static long _vq_lengthlist__44u0__p7_1[] = {
  140688. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  140689. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  140690. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  140691. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  140692. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  140693. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  140694. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  140695. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  140696. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  140697. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  140698. 15,15,15,15,15,15,15,15,15,
  140699. };
  140700. static float _vq_quantthresh__44u0__p7_1[] = {
  140701. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  140702. 32.5, 45.5, 58.5, 71.5,
  140703. };
  140704. static long _vq_quantmap__44u0__p7_1[] = {
  140705. 11, 9, 7, 5, 3, 1, 0, 2,
  140706. 4, 6, 8, 10, 12,
  140707. };
  140708. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  140709. _vq_quantthresh__44u0__p7_1,
  140710. _vq_quantmap__44u0__p7_1,
  140711. 13,
  140712. 13
  140713. };
  140714. static static_codebook _44u0__p7_1 = {
  140715. 2, 169,
  140716. _vq_lengthlist__44u0__p7_1,
  140717. 1, -523010048, 1618608128, 4, 0,
  140718. _vq_quantlist__44u0__p7_1,
  140719. NULL,
  140720. &_vq_auxt__44u0__p7_1,
  140721. NULL,
  140722. 0
  140723. };
  140724. static long _vq_quantlist__44u0__p7_2[] = {
  140725. 6,
  140726. 5,
  140727. 7,
  140728. 4,
  140729. 8,
  140730. 3,
  140731. 9,
  140732. 2,
  140733. 10,
  140734. 1,
  140735. 11,
  140736. 0,
  140737. 12,
  140738. };
  140739. static long _vq_lengthlist__44u0__p7_2[] = {
  140740. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  140741. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  140742. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  140743. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  140744. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  140745. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  140746. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  140747. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140748. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140749. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  140750. 9, 9, 9,10, 9, 9,10,10, 9,
  140751. };
  140752. static float _vq_quantthresh__44u0__p7_2[] = {
  140753. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  140754. 2.5, 3.5, 4.5, 5.5,
  140755. };
  140756. static long _vq_quantmap__44u0__p7_2[] = {
  140757. 11, 9, 7, 5, 3, 1, 0, 2,
  140758. 4, 6, 8, 10, 12,
  140759. };
  140760. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  140761. _vq_quantthresh__44u0__p7_2,
  140762. _vq_quantmap__44u0__p7_2,
  140763. 13,
  140764. 13
  140765. };
  140766. static static_codebook _44u0__p7_2 = {
  140767. 2, 169,
  140768. _vq_lengthlist__44u0__p7_2,
  140769. 1, -531103744, 1611661312, 4, 0,
  140770. _vq_quantlist__44u0__p7_2,
  140771. NULL,
  140772. &_vq_auxt__44u0__p7_2,
  140773. NULL,
  140774. 0
  140775. };
  140776. static long _huff_lengthlist__44u0__short[] = {
  140777. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  140778. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  140779. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  140780. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  140781. };
  140782. static static_codebook _huff_book__44u0__short = {
  140783. 2, 64,
  140784. _huff_lengthlist__44u0__short,
  140785. 0, 0, 0, 0, 0,
  140786. NULL,
  140787. NULL,
  140788. NULL,
  140789. NULL,
  140790. 0
  140791. };
  140792. static long _huff_lengthlist__44u1__long[] = {
  140793. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  140794. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  140795. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  140796. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  140797. };
  140798. static static_codebook _huff_book__44u1__long = {
  140799. 2, 64,
  140800. _huff_lengthlist__44u1__long,
  140801. 0, 0, 0, 0, 0,
  140802. NULL,
  140803. NULL,
  140804. NULL,
  140805. NULL,
  140806. 0
  140807. };
  140808. static long _vq_quantlist__44u1__p1_0[] = {
  140809. 1,
  140810. 0,
  140811. 2,
  140812. };
  140813. static long _vq_lengthlist__44u1__p1_0[] = {
  140814. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  140815. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  140816. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  140817. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  140818. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  140819. 13,
  140820. };
  140821. static float _vq_quantthresh__44u1__p1_0[] = {
  140822. -0.5, 0.5,
  140823. };
  140824. static long _vq_quantmap__44u1__p1_0[] = {
  140825. 1, 0, 2,
  140826. };
  140827. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  140828. _vq_quantthresh__44u1__p1_0,
  140829. _vq_quantmap__44u1__p1_0,
  140830. 3,
  140831. 3
  140832. };
  140833. static static_codebook _44u1__p1_0 = {
  140834. 4, 81,
  140835. _vq_lengthlist__44u1__p1_0,
  140836. 1, -535822336, 1611661312, 2, 0,
  140837. _vq_quantlist__44u1__p1_0,
  140838. NULL,
  140839. &_vq_auxt__44u1__p1_0,
  140840. NULL,
  140841. 0
  140842. };
  140843. static long _vq_quantlist__44u1__p2_0[] = {
  140844. 1,
  140845. 0,
  140846. 2,
  140847. };
  140848. static long _vq_lengthlist__44u1__p2_0[] = {
  140849. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  140850. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  140851. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  140852. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  140853. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  140854. 9,
  140855. };
  140856. static float _vq_quantthresh__44u1__p2_0[] = {
  140857. -0.5, 0.5,
  140858. };
  140859. static long _vq_quantmap__44u1__p2_0[] = {
  140860. 1, 0, 2,
  140861. };
  140862. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  140863. _vq_quantthresh__44u1__p2_0,
  140864. _vq_quantmap__44u1__p2_0,
  140865. 3,
  140866. 3
  140867. };
  140868. static static_codebook _44u1__p2_0 = {
  140869. 4, 81,
  140870. _vq_lengthlist__44u1__p2_0,
  140871. 1, -535822336, 1611661312, 2, 0,
  140872. _vq_quantlist__44u1__p2_0,
  140873. NULL,
  140874. &_vq_auxt__44u1__p2_0,
  140875. NULL,
  140876. 0
  140877. };
  140878. static long _vq_quantlist__44u1__p3_0[] = {
  140879. 2,
  140880. 1,
  140881. 3,
  140882. 0,
  140883. 4,
  140884. };
  140885. static long _vq_lengthlist__44u1__p3_0[] = {
  140886. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  140887. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  140888. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  140889. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  140890. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  140891. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  140892. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  140893. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  140894. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  140895. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  140896. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  140897. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  140898. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  140899. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  140900. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  140901. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  140902. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  140903. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  140904. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  140905. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  140906. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  140907. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  140908. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  140909. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  140910. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  140911. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  140912. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  140913. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  140914. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  140915. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  140916. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  140917. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  140918. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  140919. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  140920. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  140921. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  140922. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  140923. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  140924. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  140925. 19,
  140926. };
  140927. static float _vq_quantthresh__44u1__p3_0[] = {
  140928. -1.5, -0.5, 0.5, 1.5,
  140929. };
  140930. static long _vq_quantmap__44u1__p3_0[] = {
  140931. 3, 1, 0, 2, 4,
  140932. };
  140933. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  140934. _vq_quantthresh__44u1__p3_0,
  140935. _vq_quantmap__44u1__p3_0,
  140936. 5,
  140937. 5
  140938. };
  140939. static static_codebook _44u1__p3_0 = {
  140940. 4, 625,
  140941. _vq_lengthlist__44u1__p3_0,
  140942. 1, -533725184, 1611661312, 3, 0,
  140943. _vq_quantlist__44u1__p3_0,
  140944. NULL,
  140945. &_vq_auxt__44u1__p3_0,
  140946. NULL,
  140947. 0
  140948. };
  140949. static long _vq_quantlist__44u1__p4_0[] = {
  140950. 2,
  140951. 1,
  140952. 3,
  140953. 0,
  140954. 4,
  140955. };
  140956. static long _vq_lengthlist__44u1__p4_0[] = {
  140957. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  140958. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  140959. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  140960. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  140961. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  140962. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  140963. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  140964. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  140965. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  140966. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  140967. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  140968. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  140969. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  140970. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  140971. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  140972. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  140973. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  140974. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  140975. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  140976. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  140977. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  140978. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  140979. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  140980. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  140981. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  140982. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  140983. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  140984. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  140985. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  140986. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  140987. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  140988. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  140989. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  140990. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  140991. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  140992. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  140993. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  140994. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  140995. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  140996. 12,
  140997. };
  140998. static float _vq_quantthresh__44u1__p4_0[] = {
  140999. -1.5, -0.5, 0.5, 1.5,
  141000. };
  141001. static long _vq_quantmap__44u1__p4_0[] = {
  141002. 3, 1, 0, 2, 4,
  141003. };
  141004. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  141005. _vq_quantthresh__44u1__p4_0,
  141006. _vq_quantmap__44u1__p4_0,
  141007. 5,
  141008. 5
  141009. };
  141010. static static_codebook _44u1__p4_0 = {
  141011. 4, 625,
  141012. _vq_lengthlist__44u1__p4_0,
  141013. 1, -533725184, 1611661312, 3, 0,
  141014. _vq_quantlist__44u1__p4_0,
  141015. NULL,
  141016. &_vq_auxt__44u1__p4_0,
  141017. NULL,
  141018. 0
  141019. };
  141020. static long _vq_quantlist__44u1__p5_0[] = {
  141021. 4,
  141022. 3,
  141023. 5,
  141024. 2,
  141025. 6,
  141026. 1,
  141027. 7,
  141028. 0,
  141029. 8,
  141030. };
  141031. static long _vq_lengthlist__44u1__p5_0[] = {
  141032. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  141033. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  141034. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  141035. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  141036. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  141037. 12,
  141038. };
  141039. static float _vq_quantthresh__44u1__p5_0[] = {
  141040. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141041. };
  141042. static long _vq_quantmap__44u1__p5_0[] = {
  141043. 7, 5, 3, 1, 0, 2, 4, 6,
  141044. 8,
  141045. };
  141046. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  141047. _vq_quantthresh__44u1__p5_0,
  141048. _vq_quantmap__44u1__p5_0,
  141049. 9,
  141050. 9
  141051. };
  141052. static static_codebook _44u1__p5_0 = {
  141053. 2, 81,
  141054. _vq_lengthlist__44u1__p5_0,
  141055. 1, -531628032, 1611661312, 4, 0,
  141056. _vq_quantlist__44u1__p5_0,
  141057. NULL,
  141058. &_vq_auxt__44u1__p5_0,
  141059. NULL,
  141060. 0
  141061. };
  141062. static long _vq_quantlist__44u1__p6_0[] = {
  141063. 6,
  141064. 5,
  141065. 7,
  141066. 4,
  141067. 8,
  141068. 3,
  141069. 9,
  141070. 2,
  141071. 10,
  141072. 1,
  141073. 11,
  141074. 0,
  141075. 12,
  141076. };
  141077. static long _vq_lengthlist__44u1__p6_0[] = {
  141078. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  141079. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  141080. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  141081. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  141082. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  141083. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  141084. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  141085. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  141086. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  141087. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  141088. 15,17,16,17,18,17,17,18, 0,
  141089. };
  141090. static float _vq_quantthresh__44u1__p6_0[] = {
  141091. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141092. 12.5, 17.5, 22.5, 27.5,
  141093. };
  141094. static long _vq_quantmap__44u1__p6_0[] = {
  141095. 11, 9, 7, 5, 3, 1, 0, 2,
  141096. 4, 6, 8, 10, 12,
  141097. };
  141098. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  141099. _vq_quantthresh__44u1__p6_0,
  141100. _vq_quantmap__44u1__p6_0,
  141101. 13,
  141102. 13
  141103. };
  141104. static static_codebook _44u1__p6_0 = {
  141105. 2, 169,
  141106. _vq_lengthlist__44u1__p6_0,
  141107. 1, -526516224, 1616117760, 4, 0,
  141108. _vq_quantlist__44u1__p6_0,
  141109. NULL,
  141110. &_vq_auxt__44u1__p6_0,
  141111. NULL,
  141112. 0
  141113. };
  141114. static long _vq_quantlist__44u1__p6_1[] = {
  141115. 2,
  141116. 1,
  141117. 3,
  141118. 0,
  141119. 4,
  141120. };
  141121. static long _vq_lengthlist__44u1__p6_1[] = {
  141122. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  141123. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  141124. };
  141125. static float _vq_quantthresh__44u1__p6_1[] = {
  141126. -1.5, -0.5, 0.5, 1.5,
  141127. };
  141128. static long _vq_quantmap__44u1__p6_1[] = {
  141129. 3, 1, 0, 2, 4,
  141130. };
  141131. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  141132. _vq_quantthresh__44u1__p6_1,
  141133. _vq_quantmap__44u1__p6_1,
  141134. 5,
  141135. 5
  141136. };
  141137. static static_codebook _44u1__p6_1 = {
  141138. 2, 25,
  141139. _vq_lengthlist__44u1__p6_1,
  141140. 1, -533725184, 1611661312, 3, 0,
  141141. _vq_quantlist__44u1__p6_1,
  141142. NULL,
  141143. &_vq_auxt__44u1__p6_1,
  141144. NULL,
  141145. 0
  141146. };
  141147. static long _vq_quantlist__44u1__p7_0[] = {
  141148. 3,
  141149. 2,
  141150. 4,
  141151. 1,
  141152. 5,
  141153. 0,
  141154. 6,
  141155. };
  141156. static long _vq_lengthlist__44u1__p7_0[] = {
  141157. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141158. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141159. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141160. 8,
  141161. };
  141162. static float _vq_quantthresh__44u1__p7_0[] = {
  141163. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  141164. };
  141165. static long _vq_quantmap__44u1__p7_0[] = {
  141166. 5, 3, 1, 0, 2, 4, 6,
  141167. };
  141168. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  141169. _vq_quantthresh__44u1__p7_0,
  141170. _vq_quantmap__44u1__p7_0,
  141171. 7,
  141172. 7
  141173. };
  141174. static static_codebook _44u1__p7_0 = {
  141175. 2, 49,
  141176. _vq_lengthlist__44u1__p7_0,
  141177. 1, -518017024, 1626677248, 3, 0,
  141178. _vq_quantlist__44u1__p7_0,
  141179. NULL,
  141180. &_vq_auxt__44u1__p7_0,
  141181. NULL,
  141182. 0
  141183. };
  141184. static long _vq_quantlist__44u1__p7_1[] = {
  141185. 6,
  141186. 5,
  141187. 7,
  141188. 4,
  141189. 8,
  141190. 3,
  141191. 9,
  141192. 2,
  141193. 10,
  141194. 1,
  141195. 11,
  141196. 0,
  141197. 12,
  141198. };
  141199. static long _vq_lengthlist__44u1__p7_1[] = {
  141200. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  141201. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  141202. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  141203. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  141204. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  141205. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  141206. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  141207. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  141208. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  141209. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  141210. 15,15,15,15,15,15,15,15,15,
  141211. };
  141212. static float _vq_quantthresh__44u1__p7_1[] = {
  141213. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  141214. 32.5, 45.5, 58.5, 71.5,
  141215. };
  141216. static long _vq_quantmap__44u1__p7_1[] = {
  141217. 11, 9, 7, 5, 3, 1, 0, 2,
  141218. 4, 6, 8, 10, 12,
  141219. };
  141220. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  141221. _vq_quantthresh__44u1__p7_1,
  141222. _vq_quantmap__44u1__p7_1,
  141223. 13,
  141224. 13
  141225. };
  141226. static static_codebook _44u1__p7_1 = {
  141227. 2, 169,
  141228. _vq_lengthlist__44u1__p7_1,
  141229. 1, -523010048, 1618608128, 4, 0,
  141230. _vq_quantlist__44u1__p7_1,
  141231. NULL,
  141232. &_vq_auxt__44u1__p7_1,
  141233. NULL,
  141234. 0
  141235. };
  141236. static long _vq_quantlist__44u1__p7_2[] = {
  141237. 6,
  141238. 5,
  141239. 7,
  141240. 4,
  141241. 8,
  141242. 3,
  141243. 9,
  141244. 2,
  141245. 10,
  141246. 1,
  141247. 11,
  141248. 0,
  141249. 12,
  141250. };
  141251. static long _vq_lengthlist__44u1__p7_2[] = {
  141252. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  141253. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  141254. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  141255. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  141256. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  141257. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  141258. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  141259. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141260. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141261. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  141262. 9, 9, 9,10, 9, 9,10,10, 9,
  141263. };
  141264. static float _vq_quantthresh__44u1__p7_2[] = {
  141265. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  141266. 2.5, 3.5, 4.5, 5.5,
  141267. };
  141268. static long _vq_quantmap__44u1__p7_2[] = {
  141269. 11, 9, 7, 5, 3, 1, 0, 2,
  141270. 4, 6, 8, 10, 12,
  141271. };
  141272. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  141273. _vq_quantthresh__44u1__p7_2,
  141274. _vq_quantmap__44u1__p7_2,
  141275. 13,
  141276. 13
  141277. };
  141278. static static_codebook _44u1__p7_2 = {
  141279. 2, 169,
  141280. _vq_lengthlist__44u1__p7_2,
  141281. 1, -531103744, 1611661312, 4, 0,
  141282. _vq_quantlist__44u1__p7_2,
  141283. NULL,
  141284. &_vq_auxt__44u1__p7_2,
  141285. NULL,
  141286. 0
  141287. };
  141288. static long _huff_lengthlist__44u1__short[] = {
  141289. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  141290. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  141291. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  141292. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  141293. };
  141294. static static_codebook _huff_book__44u1__short = {
  141295. 2, 64,
  141296. _huff_lengthlist__44u1__short,
  141297. 0, 0, 0, 0, 0,
  141298. NULL,
  141299. NULL,
  141300. NULL,
  141301. NULL,
  141302. 0
  141303. };
  141304. static long _huff_lengthlist__44u2__long[] = {
  141305. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  141306. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  141307. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  141308. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  141309. };
  141310. static static_codebook _huff_book__44u2__long = {
  141311. 2, 64,
  141312. _huff_lengthlist__44u2__long,
  141313. 0, 0, 0, 0, 0,
  141314. NULL,
  141315. NULL,
  141316. NULL,
  141317. NULL,
  141318. 0
  141319. };
  141320. static long _vq_quantlist__44u2__p1_0[] = {
  141321. 1,
  141322. 0,
  141323. 2,
  141324. };
  141325. static long _vq_lengthlist__44u2__p1_0[] = {
  141326. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  141327. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141328. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  141329. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  141330. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  141331. 13,
  141332. };
  141333. static float _vq_quantthresh__44u2__p1_0[] = {
  141334. -0.5, 0.5,
  141335. };
  141336. static long _vq_quantmap__44u2__p1_0[] = {
  141337. 1, 0, 2,
  141338. };
  141339. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  141340. _vq_quantthresh__44u2__p1_0,
  141341. _vq_quantmap__44u2__p1_0,
  141342. 3,
  141343. 3
  141344. };
  141345. static static_codebook _44u2__p1_0 = {
  141346. 4, 81,
  141347. _vq_lengthlist__44u2__p1_0,
  141348. 1, -535822336, 1611661312, 2, 0,
  141349. _vq_quantlist__44u2__p1_0,
  141350. NULL,
  141351. &_vq_auxt__44u2__p1_0,
  141352. NULL,
  141353. 0
  141354. };
  141355. static long _vq_quantlist__44u2__p2_0[] = {
  141356. 1,
  141357. 0,
  141358. 2,
  141359. };
  141360. static long _vq_lengthlist__44u2__p2_0[] = {
  141361. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  141362. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  141363. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  141364. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  141365. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  141366. 9,
  141367. };
  141368. static float _vq_quantthresh__44u2__p2_0[] = {
  141369. -0.5, 0.5,
  141370. };
  141371. static long _vq_quantmap__44u2__p2_0[] = {
  141372. 1, 0, 2,
  141373. };
  141374. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  141375. _vq_quantthresh__44u2__p2_0,
  141376. _vq_quantmap__44u2__p2_0,
  141377. 3,
  141378. 3
  141379. };
  141380. static static_codebook _44u2__p2_0 = {
  141381. 4, 81,
  141382. _vq_lengthlist__44u2__p2_0,
  141383. 1, -535822336, 1611661312, 2, 0,
  141384. _vq_quantlist__44u2__p2_0,
  141385. NULL,
  141386. &_vq_auxt__44u2__p2_0,
  141387. NULL,
  141388. 0
  141389. };
  141390. static long _vq_quantlist__44u2__p3_0[] = {
  141391. 2,
  141392. 1,
  141393. 3,
  141394. 0,
  141395. 4,
  141396. };
  141397. static long _vq_lengthlist__44u2__p3_0[] = {
  141398. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  141399. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  141400. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  141401. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  141402. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  141403. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  141404. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  141405. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  141406. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  141407. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  141408. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  141409. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  141410. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  141411. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  141412. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  141413. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  141414. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  141415. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  141416. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  141417. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  141418. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  141419. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  141420. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  141421. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  141422. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  141423. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  141424. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  141425. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  141426. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  141427. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  141428. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  141429. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  141430. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  141431. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  141432. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  141433. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  141434. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  141435. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  141436. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  141437. 0,
  141438. };
  141439. static float _vq_quantthresh__44u2__p3_0[] = {
  141440. -1.5, -0.5, 0.5, 1.5,
  141441. };
  141442. static long _vq_quantmap__44u2__p3_0[] = {
  141443. 3, 1, 0, 2, 4,
  141444. };
  141445. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  141446. _vq_quantthresh__44u2__p3_0,
  141447. _vq_quantmap__44u2__p3_0,
  141448. 5,
  141449. 5
  141450. };
  141451. static static_codebook _44u2__p3_0 = {
  141452. 4, 625,
  141453. _vq_lengthlist__44u2__p3_0,
  141454. 1, -533725184, 1611661312, 3, 0,
  141455. _vq_quantlist__44u2__p3_0,
  141456. NULL,
  141457. &_vq_auxt__44u2__p3_0,
  141458. NULL,
  141459. 0
  141460. };
  141461. static long _vq_quantlist__44u2__p4_0[] = {
  141462. 2,
  141463. 1,
  141464. 3,
  141465. 0,
  141466. 4,
  141467. };
  141468. static long _vq_lengthlist__44u2__p4_0[] = {
  141469. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  141470. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  141471. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  141472. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  141473. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  141474. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  141475. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  141476. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  141477. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  141478. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  141479. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  141480. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  141481. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  141482. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  141483. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  141484. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  141485. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  141486. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  141487. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  141488. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  141489. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  141490. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  141491. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  141492. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  141493. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  141494. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  141495. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  141496. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  141497. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  141498. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  141499. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  141500. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  141501. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  141502. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  141503. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  141504. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  141505. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  141506. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  141507. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  141508. 13,
  141509. };
  141510. static float _vq_quantthresh__44u2__p4_0[] = {
  141511. -1.5, -0.5, 0.5, 1.5,
  141512. };
  141513. static long _vq_quantmap__44u2__p4_0[] = {
  141514. 3, 1, 0, 2, 4,
  141515. };
  141516. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  141517. _vq_quantthresh__44u2__p4_0,
  141518. _vq_quantmap__44u2__p4_0,
  141519. 5,
  141520. 5
  141521. };
  141522. static static_codebook _44u2__p4_0 = {
  141523. 4, 625,
  141524. _vq_lengthlist__44u2__p4_0,
  141525. 1, -533725184, 1611661312, 3, 0,
  141526. _vq_quantlist__44u2__p4_0,
  141527. NULL,
  141528. &_vq_auxt__44u2__p4_0,
  141529. NULL,
  141530. 0
  141531. };
  141532. static long _vq_quantlist__44u2__p5_0[] = {
  141533. 4,
  141534. 3,
  141535. 5,
  141536. 2,
  141537. 6,
  141538. 1,
  141539. 7,
  141540. 0,
  141541. 8,
  141542. };
  141543. static long _vq_lengthlist__44u2__p5_0[] = {
  141544. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  141545. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  141546. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  141547. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  141548. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  141549. 13,
  141550. };
  141551. static float _vq_quantthresh__44u2__p5_0[] = {
  141552. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141553. };
  141554. static long _vq_quantmap__44u2__p5_0[] = {
  141555. 7, 5, 3, 1, 0, 2, 4, 6,
  141556. 8,
  141557. };
  141558. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  141559. _vq_quantthresh__44u2__p5_0,
  141560. _vq_quantmap__44u2__p5_0,
  141561. 9,
  141562. 9
  141563. };
  141564. static static_codebook _44u2__p5_0 = {
  141565. 2, 81,
  141566. _vq_lengthlist__44u2__p5_0,
  141567. 1, -531628032, 1611661312, 4, 0,
  141568. _vq_quantlist__44u2__p5_0,
  141569. NULL,
  141570. &_vq_auxt__44u2__p5_0,
  141571. NULL,
  141572. 0
  141573. };
  141574. static long _vq_quantlist__44u2__p6_0[] = {
  141575. 6,
  141576. 5,
  141577. 7,
  141578. 4,
  141579. 8,
  141580. 3,
  141581. 9,
  141582. 2,
  141583. 10,
  141584. 1,
  141585. 11,
  141586. 0,
  141587. 12,
  141588. };
  141589. static long _vq_lengthlist__44u2__p6_0[] = {
  141590. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  141591. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  141592. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  141593. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  141594. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  141595. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  141596. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  141597. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  141598. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  141599. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  141600. 15,17,17,16,18,17,18, 0, 0,
  141601. };
  141602. static float _vq_quantthresh__44u2__p6_0[] = {
  141603. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141604. 12.5, 17.5, 22.5, 27.5,
  141605. };
  141606. static long _vq_quantmap__44u2__p6_0[] = {
  141607. 11, 9, 7, 5, 3, 1, 0, 2,
  141608. 4, 6, 8, 10, 12,
  141609. };
  141610. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  141611. _vq_quantthresh__44u2__p6_0,
  141612. _vq_quantmap__44u2__p6_0,
  141613. 13,
  141614. 13
  141615. };
  141616. static static_codebook _44u2__p6_0 = {
  141617. 2, 169,
  141618. _vq_lengthlist__44u2__p6_0,
  141619. 1, -526516224, 1616117760, 4, 0,
  141620. _vq_quantlist__44u2__p6_0,
  141621. NULL,
  141622. &_vq_auxt__44u2__p6_0,
  141623. NULL,
  141624. 0
  141625. };
  141626. static long _vq_quantlist__44u2__p6_1[] = {
  141627. 2,
  141628. 1,
  141629. 3,
  141630. 0,
  141631. 4,
  141632. };
  141633. static long _vq_lengthlist__44u2__p6_1[] = {
  141634. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  141635. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  141636. };
  141637. static float _vq_quantthresh__44u2__p6_1[] = {
  141638. -1.5, -0.5, 0.5, 1.5,
  141639. };
  141640. static long _vq_quantmap__44u2__p6_1[] = {
  141641. 3, 1, 0, 2, 4,
  141642. };
  141643. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  141644. _vq_quantthresh__44u2__p6_1,
  141645. _vq_quantmap__44u2__p6_1,
  141646. 5,
  141647. 5
  141648. };
  141649. static static_codebook _44u2__p6_1 = {
  141650. 2, 25,
  141651. _vq_lengthlist__44u2__p6_1,
  141652. 1, -533725184, 1611661312, 3, 0,
  141653. _vq_quantlist__44u2__p6_1,
  141654. NULL,
  141655. &_vq_auxt__44u2__p6_1,
  141656. NULL,
  141657. 0
  141658. };
  141659. static long _vq_quantlist__44u2__p7_0[] = {
  141660. 4,
  141661. 3,
  141662. 5,
  141663. 2,
  141664. 6,
  141665. 1,
  141666. 7,
  141667. 0,
  141668. 8,
  141669. };
  141670. static long _vq_lengthlist__44u2__p7_0[] = {
  141671. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  141672. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  141673. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141674. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141675. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141676. 11,
  141677. };
  141678. static float _vq_quantthresh__44u2__p7_0[] = {
  141679. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  141680. };
  141681. static long _vq_quantmap__44u2__p7_0[] = {
  141682. 7, 5, 3, 1, 0, 2, 4, 6,
  141683. 8,
  141684. };
  141685. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  141686. _vq_quantthresh__44u2__p7_0,
  141687. _vq_quantmap__44u2__p7_0,
  141688. 9,
  141689. 9
  141690. };
  141691. static static_codebook _44u2__p7_0 = {
  141692. 2, 81,
  141693. _vq_lengthlist__44u2__p7_0,
  141694. 1, -516612096, 1626677248, 4, 0,
  141695. _vq_quantlist__44u2__p7_0,
  141696. NULL,
  141697. &_vq_auxt__44u2__p7_0,
  141698. NULL,
  141699. 0
  141700. };
  141701. static long _vq_quantlist__44u2__p7_1[] = {
  141702. 6,
  141703. 5,
  141704. 7,
  141705. 4,
  141706. 8,
  141707. 3,
  141708. 9,
  141709. 2,
  141710. 10,
  141711. 1,
  141712. 11,
  141713. 0,
  141714. 12,
  141715. };
  141716. static long _vq_lengthlist__44u2__p7_1[] = {
  141717. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  141718. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  141719. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  141720. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  141721. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  141722. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  141723. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  141724. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  141725. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  141726. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  141727. 14,14,14,17,15,17,17,17,17,
  141728. };
  141729. static float _vq_quantthresh__44u2__p7_1[] = {
  141730. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  141731. 32.5, 45.5, 58.5, 71.5,
  141732. };
  141733. static long _vq_quantmap__44u2__p7_1[] = {
  141734. 11, 9, 7, 5, 3, 1, 0, 2,
  141735. 4, 6, 8, 10, 12,
  141736. };
  141737. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  141738. _vq_quantthresh__44u2__p7_1,
  141739. _vq_quantmap__44u2__p7_1,
  141740. 13,
  141741. 13
  141742. };
  141743. static static_codebook _44u2__p7_1 = {
  141744. 2, 169,
  141745. _vq_lengthlist__44u2__p7_1,
  141746. 1, -523010048, 1618608128, 4, 0,
  141747. _vq_quantlist__44u2__p7_1,
  141748. NULL,
  141749. &_vq_auxt__44u2__p7_1,
  141750. NULL,
  141751. 0
  141752. };
  141753. static long _vq_quantlist__44u2__p7_2[] = {
  141754. 6,
  141755. 5,
  141756. 7,
  141757. 4,
  141758. 8,
  141759. 3,
  141760. 9,
  141761. 2,
  141762. 10,
  141763. 1,
  141764. 11,
  141765. 0,
  141766. 12,
  141767. };
  141768. static long _vq_lengthlist__44u2__p7_2[] = {
  141769. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  141770. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  141771. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  141772. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  141773. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  141774. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  141775. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  141776. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141777. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  141778. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  141779. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141780. };
  141781. static float _vq_quantthresh__44u2__p7_2[] = {
  141782. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  141783. 2.5, 3.5, 4.5, 5.5,
  141784. };
  141785. static long _vq_quantmap__44u2__p7_2[] = {
  141786. 11, 9, 7, 5, 3, 1, 0, 2,
  141787. 4, 6, 8, 10, 12,
  141788. };
  141789. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  141790. _vq_quantthresh__44u2__p7_2,
  141791. _vq_quantmap__44u2__p7_2,
  141792. 13,
  141793. 13
  141794. };
  141795. static static_codebook _44u2__p7_2 = {
  141796. 2, 169,
  141797. _vq_lengthlist__44u2__p7_2,
  141798. 1, -531103744, 1611661312, 4, 0,
  141799. _vq_quantlist__44u2__p7_2,
  141800. NULL,
  141801. &_vq_auxt__44u2__p7_2,
  141802. NULL,
  141803. 0
  141804. };
  141805. static long _huff_lengthlist__44u2__short[] = {
  141806. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  141807. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  141808. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  141809. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  141810. };
  141811. static static_codebook _huff_book__44u2__short = {
  141812. 2, 64,
  141813. _huff_lengthlist__44u2__short,
  141814. 0, 0, 0, 0, 0,
  141815. NULL,
  141816. NULL,
  141817. NULL,
  141818. NULL,
  141819. 0
  141820. };
  141821. static long _huff_lengthlist__44u3__long[] = {
  141822. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  141823. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  141824. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  141825. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  141826. };
  141827. static static_codebook _huff_book__44u3__long = {
  141828. 2, 64,
  141829. _huff_lengthlist__44u3__long,
  141830. 0, 0, 0, 0, 0,
  141831. NULL,
  141832. NULL,
  141833. NULL,
  141834. NULL,
  141835. 0
  141836. };
  141837. static long _vq_quantlist__44u3__p1_0[] = {
  141838. 1,
  141839. 0,
  141840. 2,
  141841. };
  141842. static long _vq_lengthlist__44u3__p1_0[] = {
  141843. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  141844. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141845. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  141846. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  141847. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  141848. 13,
  141849. };
  141850. static float _vq_quantthresh__44u3__p1_0[] = {
  141851. -0.5, 0.5,
  141852. };
  141853. static long _vq_quantmap__44u3__p1_0[] = {
  141854. 1, 0, 2,
  141855. };
  141856. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  141857. _vq_quantthresh__44u3__p1_0,
  141858. _vq_quantmap__44u3__p1_0,
  141859. 3,
  141860. 3
  141861. };
  141862. static static_codebook _44u3__p1_0 = {
  141863. 4, 81,
  141864. _vq_lengthlist__44u3__p1_0,
  141865. 1, -535822336, 1611661312, 2, 0,
  141866. _vq_quantlist__44u3__p1_0,
  141867. NULL,
  141868. &_vq_auxt__44u3__p1_0,
  141869. NULL,
  141870. 0
  141871. };
  141872. static long _vq_quantlist__44u3__p2_0[] = {
  141873. 1,
  141874. 0,
  141875. 2,
  141876. };
  141877. static long _vq_lengthlist__44u3__p2_0[] = {
  141878. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  141879. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  141880. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  141881. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  141882. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  141883. 9,
  141884. };
  141885. static float _vq_quantthresh__44u3__p2_0[] = {
  141886. -0.5, 0.5,
  141887. };
  141888. static long _vq_quantmap__44u3__p2_0[] = {
  141889. 1, 0, 2,
  141890. };
  141891. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  141892. _vq_quantthresh__44u3__p2_0,
  141893. _vq_quantmap__44u3__p2_0,
  141894. 3,
  141895. 3
  141896. };
  141897. static static_codebook _44u3__p2_0 = {
  141898. 4, 81,
  141899. _vq_lengthlist__44u3__p2_0,
  141900. 1, -535822336, 1611661312, 2, 0,
  141901. _vq_quantlist__44u3__p2_0,
  141902. NULL,
  141903. &_vq_auxt__44u3__p2_0,
  141904. NULL,
  141905. 0
  141906. };
  141907. static long _vq_quantlist__44u3__p3_0[] = {
  141908. 2,
  141909. 1,
  141910. 3,
  141911. 0,
  141912. 4,
  141913. };
  141914. static long _vq_lengthlist__44u3__p3_0[] = {
  141915. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  141916. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  141917. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  141918. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  141919. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  141920. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  141921. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  141922. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  141923. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  141924. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  141925. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  141926. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  141927. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  141928. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  141929. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  141930. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  141931. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  141932. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  141933. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  141934. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  141935. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  141936. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  141937. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  141938. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  141939. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  141940. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  141941. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  141942. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  141943. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  141944. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  141945. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  141946. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  141947. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  141948. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  141949. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  141950. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  141951. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  141952. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  141953. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  141954. 0,
  141955. };
  141956. static float _vq_quantthresh__44u3__p3_0[] = {
  141957. -1.5, -0.5, 0.5, 1.5,
  141958. };
  141959. static long _vq_quantmap__44u3__p3_0[] = {
  141960. 3, 1, 0, 2, 4,
  141961. };
  141962. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  141963. _vq_quantthresh__44u3__p3_0,
  141964. _vq_quantmap__44u3__p3_0,
  141965. 5,
  141966. 5
  141967. };
  141968. static static_codebook _44u3__p3_0 = {
  141969. 4, 625,
  141970. _vq_lengthlist__44u3__p3_0,
  141971. 1, -533725184, 1611661312, 3, 0,
  141972. _vq_quantlist__44u3__p3_0,
  141973. NULL,
  141974. &_vq_auxt__44u3__p3_0,
  141975. NULL,
  141976. 0
  141977. };
  141978. static long _vq_quantlist__44u3__p4_0[] = {
  141979. 2,
  141980. 1,
  141981. 3,
  141982. 0,
  141983. 4,
  141984. };
  141985. static long _vq_lengthlist__44u3__p4_0[] = {
  141986. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  141987. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  141988. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  141989. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  141990. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  141991. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  141992. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  141993. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  141994. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  141995. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  141996. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  141997. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  141998. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  141999. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  142000. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  142001. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  142002. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  142003. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  142004. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  142005. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  142006. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  142007. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  142008. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  142009. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  142010. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  142011. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  142012. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  142013. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  142014. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  142015. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  142016. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  142017. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  142018. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  142019. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  142020. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  142021. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  142022. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  142023. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  142024. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  142025. 13,
  142026. };
  142027. static float _vq_quantthresh__44u3__p4_0[] = {
  142028. -1.5, -0.5, 0.5, 1.5,
  142029. };
  142030. static long _vq_quantmap__44u3__p4_0[] = {
  142031. 3, 1, 0, 2, 4,
  142032. };
  142033. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  142034. _vq_quantthresh__44u3__p4_0,
  142035. _vq_quantmap__44u3__p4_0,
  142036. 5,
  142037. 5
  142038. };
  142039. static static_codebook _44u3__p4_0 = {
  142040. 4, 625,
  142041. _vq_lengthlist__44u3__p4_0,
  142042. 1, -533725184, 1611661312, 3, 0,
  142043. _vq_quantlist__44u3__p4_0,
  142044. NULL,
  142045. &_vq_auxt__44u3__p4_0,
  142046. NULL,
  142047. 0
  142048. };
  142049. static long _vq_quantlist__44u3__p5_0[] = {
  142050. 4,
  142051. 3,
  142052. 5,
  142053. 2,
  142054. 6,
  142055. 1,
  142056. 7,
  142057. 0,
  142058. 8,
  142059. };
  142060. static long _vq_lengthlist__44u3__p5_0[] = {
  142061. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  142062. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  142063. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  142064. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142065. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  142066. 12,
  142067. };
  142068. static float _vq_quantthresh__44u3__p5_0[] = {
  142069. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142070. };
  142071. static long _vq_quantmap__44u3__p5_0[] = {
  142072. 7, 5, 3, 1, 0, 2, 4, 6,
  142073. 8,
  142074. };
  142075. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  142076. _vq_quantthresh__44u3__p5_0,
  142077. _vq_quantmap__44u3__p5_0,
  142078. 9,
  142079. 9
  142080. };
  142081. static static_codebook _44u3__p5_0 = {
  142082. 2, 81,
  142083. _vq_lengthlist__44u3__p5_0,
  142084. 1, -531628032, 1611661312, 4, 0,
  142085. _vq_quantlist__44u3__p5_0,
  142086. NULL,
  142087. &_vq_auxt__44u3__p5_0,
  142088. NULL,
  142089. 0
  142090. };
  142091. static long _vq_quantlist__44u3__p6_0[] = {
  142092. 6,
  142093. 5,
  142094. 7,
  142095. 4,
  142096. 8,
  142097. 3,
  142098. 9,
  142099. 2,
  142100. 10,
  142101. 1,
  142102. 11,
  142103. 0,
  142104. 12,
  142105. };
  142106. static long _vq_lengthlist__44u3__p6_0[] = {
  142107. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  142108. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  142109. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142110. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  142111. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  142112. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  142113. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  142114. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  142115. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  142116. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  142117. 15,16,16,16,17,18,16,20,18,
  142118. };
  142119. static float _vq_quantthresh__44u3__p6_0[] = {
  142120. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142121. 12.5, 17.5, 22.5, 27.5,
  142122. };
  142123. static long _vq_quantmap__44u3__p6_0[] = {
  142124. 11, 9, 7, 5, 3, 1, 0, 2,
  142125. 4, 6, 8, 10, 12,
  142126. };
  142127. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  142128. _vq_quantthresh__44u3__p6_0,
  142129. _vq_quantmap__44u3__p6_0,
  142130. 13,
  142131. 13
  142132. };
  142133. static static_codebook _44u3__p6_0 = {
  142134. 2, 169,
  142135. _vq_lengthlist__44u3__p6_0,
  142136. 1, -526516224, 1616117760, 4, 0,
  142137. _vq_quantlist__44u3__p6_0,
  142138. NULL,
  142139. &_vq_auxt__44u3__p6_0,
  142140. NULL,
  142141. 0
  142142. };
  142143. static long _vq_quantlist__44u3__p6_1[] = {
  142144. 2,
  142145. 1,
  142146. 3,
  142147. 0,
  142148. 4,
  142149. };
  142150. static long _vq_lengthlist__44u3__p6_1[] = {
  142151. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  142152. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  142153. };
  142154. static float _vq_quantthresh__44u3__p6_1[] = {
  142155. -1.5, -0.5, 0.5, 1.5,
  142156. };
  142157. static long _vq_quantmap__44u3__p6_1[] = {
  142158. 3, 1, 0, 2, 4,
  142159. };
  142160. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  142161. _vq_quantthresh__44u3__p6_1,
  142162. _vq_quantmap__44u3__p6_1,
  142163. 5,
  142164. 5
  142165. };
  142166. static static_codebook _44u3__p6_1 = {
  142167. 2, 25,
  142168. _vq_lengthlist__44u3__p6_1,
  142169. 1, -533725184, 1611661312, 3, 0,
  142170. _vq_quantlist__44u3__p6_1,
  142171. NULL,
  142172. &_vq_auxt__44u3__p6_1,
  142173. NULL,
  142174. 0
  142175. };
  142176. static long _vq_quantlist__44u3__p7_0[] = {
  142177. 4,
  142178. 3,
  142179. 5,
  142180. 2,
  142181. 6,
  142182. 1,
  142183. 7,
  142184. 0,
  142185. 8,
  142186. };
  142187. static long _vq_lengthlist__44u3__p7_0[] = {
  142188. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  142189. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  142190. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142191. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142192. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142193. 9,
  142194. };
  142195. static float _vq_quantthresh__44u3__p7_0[] = {
  142196. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  142197. };
  142198. static long _vq_quantmap__44u3__p7_0[] = {
  142199. 7, 5, 3, 1, 0, 2, 4, 6,
  142200. 8,
  142201. };
  142202. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  142203. _vq_quantthresh__44u3__p7_0,
  142204. _vq_quantmap__44u3__p7_0,
  142205. 9,
  142206. 9
  142207. };
  142208. static static_codebook _44u3__p7_0 = {
  142209. 2, 81,
  142210. _vq_lengthlist__44u3__p7_0,
  142211. 1, -515907584, 1627381760, 4, 0,
  142212. _vq_quantlist__44u3__p7_0,
  142213. NULL,
  142214. &_vq_auxt__44u3__p7_0,
  142215. NULL,
  142216. 0
  142217. };
  142218. static long _vq_quantlist__44u3__p7_1[] = {
  142219. 7,
  142220. 6,
  142221. 8,
  142222. 5,
  142223. 9,
  142224. 4,
  142225. 10,
  142226. 3,
  142227. 11,
  142228. 2,
  142229. 12,
  142230. 1,
  142231. 13,
  142232. 0,
  142233. 14,
  142234. };
  142235. static long _vq_lengthlist__44u3__p7_1[] = {
  142236. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  142237. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  142238. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  142239. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  142240. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  142241. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  142242. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  142243. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  142244. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  142245. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  142246. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  142247. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  142248. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  142249. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  142250. 17,
  142251. };
  142252. static float _vq_quantthresh__44u3__p7_1[] = {
  142253. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  142254. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  142255. };
  142256. static long _vq_quantmap__44u3__p7_1[] = {
  142257. 13, 11, 9, 7, 5, 3, 1, 0,
  142258. 2, 4, 6, 8, 10, 12, 14,
  142259. };
  142260. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  142261. _vq_quantthresh__44u3__p7_1,
  142262. _vq_quantmap__44u3__p7_1,
  142263. 15,
  142264. 15
  142265. };
  142266. static static_codebook _44u3__p7_1 = {
  142267. 2, 225,
  142268. _vq_lengthlist__44u3__p7_1,
  142269. 1, -522338304, 1620115456, 4, 0,
  142270. _vq_quantlist__44u3__p7_1,
  142271. NULL,
  142272. &_vq_auxt__44u3__p7_1,
  142273. NULL,
  142274. 0
  142275. };
  142276. static long _vq_quantlist__44u3__p7_2[] = {
  142277. 8,
  142278. 7,
  142279. 9,
  142280. 6,
  142281. 10,
  142282. 5,
  142283. 11,
  142284. 4,
  142285. 12,
  142286. 3,
  142287. 13,
  142288. 2,
  142289. 14,
  142290. 1,
  142291. 15,
  142292. 0,
  142293. 16,
  142294. };
  142295. static long _vq_lengthlist__44u3__p7_2[] = {
  142296. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142297. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142298. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  142299. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142300. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  142301. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142302. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  142303. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142304. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  142305. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  142306. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  142307. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  142308. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  142309. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  142310. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  142311. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  142312. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142313. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  142314. 11,
  142315. };
  142316. static float _vq_quantthresh__44u3__p7_2[] = {
  142317. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142318. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142319. };
  142320. static long _vq_quantmap__44u3__p7_2[] = {
  142321. 15, 13, 11, 9, 7, 5, 3, 1,
  142322. 0, 2, 4, 6, 8, 10, 12, 14,
  142323. 16,
  142324. };
  142325. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  142326. _vq_quantthresh__44u3__p7_2,
  142327. _vq_quantmap__44u3__p7_2,
  142328. 17,
  142329. 17
  142330. };
  142331. static static_codebook _44u3__p7_2 = {
  142332. 2, 289,
  142333. _vq_lengthlist__44u3__p7_2,
  142334. 1, -529530880, 1611661312, 5, 0,
  142335. _vq_quantlist__44u3__p7_2,
  142336. NULL,
  142337. &_vq_auxt__44u3__p7_2,
  142338. NULL,
  142339. 0
  142340. };
  142341. static long _huff_lengthlist__44u3__short[] = {
  142342. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  142343. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  142344. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  142345. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  142346. };
  142347. static static_codebook _huff_book__44u3__short = {
  142348. 2, 64,
  142349. _huff_lengthlist__44u3__short,
  142350. 0, 0, 0, 0, 0,
  142351. NULL,
  142352. NULL,
  142353. NULL,
  142354. NULL,
  142355. 0
  142356. };
  142357. static long _huff_lengthlist__44u4__long[] = {
  142358. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  142359. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  142360. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  142361. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  142362. };
  142363. static static_codebook _huff_book__44u4__long = {
  142364. 2, 64,
  142365. _huff_lengthlist__44u4__long,
  142366. 0, 0, 0, 0, 0,
  142367. NULL,
  142368. NULL,
  142369. NULL,
  142370. NULL,
  142371. 0
  142372. };
  142373. static long _vq_quantlist__44u4__p1_0[] = {
  142374. 1,
  142375. 0,
  142376. 2,
  142377. };
  142378. static long _vq_lengthlist__44u4__p1_0[] = {
  142379. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  142380. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  142381. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  142382. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  142383. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  142384. 13,
  142385. };
  142386. static float _vq_quantthresh__44u4__p1_0[] = {
  142387. -0.5, 0.5,
  142388. };
  142389. static long _vq_quantmap__44u4__p1_0[] = {
  142390. 1, 0, 2,
  142391. };
  142392. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  142393. _vq_quantthresh__44u4__p1_0,
  142394. _vq_quantmap__44u4__p1_0,
  142395. 3,
  142396. 3
  142397. };
  142398. static static_codebook _44u4__p1_0 = {
  142399. 4, 81,
  142400. _vq_lengthlist__44u4__p1_0,
  142401. 1, -535822336, 1611661312, 2, 0,
  142402. _vq_quantlist__44u4__p1_0,
  142403. NULL,
  142404. &_vq_auxt__44u4__p1_0,
  142405. NULL,
  142406. 0
  142407. };
  142408. static long _vq_quantlist__44u4__p2_0[] = {
  142409. 1,
  142410. 0,
  142411. 2,
  142412. };
  142413. static long _vq_lengthlist__44u4__p2_0[] = {
  142414. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  142415. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  142416. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  142417. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  142418. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  142419. 9,
  142420. };
  142421. static float _vq_quantthresh__44u4__p2_0[] = {
  142422. -0.5, 0.5,
  142423. };
  142424. static long _vq_quantmap__44u4__p2_0[] = {
  142425. 1, 0, 2,
  142426. };
  142427. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  142428. _vq_quantthresh__44u4__p2_0,
  142429. _vq_quantmap__44u4__p2_0,
  142430. 3,
  142431. 3
  142432. };
  142433. static static_codebook _44u4__p2_0 = {
  142434. 4, 81,
  142435. _vq_lengthlist__44u4__p2_0,
  142436. 1, -535822336, 1611661312, 2, 0,
  142437. _vq_quantlist__44u4__p2_0,
  142438. NULL,
  142439. &_vq_auxt__44u4__p2_0,
  142440. NULL,
  142441. 0
  142442. };
  142443. static long _vq_quantlist__44u4__p3_0[] = {
  142444. 2,
  142445. 1,
  142446. 3,
  142447. 0,
  142448. 4,
  142449. };
  142450. static long _vq_lengthlist__44u4__p3_0[] = {
  142451. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  142452. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  142453. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  142454. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  142455. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  142456. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  142457. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  142458. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  142459. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  142460. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  142461. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  142462. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  142463. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  142464. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  142465. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  142466. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  142467. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  142468. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  142469. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  142470. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  142471. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  142472. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  142473. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  142474. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  142475. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  142476. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  142477. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  142478. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  142479. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  142480. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  142481. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  142482. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  142483. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  142484. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  142485. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  142486. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  142487. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  142488. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  142489. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  142490. 0,
  142491. };
  142492. static float _vq_quantthresh__44u4__p3_0[] = {
  142493. -1.5, -0.5, 0.5, 1.5,
  142494. };
  142495. static long _vq_quantmap__44u4__p3_0[] = {
  142496. 3, 1, 0, 2, 4,
  142497. };
  142498. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  142499. _vq_quantthresh__44u4__p3_0,
  142500. _vq_quantmap__44u4__p3_0,
  142501. 5,
  142502. 5
  142503. };
  142504. static static_codebook _44u4__p3_0 = {
  142505. 4, 625,
  142506. _vq_lengthlist__44u4__p3_0,
  142507. 1, -533725184, 1611661312, 3, 0,
  142508. _vq_quantlist__44u4__p3_0,
  142509. NULL,
  142510. &_vq_auxt__44u4__p3_0,
  142511. NULL,
  142512. 0
  142513. };
  142514. static long _vq_quantlist__44u4__p4_0[] = {
  142515. 2,
  142516. 1,
  142517. 3,
  142518. 0,
  142519. 4,
  142520. };
  142521. static long _vq_lengthlist__44u4__p4_0[] = {
  142522. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  142523. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  142524. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  142525. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  142526. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  142527. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  142528. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  142529. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  142530. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  142531. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  142532. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  142533. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142534. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  142535. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  142536. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  142537. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  142538. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  142539. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  142540. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  142541. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  142542. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  142543. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  142544. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  142545. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  142546. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  142547. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  142548. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  142549. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  142550. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  142551. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  142552. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  142553. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  142554. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  142555. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  142556. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  142557. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  142558. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  142559. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  142560. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  142561. 13,
  142562. };
  142563. static float _vq_quantthresh__44u4__p4_0[] = {
  142564. -1.5, -0.5, 0.5, 1.5,
  142565. };
  142566. static long _vq_quantmap__44u4__p4_0[] = {
  142567. 3, 1, 0, 2, 4,
  142568. };
  142569. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  142570. _vq_quantthresh__44u4__p4_0,
  142571. _vq_quantmap__44u4__p4_0,
  142572. 5,
  142573. 5
  142574. };
  142575. static static_codebook _44u4__p4_0 = {
  142576. 4, 625,
  142577. _vq_lengthlist__44u4__p4_0,
  142578. 1, -533725184, 1611661312, 3, 0,
  142579. _vq_quantlist__44u4__p4_0,
  142580. NULL,
  142581. &_vq_auxt__44u4__p4_0,
  142582. NULL,
  142583. 0
  142584. };
  142585. static long _vq_quantlist__44u4__p5_0[] = {
  142586. 4,
  142587. 3,
  142588. 5,
  142589. 2,
  142590. 6,
  142591. 1,
  142592. 7,
  142593. 0,
  142594. 8,
  142595. };
  142596. static long _vq_lengthlist__44u4__p5_0[] = {
  142597. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  142598. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  142599. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  142600. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142601. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  142602. 12,
  142603. };
  142604. static float _vq_quantthresh__44u4__p5_0[] = {
  142605. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142606. };
  142607. static long _vq_quantmap__44u4__p5_0[] = {
  142608. 7, 5, 3, 1, 0, 2, 4, 6,
  142609. 8,
  142610. };
  142611. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  142612. _vq_quantthresh__44u4__p5_0,
  142613. _vq_quantmap__44u4__p5_0,
  142614. 9,
  142615. 9
  142616. };
  142617. static static_codebook _44u4__p5_0 = {
  142618. 2, 81,
  142619. _vq_lengthlist__44u4__p5_0,
  142620. 1, -531628032, 1611661312, 4, 0,
  142621. _vq_quantlist__44u4__p5_0,
  142622. NULL,
  142623. &_vq_auxt__44u4__p5_0,
  142624. NULL,
  142625. 0
  142626. };
  142627. static long _vq_quantlist__44u4__p6_0[] = {
  142628. 6,
  142629. 5,
  142630. 7,
  142631. 4,
  142632. 8,
  142633. 3,
  142634. 9,
  142635. 2,
  142636. 10,
  142637. 1,
  142638. 11,
  142639. 0,
  142640. 12,
  142641. };
  142642. static long _vq_lengthlist__44u4__p6_0[] = {
  142643. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  142644. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  142645. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142646. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  142647. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  142648. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  142649. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  142650. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  142651. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  142652. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  142653. 16,16,16,17,17,18,17,20,21,
  142654. };
  142655. static float _vq_quantthresh__44u4__p6_0[] = {
  142656. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142657. 12.5, 17.5, 22.5, 27.5,
  142658. };
  142659. static long _vq_quantmap__44u4__p6_0[] = {
  142660. 11, 9, 7, 5, 3, 1, 0, 2,
  142661. 4, 6, 8, 10, 12,
  142662. };
  142663. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  142664. _vq_quantthresh__44u4__p6_0,
  142665. _vq_quantmap__44u4__p6_0,
  142666. 13,
  142667. 13
  142668. };
  142669. static static_codebook _44u4__p6_0 = {
  142670. 2, 169,
  142671. _vq_lengthlist__44u4__p6_0,
  142672. 1, -526516224, 1616117760, 4, 0,
  142673. _vq_quantlist__44u4__p6_0,
  142674. NULL,
  142675. &_vq_auxt__44u4__p6_0,
  142676. NULL,
  142677. 0
  142678. };
  142679. static long _vq_quantlist__44u4__p6_1[] = {
  142680. 2,
  142681. 1,
  142682. 3,
  142683. 0,
  142684. 4,
  142685. };
  142686. static long _vq_lengthlist__44u4__p6_1[] = {
  142687. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  142688. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  142689. };
  142690. static float _vq_quantthresh__44u4__p6_1[] = {
  142691. -1.5, -0.5, 0.5, 1.5,
  142692. };
  142693. static long _vq_quantmap__44u4__p6_1[] = {
  142694. 3, 1, 0, 2, 4,
  142695. };
  142696. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  142697. _vq_quantthresh__44u4__p6_1,
  142698. _vq_quantmap__44u4__p6_1,
  142699. 5,
  142700. 5
  142701. };
  142702. static static_codebook _44u4__p6_1 = {
  142703. 2, 25,
  142704. _vq_lengthlist__44u4__p6_1,
  142705. 1, -533725184, 1611661312, 3, 0,
  142706. _vq_quantlist__44u4__p6_1,
  142707. NULL,
  142708. &_vq_auxt__44u4__p6_1,
  142709. NULL,
  142710. 0
  142711. };
  142712. static long _vq_quantlist__44u4__p7_0[] = {
  142713. 6,
  142714. 5,
  142715. 7,
  142716. 4,
  142717. 8,
  142718. 3,
  142719. 9,
  142720. 2,
  142721. 10,
  142722. 1,
  142723. 11,
  142724. 0,
  142725. 12,
  142726. };
  142727. static long _vq_lengthlist__44u4__p7_0[] = {
  142728. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  142729. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  142730. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142731. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142732. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142733. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142734. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142735. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142736. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142737. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142738. 11,11,11,11,11,11,11,11,11,
  142739. };
  142740. static float _vq_quantthresh__44u4__p7_0[] = {
  142741. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  142742. 637.5, 892.5, 1147.5, 1402.5,
  142743. };
  142744. static long _vq_quantmap__44u4__p7_0[] = {
  142745. 11, 9, 7, 5, 3, 1, 0, 2,
  142746. 4, 6, 8, 10, 12,
  142747. };
  142748. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  142749. _vq_quantthresh__44u4__p7_0,
  142750. _vq_quantmap__44u4__p7_0,
  142751. 13,
  142752. 13
  142753. };
  142754. static static_codebook _44u4__p7_0 = {
  142755. 2, 169,
  142756. _vq_lengthlist__44u4__p7_0,
  142757. 1, -514332672, 1627381760, 4, 0,
  142758. _vq_quantlist__44u4__p7_0,
  142759. NULL,
  142760. &_vq_auxt__44u4__p7_0,
  142761. NULL,
  142762. 0
  142763. };
  142764. static long _vq_quantlist__44u4__p7_1[] = {
  142765. 7,
  142766. 6,
  142767. 8,
  142768. 5,
  142769. 9,
  142770. 4,
  142771. 10,
  142772. 3,
  142773. 11,
  142774. 2,
  142775. 12,
  142776. 1,
  142777. 13,
  142778. 0,
  142779. 14,
  142780. };
  142781. static long _vq_lengthlist__44u4__p7_1[] = {
  142782. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  142783. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  142784. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  142785. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  142786. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  142787. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  142788. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  142789. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  142790. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  142791. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  142792. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  142793. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  142794. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  142795. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  142796. 16,
  142797. };
  142798. static float _vq_quantthresh__44u4__p7_1[] = {
  142799. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  142800. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  142801. };
  142802. static long _vq_quantmap__44u4__p7_1[] = {
  142803. 13, 11, 9, 7, 5, 3, 1, 0,
  142804. 2, 4, 6, 8, 10, 12, 14,
  142805. };
  142806. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  142807. _vq_quantthresh__44u4__p7_1,
  142808. _vq_quantmap__44u4__p7_1,
  142809. 15,
  142810. 15
  142811. };
  142812. static static_codebook _44u4__p7_1 = {
  142813. 2, 225,
  142814. _vq_lengthlist__44u4__p7_1,
  142815. 1, -522338304, 1620115456, 4, 0,
  142816. _vq_quantlist__44u4__p7_1,
  142817. NULL,
  142818. &_vq_auxt__44u4__p7_1,
  142819. NULL,
  142820. 0
  142821. };
  142822. static long _vq_quantlist__44u4__p7_2[] = {
  142823. 8,
  142824. 7,
  142825. 9,
  142826. 6,
  142827. 10,
  142828. 5,
  142829. 11,
  142830. 4,
  142831. 12,
  142832. 3,
  142833. 13,
  142834. 2,
  142835. 14,
  142836. 1,
  142837. 15,
  142838. 0,
  142839. 16,
  142840. };
  142841. static long _vq_lengthlist__44u4__p7_2[] = {
  142842. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142843. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142844. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142845. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142846. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  142847. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142848. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142849. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  142850. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  142851. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  142852. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  142853. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  142854. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  142855. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  142856. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  142857. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  142858. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142859. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  142860. 10,
  142861. };
  142862. static float _vq_quantthresh__44u4__p7_2[] = {
  142863. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142864. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142865. };
  142866. static long _vq_quantmap__44u4__p7_2[] = {
  142867. 15, 13, 11, 9, 7, 5, 3, 1,
  142868. 0, 2, 4, 6, 8, 10, 12, 14,
  142869. 16,
  142870. };
  142871. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  142872. _vq_quantthresh__44u4__p7_2,
  142873. _vq_quantmap__44u4__p7_2,
  142874. 17,
  142875. 17
  142876. };
  142877. static static_codebook _44u4__p7_2 = {
  142878. 2, 289,
  142879. _vq_lengthlist__44u4__p7_2,
  142880. 1, -529530880, 1611661312, 5, 0,
  142881. _vq_quantlist__44u4__p7_2,
  142882. NULL,
  142883. &_vq_auxt__44u4__p7_2,
  142884. NULL,
  142885. 0
  142886. };
  142887. static long _huff_lengthlist__44u4__short[] = {
  142888. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  142889. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  142890. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  142891. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  142892. };
  142893. static static_codebook _huff_book__44u4__short = {
  142894. 2, 64,
  142895. _huff_lengthlist__44u4__short,
  142896. 0, 0, 0, 0, 0,
  142897. NULL,
  142898. NULL,
  142899. NULL,
  142900. NULL,
  142901. 0
  142902. };
  142903. static long _huff_lengthlist__44u5__long[] = {
  142904. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  142905. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  142906. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  142907. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  142908. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  142909. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  142910. 14, 8, 7, 8,
  142911. };
  142912. static static_codebook _huff_book__44u5__long = {
  142913. 2, 100,
  142914. _huff_lengthlist__44u5__long,
  142915. 0, 0, 0, 0, 0,
  142916. NULL,
  142917. NULL,
  142918. NULL,
  142919. NULL,
  142920. 0
  142921. };
  142922. static long _vq_quantlist__44u5__p1_0[] = {
  142923. 1,
  142924. 0,
  142925. 2,
  142926. };
  142927. static long _vq_lengthlist__44u5__p1_0[] = {
  142928. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  142929. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  142930. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  142931. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  142932. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  142933. 12,
  142934. };
  142935. static float _vq_quantthresh__44u5__p1_0[] = {
  142936. -0.5, 0.5,
  142937. };
  142938. static long _vq_quantmap__44u5__p1_0[] = {
  142939. 1, 0, 2,
  142940. };
  142941. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  142942. _vq_quantthresh__44u5__p1_0,
  142943. _vq_quantmap__44u5__p1_0,
  142944. 3,
  142945. 3
  142946. };
  142947. static static_codebook _44u5__p1_0 = {
  142948. 4, 81,
  142949. _vq_lengthlist__44u5__p1_0,
  142950. 1, -535822336, 1611661312, 2, 0,
  142951. _vq_quantlist__44u5__p1_0,
  142952. NULL,
  142953. &_vq_auxt__44u5__p1_0,
  142954. NULL,
  142955. 0
  142956. };
  142957. static long _vq_quantlist__44u5__p2_0[] = {
  142958. 1,
  142959. 0,
  142960. 2,
  142961. };
  142962. static long _vq_lengthlist__44u5__p2_0[] = {
  142963. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  142964. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  142965. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  142966. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  142967. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  142968. 9,
  142969. };
  142970. static float _vq_quantthresh__44u5__p2_0[] = {
  142971. -0.5, 0.5,
  142972. };
  142973. static long _vq_quantmap__44u5__p2_0[] = {
  142974. 1, 0, 2,
  142975. };
  142976. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  142977. _vq_quantthresh__44u5__p2_0,
  142978. _vq_quantmap__44u5__p2_0,
  142979. 3,
  142980. 3
  142981. };
  142982. static static_codebook _44u5__p2_0 = {
  142983. 4, 81,
  142984. _vq_lengthlist__44u5__p2_0,
  142985. 1, -535822336, 1611661312, 2, 0,
  142986. _vq_quantlist__44u5__p2_0,
  142987. NULL,
  142988. &_vq_auxt__44u5__p2_0,
  142989. NULL,
  142990. 0
  142991. };
  142992. static long _vq_quantlist__44u5__p3_0[] = {
  142993. 2,
  142994. 1,
  142995. 3,
  142996. 0,
  142997. 4,
  142998. };
  142999. static long _vq_lengthlist__44u5__p3_0[] = {
  143000. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  143001. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  143002. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  143003. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  143004. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  143005. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  143006. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  143007. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  143008. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  143009. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  143010. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  143011. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  143012. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  143013. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  143014. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  143015. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  143016. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  143017. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  143018. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  143019. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  143020. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  143021. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  143022. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  143023. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  143024. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  143025. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  143026. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  143027. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  143028. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  143029. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  143030. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  143031. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  143032. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  143033. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  143034. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  143035. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  143036. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  143037. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  143038. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  143039. 0,
  143040. };
  143041. static float _vq_quantthresh__44u5__p3_0[] = {
  143042. -1.5, -0.5, 0.5, 1.5,
  143043. };
  143044. static long _vq_quantmap__44u5__p3_0[] = {
  143045. 3, 1, 0, 2, 4,
  143046. };
  143047. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  143048. _vq_quantthresh__44u5__p3_0,
  143049. _vq_quantmap__44u5__p3_0,
  143050. 5,
  143051. 5
  143052. };
  143053. static static_codebook _44u5__p3_0 = {
  143054. 4, 625,
  143055. _vq_lengthlist__44u5__p3_0,
  143056. 1, -533725184, 1611661312, 3, 0,
  143057. _vq_quantlist__44u5__p3_0,
  143058. NULL,
  143059. &_vq_auxt__44u5__p3_0,
  143060. NULL,
  143061. 0
  143062. };
  143063. static long _vq_quantlist__44u5__p4_0[] = {
  143064. 2,
  143065. 1,
  143066. 3,
  143067. 0,
  143068. 4,
  143069. };
  143070. static long _vq_lengthlist__44u5__p4_0[] = {
  143071. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  143072. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  143073. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  143074. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  143075. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  143076. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  143077. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  143078. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  143079. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  143080. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  143081. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  143082. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143083. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  143084. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  143085. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  143086. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  143087. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  143088. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  143089. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  143090. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  143091. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  143092. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  143093. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  143094. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  143095. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  143096. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  143097. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  143098. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  143099. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  143100. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  143101. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  143102. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  143103. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  143104. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  143105. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  143106. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  143107. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  143108. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  143109. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  143110. 12,
  143111. };
  143112. static float _vq_quantthresh__44u5__p4_0[] = {
  143113. -1.5, -0.5, 0.5, 1.5,
  143114. };
  143115. static long _vq_quantmap__44u5__p4_0[] = {
  143116. 3, 1, 0, 2, 4,
  143117. };
  143118. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  143119. _vq_quantthresh__44u5__p4_0,
  143120. _vq_quantmap__44u5__p4_0,
  143121. 5,
  143122. 5
  143123. };
  143124. static static_codebook _44u5__p4_0 = {
  143125. 4, 625,
  143126. _vq_lengthlist__44u5__p4_0,
  143127. 1, -533725184, 1611661312, 3, 0,
  143128. _vq_quantlist__44u5__p4_0,
  143129. NULL,
  143130. &_vq_auxt__44u5__p4_0,
  143131. NULL,
  143132. 0
  143133. };
  143134. static long _vq_quantlist__44u5__p5_0[] = {
  143135. 4,
  143136. 3,
  143137. 5,
  143138. 2,
  143139. 6,
  143140. 1,
  143141. 7,
  143142. 0,
  143143. 8,
  143144. };
  143145. static long _vq_lengthlist__44u5__p5_0[] = {
  143146. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  143147. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  143148. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  143149. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  143150. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  143151. 14,
  143152. };
  143153. static float _vq_quantthresh__44u5__p5_0[] = {
  143154. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143155. };
  143156. static long _vq_quantmap__44u5__p5_0[] = {
  143157. 7, 5, 3, 1, 0, 2, 4, 6,
  143158. 8,
  143159. };
  143160. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  143161. _vq_quantthresh__44u5__p5_0,
  143162. _vq_quantmap__44u5__p5_0,
  143163. 9,
  143164. 9
  143165. };
  143166. static static_codebook _44u5__p5_0 = {
  143167. 2, 81,
  143168. _vq_lengthlist__44u5__p5_0,
  143169. 1, -531628032, 1611661312, 4, 0,
  143170. _vq_quantlist__44u5__p5_0,
  143171. NULL,
  143172. &_vq_auxt__44u5__p5_0,
  143173. NULL,
  143174. 0
  143175. };
  143176. static long _vq_quantlist__44u5__p6_0[] = {
  143177. 4,
  143178. 3,
  143179. 5,
  143180. 2,
  143181. 6,
  143182. 1,
  143183. 7,
  143184. 0,
  143185. 8,
  143186. };
  143187. static long _vq_lengthlist__44u5__p6_0[] = {
  143188. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  143189. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  143190. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  143191. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  143192. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  143193. 11,
  143194. };
  143195. static float _vq_quantthresh__44u5__p6_0[] = {
  143196. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143197. };
  143198. static long _vq_quantmap__44u5__p6_0[] = {
  143199. 7, 5, 3, 1, 0, 2, 4, 6,
  143200. 8,
  143201. };
  143202. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  143203. _vq_quantthresh__44u5__p6_0,
  143204. _vq_quantmap__44u5__p6_0,
  143205. 9,
  143206. 9
  143207. };
  143208. static static_codebook _44u5__p6_0 = {
  143209. 2, 81,
  143210. _vq_lengthlist__44u5__p6_0,
  143211. 1, -531628032, 1611661312, 4, 0,
  143212. _vq_quantlist__44u5__p6_0,
  143213. NULL,
  143214. &_vq_auxt__44u5__p6_0,
  143215. NULL,
  143216. 0
  143217. };
  143218. static long _vq_quantlist__44u5__p7_0[] = {
  143219. 1,
  143220. 0,
  143221. 2,
  143222. };
  143223. static long _vq_lengthlist__44u5__p7_0[] = {
  143224. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  143225. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  143226. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  143227. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  143228. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  143229. 12,
  143230. };
  143231. static float _vq_quantthresh__44u5__p7_0[] = {
  143232. -5.5, 5.5,
  143233. };
  143234. static long _vq_quantmap__44u5__p7_0[] = {
  143235. 1, 0, 2,
  143236. };
  143237. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  143238. _vq_quantthresh__44u5__p7_0,
  143239. _vq_quantmap__44u5__p7_0,
  143240. 3,
  143241. 3
  143242. };
  143243. static static_codebook _44u5__p7_0 = {
  143244. 4, 81,
  143245. _vq_lengthlist__44u5__p7_0,
  143246. 1, -529137664, 1618345984, 2, 0,
  143247. _vq_quantlist__44u5__p7_0,
  143248. NULL,
  143249. &_vq_auxt__44u5__p7_0,
  143250. NULL,
  143251. 0
  143252. };
  143253. static long _vq_quantlist__44u5__p7_1[] = {
  143254. 5,
  143255. 4,
  143256. 6,
  143257. 3,
  143258. 7,
  143259. 2,
  143260. 8,
  143261. 1,
  143262. 9,
  143263. 0,
  143264. 10,
  143265. };
  143266. static long _vq_lengthlist__44u5__p7_1[] = {
  143267. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  143268. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  143269. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143270. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  143271. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  143272. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  143273. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  143274. 9, 9, 9, 9, 9,10,10,10,10,
  143275. };
  143276. static float _vq_quantthresh__44u5__p7_1[] = {
  143277. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143278. 3.5, 4.5,
  143279. };
  143280. static long _vq_quantmap__44u5__p7_1[] = {
  143281. 9, 7, 5, 3, 1, 0, 2, 4,
  143282. 6, 8, 10,
  143283. };
  143284. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  143285. _vq_quantthresh__44u5__p7_1,
  143286. _vq_quantmap__44u5__p7_1,
  143287. 11,
  143288. 11
  143289. };
  143290. static static_codebook _44u5__p7_1 = {
  143291. 2, 121,
  143292. _vq_lengthlist__44u5__p7_1,
  143293. 1, -531365888, 1611661312, 4, 0,
  143294. _vq_quantlist__44u5__p7_1,
  143295. NULL,
  143296. &_vq_auxt__44u5__p7_1,
  143297. NULL,
  143298. 0
  143299. };
  143300. static long _vq_quantlist__44u5__p8_0[] = {
  143301. 5,
  143302. 4,
  143303. 6,
  143304. 3,
  143305. 7,
  143306. 2,
  143307. 8,
  143308. 1,
  143309. 9,
  143310. 0,
  143311. 10,
  143312. };
  143313. static long _vq_lengthlist__44u5__p8_0[] = {
  143314. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  143315. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  143316. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  143317. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  143318. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  143319. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  143320. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  143321. 12,13,13,14,14,14,14,15,15,
  143322. };
  143323. static float _vq_quantthresh__44u5__p8_0[] = {
  143324. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143325. 38.5, 49.5,
  143326. };
  143327. static long _vq_quantmap__44u5__p8_0[] = {
  143328. 9, 7, 5, 3, 1, 0, 2, 4,
  143329. 6, 8, 10,
  143330. };
  143331. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  143332. _vq_quantthresh__44u5__p8_0,
  143333. _vq_quantmap__44u5__p8_0,
  143334. 11,
  143335. 11
  143336. };
  143337. static static_codebook _44u5__p8_0 = {
  143338. 2, 121,
  143339. _vq_lengthlist__44u5__p8_0,
  143340. 1, -524582912, 1618345984, 4, 0,
  143341. _vq_quantlist__44u5__p8_0,
  143342. NULL,
  143343. &_vq_auxt__44u5__p8_0,
  143344. NULL,
  143345. 0
  143346. };
  143347. static long _vq_quantlist__44u5__p8_1[] = {
  143348. 5,
  143349. 4,
  143350. 6,
  143351. 3,
  143352. 7,
  143353. 2,
  143354. 8,
  143355. 1,
  143356. 9,
  143357. 0,
  143358. 10,
  143359. };
  143360. static long _vq_lengthlist__44u5__p8_1[] = {
  143361. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  143362. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  143363. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  143364. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  143365. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  143366. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  143367. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143368. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143369. };
  143370. static float _vq_quantthresh__44u5__p8_1[] = {
  143371. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143372. 3.5, 4.5,
  143373. };
  143374. static long _vq_quantmap__44u5__p8_1[] = {
  143375. 9, 7, 5, 3, 1, 0, 2, 4,
  143376. 6, 8, 10,
  143377. };
  143378. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  143379. _vq_quantthresh__44u5__p8_1,
  143380. _vq_quantmap__44u5__p8_1,
  143381. 11,
  143382. 11
  143383. };
  143384. static static_codebook _44u5__p8_1 = {
  143385. 2, 121,
  143386. _vq_lengthlist__44u5__p8_1,
  143387. 1, -531365888, 1611661312, 4, 0,
  143388. _vq_quantlist__44u5__p8_1,
  143389. NULL,
  143390. &_vq_auxt__44u5__p8_1,
  143391. NULL,
  143392. 0
  143393. };
  143394. static long _vq_quantlist__44u5__p9_0[] = {
  143395. 6,
  143396. 5,
  143397. 7,
  143398. 4,
  143399. 8,
  143400. 3,
  143401. 9,
  143402. 2,
  143403. 10,
  143404. 1,
  143405. 11,
  143406. 0,
  143407. 12,
  143408. };
  143409. static long _vq_lengthlist__44u5__p9_0[] = {
  143410. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  143411. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  143412. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  143413. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  143414. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  143415. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  143416. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  143417. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  143418. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  143419. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143420. 12,12,12,12,12,12,12,12,12,
  143421. };
  143422. static float _vq_quantthresh__44u5__p9_0[] = {
  143423. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  143424. 637.5, 892.5, 1147.5, 1402.5,
  143425. };
  143426. static long _vq_quantmap__44u5__p9_0[] = {
  143427. 11, 9, 7, 5, 3, 1, 0, 2,
  143428. 4, 6, 8, 10, 12,
  143429. };
  143430. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  143431. _vq_quantthresh__44u5__p9_0,
  143432. _vq_quantmap__44u5__p9_0,
  143433. 13,
  143434. 13
  143435. };
  143436. static static_codebook _44u5__p9_0 = {
  143437. 2, 169,
  143438. _vq_lengthlist__44u5__p9_0,
  143439. 1, -514332672, 1627381760, 4, 0,
  143440. _vq_quantlist__44u5__p9_0,
  143441. NULL,
  143442. &_vq_auxt__44u5__p9_0,
  143443. NULL,
  143444. 0
  143445. };
  143446. static long _vq_quantlist__44u5__p9_1[] = {
  143447. 7,
  143448. 6,
  143449. 8,
  143450. 5,
  143451. 9,
  143452. 4,
  143453. 10,
  143454. 3,
  143455. 11,
  143456. 2,
  143457. 12,
  143458. 1,
  143459. 13,
  143460. 0,
  143461. 14,
  143462. };
  143463. static long _vq_lengthlist__44u5__p9_1[] = {
  143464. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  143465. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  143466. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  143467. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  143468. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  143469. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  143470. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  143471. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  143472. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  143473. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  143474. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  143475. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  143476. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  143477. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  143478. 14,
  143479. };
  143480. static float _vq_quantthresh__44u5__p9_1[] = {
  143481. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143482. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143483. };
  143484. static long _vq_quantmap__44u5__p9_1[] = {
  143485. 13, 11, 9, 7, 5, 3, 1, 0,
  143486. 2, 4, 6, 8, 10, 12, 14,
  143487. };
  143488. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  143489. _vq_quantthresh__44u5__p9_1,
  143490. _vq_quantmap__44u5__p9_1,
  143491. 15,
  143492. 15
  143493. };
  143494. static static_codebook _44u5__p9_1 = {
  143495. 2, 225,
  143496. _vq_lengthlist__44u5__p9_1,
  143497. 1, -522338304, 1620115456, 4, 0,
  143498. _vq_quantlist__44u5__p9_1,
  143499. NULL,
  143500. &_vq_auxt__44u5__p9_1,
  143501. NULL,
  143502. 0
  143503. };
  143504. static long _vq_quantlist__44u5__p9_2[] = {
  143505. 8,
  143506. 7,
  143507. 9,
  143508. 6,
  143509. 10,
  143510. 5,
  143511. 11,
  143512. 4,
  143513. 12,
  143514. 3,
  143515. 13,
  143516. 2,
  143517. 14,
  143518. 1,
  143519. 15,
  143520. 0,
  143521. 16,
  143522. };
  143523. static long _vq_lengthlist__44u5__p9_2[] = {
  143524. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143525. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  143526. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  143527. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  143528. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  143529. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  143530. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  143531. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143532. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  143533. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  143534. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  143535. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  143536. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  143537. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  143538. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  143539. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  143540. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143541. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  143542. 10,
  143543. };
  143544. static float _vq_quantthresh__44u5__p9_2[] = {
  143545. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143546. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143547. };
  143548. static long _vq_quantmap__44u5__p9_2[] = {
  143549. 15, 13, 11, 9, 7, 5, 3, 1,
  143550. 0, 2, 4, 6, 8, 10, 12, 14,
  143551. 16,
  143552. };
  143553. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  143554. _vq_quantthresh__44u5__p9_2,
  143555. _vq_quantmap__44u5__p9_2,
  143556. 17,
  143557. 17
  143558. };
  143559. static static_codebook _44u5__p9_2 = {
  143560. 2, 289,
  143561. _vq_lengthlist__44u5__p9_2,
  143562. 1, -529530880, 1611661312, 5, 0,
  143563. _vq_quantlist__44u5__p9_2,
  143564. NULL,
  143565. &_vq_auxt__44u5__p9_2,
  143566. NULL,
  143567. 0
  143568. };
  143569. static long _huff_lengthlist__44u5__short[] = {
  143570. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  143571. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  143572. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  143573. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  143574. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  143575. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  143576. 6, 8,15,17,
  143577. };
  143578. static static_codebook _huff_book__44u5__short = {
  143579. 2, 100,
  143580. _huff_lengthlist__44u5__short,
  143581. 0, 0, 0, 0, 0,
  143582. NULL,
  143583. NULL,
  143584. NULL,
  143585. NULL,
  143586. 0
  143587. };
  143588. static long _huff_lengthlist__44u6__long[] = {
  143589. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  143590. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  143591. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  143592. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  143593. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  143594. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  143595. 13, 8, 7, 7,
  143596. };
  143597. static static_codebook _huff_book__44u6__long = {
  143598. 2, 100,
  143599. _huff_lengthlist__44u6__long,
  143600. 0, 0, 0, 0, 0,
  143601. NULL,
  143602. NULL,
  143603. NULL,
  143604. NULL,
  143605. 0
  143606. };
  143607. static long _vq_quantlist__44u6__p1_0[] = {
  143608. 1,
  143609. 0,
  143610. 2,
  143611. };
  143612. static long _vq_lengthlist__44u6__p1_0[] = {
  143613. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  143614. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  143615. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  143616. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  143617. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  143618. 12,
  143619. };
  143620. static float _vq_quantthresh__44u6__p1_0[] = {
  143621. -0.5, 0.5,
  143622. };
  143623. static long _vq_quantmap__44u6__p1_0[] = {
  143624. 1, 0, 2,
  143625. };
  143626. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  143627. _vq_quantthresh__44u6__p1_0,
  143628. _vq_quantmap__44u6__p1_0,
  143629. 3,
  143630. 3
  143631. };
  143632. static static_codebook _44u6__p1_0 = {
  143633. 4, 81,
  143634. _vq_lengthlist__44u6__p1_0,
  143635. 1, -535822336, 1611661312, 2, 0,
  143636. _vq_quantlist__44u6__p1_0,
  143637. NULL,
  143638. &_vq_auxt__44u6__p1_0,
  143639. NULL,
  143640. 0
  143641. };
  143642. static long _vq_quantlist__44u6__p2_0[] = {
  143643. 1,
  143644. 0,
  143645. 2,
  143646. };
  143647. static long _vq_lengthlist__44u6__p2_0[] = {
  143648. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  143649. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  143650. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  143651. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  143652. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  143653. 9,
  143654. };
  143655. static float _vq_quantthresh__44u6__p2_0[] = {
  143656. -0.5, 0.5,
  143657. };
  143658. static long _vq_quantmap__44u6__p2_0[] = {
  143659. 1, 0, 2,
  143660. };
  143661. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  143662. _vq_quantthresh__44u6__p2_0,
  143663. _vq_quantmap__44u6__p2_0,
  143664. 3,
  143665. 3
  143666. };
  143667. static static_codebook _44u6__p2_0 = {
  143668. 4, 81,
  143669. _vq_lengthlist__44u6__p2_0,
  143670. 1, -535822336, 1611661312, 2, 0,
  143671. _vq_quantlist__44u6__p2_0,
  143672. NULL,
  143673. &_vq_auxt__44u6__p2_0,
  143674. NULL,
  143675. 0
  143676. };
  143677. static long _vq_quantlist__44u6__p3_0[] = {
  143678. 2,
  143679. 1,
  143680. 3,
  143681. 0,
  143682. 4,
  143683. };
  143684. static long _vq_lengthlist__44u6__p3_0[] = {
  143685. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  143686. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  143687. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  143688. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  143689. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  143690. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  143691. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  143692. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  143693. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  143694. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  143695. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  143696. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  143697. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  143698. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  143699. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  143700. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  143701. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  143702. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  143703. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  143704. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  143705. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  143706. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  143707. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  143708. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  143709. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  143710. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  143711. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  143712. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  143713. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  143714. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  143715. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  143716. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  143717. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  143718. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  143719. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  143720. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  143721. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  143722. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  143723. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  143724. 19,
  143725. };
  143726. static float _vq_quantthresh__44u6__p3_0[] = {
  143727. -1.5, -0.5, 0.5, 1.5,
  143728. };
  143729. static long _vq_quantmap__44u6__p3_0[] = {
  143730. 3, 1, 0, 2, 4,
  143731. };
  143732. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  143733. _vq_quantthresh__44u6__p3_0,
  143734. _vq_quantmap__44u6__p3_0,
  143735. 5,
  143736. 5
  143737. };
  143738. static static_codebook _44u6__p3_0 = {
  143739. 4, 625,
  143740. _vq_lengthlist__44u6__p3_0,
  143741. 1, -533725184, 1611661312, 3, 0,
  143742. _vq_quantlist__44u6__p3_0,
  143743. NULL,
  143744. &_vq_auxt__44u6__p3_0,
  143745. NULL,
  143746. 0
  143747. };
  143748. static long _vq_quantlist__44u6__p4_0[] = {
  143749. 2,
  143750. 1,
  143751. 3,
  143752. 0,
  143753. 4,
  143754. };
  143755. static long _vq_lengthlist__44u6__p4_0[] = {
  143756. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  143757. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  143758. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  143759. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  143760. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  143761. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  143762. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  143763. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  143764. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  143765. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  143766. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  143767. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  143768. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  143769. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  143770. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  143771. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  143772. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  143773. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143774. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  143775. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  143776. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  143777. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  143778. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  143779. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  143780. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  143781. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  143782. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  143783. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  143784. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  143785. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  143786. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  143787. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  143788. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  143789. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  143790. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  143791. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  143792. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  143793. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  143794. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  143795. 13,
  143796. };
  143797. static float _vq_quantthresh__44u6__p4_0[] = {
  143798. -1.5, -0.5, 0.5, 1.5,
  143799. };
  143800. static long _vq_quantmap__44u6__p4_0[] = {
  143801. 3, 1, 0, 2, 4,
  143802. };
  143803. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  143804. _vq_quantthresh__44u6__p4_0,
  143805. _vq_quantmap__44u6__p4_0,
  143806. 5,
  143807. 5
  143808. };
  143809. static static_codebook _44u6__p4_0 = {
  143810. 4, 625,
  143811. _vq_lengthlist__44u6__p4_0,
  143812. 1, -533725184, 1611661312, 3, 0,
  143813. _vq_quantlist__44u6__p4_0,
  143814. NULL,
  143815. &_vq_auxt__44u6__p4_0,
  143816. NULL,
  143817. 0
  143818. };
  143819. static long _vq_quantlist__44u6__p5_0[] = {
  143820. 4,
  143821. 3,
  143822. 5,
  143823. 2,
  143824. 6,
  143825. 1,
  143826. 7,
  143827. 0,
  143828. 8,
  143829. };
  143830. static long _vq_lengthlist__44u6__p5_0[] = {
  143831. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  143832. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  143833. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  143834. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  143835. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  143836. 14,
  143837. };
  143838. static float _vq_quantthresh__44u6__p5_0[] = {
  143839. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143840. };
  143841. static long _vq_quantmap__44u6__p5_0[] = {
  143842. 7, 5, 3, 1, 0, 2, 4, 6,
  143843. 8,
  143844. };
  143845. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  143846. _vq_quantthresh__44u6__p5_0,
  143847. _vq_quantmap__44u6__p5_0,
  143848. 9,
  143849. 9
  143850. };
  143851. static static_codebook _44u6__p5_0 = {
  143852. 2, 81,
  143853. _vq_lengthlist__44u6__p5_0,
  143854. 1, -531628032, 1611661312, 4, 0,
  143855. _vq_quantlist__44u6__p5_0,
  143856. NULL,
  143857. &_vq_auxt__44u6__p5_0,
  143858. NULL,
  143859. 0
  143860. };
  143861. static long _vq_quantlist__44u6__p6_0[] = {
  143862. 4,
  143863. 3,
  143864. 5,
  143865. 2,
  143866. 6,
  143867. 1,
  143868. 7,
  143869. 0,
  143870. 8,
  143871. };
  143872. static long _vq_lengthlist__44u6__p6_0[] = {
  143873. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  143874. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  143875. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  143876. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  143877. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  143878. 12,
  143879. };
  143880. static float _vq_quantthresh__44u6__p6_0[] = {
  143881. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143882. };
  143883. static long _vq_quantmap__44u6__p6_0[] = {
  143884. 7, 5, 3, 1, 0, 2, 4, 6,
  143885. 8,
  143886. };
  143887. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  143888. _vq_quantthresh__44u6__p6_0,
  143889. _vq_quantmap__44u6__p6_0,
  143890. 9,
  143891. 9
  143892. };
  143893. static static_codebook _44u6__p6_0 = {
  143894. 2, 81,
  143895. _vq_lengthlist__44u6__p6_0,
  143896. 1, -531628032, 1611661312, 4, 0,
  143897. _vq_quantlist__44u6__p6_0,
  143898. NULL,
  143899. &_vq_auxt__44u6__p6_0,
  143900. NULL,
  143901. 0
  143902. };
  143903. static long _vq_quantlist__44u6__p7_0[] = {
  143904. 1,
  143905. 0,
  143906. 2,
  143907. };
  143908. static long _vq_lengthlist__44u6__p7_0[] = {
  143909. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  143910. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  143911. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  143912. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  143913. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  143914. 10,
  143915. };
  143916. static float _vq_quantthresh__44u6__p7_0[] = {
  143917. -5.5, 5.5,
  143918. };
  143919. static long _vq_quantmap__44u6__p7_0[] = {
  143920. 1, 0, 2,
  143921. };
  143922. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  143923. _vq_quantthresh__44u6__p7_0,
  143924. _vq_quantmap__44u6__p7_0,
  143925. 3,
  143926. 3
  143927. };
  143928. static static_codebook _44u6__p7_0 = {
  143929. 4, 81,
  143930. _vq_lengthlist__44u6__p7_0,
  143931. 1, -529137664, 1618345984, 2, 0,
  143932. _vq_quantlist__44u6__p7_0,
  143933. NULL,
  143934. &_vq_auxt__44u6__p7_0,
  143935. NULL,
  143936. 0
  143937. };
  143938. static long _vq_quantlist__44u6__p7_1[] = {
  143939. 5,
  143940. 4,
  143941. 6,
  143942. 3,
  143943. 7,
  143944. 2,
  143945. 8,
  143946. 1,
  143947. 9,
  143948. 0,
  143949. 10,
  143950. };
  143951. static long _vq_lengthlist__44u6__p7_1[] = {
  143952. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  143953. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  143954. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  143955. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  143956. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143957. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143958. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143959. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143960. };
  143961. static float _vq_quantthresh__44u6__p7_1[] = {
  143962. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143963. 3.5, 4.5,
  143964. };
  143965. static long _vq_quantmap__44u6__p7_1[] = {
  143966. 9, 7, 5, 3, 1, 0, 2, 4,
  143967. 6, 8, 10,
  143968. };
  143969. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  143970. _vq_quantthresh__44u6__p7_1,
  143971. _vq_quantmap__44u6__p7_1,
  143972. 11,
  143973. 11
  143974. };
  143975. static static_codebook _44u6__p7_1 = {
  143976. 2, 121,
  143977. _vq_lengthlist__44u6__p7_1,
  143978. 1, -531365888, 1611661312, 4, 0,
  143979. _vq_quantlist__44u6__p7_1,
  143980. NULL,
  143981. &_vq_auxt__44u6__p7_1,
  143982. NULL,
  143983. 0
  143984. };
  143985. static long _vq_quantlist__44u6__p8_0[] = {
  143986. 5,
  143987. 4,
  143988. 6,
  143989. 3,
  143990. 7,
  143991. 2,
  143992. 8,
  143993. 1,
  143994. 9,
  143995. 0,
  143996. 10,
  143997. };
  143998. static long _vq_lengthlist__44u6__p8_0[] = {
  143999. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  144000. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  144001. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  144002. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  144003. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  144004. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  144005. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  144006. 12,13,13,14,14,14,15,15,15,
  144007. };
  144008. static float _vq_quantthresh__44u6__p8_0[] = {
  144009. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144010. 38.5, 49.5,
  144011. };
  144012. static long _vq_quantmap__44u6__p8_0[] = {
  144013. 9, 7, 5, 3, 1, 0, 2, 4,
  144014. 6, 8, 10,
  144015. };
  144016. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  144017. _vq_quantthresh__44u6__p8_0,
  144018. _vq_quantmap__44u6__p8_0,
  144019. 11,
  144020. 11
  144021. };
  144022. static static_codebook _44u6__p8_0 = {
  144023. 2, 121,
  144024. _vq_lengthlist__44u6__p8_0,
  144025. 1, -524582912, 1618345984, 4, 0,
  144026. _vq_quantlist__44u6__p8_0,
  144027. NULL,
  144028. &_vq_auxt__44u6__p8_0,
  144029. NULL,
  144030. 0
  144031. };
  144032. static long _vq_quantlist__44u6__p8_1[] = {
  144033. 5,
  144034. 4,
  144035. 6,
  144036. 3,
  144037. 7,
  144038. 2,
  144039. 8,
  144040. 1,
  144041. 9,
  144042. 0,
  144043. 10,
  144044. };
  144045. static long _vq_lengthlist__44u6__p8_1[] = {
  144046. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  144047. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  144048. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  144049. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  144050. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144051. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  144052. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144053. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144054. };
  144055. static float _vq_quantthresh__44u6__p8_1[] = {
  144056. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144057. 3.5, 4.5,
  144058. };
  144059. static long _vq_quantmap__44u6__p8_1[] = {
  144060. 9, 7, 5, 3, 1, 0, 2, 4,
  144061. 6, 8, 10,
  144062. };
  144063. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  144064. _vq_quantthresh__44u6__p8_1,
  144065. _vq_quantmap__44u6__p8_1,
  144066. 11,
  144067. 11
  144068. };
  144069. static static_codebook _44u6__p8_1 = {
  144070. 2, 121,
  144071. _vq_lengthlist__44u6__p8_1,
  144072. 1, -531365888, 1611661312, 4, 0,
  144073. _vq_quantlist__44u6__p8_1,
  144074. NULL,
  144075. &_vq_auxt__44u6__p8_1,
  144076. NULL,
  144077. 0
  144078. };
  144079. static long _vq_quantlist__44u6__p9_0[] = {
  144080. 7,
  144081. 6,
  144082. 8,
  144083. 5,
  144084. 9,
  144085. 4,
  144086. 10,
  144087. 3,
  144088. 11,
  144089. 2,
  144090. 12,
  144091. 1,
  144092. 13,
  144093. 0,
  144094. 14,
  144095. };
  144096. static long _vq_lengthlist__44u6__p9_0[] = {
  144097. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  144098. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  144099. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  144100. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  144101. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144102. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144103. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144104. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144105. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144106. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144107. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144108. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144109. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144110. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144111. 14,
  144112. };
  144113. static float _vq_quantthresh__44u6__p9_0[] = {
  144114. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  144115. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  144116. };
  144117. static long _vq_quantmap__44u6__p9_0[] = {
  144118. 13, 11, 9, 7, 5, 3, 1, 0,
  144119. 2, 4, 6, 8, 10, 12, 14,
  144120. };
  144121. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  144122. _vq_quantthresh__44u6__p9_0,
  144123. _vq_quantmap__44u6__p9_0,
  144124. 15,
  144125. 15
  144126. };
  144127. static static_codebook _44u6__p9_0 = {
  144128. 2, 225,
  144129. _vq_lengthlist__44u6__p9_0,
  144130. 1, -514071552, 1627381760, 4, 0,
  144131. _vq_quantlist__44u6__p9_0,
  144132. NULL,
  144133. &_vq_auxt__44u6__p9_0,
  144134. NULL,
  144135. 0
  144136. };
  144137. static long _vq_quantlist__44u6__p9_1[] = {
  144138. 7,
  144139. 6,
  144140. 8,
  144141. 5,
  144142. 9,
  144143. 4,
  144144. 10,
  144145. 3,
  144146. 11,
  144147. 2,
  144148. 12,
  144149. 1,
  144150. 13,
  144151. 0,
  144152. 14,
  144153. };
  144154. static long _vq_lengthlist__44u6__p9_1[] = {
  144155. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  144156. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  144157. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  144158. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  144159. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  144160. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  144161. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  144162. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  144163. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  144164. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  144165. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  144166. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  144167. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  144168. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  144169. 13,
  144170. };
  144171. static float _vq_quantthresh__44u6__p9_1[] = {
  144172. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144173. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144174. };
  144175. static long _vq_quantmap__44u6__p9_1[] = {
  144176. 13, 11, 9, 7, 5, 3, 1, 0,
  144177. 2, 4, 6, 8, 10, 12, 14,
  144178. };
  144179. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  144180. _vq_quantthresh__44u6__p9_1,
  144181. _vq_quantmap__44u6__p9_1,
  144182. 15,
  144183. 15
  144184. };
  144185. static static_codebook _44u6__p9_1 = {
  144186. 2, 225,
  144187. _vq_lengthlist__44u6__p9_1,
  144188. 1, -522338304, 1620115456, 4, 0,
  144189. _vq_quantlist__44u6__p9_1,
  144190. NULL,
  144191. &_vq_auxt__44u6__p9_1,
  144192. NULL,
  144193. 0
  144194. };
  144195. static long _vq_quantlist__44u6__p9_2[] = {
  144196. 8,
  144197. 7,
  144198. 9,
  144199. 6,
  144200. 10,
  144201. 5,
  144202. 11,
  144203. 4,
  144204. 12,
  144205. 3,
  144206. 13,
  144207. 2,
  144208. 14,
  144209. 1,
  144210. 15,
  144211. 0,
  144212. 16,
  144213. };
  144214. static long _vq_lengthlist__44u6__p9_2[] = {
  144215. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  144216. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  144217. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  144218. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144219. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144220. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144221. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144222. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144223. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  144224. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  144225. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  144226. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144227. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  144228. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  144229. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  144230. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  144231. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  144232. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  144233. 10,
  144234. };
  144235. static float _vq_quantthresh__44u6__p9_2[] = {
  144236. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144237. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144238. };
  144239. static long _vq_quantmap__44u6__p9_2[] = {
  144240. 15, 13, 11, 9, 7, 5, 3, 1,
  144241. 0, 2, 4, 6, 8, 10, 12, 14,
  144242. 16,
  144243. };
  144244. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  144245. _vq_quantthresh__44u6__p9_2,
  144246. _vq_quantmap__44u6__p9_2,
  144247. 17,
  144248. 17
  144249. };
  144250. static static_codebook _44u6__p9_2 = {
  144251. 2, 289,
  144252. _vq_lengthlist__44u6__p9_2,
  144253. 1, -529530880, 1611661312, 5, 0,
  144254. _vq_quantlist__44u6__p9_2,
  144255. NULL,
  144256. &_vq_auxt__44u6__p9_2,
  144257. NULL,
  144258. 0
  144259. };
  144260. static long _huff_lengthlist__44u6__short[] = {
  144261. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  144262. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  144263. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  144264. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  144265. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  144266. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  144267. 7, 6, 9,16,
  144268. };
  144269. static static_codebook _huff_book__44u6__short = {
  144270. 2, 100,
  144271. _huff_lengthlist__44u6__short,
  144272. 0, 0, 0, 0, 0,
  144273. NULL,
  144274. NULL,
  144275. NULL,
  144276. NULL,
  144277. 0
  144278. };
  144279. static long _huff_lengthlist__44u7__long[] = {
  144280. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  144281. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  144282. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  144283. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  144284. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  144285. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  144286. 12, 8, 6, 7,
  144287. };
  144288. static static_codebook _huff_book__44u7__long = {
  144289. 2, 100,
  144290. _huff_lengthlist__44u7__long,
  144291. 0, 0, 0, 0, 0,
  144292. NULL,
  144293. NULL,
  144294. NULL,
  144295. NULL,
  144296. 0
  144297. };
  144298. static long _vq_quantlist__44u7__p1_0[] = {
  144299. 1,
  144300. 0,
  144301. 2,
  144302. };
  144303. static long _vq_lengthlist__44u7__p1_0[] = {
  144304. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144305. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  144306. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  144307. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  144308. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  144309. 12,
  144310. };
  144311. static float _vq_quantthresh__44u7__p1_0[] = {
  144312. -0.5, 0.5,
  144313. };
  144314. static long _vq_quantmap__44u7__p1_0[] = {
  144315. 1, 0, 2,
  144316. };
  144317. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  144318. _vq_quantthresh__44u7__p1_0,
  144319. _vq_quantmap__44u7__p1_0,
  144320. 3,
  144321. 3
  144322. };
  144323. static static_codebook _44u7__p1_0 = {
  144324. 4, 81,
  144325. _vq_lengthlist__44u7__p1_0,
  144326. 1, -535822336, 1611661312, 2, 0,
  144327. _vq_quantlist__44u7__p1_0,
  144328. NULL,
  144329. &_vq_auxt__44u7__p1_0,
  144330. NULL,
  144331. 0
  144332. };
  144333. static long _vq_quantlist__44u7__p2_0[] = {
  144334. 1,
  144335. 0,
  144336. 2,
  144337. };
  144338. static long _vq_lengthlist__44u7__p2_0[] = {
  144339. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  144340. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  144341. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  144342. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  144343. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  144344. 9,
  144345. };
  144346. static float _vq_quantthresh__44u7__p2_0[] = {
  144347. -0.5, 0.5,
  144348. };
  144349. static long _vq_quantmap__44u7__p2_0[] = {
  144350. 1, 0, 2,
  144351. };
  144352. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  144353. _vq_quantthresh__44u7__p2_0,
  144354. _vq_quantmap__44u7__p2_0,
  144355. 3,
  144356. 3
  144357. };
  144358. static static_codebook _44u7__p2_0 = {
  144359. 4, 81,
  144360. _vq_lengthlist__44u7__p2_0,
  144361. 1, -535822336, 1611661312, 2, 0,
  144362. _vq_quantlist__44u7__p2_0,
  144363. NULL,
  144364. &_vq_auxt__44u7__p2_0,
  144365. NULL,
  144366. 0
  144367. };
  144368. static long _vq_quantlist__44u7__p3_0[] = {
  144369. 2,
  144370. 1,
  144371. 3,
  144372. 0,
  144373. 4,
  144374. };
  144375. static long _vq_lengthlist__44u7__p3_0[] = {
  144376. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  144377. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  144378. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  144379. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  144380. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  144381. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  144382. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  144383. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  144384. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  144385. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  144386. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  144387. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  144388. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  144389. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  144390. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  144391. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  144392. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  144393. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  144394. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  144395. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  144396. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  144397. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  144398. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  144399. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  144400. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  144401. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  144402. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  144403. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  144404. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  144405. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  144406. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  144407. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  144408. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  144409. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  144410. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  144411. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  144412. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  144413. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  144414. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  144415. 0,
  144416. };
  144417. static float _vq_quantthresh__44u7__p3_0[] = {
  144418. -1.5, -0.5, 0.5, 1.5,
  144419. };
  144420. static long _vq_quantmap__44u7__p3_0[] = {
  144421. 3, 1, 0, 2, 4,
  144422. };
  144423. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  144424. _vq_quantthresh__44u7__p3_0,
  144425. _vq_quantmap__44u7__p3_0,
  144426. 5,
  144427. 5
  144428. };
  144429. static static_codebook _44u7__p3_0 = {
  144430. 4, 625,
  144431. _vq_lengthlist__44u7__p3_0,
  144432. 1, -533725184, 1611661312, 3, 0,
  144433. _vq_quantlist__44u7__p3_0,
  144434. NULL,
  144435. &_vq_auxt__44u7__p3_0,
  144436. NULL,
  144437. 0
  144438. };
  144439. static long _vq_quantlist__44u7__p4_0[] = {
  144440. 2,
  144441. 1,
  144442. 3,
  144443. 0,
  144444. 4,
  144445. };
  144446. static long _vq_lengthlist__44u7__p4_0[] = {
  144447. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  144448. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  144449. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  144450. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  144451. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  144452. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  144453. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  144454. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  144455. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  144456. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  144457. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  144458. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  144459. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  144460. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  144461. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  144462. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  144463. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  144464. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  144465. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  144466. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  144467. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  144468. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  144469. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  144470. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  144471. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  144472. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  144473. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  144474. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  144475. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  144476. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  144477. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  144478. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  144479. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  144480. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  144481. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  144482. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  144483. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  144484. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  144485. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  144486. 14,
  144487. };
  144488. static float _vq_quantthresh__44u7__p4_0[] = {
  144489. -1.5, -0.5, 0.5, 1.5,
  144490. };
  144491. static long _vq_quantmap__44u7__p4_0[] = {
  144492. 3, 1, 0, 2, 4,
  144493. };
  144494. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  144495. _vq_quantthresh__44u7__p4_0,
  144496. _vq_quantmap__44u7__p4_0,
  144497. 5,
  144498. 5
  144499. };
  144500. static static_codebook _44u7__p4_0 = {
  144501. 4, 625,
  144502. _vq_lengthlist__44u7__p4_0,
  144503. 1, -533725184, 1611661312, 3, 0,
  144504. _vq_quantlist__44u7__p4_0,
  144505. NULL,
  144506. &_vq_auxt__44u7__p4_0,
  144507. NULL,
  144508. 0
  144509. };
  144510. static long _vq_quantlist__44u7__p5_0[] = {
  144511. 4,
  144512. 3,
  144513. 5,
  144514. 2,
  144515. 6,
  144516. 1,
  144517. 7,
  144518. 0,
  144519. 8,
  144520. };
  144521. static long _vq_lengthlist__44u7__p5_0[] = {
  144522. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  144523. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  144524. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  144525. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  144526. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  144527. 14,
  144528. };
  144529. static float _vq_quantthresh__44u7__p5_0[] = {
  144530. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144531. };
  144532. static long _vq_quantmap__44u7__p5_0[] = {
  144533. 7, 5, 3, 1, 0, 2, 4, 6,
  144534. 8,
  144535. };
  144536. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  144537. _vq_quantthresh__44u7__p5_0,
  144538. _vq_quantmap__44u7__p5_0,
  144539. 9,
  144540. 9
  144541. };
  144542. static static_codebook _44u7__p5_0 = {
  144543. 2, 81,
  144544. _vq_lengthlist__44u7__p5_0,
  144545. 1, -531628032, 1611661312, 4, 0,
  144546. _vq_quantlist__44u7__p5_0,
  144547. NULL,
  144548. &_vq_auxt__44u7__p5_0,
  144549. NULL,
  144550. 0
  144551. };
  144552. static long _vq_quantlist__44u7__p6_0[] = {
  144553. 4,
  144554. 3,
  144555. 5,
  144556. 2,
  144557. 6,
  144558. 1,
  144559. 7,
  144560. 0,
  144561. 8,
  144562. };
  144563. static long _vq_lengthlist__44u7__p6_0[] = {
  144564. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  144565. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  144566. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  144567. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  144568. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  144569. 12,
  144570. };
  144571. static float _vq_quantthresh__44u7__p6_0[] = {
  144572. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144573. };
  144574. static long _vq_quantmap__44u7__p6_0[] = {
  144575. 7, 5, 3, 1, 0, 2, 4, 6,
  144576. 8,
  144577. };
  144578. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  144579. _vq_quantthresh__44u7__p6_0,
  144580. _vq_quantmap__44u7__p6_0,
  144581. 9,
  144582. 9
  144583. };
  144584. static static_codebook _44u7__p6_0 = {
  144585. 2, 81,
  144586. _vq_lengthlist__44u7__p6_0,
  144587. 1, -531628032, 1611661312, 4, 0,
  144588. _vq_quantlist__44u7__p6_0,
  144589. NULL,
  144590. &_vq_auxt__44u7__p6_0,
  144591. NULL,
  144592. 0
  144593. };
  144594. static long _vq_quantlist__44u7__p7_0[] = {
  144595. 1,
  144596. 0,
  144597. 2,
  144598. };
  144599. static long _vq_lengthlist__44u7__p7_0[] = {
  144600. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  144601. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  144602. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  144603. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  144604. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  144605. 10,
  144606. };
  144607. static float _vq_quantthresh__44u7__p7_0[] = {
  144608. -5.5, 5.5,
  144609. };
  144610. static long _vq_quantmap__44u7__p7_0[] = {
  144611. 1, 0, 2,
  144612. };
  144613. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  144614. _vq_quantthresh__44u7__p7_0,
  144615. _vq_quantmap__44u7__p7_0,
  144616. 3,
  144617. 3
  144618. };
  144619. static static_codebook _44u7__p7_0 = {
  144620. 4, 81,
  144621. _vq_lengthlist__44u7__p7_0,
  144622. 1, -529137664, 1618345984, 2, 0,
  144623. _vq_quantlist__44u7__p7_0,
  144624. NULL,
  144625. &_vq_auxt__44u7__p7_0,
  144626. NULL,
  144627. 0
  144628. };
  144629. static long _vq_quantlist__44u7__p7_1[] = {
  144630. 5,
  144631. 4,
  144632. 6,
  144633. 3,
  144634. 7,
  144635. 2,
  144636. 8,
  144637. 1,
  144638. 9,
  144639. 0,
  144640. 10,
  144641. };
  144642. static long _vq_lengthlist__44u7__p7_1[] = {
  144643. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  144644. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  144645. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  144646. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  144647. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  144648. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  144649. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  144650. 8, 9, 9, 9, 9, 9,10,10,10,
  144651. };
  144652. static float _vq_quantthresh__44u7__p7_1[] = {
  144653. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144654. 3.5, 4.5,
  144655. };
  144656. static long _vq_quantmap__44u7__p7_1[] = {
  144657. 9, 7, 5, 3, 1, 0, 2, 4,
  144658. 6, 8, 10,
  144659. };
  144660. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  144661. _vq_quantthresh__44u7__p7_1,
  144662. _vq_quantmap__44u7__p7_1,
  144663. 11,
  144664. 11
  144665. };
  144666. static static_codebook _44u7__p7_1 = {
  144667. 2, 121,
  144668. _vq_lengthlist__44u7__p7_1,
  144669. 1, -531365888, 1611661312, 4, 0,
  144670. _vq_quantlist__44u7__p7_1,
  144671. NULL,
  144672. &_vq_auxt__44u7__p7_1,
  144673. NULL,
  144674. 0
  144675. };
  144676. static long _vq_quantlist__44u7__p8_0[] = {
  144677. 5,
  144678. 4,
  144679. 6,
  144680. 3,
  144681. 7,
  144682. 2,
  144683. 8,
  144684. 1,
  144685. 9,
  144686. 0,
  144687. 10,
  144688. };
  144689. static long _vq_lengthlist__44u7__p8_0[] = {
  144690. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  144691. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  144692. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  144693. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  144694. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  144695. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  144696. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  144697. 12,13,13,14,14,15,15,15,16,
  144698. };
  144699. static float _vq_quantthresh__44u7__p8_0[] = {
  144700. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144701. 38.5, 49.5,
  144702. };
  144703. static long _vq_quantmap__44u7__p8_0[] = {
  144704. 9, 7, 5, 3, 1, 0, 2, 4,
  144705. 6, 8, 10,
  144706. };
  144707. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  144708. _vq_quantthresh__44u7__p8_0,
  144709. _vq_quantmap__44u7__p8_0,
  144710. 11,
  144711. 11
  144712. };
  144713. static static_codebook _44u7__p8_0 = {
  144714. 2, 121,
  144715. _vq_lengthlist__44u7__p8_0,
  144716. 1, -524582912, 1618345984, 4, 0,
  144717. _vq_quantlist__44u7__p8_0,
  144718. NULL,
  144719. &_vq_auxt__44u7__p8_0,
  144720. NULL,
  144721. 0
  144722. };
  144723. static long _vq_quantlist__44u7__p8_1[] = {
  144724. 5,
  144725. 4,
  144726. 6,
  144727. 3,
  144728. 7,
  144729. 2,
  144730. 8,
  144731. 1,
  144732. 9,
  144733. 0,
  144734. 10,
  144735. };
  144736. static long _vq_lengthlist__44u7__p8_1[] = {
  144737. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144738. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  144739. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  144740. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  144741. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  144742. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  144743. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  144744. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  144745. };
  144746. static float _vq_quantthresh__44u7__p8_1[] = {
  144747. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144748. 3.5, 4.5,
  144749. };
  144750. static long _vq_quantmap__44u7__p8_1[] = {
  144751. 9, 7, 5, 3, 1, 0, 2, 4,
  144752. 6, 8, 10,
  144753. };
  144754. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  144755. _vq_quantthresh__44u7__p8_1,
  144756. _vq_quantmap__44u7__p8_1,
  144757. 11,
  144758. 11
  144759. };
  144760. static static_codebook _44u7__p8_1 = {
  144761. 2, 121,
  144762. _vq_lengthlist__44u7__p8_1,
  144763. 1, -531365888, 1611661312, 4, 0,
  144764. _vq_quantlist__44u7__p8_1,
  144765. NULL,
  144766. &_vq_auxt__44u7__p8_1,
  144767. NULL,
  144768. 0
  144769. };
  144770. static long _vq_quantlist__44u7__p9_0[] = {
  144771. 5,
  144772. 4,
  144773. 6,
  144774. 3,
  144775. 7,
  144776. 2,
  144777. 8,
  144778. 1,
  144779. 9,
  144780. 0,
  144781. 10,
  144782. };
  144783. static long _vq_lengthlist__44u7__p9_0[] = {
  144784. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  144785. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  144786. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144787. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144788. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144789. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144790. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  144791. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144792. };
  144793. static float _vq_quantthresh__44u7__p9_0[] = {
  144794. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  144795. 2229.5, 2866.5,
  144796. };
  144797. static long _vq_quantmap__44u7__p9_0[] = {
  144798. 9, 7, 5, 3, 1, 0, 2, 4,
  144799. 6, 8, 10,
  144800. };
  144801. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  144802. _vq_quantthresh__44u7__p9_0,
  144803. _vq_quantmap__44u7__p9_0,
  144804. 11,
  144805. 11
  144806. };
  144807. static static_codebook _44u7__p9_0 = {
  144808. 2, 121,
  144809. _vq_lengthlist__44u7__p9_0,
  144810. 1, -512171520, 1630791680, 4, 0,
  144811. _vq_quantlist__44u7__p9_0,
  144812. NULL,
  144813. &_vq_auxt__44u7__p9_0,
  144814. NULL,
  144815. 0
  144816. };
  144817. static long _vq_quantlist__44u7__p9_1[] = {
  144818. 6,
  144819. 5,
  144820. 7,
  144821. 4,
  144822. 8,
  144823. 3,
  144824. 9,
  144825. 2,
  144826. 10,
  144827. 1,
  144828. 11,
  144829. 0,
  144830. 12,
  144831. };
  144832. static long _vq_lengthlist__44u7__p9_1[] = {
  144833. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  144834. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  144835. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  144836. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  144837. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  144838. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  144839. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  144840. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  144841. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  144842. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  144843. 15,15,15,15,17,17,16,17,16,
  144844. };
  144845. static float _vq_quantthresh__44u7__p9_1[] = {
  144846. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  144847. 122.5, 171.5, 220.5, 269.5,
  144848. };
  144849. static long _vq_quantmap__44u7__p9_1[] = {
  144850. 11, 9, 7, 5, 3, 1, 0, 2,
  144851. 4, 6, 8, 10, 12,
  144852. };
  144853. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  144854. _vq_quantthresh__44u7__p9_1,
  144855. _vq_quantmap__44u7__p9_1,
  144856. 13,
  144857. 13
  144858. };
  144859. static static_codebook _44u7__p9_1 = {
  144860. 2, 169,
  144861. _vq_lengthlist__44u7__p9_1,
  144862. 1, -518889472, 1622704128, 4, 0,
  144863. _vq_quantlist__44u7__p9_1,
  144864. NULL,
  144865. &_vq_auxt__44u7__p9_1,
  144866. NULL,
  144867. 0
  144868. };
  144869. static long _vq_quantlist__44u7__p9_2[] = {
  144870. 24,
  144871. 23,
  144872. 25,
  144873. 22,
  144874. 26,
  144875. 21,
  144876. 27,
  144877. 20,
  144878. 28,
  144879. 19,
  144880. 29,
  144881. 18,
  144882. 30,
  144883. 17,
  144884. 31,
  144885. 16,
  144886. 32,
  144887. 15,
  144888. 33,
  144889. 14,
  144890. 34,
  144891. 13,
  144892. 35,
  144893. 12,
  144894. 36,
  144895. 11,
  144896. 37,
  144897. 10,
  144898. 38,
  144899. 9,
  144900. 39,
  144901. 8,
  144902. 40,
  144903. 7,
  144904. 41,
  144905. 6,
  144906. 42,
  144907. 5,
  144908. 43,
  144909. 4,
  144910. 44,
  144911. 3,
  144912. 45,
  144913. 2,
  144914. 46,
  144915. 1,
  144916. 47,
  144917. 0,
  144918. 48,
  144919. };
  144920. static long _vq_lengthlist__44u7__p9_2[] = {
  144921. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  144922. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144923. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  144924. 8,
  144925. };
  144926. static float _vq_quantthresh__44u7__p9_2[] = {
  144927. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144928. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144929. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144930. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144931. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144932. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144933. };
  144934. static long _vq_quantmap__44u7__p9_2[] = {
  144935. 47, 45, 43, 41, 39, 37, 35, 33,
  144936. 31, 29, 27, 25, 23, 21, 19, 17,
  144937. 15, 13, 11, 9, 7, 5, 3, 1,
  144938. 0, 2, 4, 6, 8, 10, 12, 14,
  144939. 16, 18, 20, 22, 24, 26, 28, 30,
  144940. 32, 34, 36, 38, 40, 42, 44, 46,
  144941. 48,
  144942. };
  144943. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  144944. _vq_quantthresh__44u7__p9_2,
  144945. _vq_quantmap__44u7__p9_2,
  144946. 49,
  144947. 49
  144948. };
  144949. static static_codebook _44u7__p9_2 = {
  144950. 1, 49,
  144951. _vq_lengthlist__44u7__p9_2,
  144952. 1, -526909440, 1611661312, 6, 0,
  144953. _vq_quantlist__44u7__p9_2,
  144954. NULL,
  144955. &_vq_auxt__44u7__p9_2,
  144956. NULL,
  144957. 0
  144958. };
  144959. static long _huff_lengthlist__44u7__short[] = {
  144960. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  144961. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  144962. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  144963. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  144964. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  144965. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  144966. 6, 8, 5, 9,
  144967. };
  144968. static static_codebook _huff_book__44u7__short = {
  144969. 2, 100,
  144970. _huff_lengthlist__44u7__short,
  144971. 0, 0, 0, 0, 0,
  144972. NULL,
  144973. NULL,
  144974. NULL,
  144975. NULL,
  144976. 0
  144977. };
  144978. static long _huff_lengthlist__44u8__long[] = {
  144979. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  144980. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  144981. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  144982. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  144983. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  144984. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  144985. 10, 8, 8, 9,
  144986. };
  144987. static static_codebook _huff_book__44u8__long = {
  144988. 2, 100,
  144989. _huff_lengthlist__44u8__long,
  144990. 0, 0, 0, 0, 0,
  144991. NULL,
  144992. NULL,
  144993. NULL,
  144994. NULL,
  144995. 0
  144996. };
  144997. static long _huff_lengthlist__44u8__short[] = {
  144998. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  144999. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  145000. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  145001. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  145002. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  145003. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  145004. 10,10,15,17,
  145005. };
  145006. static static_codebook _huff_book__44u8__short = {
  145007. 2, 100,
  145008. _huff_lengthlist__44u8__short,
  145009. 0, 0, 0, 0, 0,
  145010. NULL,
  145011. NULL,
  145012. NULL,
  145013. NULL,
  145014. 0
  145015. };
  145016. static long _vq_quantlist__44u8_p1_0[] = {
  145017. 1,
  145018. 0,
  145019. 2,
  145020. };
  145021. static long _vq_lengthlist__44u8_p1_0[] = {
  145022. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  145023. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  145024. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  145025. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  145026. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  145027. 10,
  145028. };
  145029. static float _vq_quantthresh__44u8_p1_0[] = {
  145030. -0.5, 0.5,
  145031. };
  145032. static long _vq_quantmap__44u8_p1_0[] = {
  145033. 1, 0, 2,
  145034. };
  145035. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  145036. _vq_quantthresh__44u8_p1_0,
  145037. _vq_quantmap__44u8_p1_0,
  145038. 3,
  145039. 3
  145040. };
  145041. static static_codebook _44u8_p1_0 = {
  145042. 4, 81,
  145043. _vq_lengthlist__44u8_p1_0,
  145044. 1, -535822336, 1611661312, 2, 0,
  145045. _vq_quantlist__44u8_p1_0,
  145046. NULL,
  145047. &_vq_auxt__44u8_p1_0,
  145048. NULL,
  145049. 0
  145050. };
  145051. static long _vq_quantlist__44u8_p2_0[] = {
  145052. 2,
  145053. 1,
  145054. 3,
  145055. 0,
  145056. 4,
  145057. };
  145058. static long _vq_lengthlist__44u8_p2_0[] = {
  145059. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  145060. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  145061. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  145062. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  145063. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  145064. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  145065. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145066. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  145067. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  145068. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  145069. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  145070. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145071. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  145072. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  145073. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  145074. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  145075. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  145076. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  145077. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  145078. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  145079. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  145080. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  145081. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  145082. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  145083. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  145084. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  145085. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  145086. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  145087. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  145088. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  145089. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  145090. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145091. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  145092. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  145093. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  145094. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  145095. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  145096. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  145097. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  145098. 14,
  145099. };
  145100. static float _vq_quantthresh__44u8_p2_0[] = {
  145101. -1.5, -0.5, 0.5, 1.5,
  145102. };
  145103. static long _vq_quantmap__44u8_p2_0[] = {
  145104. 3, 1, 0, 2, 4,
  145105. };
  145106. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  145107. _vq_quantthresh__44u8_p2_0,
  145108. _vq_quantmap__44u8_p2_0,
  145109. 5,
  145110. 5
  145111. };
  145112. static static_codebook _44u8_p2_0 = {
  145113. 4, 625,
  145114. _vq_lengthlist__44u8_p2_0,
  145115. 1, -533725184, 1611661312, 3, 0,
  145116. _vq_quantlist__44u8_p2_0,
  145117. NULL,
  145118. &_vq_auxt__44u8_p2_0,
  145119. NULL,
  145120. 0
  145121. };
  145122. static long _vq_quantlist__44u8_p3_0[] = {
  145123. 4,
  145124. 3,
  145125. 5,
  145126. 2,
  145127. 6,
  145128. 1,
  145129. 7,
  145130. 0,
  145131. 8,
  145132. };
  145133. static long _vq_lengthlist__44u8_p3_0[] = {
  145134. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  145135. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  145136. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  145137. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  145138. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  145139. 12,
  145140. };
  145141. static float _vq_quantthresh__44u8_p3_0[] = {
  145142. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145143. };
  145144. static long _vq_quantmap__44u8_p3_0[] = {
  145145. 7, 5, 3, 1, 0, 2, 4, 6,
  145146. 8,
  145147. };
  145148. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  145149. _vq_quantthresh__44u8_p3_0,
  145150. _vq_quantmap__44u8_p3_0,
  145151. 9,
  145152. 9
  145153. };
  145154. static static_codebook _44u8_p3_0 = {
  145155. 2, 81,
  145156. _vq_lengthlist__44u8_p3_0,
  145157. 1, -531628032, 1611661312, 4, 0,
  145158. _vq_quantlist__44u8_p3_0,
  145159. NULL,
  145160. &_vq_auxt__44u8_p3_0,
  145161. NULL,
  145162. 0
  145163. };
  145164. static long _vq_quantlist__44u8_p4_0[] = {
  145165. 8,
  145166. 7,
  145167. 9,
  145168. 6,
  145169. 10,
  145170. 5,
  145171. 11,
  145172. 4,
  145173. 12,
  145174. 3,
  145175. 13,
  145176. 2,
  145177. 14,
  145178. 1,
  145179. 15,
  145180. 0,
  145181. 16,
  145182. };
  145183. static long _vq_lengthlist__44u8_p4_0[] = {
  145184. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  145185. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  145186. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  145187. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  145188. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  145189. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  145190. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  145191. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  145192. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  145193. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  145194. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  145195. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  145196. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  145197. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  145198. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  145199. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  145200. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  145201. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  145202. 14,
  145203. };
  145204. static float _vq_quantthresh__44u8_p4_0[] = {
  145205. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145206. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145207. };
  145208. static long _vq_quantmap__44u8_p4_0[] = {
  145209. 15, 13, 11, 9, 7, 5, 3, 1,
  145210. 0, 2, 4, 6, 8, 10, 12, 14,
  145211. 16,
  145212. };
  145213. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  145214. _vq_quantthresh__44u8_p4_0,
  145215. _vq_quantmap__44u8_p4_0,
  145216. 17,
  145217. 17
  145218. };
  145219. static static_codebook _44u8_p4_0 = {
  145220. 2, 289,
  145221. _vq_lengthlist__44u8_p4_0,
  145222. 1, -529530880, 1611661312, 5, 0,
  145223. _vq_quantlist__44u8_p4_0,
  145224. NULL,
  145225. &_vq_auxt__44u8_p4_0,
  145226. NULL,
  145227. 0
  145228. };
  145229. static long _vq_quantlist__44u8_p5_0[] = {
  145230. 1,
  145231. 0,
  145232. 2,
  145233. };
  145234. static long _vq_lengthlist__44u8_p5_0[] = {
  145235. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  145236. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  145237. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  145238. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145239. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  145240. 10,
  145241. };
  145242. static float _vq_quantthresh__44u8_p5_0[] = {
  145243. -5.5, 5.5,
  145244. };
  145245. static long _vq_quantmap__44u8_p5_0[] = {
  145246. 1, 0, 2,
  145247. };
  145248. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  145249. _vq_quantthresh__44u8_p5_0,
  145250. _vq_quantmap__44u8_p5_0,
  145251. 3,
  145252. 3
  145253. };
  145254. static static_codebook _44u8_p5_0 = {
  145255. 4, 81,
  145256. _vq_lengthlist__44u8_p5_0,
  145257. 1, -529137664, 1618345984, 2, 0,
  145258. _vq_quantlist__44u8_p5_0,
  145259. NULL,
  145260. &_vq_auxt__44u8_p5_0,
  145261. NULL,
  145262. 0
  145263. };
  145264. static long _vq_quantlist__44u8_p5_1[] = {
  145265. 5,
  145266. 4,
  145267. 6,
  145268. 3,
  145269. 7,
  145270. 2,
  145271. 8,
  145272. 1,
  145273. 9,
  145274. 0,
  145275. 10,
  145276. };
  145277. static long _vq_lengthlist__44u8_p5_1[] = {
  145278. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  145279. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  145280. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  145281. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  145282. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  145283. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  145284. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  145285. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  145286. };
  145287. static float _vq_quantthresh__44u8_p5_1[] = {
  145288. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145289. 3.5, 4.5,
  145290. };
  145291. static long _vq_quantmap__44u8_p5_1[] = {
  145292. 9, 7, 5, 3, 1, 0, 2, 4,
  145293. 6, 8, 10,
  145294. };
  145295. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  145296. _vq_quantthresh__44u8_p5_1,
  145297. _vq_quantmap__44u8_p5_1,
  145298. 11,
  145299. 11
  145300. };
  145301. static static_codebook _44u8_p5_1 = {
  145302. 2, 121,
  145303. _vq_lengthlist__44u8_p5_1,
  145304. 1, -531365888, 1611661312, 4, 0,
  145305. _vq_quantlist__44u8_p5_1,
  145306. NULL,
  145307. &_vq_auxt__44u8_p5_1,
  145308. NULL,
  145309. 0
  145310. };
  145311. static long _vq_quantlist__44u8_p6_0[] = {
  145312. 6,
  145313. 5,
  145314. 7,
  145315. 4,
  145316. 8,
  145317. 3,
  145318. 9,
  145319. 2,
  145320. 10,
  145321. 1,
  145322. 11,
  145323. 0,
  145324. 12,
  145325. };
  145326. static long _vq_lengthlist__44u8_p6_0[] = {
  145327. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  145328. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  145329. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  145330. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  145331. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  145332. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  145333. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  145334. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  145335. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  145336. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  145337. 11,11,11,11,11,12,11,12,12,
  145338. };
  145339. static float _vq_quantthresh__44u8_p6_0[] = {
  145340. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145341. 12.5, 17.5, 22.5, 27.5,
  145342. };
  145343. static long _vq_quantmap__44u8_p6_0[] = {
  145344. 11, 9, 7, 5, 3, 1, 0, 2,
  145345. 4, 6, 8, 10, 12,
  145346. };
  145347. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  145348. _vq_quantthresh__44u8_p6_0,
  145349. _vq_quantmap__44u8_p6_0,
  145350. 13,
  145351. 13
  145352. };
  145353. static static_codebook _44u8_p6_0 = {
  145354. 2, 169,
  145355. _vq_lengthlist__44u8_p6_0,
  145356. 1, -526516224, 1616117760, 4, 0,
  145357. _vq_quantlist__44u8_p6_0,
  145358. NULL,
  145359. &_vq_auxt__44u8_p6_0,
  145360. NULL,
  145361. 0
  145362. };
  145363. static long _vq_quantlist__44u8_p6_1[] = {
  145364. 2,
  145365. 1,
  145366. 3,
  145367. 0,
  145368. 4,
  145369. };
  145370. static long _vq_lengthlist__44u8_p6_1[] = {
  145371. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  145372. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  145373. };
  145374. static float _vq_quantthresh__44u8_p6_1[] = {
  145375. -1.5, -0.5, 0.5, 1.5,
  145376. };
  145377. static long _vq_quantmap__44u8_p6_1[] = {
  145378. 3, 1, 0, 2, 4,
  145379. };
  145380. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  145381. _vq_quantthresh__44u8_p6_1,
  145382. _vq_quantmap__44u8_p6_1,
  145383. 5,
  145384. 5
  145385. };
  145386. static static_codebook _44u8_p6_1 = {
  145387. 2, 25,
  145388. _vq_lengthlist__44u8_p6_1,
  145389. 1, -533725184, 1611661312, 3, 0,
  145390. _vq_quantlist__44u8_p6_1,
  145391. NULL,
  145392. &_vq_auxt__44u8_p6_1,
  145393. NULL,
  145394. 0
  145395. };
  145396. static long _vq_quantlist__44u8_p7_0[] = {
  145397. 6,
  145398. 5,
  145399. 7,
  145400. 4,
  145401. 8,
  145402. 3,
  145403. 9,
  145404. 2,
  145405. 10,
  145406. 1,
  145407. 11,
  145408. 0,
  145409. 12,
  145410. };
  145411. static long _vq_lengthlist__44u8_p7_0[] = {
  145412. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  145413. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  145414. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  145415. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  145416. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  145417. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  145418. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  145419. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  145420. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  145421. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  145422. 13,13,14,14,14,15,15,15,16,
  145423. };
  145424. static float _vq_quantthresh__44u8_p7_0[] = {
  145425. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  145426. 27.5, 38.5, 49.5, 60.5,
  145427. };
  145428. static long _vq_quantmap__44u8_p7_0[] = {
  145429. 11, 9, 7, 5, 3, 1, 0, 2,
  145430. 4, 6, 8, 10, 12,
  145431. };
  145432. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  145433. _vq_quantthresh__44u8_p7_0,
  145434. _vq_quantmap__44u8_p7_0,
  145435. 13,
  145436. 13
  145437. };
  145438. static static_codebook _44u8_p7_0 = {
  145439. 2, 169,
  145440. _vq_lengthlist__44u8_p7_0,
  145441. 1, -523206656, 1618345984, 4, 0,
  145442. _vq_quantlist__44u8_p7_0,
  145443. NULL,
  145444. &_vq_auxt__44u8_p7_0,
  145445. NULL,
  145446. 0
  145447. };
  145448. static long _vq_quantlist__44u8_p7_1[] = {
  145449. 5,
  145450. 4,
  145451. 6,
  145452. 3,
  145453. 7,
  145454. 2,
  145455. 8,
  145456. 1,
  145457. 9,
  145458. 0,
  145459. 10,
  145460. };
  145461. static long _vq_lengthlist__44u8_p7_1[] = {
  145462. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  145463. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  145464. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  145465. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  145466. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  145467. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  145468. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  145469. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  145470. };
  145471. static float _vq_quantthresh__44u8_p7_1[] = {
  145472. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145473. 3.5, 4.5,
  145474. };
  145475. static long _vq_quantmap__44u8_p7_1[] = {
  145476. 9, 7, 5, 3, 1, 0, 2, 4,
  145477. 6, 8, 10,
  145478. };
  145479. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  145480. _vq_quantthresh__44u8_p7_1,
  145481. _vq_quantmap__44u8_p7_1,
  145482. 11,
  145483. 11
  145484. };
  145485. static static_codebook _44u8_p7_1 = {
  145486. 2, 121,
  145487. _vq_lengthlist__44u8_p7_1,
  145488. 1, -531365888, 1611661312, 4, 0,
  145489. _vq_quantlist__44u8_p7_1,
  145490. NULL,
  145491. &_vq_auxt__44u8_p7_1,
  145492. NULL,
  145493. 0
  145494. };
  145495. static long _vq_quantlist__44u8_p8_0[] = {
  145496. 7,
  145497. 6,
  145498. 8,
  145499. 5,
  145500. 9,
  145501. 4,
  145502. 10,
  145503. 3,
  145504. 11,
  145505. 2,
  145506. 12,
  145507. 1,
  145508. 13,
  145509. 0,
  145510. 14,
  145511. };
  145512. static long _vq_lengthlist__44u8_p8_0[] = {
  145513. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  145514. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  145515. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  145516. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  145517. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  145518. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  145519. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  145520. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  145521. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  145522. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  145523. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  145524. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  145525. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  145526. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  145527. 17,
  145528. };
  145529. static float _vq_quantthresh__44u8_p8_0[] = {
  145530. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145531. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145532. };
  145533. static long _vq_quantmap__44u8_p8_0[] = {
  145534. 13, 11, 9, 7, 5, 3, 1, 0,
  145535. 2, 4, 6, 8, 10, 12, 14,
  145536. };
  145537. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  145538. _vq_quantthresh__44u8_p8_0,
  145539. _vq_quantmap__44u8_p8_0,
  145540. 15,
  145541. 15
  145542. };
  145543. static static_codebook _44u8_p8_0 = {
  145544. 2, 225,
  145545. _vq_lengthlist__44u8_p8_0,
  145546. 1, -520986624, 1620377600, 4, 0,
  145547. _vq_quantlist__44u8_p8_0,
  145548. NULL,
  145549. &_vq_auxt__44u8_p8_0,
  145550. NULL,
  145551. 0
  145552. };
  145553. static long _vq_quantlist__44u8_p8_1[] = {
  145554. 10,
  145555. 9,
  145556. 11,
  145557. 8,
  145558. 12,
  145559. 7,
  145560. 13,
  145561. 6,
  145562. 14,
  145563. 5,
  145564. 15,
  145565. 4,
  145566. 16,
  145567. 3,
  145568. 17,
  145569. 2,
  145570. 18,
  145571. 1,
  145572. 19,
  145573. 0,
  145574. 20,
  145575. };
  145576. static long _vq_lengthlist__44u8_p8_1[] = {
  145577. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145578. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  145579. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  145580. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  145581. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145582. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145583. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  145584. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  145585. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  145586. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  145587. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  145588. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  145589. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  145590. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  145591. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  145592. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145593. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  145594. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  145595. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  145596. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  145597. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145598. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  145599. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  145600. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145601. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145602. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  145603. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  145604. 10,10,10,10,10,10,10,10,10,
  145605. };
  145606. static float _vq_quantthresh__44u8_p8_1[] = {
  145607. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145608. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145609. 6.5, 7.5, 8.5, 9.5,
  145610. };
  145611. static long _vq_quantmap__44u8_p8_1[] = {
  145612. 19, 17, 15, 13, 11, 9, 7, 5,
  145613. 3, 1, 0, 2, 4, 6, 8, 10,
  145614. 12, 14, 16, 18, 20,
  145615. };
  145616. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  145617. _vq_quantthresh__44u8_p8_1,
  145618. _vq_quantmap__44u8_p8_1,
  145619. 21,
  145620. 21
  145621. };
  145622. static static_codebook _44u8_p8_1 = {
  145623. 2, 441,
  145624. _vq_lengthlist__44u8_p8_1,
  145625. 1, -529268736, 1611661312, 5, 0,
  145626. _vq_quantlist__44u8_p8_1,
  145627. NULL,
  145628. &_vq_auxt__44u8_p8_1,
  145629. NULL,
  145630. 0
  145631. };
  145632. static long _vq_quantlist__44u8_p9_0[] = {
  145633. 4,
  145634. 3,
  145635. 5,
  145636. 2,
  145637. 6,
  145638. 1,
  145639. 7,
  145640. 0,
  145641. 8,
  145642. };
  145643. static long _vq_lengthlist__44u8_p9_0[] = {
  145644. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  145645. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145646. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145647. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145648. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  145649. 8,
  145650. };
  145651. static float _vq_quantthresh__44u8_p9_0[] = {
  145652. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  145653. };
  145654. static long _vq_quantmap__44u8_p9_0[] = {
  145655. 7, 5, 3, 1, 0, 2, 4, 6,
  145656. 8,
  145657. };
  145658. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  145659. _vq_quantthresh__44u8_p9_0,
  145660. _vq_quantmap__44u8_p9_0,
  145661. 9,
  145662. 9
  145663. };
  145664. static static_codebook _44u8_p9_0 = {
  145665. 2, 81,
  145666. _vq_lengthlist__44u8_p9_0,
  145667. 1, -511895552, 1631393792, 4, 0,
  145668. _vq_quantlist__44u8_p9_0,
  145669. NULL,
  145670. &_vq_auxt__44u8_p9_0,
  145671. NULL,
  145672. 0
  145673. };
  145674. static long _vq_quantlist__44u8_p9_1[] = {
  145675. 9,
  145676. 8,
  145677. 10,
  145678. 7,
  145679. 11,
  145680. 6,
  145681. 12,
  145682. 5,
  145683. 13,
  145684. 4,
  145685. 14,
  145686. 3,
  145687. 15,
  145688. 2,
  145689. 16,
  145690. 1,
  145691. 17,
  145692. 0,
  145693. 18,
  145694. };
  145695. static long _vq_lengthlist__44u8_p9_1[] = {
  145696. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  145697. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  145698. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  145699. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  145700. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  145701. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  145702. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  145703. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  145704. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  145705. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  145706. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  145707. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  145708. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  145709. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  145710. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  145711. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  145712. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  145713. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  145714. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  145715. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  145716. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  145717. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  145718. 16,15,16,16,16,16,16,16,16,
  145719. };
  145720. static float _vq_quantthresh__44u8_p9_1[] = {
  145721. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  145722. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  145723. 367.5, 416.5,
  145724. };
  145725. static long _vq_quantmap__44u8_p9_1[] = {
  145726. 17, 15, 13, 11, 9, 7, 5, 3,
  145727. 1, 0, 2, 4, 6, 8, 10, 12,
  145728. 14, 16, 18,
  145729. };
  145730. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  145731. _vq_quantthresh__44u8_p9_1,
  145732. _vq_quantmap__44u8_p9_1,
  145733. 19,
  145734. 19
  145735. };
  145736. static static_codebook _44u8_p9_1 = {
  145737. 2, 361,
  145738. _vq_lengthlist__44u8_p9_1,
  145739. 1, -518287360, 1622704128, 5, 0,
  145740. _vq_quantlist__44u8_p9_1,
  145741. NULL,
  145742. &_vq_auxt__44u8_p9_1,
  145743. NULL,
  145744. 0
  145745. };
  145746. static long _vq_quantlist__44u8_p9_2[] = {
  145747. 24,
  145748. 23,
  145749. 25,
  145750. 22,
  145751. 26,
  145752. 21,
  145753. 27,
  145754. 20,
  145755. 28,
  145756. 19,
  145757. 29,
  145758. 18,
  145759. 30,
  145760. 17,
  145761. 31,
  145762. 16,
  145763. 32,
  145764. 15,
  145765. 33,
  145766. 14,
  145767. 34,
  145768. 13,
  145769. 35,
  145770. 12,
  145771. 36,
  145772. 11,
  145773. 37,
  145774. 10,
  145775. 38,
  145776. 9,
  145777. 39,
  145778. 8,
  145779. 40,
  145780. 7,
  145781. 41,
  145782. 6,
  145783. 42,
  145784. 5,
  145785. 43,
  145786. 4,
  145787. 44,
  145788. 3,
  145789. 45,
  145790. 2,
  145791. 46,
  145792. 1,
  145793. 47,
  145794. 0,
  145795. 48,
  145796. };
  145797. static long _vq_lengthlist__44u8_p9_2[] = {
  145798. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  145799. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145800. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145801. 7,
  145802. };
  145803. static float _vq_quantthresh__44u8_p9_2[] = {
  145804. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145805. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145806. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145807. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145808. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145809. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145810. };
  145811. static long _vq_quantmap__44u8_p9_2[] = {
  145812. 47, 45, 43, 41, 39, 37, 35, 33,
  145813. 31, 29, 27, 25, 23, 21, 19, 17,
  145814. 15, 13, 11, 9, 7, 5, 3, 1,
  145815. 0, 2, 4, 6, 8, 10, 12, 14,
  145816. 16, 18, 20, 22, 24, 26, 28, 30,
  145817. 32, 34, 36, 38, 40, 42, 44, 46,
  145818. 48,
  145819. };
  145820. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  145821. _vq_quantthresh__44u8_p9_2,
  145822. _vq_quantmap__44u8_p9_2,
  145823. 49,
  145824. 49
  145825. };
  145826. static static_codebook _44u8_p9_2 = {
  145827. 1, 49,
  145828. _vq_lengthlist__44u8_p9_2,
  145829. 1, -526909440, 1611661312, 6, 0,
  145830. _vq_quantlist__44u8_p9_2,
  145831. NULL,
  145832. &_vq_auxt__44u8_p9_2,
  145833. NULL,
  145834. 0
  145835. };
  145836. static long _huff_lengthlist__44u9__long[] = {
  145837. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  145838. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  145839. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  145840. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  145841. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  145842. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  145843. 10, 8, 8, 9,
  145844. };
  145845. static static_codebook _huff_book__44u9__long = {
  145846. 2, 100,
  145847. _huff_lengthlist__44u9__long,
  145848. 0, 0, 0, 0, 0,
  145849. NULL,
  145850. NULL,
  145851. NULL,
  145852. NULL,
  145853. 0
  145854. };
  145855. static long _huff_lengthlist__44u9__short[] = {
  145856. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  145857. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  145858. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  145859. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  145860. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  145861. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  145862. 9, 9,12,15,
  145863. };
  145864. static static_codebook _huff_book__44u9__short = {
  145865. 2, 100,
  145866. _huff_lengthlist__44u9__short,
  145867. 0, 0, 0, 0, 0,
  145868. NULL,
  145869. NULL,
  145870. NULL,
  145871. NULL,
  145872. 0
  145873. };
  145874. static long _vq_quantlist__44u9_p1_0[] = {
  145875. 1,
  145876. 0,
  145877. 2,
  145878. };
  145879. static long _vq_lengthlist__44u9_p1_0[] = {
  145880. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  145881. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  145882. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  145883. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  145884. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  145885. 10,
  145886. };
  145887. static float _vq_quantthresh__44u9_p1_0[] = {
  145888. -0.5, 0.5,
  145889. };
  145890. static long _vq_quantmap__44u9_p1_0[] = {
  145891. 1, 0, 2,
  145892. };
  145893. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  145894. _vq_quantthresh__44u9_p1_0,
  145895. _vq_quantmap__44u9_p1_0,
  145896. 3,
  145897. 3
  145898. };
  145899. static static_codebook _44u9_p1_0 = {
  145900. 4, 81,
  145901. _vq_lengthlist__44u9_p1_0,
  145902. 1, -535822336, 1611661312, 2, 0,
  145903. _vq_quantlist__44u9_p1_0,
  145904. NULL,
  145905. &_vq_auxt__44u9_p1_0,
  145906. NULL,
  145907. 0
  145908. };
  145909. static long _vq_quantlist__44u9_p2_0[] = {
  145910. 2,
  145911. 1,
  145912. 3,
  145913. 0,
  145914. 4,
  145915. };
  145916. static long _vq_lengthlist__44u9_p2_0[] = {
  145917. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145918. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  145919. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  145920. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  145921. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  145922. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  145923. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  145924. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  145925. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  145926. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  145927. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  145928. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  145929. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  145930. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  145931. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  145932. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  145933. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  145934. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  145935. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  145936. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  145937. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  145938. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  145939. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  145940. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  145941. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  145942. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  145943. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  145944. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  145945. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  145946. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  145947. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  145948. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  145949. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  145950. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  145951. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  145952. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  145953. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  145954. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  145955. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  145956. 14,
  145957. };
  145958. static float _vq_quantthresh__44u9_p2_0[] = {
  145959. -1.5, -0.5, 0.5, 1.5,
  145960. };
  145961. static long _vq_quantmap__44u9_p2_0[] = {
  145962. 3, 1, 0, 2, 4,
  145963. };
  145964. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  145965. _vq_quantthresh__44u9_p2_0,
  145966. _vq_quantmap__44u9_p2_0,
  145967. 5,
  145968. 5
  145969. };
  145970. static static_codebook _44u9_p2_0 = {
  145971. 4, 625,
  145972. _vq_lengthlist__44u9_p2_0,
  145973. 1, -533725184, 1611661312, 3, 0,
  145974. _vq_quantlist__44u9_p2_0,
  145975. NULL,
  145976. &_vq_auxt__44u9_p2_0,
  145977. NULL,
  145978. 0
  145979. };
  145980. static long _vq_quantlist__44u9_p3_0[] = {
  145981. 4,
  145982. 3,
  145983. 5,
  145984. 2,
  145985. 6,
  145986. 1,
  145987. 7,
  145988. 0,
  145989. 8,
  145990. };
  145991. static long _vq_lengthlist__44u9_p3_0[] = {
  145992. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  145993. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  145994. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145995. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  145996. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  145997. 11,
  145998. };
  145999. static float _vq_quantthresh__44u9_p3_0[] = {
  146000. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146001. };
  146002. static long _vq_quantmap__44u9_p3_0[] = {
  146003. 7, 5, 3, 1, 0, 2, 4, 6,
  146004. 8,
  146005. };
  146006. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  146007. _vq_quantthresh__44u9_p3_0,
  146008. _vq_quantmap__44u9_p3_0,
  146009. 9,
  146010. 9
  146011. };
  146012. static static_codebook _44u9_p3_0 = {
  146013. 2, 81,
  146014. _vq_lengthlist__44u9_p3_0,
  146015. 1, -531628032, 1611661312, 4, 0,
  146016. _vq_quantlist__44u9_p3_0,
  146017. NULL,
  146018. &_vq_auxt__44u9_p3_0,
  146019. NULL,
  146020. 0
  146021. };
  146022. static long _vq_quantlist__44u9_p4_0[] = {
  146023. 8,
  146024. 7,
  146025. 9,
  146026. 6,
  146027. 10,
  146028. 5,
  146029. 11,
  146030. 4,
  146031. 12,
  146032. 3,
  146033. 13,
  146034. 2,
  146035. 14,
  146036. 1,
  146037. 15,
  146038. 0,
  146039. 16,
  146040. };
  146041. static long _vq_lengthlist__44u9_p4_0[] = {
  146042. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  146043. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  146044. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  146045. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  146046. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  146047. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  146048. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  146049. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  146050. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  146051. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  146052. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  146053. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  146054. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  146055. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  146056. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  146057. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  146058. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  146059. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  146060. 14,
  146061. };
  146062. static float _vq_quantthresh__44u9_p4_0[] = {
  146063. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146064. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146065. };
  146066. static long _vq_quantmap__44u9_p4_0[] = {
  146067. 15, 13, 11, 9, 7, 5, 3, 1,
  146068. 0, 2, 4, 6, 8, 10, 12, 14,
  146069. 16,
  146070. };
  146071. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  146072. _vq_quantthresh__44u9_p4_0,
  146073. _vq_quantmap__44u9_p4_0,
  146074. 17,
  146075. 17
  146076. };
  146077. static static_codebook _44u9_p4_0 = {
  146078. 2, 289,
  146079. _vq_lengthlist__44u9_p4_0,
  146080. 1, -529530880, 1611661312, 5, 0,
  146081. _vq_quantlist__44u9_p4_0,
  146082. NULL,
  146083. &_vq_auxt__44u9_p4_0,
  146084. NULL,
  146085. 0
  146086. };
  146087. static long _vq_quantlist__44u9_p5_0[] = {
  146088. 1,
  146089. 0,
  146090. 2,
  146091. };
  146092. static long _vq_lengthlist__44u9_p5_0[] = {
  146093. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  146094. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  146095. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  146096. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  146097. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  146098. 10,
  146099. };
  146100. static float _vq_quantthresh__44u9_p5_0[] = {
  146101. -5.5, 5.5,
  146102. };
  146103. static long _vq_quantmap__44u9_p5_0[] = {
  146104. 1, 0, 2,
  146105. };
  146106. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  146107. _vq_quantthresh__44u9_p5_0,
  146108. _vq_quantmap__44u9_p5_0,
  146109. 3,
  146110. 3
  146111. };
  146112. static static_codebook _44u9_p5_0 = {
  146113. 4, 81,
  146114. _vq_lengthlist__44u9_p5_0,
  146115. 1, -529137664, 1618345984, 2, 0,
  146116. _vq_quantlist__44u9_p5_0,
  146117. NULL,
  146118. &_vq_auxt__44u9_p5_0,
  146119. NULL,
  146120. 0
  146121. };
  146122. static long _vq_quantlist__44u9_p5_1[] = {
  146123. 5,
  146124. 4,
  146125. 6,
  146126. 3,
  146127. 7,
  146128. 2,
  146129. 8,
  146130. 1,
  146131. 9,
  146132. 0,
  146133. 10,
  146134. };
  146135. static long _vq_lengthlist__44u9_p5_1[] = {
  146136. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  146137. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  146138. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  146139. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  146140. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  146141. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  146142. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  146143. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146144. };
  146145. static float _vq_quantthresh__44u9_p5_1[] = {
  146146. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146147. 3.5, 4.5,
  146148. };
  146149. static long _vq_quantmap__44u9_p5_1[] = {
  146150. 9, 7, 5, 3, 1, 0, 2, 4,
  146151. 6, 8, 10,
  146152. };
  146153. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  146154. _vq_quantthresh__44u9_p5_1,
  146155. _vq_quantmap__44u9_p5_1,
  146156. 11,
  146157. 11
  146158. };
  146159. static static_codebook _44u9_p5_1 = {
  146160. 2, 121,
  146161. _vq_lengthlist__44u9_p5_1,
  146162. 1, -531365888, 1611661312, 4, 0,
  146163. _vq_quantlist__44u9_p5_1,
  146164. NULL,
  146165. &_vq_auxt__44u9_p5_1,
  146166. NULL,
  146167. 0
  146168. };
  146169. static long _vq_quantlist__44u9_p6_0[] = {
  146170. 6,
  146171. 5,
  146172. 7,
  146173. 4,
  146174. 8,
  146175. 3,
  146176. 9,
  146177. 2,
  146178. 10,
  146179. 1,
  146180. 11,
  146181. 0,
  146182. 12,
  146183. };
  146184. static long _vq_lengthlist__44u9_p6_0[] = {
  146185. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  146186. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  146187. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  146188. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  146189. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  146190. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  146191. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  146192. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  146193. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  146194. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  146195. 10,11,11,11,11,12,11,12,12,
  146196. };
  146197. static float _vq_quantthresh__44u9_p6_0[] = {
  146198. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146199. 12.5, 17.5, 22.5, 27.5,
  146200. };
  146201. static long _vq_quantmap__44u9_p6_0[] = {
  146202. 11, 9, 7, 5, 3, 1, 0, 2,
  146203. 4, 6, 8, 10, 12,
  146204. };
  146205. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  146206. _vq_quantthresh__44u9_p6_0,
  146207. _vq_quantmap__44u9_p6_0,
  146208. 13,
  146209. 13
  146210. };
  146211. static static_codebook _44u9_p6_0 = {
  146212. 2, 169,
  146213. _vq_lengthlist__44u9_p6_0,
  146214. 1, -526516224, 1616117760, 4, 0,
  146215. _vq_quantlist__44u9_p6_0,
  146216. NULL,
  146217. &_vq_auxt__44u9_p6_0,
  146218. NULL,
  146219. 0
  146220. };
  146221. static long _vq_quantlist__44u9_p6_1[] = {
  146222. 2,
  146223. 1,
  146224. 3,
  146225. 0,
  146226. 4,
  146227. };
  146228. static long _vq_lengthlist__44u9_p6_1[] = {
  146229. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  146230. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  146231. };
  146232. static float _vq_quantthresh__44u9_p6_1[] = {
  146233. -1.5, -0.5, 0.5, 1.5,
  146234. };
  146235. static long _vq_quantmap__44u9_p6_1[] = {
  146236. 3, 1, 0, 2, 4,
  146237. };
  146238. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  146239. _vq_quantthresh__44u9_p6_1,
  146240. _vq_quantmap__44u9_p6_1,
  146241. 5,
  146242. 5
  146243. };
  146244. static static_codebook _44u9_p6_1 = {
  146245. 2, 25,
  146246. _vq_lengthlist__44u9_p6_1,
  146247. 1, -533725184, 1611661312, 3, 0,
  146248. _vq_quantlist__44u9_p6_1,
  146249. NULL,
  146250. &_vq_auxt__44u9_p6_1,
  146251. NULL,
  146252. 0
  146253. };
  146254. static long _vq_quantlist__44u9_p7_0[] = {
  146255. 6,
  146256. 5,
  146257. 7,
  146258. 4,
  146259. 8,
  146260. 3,
  146261. 9,
  146262. 2,
  146263. 10,
  146264. 1,
  146265. 11,
  146266. 0,
  146267. 12,
  146268. };
  146269. static long _vq_lengthlist__44u9_p7_0[] = {
  146270. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  146271. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  146272. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  146273. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  146274. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  146275. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  146276. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  146277. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  146278. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  146279. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  146280. 12,13,13,14,14,14,15,15,15,
  146281. };
  146282. static float _vq_quantthresh__44u9_p7_0[] = {
  146283. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  146284. 27.5, 38.5, 49.5, 60.5,
  146285. };
  146286. static long _vq_quantmap__44u9_p7_0[] = {
  146287. 11, 9, 7, 5, 3, 1, 0, 2,
  146288. 4, 6, 8, 10, 12,
  146289. };
  146290. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  146291. _vq_quantthresh__44u9_p7_0,
  146292. _vq_quantmap__44u9_p7_0,
  146293. 13,
  146294. 13
  146295. };
  146296. static static_codebook _44u9_p7_0 = {
  146297. 2, 169,
  146298. _vq_lengthlist__44u9_p7_0,
  146299. 1, -523206656, 1618345984, 4, 0,
  146300. _vq_quantlist__44u9_p7_0,
  146301. NULL,
  146302. &_vq_auxt__44u9_p7_0,
  146303. NULL,
  146304. 0
  146305. };
  146306. static long _vq_quantlist__44u9_p7_1[] = {
  146307. 5,
  146308. 4,
  146309. 6,
  146310. 3,
  146311. 7,
  146312. 2,
  146313. 8,
  146314. 1,
  146315. 9,
  146316. 0,
  146317. 10,
  146318. };
  146319. static long _vq_lengthlist__44u9_p7_1[] = {
  146320. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  146321. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  146322. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  146323. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146324. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146325. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146326. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  146327. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  146328. };
  146329. static float _vq_quantthresh__44u9_p7_1[] = {
  146330. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146331. 3.5, 4.5,
  146332. };
  146333. static long _vq_quantmap__44u9_p7_1[] = {
  146334. 9, 7, 5, 3, 1, 0, 2, 4,
  146335. 6, 8, 10,
  146336. };
  146337. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  146338. _vq_quantthresh__44u9_p7_1,
  146339. _vq_quantmap__44u9_p7_1,
  146340. 11,
  146341. 11
  146342. };
  146343. static static_codebook _44u9_p7_1 = {
  146344. 2, 121,
  146345. _vq_lengthlist__44u9_p7_1,
  146346. 1, -531365888, 1611661312, 4, 0,
  146347. _vq_quantlist__44u9_p7_1,
  146348. NULL,
  146349. &_vq_auxt__44u9_p7_1,
  146350. NULL,
  146351. 0
  146352. };
  146353. static long _vq_quantlist__44u9_p8_0[] = {
  146354. 7,
  146355. 6,
  146356. 8,
  146357. 5,
  146358. 9,
  146359. 4,
  146360. 10,
  146361. 3,
  146362. 11,
  146363. 2,
  146364. 12,
  146365. 1,
  146366. 13,
  146367. 0,
  146368. 14,
  146369. };
  146370. static long _vq_lengthlist__44u9_p8_0[] = {
  146371. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  146372. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  146373. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  146374. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  146375. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  146376. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  146377. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  146378. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  146379. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  146380. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  146381. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  146382. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  146383. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  146384. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  146385. 15,
  146386. };
  146387. static float _vq_quantthresh__44u9_p8_0[] = {
  146388. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  146389. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  146390. };
  146391. static long _vq_quantmap__44u9_p8_0[] = {
  146392. 13, 11, 9, 7, 5, 3, 1, 0,
  146393. 2, 4, 6, 8, 10, 12, 14,
  146394. };
  146395. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  146396. _vq_quantthresh__44u9_p8_0,
  146397. _vq_quantmap__44u9_p8_0,
  146398. 15,
  146399. 15
  146400. };
  146401. static static_codebook _44u9_p8_0 = {
  146402. 2, 225,
  146403. _vq_lengthlist__44u9_p8_0,
  146404. 1, -520986624, 1620377600, 4, 0,
  146405. _vq_quantlist__44u9_p8_0,
  146406. NULL,
  146407. &_vq_auxt__44u9_p8_0,
  146408. NULL,
  146409. 0
  146410. };
  146411. static long _vq_quantlist__44u9_p8_1[] = {
  146412. 10,
  146413. 9,
  146414. 11,
  146415. 8,
  146416. 12,
  146417. 7,
  146418. 13,
  146419. 6,
  146420. 14,
  146421. 5,
  146422. 15,
  146423. 4,
  146424. 16,
  146425. 3,
  146426. 17,
  146427. 2,
  146428. 18,
  146429. 1,
  146430. 19,
  146431. 0,
  146432. 20,
  146433. };
  146434. static long _vq_lengthlist__44u9_p8_1[] = {
  146435. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146436. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  146437. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  146438. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  146439. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146440. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  146441. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  146442. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  146443. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146444. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146445. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  146446. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  146447. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  146448. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  146449. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146450. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146451. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  146452. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  146453. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  146454. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  146455. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146456. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  146457. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  146458. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  146459. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146460. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  146461. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  146462. 10,10,10,10,10,10,10,10,10,
  146463. };
  146464. static float _vq_quantthresh__44u9_p8_1[] = {
  146465. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  146466. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  146467. 6.5, 7.5, 8.5, 9.5,
  146468. };
  146469. static long _vq_quantmap__44u9_p8_1[] = {
  146470. 19, 17, 15, 13, 11, 9, 7, 5,
  146471. 3, 1, 0, 2, 4, 6, 8, 10,
  146472. 12, 14, 16, 18, 20,
  146473. };
  146474. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  146475. _vq_quantthresh__44u9_p8_1,
  146476. _vq_quantmap__44u9_p8_1,
  146477. 21,
  146478. 21
  146479. };
  146480. static static_codebook _44u9_p8_1 = {
  146481. 2, 441,
  146482. _vq_lengthlist__44u9_p8_1,
  146483. 1, -529268736, 1611661312, 5, 0,
  146484. _vq_quantlist__44u9_p8_1,
  146485. NULL,
  146486. &_vq_auxt__44u9_p8_1,
  146487. NULL,
  146488. 0
  146489. };
  146490. static long _vq_quantlist__44u9_p9_0[] = {
  146491. 7,
  146492. 6,
  146493. 8,
  146494. 5,
  146495. 9,
  146496. 4,
  146497. 10,
  146498. 3,
  146499. 11,
  146500. 2,
  146501. 12,
  146502. 1,
  146503. 13,
  146504. 0,
  146505. 14,
  146506. };
  146507. static long _vq_lengthlist__44u9_p9_0[] = {
  146508. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  146509. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  146510. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146511. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146512. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146513. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146514. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146515. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146516. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146517. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146518. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146519. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146520. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146521. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146522. 10,
  146523. };
  146524. static float _vq_quantthresh__44u9_p9_0[] = {
  146525. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  146526. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  146527. };
  146528. static long _vq_quantmap__44u9_p9_0[] = {
  146529. 13, 11, 9, 7, 5, 3, 1, 0,
  146530. 2, 4, 6, 8, 10, 12, 14,
  146531. };
  146532. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  146533. _vq_quantthresh__44u9_p9_0,
  146534. _vq_quantmap__44u9_p9_0,
  146535. 15,
  146536. 15
  146537. };
  146538. static static_codebook _44u9_p9_0 = {
  146539. 2, 225,
  146540. _vq_lengthlist__44u9_p9_0,
  146541. 1, -510036736, 1631393792, 4, 0,
  146542. _vq_quantlist__44u9_p9_0,
  146543. NULL,
  146544. &_vq_auxt__44u9_p9_0,
  146545. NULL,
  146546. 0
  146547. };
  146548. static long _vq_quantlist__44u9_p9_1[] = {
  146549. 9,
  146550. 8,
  146551. 10,
  146552. 7,
  146553. 11,
  146554. 6,
  146555. 12,
  146556. 5,
  146557. 13,
  146558. 4,
  146559. 14,
  146560. 3,
  146561. 15,
  146562. 2,
  146563. 16,
  146564. 1,
  146565. 17,
  146566. 0,
  146567. 18,
  146568. };
  146569. static long _vq_lengthlist__44u9_p9_1[] = {
  146570. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  146571. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  146572. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  146573. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  146574. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  146575. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  146576. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  146577. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  146578. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  146579. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  146580. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  146581. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  146582. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  146583. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  146584. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  146585. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  146586. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  146587. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  146588. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  146589. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  146590. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  146591. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  146592. 17,17,15,17,15,17,16,16,17,
  146593. };
  146594. static float _vq_quantthresh__44u9_p9_1[] = {
  146595. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  146596. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  146597. 367.5, 416.5,
  146598. };
  146599. static long _vq_quantmap__44u9_p9_1[] = {
  146600. 17, 15, 13, 11, 9, 7, 5, 3,
  146601. 1, 0, 2, 4, 6, 8, 10, 12,
  146602. 14, 16, 18,
  146603. };
  146604. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  146605. _vq_quantthresh__44u9_p9_1,
  146606. _vq_quantmap__44u9_p9_1,
  146607. 19,
  146608. 19
  146609. };
  146610. static static_codebook _44u9_p9_1 = {
  146611. 2, 361,
  146612. _vq_lengthlist__44u9_p9_1,
  146613. 1, -518287360, 1622704128, 5, 0,
  146614. _vq_quantlist__44u9_p9_1,
  146615. NULL,
  146616. &_vq_auxt__44u9_p9_1,
  146617. NULL,
  146618. 0
  146619. };
  146620. static long _vq_quantlist__44u9_p9_2[] = {
  146621. 24,
  146622. 23,
  146623. 25,
  146624. 22,
  146625. 26,
  146626. 21,
  146627. 27,
  146628. 20,
  146629. 28,
  146630. 19,
  146631. 29,
  146632. 18,
  146633. 30,
  146634. 17,
  146635. 31,
  146636. 16,
  146637. 32,
  146638. 15,
  146639. 33,
  146640. 14,
  146641. 34,
  146642. 13,
  146643. 35,
  146644. 12,
  146645. 36,
  146646. 11,
  146647. 37,
  146648. 10,
  146649. 38,
  146650. 9,
  146651. 39,
  146652. 8,
  146653. 40,
  146654. 7,
  146655. 41,
  146656. 6,
  146657. 42,
  146658. 5,
  146659. 43,
  146660. 4,
  146661. 44,
  146662. 3,
  146663. 45,
  146664. 2,
  146665. 46,
  146666. 1,
  146667. 47,
  146668. 0,
  146669. 48,
  146670. };
  146671. static long _vq_lengthlist__44u9_p9_2[] = {
  146672. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  146673. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146674. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146675. 7,
  146676. };
  146677. static float _vq_quantthresh__44u9_p9_2[] = {
  146678. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  146679. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  146680. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146681. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146682. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  146683. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  146684. };
  146685. static long _vq_quantmap__44u9_p9_2[] = {
  146686. 47, 45, 43, 41, 39, 37, 35, 33,
  146687. 31, 29, 27, 25, 23, 21, 19, 17,
  146688. 15, 13, 11, 9, 7, 5, 3, 1,
  146689. 0, 2, 4, 6, 8, 10, 12, 14,
  146690. 16, 18, 20, 22, 24, 26, 28, 30,
  146691. 32, 34, 36, 38, 40, 42, 44, 46,
  146692. 48,
  146693. };
  146694. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  146695. _vq_quantthresh__44u9_p9_2,
  146696. _vq_quantmap__44u9_p9_2,
  146697. 49,
  146698. 49
  146699. };
  146700. static static_codebook _44u9_p9_2 = {
  146701. 1, 49,
  146702. _vq_lengthlist__44u9_p9_2,
  146703. 1, -526909440, 1611661312, 6, 0,
  146704. _vq_quantlist__44u9_p9_2,
  146705. NULL,
  146706. &_vq_auxt__44u9_p9_2,
  146707. NULL,
  146708. 0
  146709. };
  146710. static long _huff_lengthlist__44un1__long[] = {
  146711. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  146712. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  146713. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  146714. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  146715. };
  146716. static static_codebook _huff_book__44un1__long = {
  146717. 2, 64,
  146718. _huff_lengthlist__44un1__long,
  146719. 0, 0, 0, 0, 0,
  146720. NULL,
  146721. NULL,
  146722. NULL,
  146723. NULL,
  146724. 0
  146725. };
  146726. static long _vq_quantlist__44un1__p1_0[] = {
  146727. 1,
  146728. 0,
  146729. 2,
  146730. };
  146731. static long _vq_lengthlist__44un1__p1_0[] = {
  146732. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  146733. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  146734. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  146735. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  146736. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  146737. 12,
  146738. };
  146739. static float _vq_quantthresh__44un1__p1_0[] = {
  146740. -0.5, 0.5,
  146741. };
  146742. static long _vq_quantmap__44un1__p1_0[] = {
  146743. 1, 0, 2,
  146744. };
  146745. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  146746. _vq_quantthresh__44un1__p1_0,
  146747. _vq_quantmap__44un1__p1_0,
  146748. 3,
  146749. 3
  146750. };
  146751. static static_codebook _44un1__p1_0 = {
  146752. 4, 81,
  146753. _vq_lengthlist__44un1__p1_0,
  146754. 1, -535822336, 1611661312, 2, 0,
  146755. _vq_quantlist__44un1__p1_0,
  146756. NULL,
  146757. &_vq_auxt__44un1__p1_0,
  146758. NULL,
  146759. 0
  146760. };
  146761. static long _vq_quantlist__44un1__p2_0[] = {
  146762. 1,
  146763. 0,
  146764. 2,
  146765. };
  146766. static long _vq_lengthlist__44un1__p2_0[] = {
  146767. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146768. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  146769. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  146770. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  146771. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  146772. 8,
  146773. };
  146774. static float _vq_quantthresh__44un1__p2_0[] = {
  146775. -0.5, 0.5,
  146776. };
  146777. static long _vq_quantmap__44un1__p2_0[] = {
  146778. 1, 0, 2,
  146779. };
  146780. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  146781. _vq_quantthresh__44un1__p2_0,
  146782. _vq_quantmap__44un1__p2_0,
  146783. 3,
  146784. 3
  146785. };
  146786. static static_codebook _44un1__p2_0 = {
  146787. 4, 81,
  146788. _vq_lengthlist__44un1__p2_0,
  146789. 1, -535822336, 1611661312, 2, 0,
  146790. _vq_quantlist__44un1__p2_0,
  146791. NULL,
  146792. &_vq_auxt__44un1__p2_0,
  146793. NULL,
  146794. 0
  146795. };
  146796. static long _vq_quantlist__44un1__p3_0[] = {
  146797. 2,
  146798. 1,
  146799. 3,
  146800. 0,
  146801. 4,
  146802. };
  146803. static long _vq_lengthlist__44un1__p3_0[] = {
  146804. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146805. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  146806. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  146807. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  146808. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  146809. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  146810. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  146811. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  146812. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  146813. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  146814. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  146815. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  146816. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  146817. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  146818. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  146819. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  146820. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  146821. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  146822. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  146823. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  146824. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  146825. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  146826. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  146827. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  146828. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  146829. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  146830. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  146831. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  146832. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  146833. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  146834. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  146835. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  146836. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  146837. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  146838. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  146839. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  146840. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  146841. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  146842. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  146843. 17,
  146844. };
  146845. static float _vq_quantthresh__44un1__p3_0[] = {
  146846. -1.5, -0.5, 0.5, 1.5,
  146847. };
  146848. static long _vq_quantmap__44un1__p3_0[] = {
  146849. 3, 1, 0, 2, 4,
  146850. };
  146851. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  146852. _vq_quantthresh__44un1__p3_0,
  146853. _vq_quantmap__44un1__p3_0,
  146854. 5,
  146855. 5
  146856. };
  146857. static static_codebook _44un1__p3_0 = {
  146858. 4, 625,
  146859. _vq_lengthlist__44un1__p3_0,
  146860. 1, -533725184, 1611661312, 3, 0,
  146861. _vq_quantlist__44un1__p3_0,
  146862. NULL,
  146863. &_vq_auxt__44un1__p3_0,
  146864. NULL,
  146865. 0
  146866. };
  146867. static long _vq_quantlist__44un1__p4_0[] = {
  146868. 2,
  146869. 1,
  146870. 3,
  146871. 0,
  146872. 4,
  146873. };
  146874. static long _vq_lengthlist__44un1__p4_0[] = {
  146875. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  146876. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  146877. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  146878. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  146879. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  146880. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  146881. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  146882. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  146883. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  146884. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  146885. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  146886. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  146887. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  146888. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  146889. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  146890. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  146891. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  146892. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  146893. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  146894. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  146895. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  146896. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  146897. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  146898. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  146899. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  146900. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  146901. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  146902. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  146903. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  146904. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  146905. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  146906. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  146907. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  146908. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  146909. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  146910. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  146911. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  146912. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  146913. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  146914. 12,
  146915. };
  146916. static float _vq_quantthresh__44un1__p4_0[] = {
  146917. -1.5, -0.5, 0.5, 1.5,
  146918. };
  146919. static long _vq_quantmap__44un1__p4_0[] = {
  146920. 3, 1, 0, 2, 4,
  146921. };
  146922. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  146923. _vq_quantthresh__44un1__p4_0,
  146924. _vq_quantmap__44un1__p4_0,
  146925. 5,
  146926. 5
  146927. };
  146928. static static_codebook _44un1__p4_0 = {
  146929. 4, 625,
  146930. _vq_lengthlist__44un1__p4_0,
  146931. 1, -533725184, 1611661312, 3, 0,
  146932. _vq_quantlist__44un1__p4_0,
  146933. NULL,
  146934. &_vq_auxt__44un1__p4_0,
  146935. NULL,
  146936. 0
  146937. };
  146938. static long _vq_quantlist__44un1__p5_0[] = {
  146939. 4,
  146940. 3,
  146941. 5,
  146942. 2,
  146943. 6,
  146944. 1,
  146945. 7,
  146946. 0,
  146947. 8,
  146948. };
  146949. static long _vq_lengthlist__44un1__p5_0[] = {
  146950. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  146951. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  146952. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  146953. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  146954. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  146955. 12,
  146956. };
  146957. static float _vq_quantthresh__44un1__p5_0[] = {
  146958. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146959. };
  146960. static long _vq_quantmap__44un1__p5_0[] = {
  146961. 7, 5, 3, 1, 0, 2, 4, 6,
  146962. 8,
  146963. };
  146964. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  146965. _vq_quantthresh__44un1__p5_0,
  146966. _vq_quantmap__44un1__p5_0,
  146967. 9,
  146968. 9
  146969. };
  146970. static static_codebook _44un1__p5_0 = {
  146971. 2, 81,
  146972. _vq_lengthlist__44un1__p5_0,
  146973. 1, -531628032, 1611661312, 4, 0,
  146974. _vq_quantlist__44un1__p5_0,
  146975. NULL,
  146976. &_vq_auxt__44un1__p5_0,
  146977. NULL,
  146978. 0
  146979. };
  146980. static long _vq_quantlist__44un1__p6_0[] = {
  146981. 6,
  146982. 5,
  146983. 7,
  146984. 4,
  146985. 8,
  146986. 3,
  146987. 9,
  146988. 2,
  146989. 10,
  146990. 1,
  146991. 11,
  146992. 0,
  146993. 12,
  146994. };
  146995. static long _vq_lengthlist__44un1__p6_0[] = {
  146996. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  146997. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  146998. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  146999. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  147000. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  147001. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  147002. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  147003. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  147004. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  147005. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  147006. 16, 0,15,18,18, 0,16, 0, 0,
  147007. };
  147008. static float _vq_quantthresh__44un1__p6_0[] = {
  147009. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147010. 12.5, 17.5, 22.5, 27.5,
  147011. };
  147012. static long _vq_quantmap__44un1__p6_0[] = {
  147013. 11, 9, 7, 5, 3, 1, 0, 2,
  147014. 4, 6, 8, 10, 12,
  147015. };
  147016. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  147017. _vq_quantthresh__44un1__p6_0,
  147018. _vq_quantmap__44un1__p6_0,
  147019. 13,
  147020. 13
  147021. };
  147022. static static_codebook _44un1__p6_0 = {
  147023. 2, 169,
  147024. _vq_lengthlist__44un1__p6_0,
  147025. 1, -526516224, 1616117760, 4, 0,
  147026. _vq_quantlist__44un1__p6_0,
  147027. NULL,
  147028. &_vq_auxt__44un1__p6_0,
  147029. NULL,
  147030. 0
  147031. };
  147032. static long _vq_quantlist__44un1__p6_1[] = {
  147033. 2,
  147034. 1,
  147035. 3,
  147036. 0,
  147037. 4,
  147038. };
  147039. static long _vq_lengthlist__44un1__p6_1[] = {
  147040. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  147041. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  147042. };
  147043. static float _vq_quantthresh__44un1__p6_1[] = {
  147044. -1.5, -0.5, 0.5, 1.5,
  147045. };
  147046. static long _vq_quantmap__44un1__p6_1[] = {
  147047. 3, 1, 0, 2, 4,
  147048. };
  147049. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  147050. _vq_quantthresh__44un1__p6_1,
  147051. _vq_quantmap__44un1__p6_1,
  147052. 5,
  147053. 5
  147054. };
  147055. static static_codebook _44un1__p6_1 = {
  147056. 2, 25,
  147057. _vq_lengthlist__44un1__p6_1,
  147058. 1, -533725184, 1611661312, 3, 0,
  147059. _vq_quantlist__44un1__p6_1,
  147060. NULL,
  147061. &_vq_auxt__44un1__p6_1,
  147062. NULL,
  147063. 0
  147064. };
  147065. static long _vq_quantlist__44un1__p7_0[] = {
  147066. 2,
  147067. 1,
  147068. 3,
  147069. 0,
  147070. 4,
  147071. };
  147072. static long _vq_lengthlist__44un1__p7_0[] = {
  147073. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  147074. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  147075. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147076. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147077. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147078. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147079. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147080. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  147081. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147082. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147083. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  147084. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147085. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147086. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147087. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147088. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  147089. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147090. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  147091. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147092. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147093. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147094. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147095. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147096. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147097. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147098. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147099. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147100. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147101. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147102. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147103. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147104. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147105. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147106. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147107. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147108. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147109. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147110. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147111. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147112. 10,
  147113. };
  147114. static float _vq_quantthresh__44un1__p7_0[] = {
  147115. -253.5, -84.5, 84.5, 253.5,
  147116. };
  147117. static long _vq_quantmap__44un1__p7_0[] = {
  147118. 3, 1, 0, 2, 4,
  147119. };
  147120. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  147121. _vq_quantthresh__44un1__p7_0,
  147122. _vq_quantmap__44un1__p7_0,
  147123. 5,
  147124. 5
  147125. };
  147126. static static_codebook _44un1__p7_0 = {
  147127. 4, 625,
  147128. _vq_lengthlist__44un1__p7_0,
  147129. 1, -518709248, 1626677248, 3, 0,
  147130. _vq_quantlist__44un1__p7_0,
  147131. NULL,
  147132. &_vq_auxt__44un1__p7_0,
  147133. NULL,
  147134. 0
  147135. };
  147136. static long _vq_quantlist__44un1__p7_1[] = {
  147137. 6,
  147138. 5,
  147139. 7,
  147140. 4,
  147141. 8,
  147142. 3,
  147143. 9,
  147144. 2,
  147145. 10,
  147146. 1,
  147147. 11,
  147148. 0,
  147149. 12,
  147150. };
  147151. static long _vq_lengthlist__44un1__p7_1[] = {
  147152. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  147153. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  147154. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  147155. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  147156. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  147157. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  147158. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  147159. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  147160. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  147161. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  147162. 12,13,13,12,13,13,14,14,14,
  147163. };
  147164. static float _vq_quantthresh__44un1__p7_1[] = {
  147165. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147166. 32.5, 45.5, 58.5, 71.5,
  147167. };
  147168. static long _vq_quantmap__44un1__p7_1[] = {
  147169. 11, 9, 7, 5, 3, 1, 0, 2,
  147170. 4, 6, 8, 10, 12,
  147171. };
  147172. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  147173. _vq_quantthresh__44un1__p7_1,
  147174. _vq_quantmap__44un1__p7_1,
  147175. 13,
  147176. 13
  147177. };
  147178. static static_codebook _44un1__p7_1 = {
  147179. 2, 169,
  147180. _vq_lengthlist__44un1__p7_1,
  147181. 1, -523010048, 1618608128, 4, 0,
  147182. _vq_quantlist__44un1__p7_1,
  147183. NULL,
  147184. &_vq_auxt__44un1__p7_1,
  147185. NULL,
  147186. 0
  147187. };
  147188. static long _vq_quantlist__44un1__p7_2[] = {
  147189. 6,
  147190. 5,
  147191. 7,
  147192. 4,
  147193. 8,
  147194. 3,
  147195. 9,
  147196. 2,
  147197. 10,
  147198. 1,
  147199. 11,
  147200. 0,
  147201. 12,
  147202. };
  147203. static long _vq_lengthlist__44un1__p7_2[] = {
  147204. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  147205. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  147206. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  147207. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  147208. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  147209. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  147210. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  147211. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  147212. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  147213. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  147214. 9, 9, 9,10,10,10,10,10,10,
  147215. };
  147216. static float _vq_quantthresh__44un1__p7_2[] = {
  147217. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147218. 2.5, 3.5, 4.5, 5.5,
  147219. };
  147220. static long _vq_quantmap__44un1__p7_2[] = {
  147221. 11, 9, 7, 5, 3, 1, 0, 2,
  147222. 4, 6, 8, 10, 12,
  147223. };
  147224. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  147225. _vq_quantthresh__44un1__p7_2,
  147226. _vq_quantmap__44un1__p7_2,
  147227. 13,
  147228. 13
  147229. };
  147230. static static_codebook _44un1__p7_2 = {
  147231. 2, 169,
  147232. _vq_lengthlist__44un1__p7_2,
  147233. 1, -531103744, 1611661312, 4, 0,
  147234. _vq_quantlist__44un1__p7_2,
  147235. NULL,
  147236. &_vq_auxt__44un1__p7_2,
  147237. NULL,
  147238. 0
  147239. };
  147240. static long _huff_lengthlist__44un1__short[] = {
  147241. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  147242. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  147243. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  147244. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  147245. };
  147246. static static_codebook _huff_book__44un1__short = {
  147247. 2, 64,
  147248. _huff_lengthlist__44un1__short,
  147249. 0, 0, 0, 0, 0,
  147250. NULL,
  147251. NULL,
  147252. NULL,
  147253. NULL,
  147254. 0
  147255. };
  147256. /********* End of inlined file: res_books_uncoupled.h *********/
  147257. /***** residue backends *********************************************/
  147258. static vorbis_info_residue0 _residue_44_low_un={
  147259. 0,-1, -1, 8,-1,
  147260. {0},
  147261. {-1},
  147262. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  147263. { -1, 25, -1, 45, -1, -1, -1}
  147264. };
  147265. static vorbis_info_residue0 _residue_44_mid_un={
  147266. 0,-1, -1, 10,-1,
  147267. /* 0 1 2 3 4 5 6 7 8 9 */
  147268. {0},
  147269. {-1},
  147270. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  147271. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  147272. };
  147273. static vorbis_info_residue0 _residue_44_hi_un={
  147274. 0,-1, -1, 10,-1,
  147275. /* 0 1 2 3 4 5 6 7 8 9 */
  147276. {0},
  147277. {-1},
  147278. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  147279. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  147280. };
  147281. /* mapping conventions:
  147282. only one submap (this would change for efficient 5.1 support for example)*/
  147283. /* Four psychoacoustic profiles are used, one for each blocktype */
  147284. static vorbis_info_mapping0 _map_nominal_u[2]={
  147285. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  147286. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  147287. };
  147288. static static_bookblock _resbook_44u_n1={
  147289. {
  147290. {0},
  147291. {0,0,&_44un1__p1_0},
  147292. {0,0,&_44un1__p2_0},
  147293. {0,0,&_44un1__p3_0},
  147294. {0,0,&_44un1__p4_0},
  147295. {0,0,&_44un1__p5_0},
  147296. {&_44un1__p6_0,&_44un1__p6_1},
  147297. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  147298. }
  147299. };
  147300. static static_bookblock _resbook_44u_0={
  147301. {
  147302. {0},
  147303. {0,0,&_44u0__p1_0},
  147304. {0,0,&_44u0__p2_0},
  147305. {0,0,&_44u0__p3_0},
  147306. {0,0,&_44u0__p4_0},
  147307. {0,0,&_44u0__p5_0},
  147308. {&_44u0__p6_0,&_44u0__p6_1},
  147309. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  147310. }
  147311. };
  147312. static static_bookblock _resbook_44u_1={
  147313. {
  147314. {0},
  147315. {0,0,&_44u1__p1_0},
  147316. {0,0,&_44u1__p2_0},
  147317. {0,0,&_44u1__p3_0},
  147318. {0,0,&_44u1__p4_0},
  147319. {0,0,&_44u1__p5_0},
  147320. {&_44u1__p6_0,&_44u1__p6_1},
  147321. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  147322. }
  147323. };
  147324. static static_bookblock _resbook_44u_2={
  147325. {
  147326. {0},
  147327. {0,0,&_44u2__p1_0},
  147328. {0,0,&_44u2__p2_0},
  147329. {0,0,&_44u2__p3_0},
  147330. {0,0,&_44u2__p4_0},
  147331. {0,0,&_44u2__p5_0},
  147332. {&_44u2__p6_0,&_44u2__p6_1},
  147333. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  147334. }
  147335. };
  147336. static static_bookblock _resbook_44u_3={
  147337. {
  147338. {0},
  147339. {0,0,&_44u3__p1_0},
  147340. {0,0,&_44u3__p2_0},
  147341. {0,0,&_44u3__p3_0},
  147342. {0,0,&_44u3__p4_0},
  147343. {0,0,&_44u3__p5_0},
  147344. {&_44u3__p6_0,&_44u3__p6_1},
  147345. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  147346. }
  147347. };
  147348. static static_bookblock _resbook_44u_4={
  147349. {
  147350. {0},
  147351. {0,0,&_44u4__p1_0},
  147352. {0,0,&_44u4__p2_0},
  147353. {0,0,&_44u4__p3_0},
  147354. {0,0,&_44u4__p4_0},
  147355. {0,0,&_44u4__p5_0},
  147356. {&_44u4__p6_0,&_44u4__p6_1},
  147357. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  147358. }
  147359. };
  147360. static static_bookblock _resbook_44u_5={
  147361. {
  147362. {0},
  147363. {0,0,&_44u5__p1_0},
  147364. {0,0,&_44u5__p2_0},
  147365. {0,0,&_44u5__p3_0},
  147366. {0,0,&_44u5__p4_0},
  147367. {0,0,&_44u5__p5_0},
  147368. {0,0,&_44u5__p6_0},
  147369. {&_44u5__p7_0,&_44u5__p7_1},
  147370. {&_44u5__p8_0,&_44u5__p8_1},
  147371. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  147372. }
  147373. };
  147374. static static_bookblock _resbook_44u_6={
  147375. {
  147376. {0},
  147377. {0,0,&_44u6__p1_0},
  147378. {0,0,&_44u6__p2_0},
  147379. {0,0,&_44u6__p3_0},
  147380. {0,0,&_44u6__p4_0},
  147381. {0,0,&_44u6__p5_0},
  147382. {0,0,&_44u6__p6_0},
  147383. {&_44u6__p7_0,&_44u6__p7_1},
  147384. {&_44u6__p8_0,&_44u6__p8_1},
  147385. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  147386. }
  147387. };
  147388. static static_bookblock _resbook_44u_7={
  147389. {
  147390. {0},
  147391. {0,0,&_44u7__p1_0},
  147392. {0,0,&_44u7__p2_0},
  147393. {0,0,&_44u7__p3_0},
  147394. {0,0,&_44u7__p4_0},
  147395. {0,0,&_44u7__p5_0},
  147396. {0,0,&_44u7__p6_0},
  147397. {&_44u7__p7_0,&_44u7__p7_1},
  147398. {&_44u7__p8_0,&_44u7__p8_1},
  147399. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  147400. }
  147401. };
  147402. static static_bookblock _resbook_44u_8={
  147403. {
  147404. {0},
  147405. {0,0,&_44u8_p1_0},
  147406. {0,0,&_44u8_p2_0},
  147407. {0,0,&_44u8_p3_0},
  147408. {0,0,&_44u8_p4_0},
  147409. {&_44u8_p5_0,&_44u8_p5_1},
  147410. {&_44u8_p6_0,&_44u8_p6_1},
  147411. {&_44u8_p7_0,&_44u8_p7_1},
  147412. {&_44u8_p8_0,&_44u8_p8_1},
  147413. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  147414. }
  147415. };
  147416. static static_bookblock _resbook_44u_9={
  147417. {
  147418. {0},
  147419. {0,0,&_44u9_p1_0},
  147420. {0,0,&_44u9_p2_0},
  147421. {0,0,&_44u9_p3_0},
  147422. {0,0,&_44u9_p4_0},
  147423. {&_44u9_p5_0,&_44u9_p5_1},
  147424. {&_44u9_p6_0,&_44u9_p6_1},
  147425. {&_44u9_p7_0,&_44u9_p7_1},
  147426. {&_44u9_p8_0,&_44u9_p8_1},
  147427. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  147428. }
  147429. };
  147430. static vorbis_residue_template _res_44u_n1[]={
  147431. {1,0, &_residue_44_low_un,
  147432. &_huff_book__44un1__short,&_huff_book__44un1__short,
  147433. &_resbook_44u_n1,&_resbook_44u_n1},
  147434. {1,0, &_residue_44_low_un,
  147435. &_huff_book__44un1__long,&_huff_book__44un1__long,
  147436. &_resbook_44u_n1,&_resbook_44u_n1}
  147437. };
  147438. static vorbis_residue_template _res_44u_0[]={
  147439. {1,0, &_residue_44_low_un,
  147440. &_huff_book__44u0__short,&_huff_book__44u0__short,
  147441. &_resbook_44u_0,&_resbook_44u_0},
  147442. {1,0, &_residue_44_low_un,
  147443. &_huff_book__44u0__long,&_huff_book__44u0__long,
  147444. &_resbook_44u_0,&_resbook_44u_0}
  147445. };
  147446. static vorbis_residue_template _res_44u_1[]={
  147447. {1,0, &_residue_44_low_un,
  147448. &_huff_book__44u1__short,&_huff_book__44u1__short,
  147449. &_resbook_44u_1,&_resbook_44u_1},
  147450. {1,0, &_residue_44_low_un,
  147451. &_huff_book__44u1__long,&_huff_book__44u1__long,
  147452. &_resbook_44u_1,&_resbook_44u_1}
  147453. };
  147454. static vorbis_residue_template _res_44u_2[]={
  147455. {1,0, &_residue_44_low_un,
  147456. &_huff_book__44u2__short,&_huff_book__44u2__short,
  147457. &_resbook_44u_2,&_resbook_44u_2},
  147458. {1,0, &_residue_44_low_un,
  147459. &_huff_book__44u2__long,&_huff_book__44u2__long,
  147460. &_resbook_44u_2,&_resbook_44u_2}
  147461. };
  147462. static vorbis_residue_template _res_44u_3[]={
  147463. {1,0, &_residue_44_low_un,
  147464. &_huff_book__44u3__short,&_huff_book__44u3__short,
  147465. &_resbook_44u_3,&_resbook_44u_3},
  147466. {1,0, &_residue_44_low_un,
  147467. &_huff_book__44u3__long,&_huff_book__44u3__long,
  147468. &_resbook_44u_3,&_resbook_44u_3}
  147469. };
  147470. static vorbis_residue_template _res_44u_4[]={
  147471. {1,0, &_residue_44_low_un,
  147472. &_huff_book__44u4__short,&_huff_book__44u4__short,
  147473. &_resbook_44u_4,&_resbook_44u_4},
  147474. {1,0, &_residue_44_low_un,
  147475. &_huff_book__44u4__long,&_huff_book__44u4__long,
  147476. &_resbook_44u_4,&_resbook_44u_4}
  147477. };
  147478. static vorbis_residue_template _res_44u_5[]={
  147479. {1,0, &_residue_44_mid_un,
  147480. &_huff_book__44u5__short,&_huff_book__44u5__short,
  147481. &_resbook_44u_5,&_resbook_44u_5},
  147482. {1,0, &_residue_44_mid_un,
  147483. &_huff_book__44u5__long,&_huff_book__44u5__long,
  147484. &_resbook_44u_5,&_resbook_44u_5}
  147485. };
  147486. static vorbis_residue_template _res_44u_6[]={
  147487. {1,0, &_residue_44_mid_un,
  147488. &_huff_book__44u6__short,&_huff_book__44u6__short,
  147489. &_resbook_44u_6,&_resbook_44u_6},
  147490. {1,0, &_residue_44_mid_un,
  147491. &_huff_book__44u6__long,&_huff_book__44u6__long,
  147492. &_resbook_44u_6,&_resbook_44u_6}
  147493. };
  147494. static vorbis_residue_template _res_44u_7[]={
  147495. {1,0, &_residue_44_mid_un,
  147496. &_huff_book__44u7__short,&_huff_book__44u7__short,
  147497. &_resbook_44u_7,&_resbook_44u_7},
  147498. {1,0, &_residue_44_mid_un,
  147499. &_huff_book__44u7__long,&_huff_book__44u7__long,
  147500. &_resbook_44u_7,&_resbook_44u_7}
  147501. };
  147502. static vorbis_residue_template _res_44u_8[]={
  147503. {1,0, &_residue_44_hi_un,
  147504. &_huff_book__44u8__short,&_huff_book__44u8__short,
  147505. &_resbook_44u_8,&_resbook_44u_8},
  147506. {1,0, &_residue_44_hi_un,
  147507. &_huff_book__44u8__long,&_huff_book__44u8__long,
  147508. &_resbook_44u_8,&_resbook_44u_8}
  147509. };
  147510. static vorbis_residue_template _res_44u_9[]={
  147511. {1,0, &_residue_44_hi_un,
  147512. &_huff_book__44u9__short,&_huff_book__44u9__short,
  147513. &_resbook_44u_9,&_resbook_44u_9},
  147514. {1,0, &_residue_44_hi_un,
  147515. &_huff_book__44u9__long,&_huff_book__44u9__long,
  147516. &_resbook_44u_9,&_resbook_44u_9}
  147517. };
  147518. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  147519. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  147520. { _map_nominal_u, _res_44u_0 }, /* 0 */
  147521. { _map_nominal_u, _res_44u_1 }, /* 1 */
  147522. { _map_nominal_u, _res_44u_2 }, /* 2 */
  147523. { _map_nominal_u, _res_44u_3 }, /* 3 */
  147524. { _map_nominal_u, _res_44u_4 }, /* 4 */
  147525. { _map_nominal_u, _res_44u_5 }, /* 5 */
  147526. { _map_nominal_u, _res_44u_6 }, /* 6 */
  147527. { _map_nominal_u, _res_44u_7 }, /* 7 */
  147528. { _map_nominal_u, _res_44u_8 }, /* 8 */
  147529. { _map_nominal_u, _res_44u_9 }, /* 9 */
  147530. };
  147531. /********* End of inlined file: residue_44u.h *********/
  147532. static double rate_mapping_44_un[12]={
  147533. 32000.,48000.,60000.,70000.,80000.,86000.,
  147534. 96000.,110000.,120000.,140000.,160000.,240001.
  147535. };
  147536. ve_setup_data_template ve_setup_44_uncoupled={
  147537. 11,
  147538. rate_mapping_44_un,
  147539. quality_mapping_44,
  147540. -1,
  147541. 40000,
  147542. 50000,
  147543. blocksize_short_44,
  147544. blocksize_long_44,
  147545. _psy_tone_masteratt_44,
  147546. _psy_tone_0dB,
  147547. _psy_tone_suppress,
  147548. _vp_tonemask_adj_otherblock,
  147549. _vp_tonemask_adj_longblock,
  147550. _vp_tonemask_adj_otherblock,
  147551. _psy_noiseguards_44,
  147552. _psy_noisebias_impulse,
  147553. _psy_noisebias_padding,
  147554. _psy_noisebias_trans,
  147555. _psy_noisebias_long,
  147556. _psy_noise_suppress,
  147557. _psy_compand_44,
  147558. _psy_compand_short_mapping,
  147559. _psy_compand_long_mapping,
  147560. {_noise_start_short_44,_noise_start_long_44},
  147561. {_noise_part_short_44,_noise_part_long_44},
  147562. _noise_thresh_44,
  147563. _psy_ath_floater,
  147564. _psy_ath_abs,
  147565. _psy_lowpass_44,
  147566. _psy_global_44,
  147567. _global_mapping_44,
  147568. NULL,
  147569. _floor_books,
  147570. _floor,
  147571. _floor_short_mapping_44,
  147572. _floor_long_mapping_44,
  147573. _mapres_template_44_uncoupled
  147574. };
  147575. /********* End of inlined file: setup_44u.h *********/
  147576. /********* Start of inlined file: setup_32.h *********/
  147577. static double rate_mapping_32[12]={
  147578. 18000.,28000.,35000.,45000.,56000.,60000.,
  147579. 75000.,90000.,100000.,115000.,150000.,190000.,
  147580. };
  147581. static double rate_mapping_32_un[12]={
  147582. 30000.,42000.,52000.,64000.,72000.,78000.,
  147583. 86000.,92000.,110000.,120000.,140000.,190000.,
  147584. };
  147585. static double _psy_lowpass_32[12]={
  147586. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  147587. };
  147588. ve_setup_data_template ve_setup_32_stereo={
  147589. 11,
  147590. rate_mapping_32,
  147591. quality_mapping_44,
  147592. 2,
  147593. 26000,
  147594. 40000,
  147595. blocksize_short_44,
  147596. blocksize_long_44,
  147597. _psy_tone_masteratt_44,
  147598. _psy_tone_0dB,
  147599. _psy_tone_suppress,
  147600. _vp_tonemask_adj_otherblock,
  147601. _vp_tonemask_adj_longblock,
  147602. _vp_tonemask_adj_otherblock,
  147603. _psy_noiseguards_44,
  147604. _psy_noisebias_impulse,
  147605. _psy_noisebias_padding,
  147606. _psy_noisebias_trans,
  147607. _psy_noisebias_long,
  147608. _psy_noise_suppress,
  147609. _psy_compand_44,
  147610. _psy_compand_short_mapping,
  147611. _psy_compand_long_mapping,
  147612. {_noise_start_short_44,_noise_start_long_44},
  147613. {_noise_part_short_44,_noise_part_long_44},
  147614. _noise_thresh_44,
  147615. _psy_ath_floater,
  147616. _psy_ath_abs,
  147617. _psy_lowpass_32,
  147618. _psy_global_44,
  147619. _global_mapping_44,
  147620. _psy_stereo_modes_44,
  147621. _floor_books,
  147622. _floor,
  147623. _floor_short_mapping_44,
  147624. _floor_long_mapping_44,
  147625. _mapres_template_44_stereo
  147626. };
  147627. ve_setup_data_template ve_setup_32_uncoupled={
  147628. 11,
  147629. rate_mapping_32_un,
  147630. quality_mapping_44,
  147631. -1,
  147632. 26000,
  147633. 40000,
  147634. blocksize_short_44,
  147635. blocksize_long_44,
  147636. _psy_tone_masteratt_44,
  147637. _psy_tone_0dB,
  147638. _psy_tone_suppress,
  147639. _vp_tonemask_adj_otherblock,
  147640. _vp_tonemask_adj_longblock,
  147641. _vp_tonemask_adj_otherblock,
  147642. _psy_noiseguards_44,
  147643. _psy_noisebias_impulse,
  147644. _psy_noisebias_padding,
  147645. _psy_noisebias_trans,
  147646. _psy_noisebias_long,
  147647. _psy_noise_suppress,
  147648. _psy_compand_44,
  147649. _psy_compand_short_mapping,
  147650. _psy_compand_long_mapping,
  147651. {_noise_start_short_44,_noise_start_long_44},
  147652. {_noise_part_short_44,_noise_part_long_44},
  147653. _noise_thresh_44,
  147654. _psy_ath_floater,
  147655. _psy_ath_abs,
  147656. _psy_lowpass_32,
  147657. _psy_global_44,
  147658. _global_mapping_44,
  147659. NULL,
  147660. _floor_books,
  147661. _floor,
  147662. _floor_short_mapping_44,
  147663. _floor_long_mapping_44,
  147664. _mapres_template_44_uncoupled
  147665. };
  147666. /********* End of inlined file: setup_32.h *********/
  147667. /********* Start of inlined file: setup_8.h *********/
  147668. /********* Start of inlined file: psych_8.h *********/
  147669. static att3 _psy_tone_masteratt_8[3]={
  147670. {{ 32, 25, 12}, 0, 0}, /* 0 */
  147671. {{ 30, 25, 12}, 0, 0}, /* 0 */
  147672. {{ 20, 0, -14}, 0, 0}, /* 0 */
  147673. };
  147674. static vp_adjblock _vp_tonemask_adj_8[3]={
  147675. /* adjust for mode zero */
  147676. /* 63 125 250 500 1 2 4 8 16 */
  147677. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  147678. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  147679. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  147680. };
  147681. static noise3 _psy_noisebias_8[3]={
  147682. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  147683. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  147684. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  147685. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  147686. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  147687. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  147688. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  147689. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  147690. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  147691. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  147692. };
  147693. /* stereo mode by base quality level */
  147694. static adj_stereo _psy_stereo_modes_8[3]={
  147695. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  147696. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147697. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147698. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  147699. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147700. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147701. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147702. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  147703. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147704. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147705. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147706. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  147707. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147708. };
  147709. static noiseguard _psy_noiseguards_8[2]={
  147710. {10,10,-1},
  147711. {10,10,-1},
  147712. };
  147713. static compandblock _psy_compand_8[2]={
  147714. {{
  147715. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  147716. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  147717. 12,12,13,13,14,14,15, 15, /* 23dB */
  147718. 16,16,17,17,17,18,18, 19, /* 31dB */
  147719. 19,19,20,21,22,23,24, 25, /* 39dB */
  147720. }},
  147721. {{
  147722. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  147723. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  147724. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  147725. 9,10,11,12,13,14,15, 16, /* 31dB */
  147726. 17,18,19,20,21,22,23, 24, /* 39dB */
  147727. }},
  147728. };
  147729. static double _psy_lowpass_8[3]={3.,4.,4.};
  147730. static int _noise_start_8[2]={
  147731. 64,64,
  147732. };
  147733. static int _noise_part_8[2]={
  147734. 8,8,
  147735. };
  147736. static int _psy_ath_floater_8[3]={
  147737. -100,-100,-105,
  147738. };
  147739. static int _psy_ath_abs_8[3]={
  147740. -130,-130,-140,
  147741. };
  147742. /********* End of inlined file: psych_8.h *********/
  147743. /********* Start of inlined file: residue_8.h *********/
  147744. /***** residue backends *********************************************/
  147745. static static_bookblock _resbook_8s_0={
  147746. {
  147747. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  147748. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  147749. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  147750. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  147751. }
  147752. };
  147753. static static_bookblock _resbook_8s_1={
  147754. {
  147755. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  147756. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  147757. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  147758. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  147759. }
  147760. };
  147761. static vorbis_residue_template _res_8s_0[]={
  147762. {2,0, &_residue_44_mid,
  147763. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  147764. &_resbook_8s_0,&_resbook_8s_0},
  147765. };
  147766. static vorbis_residue_template _res_8s_1[]={
  147767. {2,0, &_residue_44_mid,
  147768. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  147769. &_resbook_8s_1,&_resbook_8s_1},
  147770. };
  147771. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  147772. { _map_nominal, _res_8s_0 }, /* 0 */
  147773. { _map_nominal, _res_8s_1 }, /* 1 */
  147774. };
  147775. static static_bookblock _resbook_8u_0={
  147776. {
  147777. {0},
  147778. {0,0,&_8u0__p1_0},
  147779. {0,0,&_8u0__p2_0},
  147780. {0,0,&_8u0__p3_0},
  147781. {0,0,&_8u0__p4_0},
  147782. {0,0,&_8u0__p5_0},
  147783. {&_8u0__p6_0,&_8u0__p6_1},
  147784. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  147785. }
  147786. };
  147787. static static_bookblock _resbook_8u_1={
  147788. {
  147789. {0},
  147790. {0,0,&_8u1__p1_0},
  147791. {0,0,&_8u1__p2_0},
  147792. {0,0,&_8u1__p3_0},
  147793. {0,0,&_8u1__p4_0},
  147794. {0,0,&_8u1__p5_0},
  147795. {0,0,&_8u1__p6_0},
  147796. {&_8u1__p7_0,&_8u1__p7_1},
  147797. {&_8u1__p8_0,&_8u1__p8_1},
  147798. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  147799. }
  147800. };
  147801. static vorbis_residue_template _res_8u_0[]={
  147802. {1,0, &_residue_44_low_un,
  147803. &_huff_book__8u0__single,&_huff_book__8u0__single,
  147804. &_resbook_8u_0,&_resbook_8u_0},
  147805. };
  147806. static vorbis_residue_template _res_8u_1[]={
  147807. {1,0, &_residue_44_mid_un,
  147808. &_huff_book__8u1__single,&_huff_book__8u1__single,
  147809. &_resbook_8u_1,&_resbook_8u_1},
  147810. };
  147811. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  147812. { _map_nominal_u, _res_8u_0 }, /* 0 */
  147813. { _map_nominal_u, _res_8u_1 }, /* 1 */
  147814. };
  147815. /********* End of inlined file: residue_8.h *********/
  147816. static int blocksize_8[2]={
  147817. 512,512
  147818. };
  147819. static int _floor_mapping_8[2]={
  147820. 6,6,
  147821. };
  147822. static double rate_mapping_8[3]={
  147823. 6000.,9000.,32000.,
  147824. };
  147825. static double rate_mapping_8_uncoupled[3]={
  147826. 8000.,14000.,42000.,
  147827. };
  147828. static double quality_mapping_8[3]={
  147829. -.1,.0,1.
  147830. };
  147831. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  147832. static double _global_mapping_8[3]={ 1., 2., 3. };
  147833. ve_setup_data_template ve_setup_8_stereo={
  147834. 2,
  147835. rate_mapping_8,
  147836. quality_mapping_8,
  147837. 2,
  147838. 8000,
  147839. 9000,
  147840. blocksize_8,
  147841. blocksize_8,
  147842. _psy_tone_masteratt_8,
  147843. _psy_tone_0dB,
  147844. _psy_tone_suppress,
  147845. _vp_tonemask_adj_8,
  147846. NULL,
  147847. _vp_tonemask_adj_8,
  147848. _psy_noiseguards_8,
  147849. _psy_noisebias_8,
  147850. _psy_noisebias_8,
  147851. NULL,
  147852. NULL,
  147853. _psy_noise_suppress,
  147854. _psy_compand_8,
  147855. _psy_compand_8_mapping,
  147856. NULL,
  147857. {_noise_start_8,_noise_start_8},
  147858. {_noise_part_8,_noise_part_8},
  147859. _noise_thresh_5only,
  147860. _psy_ath_floater_8,
  147861. _psy_ath_abs_8,
  147862. _psy_lowpass_8,
  147863. _psy_global_44,
  147864. _global_mapping_8,
  147865. _psy_stereo_modes_8,
  147866. _floor_books,
  147867. _floor,
  147868. _floor_mapping_8,
  147869. NULL,
  147870. _mapres_template_8_stereo
  147871. };
  147872. ve_setup_data_template ve_setup_8_uncoupled={
  147873. 2,
  147874. rate_mapping_8_uncoupled,
  147875. quality_mapping_8,
  147876. -1,
  147877. 8000,
  147878. 9000,
  147879. blocksize_8,
  147880. blocksize_8,
  147881. _psy_tone_masteratt_8,
  147882. _psy_tone_0dB,
  147883. _psy_tone_suppress,
  147884. _vp_tonemask_adj_8,
  147885. NULL,
  147886. _vp_tonemask_adj_8,
  147887. _psy_noiseguards_8,
  147888. _psy_noisebias_8,
  147889. _psy_noisebias_8,
  147890. NULL,
  147891. NULL,
  147892. _psy_noise_suppress,
  147893. _psy_compand_8,
  147894. _psy_compand_8_mapping,
  147895. NULL,
  147896. {_noise_start_8,_noise_start_8},
  147897. {_noise_part_8,_noise_part_8},
  147898. _noise_thresh_5only,
  147899. _psy_ath_floater_8,
  147900. _psy_ath_abs_8,
  147901. _psy_lowpass_8,
  147902. _psy_global_44,
  147903. _global_mapping_8,
  147904. _psy_stereo_modes_8,
  147905. _floor_books,
  147906. _floor,
  147907. _floor_mapping_8,
  147908. NULL,
  147909. _mapres_template_8_uncoupled
  147910. };
  147911. /********* End of inlined file: setup_8.h *********/
  147912. /********* Start of inlined file: setup_11.h *********/
  147913. /********* Start of inlined file: psych_11.h *********/
  147914. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  147915. static att3 _psy_tone_masteratt_11[3]={
  147916. {{ 30, 25, 12}, 0, 0}, /* 0 */
  147917. {{ 30, 25, 12}, 0, 0}, /* 0 */
  147918. {{ 20, 0, -14}, 0, 0}, /* 0 */
  147919. };
  147920. static vp_adjblock _vp_tonemask_adj_11[3]={
  147921. /* adjust for mode zero */
  147922. /* 63 125 250 500 1 2 4 8 16 */
  147923. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  147924. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  147925. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  147926. };
  147927. static noise3 _psy_noisebias_11[3]={
  147928. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  147929. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  147930. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  147931. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  147932. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  147933. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  147934. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  147935. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  147936. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  147937. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  147938. };
  147939. static double _noise_thresh_11[3]={ .3,.5,.5 };
  147940. /********* End of inlined file: psych_11.h *********/
  147941. static int blocksize_11[2]={
  147942. 512,512
  147943. };
  147944. static int _floor_mapping_11[2]={
  147945. 6,6,
  147946. };
  147947. static double rate_mapping_11[3]={
  147948. 8000.,13000.,44000.,
  147949. };
  147950. static double rate_mapping_11_uncoupled[3]={
  147951. 12000.,20000.,50000.,
  147952. };
  147953. static double quality_mapping_11[3]={
  147954. -.1,.0,1.
  147955. };
  147956. ve_setup_data_template ve_setup_11_stereo={
  147957. 2,
  147958. rate_mapping_11,
  147959. quality_mapping_11,
  147960. 2,
  147961. 9000,
  147962. 15000,
  147963. blocksize_11,
  147964. blocksize_11,
  147965. _psy_tone_masteratt_11,
  147966. _psy_tone_0dB,
  147967. _psy_tone_suppress,
  147968. _vp_tonemask_adj_11,
  147969. NULL,
  147970. _vp_tonemask_adj_11,
  147971. _psy_noiseguards_8,
  147972. _psy_noisebias_11,
  147973. _psy_noisebias_11,
  147974. NULL,
  147975. NULL,
  147976. _psy_noise_suppress,
  147977. _psy_compand_8,
  147978. _psy_compand_8_mapping,
  147979. NULL,
  147980. {_noise_start_8,_noise_start_8},
  147981. {_noise_part_8,_noise_part_8},
  147982. _noise_thresh_11,
  147983. _psy_ath_floater_8,
  147984. _psy_ath_abs_8,
  147985. _psy_lowpass_11,
  147986. _psy_global_44,
  147987. _global_mapping_8,
  147988. _psy_stereo_modes_8,
  147989. _floor_books,
  147990. _floor,
  147991. _floor_mapping_11,
  147992. NULL,
  147993. _mapres_template_8_stereo
  147994. };
  147995. ve_setup_data_template ve_setup_11_uncoupled={
  147996. 2,
  147997. rate_mapping_11_uncoupled,
  147998. quality_mapping_11,
  147999. -1,
  148000. 9000,
  148001. 15000,
  148002. blocksize_11,
  148003. blocksize_11,
  148004. _psy_tone_masteratt_11,
  148005. _psy_tone_0dB,
  148006. _psy_tone_suppress,
  148007. _vp_tonemask_adj_11,
  148008. NULL,
  148009. _vp_tonemask_adj_11,
  148010. _psy_noiseguards_8,
  148011. _psy_noisebias_11,
  148012. _psy_noisebias_11,
  148013. NULL,
  148014. NULL,
  148015. _psy_noise_suppress,
  148016. _psy_compand_8,
  148017. _psy_compand_8_mapping,
  148018. NULL,
  148019. {_noise_start_8,_noise_start_8},
  148020. {_noise_part_8,_noise_part_8},
  148021. _noise_thresh_11,
  148022. _psy_ath_floater_8,
  148023. _psy_ath_abs_8,
  148024. _psy_lowpass_11,
  148025. _psy_global_44,
  148026. _global_mapping_8,
  148027. _psy_stereo_modes_8,
  148028. _floor_books,
  148029. _floor,
  148030. _floor_mapping_11,
  148031. NULL,
  148032. _mapres_template_8_uncoupled
  148033. };
  148034. /********* End of inlined file: setup_11.h *********/
  148035. /********* Start of inlined file: setup_16.h *********/
  148036. /********* Start of inlined file: psych_16.h *********/
  148037. /* stereo mode by base quality level */
  148038. static adj_stereo _psy_stereo_modes_16[4]={
  148039. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  148040. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148041. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148042. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  148043. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148044. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148045. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148046. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  148047. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148048. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148049. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148050. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148051. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148052. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  148053. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  148054. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  148055. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148056. };
  148057. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  148058. static att3 _psy_tone_masteratt_16[4]={
  148059. {{ 30, 25, 12}, 0, 0}, /* 0 */
  148060. {{ 25, 22, 12}, 0, 0}, /* 0 */
  148061. {{ 20, 12, 0}, 0, 0}, /* 0 */
  148062. {{ 15, 0, -14}, 0, 0}, /* 0 */
  148063. };
  148064. static vp_adjblock _vp_tonemask_adj_16[4]={
  148065. /* adjust for mode zero */
  148066. /* 63 125 250 500 1 2 4 8 16 */
  148067. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  148068. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  148069. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  148070. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  148071. };
  148072. static noise3 _psy_noisebias_16_short[4]={
  148073. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  148074. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  148075. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  148076. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  148077. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  148078. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  148079. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  148080. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  148081. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  148082. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148083. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  148084. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  148085. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148086. };
  148087. static noise3 _psy_noisebias_16_impulse[4]={
  148088. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  148089. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  148090. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  148091. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  148092. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  148093. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  148094. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  148095. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  148096. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  148097. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148098. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  148099. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  148100. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148101. };
  148102. static noise3 _psy_noisebias_16[4]={
  148103. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  148104. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  148105. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  148106. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  148107. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  148108. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  148109. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  148110. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  148111. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  148112. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148113. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  148114. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  148115. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148116. };
  148117. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  148118. static int _noise_start_16[3]={ 256,256,9999 };
  148119. static int _noise_part_16[4]={ 8,8,8,8 };
  148120. static int _psy_ath_floater_16[4]={
  148121. -100,-100,-100,-105,
  148122. };
  148123. static int _psy_ath_abs_16[4]={
  148124. -130,-130,-130,-140,
  148125. };
  148126. /********* End of inlined file: psych_16.h *********/
  148127. /********* Start of inlined file: residue_16.h *********/
  148128. /***** residue backends *********************************************/
  148129. static static_bookblock _resbook_16s_0={
  148130. {
  148131. {0},
  148132. {0,0,&_16c0_s_p1_0},
  148133. {0,0,&_16c0_s_p2_0},
  148134. {0,0,&_16c0_s_p3_0},
  148135. {0,0,&_16c0_s_p4_0},
  148136. {0,0,&_16c0_s_p5_0},
  148137. {0,0,&_16c0_s_p6_0},
  148138. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  148139. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  148140. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  148141. }
  148142. };
  148143. static static_bookblock _resbook_16s_1={
  148144. {
  148145. {0},
  148146. {0,0,&_16c1_s_p1_0},
  148147. {0,0,&_16c1_s_p2_0},
  148148. {0,0,&_16c1_s_p3_0},
  148149. {0,0,&_16c1_s_p4_0},
  148150. {0,0,&_16c1_s_p5_0},
  148151. {0,0,&_16c1_s_p6_0},
  148152. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  148153. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  148154. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  148155. }
  148156. };
  148157. static static_bookblock _resbook_16s_2={
  148158. {
  148159. {0},
  148160. {0,0,&_16c2_s_p1_0},
  148161. {0,0,&_16c2_s_p2_0},
  148162. {0,0,&_16c2_s_p3_0},
  148163. {0,0,&_16c2_s_p4_0},
  148164. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  148165. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  148166. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  148167. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  148168. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  148169. }
  148170. };
  148171. static vorbis_residue_template _res_16s_0[]={
  148172. {2,0, &_residue_44_mid,
  148173. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  148174. &_resbook_16s_0,&_resbook_16s_0},
  148175. };
  148176. static vorbis_residue_template _res_16s_1[]={
  148177. {2,0, &_residue_44_mid,
  148178. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  148179. &_resbook_16s_1,&_resbook_16s_1},
  148180. {2,0, &_residue_44_mid,
  148181. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  148182. &_resbook_16s_1,&_resbook_16s_1}
  148183. };
  148184. static vorbis_residue_template _res_16s_2[]={
  148185. {2,0, &_residue_44_high,
  148186. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  148187. &_resbook_16s_2,&_resbook_16s_2},
  148188. {2,0, &_residue_44_high,
  148189. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  148190. &_resbook_16s_2,&_resbook_16s_2}
  148191. };
  148192. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  148193. { _map_nominal, _res_16s_0 }, /* 0 */
  148194. { _map_nominal, _res_16s_1 }, /* 1 */
  148195. { _map_nominal, _res_16s_2 }, /* 2 */
  148196. };
  148197. static static_bookblock _resbook_16u_0={
  148198. {
  148199. {0},
  148200. {0,0,&_16u0__p1_0},
  148201. {0,0,&_16u0__p2_0},
  148202. {0,0,&_16u0__p3_0},
  148203. {0,0,&_16u0__p4_0},
  148204. {0,0,&_16u0__p5_0},
  148205. {&_16u0__p6_0,&_16u0__p6_1},
  148206. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  148207. }
  148208. };
  148209. static static_bookblock _resbook_16u_1={
  148210. {
  148211. {0},
  148212. {0,0,&_16u1__p1_0},
  148213. {0,0,&_16u1__p2_0},
  148214. {0,0,&_16u1__p3_0},
  148215. {0,0,&_16u1__p4_0},
  148216. {0,0,&_16u1__p5_0},
  148217. {0,0,&_16u1__p6_0},
  148218. {&_16u1__p7_0,&_16u1__p7_1},
  148219. {&_16u1__p8_0,&_16u1__p8_1},
  148220. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  148221. }
  148222. };
  148223. static static_bookblock _resbook_16u_2={
  148224. {
  148225. {0},
  148226. {0,0,&_16u2_p1_0},
  148227. {0,0,&_16u2_p2_0},
  148228. {0,0,&_16u2_p3_0},
  148229. {0,0,&_16u2_p4_0},
  148230. {&_16u2_p5_0,&_16u2_p5_1},
  148231. {&_16u2_p6_0,&_16u2_p6_1},
  148232. {&_16u2_p7_0,&_16u2_p7_1},
  148233. {&_16u2_p8_0,&_16u2_p8_1},
  148234. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  148235. }
  148236. };
  148237. static vorbis_residue_template _res_16u_0[]={
  148238. {1,0, &_residue_44_low_un,
  148239. &_huff_book__16u0__single,&_huff_book__16u0__single,
  148240. &_resbook_16u_0,&_resbook_16u_0},
  148241. };
  148242. static vorbis_residue_template _res_16u_1[]={
  148243. {1,0, &_residue_44_mid_un,
  148244. &_huff_book__16u1__short,&_huff_book__16u1__short,
  148245. &_resbook_16u_1,&_resbook_16u_1},
  148246. {1,0, &_residue_44_mid_un,
  148247. &_huff_book__16u1__long,&_huff_book__16u1__long,
  148248. &_resbook_16u_1,&_resbook_16u_1}
  148249. };
  148250. static vorbis_residue_template _res_16u_2[]={
  148251. {1,0, &_residue_44_hi_un,
  148252. &_huff_book__16u2__short,&_huff_book__16u2__short,
  148253. &_resbook_16u_2,&_resbook_16u_2},
  148254. {1,0, &_residue_44_hi_un,
  148255. &_huff_book__16u2__long,&_huff_book__16u2__long,
  148256. &_resbook_16u_2,&_resbook_16u_2}
  148257. };
  148258. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  148259. { _map_nominal_u, _res_16u_0 }, /* 0 */
  148260. { _map_nominal_u, _res_16u_1 }, /* 1 */
  148261. { _map_nominal_u, _res_16u_2 }, /* 2 */
  148262. };
  148263. /********* End of inlined file: residue_16.h *********/
  148264. static int blocksize_16_short[3]={
  148265. 1024,512,512
  148266. };
  148267. static int blocksize_16_long[3]={
  148268. 1024,1024,1024
  148269. };
  148270. static int _floor_mapping_16_short[3]={
  148271. 9,3,3
  148272. };
  148273. static int _floor_mapping_16[3]={
  148274. 9,9,9
  148275. };
  148276. static double rate_mapping_16[4]={
  148277. 12000.,20000.,44000.,86000.
  148278. };
  148279. static double rate_mapping_16_uncoupled[4]={
  148280. 16000.,28000.,64000.,100000.
  148281. };
  148282. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  148283. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  148284. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  148285. ve_setup_data_template ve_setup_16_stereo={
  148286. 3,
  148287. rate_mapping_16,
  148288. quality_mapping_16,
  148289. 2,
  148290. 15000,
  148291. 19000,
  148292. blocksize_16_short,
  148293. blocksize_16_long,
  148294. _psy_tone_masteratt_16,
  148295. _psy_tone_0dB,
  148296. _psy_tone_suppress,
  148297. _vp_tonemask_adj_16,
  148298. _vp_tonemask_adj_16,
  148299. _vp_tonemask_adj_16,
  148300. _psy_noiseguards_8,
  148301. _psy_noisebias_16_impulse,
  148302. _psy_noisebias_16_short,
  148303. _psy_noisebias_16_short,
  148304. _psy_noisebias_16,
  148305. _psy_noise_suppress,
  148306. _psy_compand_8,
  148307. _psy_compand_16_mapping,
  148308. _psy_compand_16_mapping,
  148309. {_noise_start_16,_noise_start_16},
  148310. { _noise_part_16, _noise_part_16},
  148311. _noise_thresh_16,
  148312. _psy_ath_floater_16,
  148313. _psy_ath_abs_16,
  148314. _psy_lowpass_16,
  148315. _psy_global_44,
  148316. _global_mapping_16,
  148317. _psy_stereo_modes_16,
  148318. _floor_books,
  148319. _floor,
  148320. _floor_mapping_16_short,
  148321. _floor_mapping_16,
  148322. _mapres_template_16_stereo
  148323. };
  148324. ve_setup_data_template ve_setup_16_uncoupled={
  148325. 3,
  148326. rate_mapping_16_uncoupled,
  148327. quality_mapping_16,
  148328. -1,
  148329. 15000,
  148330. 19000,
  148331. blocksize_16_short,
  148332. blocksize_16_long,
  148333. _psy_tone_masteratt_16,
  148334. _psy_tone_0dB,
  148335. _psy_tone_suppress,
  148336. _vp_tonemask_adj_16,
  148337. _vp_tonemask_adj_16,
  148338. _vp_tonemask_adj_16,
  148339. _psy_noiseguards_8,
  148340. _psy_noisebias_16_impulse,
  148341. _psy_noisebias_16_short,
  148342. _psy_noisebias_16_short,
  148343. _psy_noisebias_16,
  148344. _psy_noise_suppress,
  148345. _psy_compand_8,
  148346. _psy_compand_16_mapping,
  148347. _psy_compand_16_mapping,
  148348. {_noise_start_16,_noise_start_16},
  148349. { _noise_part_16, _noise_part_16},
  148350. _noise_thresh_16,
  148351. _psy_ath_floater_16,
  148352. _psy_ath_abs_16,
  148353. _psy_lowpass_16,
  148354. _psy_global_44,
  148355. _global_mapping_16,
  148356. _psy_stereo_modes_16,
  148357. _floor_books,
  148358. _floor,
  148359. _floor_mapping_16_short,
  148360. _floor_mapping_16,
  148361. _mapres_template_16_uncoupled
  148362. };
  148363. /********* End of inlined file: setup_16.h *********/
  148364. /********* Start of inlined file: setup_22.h *********/
  148365. static double rate_mapping_22[4]={
  148366. 15000.,20000.,44000.,86000.
  148367. };
  148368. static double rate_mapping_22_uncoupled[4]={
  148369. 16000.,28000.,50000.,90000.
  148370. };
  148371. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  148372. ve_setup_data_template ve_setup_22_stereo={
  148373. 3,
  148374. rate_mapping_22,
  148375. quality_mapping_16,
  148376. 2,
  148377. 19000,
  148378. 26000,
  148379. blocksize_16_short,
  148380. blocksize_16_long,
  148381. _psy_tone_masteratt_16,
  148382. _psy_tone_0dB,
  148383. _psy_tone_suppress,
  148384. _vp_tonemask_adj_16,
  148385. _vp_tonemask_adj_16,
  148386. _vp_tonemask_adj_16,
  148387. _psy_noiseguards_8,
  148388. _psy_noisebias_16_impulse,
  148389. _psy_noisebias_16_short,
  148390. _psy_noisebias_16_short,
  148391. _psy_noisebias_16,
  148392. _psy_noise_suppress,
  148393. _psy_compand_8,
  148394. _psy_compand_8_mapping,
  148395. _psy_compand_8_mapping,
  148396. {_noise_start_16,_noise_start_16},
  148397. { _noise_part_16, _noise_part_16},
  148398. _noise_thresh_16,
  148399. _psy_ath_floater_16,
  148400. _psy_ath_abs_16,
  148401. _psy_lowpass_22,
  148402. _psy_global_44,
  148403. _global_mapping_16,
  148404. _psy_stereo_modes_16,
  148405. _floor_books,
  148406. _floor,
  148407. _floor_mapping_16_short,
  148408. _floor_mapping_16,
  148409. _mapres_template_16_stereo
  148410. };
  148411. ve_setup_data_template ve_setup_22_uncoupled={
  148412. 3,
  148413. rate_mapping_22_uncoupled,
  148414. quality_mapping_16,
  148415. -1,
  148416. 19000,
  148417. 26000,
  148418. blocksize_16_short,
  148419. blocksize_16_long,
  148420. _psy_tone_masteratt_16,
  148421. _psy_tone_0dB,
  148422. _psy_tone_suppress,
  148423. _vp_tonemask_adj_16,
  148424. _vp_tonemask_adj_16,
  148425. _vp_tonemask_adj_16,
  148426. _psy_noiseguards_8,
  148427. _psy_noisebias_16_impulse,
  148428. _psy_noisebias_16_short,
  148429. _psy_noisebias_16_short,
  148430. _psy_noisebias_16,
  148431. _psy_noise_suppress,
  148432. _psy_compand_8,
  148433. _psy_compand_8_mapping,
  148434. _psy_compand_8_mapping,
  148435. {_noise_start_16,_noise_start_16},
  148436. { _noise_part_16, _noise_part_16},
  148437. _noise_thresh_16,
  148438. _psy_ath_floater_16,
  148439. _psy_ath_abs_16,
  148440. _psy_lowpass_22,
  148441. _psy_global_44,
  148442. _global_mapping_16,
  148443. _psy_stereo_modes_16,
  148444. _floor_books,
  148445. _floor,
  148446. _floor_mapping_16_short,
  148447. _floor_mapping_16,
  148448. _mapres_template_16_uncoupled
  148449. };
  148450. /********* End of inlined file: setup_22.h *********/
  148451. /********* Start of inlined file: setup_X.h *********/
  148452. static double rate_mapping_X[12]={
  148453. -1.,-1.,-1.,-1.,-1.,-1.,
  148454. -1.,-1.,-1.,-1.,-1.,-1.
  148455. };
  148456. ve_setup_data_template ve_setup_X_stereo={
  148457. 11,
  148458. rate_mapping_X,
  148459. quality_mapping_44,
  148460. 2,
  148461. 50000,
  148462. 200000,
  148463. blocksize_short_44,
  148464. blocksize_long_44,
  148465. _psy_tone_masteratt_44,
  148466. _psy_tone_0dB,
  148467. _psy_tone_suppress,
  148468. _vp_tonemask_adj_otherblock,
  148469. _vp_tonemask_adj_longblock,
  148470. _vp_tonemask_adj_otherblock,
  148471. _psy_noiseguards_44,
  148472. _psy_noisebias_impulse,
  148473. _psy_noisebias_padding,
  148474. _psy_noisebias_trans,
  148475. _psy_noisebias_long,
  148476. _psy_noise_suppress,
  148477. _psy_compand_44,
  148478. _psy_compand_short_mapping,
  148479. _psy_compand_long_mapping,
  148480. {_noise_start_short_44,_noise_start_long_44},
  148481. {_noise_part_short_44,_noise_part_long_44},
  148482. _noise_thresh_44,
  148483. _psy_ath_floater,
  148484. _psy_ath_abs,
  148485. _psy_lowpass_44,
  148486. _psy_global_44,
  148487. _global_mapping_44,
  148488. _psy_stereo_modes_44,
  148489. _floor_books,
  148490. _floor,
  148491. _floor_short_mapping_44,
  148492. _floor_long_mapping_44,
  148493. _mapres_template_44_stereo
  148494. };
  148495. ve_setup_data_template ve_setup_X_uncoupled={
  148496. 11,
  148497. rate_mapping_X,
  148498. quality_mapping_44,
  148499. -1,
  148500. 50000,
  148501. 200000,
  148502. blocksize_short_44,
  148503. blocksize_long_44,
  148504. _psy_tone_masteratt_44,
  148505. _psy_tone_0dB,
  148506. _psy_tone_suppress,
  148507. _vp_tonemask_adj_otherblock,
  148508. _vp_tonemask_adj_longblock,
  148509. _vp_tonemask_adj_otherblock,
  148510. _psy_noiseguards_44,
  148511. _psy_noisebias_impulse,
  148512. _psy_noisebias_padding,
  148513. _psy_noisebias_trans,
  148514. _psy_noisebias_long,
  148515. _psy_noise_suppress,
  148516. _psy_compand_44,
  148517. _psy_compand_short_mapping,
  148518. _psy_compand_long_mapping,
  148519. {_noise_start_short_44,_noise_start_long_44},
  148520. {_noise_part_short_44,_noise_part_long_44},
  148521. _noise_thresh_44,
  148522. _psy_ath_floater,
  148523. _psy_ath_abs,
  148524. _psy_lowpass_44,
  148525. _psy_global_44,
  148526. _global_mapping_44,
  148527. NULL,
  148528. _floor_books,
  148529. _floor,
  148530. _floor_short_mapping_44,
  148531. _floor_long_mapping_44,
  148532. _mapres_template_44_uncoupled
  148533. };
  148534. ve_setup_data_template ve_setup_XX_stereo={
  148535. 2,
  148536. rate_mapping_X,
  148537. quality_mapping_8,
  148538. 2,
  148539. 0,
  148540. 8000,
  148541. blocksize_8,
  148542. blocksize_8,
  148543. _psy_tone_masteratt_8,
  148544. _psy_tone_0dB,
  148545. _psy_tone_suppress,
  148546. _vp_tonemask_adj_8,
  148547. NULL,
  148548. _vp_tonemask_adj_8,
  148549. _psy_noiseguards_8,
  148550. _psy_noisebias_8,
  148551. _psy_noisebias_8,
  148552. NULL,
  148553. NULL,
  148554. _psy_noise_suppress,
  148555. _psy_compand_8,
  148556. _psy_compand_8_mapping,
  148557. NULL,
  148558. {_noise_start_8,_noise_start_8},
  148559. {_noise_part_8,_noise_part_8},
  148560. _noise_thresh_5only,
  148561. _psy_ath_floater_8,
  148562. _psy_ath_abs_8,
  148563. _psy_lowpass_8,
  148564. _psy_global_44,
  148565. _global_mapping_8,
  148566. _psy_stereo_modes_8,
  148567. _floor_books,
  148568. _floor,
  148569. _floor_mapping_8,
  148570. NULL,
  148571. _mapres_template_8_stereo
  148572. };
  148573. ve_setup_data_template ve_setup_XX_uncoupled={
  148574. 2,
  148575. rate_mapping_X,
  148576. quality_mapping_8,
  148577. -1,
  148578. 0,
  148579. 8000,
  148580. blocksize_8,
  148581. blocksize_8,
  148582. _psy_tone_masteratt_8,
  148583. _psy_tone_0dB,
  148584. _psy_tone_suppress,
  148585. _vp_tonemask_adj_8,
  148586. NULL,
  148587. _vp_tonemask_adj_8,
  148588. _psy_noiseguards_8,
  148589. _psy_noisebias_8,
  148590. _psy_noisebias_8,
  148591. NULL,
  148592. NULL,
  148593. _psy_noise_suppress,
  148594. _psy_compand_8,
  148595. _psy_compand_8_mapping,
  148596. NULL,
  148597. {_noise_start_8,_noise_start_8},
  148598. {_noise_part_8,_noise_part_8},
  148599. _noise_thresh_5only,
  148600. _psy_ath_floater_8,
  148601. _psy_ath_abs_8,
  148602. _psy_lowpass_8,
  148603. _psy_global_44,
  148604. _global_mapping_8,
  148605. _psy_stereo_modes_8,
  148606. _floor_books,
  148607. _floor,
  148608. _floor_mapping_8,
  148609. NULL,
  148610. _mapres_template_8_uncoupled
  148611. };
  148612. /********* End of inlined file: setup_X.h *********/
  148613. static ve_setup_data_template *setup_list[]={
  148614. &ve_setup_44_stereo,
  148615. &ve_setup_44_uncoupled,
  148616. &ve_setup_32_stereo,
  148617. &ve_setup_32_uncoupled,
  148618. &ve_setup_22_stereo,
  148619. &ve_setup_22_uncoupled,
  148620. &ve_setup_16_stereo,
  148621. &ve_setup_16_uncoupled,
  148622. &ve_setup_11_stereo,
  148623. &ve_setup_11_uncoupled,
  148624. &ve_setup_8_stereo,
  148625. &ve_setup_8_uncoupled,
  148626. &ve_setup_X_stereo,
  148627. &ve_setup_X_uncoupled,
  148628. &ve_setup_XX_stereo,
  148629. &ve_setup_XX_uncoupled,
  148630. 0
  148631. };
  148632. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  148633. if(vi && vi->codec_setup){
  148634. vi->version=0;
  148635. vi->channels=ch;
  148636. vi->rate=rate;
  148637. return(0);
  148638. }
  148639. return(OV_EINVAL);
  148640. }
  148641. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  148642. static_codebook ***books,
  148643. vorbis_info_floor1 *in,
  148644. int *x){
  148645. int i,k,is=s;
  148646. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  148647. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148648. memcpy(f,in+x[is],sizeof(*f));
  148649. /* fill in the lowpass field, even if it's temporary */
  148650. f->n=ci->blocksizes[block]>>1;
  148651. /* books */
  148652. {
  148653. int partitions=f->partitions;
  148654. int maxclass=-1;
  148655. int maxbook=-1;
  148656. for(i=0;i<partitions;i++)
  148657. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  148658. for(i=0;i<=maxclass;i++){
  148659. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  148660. f->class_book[i]+=ci->books;
  148661. for(k=0;k<(1<<f->class_subs[i]);k++){
  148662. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  148663. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  148664. }
  148665. }
  148666. for(i=0;i<=maxbook;i++)
  148667. ci->book_param[ci->books++]=books[x[is]][i];
  148668. }
  148669. /* for now, we're only using floor 1 */
  148670. ci->floor_type[ci->floors]=1;
  148671. ci->floor_param[ci->floors]=f;
  148672. ci->floors++;
  148673. return;
  148674. }
  148675. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  148676. vorbis_info_psy_global *in,
  148677. double *x){
  148678. int i,is=s;
  148679. double ds=s-is;
  148680. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148681. vorbis_info_psy_global *g=&ci->psy_g_param;
  148682. memcpy(g,in+(int)x[is],sizeof(*g));
  148683. ds=x[is]*(1.-ds)+x[is+1]*ds;
  148684. is=(int)ds;
  148685. ds-=is;
  148686. if(ds==0 && is>0){
  148687. is--;
  148688. ds=1.;
  148689. }
  148690. /* interpolate the trigger threshholds */
  148691. for(i=0;i<4;i++){
  148692. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  148693. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  148694. }
  148695. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  148696. return;
  148697. }
  148698. static void vorbis_encode_global_stereo(vorbis_info *vi,
  148699. highlevel_encode_setup *hi,
  148700. adj_stereo *p){
  148701. float s=hi->stereo_point_setting;
  148702. int i,is=s;
  148703. double ds=s-is;
  148704. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148705. vorbis_info_psy_global *g=&ci->psy_g_param;
  148706. if(p){
  148707. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  148708. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  148709. if(hi->managed){
  148710. /* interpolate the kHz threshholds */
  148711. for(i=0;i<PACKETBLOBS;i++){
  148712. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  148713. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148714. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148715. g->coupling_pkHz[i]=kHz;
  148716. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  148717. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148718. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148719. }
  148720. }else{
  148721. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  148722. for(i=0;i<PACKETBLOBS;i++){
  148723. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148724. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148725. g->coupling_pkHz[i]=kHz;
  148726. }
  148727. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  148728. for(i=0;i<PACKETBLOBS;i++){
  148729. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148730. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148731. }
  148732. }
  148733. }else{
  148734. for(i=0;i<PACKETBLOBS;i++){
  148735. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  148736. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  148737. }
  148738. }
  148739. return;
  148740. }
  148741. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  148742. int *nn_start,
  148743. int *nn_partition,
  148744. double *nn_thresh,
  148745. int block){
  148746. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  148747. vorbis_info_psy *p=ci->psy_param[block];
  148748. highlevel_encode_setup *hi=&ci->hi;
  148749. int is=s;
  148750. if(block>=ci->psys)
  148751. ci->psys=block+1;
  148752. if(!p){
  148753. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  148754. ci->psy_param[block]=p;
  148755. }
  148756. memcpy(p,&_psy_info_template,sizeof(*p));
  148757. p->blockflag=block>>1;
  148758. if(hi->noise_normalize_p){
  148759. p->normal_channel_p=1;
  148760. p->normal_point_p=1;
  148761. p->normal_start=nn_start[is];
  148762. p->normal_partition=nn_partition[is];
  148763. p->normal_thresh=nn_thresh[is];
  148764. }
  148765. return;
  148766. }
  148767. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  148768. att3 *att,
  148769. int *max,
  148770. vp_adjblock *in){
  148771. int i,is=s;
  148772. double ds=s-is;
  148773. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  148774. vorbis_info_psy *p=ci->psy_param[block];
  148775. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  148776. filling the values in here */
  148777. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  148778. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  148779. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  148780. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  148781. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  148782. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  148783. for(i=0;i<P_BANDS;i++)
  148784. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  148785. return;
  148786. }
  148787. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  148788. compandblock *in, double *x){
  148789. int i,is=s;
  148790. double ds=s-is;
  148791. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148792. vorbis_info_psy *p=ci->psy_param[block];
  148793. ds=x[is]*(1.-ds)+x[is+1]*ds;
  148794. is=(int)ds;
  148795. ds-=is;
  148796. if(ds==0 && is>0){
  148797. is--;
  148798. ds=1.;
  148799. }
  148800. /* interpolate the compander settings */
  148801. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  148802. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  148803. return;
  148804. }
  148805. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  148806. int *suppress){
  148807. int is=s;
  148808. double ds=s-is;
  148809. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148810. vorbis_info_psy *p=ci->psy_param[block];
  148811. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  148812. return;
  148813. }
  148814. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  148815. int *suppress,
  148816. noise3 *in,
  148817. noiseguard *guard,
  148818. double userbias){
  148819. int i,is=s,j;
  148820. double ds=s-is;
  148821. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148822. vorbis_info_psy *p=ci->psy_param[block];
  148823. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  148824. p->noisewindowlomin=guard[block].lo;
  148825. p->noisewindowhimin=guard[block].hi;
  148826. p->noisewindowfixed=guard[block].fixed;
  148827. for(j=0;j<P_NOISECURVES;j++)
  148828. for(i=0;i<P_BANDS;i++)
  148829. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  148830. /* impulse blocks may take a user specified bias to boost the
  148831. nominal/high noise encoding depth */
  148832. for(j=0;j<P_NOISECURVES;j++){
  148833. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  148834. for(i=0;i<P_BANDS;i++){
  148835. p->noiseoff[j][i]+=userbias;
  148836. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  148837. }
  148838. }
  148839. return;
  148840. }
  148841. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  148842. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148843. vorbis_info_psy *p=ci->psy_param[block];
  148844. p->ath_adjatt=ci->hi.ath_floating_dB;
  148845. p->ath_maxatt=ci->hi.ath_absolute_dB;
  148846. return;
  148847. }
  148848. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  148849. int i;
  148850. for(i=0;i<ci->books;i++)
  148851. if(ci->book_param[i]==book)return(i);
  148852. return(ci->books++);
  148853. }
  148854. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  148855. int *shortb,int *longb){
  148856. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148857. int is=s;
  148858. int blockshort=shortb[is];
  148859. int blocklong=longb[is];
  148860. ci->blocksizes[0]=blockshort;
  148861. ci->blocksizes[1]=blocklong;
  148862. }
  148863. static void vorbis_encode_residue_setup(vorbis_info *vi,
  148864. int number, int block,
  148865. vorbis_residue_template *res){
  148866. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148867. int i,n;
  148868. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  148869. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  148870. memcpy(r,res->res,sizeof(*r));
  148871. if(ci->residues<=number)ci->residues=number+1;
  148872. switch(ci->blocksizes[block]){
  148873. case 64:case 128:case 256:
  148874. r->grouping=16;
  148875. break;
  148876. default:
  148877. r->grouping=32;
  148878. break;
  148879. }
  148880. ci->residue_type[number]=res->res_type;
  148881. /* to be adjusted by lowpass/pointlimit later */
  148882. n=r->end=ci->blocksizes[block]>>1;
  148883. if(res->res_type==2)
  148884. n=r->end*=vi->channels;
  148885. /* fill in all the books */
  148886. {
  148887. int booklist=0,k;
  148888. if(ci->hi.managed){
  148889. for(i=0;i<r->partitions;i++)
  148890. for(k=0;k<3;k++)
  148891. if(res->books_base_managed->books[i][k])
  148892. r->secondstages[i]|=(1<<k);
  148893. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  148894. ci->book_param[r->groupbook]=res->book_aux_managed;
  148895. for(i=0;i<r->partitions;i++){
  148896. for(k=0;k<3;k++){
  148897. if(res->books_base_managed->books[i][k]){
  148898. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  148899. r->booklist[booklist++]=bookid;
  148900. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  148901. }
  148902. }
  148903. }
  148904. }else{
  148905. for(i=0;i<r->partitions;i++)
  148906. for(k=0;k<3;k++)
  148907. if(res->books_base->books[i][k])
  148908. r->secondstages[i]|=(1<<k);
  148909. r->groupbook=book_dup_or_new(ci,res->book_aux);
  148910. ci->book_param[r->groupbook]=res->book_aux;
  148911. for(i=0;i<r->partitions;i++){
  148912. for(k=0;k<3;k++){
  148913. if(res->books_base->books[i][k]){
  148914. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  148915. r->booklist[booklist++]=bookid;
  148916. ci->book_param[bookid]=res->books_base->books[i][k];
  148917. }
  148918. }
  148919. }
  148920. }
  148921. }
  148922. /* lowpass setup/pointlimit */
  148923. {
  148924. double freq=ci->hi.lowpass_kHz*1000.;
  148925. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  148926. double nyq=vi->rate/2.;
  148927. long blocksize=ci->blocksizes[block]>>1;
  148928. /* lowpass needs to be set in the floor and the residue. */
  148929. if(freq>nyq)freq=nyq;
  148930. /* in the floor, the granularity can be very fine; it doesn't alter
  148931. the encoding structure, only the samples used to fit the floor
  148932. approximation */
  148933. f->n=freq/nyq*blocksize;
  148934. /* this res may by limited by the maximum pointlimit of the mode,
  148935. not the lowpass. the floor is always lowpass limited. */
  148936. if(res->limit_type){
  148937. if(ci->hi.managed)
  148938. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  148939. else
  148940. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  148941. if(freq>nyq)freq=nyq;
  148942. }
  148943. /* in the residue, we're constrained, physically, by partition
  148944. boundaries. We still lowpass 'wherever', but we have to round up
  148945. here to next boundary, or the vorbis spec will round it *down* to
  148946. previous boundary in encode/decode */
  148947. if(ci->residue_type[block]==2)
  148948. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  148949. r->grouping;
  148950. else
  148951. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  148952. r->grouping;
  148953. }
  148954. }
  148955. /* we assume two maps in this encoder */
  148956. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  148957. vorbis_mapping_template *maps){
  148958. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148959. int i,j,is=s,modes=2;
  148960. vorbis_info_mapping0 *map=maps[is].map;
  148961. vorbis_info_mode *mode=_mode_template;
  148962. vorbis_residue_template *res=maps[is].res;
  148963. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  148964. for(i=0;i<modes;i++){
  148965. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  148966. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  148967. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  148968. if(i>=ci->modes)ci->modes=i+1;
  148969. ci->map_type[i]=0;
  148970. memcpy(ci->map_param[i],map+i,sizeof(*map));
  148971. if(i>=ci->maps)ci->maps=i+1;
  148972. for(j=0;j<map[i].submaps;j++)
  148973. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  148974. ,res+map[i].residuesubmap[j]);
  148975. }
  148976. }
  148977. static double setting_to_approx_bitrate(vorbis_info *vi){
  148978. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148979. highlevel_encode_setup *hi=&ci->hi;
  148980. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  148981. int is=hi->base_setting;
  148982. double ds=hi->base_setting-is;
  148983. int ch=vi->channels;
  148984. double *r=setup->rate_mapping;
  148985. if(r==NULL)
  148986. return(-1);
  148987. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  148988. }
  148989. static void get_setup_template(vorbis_info *vi,
  148990. long ch,long srate,
  148991. double req,int q_or_bitrate){
  148992. int i=0,j;
  148993. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  148994. highlevel_encode_setup *hi=&ci->hi;
  148995. if(q_or_bitrate)req/=ch;
  148996. while(setup_list[i]){
  148997. if(setup_list[i]->coupling_restriction==-1 ||
  148998. setup_list[i]->coupling_restriction==ch){
  148999. if(srate>=setup_list[i]->samplerate_min_restriction &&
  149000. srate<=setup_list[i]->samplerate_max_restriction){
  149001. int mappings=setup_list[i]->mappings;
  149002. double *map=(q_or_bitrate?
  149003. setup_list[i]->rate_mapping:
  149004. setup_list[i]->quality_mapping);
  149005. /* the template matches. Does the requested quality mode
  149006. fall within this template's modes? */
  149007. if(req<map[0]){++i;continue;}
  149008. if(req>map[setup_list[i]->mappings]){++i;continue;}
  149009. for(j=0;j<mappings;j++)
  149010. if(req>=map[j] && req<map[j+1])break;
  149011. /* an all-points match */
  149012. hi->setup=setup_list[i];
  149013. if(j==mappings)
  149014. hi->base_setting=j-.001;
  149015. else{
  149016. float low=map[j];
  149017. float high=map[j+1];
  149018. float del=(req-low)/(high-low);
  149019. hi->base_setting=j+del;
  149020. }
  149021. return;
  149022. }
  149023. }
  149024. i++;
  149025. }
  149026. hi->setup=NULL;
  149027. }
  149028. /* encoders will need to use vorbis_info_init beforehand and call
  149029. vorbis_info clear when all done */
  149030. /* two interfaces; this, more detailed one, and later a convenience
  149031. layer on top */
  149032. /* the final setup call */
  149033. int vorbis_encode_setup_init(vorbis_info *vi){
  149034. int i0=0,singleblock=0;
  149035. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  149036. ve_setup_data_template *setup=NULL;
  149037. highlevel_encode_setup *hi=&ci->hi;
  149038. if(ci==NULL)return(OV_EINVAL);
  149039. if(!hi->impulse_block_p)i0=1;
  149040. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  149041. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  149042. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  149043. /* again, bound this to avoid the app shooting itself int he foot
  149044. too badly */
  149045. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  149046. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  149047. /* get the appropriate setup template; matches the fetch in previous
  149048. stages */
  149049. setup=(ve_setup_data_template *)hi->setup;
  149050. if(setup==NULL)return(OV_EINVAL);
  149051. hi->set_in_stone=1;
  149052. /* choose block sizes from configured sizes as well as paying
  149053. attention to long_block_p and short_block_p. If the configured
  149054. short and long blocks are the same length, we set long_block_p
  149055. and unset short_block_p */
  149056. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  149057. setup->blocksize_short,
  149058. setup->blocksize_long);
  149059. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  149060. /* floor setup; choose proper floor params. Allocated on the floor
  149061. stack in order; if we alloc only long floor, it's 0 */
  149062. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  149063. setup->floor_books,
  149064. setup->floor_params,
  149065. setup->floor_short_mapping);
  149066. if(!singleblock)
  149067. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  149068. setup->floor_books,
  149069. setup->floor_params,
  149070. setup->floor_long_mapping);
  149071. /* setup of [mostly] short block detection and stereo*/
  149072. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  149073. setup->global_params,
  149074. setup->global_mapping);
  149075. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  149076. /* basic psych setup and noise normalization */
  149077. vorbis_encode_psyset_setup(vi,hi->short_setting,
  149078. setup->psy_noise_normal_start[0],
  149079. setup->psy_noise_normal_partition[0],
  149080. setup->psy_noise_normal_thresh,
  149081. 0);
  149082. vorbis_encode_psyset_setup(vi,hi->short_setting,
  149083. setup->psy_noise_normal_start[0],
  149084. setup->psy_noise_normal_partition[0],
  149085. setup->psy_noise_normal_thresh,
  149086. 1);
  149087. if(!singleblock){
  149088. vorbis_encode_psyset_setup(vi,hi->long_setting,
  149089. setup->psy_noise_normal_start[1],
  149090. setup->psy_noise_normal_partition[1],
  149091. setup->psy_noise_normal_thresh,
  149092. 2);
  149093. vorbis_encode_psyset_setup(vi,hi->long_setting,
  149094. setup->psy_noise_normal_start[1],
  149095. setup->psy_noise_normal_partition[1],
  149096. setup->psy_noise_normal_thresh,
  149097. 3);
  149098. }
  149099. /* tone masking setup */
  149100. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  149101. setup->psy_tone_masteratt,
  149102. setup->psy_tone_0dB,
  149103. setup->psy_tone_adj_impulse);
  149104. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  149105. setup->psy_tone_masteratt,
  149106. setup->psy_tone_0dB,
  149107. setup->psy_tone_adj_other);
  149108. if(!singleblock){
  149109. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  149110. setup->psy_tone_masteratt,
  149111. setup->psy_tone_0dB,
  149112. setup->psy_tone_adj_other);
  149113. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  149114. setup->psy_tone_masteratt,
  149115. setup->psy_tone_0dB,
  149116. setup->psy_tone_adj_long);
  149117. }
  149118. /* noise companding setup */
  149119. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  149120. setup->psy_noise_compand,
  149121. setup->psy_noise_compand_short_mapping);
  149122. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  149123. setup->psy_noise_compand,
  149124. setup->psy_noise_compand_short_mapping);
  149125. if(!singleblock){
  149126. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  149127. setup->psy_noise_compand,
  149128. setup->psy_noise_compand_long_mapping);
  149129. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  149130. setup->psy_noise_compand,
  149131. setup->psy_noise_compand_long_mapping);
  149132. }
  149133. /* peak guarding setup */
  149134. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  149135. setup->psy_tone_dBsuppress);
  149136. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  149137. setup->psy_tone_dBsuppress);
  149138. if(!singleblock){
  149139. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  149140. setup->psy_tone_dBsuppress);
  149141. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  149142. setup->psy_tone_dBsuppress);
  149143. }
  149144. /* noise bias setup */
  149145. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  149146. setup->psy_noise_dBsuppress,
  149147. setup->psy_noise_bias_impulse,
  149148. setup->psy_noiseguards,
  149149. (i0==0?hi->impulse_noisetune:0.));
  149150. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  149151. setup->psy_noise_dBsuppress,
  149152. setup->psy_noise_bias_padding,
  149153. setup->psy_noiseguards,0.);
  149154. if(!singleblock){
  149155. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  149156. setup->psy_noise_dBsuppress,
  149157. setup->psy_noise_bias_trans,
  149158. setup->psy_noiseguards,0.);
  149159. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  149160. setup->psy_noise_dBsuppress,
  149161. setup->psy_noise_bias_long,
  149162. setup->psy_noiseguards,0.);
  149163. }
  149164. vorbis_encode_ath_setup(vi,0);
  149165. vorbis_encode_ath_setup(vi,1);
  149166. if(!singleblock){
  149167. vorbis_encode_ath_setup(vi,2);
  149168. vorbis_encode_ath_setup(vi,3);
  149169. }
  149170. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  149171. /* set bitrate readonlies and management */
  149172. if(hi->bitrate_av>0)
  149173. vi->bitrate_nominal=hi->bitrate_av;
  149174. else{
  149175. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  149176. }
  149177. vi->bitrate_lower=hi->bitrate_min;
  149178. vi->bitrate_upper=hi->bitrate_max;
  149179. if(hi->bitrate_av)
  149180. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  149181. else
  149182. vi->bitrate_window=0.;
  149183. if(hi->managed){
  149184. ci->bi.avg_rate=hi->bitrate_av;
  149185. ci->bi.min_rate=hi->bitrate_min;
  149186. ci->bi.max_rate=hi->bitrate_max;
  149187. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  149188. ci->bi.reservoir_bias=
  149189. hi->bitrate_reservoir_bias;
  149190. ci->bi.slew_damp=hi->bitrate_av_damp;
  149191. }
  149192. return(0);
  149193. }
  149194. static int vorbis_encode_setup_setting(vorbis_info *vi,
  149195. long channels,
  149196. long rate){
  149197. int ret=0,i,is;
  149198. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149199. highlevel_encode_setup *hi=&ci->hi;
  149200. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  149201. double ds;
  149202. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  149203. if(ret)return(ret);
  149204. is=hi->base_setting;
  149205. ds=hi->base_setting-is;
  149206. hi->short_setting=hi->base_setting;
  149207. hi->long_setting=hi->base_setting;
  149208. hi->managed=0;
  149209. hi->impulse_block_p=1;
  149210. hi->noise_normalize_p=1;
  149211. hi->stereo_point_setting=hi->base_setting;
  149212. hi->lowpass_kHz=
  149213. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  149214. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  149215. setup->psy_ath_float[is+1]*ds;
  149216. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  149217. setup->psy_ath_abs[is+1]*ds;
  149218. hi->amplitude_track_dBpersec=-6.;
  149219. hi->trigger_setting=hi->base_setting;
  149220. for(i=0;i<4;i++){
  149221. hi->block[i].tone_mask_setting=hi->base_setting;
  149222. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  149223. hi->block[i].noise_bias_setting=hi->base_setting;
  149224. hi->block[i].noise_compand_setting=hi->base_setting;
  149225. }
  149226. return(ret);
  149227. }
  149228. int vorbis_encode_setup_vbr(vorbis_info *vi,
  149229. long channels,
  149230. long rate,
  149231. float quality){
  149232. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  149233. highlevel_encode_setup *hi=&ci->hi;
  149234. quality+=.0000001;
  149235. if(quality>=1.)quality=.9999;
  149236. get_setup_template(vi,channels,rate,quality,0);
  149237. if(!hi->setup)return OV_EIMPL;
  149238. return vorbis_encode_setup_setting(vi,channels,rate);
  149239. }
  149240. int vorbis_encode_init_vbr(vorbis_info *vi,
  149241. long channels,
  149242. long rate,
  149243. float base_quality /* 0. to 1. */
  149244. ){
  149245. int ret=0;
  149246. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  149247. if(ret){
  149248. vorbis_info_clear(vi);
  149249. return ret;
  149250. }
  149251. ret=vorbis_encode_setup_init(vi);
  149252. if(ret)
  149253. vorbis_info_clear(vi);
  149254. return(ret);
  149255. }
  149256. int vorbis_encode_setup_managed(vorbis_info *vi,
  149257. long channels,
  149258. long rate,
  149259. long max_bitrate,
  149260. long nominal_bitrate,
  149261. long min_bitrate){
  149262. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149263. highlevel_encode_setup *hi=&ci->hi;
  149264. double tnominal=nominal_bitrate;
  149265. int ret=0;
  149266. if(nominal_bitrate<=0.){
  149267. if(max_bitrate>0.){
  149268. if(min_bitrate>0.)
  149269. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  149270. else
  149271. nominal_bitrate=max_bitrate*.875;
  149272. }else{
  149273. if(min_bitrate>0.){
  149274. nominal_bitrate=min_bitrate;
  149275. }else{
  149276. return(OV_EINVAL);
  149277. }
  149278. }
  149279. }
  149280. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  149281. if(!hi->setup)return OV_EIMPL;
  149282. ret=vorbis_encode_setup_setting(vi,channels,rate);
  149283. if(ret){
  149284. vorbis_info_clear(vi);
  149285. return ret;
  149286. }
  149287. /* initialize management with sane defaults */
  149288. hi->managed=1;
  149289. hi->bitrate_min=min_bitrate;
  149290. hi->bitrate_max=max_bitrate;
  149291. hi->bitrate_av=tnominal;
  149292. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  149293. hi->bitrate_reservoir=nominal_bitrate*2;
  149294. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  149295. return(ret);
  149296. }
  149297. int vorbis_encode_init(vorbis_info *vi,
  149298. long channels,
  149299. long rate,
  149300. long max_bitrate,
  149301. long nominal_bitrate,
  149302. long min_bitrate){
  149303. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  149304. max_bitrate,
  149305. nominal_bitrate,
  149306. min_bitrate);
  149307. if(ret){
  149308. vorbis_info_clear(vi);
  149309. return(ret);
  149310. }
  149311. ret=vorbis_encode_setup_init(vi);
  149312. if(ret)
  149313. vorbis_info_clear(vi);
  149314. return(ret);
  149315. }
  149316. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  149317. if(vi){
  149318. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149319. highlevel_encode_setup *hi=&ci->hi;
  149320. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  149321. if(setp && hi->set_in_stone)return(OV_EINVAL);
  149322. switch(number){
  149323. /* now deprecated *****************/
  149324. case OV_ECTL_RATEMANAGE_GET:
  149325. {
  149326. struct ovectl_ratemanage_arg *ai=
  149327. (struct ovectl_ratemanage_arg *)arg;
  149328. ai->management_active=hi->managed;
  149329. ai->bitrate_hard_window=ai->bitrate_av_window=
  149330. (double)hi->bitrate_reservoir/vi->rate;
  149331. ai->bitrate_av_window_center=1.;
  149332. ai->bitrate_hard_min=hi->bitrate_min;
  149333. ai->bitrate_hard_max=hi->bitrate_max;
  149334. ai->bitrate_av_lo=hi->bitrate_av;
  149335. ai->bitrate_av_hi=hi->bitrate_av;
  149336. }
  149337. return(0);
  149338. /* now deprecated *****************/
  149339. case OV_ECTL_RATEMANAGE_SET:
  149340. {
  149341. struct ovectl_ratemanage_arg *ai=
  149342. (struct ovectl_ratemanage_arg *)arg;
  149343. if(ai==NULL){
  149344. hi->managed=0;
  149345. }else{
  149346. hi->managed=ai->management_active;
  149347. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  149348. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  149349. }
  149350. }
  149351. return 0;
  149352. /* now deprecated *****************/
  149353. case OV_ECTL_RATEMANAGE_AVG:
  149354. {
  149355. struct ovectl_ratemanage_arg *ai=
  149356. (struct ovectl_ratemanage_arg *)arg;
  149357. if(ai==NULL){
  149358. hi->bitrate_av=0;
  149359. }else{
  149360. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  149361. }
  149362. }
  149363. return(0);
  149364. /* now deprecated *****************/
  149365. case OV_ECTL_RATEMANAGE_HARD:
  149366. {
  149367. struct ovectl_ratemanage_arg *ai=
  149368. (struct ovectl_ratemanage_arg *)arg;
  149369. if(ai==NULL){
  149370. hi->bitrate_min=0;
  149371. hi->bitrate_max=0;
  149372. }else{
  149373. hi->bitrate_min=ai->bitrate_hard_min;
  149374. hi->bitrate_max=ai->bitrate_hard_max;
  149375. hi->bitrate_reservoir=ai->bitrate_hard_window*
  149376. (hi->bitrate_max+hi->bitrate_min)*.5;
  149377. }
  149378. if(hi->bitrate_reservoir<128.)
  149379. hi->bitrate_reservoir=128.;
  149380. }
  149381. return(0);
  149382. /* replacement ratemanage interface */
  149383. case OV_ECTL_RATEMANAGE2_GET:
  149384. {
  149385. struct ovectl_ratemanage2_arg *ai=
  149386. (struct ovectl_ratemanage2_arg *)arg;
  149387. if(ai==NULL)return OV_EINVAL;
  149388. ai->management_active=hi->managed;
  149389. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  149390. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  149391. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  149392. ai->bitrate_average_damping=hi->bitrate_av_damp;
  149393. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  149394. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  149395. }
  149396. return (0);
  149397. case OV_ECTL_RATEMANAGE2_SET:
  149398. {
  149399. struct ovectl_ratemanage2_arg *ai=
  149400. (struct ovectl_ratemanage2_arg *)arg;
  149401. if(ai==NULL){
  149402. hi->managed=0;
  149403. }else{
  149404. /* sanity check; only catch invariant violations */
  149405. if(ai->bitrate_limit_min_kbps>0 &&
  149406. ai->bitrate_average_kbps>0 &&
  149407. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  149408. return OV_EINVAL;
  149409. if(ai->bitrate_limit_max_kbps>0 &&
  149410. ai->bitrate_average_kbps>0 &&
  149411. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  149412. return OV_EINVAL;
  149413. if(ai->bitrate_limit_min_kbps>0 &&
  149414. ai->bitrate_limit_max_kbps>0 &&
  149415. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  149416. return OV_EINVAL;
  149417. if(ai->bitrate_average_damping <= 0.)
  149418. return OV_EINVAL;
  149419. if(ai->bitrate_limit_reservoir_bits < 0)
  149420. return OV_EINVAL;
  149421. if(ai->bitrate_limit_reservoir_bias < 0.)
  149422. return OV_EINVAL;
  149423. if(ai->bitrate_limit_reservoir_bias > 1.)
  149424. return OV_EINVAL;
  149425. hi->managed=ai->management_active;
  149426. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  149427. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  149428. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  149429. hi->bitrate_av_damp=ai->bitrate_average_damping;
  149430. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  149431. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  149432. }
  149433. }
  149434. return 0;
  149435. case OV_ECTL_LOWPASS_GET:
  149436. {
  149437. double *farg=(double *)arg;
  149438. *farg=hi->lowpass_kHz;
  149439. }
  149440. return(0);
  149441. case OV_ECTL_LOWPASS_SET:
  149442. {
  149443. double *farg=(double *)arg;
  149444. hi->lowpass_kHz=*farg;
  149445. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  149446. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  149447. }
  149448. return(0);
  149449. case OV_ECTL_IBLOCK_GET:
  149450. {
  149451. double *farg=(double *)arg;
  149452. *farg=hi->impulse_noisetune;
  149453. }
  149454. return(0);
  149455. case OV_ECTL_IBLOCK_SET:
  149456. {
  149457. double *farg=(double *)arg;
  149458. hi->impulse_noisetune=*farg;
  149459. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  149460. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  149461. }
  149462. return(0);
  149463. }
  149464. return(OV_EIMPL);
  149465. }
  149466. return(OV_EINVAL);
  149467. }
  149468. #endif
  149469. /********* End of inlined file: vorbisenc.c *********/
  149470. /********* Start of inlined file: vorbisfile.c *********/
  149471. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  149472. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  149473. // tasks..
  149474. #ifdef _MSC_VER
  149475. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  149476. #endif
  149477. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  149478. #if JUCE_USE_OGGVORBIS
  149479. #include <stdlib.h>
  149480. #include <stdio.h>
  149481. #include <errno.h>
  149482. #include <string.h>
  149483. #include <math.h>
  149484. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  149485. one logical bitstream arranged end to end (the only form of Ogg
  149486. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  149487. multiplexing] is not allowed in Vorbis) */
  149488. /* A Vorbis file can be played beginning to end (streamed) without
  149489. worrying ahead of time about chaining (see decoder_example.c). If
  149490. we have the whole file, however, and want random access
  149491. (seeking/scrubbing) or desire to know the total length/time of a
  149492. file, we need to account for the possibility of chaining. */
  149493. /* We can handle things a number of ways; we can determine the entire
  149494. bitstream structure right off the bat, or find pieces on demand.
  149495. This example determines and caches structure for the entire
  149496. bitstream, but builds a virtual decoder on the fly when moving
  149497. between links in the chain. */
  149498. /* There are also different ways to implement seeking. Enough
  149499. information exists in an Ogg bitstream to seek to
  149500. sample-granularity positions in the output. Or, one can seek by
  149501. picking some portion of the stream roughly in the desired area if
  149502. we only want coarse navigation through the stream. */
  149503. /*************************************************************************
  149504. * Many, many internal helpers. The intention is not to be confusing;
  149505. * rampant duplication and monolithic function implementation would be
  149506. * harder to understand anyway. The high level functions are last. Begin
  149507. * grokking near the end of the file */
  149508. /* read a little more data from the file/pipe into the ogg_sync framer
  149509. */
  149510. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  149511. over 8k gets what they deserve */
  149512. static long _get_data(OggVorbis_File *vf){
  149513. errno=0;
  149514. if(vf->datasource){
  149515. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  149516. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  149517. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  149518. if(bytes==0 && errno)return(-1);
  149519. return(bytes);
  149520. }else
  149521. return(0);
  149522. }
  149523. /* save a tiny smidge of verbosity to make the code more readable */
  149524. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  149525. if(vf->datasource){
  149526. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  149527. vf->offset=offset;
  149528. ogg_sync_reset(&vf->oy);
  149529. }else{
  149530. /* shouldn't happen unless someone writes a broken callback */
  149531. return;
  149532. }
  149533. }
  149534. /* The read/seek functions track absolute position within the stream */
  149535. /* from the head of the stream, get the next page. boundary specifies
  149536. if the function is allowed to fetch more data from the stream (and
  149537. how much) or only use internally buffered data.
  149538. boundary: -1) unbounded search
  149539. 0) read no additional data; use cached only
  149540. n) search for a new page beginning for n bytes
  149541. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  149542. n) found a page at absolute offset n */
  149543. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  149544. ogg_int64_t boundary){
  149545. if(boundary>0)boundary+=vf->offset;
  149546. while(1){
  149547. long more;
  149548. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  149549. more=ogg_sync_pageseek(&vf->oy,og);
  149550. if(more<0){
  149551. /* skipped n bytes */
  149552. vf->offset-=more;
  149553. }else{
  149554. if(more==0){
  149555. /* send more paramedics */
  149556. if(!boundary)return(OV_FALSE);
  149557. {
  149558. long ret=_get_data(vf);
  149559. if(ret==0)return(OV_EOF);
  149560. if(ret<0)return(OV_EREAD);
  149561. }
  149562. }else{
  149563. /* got a page. Return the offset at the page beginning,
  149564. advance the internal offset past the page end */
  149565. ogg_int64_t ret=vf->offset;
  149566. vf->offset+=more;
  149567. return(ret);
  149568. }
  149569. }
  149570. }
  149571. }
  149572. /* find the latest page beginning before the current stream cursor
  149573. position. Much dirtier than the above as Ogg doesn't have any
  149574. backward search linkage. no 'readp' as it will certainly have to
  149575. read. */
  149576. /* returns offset or OV_EREAD, OV_FAULT */
  149577. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  149578. ogg_int64_t begin=vf->offset;
  149579. ogg_int64_t end=begin;
  149580. ogg_int64_t ret;
  149581. ogg_int64_t offset=-1;
  149582. while(offset==-1){
  149583. begin-=CHUNKSIZE;
  149584. if(begin<0)
  149585. begin=0;
  149586. _seek_helper(vf,begin);
  149587. while(vf->offset<end){
  149588. ret=_get_next_page(vf,og,end-vf->offset);
  149589. if(ret==OV_EREAD)return(OV_EREAD);
  149590. if(ret<0){
  149591. break;
  149592. }else{
  149593. offset=ret;
  149594. }
  149595. }
  149596. }
  149597. /* we have the offset. Actually snork and hold the page now */
  149598. _seek_helper(vf,offset);
  149599. ret=_get_next_page(vf,og,CHUNKSIZE);
  149600. if(ret<0)
  149601. /* this shouldn't be possible */
  149602. return(OV_EFAULT);
  149603. return(offset);
  149604. }
  149605. /* finds each bitstream link one at a time using a bisection search
  149606. (has to begin by knowing the offset of the lb's initial page).
  149607. Recurses for each link so it can alloc the link storage after
  149608. finding them all, then unroll and fill the cache at the same time */
  149609. static int _bisect_forward_serialno(OggVorbis_File *vf,
  149610. ogg_int64_t begin,
  149611. ogg_int64_t searched,
  149612. ogg_int64_t end,
  149613. long currentno,
  149614. long m){
  149615. ogg_int64_t endsearched=end;
  149616. ogg_int64_t next=end;
  149617. ogg_page og;
  149618. ogg_int64_t ret;
  149619. /* the below guards against garbage seperating the last and
  149620. first pages of two links. */
  149621. while(searched<endsearched){
  149622. ogg_int64_t bisect;
  149623. if(endsearched-searched<CHUNKSIZE){
  149624. bisect=searched;
  149625. }else{
  149626. bisect=(searched+endsearched)/2;
  149627. }
  149628. _seek_helper(vf,bisect);
  149629. ret=_get_next_page(vf,&og,-1);
  149630. if(ret==OV_EREAD)return(OV_EREAD);
  149631. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  149632. endsearched=bisect;
  149633. if(ret>=0)next=ret;
  149634. }else{
  149635. searched=ret+og.header_len+og.body_len;
  149636. }
  149637. }
  149638. _seek_helper(vf,next);
  149639. ret=_get_next_page(vf,&og,-1);
  149640. if(ret==OV_EREAD)return(OV_EREAD);
  149641. if(searched>=end || ret<0){
  149642. vf->links=m+1;
  149643. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  149644. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  149645. vf->offsets[m+1]=searched;
  149646. }else{
  149647. ret=_bisect_forward_serialno(vf,next,vf->offset,
  149648. end,ogg_page_serialno(&og),m+1);
  149649. if(ret==OV_EREAD)return(OV_EREAD);
  149650. }
  149651. vf->offsets[m]=begin;
  149652. vf->serialnos[m]=currentno;
  149653. return(0);
  149654. }
  149655. /* uses the local ogg_stream storage in vf; this is important for
  149656. non-streaming input sources */
  149657. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  149658. long *serialno,ogg_page *og_ptr){
  149659. ogg_page og;
  149660. ogg_packet op;
  149661. int i,ret;
  149662. if(!og_ptr){
  149663. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  149664. if(llret==OV_EREAD)return(OV_EREAD);
  149665. if(llret<0)return OV_ENOTVORBIS;
  149666. og_ptr=&og;
  149667. }
  149668. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  149669. if(serialno)*serialno=vf->os.serialno;
  149670. vf->ready_state=STREAMSET;
  149671. /* extract the initial header from the first page and verify that the
  149672. Ogg bitstream is in fact Vorbis data */
  149673. vorbis_info_init(vi);
  149674. vorbis_comment_init(vc);
  149675. i=0;
  149676. while(i<3){
  149677. ogg_stream_pagein(&vf->os,og_ptr);
  149678. while(i<3){
  149679. int result=ogg_stream_packetout(&vf->os,&op);
  149680. if(result==0)break;
  149681. if(result==-1){
  149682. ret=OV_EBADHEADER;
  149683. goto bail_header;
  149684. }
  149685. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  149686. goto bail_header;
  149687. }
  149688. i++;
  149689. }
  149690. if(i<3)
  149691. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  149692. ret=OV_EBADHEADER;
  149693. goto bail_header;
  149694. }
  149695. }
  149696. return 0;
  149697. bail_header:
  149698. vorbis_info_clear(vi);
  149699. vorbis_comment_clear(vc);
  149700. vf->ready_state=OPENED;
  149701. return ret;
  149702. }
  149703. /* last step of the OggVorbis_File initialization; get all the
  149704. vorbis_info structs and PCM positions. Only called by the seekable
  149705. initialization (local stream storage is hacked slightly; pay
  149706. attention to how that's done) */
  149707. /* this is void and does not propogate errors up because we want to be
  149708. able to open and use damaged bitstreams as well as we can. Just
  149709. watch out for missing information for links in the OggVorbis_File
  149710. struct */
  149711. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  149712. ogg_page og;
  149713. int i;
  149714. ogg_int64_t ret;
  149715. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  149716. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  149717. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  149718. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  149719. for(i=0;i<vf->links;i++){
  149720. if(i==0){
  149721. /* we already grabbed the initial header earlier. Just set the offset */
  149722. vf->dataoffsets[i]=dataoffset;
  149723. _seek_helper(vf,dataoffset);
  149724. }else{
  149725. /* seek to the location of the initial header */
  149726. _seek_helper(vf,vf->offsets[i]);
  149727. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  149728. vf->dataoffsets[i]=-1;
  149729. }else{
  149730. vf->dataoffsets[i]=vf->offset;
  149731. }
  149732. }
  149733. /* fetch beginning PCM offset */
  149734. if(vf->dataoffsets[i]!=-1){
  149735. ogg_int64_t accumulated=0;
  149736. long lastblock=-1;
  149737. int result;
  149738. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  149739. while(1){
  149740. ogg_packet op;
  149741. ret=_get_next_page(vf,&og,-1);
  149742. if(ret<0)
  149743. /* this should not be possible unless the file is
  149744. truncated/mangled */
  149745. break;
  149746. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  149747. break;
  149748. /* count blocksizes of all frames in the page */
  149749. ogg_stream_pagein(&vf->os,&og);
  149750. while((result=ogg_stream_packetout(&vf->os,&op))){
  149751. if(result>0){ /* ignore holes */
  149752. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  149753. if(lastblock!=-1)
  149754. accumulated+=(lastblock+thisblock)>>2;
  149755. lastblock=thisblock;
  149756. }
  149757. }
  149758. if(ogg_page_granulepos(&og)!=-1){
  149759. /* pcm offset of last packet on the first audio page */
  149760. accumulated= ogg_page_granulepos(&og)-accumulated;
  149761. break;
  149762. }
  149763. }
  149764. /* less than zero? This is a stream with samples trimmed off
  149765. the beginning, a normal occurrence; set the offset to zero */
  149766. if(accumulated<0)accumulated=0;
  149767. vf->pcmlengths[i*2]=accumulated;
  149768. }
  149769. /* get the PCM length of this link. To do this,
  149770. get the last page of the stream */
  149771. {
  149772. ogg_int64_t end=vf->offsets[i+1];
  149773. _seek_helper(vf,end);
  149774. while(1){
  149775. ret=_get_prev_page(vf,&og);
  149776. if(ret<0){
  149777. /* this should not be possible */
  149778. vorbis_info_clear(vf->vi+i);
  149779. vorbis_comment_clear(vf->vc+i);
  149780. break;
  149781. }
  149782. if(ogg_page_granulepos(&og)!=-1){
  149783. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  149784. break;
  149785. }
  149786. vf->offset=ret;
  149787. }
  149788. }
  149789. }
  149790. }
  149791. static int _make_decode_ready(OggVorbis_File *vf){
  149792. if(vf->ready_state>STREAMSET)return 0;
  149793. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  149794. if(vf->seekable){
  149795. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  149796. return OV_EBADLINK;
  149797. }else{
  149798. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  149799. return OV_EBADLINK;
  149800. }
  149801. vorbis_block_init(&vf->vd,&vf->vb);
  149802. vf->ready_state=INITSET;
  149803. vf->bittrack=0.f;
  149804. vf->samptrack=0.f;
  149805. return 0;
  149806. }
  149807. static int _open_seekable2(OggVorbis_File *vf){
  149808. long serialno=vf->current_serialno;
  149809. ogg_int64_t dataoffset=vf->offset, end;
  149810. ogg_page og;
  149811. /* we're partially open and have a first link header state in
  149812. storage in vf */
  149813. /* we can seek, so set out learning all about this file */
  149814. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  149815. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  149816. /* We get the offset for the last page of the physical bitstream.
  149817. Most OggVorbis files will contain a single logical bitstream */
  149818. end=_get_prev_page(vf,&og);
  149819. if(end<0)return(end);
  149820. /* more than one logical bitstream? */
  149821. if(ogg_page_serialno(&og)!=serialno){
  149822. /* Chained bitstream. Bisect-search each logical bitstream
  149823. section. Do so based on serial number only */
  149824. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  149825. }else{
  149826. /* Only one logical bitstream */
  149827. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  149828. }
  149829. /* the initial header memory is referenced by vf after; don't free it */
  149830. _prefetch_all_headers(vf,dataoffset);
  149831. return(ov_raw_seek(vf,0));
  149832. }
  149833. /* clear out the current logical bitstream decoder */
  149834. static void _decode_clear(OggVorbis_File *vf){
  149835. vorbis_dsp_clear(&vf->vd);
  149836. vorbis_block_clear(&vf->vb);
  149837. vf->ready_state=OPENED;
  149838. }
  149839. /* fetch and process a packet. Handles the case where we're at a
  149840. bitstream boundary and dumps the decoding machine. If the decoding
  149841. machine is unloaded, it loads it. It also keeps pcm_offset up to
  149842. date (seek and read both use this. seek uses a special hack with
  149843. readp).
  149844. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  149845. 0) need more data (only if readp==0)
  149846. 1) got a packet
  149847. */
  149848. static int _fetch_and_process_packet(OggVorbis_File *vf,
  149849. ogg_packet *op_in,
  149850. int readp,
  149851. int spanp){
  149852. ogg_page og;
  149853. /* handle one packet. Try to fetch it from current stream state */
  149854. /* extract packets from page */
  149855. while(1){
  149856. /* process a packet if we can. If the machine isn't loaded,
  149857. neither is a page */
  149858. if(vf->ready_state==INITSET){
  149859. while(1) {
  149860. ogg_packet op;
  149861. ogg_packet *op_ptr=(op_in?op_in:&op);
  149862. int result=ogg_stream_packetout(&vf->os,op_ptr);
  149863. ogg_int64_t granulepos;
  149864. op_in=NULL;
  149865. if(result==-1)return(OV_HOLE); /* hole in the data. */
  149866. if(result>0){
  149867. /* got a packet. process it */
  149868. granulepos=op_ptr->granulepos;
  149869. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  149870. header handling. The
  149871. header packets aren't
  149872. audio, so if/when we
  149873. submit them,
  149874. vorbis_synthesis will
  149875. reject them */
  149876. /* suck in the synthesis data and track bitrate */
  149877. {
  149878. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  149879. /* for proper use of libvorbis within libvorbisfile,
  149880. oldsamples will always be zero. */
  149881. if(oldsamples)return(OV_EFAULT);
  149882. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  149883. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  149884. vf->bittrack+=op_ptr->bytes*8;
  149885. }
  149886. /* update the pcm offset. */
  149887. if(granulepos!=-1 && !op_ptr->e_o_s){
  149888. int link=(vf->seekable?vf->current_link:0);
  149889. int i,samples;
  149890. /* this packet has a pcm_offset on it (the last packet
  149891. completed on a page carries the offset) After processing
  149892. (above), we know the pcm position of the *last* sample
  149893. ready to be returned. Find the offset of the *first*
  149894. As an aside, this trick is inaccurate if we begin
  149895. reading anew right at the last page; the end-of-stream
  149896. granulepos declares the last frame in the stream, and the
  149897. last packet of the last page may be a partial frame.
  149898. So, we need a previous granulepos from an in-sequence page
  149899. to have a reference point. Thus the !op_ptr->e_o_s clause
  149900. above */
  149901. if(vf->seekable && link>0)
  149902. granulepos-=vf->pcmlengths[link*2];
  149903. if(granulepos<0)granulepos=0; /* actually, this
  149904. shouldn't be possible
  149905. here unless the stream
  149906. is very broken */
  149907. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  149908. granulepos-=samples;
  149909. for(i=0;i<link;i++)
  149910. granulepos+=vf->pcmlengths[i*2+1];
  149911. vf->pcm_offset=granulepos;
  149912. }
  149913. return(1);
  149914. }
  149915. }
  149916. else
  149917. break;
  149918. }
  149919. }
  149920. if(vf->ready_state>=OPENED){
  149921. ogg_int64_t ret;
  149922. if(!readp)return(0);
  149923. if((ret=_get_next_page(vf,&og,-1))<0){
  149924. return(OV_EOF); /* eof.
  149925. leave unitialized */
  149926. }
  149927. /* bitrate tracking; add the header's bytes here, the body bytes
  149928. are done by packet above */
  149929. vf->bittrack+=og.header_len*8;
  149930. /* has our decoding just traversed a bitstream boundary? */
  149931. if(vf->ready_state==INITSET){
  149932. if(vf->current_serialno!=ogg_page_serialno(&og)){
  149933. if(!spanp)
  149934. return(OV_EOF);
  149935. _decode_clear(vf);
  149936. if(!vf->seekable){
  149937. vorbis_info_clear(vf->vi);
  149938. vorbis_comment_clear(vf->vc);
  149939. }
  149940. }
  149941. }
  149942. }
  149943. /* Do we need to load a new machine before submitting the page? */
  149944. /* This is different in the seekable and non-seekable cases.
  149945. In the seekable case, we already have all the header
  149946. information loaded and cached; we just initialize the machine
  149947. with it and continue on our merry way.
  149948. In the non-seekable (streaming) case, we'll only be at a
  149949. boundary if we just left the previous logical bitstream and
  149950. we're now nominally at the header of the next bitstream
  149951. */
  149952. if(vf->ready_state!=INITSET){
  149953. int link;
  149954. if(vf->ready_state<STREAMSET){
  149955. if(vf->seekable){
  149956. vf->current_serialno=ogg_page_serialno(&og);
  149957. /* match the serialno to bitstream section. We use this rather than
  149958. offset positions to avoid problems near logical bitstream
  149959. boundaries */
  149960. for(link=0;link<vf->links;link++)
  149961. if(vf->serialnos[link]==vf->current_serialno)break;
  149962. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  149963. stream. error out,
  149964. leave machine
  149965. uninitialized */
  149966. vf->current_link=link;
  149967. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  149968. vf->ready_state=STREAMSET;
  149969. }else{
  149970. /* we're streaming */
  149971. /* fetch the three header packets, build the info struct */
  149972. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  149973. if(ret)return(ret);
  149974. vf->current_link++;
  149975. link=0;
  149976. }
  149977. }
  149978. {
  149979. int ret=_make_decode_ready(vf);
  149980. if(ret<0)return ret;
  149981. }
  149982. }
  149983. ogg_stream_pagein(&vf->os,&og);
  149984. }
  149985. }
  149986. /* if, eg, 64 bit stdio is configured by default, this will build with
  149987. fseek64 */
  149988. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  149989. if(f==NULL)return(-1);
  149990. return fseek(f,off,whence);
  149991. }
  149992. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  149993. long ibytes, ov_callbacks callbacks){
  149994. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  149995. int ret;
  149996. memset(vf,0,sizeof(*vf));
  149997. vf->datasource=f;
  149998. vf->callbacks = callbacks;
  149999. /* init the framing state */
  150000. ogg_sync_init(&vf->oy);
  150001. /* perhaps some data was previously read into a buffer for testing
  150002. against other stream types. Allow initialization from this
  150003. previously read data (as we may be reading from a non-seekable
  150004. stream) */
  150005. if(initial){
  150006. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  150007. memcpy(buffer,initial,ibytes);
  150008. ogg_sync_wrote(&vf->oy,ibytes);
  150009. }
  150010. /* can we seek? Stevens suggests the seek test was portable */
  150011. if(offsettest!=-1)vf->seekable=1;
  150012. /* No seeking yet; Set up a 'single' (current) logical bitstream
  150013. entry for partial open */
  150014. vf->links=1;
  150015. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  150016. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  150017. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  150018. /* Try to fetch the headers, maintaining all the storage */
  150019. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  150020. vf->datasource=NULL;
  150021. ov_clear(vf);
  150022. }else
  150023. vf->ready_state=PARTOPEN;
  150024. return(ret);
  150025. }
  150026. static int _ov_open2(OggVorbis_File *vf){
  150027. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  150028. vf->ready_state=OPENED;
  150029. if(vf->seekable){
  150030. int ret=_open_seekable2(vf);
  150031. if(ret){
  150032. vf->datasource=NULL;
  150033. ov_clear(vf);
  150034. }
  150035. return(ret);
  150036. }else
  150037. vf->ready_state=STREAMSET;
  150038. return 0;
  150039. }
  150040. /* clear out the OggVorbis_File struct */
  150041. int ov_clear(OggVorbis_File *vf){
  150042. if(vf){
  150043. vorbis_block_clear(&vf->vb);
  150044. vorbis_dsp_clear(&vf->vd);
  150045. ogg_stream_clear(&vf->os);
  150046. if(vf->vi && vf->links){
  150047. int i;
  150048. for(i=0;i<vf->links;i++){
  150049. vorbis_info_clear(vf->vi+i);
  150050. vorbis_comment_clear(vf->vc+i);
  150051. }
  150052. _ogg_free(vf->vi);
  150053. _ogg_free(vf->vc);
  150054. }
  150055. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  150056. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  150057. if(vf->serialnos)_ogg_free(vf->serialnos);
  150058. if(vf->offsets)_ogg_free(vf->offsets);
  150059. ogg_sync_clear(&vf->oy);
  150060. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  150061. memset(vf,0,sizeof(*vf));
  150062. }
  150063. #ifdef DEBUG_LEAKS
  150064. _VDBG_dump();
  150065. #endif
  150066. return(0);
  150067. }
  150068. /* inspects the OggVorbis file and finds/documents all the logical
  150069. bitstreams contained in it. Tries to be tolerant of logical
  150070. bitstream sections that are truncated/woogie.
  150071. return: -1) error
  150072. 0) OK
  150073. */
  150074. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  150075. ov_callbacks callbacks){
  150076. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  150077. if(ret)return ret;
  150078. return _ov_open2(vf);
  150079. }
  150080. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  150081. ov_callbacks callbacks = {
  150082. (size_t (*)(void *, size_t, size_t, void *)) fread,
  150083. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  150084. (int (*)(void *)) fclose,
  150085. (long (*)(void *)) ftell
  150086. };
  150087. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  150088. }
  150089. /* cheap hack for game usage where downsampling is desirable; there's
  150090. no need for SRC as we can just do it cheaply in libvorbis. */
  150091. int ov_halfrate(OggVorbis_File *vf,int flag){
  150092. int i;
  150093. if(vf->vi==NULL)return OV_EINVAL;
  150094. if(!vf->seekable)return OV_EINVAL;
  150095. if(vf->ready_state>=STREAMSET)
  150096. _decode_clear(vf); /* clear out stream state; later on libvorbis
  150097. will be able to swap this on the fly, but
  150098. for now dumping the decode machine is needed
  150099. to reinit the MDCT lookups. 1.1 libvorbis
  150100. is planned to be able to switch on the fly */
  150101. for(i=0;i<vf->links;i++){
  150102. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  150103. ov_halfrate(vf,0);
  150104. return OV_EINVAL;
  150105. }
  150106. }
  150107. return 0;
  150108. }
  150109. int ov_halfrate_p(OggVorbis_File *vf){
  150110. if(vf->vi==NULL)return OV_EINVAL;
  150111. return vorbis_synthesis_halfrate_p(vf->vi);
  150112. }
  150113. /* Only partially open the vorbis file; test for Vorbisness, and load
  150114. the headers for the first chain. Do not seek (although test for
  150115. seekability). Use ov_test_open to finish opening the file, else
  150116. ov_clear to close/free it. Same return codes as open. */
  150117. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  150118. ov_callbacks callbacks)
  150119. {
  150120. return _ov_open1(f,vf,initial,ibytes,callbacks);
  150121. }
  150122. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  150123. ov_callbacks callbacks = {
  150124. (size_t (*)(void *, size_t, size_t, void *)) fread,
  150125. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  150126. (int (*)(void *)) fclose,
  150127. (long (*)(void *)) ftell
  150128. };
  150129. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  150130. }
  150131. int ov_test_open(OggVorbis_File *vf){
  150132. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  150133. return _ov_open2(vf);
  150134. }
  150135. /* How many logical bitstreams in this physical bitstream? */
  150136. long ov_streams(OggVorbis_File *vf){
  150137. return vf->links;
  150138. }
  150139. /* Is the FILE * associated with vf seekable? */
  150140. long ov_seekable(OggVorbis_File *vf){
  150141. return vf->seekable;
  150142. }
  150143. /* returns the bitrate for a given logical bitstream or the entire
  150144. physical bitstream. If the file is open for random access, it will
  150145. find the *actual* average bitrate. If the file is streaming, it
  150146. returns the nominal bitrate (if set) else the average of the
  150147. upper/lower bounds (if set) else -1 (unset).
  150148. If you want the actual bitrate field settings, get them from the
  150149. vorbis_info structs */
  150150. long ov_bitrate(OggVorbis_File *vf,int i){
  150151. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150152. if(i>=vf->links)return(OV_EINVAL);
  150153. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  150154. if(i<0){
  150155. ogg_int64_t bits=0;
  150156. int i;
  150157. float br;
  150158. for(i=0;i<vf->links;i++)
  150159. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  150160. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  150161. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  150162. * so this is slightly transformed to make it work.
  150163. */
  150164. br = bits/ov_time_total(vf,-1);
  150165. return(rint(br));
  150166. }else{
  150167. if(vf->seekable){
  150168. /* return the actual bitrate */
  150169. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  150170. }else{
  150171. /* return nominal if set */
  150172. if(vf->vi[i].bitrate_nominal>0){
  150173. return vf->vi[i].bitrate_nominal;
  150174. }else{
  150175. if(vf->vi[i].bitrate_upper>0){
  150176. if(vf->vi[i].bitrate_lower>0){
  150177. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  150178. }else{
  150179. return vf->vi[i].bitrate_upper;
  150180. }
  150181. }
  150182. return(OV_FALSE);
  150183. }
  150184. }
  150185. }
  150186. }
  150187. /* returns the actual bitrate since last call. returns -1 if no
  150188. additional data to offer since last call (or at beginning of stream),
  150189. EINVAL if stream is only partially open
  150190. */
  150191. long ov_bitrate_instant(OggVorbis_File *vf){
  150192. int link=(vf->seekable?vf->current_link:0);
  150193. long ret;
  150194. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150195. if(vf->samptrack==0)return(OV_FALSE);
  150196. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  150197. vf->bittrack=0.f;
  150198. vf->samptrack=0.f;
  150199. return(ret);
  150200. }
  150201. /* Guess */
  150202. long ov_serialnumber(OggVorbis_File *vf,int i){
  150203. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  150204. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  150205. if(i<0){
  150206. return(vf->current_serialno);
  150207. }else{
  150208. return(vf->serialnos[i]);
  150209. }
  150210. }
  150211. /* returns: total raw (compressed) length of content if i==-1
  150212. raw (compressed) length of that logical bitstream for i==0 to n
  150213. OV_EINVAL if the stream is not seekable (we can't know the length)
  150214. or if stream is only partially open
  150215. */
  150216. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  150217. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150218. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  150219. if(i<0){
  150220. ogg_int64_t acc=0;
  150221. int i;
  150222. for(i=0;i<vf->links;i++)
  150223. acc+=ov_raw_total(vf,i);
  150224. return(acc);
  150225. }else{
  150226. return(vf->offsets[i+1]-vf->offsets[i]);
  150227. }
  150228. }
  150229. /* returns: total PCM length (samples) of content if i==-1 PCM length
  150230. (samples) of that logical bitstream for i==0 to n
  150231. OV_EINVAL if the stream is not seekable (we can't know the
  150232. length) or only partially open
  150233. */
  150234. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  150235. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150236. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  150237. if(i<0){
  150238. ogg_int64_t acc=0;
  150239. int i;
  150240. for(i=0;i<vf->links;i++)
  150241. acc+=ov_pcm_total(vf,i);
  150242. return(acc);
  150243. }else{
  150244. return(vf->pcmlengths[i*2+1]);
  150245. }
  150246. }
  150247. /* returns: total seconds of content if i==-1
  150248. seconds in that logical bitstream for i==0 to n
  150249. OV_EINVAL if the stream is not seekable (we can't know the
  150250. length) or only partially open
  150251. */
  150252. double ov_time_total(OggVorbis_File *vf,int i){
  150253. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150254. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  150255. if(i<0){
  150256. double acc=0;
  150257. int i;
  150258. for(i=0;i<vf->links;i++)
  150259. acc+=ov_time_total(vf,i);
  150260. return(acc);
  150261. }else{
  150262. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  150263. }
  150264. }
  150265. /* seek to an offset relative to the *compressed* data. This also
  150266. scans packets to update the PCM cursor. It will cross a logical
  150267. bitstream boundary, but only if it can't get any packets out of the
  150268. tail of the bitstream we seek to (so no surprises).
  150269. returns zero on success, nonzero on failure */
  150270. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  150271. ogg_stream_state work_os;
  150272. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150273. if(!vf->seekable)
  150274. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  150275. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  150276. /* don't yet clear out decoding machine (if it's initialized), in
  150277. the case we're in the same link. Restart the decode lapping, and
  150278. let _fetch_and_process_packet deal with a potential bitstream
  150279. boundary */
  150280. vf->pcm_offset=-1;
  150281. ogg_stream_reset_serialno(&vf->os,
  150282. vf->current_serialno); /* must set serialno */
  150283. vorbis_synthesis_restart(&vf->vd);
  150284. _seek_helper(vf,pos);
  150285. /* we need to make sure the pcm_offset is set, but we don't want to
  150286. advance the raw cursor past good packets just to get to the first
  150287. with a granulepos. That's not equivalent behavior to beginning
  150288. decoding as immediately after the seek position as possible.
  150289. So, a hack. We use two stream states; a local scratch state and
  150290. the shared vf->os stream state. We use the local state to
  150291. scan, and the shared state as a buffer for later decode.
  150292. Unfortuantely, on the last page we still advance to last packet
  150293. because the granulepos on the last page is not necessarily on a
  150294. packet boundary, and we need to make sure the granpos is
  150295. correct.
  150296. */
  150297. {
  150298. ogg_page og;
  150299. ogg_packet op;
  150300. int lastblock=0;
  150301. int accblock=0;
  150302. int thisblock;
  150303. int eosflag;
  150304. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  150305. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  150306. return from not necessarily
  150307. starting from the beginning */
  150308. while(1){
  150309. if(vf->ready_state>=STREAMSET){
  150310. /* snarf/scan a packet if we can */
  150311. int result=ogg_stream_packetout(&work_os,&op);
  150312. if(result>0){
  150313. if(vf->vi[vf->current_link].codec_setup){
  150314. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  150315. if(thisblock<0){
  150316. ogg_stream_packetout(&vf->os,NULL);
  150317. thisblock=0;
  150318. }else{
  150319. if(eosflag)
  150320. ogg_stream_packetout(&vf->os,NULL);
  150321. else
  150322. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  150323. }
  150324. if(op.granulepos!=-1){
  150325. int i,link=vf->current_link;
  150326. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  150327. if(granulepos<0)granulepos=0;
  150328. for(i=0;i<link;i++)
  150329. granulepos+=vf->pcmlengths[i*2+1];
  150330. vf->pcm_offset=granulepos-accblock;
  150331. break;
  150332. }
  150333. lastblock=thisblock;
  150334. continue;
  150335. }else
  150336. ogg_stream_packetout(&vf->os,NULL);
  150337. }
  150338. }
  150339. if(!lastblock){
  150340. if(_get_next_page(vf,&og,-1)<0){
  150341. vf->pcm_offset=ov_pcm_total(vf,-1);
  150342. break;
  150343. }
  150344. }else{
  150345. /* huh? Bogus stream with packets but no granulepos */
  150346. vf->pcm_offset=-1;
  150347. break;
  150348. }
  150349. /* has our decoding just traversed a bitstream boundary? */
  150350. if(vf->ready_state>=STREAMSET)
  150351. if(vf->current_serialno!=ogg_page_serialno(&og)){
  150352. _decode_clear(vf); /* clear out stream state */
  150353. ogg_stream_clear(&work_os);
  150354. }
  150355. if(vf->ready_state<STREAMSET){
  150356. int link;
  150357. vf->current_serialno=ogg_page_serialno(&og);
  150358. for(link=0;link<vf->links;link++)
  150359. if(vf->serialnos[link]==vf->current_serialno)break;
  150360. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  150361. error out, leave
  150362. machine uninitialized */
  150363. vf->current_link=link;
  150364. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  150365. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  150366. vf->ready_state=STREAMSET;
  150367. }
  150368. ogg_stream_pagein(&vf->os,&og);
  150369. ogg_stream_pagein(&work_os,&og);
  150370. eosflag=ogg_page_eos(&og);
  150371. }
  150372. }
  150373. ogg_stream_clear(&work_os);
  150374. vf->bittrack=0.f;
  150375. vf->samptrack=0.f;
  150376. return(0);
  150377. seek_error:
  150378. /* dump the machine so we're in a known state */
  150379. vf->pcm_offset=-1;
  150380. ogg_stream_clear(&work_os);
  150381. _decode_clear(vf);
  150382. return OV_EBADLINK;
  150383. }
  150384. /* Page granularity seek (faster than sample granularity because we
  150385. don't do the last bit of decode to find a specific sample).
  150386. Seek to the last [granule marked] page preceeding the specified pos
  150387. location, such that decoding past the returned point will quickly
  150388. arrive at the requested position. */
  150389. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  150390. int link=-1;
  150391. ogg_int64_t result=0;
  150392. ogg_int64_t total=ov_pcm_total(vf,-1);
  150393. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150394. if(!vf->seekable)return(OV_ENOSEEK);
  150395. if(pos<0 || pos>total)return(OV_EINVAL);
  150396. /* which bitstream section does this pcm offset occur in? */
  150397. for(link=vf->links-1;link>=0;link--){
  150398. total-=vf->pcmlengths[link*2+1];
  150399. if(pos>=total)break;
  150400. }
  150401. /* search within the logical bitstream for the page with the highest
  150402. pcm_pos preceeding (or equal to) pos. There is a danger here;
  150403. missing pages or incorrect frame number information in the
  150404. bitstream could make our task impossible. Account for that (it
  150405. would be an error condition) */
  150406. /* new search algorithm by HB (Nicholas Vinen) */
  150407. {
  150408. ogg_int64_t end=vf->offsets[link+1];
  150409. ogg_int64_t begin=vf->offsets[link];
  150410. ogg_int64_t begintime = vf->pcmlengths[link*2];
  150411. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  150412. ogg_int64_t target=pos-total+begintime;
  150413. ogg_int64_t best=begin;
  150414. ogg_page og;
  150415. while(begin<end){
  150416. ogg_int64_t bisect;
  150417. if(end-begin<CHUNKSIZE){
  150418. bisect=begin;
  150419. }else{
  150420. /* take a (pretty decent) guess. */
  150421. bisect=begin +
  150422. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  150423. if(bisect<=begin)
  150424. bisect=begin+1;
  150425. }
  150426. _seek_helper(vf,bisect);
  150427. while(begin<end){
  150428. result=_get_next_page(vf,&og,end-vf->offset);
  150429. if(result==OV_EREAD) goto seek_error;
  150430. if(result<0){
  150431. if(bisect<=begin+1)
  150432. end=begin; /* found it */
  150433. else{
  150434. if(bisect==0) goto seek_error;
  150435. bisect-=CHUNKSIZE;
  150436. if(bisect<=begin)bisect=begin+1;
  150437. _seek_helper(vf,bisect);
  150438. }
  150439. }else{
  150440. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  150441. if(granulepos==-1)continue;
  150442. if(granulepos<target){
  150443. best=result; /* raw offset of packet with granulepos */
  150444. begin=vf->offset; /* raw offset of next page */
  150445. begintime=granulepos;
  150446. if(target-begintime>44100)break;
  150447. bisect=begin; /* *not* begin + 1 */
  150448. }else{
  150449. if(bisect<=begin+1)
  150450. end=begin; /* found it */
  150451. else{
  150452. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  150453. end=result;
  150454. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  150455. if(bisect<=begin)bisect=begin+1;
  150456. _seek_helper(vf,bisect);
  150457. }else{
  150458. end=result;
  150459. endtime=granulepos;
  150460. break;
  150461. }
  150462. }
  150463. }
  150464. }
  150465. }
  150466. }
  150467. /* found our page. seek to it, update pcm offset. Easier case than
  150468. raw_seek, don't keep packets preceeding granulepos. */
  150469. {
  150470. ogg_page og;
  150471. ogg_packet op;
  150472. /* seek */
  150473. _seek_helper(vf,best);
  150474. vf->pcm_offset=-1;
  150475. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  150476. if(link!=vf->current_link){
  150477. /* Different link; dump entire decode machine */
  150478. _decode_clear(vf);
  150479. vf->current_link=link;
  150480. vf->current_serialno=ogg_page_serialno(&og);
  150481. vf->ready_state=STREAMSET;
  150482. }else{
  150483. vorbis_synthesis_restart(&vf->vd);
  150484. }
  150485. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  150486. ogg_stream_pagein(&vf->os,&og);
  150487. /* pull out all but last packet; the one with granulepos */
  150488. while(1){
  150489. result=ogg_stream_packetpeek(&vf->os,&op);
  150490. if(result==0){
  150491. /* !!! the packet finishing this page originated on a
  150492. preceeding page. Keep fetching previous pages until we
  150493. get one with a granulepos or without the 'continued' flag
  150494. set. Then just use raw_seek for simplicity. */
  150495. _seek_helper(vf,best);
  150496. while(1){
  150497. result=_get_prev_page(vf,&og);
  150498. if(result<0) goto seek_error;
  150499. if(ogg_page_granulepos(&og)>-1 ||
  150500. !ogg_page_continued(&og)){
  150501. return ov_raw_seek(vf,result);
  150502. }
  150503. vf->offset=result;
  150504. }
  150505. }
  150506. if(result<0){
  150507. result = OV_EBADPACKET;
  150508. goto seek_error;
  150509. }
  150510. if(op.granulepos!=-1){
  150511. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  150512. if(vf->pcm_offset<0)vf->pcm_offset=0;
  150513. vf->pcm_offset+=total;
  150514. break;
  150515. }else
  150516. result=ogg_stream_packetout(&vf->os,NULL);
  150517. }
  150518. }
  150519. }
  150520. /* verify result */
  150521. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  150522. result=OV_EFAULT;
  150523. goto seek_error;
  150524. }
  150525. vf->bittrack=0.f;
  150526. vf->samptrack=0.f;
  150527. return(0);
  150528. seek_error:
  150529. /* dump machine so we're in a known state */
  150530. vf->pcm_offset=-1;
  150531. _decode_clear(vf);
  150532. return (int)result;
  150533. }
  150534. /* seek to a sample offset relative to the decompressed pcm stream
  150535. returns zero on success, nonzero on failure */
  150536. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  150537. int thisblock,lastblock=0;
  150538. int ret=ov_pcm_seek_page(vf,pos);
  150539. if(ret<0)return(ret);
  150540. if((ret=_make_decode_ready(vf)))return ret;
  150541. /* discard leading packets we don't need for the lapping of the
  150542. position we want; don't decode them */
  150543. while(1){
  150544. ogg_packet op;
  150545. ogg_page og;
  150546. int ret=ogg_stream_packetpeek(&vf->os,&op);
  150547. if(ret>0){
  150548. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  150549. if(thisblock<0){
  150550. ogg_stream_packetout(&vf->os,NULL);
  150551. continue; /* non audio packet */
  150552. }
  150553. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  150554. if(vf->pcm_offset+((thisblock+
  150555. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  150556. /* remove the packet from packet queue and track its granulepos */
  150557. ogg_stream_packetout(&vf->os,NULL);
  150558. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  150559. only tracking, no
  150560. pcm_decode */
  150561. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  150562. /* end of logical stream case is hard, especially with exact
  150563. length positioning. */
  150564. if(op.granulepos>-1){
  150565. int i;
  150566. /* always believe the stream markers */
  150567. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  150568. if(vf->pcm_offset<0)vf->pcm_offset=0;
  150569. for(i=0;i<vf->current_link;i++)
  150570. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  150571. }
  150572. lastblock=thisblock;
  150573. }else{
  150574. if(ret<0 && ret!=OV_HOLE)break;
  150575. /* suck in a new page */
  150576. if(_get_next_page(vf,&og,-1)<0)break;
  150577. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  150578. if(vf->ready_state<STREAMSET){
  150579. int link;
  150580. vf->current_serialno=ogg_page_serialno(&og);
  150581. for(link=0;link<vf->links;link++)
  150582. if(vf->serialnos[link]==vf->current_serialno)break;
  150583. if(link==vf->links)return(OV_EBADLINK);
  150584. vf->current_link=link;
  150585. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  150586. vf->ready_state=STREAMSET;
  150587. ret=_make_decode_ready(vf);
  150588. if(ret)return ret;
  150589. lastblock=0;
  150590. }
  150591. ogg_stream_pagein(&vf->os,&og);
  150592. }
  150593. }
  150594. vf->bittrack=0.f;
  150595. vf->samptrack=0.f;
  150596. /* discard samples until we reach the desired position. Crossing a
  150597. logical bitstream boundary with abandon is OK. */
  150598. while(vf->pcm_offset<pos){
  150599. ogg_int64_t target=pos-vf->pcm_offset;
  150600. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  150601. if(samples>target)samples=target;
  150602. vorbis_synthesis_read(&vf->vd,samples);
  150603. vf->pcm_offset+=samples;
  150604. if(samples<target)
  150605. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  150606. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  150607. }
  150608. return 0;
  150609. }
  150610. /* seek to a playback time relative to the decompressed pcm stream
  150611. returns zero on success, nonzero on failure */
  150612. int ov_time_seek(OggVorbis_File *vf,double seconds){
  150613. /* translate time to PCM position and call ov_pcm_seek */
  150614. int link=-1;
  150615. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  150616. double time_total=ov_time_total(vf,-1);
  150617. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150618. if(!vf->seekable)return(OV_ENOSEEK);
  150619. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  150620. /* which bitstream section does this time offset occur in? */
  150621. for(link=vf->links-1;link>=0;link--){
  150622. pcm_total-=vf->pcmlengths[link*2+1];
  150623. time_total-=ov_time_total(vf,link);
  150624. if(seconds>=time_total)break;
  150625. }
  150626. /* enough information to convert time offset to pcm offset */
  150627. {
  150628. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  150629. return(ov_pcm_seek(vf,target));
  150630. }
  150631. }
  150632. /* page-granularity version of ov_time_seek
  150633. returns zero on success, nonzero on failure */
  150634. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  150635. /* translate time to PCM position and call ov_pcm_seek */
  150636. int link=-1;
  150637. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  150638. double time_total=ov_time_total(vf,-1);
  150639. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150640. if(!vf->seekable)return(OV_ENOSEEK);
  150641. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  150642. /* which bitstream section does this time offset occur in? */
  150643. for(link=vf->links-1;link>=0;link--){
  150644. pcm_total-=vf->pcmlengths[link*2+1];
  150645. time_total-=ov_time_total(vf,link);
  150646. if(seconds>=time_total)break;
  150647. }
  150648. /* enough information to convert time offset to pcm offset */
  150649. {
  150650. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  150651. return(ov_pcm_seek_page(vf,target));
  150652. }
  150653. }
  150654. /* tell the current stream offset cursor. Note that seek followed by
  150655. tell will likely not give the set offset due to caching */
  150656. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  150657. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150658. return(vf->offset);
  150659. }
  150660. /* return PCM offset (sample) of next PCM sample to be read */
  150661. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  150662. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150663. return(vf->pcm_offset);
  150664. }
  150665. /* return time offset (seconds) of next PCM sample to be read */
  150666. double ov_time_tell(OggVorbis_File *vf){
  150667. int link=0;
  150668. ogg_int64_t pcm_total=0;
  150669. double time_total=0.f;
  150670. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150671. if(vf->seekable){
  150672. pcm_total=ov_pcm_total(vf,-1);
  150673. time_total=ov_time_total(vf,-1);
  150674. /* which bitstream section does this time offset occur in? */
  150675. for(link=vf->links-1;link>=0;link--){
  150676. pcm_total-=vf->pcmlengths[link*2+1];
  150677. time_total-=ov_time_total(vf,link);
  150678. if(vf->pcm_offset>=pcm_total)break;
  150679. }
  150680. }
  150681. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  150682. }
  150683. /* link: -1) return the vorbis_info struct for the bitstream section
  150684. currently being decoded
  150685. 0-n) to request information for a specific bitstream section
  150686. In the case of a non-seekable bitstream, any call returns the
  150687. current bitstream. NULL in the case that the machine is not
  150688. initialized */
  150689. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  150690. if(vf->seekable){
  150691. if(link<0)
  150692. if(vf->ready_state>=STREAMSET)
  150693. return vf->vi+vf->current_link;
  150694. else
  150695. return vf->vi;
  150696. else
  150697. if(link>=vf->links)
  150698. return NULL;
  150699. else
  150700. return vf->vi+link;
  150701. }else{
  150702. return vf->vi;
  150703. }
  150704. }
  150705. /* grr, strong typing, grr, no templates/inheritence, grr */
  150706. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  150707. if(vf->seekable){
  150708. if(link<0)
  150709. if(vf->ready_state>=STREAMSET)
  150710. return vf->vc+vf->current_link;
  150711. else
  150712. return vf->vc;
  150713. else
  150714. if(link>=vf->links)
  150715. return NULL;
  150716. else
  150717. return vf->vc+link;
  150718. }else{
  150719. return vf->vc;
  150720. }
  150721. }
  150722. static int host_is_big_endian() {
  150723. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  150724. unsigned char *bytewise = (unsigned char *)&pattern;
  150725. if (bytewise[0] == 0xfe) return 1;
  150726. return 0;
  150727. }
  150728. /* up to this point, everything could more or less hide the multiple
  150729. logical bitstream nature of chaining from the toplevel application
  150730. if the toplevel application didn't particularly care. However, at
  150731. the point that we actually read audio back, the multiple-section
  150732. nature must surface: Multiple bitstream sections do not necessarily
  150733. have to have the same number of channels or sampling rate.
  150734. ov_read returns the sequential logical bitstream number currently
  150735. being decoded along with the PCM data in order that the toplevel
  150736. application can take action on channel/sample rate changes. This
  150737. number will be incremented even for streamed (non-seekable) streams
  150738. (for seekable streams, it represents the actual logical bitstream
  150739. index within the physical bitstream. Note that the accessor
  150740. functions above are aware of this dichotomy).
  150741. input values: buffer) a buffer to hold packed PCM data for return
  150742. length) the byte length requested to be placed into buffer
  150743. bigendianp) should the data be packed LSB first (0) or
  150744. MSB first (1)
  150745. word) word size for output. currently 1 (byte) or
  150746. 2 (16 bit short)
  150747. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  150748. 0) EOF
  150749. n) number of bytes of PCM actually returned. The
  150750. below works on a packet-by-packet basis, so the
  150751. return length is not related to the 'length' passed
  150752. in, just guaranteed to fit.
  150753. *section) set to the logical bitstream number */
  150754. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  150755. int bigendianp,int word,int sgned,int *bitstream){
  150756. int i,j;
  150757. int host_endian = host_is_big_endian();
  150758. float **pcm;
  150759. long samples;
  150760. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150761. while(1){
  150762. if(vf->ready_state==INITSET){
  150763. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  150764. if(samples)break;
  150765. }
  150766. /* suck in another packet */
  150767. {
  150768. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  150769. if(ret==OV_EOF)
  150770. return(0);
  150771. if(ret<=0)
  150772. return(ret);
  150773. }
  150774. }
  150775. if(samples>0){
  150776. /* yay! proceed to pack data into the byte buffer */
  150777. long channels=ov_info(vf,-1)->channels;
  150778. long bytespersample=word * channels;
  150779. vorbis_fpu_control fpu;
  150780. (void) fpu; // (to avoid a warning about it being unused)
  150781. if(samples>length/bytespersample)samples=length/bytespersample;
  150782. if(samples <= 0)
  150783. return OV_EINVAL;
  150784. /* a tight loop to pack each size */
  150785. {
  150786. int val;
  150787. if(word==1){
  150788. int off=(sgned?0:128);
  150789. vorbis_fpu_setround(&fpu);
  150790. for(j=0;j<samples;j++)
  150791. for(i=0;i<channels;i++){
  150792. val=vorbis_ftoi(pcm[i][j]*128.f);
  150793. if(val>127)val=127;
  150794. else if(val<-128)val=-128;
  150795. *buffer++=val+off;
  150796. }
  150797. vorbis_fpu_restore(fpu);
  150798. }else{
  150799. int off=(sgned?0:32768);
  150800. if(host_endian==bigendianp){
  150801. if(sgned){
  150802. vorbis_fpu_setround(&fpu);
  150803. for(i=0;i<channels;i++) { /* It's faster in this order */
  150804. float *src=pcm[i];
  150805. short *dest=((short *)buffer)+i;
  150806. for(j=0;j<samples;j++) {
  150807. val=vorbis_ftoi(src[j]*32768.f);
  150808. if(val>32767)val=32767;
  150809. else if(val<-32768)val=-32768;
  150810. *dest=val;
  150811. dest+=channels;
  150812. }
  150813. }
  150814. vorbis_fpu_restore(fpu);
  150815. }else{
  150816. vorbis_fpu_setround(&fpu);
  150817. for(i=0;i<channels;i++) {
  150818. float *src=pcm[i];
  150819. short *dest=((short *)buffer)+i;
  150820. for(j=0;j<samples;j++) {
  150821. val=vorbis_ftoi(src[j]*32768.f);
  150822. if(val>32767)val=32767;
  150823. else if(val<-32768)val=-32768;
  150824. *dest=val+off;
  150825. dest+=channels;
  150826. }
  150827. }
  150828. vorbis_fpu_restore(fpu);
  150829. }
  150830. }else if(bigendianp){
  150831. vorbis_fpu_setround(&fpu);
  150832. for(j=0;j<samples;j++)
  150833. for(i=0;i<channels;i++){
  150834. val=vorbis_ftoi(pcm[i][j]*32768.f);
  150835. if(val>32767)val=32767;
  150836. else if(val<-32768)val=-32768;
  150837. val+=off;
  150838. *buffer++=(val>>8);
  150839. *buffer++=(val&0xff);
  150840. }
  150841. vorbis_fpu_restore(fpu);
  150842. }else{
  150843. int val;
  150844. vorbis_fpu_setround(&fpu);
  150845. for(j=0;j<samples;j++)
  150846. for(i=0;i<channels;i++){
  150847. val=vorbis_ftoi(pcm[i][j]*32768.f);
  150848. if(val>32767)val=32767;
  150849. else if(val<-32768)val=-32768;
  150850. val+=off;
  150851. *buffer++=(val&0xff);
  150852. *buffer++=(val>>8);
  150853. }
  150854. vorbis_fpu_restore(fpu);
  150855. }
  150856. }
  150857. }
  150858. vorbis_synthesis_read(&vf->vd,samples);
  150859. vf->pcm_offset+=samples;
  150860. if(bitstream)*bitstream=vf->current_link;
  150861. return(samples*bytespersample);
  150862. }else{
  150863. return(samples);
  150864. }
  150865. }
  150866. /* input values: pcm_channels) a float vector per channel of output
  150867. length) the sample length being read by the app
  150868. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  150869. 0) EOF
  150870. n) number of samples of PCM actually returned. The
  150871. below works on a packet-by-packet basis, so the
  150872. return length is not related to the 'length' passed
  150873. in, just guaranteed to fit.
  150874. *section) set to the logical bitstream number */
  150875. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  150876. int *bitstream){
  150877. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150878. while(1){
  150879. if(vf->ready_state==INITSET){
  150880. float **pcm;
  150881. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  150882. if(samples){
  150883. if(pcm_channels)*pcm_channels=pcm;
  150884. if(samples>length)samples=length;
  150885. vorbis_synthesis_read(&vf->vd,samples);
  150886. vf->pcm_offset+=samples;
  150887. if(bitstream)*bitstream=vf->current_link;
  150888. return samples;
  150889. }
  150890. }
  150891. /* suck in another packet */
  150892. {
  150893. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  150894. if(ret==OV_EOF)return(0);
  150895. if(ret<=0)return(ret);
  150896. }
  150897. }
  150898. }
  150899. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  150900. extern void _analysis_output_always(char *base,int i,float *v,int n,int bark,int dB,
  150901. ogg_int64_t off);
  150902. static void _ov_splice(float **pcm,float **lappcm,
  150903. int n1, int n2,
  150904. int ch1, int ch2,
  150905. float *w1, float *w2){
  150906. int i,j;
  150907. float *w=w1;
  150908. int n=n1;
  150909. if(n1>n2){
  150910. n=n2;
  150911. w=w2;
  150912. }
  150913. /* splice */
  150914. for(j=0;j<ch1 && j<ch2;j++){
  150915. float *s=lappcm[j];
  150916. float *d=pcm[j];
  150917. for(i=0;i<n;i++){
  150918. float wd=w[i]*w[i];
  150919. float ws=1.-wd;
  150920. d[i]=d[i]*wd + s[i]*ws;
  150921. }
  150922. }
  150923. /* window from zero */
  150924. for(;j<ch2;j++){
  150925. float *d=pcm[j];
  150926. for(i=0;i<n;i++){
  150927. float wd=w[i]*w[i];
  150928. d[i]=d[i]*wd;
  150929. }
  150930. }
  150931. }
  150932. /* make sure vf is INITSET */
  150933. static int _ov_initset(OggVorbis_File *vf){
  150934. while(1){
  150935. if(vf->ready_state==INITSET)break;
  150936. /* suck in another packet */
  150937. {
  150938. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  150939. if(ret<0 && ret!=OV_HOLE)return(ret);
  150940. }
  150941. }
  150942. return 0;
  150943. }
  150944. /* make sure vf is INITSET and that we have a primed buffer; if
  150945. we're crosslapping at a stream section boundary, this also makes
  150946. sure we're sanity checking against the right stream information */
  150947. static int _ov_initprime(OggVorbis_File *vf){
  150948. vorbis_dsp_state *vd=&vf->vd;
  150949. while(1){
  150950. if(vf->ready_state==INITSET)
  150951. if(vorbis_synthesis_pcmout(vd,NULL))break;
  150952. /* suck in another packet */
  150953. {
  150954. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  150955. if(ret<0 && ret!=OV_HOLE)return(ret);
  150956. }
  150957. }
  150958. return 0;
  150959. }
  150960. /* grab enough data for lapping from vf; this may be in the form of
  150961. unreturned, already-decoded pcm, remaining PCM we will need to
  150962. decode, or synthetic postextrapolation from last packets. */
  150963. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  150964. float **lappcm,int lapsize){
  150965. int lapcount=0,i;
  150966. float **pcm;
  150967. /* try first to decode the lapping data */
  150968. while(lapcount<lapsize){
  150969. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  150970. if(samples){
  150971. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  150972. for(i=0;i<vi->channels;i++)
  150973. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  150974. lapcount+=samples;
  150975. vorbis_synthesis_read(vd,samples);
  150976. }else{
  150977. /* suck in another packet */
  150978. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  150979. if(ret==OV_EOF)break;
  150980. }
  150981. }
  150982. if(lapcount<lapsize){
  150983. /* failed to get lapping data from normal decode; pry it from the
  150984. postextrapolation buffering, or the second half of the MDCT
  150985. from the last packet */
  150986. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  150987. if(samples==0){
  150988. for(i=0;i<vi->channels;i++)
  150989. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  150990. lapcount=lapsize;
  150991. }else{
  150992. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  150993. for(i=0;i<vi->channels;i++)
  150994. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  150995. lapcount+=samples;
  150996. }
  150997. }
  150998. }
  150999. /* this sets up crosslapping of a sample by using trailing data from
  151000. sample 1 and lapping it into the windowing buffer of sample 2 */
  151001. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  151002. vorbis_info *vi1,*vi2;
  151003. float **lappcm;
  151004. float **pcm;
  151005. float *w1,*w2;
  151006. int n1,n2,i,ret,hs1,hs2;
  151007. if(vf1==vf2)return(0); /* degenerate case */
  151008. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  151009. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  151010. /* the relevant overlap buffers must be pre-checked and pre-primed
  151011. before looking at settings in the event that priming would cross
  151012. a bitstream boundary. So, do it now */
  151013. ret=_ov_initset(vf1);
  151014. if(ret)return(ret);
  151015. ret=_ov_initprime(vf2);
  151016. if(ret)return(ret);
  151017. vi1=ov_info(vf1,-1);
  151018. vi2=ov_info(vf2,-1);
  151019. hs1=ov_halfrate_p(vf1);
  151020. hs2=ov_halfrate_p(vf2);
  151021. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  151022. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  151023. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  151024. w1=vorbis_window(&vf1->vd,0);
  151025. w2=vorbis_window(&vf2->vd,0);
  151026. for(i=0;i<vi1->channels;i++)
  151027. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  151028. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  151029. /* have a lapping buffer from vf1; now to splice it into the lapping
  151030. buffer of vf2 */
  151031. /* consolidate and expose the buffer. */
  151032. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  151033. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  151034. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  151035. /* splice */
  151036. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  151037. /* done */
  151038. return(0);
  151039. }
  151040. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  151041. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  151042. vorbis_info *vi;
  151043. float **lappcm;
  151044. float **pcm;
  151045. float *w1,*w2;
  151046. int n1,n2,ch1,ch2,hs;
  151047. int i,ret;
  151048. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151049. ret=_ov_initset(vf);
  151050. if(ret)return(ret);
  151051. vi=ov_info(vf,-1);
  151052. hs=ov_halfrate_p(vf);
  151053. ch1=vi->channels;
  151054. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  151055. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  151056. persistent; even if the decode state
  151057. from this link gets dumped, this
  151058. window array continues to exist */
  151059. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  151060. for(i=0;i<ch1;i++)
  151061. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  151062. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  151063. /* have lapping data; seek and prime the buffer */
  151064. ret=localseek(vf,pos);
  151065. if(ret)return ret;
  151066. ret=_ov_initprime(vf);
  151067. if(ret)return(ret);
  151068. /* Guard against cross-link changes; they're perfectly legal */
  151069. vi=ov_info(vf,-1);
  151070. ch2=vi->channels;
  151071. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  151072. w2=vorbis_window(&vf->vd,0);
  151073. /* consolidate and expose the buffer. */
  151074. vorbis_synthesis_lapout(&vf->vd,&pcm);
  151075. /* splice */
  151076. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  151077. /* done */
  151078. return(0);
  151079. }
  151080. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  151081. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  151082. }
  151083. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  151084. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  151085. }
  151086. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  151087. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  151088. }
  151089. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  151090. int (*localseek)(OggVorbis_File *,double)){
  151091. vorbis_info *vi;
  151092. float **lappcm;
  151093. float **pcm;
  151094. float *w1,*w2;
  151095. int n1,n2,ch1,ch2,hs;
  151096. int i,ret;
  151097. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151098. ret=_ov_initset(vf);
  151099. if(ret)return(ret);
  151100. vi=ov_info(vf,-1);
  151101. hs=ov_halfrate_p(vf);
  151102. ch1=vi->channels;
  151103. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  151104. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  151105. persistent; even if the decode state
  151106. from this link gets dumped, this
  151107. window array continues to exist */
  151108. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  151109. for(i=0;i<ch1;i++)
  151110. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  151111. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  151112. /* have lapping data; seek and prime the buffer */
  151113. ret=localseek(vf,pos);
  151114. if(ret)return ret;
  151115. ret=_ov_initprime(vf);
  151116. if(ret)return(ret);
  151117. /* Guard against cross-link changes; they're perfectly legal */
  151118. vi=ov_info(vf,-1);
  151119. ch2=vi->channels;
  151120. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  151121. w2=vorbis_window(&vf->vd,0);
  151122. /* consolidate and expose the buffer. */
  151123. vorbis_synthesis_lapout(&vf->vd,&pcm);
  151124. /* splice */
  151125. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  151126. /* done */
  151127. return(0);
  151128. }
  151129. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  151130. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  151131. }
  151132. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  151133. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  151134. }
  151135. #endif
  151136. /********* End of inlined file: vorbisfile.c *********/
  151137. /********* Start of inlined file: window.c *********/
  151138. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  151139. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  151140. // tasks..
  151141. #ifdef _MSC_VER
  151142. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  151143. #endif
  151144. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  151145. #if JUCE_USE_OGGVORBIS
  151146. #include <stdlib.h>
  151147. #include <math.h>
  151148. static float vwin64[32] = {
  151149. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  151150. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  151151. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  151152. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  151153. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  151154. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  151155. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  151156. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  151157. };
  151158. static float vwin128[64] = {
  151159. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  151160. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  151161. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  151162. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  151163. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  151164. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  151165. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  151166. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  151167. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  151168. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  151169. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  151170. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  151171. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  151172. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  151173. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  151174. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  151175. };
  151176. static float vwin256[128] = {
  151177. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  151178. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  151179. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  151180. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  151181. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  151182. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  151183. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  151184. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  151185. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  151186. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  151187. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  151188. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  151189. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  151190. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  151191. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  151192. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  151193. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  151194. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  151195. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  151196. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  151197. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  151198. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  151199. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  151200. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  151201. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  151202. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  151203. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  151204. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  151205. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  151206. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  151207. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  151208. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  151209. };
  151210. static float vwin512[256] = {
  151211. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  151212. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  151213. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  151214. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  151215. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  151216. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  151217. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  151218. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  151219. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  151220. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  151221. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  151222. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  151223. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  151224. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  151225. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  151226. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  151227. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  151228. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  151229. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  151230. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  151231. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  151232. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  151233. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  151234. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  151235. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  151236. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  151237. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  151238. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  151239. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  151240. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  151241. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  151242. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  151243. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  151244. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  151245. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  151246. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  151247. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  151248. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  151249. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  151250. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  151251. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  151252. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  151253. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  151254. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  151255. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  151256. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  151257. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  151258. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  151259. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  151260. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  151261. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  151262. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  151263. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  151264. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  151265. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  151266. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  151267. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  151268. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  151269. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  151270. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  151271. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  151272. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  151273. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  151274. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  151275. };
  151276. static float vwin1024[512] = {
  151277. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  151278. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  151279. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  151280. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  151281. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  151282. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  151283. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  151284. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  151285. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  151286. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  151287. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  151288. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  151289. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  151290. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  151291. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  151292. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  151293. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  151294. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  151295. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  151296. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  151297. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  151298. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  151299. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  151300. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  151301. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  151302. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  151303. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  151304. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  151305. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  151306. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  151307. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  151308. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  151309. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  151310. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  151311. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  151312. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  151313. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  151314. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  151315. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  151316. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  151317. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  151318. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  151319. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  151320. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  151321. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  151322. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  151323. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  151324. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  151325. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  151326. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  151327. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  151328. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  151329. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  151330. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  151331. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  151332. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  151333. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  151334. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  151335. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  151336. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  151337. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  151338. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  151339. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  151340. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  151341. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  151342. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  151343. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  151344. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  151345. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  151346. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  151347. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  151348. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  151349. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  151350. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  151351. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  151352. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  151353. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  151354. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  151355. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  151356. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  151357. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  151358. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  151359. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  151360. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  151361. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  151362. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  151363. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  151364. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  151365. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  151366. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  151367. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  151368. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  151369. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  151370. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  151371. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  151372. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  151373. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  151374. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  151375. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  151376. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  151377. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  151378. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  151379. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  151380. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  151381. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  151382. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  151383. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  151384. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  151385. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  151386. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  151387. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  151388. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  151389. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  151390. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  151391. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  151392. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  151393. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  151394. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  151395. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  151396. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  151397. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  151398. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  151399. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  151400. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  151401. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  151402. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  151403. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  151404. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  151405. };
  151406. static float vwin2048[1024] = {
  151407. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  151408. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  151409. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  151410. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  151411. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  151412. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  151413. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  151414. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  151415. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  151416. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  151417. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  151418. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  151419. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  151420. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  151421. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  151422. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  151423. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  151424. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  151425. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  151426. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  151427. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  151428. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  151429. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  151430. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  151431. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  151432. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  151433. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  151434. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  151435. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  151436. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  151437. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  151438. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  151439. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  151440. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  151441. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  151442. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  151443. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  151444. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  151445. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  151446. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  151447. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  151448. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  151449. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  151450. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  151451. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  151452. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  151453. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  151454. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  151455. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  151456. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  151457. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  151458. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  151459. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  151460. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  151461. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  151462. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  151463. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  151464. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  151465. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  151466. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  151467. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  151468. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  151469. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  151470. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  151471. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  151472. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  151473. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  151474. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  151475. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  151476. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  151477. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  151478. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  151479. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  151480. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  151481. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  151482. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  151483. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  151484. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  151485. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  151486. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  151487. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  151488. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  151489. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  151490. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  151491. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  151492. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  151493. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  151494. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  151495. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  151496. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  151497. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  151498. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  151499. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  151500. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  151501. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  151502. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  151503. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  151504. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  151505. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  151506. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  151507. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  151508. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  151509. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  151510. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  151511. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  151512. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  151513. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  151514. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  151515. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  151516. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  151517. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  151518. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  151519. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  151520. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  151521. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  151522. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  151523. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  151524. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  151525. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  151526. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  151527. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  151528. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  151529. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  151530. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  151531. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  151532. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  151533. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  151534. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  151535. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  151536. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  151537. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  151538. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  151539. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  151540. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  151541. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  151542. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  151543. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  151544. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  151545. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  151546. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  151547. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  151548. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  151549. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  151550. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  151551. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  151552. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  151553. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  151554. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  151555. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  151556. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  151557. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  151558. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  151559. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  151560. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  151561. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  151562. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  151563. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  151564. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  151565. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  151566. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  151567. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  151568. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  151569. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  151570. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  151571. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  151572. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  151573. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  151574. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  151575. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  151576. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  151577. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  151578. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  151579. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  151580. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  151581. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  151582. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  151583. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  151584. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  151585. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  151586. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  151587. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  151588. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  151589. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  151590. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  151591. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  151592. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  151593. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  151594. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  151595. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  151596. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  151597. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  151598. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  151599. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  151600. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  151601. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  151602. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  151603. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  151604. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  151605. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  151606. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  151607. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  151608. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  151609. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  151610. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  151611. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  151612. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  151613. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  151614. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  151615. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  151616. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  151617. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  151618. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  151619. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  151620. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  151621. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  151622. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  151623. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  151624. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  151625. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  151626. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  151627. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  151628. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  151629. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  151630. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  151631. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  151632. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  151633. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  151634. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  151635. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  151636. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  151637. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  151638. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  151639. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  151640. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  151641. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  151642. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  151643. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  151644. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  151645. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  151646. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  151647. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  151648. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  151649. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  151650. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  151651. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  151652. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  151653. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  151654. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  151655. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  151656. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  151657. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  151658. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  151659. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  151660. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  151661. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  151662. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  151663. };
  151664. static float vwin4096[2048] = {
  151665. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  151666. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  151667. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  151668. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  151669. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  151670. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  151671. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  151672. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  151673. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  151674. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  151675. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  151676. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  151677. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  151678. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  151679. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  151680. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  151681. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  151682. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  151683. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  151684. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  151685. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  151686. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  151687. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  151688. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  151689. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  151690. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  151691. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  151692. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  151693. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  151694. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  151695. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  151696. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  151697. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  151698. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  151699. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  151700. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  151701. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  151702. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  151703. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  151704. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  151705. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  151706. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  151707. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  151708. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  151709. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  151710. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  151711. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  151712. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  151713. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  151714. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  151715. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  151716. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  151717. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  151718. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  151719. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  151720. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  151721. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  151722. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  151723. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  151724. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  151725. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  151726. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  151727. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  151728. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  151729. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  151730. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  151731. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  151732. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  151733. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  151734. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  151735. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  151736. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  151737. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  151738. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  151739. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  151740. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  151741. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  151742. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  151743. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  151744. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  151745. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  151746. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  151747. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  151748. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  151749. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  151750. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  151751. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  151752. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  151753. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  151754. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  151755. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  151756. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  151757. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  151758. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  151759. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  151760. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  151761. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  151762. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  151763. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  151764. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  151765. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  151766. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  151767. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  151768. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  151769. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  151770. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  151771. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  151772. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  151773. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  151774. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  151775. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  151776. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  151777. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  151778. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  151779. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  151780. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  151781. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  151782. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  151783. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  151784. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  151785. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  151786. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  151787. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  151788. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  151789. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  151790. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  151791. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  151792. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  151793. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  151794. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  151795. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  151796. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  151797. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  151798. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  151799. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  151800. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  151801. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  151802. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  151803. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  151804. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  151805. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  151806. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  151807. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  151808. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  151809. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  151810. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  151811. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  151812. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  151813. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  151814. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  151815. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  151816. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  151817. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  151818. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  151819. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  151820. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  151821. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  151822. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  151823. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  151824. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  151825. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  151826. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  151827. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  151828. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  151829. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  151830. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  151831. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  151832. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  151833. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  151834. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  151835. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  151836. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  151837. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  151838. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  151839. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  151840. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  151841. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  151842. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  151843. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  151844. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  151845. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  151846. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  151847. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  151848. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  151849. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  151850. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  151851. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  151852. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  151853. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  151854. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  151855. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  151856. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  151857. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  151858. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  151859. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  151860. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  151861. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  151862. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  151863. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  151864. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  151865. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  151866. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  151867. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  151868. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  151869. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  151870. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  151871. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  151872. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  151873. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  151874. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  151875. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  151876. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  151877. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  151878. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  151879. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  151880. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  151881. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  151882. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  151883. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  151884. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  151885. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  151886. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  151887. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  151888. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  151889. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  151890. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  151891. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  151892. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  151893. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  151894. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  151895. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  151896. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  151897. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  151898. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  151899. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  151900. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  151901. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  151902. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  151903. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  151904. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  151905. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  151906. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  151907. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  151908. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  151909. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  151910. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  151911. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  151912. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  151913. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  151914. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  151915. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  151916. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  151917. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  151918. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  151919. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  151920. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  151921. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  151922. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  151923. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  151924. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  151925. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  151926. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  151927. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  151928. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  151929. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  151930. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  151931. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  151932. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  151933. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  151934. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  151935. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  151936. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  151937. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  151938. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  151939. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  151940. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  151941. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  151942. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  151943. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  151944. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  151945. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  151946. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  151947. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  151948. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  151949. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  151950. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  151951. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  151952. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  151953. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  151954. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  151955. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  151956. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  151957. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  151958. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  151959. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  151960. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  151961. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  151962. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  151963. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  151964. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  151965. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  151966. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  151967. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  151968. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  151969. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  151970. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  151971. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  151972. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  151973. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  151974. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  151975. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  151976. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  151977. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  151978. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  151979. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  151980. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  151981. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  151982. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  151983. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  151984. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  151985. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  151986. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  151987. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  151988. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  151989. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  151990. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  151991. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  151992. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  151993. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  151994. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  151995. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  151996. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  151997. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  151998. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  151999. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  152000. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  152001. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  152002. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  152003. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  152004. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  152005. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  152006. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  152007. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  152008. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  152009. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  152010. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  152011. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  152012. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  152013. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  152014. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  152015. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  152016. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  152017. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  152018. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  152019. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  152020. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  152021. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  152022. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  152023. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  152024. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  152025. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  152026. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  152027. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  152028. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  152029. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  152030. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  152031. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  152032. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  152033. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  152034. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  152035. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  152036. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  152037. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  152038. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  152039. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  152040. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  152041. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  152042. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  152043. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  152044. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  152045. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  152046. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  152047. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  152048. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  152049. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  152050. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  152051. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  152052. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  152053. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  152054. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  152055. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  152056. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  152057. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  152058. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  152059. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  152060. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  152061. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  152062. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  152063. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  152064. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  152065. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  152066. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  152067. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  152068. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  152069. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  152070. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  152071. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  152072. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  152073. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  152074. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  152075. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  152076. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  152077. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  152078. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  152079. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  152080. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  152081. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  152082. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  152083. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  152084. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  152085. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  152086. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  152087. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  152088. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  152089. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  152090. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  152091. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  152092. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  152093. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  152094. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  152095. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  152096. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  152097. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  152098. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  152099. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  152100. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  152101. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  152102. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  152103. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  152104. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  152105. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  152106. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  152107. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  152108. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  152109. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  152110. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  152111. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  152112. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  152113. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  152114. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  152115. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  152116. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  152117. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  152118. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  152119. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  152120. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  152121. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  152122. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  152123. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  152124. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  152125. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  152126. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  152127. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  152128. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  152129. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  152130. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  152131. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  152132. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  152133. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  152134. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  152135. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  152136. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  152137. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  152138. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  152139. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  152140. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  152141. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  152142. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  152143. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  152144. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  152145. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  152146. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  152147. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  152148. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  152149. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  152150. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  152151. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  152152. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  152153. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  152154. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  152155. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  152156. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  152157. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  152158. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  152159. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  152160. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  152161. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  152162. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  152163. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  152164. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  152165. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  152166. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  152167. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  152168. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  152169. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  152170. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  152171. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  152172. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  152173. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  152174. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  152175. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  152176. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  152177. };
  152178. static float vwin8192[4096] = {
  152179. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  152180. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  152181. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  152182. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  152183. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  152184. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  152185. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  152186. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  152187. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  152188. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  152189. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  152190. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  152191. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  152192. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  152193. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  152194. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  152195. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  152196. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  152197. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  152198. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  152199. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  152200. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  152201. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  152202. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  152203. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  152204. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  152205. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  152206. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  152207. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  152208. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  152209. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  152210. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  152211. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  152212. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  152213. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  152214. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  152215. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  152216. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  152217. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  152218. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  152219. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  152220. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  152221. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  152222. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  152223. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  152224. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  152225. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  152226. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  152227. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  152228. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  152229. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  152230. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  152231. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  152232. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  152233. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  152234. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  152235. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  152236. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  152237. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  152238. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  152239. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  152240. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  152241. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  152242. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  152243. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  152244. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  152245. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  152246. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  152247. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  152248. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  152249. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  152250. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  152251. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  152252. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  152253. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  152254. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  152255. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  152256. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  152257. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  152258. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  152259. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  152260. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  152261. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  152262. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  152263. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  152264. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  152265. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  152266. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  152267. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  152268. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  152269. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  152270. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  152271. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  152272. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  152273. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  152274. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  152275. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  152276. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  152277. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  152278. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  152279. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  152280. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  152281. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  152282. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  152283. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  152284. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  152285. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  152286. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  152287. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  152288. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  152289. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  152290. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  152291. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  152292. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  152293. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  152294. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  152295. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  152296. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  152297. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  152298. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  152299. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  152300. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  152301. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  152302. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  152303. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  152304. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  152305. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  152306. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  152307. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  152308. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  152309. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  152310. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  152311. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  152312. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  152313. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  152314. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  152315. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  152316. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  152317. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  152318. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  152319. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  152320. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  152321. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  152322. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  152323. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  152324. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  152325. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  152326. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  152327. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  152328. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  152329. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  152330. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  152331. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  152332. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  152333. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  152334. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  152335. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  152336. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  152337. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  152338. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  152339. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  152340. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  152341. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  152342. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  152343. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  152344. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  152345. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  152346. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  152347. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  152348. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  152349. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  152350. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  152351. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  152352. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  152353. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  152354. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  152355. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  152356. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  152357. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  152358. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  152359. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  152360. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  152361. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  152362. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  152363. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  152364. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  152365. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  152366. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  152367. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  152368. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  152369. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  152370. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  152371. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  152372. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  152373. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  152374. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  152375. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  152376. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  152377. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  152378. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  152379. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  152380. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  152381. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  152382. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  152383. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  152384. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  152385. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  152386. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  152387. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  152388. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  152389. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  152390. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  152391. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  152392. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  152393. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  152394. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  152395. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  152396. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  152397. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  152398. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  152399. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  152400. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  152401. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  152402. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  152403. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  152404. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  152405. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  152406. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  152407. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  152408. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  152409. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  152410. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  152411. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  152412. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  152413. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  152414. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  152415. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  152416. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  152417. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  152418. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  152419. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  152420. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  152421. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  152422. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  152423. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  152424. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  152425. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  152426. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  152427. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  152428. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  152429. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  152430. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  152431. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  152432. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  152433. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  152434. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  152435. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  152436. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  152437. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  152438. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  152439. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  152440. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  152441. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  152442. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  152443. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  152444. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  152445. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  152446. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  152447. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  152448. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  152449. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  152450. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  152451. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  152452. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  152453. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  152454. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  152455. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  152456. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  152457. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  152458. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  152459. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  152460. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  152461. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  152462. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  152463. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  152464. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  152465. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  152466. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  152467. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  152468. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  152469. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  152470. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  152471. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  152472. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  152473. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  152474. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  152475. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  152476. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  152477. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  152478. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  152479. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  152480. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  152481. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  152482. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  152483. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  152484. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  152485. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  152486. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  152487. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  152488. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  152489. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  152490. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  152491. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  152492. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  152493. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  152494. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  152495. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  152496. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  152497. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  152498. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  152499. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  152500. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  152501. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  152502. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  152503. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  152504. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  152505. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  152506. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  152507. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  152508. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  152509. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  152510. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  152511. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  152512. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  152513. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  152514. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  152515. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  152516. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  152517. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  152518. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  152519. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  152520. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  152521. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  152522. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  152523. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  152524. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  152525. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  152526. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  152527. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  152528. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  152529. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  152530. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  152531. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  152532. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  152533. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  152534. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  152535. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  152536. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  152537. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  152538. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  152539. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  152540. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  152541. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  152542. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  152543. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  152544. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  152545. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  152546. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  152547. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  152548. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  152549. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  152550. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  152551. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  152552. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  152553. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  152554. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  152555. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  152556. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  152557. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  152558. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  152559. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  152560. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  152561. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  152562. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  152563. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  152564. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  152565. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  152566. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  152567. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  152568. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  152569. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  152570. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  152571. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  152572. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  152573. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  152574. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  152575. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  152576. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  152577. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  152578. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  152579. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  152580. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  152581. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  152582. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  152583. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  152584. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  152585. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  152586. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  152587. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  152588. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  152589. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  152590. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  152591. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  152592. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  152593. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  152594. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  152595. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  152596. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  152597. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  152598. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  152599. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  152600. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  152601. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  152602. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  152603. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  152604. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  152605. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  152606. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  152607. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  152608. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  152609. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  152610. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  152611. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  152612. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  152613. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  152614. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  152615. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  152616. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  152617. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  152618. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  152619. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  152620. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  152621. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  152622. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  152623. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  152624. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  152625. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  152626. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  152627. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  152628. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  152629. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  152630. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  152631. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  152632. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  152633. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  152634. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  152635. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  152636. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  152637. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  152638. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  152639. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  152640. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  152641. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  152642. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  152643. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  152644. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  152645. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  152646. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  152647. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  152648. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  152649. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  152650. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  152651. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  152652. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  152653. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  152654. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  152655. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  152656. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  152657. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  152658. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  152659. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  152660. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  152661. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  152662. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  152663. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  152664. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  152665. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  152666. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  152667. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  152668. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  152669. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  152670. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  152671. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  152672. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  152673. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  152674. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  152675. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  152676. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  152677. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  152678. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  152679. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  152680. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  152681. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  152682. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  152683. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  152684. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  152685. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  152686. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  152687. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  152688. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  152689. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  152690. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  152691. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  152692. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  152693. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  152694. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  152695. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  152696. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  152697. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  152698. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  152699. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  152700. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  152701. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  152702. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  152703. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  152704. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  152705. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  152706. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  152707. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  152708. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  152709. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  152710. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  152711. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  152712. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  152713. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  152714. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  152715. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  152716. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  152717. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  152718. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  152719. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  152720. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  152721. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  152722. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  152723. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  152724. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  152725. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  152726. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  152727. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  152728. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  152729. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  152730. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  152731. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  152732. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  152733. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  152734. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  152735. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  152736. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  152737. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  152738. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  152739. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  152740. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  152741. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  152742. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  152743. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  152744. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  152745. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  152746. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  152747. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  152748. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  152749. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  152750. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  152751. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  152752. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  152753. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  152754. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  152755. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  152756. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  152757. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  152758. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  152759. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  152760. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  152761. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  152762. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  152763. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  152764. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  152765. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  152766. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  152767. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  152768. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  152769. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  152770. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  152771. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  152772. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  152773. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  152774. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  152775. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  152776. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  152777. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  152778. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  152779. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  152780. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  152781. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  152782. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  152783. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  152784. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  152785. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  152786. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  152787. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  152788. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  152789. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  152790. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  152791. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  152792. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  152793. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  152794. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  152795. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  152796. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  152797. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  152798. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  152799. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  152800. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  152801. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  152802. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  152803. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  152804. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  152805. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  152806. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  152807. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  152808. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  152809. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  152810. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  152811. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  152812. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  152813. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  152814. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  152815. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  152816. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  152817. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  152818. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  152819. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  152820. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  152821. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  152822. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  152823. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  152824. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  152825. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  152826. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  152827. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  152828. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  152829. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  152830. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  152831. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  152832. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  152833. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  152834. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  152835. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  152836. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  152837. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  152838. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  152839. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  152840. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  152841. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  152842. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  152843. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  152844. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  152845. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  152846. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  152847. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  152848. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  152849. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  152850. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  152851. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  152852. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  152853. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  152854. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  152855. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  152856. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  152857. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  152858. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  152859. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  152860. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  152861. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  152862. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  152863. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  152864. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  152865. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  152866. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  152867. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  152868. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  152869. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  152870. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  152871. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  152872. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  152873. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  152874. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  152875. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  152876. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  152877. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  152878. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  152879. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  152880. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  152881. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  152882. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  152883. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  152884. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  152885. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  152886. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  152887. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  152888. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  152889. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  152890. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  152891. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  152892. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  152893. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  152894. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  152895. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  152896. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  152897. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  152898. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  152899. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  152900. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  152901. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  152902. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  152903. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  152904. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  152905. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  152906. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  152907. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  152908. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  152909. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  152910. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  152911. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  152912. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  152913. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  152914. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  152915. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  152916. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  152917. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  152918. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  152919. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  152920. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  152921. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  152922. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  152923. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  152924. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  152925. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  152926. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  152927. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  152928. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  152929. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  152930. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  152931. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  152932. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  152933. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  152934. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  152935. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  152936. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  152937. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  152938. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  152939. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  152940. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  152941. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  152942. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  152943. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  152944. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  152945. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  152946. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  152947. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  152948. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  152949. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  152950. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  152951. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  152952. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  152953. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  152954. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  152955. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  152956. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  152957. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  152958. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  152959. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  152960. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  152961. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  152962. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  152963. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  152964. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  152965. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  152966. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  152967. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  152968. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  152969. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  152970. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  152971. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  152972. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  152973. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  152974. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  152975. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  152976. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  152977. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  152978. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  152979. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  152980. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  152981. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  152982. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  152983. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  152984. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  152985. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  152986. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  152987. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  152988. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  152989. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  152990. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  152991. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  152992. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  152993. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  152994. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  152995. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  152996. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  152997. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  152998. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  152999. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  153000. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  153001. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  153002. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  153003. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  153004. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  153005. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  153006. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  153007. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  153008. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  153009. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  153010. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  153011. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  153012. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  153013. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  153014. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  153015. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  153016. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  153017. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  153018. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  153019. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  153020. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  153021. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  153022. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  153023. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  153024. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  153025. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  153026. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  153027. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  153028. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  153029. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  153030. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  153031. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  153032. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  153033. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  153034. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  153035. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  153036. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  153037. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  153038. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  153039. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  153040. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  153041. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  153042. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  153043. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  153044. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  153045. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  153046. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  153047. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  153048. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  153049. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  153050. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  153051. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  153052. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  153053. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  153054. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  153055. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  153056. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  153057. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  153058. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  153059. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  153060. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  153061. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  153062. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  153063. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  153064. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  153065. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  153066. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  153067. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  153068. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  153069. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  153070. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  153071. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  153072. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  153073. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  153074. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  153075. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  153076. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  153077. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  153078. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  153079. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  153080. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  153081. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  153082. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  153083. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  153084. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  153085. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  153086. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  153087. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  153088. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  153089. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  153090. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  153091. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  153092. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  153093. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  153094. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  153095. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  153096. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  153097. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  153098. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  153099. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  153100. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  153101. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  153102. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  153103. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  153104. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  153105. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  153106. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  153107. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  153108. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  153109. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  153110. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  153111. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  153112. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  153113. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  153114. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  153115. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  153116. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  153117. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  153118. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  153119. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  153120. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  153121. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  153122. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  153123. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  153124. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  153125. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  153126. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  153127. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  153128. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  153129. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  153130. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  153131. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  153132. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  153133. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  153134. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  153135. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  153136. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  153137. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  153138. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  153139. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  153140. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  153141. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  153142. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  153143. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  153144. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  153145. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  153146. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  153147. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  153148. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  153149. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  153150. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  153151. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  153152. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  153153. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  153154. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  153155. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  153156. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  153157. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  153158. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  153159. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  153160. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  153161. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  153162. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  153163. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  153164. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  153165. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  153166. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  153167. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  153168. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  153169. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  153170. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  153171. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  153172. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  153173. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  153174. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  153175. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  153176. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  153177. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  153178. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  153179. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  153180. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  153181. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  153182. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  153183. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  153184. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  153185. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  153186. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  153187. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  153188. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  153189. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  153190. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  153191. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  153192. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  153193. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  153194. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  153195. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  153196. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  153197. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  153198. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  153199. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  153200. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  153201. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  153202. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  153203. };
  153204. static float *vwin[8] = {
  153205. vwin64,
  153206. vwin128,
  153207. vwin256,
  153208. vwin512,
  153209. vwin1024,
  153210. vwin2048,
  153211. vwin4096,
  153212. vwin8192,
  153213. };
  153214. float *_vorbis_window_get(int n){
  153215. return vwin[n];
  153216. }
  153217. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  153218. int lW,int W,int nW){
  153219. lW=(W?lW:0);
  153220. nW=(W?nW:0);
  153221. {
  153222. float *windowLW=vwin[winno[lW]];
  153223. float *windowNW=vwin[winno[nW]];
  153224. long n=blocksizes[W];
  153225. long ln=blocksizes[lW];
  153226. long rn=blocksizes[nW];
  153227. long leftbegin=n/4-ln/4;
  153228. long leftend=leftbegin+ln/2;
  153229. long rightbegin=n/2+n/4-rn/4;
  153230. long rightend=rightbegin+rn/2;
  153231. int i,p;
  153232. for(i=0;i<leftbegin;i++)
  153233. d[i]=0.f;
  153234. for(p=0;i<leftend;i++,p++)
  153235. d[i]*=windowLW[p];
  153236. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  153237. d[i]*=windowNW[p];
  153238. for(;i<n;i++)
  153239. d[i]=0.f;
  153240. }
  153241. }
  153242. #endif
  153243. /********* End of inlined file: window.c *********/
  153244. }
  153245. BEGIN_JUCE_NAMESPACE
  153246. using namespace OggVorbisNamespace;
  153247. #define oggFormatName TRANS("Ogg-Vorbis file")
  153248. static const tchar* const oggExtensions[] = { T(".ogg"), 0 };
  153249. class OggReader : public AudioFormatReader
  153250. {
  153251. OggVorbis_File ovFile;
  153252. ov_callbacks callbacks;
  153253. AudioSampleBuffer reservoir;
  153254. int reservoirStart, samplesInReservoir;
  153255. public:
  153256. OggReader (InputStream* const inp)
  153257. : AudioFormatReader (inp, oggFormatName),
  153258. reservoir (2, 4096),
  153259. reservoirStart (0),
  153260. samplesInReservoir (0)
  153261. {
  153262. sampleRate = 0;
  153263. usesFloatingPointData = true;
  153264. callbacks.read_func = &oggReadCallback;
  153265. callbacks.seek_func = &oggSeekCallback;
  153266. callbacks.close_func = &oggCloseCallback;
  153267. callbacks.tell_func = &oggTellCallback;
  153268. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  153269. if (err == 0)
  153270. {
  153271. vorbis_info* info = ov_info (&ovFile, -1);
  153272. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  153273. numChannels = info->channels;
  153274. bitsPerSample = 16;
  153275. sampleRate = info->rate;
  153276. reservoir.setSize (numChannels,
  153277. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  153278. }
  153279. }
  153280. ~OggReader()
  153281. {
  153282. ov_clear (&ovFile);
  153283. }
  153284. bool read (int** destSamples,
  153285. int64 startSampleInFile,
  153286. int numSamples)
  153287. {
  153288. int writeOffset = 0;
  153289. while (numSamples > 0)
  153290. {
  153291. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  153292. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  153293. {
  153294. // got a few samples overlapping, so use them before seeking..
  153295. for (unsigned int i = 0; i < numChannels; ++i)
  153296. {
  153297. if (destSamples[i] == 0)
  153298. break;
  153299. memcpy (destSamples[i] + writeOffset,
  153300. reservoir.getSampleData (jmin (i, reservoir.getNumChannels()),
  153301. (int) (startSampleInFile - reservoirStart)),
  153302. sizeof (float) * numSamples);
  153303. }
  153304. startSampleInFile += numAvailable;
  153305. numSamples -= numAvailable;
  153306. writeOffset += numAvailable;
  153307. if (numSamples == 0)
  153308. break;
  153309. }
  153310. if (startSampleInFile < reservoirStart
  153311. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  153312. {
  153313. // buffer miss, so refill the reservoir
  153314. int bitStream = 0;
  153315. reservoirStart = jmax (0, (int) startSampleInFile);
  153316. samplesInReservoir = reservoir.getNumSamples();
  153317. if (reservoirStart != (int) ov_pcm_tell (&ovFile))
  153318. ov_pcm_seek (&ovFile, reservoirStart);
  153319. int offset = 0;
  153320. int numToRead = samplesInReservoir;
  153321. while (numToRead > 0)
  153322. {
  153323. float** dataIn = 0;
  153324. const int samps = ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  153325. if (samps == 0)
  153326. break;
  153327. jassert (samps <= numToRead);
  153328. for (int i = jmin (numChannels, reservoir.getNumChannels()); --i >= 0;)
  153329. {
  153330. memcpy (reservoir.getSampleData (i, offset),
  153331. dataIn[i],
  153332. sizeof (float) * samps);
  153333. }
  153334. numToRead -= samps;
  153335. offset += samps;
  153336. }
  153337. if (numToRead > 0)
  153338. reservoir.clear (offset, numToRead);
  153339. }
  153340. }
  153341. return true;
  153342. }
  153343. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  153344. {
  153345. return (size_t) (((InputStream*) datasource)->read (ptr, (int) (size * nmemb)) / size);
  153346. }
  153347. static int oggSeekCallback (void* datasource, ogg_int64_t offset, int whence)
  153348. {
  153349. InputStream* const in = (InputStream*) datasource;
  153350. if (whence == SEEK_CUR)
  153351. offset += in->getPosition();
  153352. else if (whence == SEEK_END)
  153353. offset += in->getTotalLength();
  153354. in->setPosition (offset);
  153355. return 0;
  153356. }
  153357. static int oggCloseCallback (void*)
  153358. {
  153359. return 0;
  153360. }
  153361. static long oggTellCallback (void* datasource)
  153362. {
  153363. return (long) ((InputStream*) datasource)->getPosition();
  153364. }
  153365. juce_UseDebuggingNewOperator
  153366. };
  153367. class OggWriter : public AudioFormatWriter
  153368. {
  153369. ogg_stream_state os;
  153370. ogg_page og;
  153371. ogg_packet op;
  153372. vorbis_info vi;
  153373. vorbis_comment vc;
  153374. vorbis_dsp_state vd;
  153375. vorbis_block vb;
  153376. public:
  153377. bool ok;
  153378. OggWriter (OutputStream* const out,
  153379. const double sampleRate,
  153380. const int numChannels,
  153381. const int bitsPerSample,
  153382. const int qualityIndex)
  153383. : AudioFormatWriter (out, oggFormatName,
  153384. sampleRate,
  153385. numChannels,
  153386. bitsPerSample)
  153387. {
  153388. ok = false;
  153389. vorbis_info_init (&vi);
  153390. if (vorbis_encode_init_vbr (&vi,
  153391. numChannels,
  153392. (int) sampleRate,
  153393. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  153394. {
  153395. vorbis_comment_init (&vc);
  153396. if (JUCEApplication::getInstance() != 0)
  153397. vorbis_comment_add_tag (&vc, "ENCODER",
  153398. (char*) (const char*) JUCEApplication::getInstance()->getApplicationName());
  153399. vorbis_analysis_init (&vd, &vi);
  153400. vorbis_block_init (&vd, &vb);
  153401. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  153402. ogg_packet header;
  153403. ogg_packet header_comm;
  153404. ogg_packet header_code;
  153405. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  153406. ogg_stream_packetin (&os, &header);
  153407. ogg_stream_packetin (&os, &header_comm);
  153408. ogg_stream_packetin (&os, &header_code);
  153409. for (;;)
  153410. {
  153411. if (ogg_stream_flush (&os, &og) == 0)
  153412. break;
  153413. output->write (og.header, og.header_len);
  153414. output->write (og.body, og.body_len);
  153415. }
  153416. ok = true;
  153417. }
  153418. }
  153419. ~OggWriter()
  153420. {
  153421. if (ok)
  153422. {
  153423. ogg_stream_clear (&os);
  153424. vorbis_block_clear (&vb);
  153425. vorbis_dsp_clear (&vd);
  153426. vorbis_comment_clear (&vc);
  153427. vorbis_info_clear (&vi);
  153428. output->flush();
  153429. }
  153430. else
  153431. {
  153432. vorbis_info_clear (&vi);
  153433. output = 0; // to stop the base class deleting this, as it needs to be returned
  153434. // to the caller of createWriter()
  153435. }
  153436. }
  153437. bool write (const int** samplesToWrite, int numSamples)
  153438. {
  153439. if (! ok)
  153440. return false;
  153441. if (numSamples > 0)
  153442. {
  153443. const double gain = 1.0 / 0x80000000u;
  153444. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  153445. for (int i = numChannels; --i >= 0;)
  153446. {
  153447. float* const dst = vorbisBuffer[i];
  153448. const int* const src = samplesToWrite [i];
  153449. if (src != 0 && dst != 0)
  153450. {
  153451. for (int j = 0; j < numSamples; ++j)
  153452. dst[j] = (float) (src[j] * gain);
  153453. }
  153454. }
  153455. }
  153456. vorbis_analysis_wrote (&vd, numSamples);
  153457. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  153458. {
  153459. vorbis_analysis (&vb, 0);
  153460. vorbis_bitrate_addblock (&vb);
  153461. while (vorbis_bitrate_flushpacket (&vd, &op))
  153462. {
  153463. ogg_stream_packetin (&os, &op);
  153464. for (;;)
  153465. {
  153466. if (ogg_stream_pageout (&os, &og) == 0)
  153467. break;
  153468. output->write (og.header, og.header_len);
  153469. output->write (og.body, og.body_len);
  153470. if (ogg_page_eos (&og))
  153471. break;
  153472. }
  153473. }
  153474. }
  153475. return true;
  153476. }
  153477. juce_UseDebuggingNewOperator
  153478. };
  153479. OggVorbisAudioFormat::OggVorbisAudioFormat()
  153480. : AudioFormat (oggFormatName, (const tchar**) oggExtensions)
  153481. {
  153482. }
  153483. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  153484. {
  153485. }
  153486. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  153487. {
  153488. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  153489. return Array <int> (rates);
  153490. }
  153491. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  153492. {
  153493. Array <int> depths;
  153494. depths.add (32);
  153495. return depths;
  153496. }
  153497. bool OggVorbisAudioFormat::canDoStereo()
  153498. {
  153499. return true;
  153500. }
  153501. bool OggVorbisAudioFormat::canDoMono()
  153502. {
  153503. return true;
  153504. }
  153505. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  153506. const bool deleteStreamIfOpeningFails)
  153507. {
  153508. OggReader* r = new OggReader (in);
  153509. if (r->sampleRate == 0)
  153510. {
  153511. if (! deleteStreamIfOpeningFails)
  153512. r->input = 0;
  153513. deleteAndZero (r);
  153514. }
  153515. return r;
  153516. }
  153517. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  153518. double sampleRate,
  153519. unsigned int numChannels,
  153520. int bitsPerSample,
  153521. const StringPairArray& /*metadataValues*/,
  153522. int qualityOptionIndex)
  153523. {
  153524. OggWriter* w = new OggWriter (out,
  153525. sampleRate,
  153526. numChannels,
  153527. bitsPerSample,
  153528. qualityOptionIndex);
  153529. if (! w->ok)
  153530. deleteAndZero (w);
  153531. return w;
  153532. }
  153533. bool OggVorbisAudioFormat::isCompressed()
  153534. {
  153535. return true;
  153536. }
  153537. const StringArray OggVorbisAudioFormat::getQualityOptions()
  153538. {
  153539. StringArray s;
  153540. s.add ("Low Quality");
  153541. s.add ("Medium Quality");
  153542. s.add ("High Quality");
  153543. return s;
  153544. }
  153545. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  153546. {
  153547. FileInputStream* const in = source.createInputStream();
  153548. if (in != 0)
  153549. {
  153550. AudioFormatReader* const r = createReaderFor (in, true);
  153551. if (r != 0)
  153552. {
  153553. const int64 numSamps = r->lengthInSamples;
  153554. delete r;
  153555. const int64 fileNumSamps = source.getSize() / 4;
  153556. const double ratio = numSamps / (double) fileNumSamps;
  153557. if (ratio > 12.0)
  153558. return 0;
  153559. else if (ratio > 6.0)
  153560. return 1;
  153561. else
  153562. return 2;
  153563. }
  153564. }
  153565. return 1;
  153566. }
  153567. END_JUCE_NAMESPACE
  153568. #endif
  153569. /********* End of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  153570. /********* Start of inlined file: juce_JPEGLoader.cpp *********/
  153571. #if JUCE_MSVC
  153572. #pragma warning (push)
  153573. #endif
  153574. namespace jpeglibNamespace
  153575. {
  153576. extern "C"
  153577. {
  153578. #define JPEG_INTERNALS
  153579. #undef FAR
  153580. /********* Start of inlined file: jpeglib.h *********/
  153581. #ifndef JPEGLIB_H
  153582. #define JPEGLIB_H
  153583. /*
  153584. * First we include the configuration files that record how this
  153585. * installation of the JPEG library is set up. jconfig.h can be
  153586. * generated automatically for many systems. jmorecfg.h contains
  153587. * manual configuration options that most people need not worry about.
  153588. */
  153589. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  153590. /********* Start of inlined file: jconfig.h *********/
  153591. /* see jconfig.doc for explanations */
  153592. // disable all the warnings under MSVC
  153593. #ifdef _MSC_VER
  153594. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  153595. #endif
  153596. #ifdef __BORLANDC__
  153597. #pragma warn -8057
  153598. #pragma warn -8019
  153599. #pragma warn -8004
  153600. #pragma warn -8008
  153601. #endif
  153602. #define HAVE_PROTOTYPES
  153603. #define HAVE_UNSIGNED_CHAR
  153604. #define HAVE_UNSIGNED_SHORT
  153605. /* #define void char */
  153606. /* #define const */
  153607. #undef CHAR_IS_UNSIGNED
  153608. #define HAVE_STDDEF_H
  153609. #define HAVE_STDLIB_H
  153610. #undef NEED_BSD_STRINGS
  153611. #undef NEED_SYS_TYPES_H
  153612. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  153613. #undef NEED_SHORT_EXTERNAL_NAMES
  153614. #undef INCOMPLETE_TYPES_BROKEN
  153615. /* Define "boolean" as unsigned char, not int, per Windows custom */
  153616. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  153617. typedef unsigned char boolean;
  153618. #endif
  153619. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  153620. #ifdef JPEG_INTERNALS
  153621. #undef RIGHT_SHIFT_IS_UNSIGNED
  153622. #endif /* JPEG_INTERNALS */
  153623. #ifdef JPEG_CJPEG_DJPEG
  153624. #define BMP_SUPPORTED /* BMP image file format */
  153625. #define GIF_SUPPORTED /* GIF image file format */
  153626. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  153627. #undef RLE_SUPPORTED /* Utah RLE image file format */
  153628. #define TARGA_SUPPORTED /* Targa image file format */
  153629. #define TWO_FILE_COMMANDLINE /* optional */
  153630. #define USE_SETMODE /* Microsoft has setmode() */
  153631. #undef NEED_SIGNAL_CATCHER
  153632. #undef DONT_USE_B_MODE
  153633. #undef PROGRESS_REPORT /* optional */
  153634. #endif /* JPEG_CJPEG_DJPEG */
  153635. /********* End of inlined file: jconfig.h *********/
  153636. /* widely used configuration options */
  153637. #endif
  153638. /********* Start of inlined file: jmorecfg.h *********/
  153639. /*
  153640. * Define BITS_IN_JSAMPLE as either
  153641. * 8 for 8-bit sample values (the usual setting)
  153642. * 12 for 12-bit sample values
  153643. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  153644. * JPEG standard, and the IJG code does not support anything else!
  153645. * We do not support run-time selection of data precision, sorry.
  153646. */
  153647. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  153648. /*
  153649. * Maximum number of components (color channels) allowed in JPEG image.
  153650. * To meet the letter of the JPEG spec, set this to 255. However, darn
  153651. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  153652. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  153653. * really short on memory. (Each allowed component costs a hundred or so
  153654. * bytes of storage, whether actually used in an image or not.)
  153655. */
  153656. #define MAX_COMPONENTS 10 /* maximum number of image components */
  153657. /*
  153658. * Basic data types.
  153659. * You may need to change these if you have a machine with unusual data
  153660. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  153661. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  153662. * but it had better be at least 16.
  153663. */
  153664. /* Representation of a single sample (pixel element value).
  153665. * We frequently allocate large arrays of these, so it's important to keep
  153666. * them small. But if you have memory to burn and access to char or short
  153667. * arrays is very slow on your hardware, you might want to change these.
  153668. */
  153669. #if BITS_IN_JSAMPLE == 8
  153670. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  153671. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  153672. */
  153673. #ifdef HAVE_UNSIGNED_CHAR
  153674. typedef unsigned char JSAMPLE;
  153675. #define GETJSAMPLE(value) ((int) (value))
  153676. #else /* not HAVE_UNSIGNED_CHAR */
  153677. typedef char JSAMPLE;
  153678. #ifdef CHAR_IS_UNSIGNED
  153679. #define GETJSAMPLE(value) ((int) (value))
  153680. #else
  153681. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  153682. #endif /* CHAR_IS_UNSIGNED */
  153683. #endif /* HAVE_UNSIGNED_CHAR */
  153684. #define MAXJSAMPLE 255
  153685. #define CENTERJSAMPLE 128
  153686. #endif /* BITS_IN_JSAMPLE == 8 */
  153687. #if BITS_IN_JSAMPLE == 12
  153688. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  153689. * On nearly all machines "short" will do nicely.
  153690. */
  153691. typedef short JSAMPLE;
  153692. #define GETJSAMPLE(value) ((int) (value))
  153693. #define MAXJSAMPLE 4095
  153694. #define CENTERJSAMPLE 2048
  153695. #endif /* BITS_IN_JSAMPLE == 12 */
  153696. /* Representation of a DCT frequency coefficient.
  153697. * This should be a signed value of at least 16 bits; "short" is usually OK.
  153698. * Again, we allocate large arrays of these, but you can change to int
  153699. * if you have memory to burn and "short" is really slow.
  153700. */
  153701. typedef short JCOEF;
  153702. /* Compressed datastreams are represented as arrays of JOCTET.
  153703. * These must be EXACTLY 8 bits wide, at least once they are written to
  153704. * external storage. Note that when using the stdio data source/destination
  153705. * managers, this is also the data type passed to fread/fwrite.
  153706. */
  153707. #ifdef HAVE_UNSIGNED_CHAR
  153708. typedef unsigned char JOCTET;
  153709. #define GETJOCTET(value) (value)
  153710. #else /* not HAVE_UNSIGNED_CHAR */
  153711. typedef char JOCTET;
  153712. #ifdef CHAR_IS_UNSIGNED
  153713. #define GETJOCTET(value) (value)
  153714. #else
  153715. #define GETJOCTET(value) ((value) & 0xFF)
  153716. #endif /* CHAR_IS_UNSIGNED */
  153717. #endif /* HAVE_UNSIGNED_CHAR */
  153718. /* These typedefs are used for various table entries and so forth.
  153719. * They must be at least as wide as specified; but making them too big
  153720. * won't cost a huge amount of memory, so we don't provide special
  153721. * extraction code like we did for JSAMPLE. (In other words, these
  153722. * typedefs live at a different point on the speed/space tradeoff curve.)
  153723. */
  153724. /* UINT8 must hold at least the values 0..255. */
  153725. #ifdef HAVE_UNSIGNED_CHAR
  153726. typedef unsigned char UINT8;
  153727. #else /* not HAVE_UNSIGNED_CHAR */
  153728. #ifdef CHAR_IS_UNSIGNED
  153729. typedef char UINT8;
  153730. #else /* not CHAR_IS_UNSIGNED */
  153731. typedef short UINT8;
  153732. #endif /* CHAR_IS_UNSIGNED */
  153733. #endif /* HAVE_UNSIGNED_CHAR */
  153734. /* UINT16 must hold at least the values 0..65535. */
  153735. #ifdef HAVE_UNSIGNED_SHORT
  153736. typedef unsigned short UINT16;
  153737. #else /* not HAVE_UNSIGNED_SHORT */
  153738. typedef unsigned int UINT16;
  153739. #endif /* HAVE_UNSIGNED_SHORT */
  153740. /* INT16 must hold at least the values -32768..32767. */
  153741. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  153742. typedef short INT16;
  153743. #endif
  153744. /* INT32 must hold at least signed 32-bit values. */
  153745. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  153746. typedef long INT32;
  153747. #endif
  153748. /* Datatype used for image dimensions. The JPEG standard only supports
  153749. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  153750. * "unsigned int" is sufficient on all machines. However, if you need to
  153751. * handle larger images and you don't mind deviating from the spec, you
  153752. * can change this datatype.
  153753. */
  153754. typedef unsigned int JDIMENSION;
  153755. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  153756. /* These macros are used in all function definitions and extern declarations.
  153757. * You could modify them if you need to change function linkage conventions;
  153758. * in particular, you'll need to do that to make the library a Windows DLL.
  153759. * Another application is to make all functions global for use with debuggers
  153760. * or code profilers that require it.
  153761. */
  153762. /* a function called through method pointers: */
  153763. #define METHODDEF(type) static type
  153764. /* a function used only in its module: */
  153765. #define LOCAL(type) static type
  153766. /* a function referenced thru EXTERNs: */
  153767. #define GLOBAL(type) type
  153768. /* a reference to a GLOBAL function: */
  153769. #define EXTERN(type) extern type
  153770. /* This macro is used to declare a "method", that is, a function pointer.
  153771. * We want to supply prototype parameters if the compiler can cope.
  153772. * Note that the arglist parameter must be parenthesized!
  153773. * Again, you can customize this if you need special linkage keywords.
  153774. */
  153775. #ifdef HAVE_PROTOTYPES
  153776. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  153777. #else
  153778. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  153779. #endif
  153780. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  153781. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  153782. * by just saying "FAR *" where such a pointer is needed. In a few places
  153783. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  153784. */
  153785. #ifdef NEED_FAR_POINTERS
  153786. #define FAR far
  153787. #else
  153788. #define FAR
  153789. #endif
  153790. /*
  153791. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  153792. * in standard header files. Or you may have conflicts with application-
  153793. * specific header files that you want to include together with these files.
  153794. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  153795. */
  153796. #ifndef HAVE_BOOLEAN
  153797. typedef int boolean;
  153798. #endif
  153799. #ifndef FALSE /* in case these macros already exist */
  153800. #define FALSE 0 /* values of boolean */
  153801. #endif
  153802. #ifndef TRUE
  153803. #define TRUE 1
  153804. #endif
  153805. /*
  153806. * The remaining options affect code selection within the JPEG library,
  153807. * but they don't need to be visible to most applications using the library.
  153808. * To minimize application namespace pollution, the symbols won't be
  153809. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  153810. */
  153811. #ifdef JPEG_INTERNALS
  153812. #define JPEG_INTERNAL_OPTIONS
  153813. #endif
  153814. #ifdef JPEG_INTERNAL_OPTIONS
  153815. /*
  153816. * These defines indicate whether to include various optional functions.
  153817. * Undefining some of these symbols will produce a smaller but less capable
  153818. * library. Note that you can leave certain source files out of the
  153819. * compilation/linking process if you've #undef'd the corresponding symbols.
  153820. * (You may HAVE to do that if your compiler doesn't like null source files.)
  153821. */
  153822. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  153823. /* Capability options common to encoder and decoder: */
  153824. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  153825. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  153826. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  153827. /* Encoder capability options: */
  153828. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  153829. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  153830. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  153831. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  153832. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  153833. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  153834. * precision, so jchuff.c normally uses entropy optimization to compute
  153835. * usable tables for higher precision. If you don't want to do optimization,
  153836. * you'll have to supply different default Huffman tables.
  153837. * The exact same statements apply for progressive JPEG: the default tables
  153838. * don't work for progressive mode. (This may get fixed, however.)
  153839. */
  153840. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  153841. /* Decoder capability options: */
  153842. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  153843. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  153844. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  153845. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  153846. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  153847. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  153848. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  153849. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  153850. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  153851. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  153852. /* more capability options later, no doubt */
  153853. /*
  153854. * Ordering of RGB data in scanlines passed to or from the application.
  153855. * If your application wants to deal with data in the order B,G,R, just
  153856. * change these macros. You can also deal with formats such as R,G,B,X
  153857. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  153858. * the offsets will also change the order in which colormap data is organized.
  153859. * RESTRICTIONS:
  153860. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  153861. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  153862. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  153863. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  153864. * is not 3 (they don't understand about dummy color components!). So you
  153865. * can't use color quantization if you change that value.
  153866. */
  153867. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  153868. #define RGB_GREEN 1 /* Offset of Green */
  153869. #define RGB_BLUE 2 /* Offset of Blue */
  153870. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  153871. /* Definitions for speed-related optimizations. */
  153872. /* If your compiler supports inline functions, define INLINE
  153873. * as the inline keyword; otherwise define it as empty.
  153874. */
  153875. #ifndef INLINE
  153876. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  153877. #define INLINE __inline__
  153878. #endif
  153879. #ifndef INLINE
  153880. #define INLINE /* default is to define it as empty */
  153881. #endif
  153882. #endif
  153883. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  153884. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  153885. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  153886. */
  153887. #ifndef MULTIPLIER
  153888. #define MULTIPLIER int /* type for fastest integer multiply */
  153889. #endif
  153890. /* FAST_FLOAT should be either float or double, whichever is done faster
  153891. * by your compiler. (Note that this type is only used in the floating point
  153892. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  153893. * Typically, float is faster in ANSI C compilers, while double is faster in
  153894. * pre-ANSI compilers (because they insist on converting to double anyway).
  153895. * The code below therefore chooses float if we have ANSI-style prototypes.
  153896. */
  153897. #ifndef FAST_FLOAT
  153898. #ifdef HAVE_PROTOTYPES
  153899. #define FAST_FLOAT float
  153900. #else
  153901. #define FAST_FLOAT double
  153902. #endif
  153903. #endif
  153904. #endif /* JPEG_INTERNAL_OPTIONS */
  153905. /********* End of inlined file: jmorecfg.h *********/
  153906. /* seldom changed options */
  153907. /* Version ID for the JPEG library.
  153908. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  153909. */
  153910. #define JPEG_LIB_VERSION 62 /* Version 6b */
  153911. /* Various constants determining the sizes of things.
  153912. * All of these are specified by the JPEG standard, so don't change them
  153913. * if you want to be compatible.
  153914. */
  153915. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  153916. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  153917. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  153918. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  153919. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  153920. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  153921. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  153922. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  153923. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  153924. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  153925. * to handle it. We even let you do this from the jconfig.h file. However,
  153926. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  153927. * sometimes emits noncompliant files doesn't mean you should too.
  153928. */
  153929. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  153930. #ifndef D_MAX_BLOCKS_IN_MCU
  153931. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  153932. #endif
  153933. /* Data structures for images (arrays of samples and of DCT coefficients).
  153934. * On 80x86 machines, the image arrays are too big for near pointers,
  153935. * but the pointer arrays can fit in near memory.
  153936. */
  153937. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  153938. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  153939. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  153940. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  153941. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  153942. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  153943. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  153944. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  153945. /* Types for JPEG compression parameters and working tables. */
  153946. /* DCT coefficient quantization tables. */
  153947. typedef struct {
  153948. /* This array gives the coefficient quantizers in natural array order
  153949. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  153950. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  153951. */
  153952. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  153953. /* This field is used only during compression. It's initialized FALSE when
  153954. * the table is created, and set TRUE when it's been output to the file.
  153955. * You could suppress output of a table by setting this to TRUE.
  153956. * (See jpeg_suppress_tables for an example.)
  153957. */
  153958. boolean sent_table; /* TRUE when table has been output */
  153959. } JQUANT_TBL;
  153960. /* Huffman coding tables. */
  153961. typedef struct {
  153962. /* These two fields directly represent the contents of a JPEG DHT marker */
  153963. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  153964. /* length k bits; bits[0] is unused */
  153965. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  153966. /* This field is used only during compression. It's initialized FALSE when
  153967. * the table is created, and set TRUE when it's been output to the file.
  153968. * You could suppress output of a table by setting this to TRUE.
  153969. * (See jpeg_suppress_tables for an example.)
  153970. */
  153971. boolean sent_table; /* TRUE when table has been output */
  153972. } JHUFF_TBL;
  153973. /* Basic info about one component (color channel). */
  153974. typedef struct {
  153975. /* These values are fixed over the whole image. */
  153976. /* For compression, they must be supplied by parameter setup; */
  153977. /* for decompression, they are read from the SOF marker. */
  153978. int component_id; /* identifier for this component (0..255) */
  153979. int component_index; /* its index in SOF or cinfo->comp_info[] */
  153980. int h_samp_factor; /* horizontal sampling factor (1..4) */
  153981. int v_samp_factor; /* vertical sampling factor (1..4) */
  153982. int quant_tbl_no; /* quantization table selector (0..3) */
  153983. /* These values may vary between scans. */
  153984. /* For compression, they must be supplied by parameter setup; */
  153985. /* for decompression, they are read from the SOS marker. */
  153986. /* The decompressor output side may not use these variables. */
  153987. int dc_tbl_no; /* DC entropy table selector (0..3) */
  153988. int ac_tbl_no; /* AC entropy table selector (0..3) */
  153989. /* Remaining fields should be treated as private by applications. */
  153990. /* These values are computed during compression or decompression startup: */
  153991. /* Component's size in DCT blocks.
  153992. * Any dummy blocks added to complete an MCU are not counted; therefore
  153993. * these values do not depend on whether a scan is interleaved or not.
  153994. */
  153995. JDIMENSION width_in_blocks;
  153996. JDIMENSION height_in_blocks;
  153997. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  153998. * For decompression this is the size of the output from one DCT block,
  153999. * reflecting any scaling we choose to apply during the IDCT step.
  154000. * Values of 1,2,4,8 are likely to be supported. Note that different
  154001. * components may receive different IDCT scalings.
  154002. */
  154003. int DCT_scaled_size;
  154004. /* The downsampled dimensions are the component's actual, unpadded number
  154005. * of samples at the main buffer (preprocessing/compression interface), thus
  154006. * downsampled_width = ceil(image_width * Hi/Hmax)
  154007. * and similarly for height. For decompression, IDCT scaling is included, so
  154008. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  154009. */
  154010. JDIMENSION downsampled_width; /* actual width in samples */
  154011. JDIMENSION downsampled_height; /* actual height in samples */
  154012. /* This flag is used only for decompression. In cases where some of the
  154013. * components will be ignored (eg grayscale output from YCbCr image),
  154014. * we can skip most computations for the unused components.
  154015. */
  154016. boolean component_needed; /* do we need the value of this component? */
  154017. /* These values are computed before starting a scan of the component. */
  154018. /* The decompressor output side may not use these variables. */
  154019. int MCU_width; /* number of blocks per MCU, horizontally */
  154020. int MCU_height; /* number of blocks per MCU, vertically */
  154021. int MCU_blocks; /* MCU_width * MCU_height */
  154022. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  154023. int last_col_width; /* # of non-dummy blocks across in last MCU */
  154024. int last_row_height; /* # of non-dummy blocks down in last MCU */
  154025. /* Saved quantization table for component; NULL if none yet saved.
  154026. * See jdinput.c comments about the need for this information.
  154027. * This field is currently used only for decompression.
  154028. */
  154029. JQUANT_TBL * quant_table;
  154030. /* Private per-component storage for DCT or IDCT subsystem. */
  154031. void * dct_table;
  154032. } jpeg_component_info;
  154033. /* The script for encoding a multiple-scan file is an array of these: */
  154034. typedef struct {
  154035. int comps_in_scan; /* number of components encoded in this scan */
  154036. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  154037. int Ss, Se; /* progressive JPEG spectral selection parms */
  154038. int Ah, Al; /* progressive JPEG successive approx. parms */
  154039. } jpeg_scan_info;
  154040. /* The decompressor can save APPn and COM markers in a list of these: */
  154041. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  154042. struct jpeg_marker_struct {
  154043. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  154044. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  154045. unsigned int original_length; /* # bytes of data in the file */
  154046. unsigned int data_length; /* # bytes of data saved at data[] */
  154047. JOCTET FAR * data; /* the data contained in the marker */
  154048. /* the marker length word is not counted in data_length or original_length */
  154049. };
  154050. /* Known color spaces. */
  154051. typedef enum {
  154052. JCS_UNKNOWN, /* error/unspecified */
  154053. JCS_GRAYSCALE, /* monochrome */
  154054. JCS_RGB, /* red/green/blue */
  154055. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  154056. JCS_CMYK, /* C/M/Y/K */
  154057. JCS_YCCK /* Y/Cb/Cr/K */
  154058. } J_COLOR_SPACE;
  154059. /* DCT/IDCT algorithm options. */
  154060. typedef enum {
  154061. JDCT_ISLOW, /* slow but accurate integer algorithm */
  154062. JDCT_IFAST, /* faster, less accurate integer method */
  154063. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  154064. } J_DCT_METHOD;
  154065. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  154066. #define JDCT_DEFAULT JDCT_ISLOW
  154067. #endif
  154068. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  154069. #define JDCT_FASTEST JDCT_IFAST
  154070. #endif
  154071. /* Dithering options for decompression. */
  154072. typedef enum {
  154073. JDITHER_NONE, /* no dithering */
  154074. JDITHER_ORDERED, /* simple ordered dither */
  154075. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  154076. } J_DITHER_MODE;
  154077. /* Common fields between JPEG compression and decompression master structs. */
  154078. #define jpeg_common_fields \
  154079. struct jpeg_error_mgr * err; /* Error handler module */\
  154080. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  154081. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  154082. void * client_data; /* Available for use by application */\
  154083. boolean is_decompressor; /* So common code can tell which is which */\
  154084. int global_state /* For checking call sequence validity */
  154085. /* Routines that are to be used by both halves of the library are declared
  154086. * to receive a pointer to this structure. There are no actual instances of
  154087. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  154088. */
  154089. struct jpeg_common_struct {
  154090. jpeg_common_fields; /* Fields common to both master struct types */
  154091. /* Additional fields follow in an actual jpeg_compress_struct or
  154092. * jpeg_decompress_struct. All three structs must agree on these
  154093. * initial fields! (This would be a lot cleaner in C++.)
  154094. */
  154095. };
  154096. typedef struct jpeg_common_struct * j_common_ptr;
  154097. typedef struct jpeg_compress_struct * j_compress_ptr;
  154098. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  154099. /* Master record for a compression instance */
  154100. struct jpeg_compress_struct {
  154101. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  154102. /* Destination for compressed data */
  154103. struct jpeg_destination_mgr * dest;
  154104. /* Description of source image --- these fields must be filled in by
  154105. * outer application before starting compression. in_color_space must
  154106. * be correct before you can even call jpeg_set_defaults().
  154107. */
  154108. JDIMENSION image_width; /* input image width */
  154109. JDIMENSION image_height; /* input image height */
  154110. int input_components; /* # of color components in input image */
  154111. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  154112. double input_gamma; /* image gamma of input image */
  154113. /* Compression parameters --- these fields must be set before calling
  154114. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  154115. * initialize everything to reasonable defaults, then changing anything
  154116. * the application specifically wants to change. That way you won't get
  154117. * burnt when new parameters are added. Also note that there are several
  154118. * helper routines to simplify changing parameters.
  154119. */
  154120. int data_precision; /* bits of precision in image data */
  154121. int num_components; /* # of color components in JPEG image */
  154122. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  154123. jpeg_component_info * comp_info;
  154124. /* comp_info[i] describes component that appears i'th in SOF */
  154125. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  154126. /* ptrs to coefficient quantization tables, or NULL if not defined */
  154127. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  154128. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  154129. /* ptrs to Huffman coding tables, or NULL if not defined */
  154130. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  154131. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  154132. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  154133. int num_scans; /* # of entries in scan_info array */
  154134. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  154135. /* The default value of scan_info is NULL, which causes a single-scan
  154136. * sequential JPEG file to be emitted. To create a multi-scan file,
  154137. * set num_scans and scan_info to point to an array of scan definitions.
  154138. */
  154139. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  154140. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  154141. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  154142. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  154143. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  154144. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  154145. /* The restart interval can be specified in absolute MCUs by setting
  154146. * restart_interval, or in MCU rows by setting restart_in_rows
  154147. * (in which case the correct restart_interval will be figured
  154148. * for each scan).
  154149. */
  154150. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  154151. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  154152. /* Parameters controlling emission of special markers. */
  154153. boolean write_JFIF_header; /* should a JFIF marker be written? */
  154154. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  154155. UINT8 JFIF_minor_version;
  154156. /* These three values are not used by the JPEG code, merely copied */
  154157. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  154158. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  154159. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  154160. UINT8 density_unit; /* JFIF code for pixel size units */
  154161. UINT16 X_density; /* Horizontal pixel density */
  154162. UINT16 Y_density; /* Vertical pixel density */
  154163. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  154164. /* State variable: index of next scanline to be written to
  154165. * jpeg_write_scanlines(). Application may use this to control its
  154166. * processing loop, e.g., "while (next_scanline < image_height)".
  154167. */
  154168. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  154169. /* Remaining fields are known throughout compressor, but generally
  154170. * should not be touched by a surrounding application.
  154171. */
  154172. /*
  154173. * These fields are computed during compression startup
  154174. */
  154175. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  154176. int max_h_samp_factor; /* largest h_samp_factor */
  154177. int max_v_samp_factor; /* largest v_samp_factor */
  154178. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  154179. /* The coefficient controller receives data in units of MCU rows as defined
  154180. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  154181. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  154182. * "iMCU" (interleaved MCU) row.
  154183. */
  154184. /*
  154185. * These fields are valid during any one scan.
  154186. * They describe the components and MCUs actually appearing in the scan.
  154187. */
  154188. int comps_in_scan; /* # of JPEG components in this scan */
  154189. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  154190. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  154191. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  154192. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  154193. int blocks_in_MCU; /* # of DCT blocks per MCU */
  154194. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  154195. /* MCU_membership[i] is index in cur_comp_info of component owning */
  154196. /* i'th block in an MCU */
  154197. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  154198. /*
  154199. * Links to compression subobjects (methods and private variables of modules)
  154200. */
  154201. struct jpeg_comp_master * master;
  154202. struct jpeg_c_main_controller * main;
  154203. struct jpeg_c_prep_controller * prep;
  154204. struct jpeg_c_coef_controller * coef;
  154205. struct jpeg_marker_writer * marker;
  154206. struct jpeg_color_converter * cconvert;
  154207. struct jpeg_downsampler * downsample;
  154208. struct jpeg_forward_dct * fdct;
  154209. struct jpeg_entropy_encoder * entropy;
  154210. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  154211. int script_space_size;
  154212. };
  154213. /* Master record for a decompression instance */
  154214. struct jpeg_decompress_struct {
  154215. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  154216. /* Source of compressed data */
  154217. struct jpeg_source_mgr * src;
  154218. /* Basic description of image --- filled in by jpeg_read_header(). */
  154219. /* Application may inspect these values to decide how to process image. */
  154220. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  154221. JDIMENSION image_height; /* nominal image height */
  154222. int num_components; /* # of color components in JPEG image */
  154223. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  154224. /* Decompression processing parameters --- these fields must be set before
  154225. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  154226. * them to default values.
  154227. */
  154228. J_COLOR_SPACE out_color_space; /* colorspace for output */
  154229. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  154230. double output_gamma; /* image gamma wanted in output */
  154231. boolean buffered_image; /* TRUE=multiple output passes */
  154232. boolean raw_data_out; /* TRUE=downsampled data wanted */
  154233. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  154234. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  154235. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  154236. boolean quantize_colors; /* TRUE=colormapped output wanted */
  154237. /* the following are ignored if not quantize_colors: */
  154238. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  154239. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  154240. int desired_number_of_colors; /* max # colors to use in created colormap */
  154241. /* these are significant only in buffered-image mode: */
  154242. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  154243. boolean enable_external_quant;/* enable future use of external colormap */
  154244. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  154245. /* Description of actual output image that will be returned to application.
  154246. * These fields are computed by jpeg_start_decompress().
  154247. * You can also use jpeg_calc_output_dimensions() to determine these values
  154248. * in advance of calling jpeg_start_decompress().
  154249. */
  154250. JDIMENSION output_width; /* scaled image width */
  154251. JDIMENSION output_height; /* scaled image height */
  154252. int out_color_components; /* # of color components in out_color_space */
  154253. int output_components; /* # of color components returned */
  154254. /* output_components is 1 (a colormap index) when quantizing colors;
  154255. * otherwise it equals out_color_components.
  154256. */
  154257. int rec_outbuf_height; /* min recommended height of scanline buffer */
  154258. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  154259. * high, space and time will be wasted due to unnecessary data copying.
  154260. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  154261. */
  154262. /* When quantizing colors, the output colormap is described by these fields.
  154263. * The application can supply a colormap by setting colormap non-NULL before
  154264. * calling jpeg_start_decompress; otherwise a colormap is created during
  154265. * jpeg_start_decompress or jpeg_start_output.
  154266. * The map has out_color_components rows and actual_number_of_colors columns.
  154267. */
  154268. int actual_number_of_colors; /* number of entries in use */
  154269. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  154270. /* State variables: these variables indicate the progress of decompression.
  154271. * The application may examine these but must not modify them.
  154272. */
  154273. /* Row index of next scanline to be read from jpeg_read_scanlines().
  154274. * Application may use this to control its processing loop, e.g.,
  154275. * "while (output_scanline < output_height)".
  154276. */
  154277. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  154278. /* Current input scan number and number of iMCU rows completed in scan.
  154279. * These indicate the progress of the decompressor input side.
  154280. */
  154281. int input_scan_number; /* Number of SOS markers seen so far */
  154282. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  154283. /* The "output scan number" is the notional scan being displayed by the
  154284. * output side. The decompressor will not allow output scan/row number
  154285. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  154286. */
  154287. int output_scan_number; /* Nominal scan number being displayed */
  154288. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  154289. /* Current progression status. coef_bits[c][i] indicates the precision
  154290. * with which component c's DCT coefficient i (in zigzag order) is known.
  154291. * It is -1 when no data has yet been received, otherwise it is the point
  154292. * transform (shift) value for the most recent scan of the coefficient
  154293. * (thus, 0 at completion of the progression).
  154294. * This pointer is NULL when reading a non-progressive file.
  154295. */
  154296. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  154297. /* Internal JPEG parameters --- the application usually need not look at
  154298. * these fields. Note that the decompressor output side may not use
  154299. * any parameters that can change between scans.
  154300. */
  154301. /* Quantization and Huffman tables are carried forward across input
  154302. * datastreams when processing abbreviated JPEG datastreams.
  154303. */
  154304. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  154305. /* ptrs to coefficient quantization tables, or NULL if not defined */
  154306. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  154307. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  154308. /* ptrs to Huffman coding tables, or NULL if not defined */
  154309. /* These parameters are never carried across datastreams, since they
  154310. * are given in SOF/SOS markers or defined to be reset by SOI.
  154311. */
  154312. int data_precision; /* bits of precision in image data */
  154313. jpeg_component_info * comp_info;
  154314. /* comp_info[i] describes component that appears i'th in SOF */
  154315. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  154316. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  154317. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  154318. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  154319. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  154320. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  154321. /* These fields record data obtained from optional markers recognized by
  154322. * the JPEG library.
  154323. */
  154324. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  154325. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  154326. UINT8 JFIF_major_version; /* JFIF version number */
  154327. UINT8 JFIF_minor_version;
  154328. UINT8 density_unit; /* JFIF code for pixel size units */
  154329. UINT16 X_density; /* Horizontal pixel density */
  154330. UINT16 Y_density; /* Vertical pixel density */
  154331. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  154332. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  154333. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  154334. /* Aside from the specific data retained from APPn markers known to the
  154335. * library, the uninterpreted contents of any or all APPn and COM markers
  154336. * can be saved in a list for examination by the application.
  154337. */
  154338. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  154339. /* Remaining fields are known throughout decompressor, but generally
  154340. * should not be touched by a surrounding application.
  154341. */
  154342. /*
  154343. * These fields are computed during decompression startup
  154344. */
  154345. int max_h_samp_factor; /* largest h_samp_factor */
  154346. int max_v_samp_factor; /* largest v_samp_factor */
  154347. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  154348. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  154349. /* The coefficient controller's input and output progress is measured in
  154350. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  154351. * in fully interleaved JPEG scans, but are used whether the scan is
  154352. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  154353. * rows of each component. Therefore, the IDCT output contains
  154354. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  154355. */
  154356. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  154357. /*
  154358. * These fields are valid during any one scan.
  154359. * They describe the components and MCUs actually appearing in the scan.
  154360. * Note that the decompressor output side must not use these fields.
  154361. */
  154362. int comps_in_scan; /* # of JPEG components in this scan */
  154363. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  154364. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  154365. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  154366. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  154367. int blocks_in_MCU; /* # of DCT blocks per MCU */
  154368. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  154369. /* MCU_membership[i] is index in cur_comp_info of component owning */
  154370. /* i'th block in an MCU */
  154371. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  154372. /* This field is shared between entropy decoder and marker parser.
  154373. * It is either zero or the code of a JPEG marker that has been
  154374. * read from the data source, but has not yet been processed.
  154375. */
  154376. int unread_marker;
  154377. /*
  154378. * Links to decompression subobjects (methods, private variables of modules)
  154379. */
  154380. struct jpeg_decomp_master * master;
  154381. struct jpeg_d_main_controller * main;
  154382. struct jpeg_d_coef_controller * coef;
  154383. struct jpeg_d_post_controller * post;
  154384. struct jpeg_input_controller * inputctl;
  154385. struct jpeg_marker_reader * marker;
  154386. struct jpeg_entropy_decoder * entropy;
  154387. struct jpeg_inverse_dct * idct;
  154388. struct jpeg_upsampler * upsample;
  154389. struct jpeg_color_deconverter * cconvert;
  154390. struct jpeg_color_quantizer * cquantize;
  154391. };
  154392. /* "Object" declarations for JPEG modules that may be supplied or called
  154393. * directly by the surrounding application.
  154394. * As with all objects in the JPEG library, these structs only define the
  154395. * publicly visible methods and state variables of a module. Additional
  154396. * private fields may exist after the public ones.
  154397. */
  154398. /* Error handler object */
  154399. struct jpeg_error_mgr {
  154400. /* Error exit handler: does not return to caller */
  154401. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  154402. /* Conditionally emit a trace or warning message */
  154403. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  154404. /* Routine that actually outputs a trace or error message */
  154405. JMETHOD(void, output_message, (j_common_ptr cinfo));
  154406. /* Format a message string for the most recent JPEG error or message */
  154407. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  154408. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  154409. /* Reset error state variables at start of a new image */
  154410. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  154411. /* The message ID code and any parameters are saved here.
  154412. * A message can have one string parameter or up to 8 int parameters.
  154413. */
  154414. int msg_code;
  154415. #define JMSG_STR_PARM_MAX 80
  154416. union {
  154417. int i[8];
  154418. char s[JMSG_STR_PARM_MAX];
  154419. } msg_parm;
  154420. /* Standard state variables for error facility */
  154421. int trace_level; /* max msg_level that will be displayed */
  154422. /* For recoverable corrupt-data errors, we emit a warning message,
  154423. * but keep going unless emit_message chooses to abort. emit_message
  154424. * should count warnings in num_warnings. The surrounding application
  154425. * can check for bad data by seeing if num_warnings is nonzero at the
  154426. * end of processing.
  154427. */
  154428. long num_warnings; /* number of corrupt-data warnings */
  154429. /* These fields point to the table(s) of error message strings.
  154430. * An application can change the table pointer to switch to a different
  154431. * message list (typically, to change the language in which errors are
  154432. * reported). Some applications may wish to add additional error codes
  154433. * that will be handled by the JPEG library error mechanism; the second
  154434. * table pointer is used for this purpose.
  154435. *
  154436. * First table includes all errors generated by JPEG library itself.
  154437. * Error code 0 is reserved for a "no such error string" message.
  154438. */
  154439. const char * const * jpeg_message_table; /* Library errors */
  154440. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  154441. /* Second table can be added by application (see cjpeg/djpeg for example).
  154442. * It contains strings numbered first_addon_message..last_addon_message.
  154443. */
  154444. const char * const * addon_message_table; /* Non-library errors */
  154445. int first_addon_message; /* code for first string in addon table */
  154446. int last_addon_message; /* code for last string in addon table */
  154447. };
  154448. /* Progress monitor object */
  154449. struct jpeg_progress_mgr {
  154450. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  154451. long pass_counter; /* work units completed in this pass */
  154452. long pass_limit; /* total number of work units in this pass */
  154453. int completed_passes; /* passes completed so far */
  154454. int total_passes; /* total number of passes expected */
  154455. };
  154456. /* Data destination object for compression */
  154457. struct jpeg_destination_mgr {
  154458. JOCTET * next_output_byte; /* => next byte to write in buffer */
  154459. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  154460. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  154461. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  154462. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  154463. };
  154464. /* Data source object for decompression */
  154465. struct jpeg_source_mgr {
  154466. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  154467. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  154468. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  154469. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  154470. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  154471. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  154472. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  154473. };
  154474. /* Memory manager object.
  154475. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  154476. * and "really big" objects (virtual arrays with backing store if needed).
  154477. * The memory manager does not allow individual objects to be freed; rather,
  154478. * each created object is assigned to a pool, and whole pools can be freed
  154479. * at once. This is faster and more convenient than remembering exactly what
  154480. * to free, especially where malloc()/free() are not too speedy.
  154481. * NB: alloc routines never return NULL. They exit to error_exit if not
  154482. * successful.
  154483. */
  154484. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  154485. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  154486. #define JPOOL_NUMPOOLS 2
  154487. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  154488. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  154489. struct jpeg_memory_mgr {
  154490. /* Method pointers */
  154491. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  154492. size_t sizeofobject));
  154493. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  154494. size_t sizeofobject));
  154495. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  154496. JDIMENSION samplesperrow,
  154497. JDIMENSION numrows));
  154498. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  154499. JDIMENSION blocksperrow,
  154500. JDIMENSION numrows));
  154501. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  154502. int pool_id,
  154503. boolean pre_zero,
  154504. JDIMENSION samplesperrow,
  154505. JDIMENSION numrows,
  154506. JDIMENSION maxaccess));
  154507. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  154508. int pool_id,
  154509. boolean pre_zero,
  154510. JDIMENSION blocksperrow,
  154511. JDIMENSION numrows,
  154512. JDIMENSION maxaccess));
  154513. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  154514. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  154515. jvirt_sarray_ptr ptr,
  154516. JDIMENSION start_row,
  154517. JDIMENSION num_rows,
  154518. boolean writable));
  154519. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  154520. jvirt_barray_ptr ptr,
  154521. JDIMENSION start_row,
  154522. JDIMENSION num_rows,
  154523. boolean writable));
  154524. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  154525. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  154526. /* Limit on memory allocation for this JPEG object. (Note that this is
  154527. * merely advisory, not a guaranteed maximum; it only affects the space
  154528. * used for virtual-array buffers.) May be changed by outer application
  154529. * after creating the JPEG object.
  154530. */
  154531. long max_memory_to_use;
  154532. /* Maximum allocation request accepted by alloc_large. */
  154533. long max_alloc_chunk;
  154534. };
  154535. /* Routine signature for application-supplied marker processing methods.
  154536. * Need not pass marker code since it is stored in cinfo->unread_marker.
  154537. */
  154538. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  154539. /* Declarations for routines called by application.
  154540. * The JPP macro hides prototype parameters from compilers that can't cope.
  154541. * Note JPP requires double parentheses.
  154542. */
  154543. #ifdef HAVE_PROTOTYPES
  154544. #define JPP(arglist) arglist
  154545. #else
  154546. #define JPP(arglist) ()
  154547. #endif
  154548. /* Short forms of external names for systems with brain-damaged linkers.
  154549. * We shorten external names to be unique in the first six letters, which
  154550. * is good enough for all known systems.
  154551. * (If your compiler itself needs names to be unique in less than 15
  154552. * characters, you are out of luck. Get a better compiler.)
  154553. */
  154554. #ifdef NEED_SHORT_EXTERNAL_NAMES
  154555. #define jpeg_std_error jStdError
  154556. #define jpeg_CreateCompress jCreaCompress
  154557. #define jpeg_CreateDecompress jCreaDecompress
  154558. #define jpeg_destroy_compress jDestCompress
  154559. #define jpeg_destroy_decompress jDestDecompress
  154560. #define jpeg_stdio_dest jStdDest
  154561. #define jpeg_stdio_src jStdSrc
  154562. #define jpeg_set_defaults jSetDefaults
  154563. #define jpeg_set_colorspace jSetColorspace
  154564. #define jpeg_default_colorspace jDefColorspace
  154565. #define jpeg_set_quality jSetQuality
  154566. #define jpeg_set_linear_quality jSetLQuality
  154567. #define jpeg_add_quant_table jAddQuantTable
  154568. #define jpeg_quality_scaling jQualityScaling
  154569. #define jpeg_simple_progression jSimProgress
  154570. #define jpeg_suppress_tables jSuppressTables
  154571. #define jpeg_alloc_quant_table jAlcQTable
  154572. #define jpeg_alloc_huff_table jAlcHTable
  154573. #define jpeg_start_compress jStrtCompress
  154574. #define jpeg_write_scanlines jWrtScanlines
  154575. #define jpeg_finish_compress jFinCompress
  154576. #define jpeg_write_raw_data jWrtRawData
  154577. #define jpeg_write_marker jWrtMarker
  154578. #define jpeg_write_m_header jWrtMHeader
  154579. #define jpeg_write_m_byte jWrtMByte
  154580. #define jpeg_write_tables jWrtTables
  154581. #define jpeg_read_header jReadHeader
  154582. #define jpeg_start_decompress jStrtDecompress
  154583. #define jpeg_read_scanlines jReadScanlines
  154584. #define jpeg_finish_decompress jFinDecompress
  154585. #define jpeg_read_raw_data jReadRawData
  154586. #define jpeg_has_multiple_scans jHasMultScn
  154587. #define jpeg_start_output jStrtOutput
  154588. #define jpeg_finish_output jFinOutput
  154589. #define jpeg_input_complete jInComplete
  154590. #define jpeg_new_colormap jNewCMap
  154591. #define jpeg_consume_input jConsumeInput
  154592. #define jpeg_calc_output_dimensions jCalcDimensions
  154593. #define jpeg_save_markers jSaveMarkers
  154594. #define jpeg_set_marker_processor jSetMarker
  154595. #define jpeg_read_coefficients jReadCoefs
  154596. #define jpeg_write_coefficients jWrtCoefs
  154597. #define jpeg_copy_critical_parameters jCopyCrit
  154598. #define jpeg_abort_compress jAbrtCompress
  154599. #define jpeg_abort_decompress jAbrtDecompress
  154600. #define jpeg_abort jAbort
  154601. #define jpeg_destroy jDestroy
  154602. #define jpeg_resync_to_restart jResyncRestart
  154603. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  154604. /* Default error-management setup */
  154605. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  154606. JPP((struct jpeg_error_mgr * err));
  154607. /* Initialization of JPEG compression objects.
  154608. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  154609. * names that applications should call. These expand to calls on
  154610. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  154611. * passed for version mismatch checking.
  154612. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  154613. */
  154614. #define jpeg_create_compress(cinfo) \
  154615. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  154616. (size_t) sizeof(struct jpeg_compress_struct))
  154617. #define jpeg_create_decompress(cinfo) \
  154618. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  154619. (size_t) sizeof(struct jpeg_decompress_struct))
  154620. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  154621. int version, size_t structsize));
  154622. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  154623. int version, size_t structsize));
  154624. /* Destruction of JPEG compression objects */
  154625. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  154626. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  154627. /* Standard data source and destination managers: stdio streams. */
  154628. /* Caller is responsible for opening the file before and closing after. */
  154629. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  154630. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  154631. /* Default parameter setup for compression */
  154632. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  154633. /* Compression parameter setup aids */
  154634. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  154635. J_COLOR_SPACE colorspace));
  154636. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  154637. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  154638. boolean force_baseline));
  154639. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  154640. int scale_factor,
  154641. boolean force_baseline));
  154642. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  154643. const unsigned int *basic_table,
  154644. int scale_factor,
  154645. boolean force_baseline));
  154646. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  154647. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  154648. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  154649. boolean suppress));
  154650. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  154651. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  154652. /* Main entry points for compression */
  154653. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  154654. boolean write_all_tables));
  154655. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  154656. JSAMPARRAY scanlines,
  154657. JDIMENSION num_lines));
  154658. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  154659. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  154660. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  154661. JSAMPIMAGE data,
  154662. JDIMENSION num_lines));
  154663. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  154664. EXTERN(void) jpeg_write_marker
  154665. JPP((j_compress_ptr cinfo, int marker,
  154666. const JOCTET * dataptr, unsigned int datalen));
  154667. /* Same, but piecemeal. */
  154668. EXTERN(void) jpeg_write_m_header
  154669. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  154670. EXTERN(void) jpeg_write_m_byte
  154671. JPP((j_compress_ptr cinfo, int val));
  154672. /* Alternate compression function: just write an abbreviated table file */
  154673. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  154674. /* Decompression startup: read start of JPEG datastream to see what's there */
  154675. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  154676. boolean require_image));
  154677. /* Return value is one of: */
  154678. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  154679. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  154680. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  154681. /* If you pass require_image = TRUE (normal case), you need not check for
  154682. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  154683. * JPEG_SUSPENDED is only possible if you use a data source module that can
  154684. * give a suspension return (the stdio source module doesn't).
  154685. */
  154686. /* Main entry points for decompression */
  154687. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  154688. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  154689. JSAMPARRAY scanlines,
  154690. JDIMENSION max_lines));
  154691. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  154692. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  154693. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  154694. JSAMPIMAGE data,
  154695. JDIMENSION max_lines));
  154696. /* Additional entry points for buffered-image mode. */
  154697. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  154698. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  154699. int scan_number));
  154700. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  154701. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  154702. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  154703. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  154704. /* Return value is one of: */
  154705. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  154706. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  154707. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  154708. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  154709. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  154710. /* Precalculate output dimensions for current decompression parameters. */
  154711. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  154712. /* Control saving of COM and APPn markers into marker_list. */
  154713. EXTERN(void) jpeg_save_markers
  154714. JPP((j_decompress_ptr cinfo, int marker_code,
  154715. unsigned int length_limit));
  154716. /* Install a special processing method for COM or APPn markers. */
  154717. EXTERN(void) jpeg_set_marker_processor
  154718. JPP((j_decompress_ptr cinfo, int marker_code,
  154719. jpeg_marker_parser_method routine));
  154720. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  154721. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  154722. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  154723. jvirt_barray_ptr * coef_arrays));
  154724. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  154725. j_compress_ptr dstinfo));
  154726. /* If you choose to abort compression or decompression before completing
  154727. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  154728. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  154729. * if you're done with the JPEG object, but if you want to clean it up and
  154730. * reuse it, call this:
  154731. */
  154732. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  154733. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  154734. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  154735. * flavor of JPEG object. These may be more convenient in some places.
  154736. */
  154737. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  154738. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  154739. /* Default restart-marker-resync procedure for use by data source modules */
  154740. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  154741. int desired));
  154742. /* These marker codes are exported since applications and data source modules
  154743. * are likely to want to use them.
  154744. */
  154745. #define JPEG_RST0 0xD0 /* RST0 marker code */
  154746. #define JPEG_EOI 0xD9 /* EOI marker code */
  154747. #define JPEG_APP0 0xE0 /* APP0 marker code */
  154748. #define JPEG_COM 0xFE /* COM marker code */
  154749. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  154750. * for structure definitions that are never filled in, keep it quiet by
  154751. * supplying dummy definitions for the various substructures.
  154752. */
  154753. #ifdef INCOMPLETE_TYPES_BROKEN
  154754. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  154755. struct jvirt_sarray_control { long dummy; };
  154756. struct jvirt_barray_control { long dummy; };
  154757. struct jpeg_comp_master { long dummy; };
  154758. struct jpeg_c_main_controller { long dummy; };
  154759. struct jpeg_c_prep_controller { long dummy; };
  154760. struct jpeg_c_coef_controller { long dummy; };
  154761. struct jpeg_marker_writer { long dummy; };
  154762. struct jpeg_color_converter { long dummy; };
  154763. struct jpeg_downsampler { long dummy; };
  154764. struct jpeg_forward_dct { long dummy; };
  154765. struct jpeg_entropy_encoder { long dummy; };
  154766. struct jpeg_decomp_master { long dummy; };
  154767. struct jpeg_d_main_controller { long dummy; };
  154768. struct jpeg_d_coef_controller { long dummy; };
  154769. struct jpeg_d_post_controller { long dummy; };
  154770. struct jpeg_input_controller { long dummy; };
  154771. struct jpeg_marker_reader { long dummy; };
  154772. struct jpeg_entropy_decoder { long dummy; };
  154773. struct jpeg_inverse_dct { long dummy; };
  154774. struct jpeg_upsampler { long dummy; };
  154775. struct jpeg_color_deconverter { long dummy; };
  154776. struct jpeg_color_quantizer { long dummy; };
  154777. #endif /* JPEG_INTERNALS */
  154778. #endif /* INCOMPLETE_TYPES_BROKEN */
  154779. /*
  154780. * The JPEG library modules define JPEG_INTERNALS before including this file.
  154781. * The internal structure declarations are read only when that is true.
  154782. * Applications using the library should not include jpegint.h, but may wish
  154783. * to include jerror.h.
  154784. */
  154785. #ifdef JPEG_INTERNALS
  154786. /********* Start of inlined file: jpegint.h *********/
  154787. /* Declarations for both compression & decompression */
  154788. typedef enum { /* Operating modes for buffer controllers */
  154789. JBUF_PASS_THRU, /* Plain stripwise operation */
  154790. /* Remaining modes require a full-image buffer to have been created */
  154791. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  154792. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  154793. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  154794. } J_BUF_MODE;
  154795. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  154796. #define CSTATE_START 100 /* after create_compress */
  154797. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  154798. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  154799. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  154800. #define DSTATE_START 200 /* after create_decompress */
  154801. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  154802. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  154803. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  154804. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  154805. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  154806. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  154807. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  154808. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  154809. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  154810. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  154811. /* Declarations for compression modules */
  154812. /* Master control module */
  154813. struct jpeg_comp_master {
  154814. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  154815. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  154816. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  154817. /* State variables made visible to other modules */
  154818. boolean call_pass_startup; /* True if pass_startup must be called */
  154819. boolean is_last_pass; /* True during last pass */
  154820. };
  154821. /* Main buffer control (downsampled-data buffer) */
  154822. struct jpeg_c_main_controller {
  154823. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  154824. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  154825. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  154826. JDIMENSION in_rows_avail));
  154827. };
  154828. /* Compression preprocessing (downsampling input buffer control) */
  154829. struct jpeg_c_prep_controller {
  154830. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  154831. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  154832. JSAMPARRAY input_buf,
  154833. JDIMENSION *in_row_ctr,
  154834. JDIMENSION in_rows_avail,
  154835. JSAMPIMAGE output_buf,
  154836. JDIMENSION *out_row_group_ctr,
  154837. JDIMENSION out_row_groups_avail));
  154838. };
  154839. /* Coefficient buffer control */
  154840. struct jpeg_c_coef_controller {
  154841. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  154842. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  154843. JSAMPIMAGE input_buf));
  154844. };
  154845. /* Colorspace conversion */
  154846. struct jpeg_color_converter {
  154847. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  154848. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  154849. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  154850. JDIMENSION output_row, int num_rows));
  154851. };
  154852. /* Downsampling */
  154853. struct jpeg_downsampler {
  154854. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  154855. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  154856. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  154857. JSAMPIMAGE output_buf,
  154858. JDIMENSION out_row_group_index));
  154859. boolean need_context_rows; /* TRUE if need rows above & below */
  154860. };
  154861. /* Forward DCT (also controls coefficient quantization) */
  154862. struct jpeg_forward_dct {
  154863. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  154864. /* perhaps this should be an array??? */
  154865. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  154866. jpeg_component_info * compptr,
  154867. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  154868. JDIMENSION start_row, JDIMENSION start_col,
  154869. JDIMENSION num_blocks));
  154870. };
  154871. /* Entropy encoding */
  154872. struct jpeg_entropy_encoder {
  154873. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  154874. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  154875. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  154876. };
  154877. /* Marker writing */
  154878. struct jpeg_marker_writer {
  154879. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  154880. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  154881. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  154882. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  154883. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  154884. /* These routines are exported to allow insertion of extra markers */
  154885. /* Probably only COM and APPn markers should be written this way */
  154886. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  154887. unsigned int datalen));
  154888. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  154889. };
  154890. /* Declarations for decompression modules */
  154891. /* Master control module */
  154892. struct jpeg_decomp_master {
  154893. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  154894. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  154895. /* State variables made visible to other modules */
  154896. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  154897. };
  154898. /* Input control module */
  154899. struct jpeg_input_controller {
  154900. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  154901. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  154902. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  154903. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  154904. /* State variables made visible to other modules */
  154905. boolean has_multiple_scans; /* True if file has multiple scans */
  154906. boolean eoi_reached; /* True when EOI has been consumed */
  154907. };
  154908. /* Main buffer control (downsampled-data buffer) */
  154909. struct jpeg_d_main_controller {
  154910. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  154911. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  154912. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  154913. JDIMENSION out_rows_avail));
  154914. };
  154915. /* Coefficient buffer control */
  154916. struct jpeg_d_coef_controller {
  154917. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  154918. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  154919. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  154920. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  154921. JSAMPIMAGE output_buf));
  154922. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  154923. jvirt_barray_ptr *coef_arrays;
  154924. };
  154925. /* Decompression postprocessing (color quantization buffer control) */
  154926. struct jpeg_d_post_controller {
  154927. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  154928. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  154929. JSAMPIMAGE input_buf,
  154930. JDIMENSION *in_row_group_ctr,
  154931. JDIMENSION in_row_groups_avail,
  154932. JSAMPARRAY output_buf,
  154933. JDIMENSION *out_row_ctr,
  154934. JDIMENSION out_rows_avail));
  154935. };
  154936. /* Marker reading & parsing */
  154937. struct jpeg_marker_reader {
  154938. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  154939. /* Read markers until SOS or EOI.
  154940. * Returns same codes as are defined for jpeg_consume_input:
  154941. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  154942. */
  154943. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  154944. /* Read a restart marker --- exported for use by entropy decoder only */
  154945. jpeg_marker_parser_method read_restart_marker;
  154946. /* State of marker reader --- nominally internal, but applications
  154947. * supplying COM or APPn handlers might like to know the state.
  154948. */
  154949. boolean saw_SOI; /* found SOI? */
  154950. boolean saw_SOF; /* found SOF? */
  154951. int next_restart_num; /* next restart number expected (0-7) */
  154952. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  154953. };
  154954. /* Entropy decoding */
  154955. struct jpeg_entropy_decoder {
  154956. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  154957. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  154958. JBLOCKROW *MCU_data));
  154959. /* This is here to share code between baseline and progressive decoders; */
  154960. /* other modules probably should not use it */
  154961. boolean insufficient_data; /* set TRUE after emitting warning */
  154962. };
  154963. /* Inverse DCT (also performs dequantization) */
  154964. typedef JMETHOD(void, inverse_DCT_method_ptr,
  154965. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  154966. JCOEFPTR coef_block,
  154967. JSAMPARRAY output_buf, JDIMENSION output_col));
  154968. struct jpeg_inverse_dct {
  154969. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  154970. /* It is useful to allow each component to have a separate IDCT method. */
  154971. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  154972. };
  154973. /* Upsampling (note that upsampler must also call color converter) */
  154974. struct jpeg_upsampler {
  154975. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  154976. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  154977. JSAMPIMAGE input_buf,
  154978. JDIMENSION *in_row_group_ctr,
  154979. JDIMENSION in_row_groups_avail,
  154980. JSAMPARRAY output_buf,
  154981. JDIMENSION *out_row_ctr,
  154982. JDIMENSION out_rows_avail));
  154983. boolean need_context_rows; /* TRUE if need rows above & below */
  154984. };
  154985. /* Colorspace conversion */
  154986. struct jpeg_color_deconverter {
  154987. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  154988. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  154989. JSAMPIMAGE input_buf, JDIMENSION input_row,
  154990. JSAMPARRAY output_buf, int num_rows));
  154991. };
  154992. /* Color quantization or color precision reduction */
  154993. struct jpeg_color_quantizer {
  154994. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  154995. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  154996. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  154997. int num_rows));
  154998. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  154999. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  155000. };
  155001. /* Miscellaneous useful macros */
  155002. #undef MAX
  155003. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  155004. #undef MIN
  155005. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  155006. /* We assume that right shift corresponds to signed division by 2 with
  155007. * rounding towards minus infinity. This is correct for typical "arithmetic
  155008. * shift" instructions that shift in copies of the sign bit. But some
  155009. * C compilers implement >> with an unsigned shift. For these machines you
  155010. * must define RIGHT_SHIFT_IS_UNSIGNED.
  155011. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  155012. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  155013. * included in the variables of any routine using RIGHT_SHIFT.
  155014. */
  155015. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  155016. #define SHIFT_TEMPS INT32 shift_temp;
  155017. #define RIGHT_SHIFT(x,shft) \
  155018. ((shift_temp = (x)) < 0 ? \
  155019. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  155020. (shift_temp >> (shft)))
  155021. #else
  155022. #define SHIFT_TEMPS
  155023. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  155024. #endif
  155025. /* Short forms of external names for systems with brain-damaged linkers. */
  155026. #ifdef NEED_SHORT_EXTERNAL_NAMES
  155027. #define jinit_compress_master jICompress
  155028. #define jinit_c_master_control jICMaster
  155029. #define jinit_c_main_controller jICMainC
  155030. #define jinit_c_prep_controller jICPrepC
  155031. #define jinit_c_coef_controller jICCoefC
  155032. #define jinit_color_converter jICColor
  155033. #define jinit_downsampler jIDownsampler
  155034. #define jinit_forward_dct jIFDCT
  155035. #define jinit_huff_encoder jIHEncoder
  155036. #define jinit_phuff_encoder jIPHEncoder
  155037. #define jinit_marker_writer jIMWriter
  155038. #define jinit_master_decompress jIDMaster
  155039. #define jinit_d_main_controller jIDMainC
  155040. #define jinit_d_coef_controller jIDCoefC
  155041. #define jinit_d_post_controller jIDPostC
  155042. #define jinit_input_controller jIInCtlr
  155043. #define jinit_marker_reader jIMReader
  155044. #define jinit_huff_decoder jIHDecoder
  155045. #define jinit_phuff_decoder jIPHDecoder
  155046. #define jinit_inverse_dct jIIDCT
  155047. #define jinit_upsampler jIUpsampler
  155048. #define jinit_color_deconverter jIDColor
  155049. #define jinit_1pass_quantizer jI1Quant
  155050. #define jinit_2pass_quantizer jI2Quant
  155051. #define jinit_merged_upsampler jIMUpsampler
  155052. #define jinit_memory_mgr jIMemMgr
  155053. #define jdiv_round_up jDivRound
  155054. #define jround_up jRound
  155055. #define jcopy_sample_rows jCopySamples
  155056. #define jcopy_block_row jCopyBlocks
  155057. #define jzero_far jZeroFar
  155058. #define jpeg_zigzag_order jZIGTable
  155059. #define jpeg_natural_order jZAGTable
  155060. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  155061. /* Compression module initialization routines */
  155062. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  155063. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  155064. boolean transcode_only));
  155065. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  155066. boolean need_full_buffer));
  155067. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  155068. boolean need_full_buffer));
  155069. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  155070. boolean need_full_buffer));
  155071. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  155072. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  155073. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  155074. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  155075. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  155076. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  155077. /* Decompression module initialization routines */
  155078. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  155079. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  155080. boolean need_full_buffer));
  155081. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  155082. boolean need_full_buffer));
  155083. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  155084. boolean need_full_buffer));
  155085. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  155086. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  155087. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  155088. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  155089. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  155090. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  155091. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  155092. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  155093. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  155094. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  155095. /* Memory manager initialization */
  155096. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  155097. /* Utility routines in jutils.c */
  155098. EXTERN(long) jdiv_round_up JPP((long a, long b));
  155099. EXTERN(long) jround_up JPP((long a, long b));
  155100. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  155101. JSAMPARRAY output_array, int dest_row,
  155102. int num_rows, JDIMENSION num_cols));
  155103. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  155104. JDIMENSION num_blocks));
  155105. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  155106. /* Constant tables in jutils.c */
  155107. #if 0 /* This table is not actually needed in v6a */
  155108. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  155109. #endif
  155110. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  155111. /* Suppress undefined-structure complaints if necessary. */
  155112. #ifdef INCOMPLETE_TYPES_BROKEN
  155113. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  155114. struct jvirt_sarray_control { long dummy; };
  155115. struct jvirt_barray_control { long dummy; };
  155116. #endif
  155117. #endif /* INCOMPLETE_TYPES_BROKEN */
  155118. /********* End of inlined file: jpegint.h *********/
  155119. /* fetch private declarations */
  155120. /********* Start of inlined file: jerror.h *********/
  155121. /*
  155122. * To define the enum list of message codes, include this file without
  155123. * defining macro JMESSAGE. To create a message string table, include it
  155124. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  155125. */
  155126. #ifndef JMESSAGE
  155127. #ifndef JERROR_H
  155128. /* First time through, define the enum list */
  155129. #define JMAKE_ENUM_LIST
  155130. #else
  155131. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  155132. #define JMESSAGE(code,string)
  155133. #endif /* JERROR_H */
  155134. #endif /* JMESSAGE */
  155135. #ifdef JMAKE_ENUM_LIST
  155136. typedef enum {
  155137. #define JMESSAGE(code,string) code ,
  155138. #endif /* JMAKE_ENUM_LIST */
  155139. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  155140. /* For maintenance convenience, list is alphabetical by message code name */
  155141. JMESSAGE(JERR_ARITH_NOTIMPL,
  155142. "Sorry, there are legal restrictions on arithmetic coding")
  155143. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  155144. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  155145. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  155146. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  155147. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  155148. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  155149. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  155150. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  155151. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  155152. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  155153. JMESSAGE(JERR_BAD_LIB_VERSION,
  155154. "Wrong JPEG library version: library is %d, caller expects %d")
  155155. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  155156. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  155157. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  155158. JMESSAGE(JERR_BAD_PROGRESSION,
  155159. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  155160. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  155161. "Invalid progressive parameters at scan script entry %d")
  155162. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  155163. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  155164. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  155165. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  155166. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  155167. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  155168. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  155169. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  155170. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  155171. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  155172. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  155173. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  155174. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  155175. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  155176. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  155177. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  155178. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  155179. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  155180. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  155181. JMESSAGE(JERR_FILE_READ, "Input file read error")
  155182. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  155183. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  155184. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  155185. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  155186. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  155187. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  155188. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  155189. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  155190. "Cannot transcode due to multiple use of quantization table %d")
  155191. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  155192. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  155193. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  155194. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  155195. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  155196. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  155197. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  155198. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  155199. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  155200. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  155201. JMESSAGE(JERR_QUANT_COMPONENTS,
  155202. "Cannot quantize more than %d color components")
  155203. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  155204. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  155205. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  155206. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  155207. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  155208. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  155209. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  155210. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  155211. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  155212. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  155213. JMESSAGE(JERR_TFILE_WRITE,
  155214. "Write failed on temporary file --- out of disk space?")
  155215. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  155216. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  155217. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  155218. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  155219. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  155220. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  155221. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  155222. JMESSAGE(JMSG_VERSION, JVERSION)
  155223. JMESSAGE(JTRC_16BIT_TABLES,
  155224. "Caution: quantization tables are too coarse for baseline JPEG")
  155225. JMESSAGE(JTRC_ADOBE,
  155226. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  155227. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  155228. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  155229. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  155230. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  155231. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  155232. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  155233. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  155234. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  155235. JMESSAGE(JTRC_EOI, "End Of Image")
  155236. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  155237. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  155238. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  155239. "Warning: thumbnail image size does not match data length %u")
  155240. JMESSAGE(JTRC_JFIF_EXTENSION,
  155241. "JFIF extension marker: type 0x%02x, length %u")
  155242. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  155243. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  155244. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  155245. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  155246. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  155247. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  155248. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  155249. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  155250. JMESSAGE(JTRC_RST, "RST%d")
  155251. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  155252. "Smoothing not supported with nonstandard sampling ratios")
  155253. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  155254. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  155255. JMESSAGE(JTRC_SOI, "Start of Image")
  155256. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  155257. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  155258. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  155259. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  155260. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  155261. JMESSAGE(JTRC_THUMB_JPEG,
  155262. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  155263. JMESSAGE(JTRC_THUMB_PALETTE,
  155264. "JFIF extension marker: palette thumbnail image, length %u")
  155265. JMESSAGE(JTRC_THUMB_RGB,
  155266. "JFIF extension marker: RGB thumbnail image, length %u")
  155267. JMESSAGE(JTRC_UNKNOWN_IDS,
  155268. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  155269. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  155270. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  155271. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  155272. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  155273. "Inconsistent progression sequence for component %d coefficient %d")
  155274. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  155275. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  155276. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  155277. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  155278. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  155279. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  155280. JMESSAGE(JWRN_MUST_RESYNC,
  155281. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  155282. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  155283. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  155284. #ifdef JMAKE_ENUM_LIST
  155285. JMSG_LASTMSGCODE
  155286. } J_MESSAGE_CODE;
  155287. #undef JMAKE_ENUM_LIST
  155288. #endif /* JMAKE_ENUM_LIST */
  155289. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  155290. #undef JMESSAGE
  155291. #ifndef JERROR_H
  155292. #define JERROR_H
  155293. /* Macros to simplify using the error and trace message stuff */
  155294. /* The first parameter is either type of cinfo pointer */
  155295. /* Fatal errors (print message and exit) */
  155296. #define ERREXIT(cinfo,code) \
  155297. ((cinfo)->err->msg_code = (code), \
  155298. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155299. #define ERREXIT1(cinfo,code,p1) \
  155300. ((cinfo)->err->msg_code = (code), \
  155301. (cinfo)->err->msg_parm.i[0] = (p1), \
  155302. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155303. #define ERREXIT2(cinfo,code,p1,p2) \
  155304. ((cinfo)->err->msg_code = (code), \
  155305. (cinfo)->err->msg_parm.i[0] = (p1), \
  155306. (cinfo)->err->msg_parm.i[1] = (p2), \
  155307. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155308. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  155309. ((cinfo)->err->msg_code = (code), \
  155310. (cinfo)->err->msg_parm.i[0] = (p1), \
  155311. (cinfo)->err->msg_parm.i[1] = (p2), \
  155312. (cinfo)->err->msg_parm.i[2] = (p3), \
  155313. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155314. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  155315. ((cinfo)->err->msg_code = (code), \
  155316. (cinfo)->err->msg_parm.i[0] = (p1), \
  155317. (cinfo)->err->msg_parm.i[1] = (p2), \
  155318. (cinfo)->err->msg_parm.i[2] = (p3), \
  155319. (cinfo)->err->msg_parm.i[3] = (p4), \
  155320. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155321. #define ERREXITS(cinfo,code,str) \
  155322. ((cinfo)->err->msg_code = (code), \
  155323. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  155324. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155325. #define MAKESTMT(stuff) do { stuff } while (0)
  155326. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  155327. #define WARNMS(cinfo,code) \
  155328. ((cinfo)->err->msg_code = (code), \
  155329. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  155330. #define WARNMS1(cinfo,code,p1) \
  155331. ((cinfo)->err->msg_code = (code), \
  155332. (cinfo)->err->msg_parm.i[0] = (p1), \
  155333. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  155334. #define WARNMS2(cinfo,code,p1,p2) \
  155335. ((cinfo)->err->msg_code = (code), \
  155336. (cinfo)->err->msg_parm.i[0] = (p1), \
  155337. (cinfo)->err->msg_parm.i[1] = (p2), \
  155338. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  155339. /* Informational/debugging messages */
  155340. #define TRACEMS(cinfo,lvl,code) \
  155341. ((cinfo)->err->msg_code = (code), \
  155342. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  155343. #define TRACEMS1(cinfo,lvl,code,p1) \
  155344. ((cinfo)->err->msg_code = (code), \
  155345. (cinfo)->err->msg_parm.i[0] = (p1), \
  155346. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  155347. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  155348. ((cinfo)->err->msg_code = (code), \
  155349. (cinfo)->err->msg_parm.i[0] = (p1), \
  155350. (cinfo)->err->msg_parm.i[1] = (p2), \
  155351. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  155352. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  155353. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  155354. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  155355. (cinfo)->err->msg_code = (code); \
  155356. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  155357. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  155358. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  155359. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  155360. (cinfo)->err->msg_code = (code); \
  155361. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  155362. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  155363. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  155364. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  155365. _mp[4] = (p5); \
  155366. (cinfo)->err->msg_code = (code); \
  155367. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  155368. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  155369. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  155370. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  155371. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  155372. (cinfo)->err->msg_code = (code); \
  155373. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  155374. #define TRACEMSS(cinfo,lvl,code,str) \
  155375. ((cinfo)->err->msg_code = (code), \
  155376. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  155377. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  155378. #endif /* JERROR_H */
  155379. /********* End of inlined file: jerror.h *********/
  155380. /* fetch error codes too */
  155381. #endif
  155382. #endif /* JPEGLIB_H */
  155383. /********* End of inlined file: jpeglib.h *********/
  155384. /********* Start of inlined file: jcapimin.c *********/
  155385. #define JPEG_INTERNALS
  155386. /********* Start of inlined file: jinclude.h *********/
  155387. /* Include auto-config file to find out which system include files we need. */
  155388. #ifndef __jinclude_h__
  155389. #define __jinclude_h__
  155390. /********* Start of inlined file: jconfig.h *********/
  155391. /* see jconfig.doc for explanations */
  155392. // disable all the warnings under MSVC
  155393. #ifdef _MSC_VER
  155394. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  155395. #endif
  155396. #ifdef __BORLANDC__
  155397. #pragma warn -8057
  155398. #pragma warn -8019
  155399. #pragma warn -8004
  155400. #pragma warn -8008
  155401. #endif
  155402. #define HAVE_PROTOTYPES
  155403. #define HAVE_UNSIGNED_CHAR
  155404. #define HAVE_UNSIGNED_SHORT
  155405. /* #define void char */
  155406. /* #define const */
  155407. #undef CHAR_IS_UNSIGNED
  155408. #define HAVE_STDDEF_H
  155409. #define HAVE_STDLIB_H
  155410. #undef NEED_BSD_STRINGS
  155411. #undef NEED_SYS_TYPES_H
  155412. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  155413. #undef NEED_SHORT_EXTERNAL_NAMES
  155414. #undef INCOMPLETE_TYPES_BROKEN
  155415. /* Define "boolean" as unsigned char, not int, per Windows custom */
  155416. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  155417. typedef unsigned char boolean;
  155418. #endif
  155419. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  155420. #ifdef JPEG_INTERNALS
  155421. #undef RIGHT_SHIFT_IS_UNSIGNED
  155422. #endif /* JPEG_INTERNALS */
  155423. #ifdef JPEG_CJPEG_DJPEG
  155424. #define BMP_SUPPORTED /* BMP image file format */
  155425. #define GIF_SUPPORTED /* GIF image file format */
  155426. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  155427. #undef RLE_SUPPORTED /* Utah RLE image file format */
  155428. #define TARGA_SUPPORTED /* Targa image file format */
  155429. #define TWO_FILE_COMMANDLINE /* optional */
  155430. #define USE_SETMODE /* Microsoft has setmode() */
  155431. #undef NEED_SIGNAL_CATCHER
  155432. #undef DONT_USE_B_MODE
  155433. #undef PROGRESS_REPORT /* optional */
  155434. #endif /* JPEG_CJPEG_DJPEG */
  155435. /********* End of inlined file: jconfig.h *********/
  155436. /* auto configuration options */
  155437. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  155438. /*
  155439. * We need the NULL macro and size_t typedef.
  155440. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  155441. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  155442. * pull in <sys/types.h> as well.
  155443. * Note that the core JPEG library does not require <stdio.h>;
  155444. * only the default error handler and data source/destination modules do.
  155445. * But we must pull it in because of the references to FILE in jpeglib.h.
  155446. * You can remove those references if you want to compile without <stdio.h>.
  155447. */
  155448. #ifdef HAVE_STDDEF_H
  155449. #include <stddef.h>
  155450. #endif
  155451. #ifdef HAVE_STDLIB_H
  155452. #include <stdlib.h>
  155453. #endif
  155454. #ifdef NEED_SYS_TYPES_H
  155455. #include <sys/types.h>
  155456. #endif
  155457. #include <stdio.h>
  155458. /*
  155459. * We need memory copying and zeroing functions, plus strncpy().
  155460. * ANSI and System V implementations declare these in <string.h>.
  155461. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  155462. * Some systems may declare memset and memcpy in <memory.h>.
  155463. *
  155464. * NOTE: we assume the size parameters to these functions are of type size_t.
  155465. * Change the casts in these macros if not!
  155466. */
  155467. #ifdef NEED_BSD_STRINGS
  155468. #include <strings.h>
  155469. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  155470. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  155471. #else /* not BSD, assume ANSI/SysV string lib */
  155472. #include <string.h>
  155473. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  155474. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  155475. #endif
  155476. /*
  155477. * In ANSI C, and indeed any rational implementation, size_t is also the
  155478. * type returned by sizeof(). However, it seems there are some irrational
  155479. * implementations out there, in which sizeof() returns an int even though
  155480. * size_t is defined as long or unsigned long. To ensure consistent results
  155481. * we always use this SIZEOF() macro in place of using sizeof() directly.
  155482. */
  155483. #define SIZEOF(object) ((size_t) sizeof(object))
  155484. /*
  155485. * The modules that use fread() and fwrite() always invoke them through
  155486. * these macros. On some systems you may need to twiddle the argument casts.
  155487. * CAUTION: argument order is different from underlying functions!
  155488. */
  155489. #define JFREAD(file,buf,sizeofbuf) \
  155490. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  155491. #define JFWRITE(file,buf,sizeofbuf) \
  155492. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  155493. typedef enum { /* JPEG marker codes */
  155494. M_SOF0 = 0xc0,
  155495. M_SOF1 = 0xc1,
  155496. M_SOF2 = 0xc2,
  155497. M_SOF3 = 0xc3,
  155498. M_SOF5 = 0xc5,
  155499. M_SOF6 = 0xc6,
  155500. M_SOF7 = 0xc7,
  155501. M_JPG = 0xc8,
  155502. M_SOF9 = 0xc9,
  155503. M_SOF10 = 0xca,
  155504. M_SOF11 = 0xcb,
  155505. M_SOF13 = 0xcd,
  155506. M_SOF14 = 0xce,
  155507. M_SOF15 = 0xcf,
  155508. M_DHT = 0xc4,
  155509. M_DAC = 0xcc,
  155510. M_RST0 = 0xd0,
  155511. M_RST1 = 0xd1,
  155512. M_RST2 = 0xd2,
  155513. M_RST3 = 0xd3,
  155514. M_RST4 = 0xd4,
  155515. M_RST5 = 0xd5,
  155516. M_RST6 = 0xd6,
  155517. M_RST7 = 0xd7,
  155518. M_SOI = 0xd8,
  155519. M_EOI = 0xd9,
  155520. M_SOS = 0xda,
  155521. M_DQT = 0xdb,
  155522. M_DNL = 0xdc,
  155523. M_DRI = 0xdd,
  155524. M_DHP = 0xde,
  155525. M_EXP = 0xdf,
  155526. M_APP0 = 0xe0,
  155527. M_APP1 = 0xe1,
  155528. M_APP2 = 0xe2,
  155529. M_APP3 = 0xe3,
  155530. M_APP4 = 0xe4,
  155531. M_APP5 = 0xe5,
  155532. M_APP6 = 0xe6,
  155533. M_APP7 = 0xe7,
  155534. M_APP8 = 0xe8,
  155535. M_APP9 = 0xe9,
  155536. M_APP10 = 0xea,
  155537. M_APP11 = 0xeb,
  155538. M_APP12 = 0xec,
  155539. M_APP13 = 0xed,
  155540. M_APP14 = 0xee,
  155541. M_APP15 = 0xef,
  155542. M_JPG0 = 0xf0,
  155543. M_JPG13 = 0xfd,
  155544. M_COM = 0xfe,
  155545. M_TEM = 0x01,
  155546. M_ERROR = 0x100
  155547. } JPEG_MARKER;
  155548. /*
  155549. * Figure F.12: extend sign bit.
  155550. * On some machines, a shift and add will be faster than a table lookup.
  155551. */
  155552. #ifdef AVOID_TABLES
  155553. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  155554. #else
  155555. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  155556. static const int extend_test[16] = /* entry n is 2**(n-1) */
  155557. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  155558. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  155559. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  155560. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  155561. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  155562. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  155563. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  155564. #endif /* AVOID_TABLES */
  155565. #endif
  155566. /********* End of inlined file: jinclude.h *********/
  155567. /*
  155568. * Initialization of a JPEG compression object.
  155569. * The error manager must already be set up (in case memory manager fails).
  155570. */
  155571. GLOBAL(void)
  155572. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  155573. {
  155574. int i;
  155575. /* Guard against version mismatches between library and caller. */
  155576. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  155577. if (version != JPEG_LIB_VERSION)
  155578. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  155579. if (structsize != SIZEOF(struct jpeg_compress_struct))
  155580. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  155581. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  155582. /* For debugging purposes, we zero the whole master structure.
  155583. * But the application has already set the err pointer, and may have set
  155584. * client_data, so we have to save and restore those fields.
  155585. * Note: if application hasn't set client_data, tools like Purify may
  155586. * complain here.
  155587. */
  155588. {
  155589. struct jpeg_error_mgr * err = cinfo->err;
  155590. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  155591. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  155592. cinfo->err = err;
  155593. cinfo->client_data = client_data;
  155594. }
  155595. cinfo->is_decompressor = FALSE;
  155596. /* Initialize a memory manager instance for this object */
  155597. jinit_memory_mgr((j_common_ptr) cinfo);
  155598. /* Zero out pointers to permanent structures. */
  155599. cinfo->progress = NULL;
  155600. cinfo->dest = NULL;
  155601. cinfo->comp_info = NULL;
  155602. for (i = 0; i < NUM_QUANT_TBLS; i++)
  155603. cinfo->quant_tbl_ptrs[i] = NULL;
  155604. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  155605. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  155606. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  155607. }
  155608. cinfo->script_space = NULL;
  155609. cinfo->input_gamma = 1.0; /* in case application forgets */
  155610. /* OK, I'm ready */
  155611. cinfo->global_state = CSTATE_START;
  155612. }
  155613. /*
  155614. * Destruction of a JPEG compression object
  155615. */
  155616. GLOBAL(void)
  155617. jpeg_destroy_compress (j_compress_ptr cinfo)
  155618. {
  155619. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  155620. }
  155621. /*
  155622. * Abort processing of a JPEG compression operation,
  155623. * but don't destroy the object itself.
  155624. */
  155625. GLOBAL(void)
  155626. jpeg_abort_compress (j_compress_ptr cinfo)
  155627. {
  155628. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  155629. }
  155630. /*
  155631. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  155632. * Marks all currently defined tables as already written (if suppress)
  155633. * or not written (if !suppress). This will control whether they get emitted
  155634. * by a subsequent jpeg_start_compress call.
  155635. *
  155636. * This routine is exported for use by applications that want to produce
  155637. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  155638. * since it is called by jpeg_start_compress, we put it here --- otherwise
  155639. * jcparam.o would be linked whether the application used it or not.
  155640. */
  155641. GLOBAL(void)
  155642. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  155643. {
  155644. int i;
  155645. JQUANT_TBL * qtbl;
  155646. JHUFF_TBL * htbl;
  155647. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  155648. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  155649. qtbl->sent_table = suppress;
  155650. }
  155651. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  155652. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  155653. htbl->sent_table = suppress;
  155654. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  155655. htbl->sent_table = suppress;
  155656. }
  155657. }
  155658. /*
  155659. * Finish JPEG compression.
  155660. *
  155661. * If a multipass operating mode was selected, this may do a great deal of
  155662. * work including most of the actual output.
  155663. */
  155664. GLOBAL(void)
  155665. jpeg_finish_compress (j_compress_ptr cinfo)
  155666. {
  155667. JDIMENSION iMCU_row;
  155668. if (cinfo->global_state == CSTATE_SCANNING ||
  155669. cinfo->global_state == CSTATE_RAW_OK) {
  155670. /* Terminate first pass */
  155671. if (cinfo->next_scanline < cinfo->image_height)
  155672. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  155673. (*cinfo->master->finish_pass) (cinfo);
  155674. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  155675. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155676. /* Perform any remaining passes */
  155677. while (! cinfo->master->is_last_pass) {
  155678. (*cinfo->master->prepare_for_pass) (cinfo);
  155679. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  155680. if (cinfo->progress != NULL) {
  155681. cinfo->progress->pass_counter = (long) iMCU_row;
  155682. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  155683. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  155684. }
  155685. /* We bypass the main controller and invoke coef controller directly;
  155686. * all work is being done from the coefficient buffer.
  155687. */
  155688. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  155689. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  155690. }
  155691. (*cinfo->master->finish_pass) (cinfo);
  155692. }
  155693. /* Write EOI, do final cleanup */
  155694. (*cinfo->marker->write_file_trailer) (cinfo);
  155695. (*cinfo->dest->term_destination) (cinfo);
  155696. /* We can use jpeg_abort to release memory and reset global_state */
  155697. jpeg_abort((j_common_ptr) cinfo);
  155698. }
  155699. /*
  155700. * Write a special marker.
  155701. * This is only recommended for writing COM or APPn markers.
  155702. * Must be called after jpeg_start_compress() and before
  155703. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  155704. */
  155705. GLOBAL(void)
  155706. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  155707. const JOCTET *dataptr, unsigned int datalen)
  155708. {
  155709. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  155710. if (cinfo->next_scanline != 0 ||
  155711. (cinfo->global_state != CSTATE_SCANNING &&
  155712. cinfo->global_state != CSTATE_RAW_OK &&
  155713. cinfo->global_state != CSTATE_WRCOEFS))
  155714. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155715. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  155716. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  155717. while (datalen--) {
  155718. (*write_marker_byte) (cinfo, *dataptr);
  155719. dataptr++;
  155720. }
  155721. }
  155722. /* Same, but piecemeal. */
  155723. GLOBAL(void)
  155724. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  155725. {
  155726. if (cinfo->next_scanline != 0 ||
  155727. (cinfo->global_state != CSTATE_SCANNING &&
  155728. cinfo->global_state != CSTATE_RAW_OK &&
  155729. cinfo->global_state != CSTATE_WRCOEFS))
  155730. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155731. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  155732. }
  155733. GLOBAL(void)
  155734. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  155735. {
  155736. (*cinfo->marker->write_marker_byte) (cinfo, val);
  155737. }
  155738. /*
  155739. * Alternate compression function: just write an abbreviated table file.
  155740. * Before calling this, all parameters and a data destination must be set up.
  155741. *
  155742. * To produce a pair of files containing abbreviated tables and abbreviated
  155743. * image data, one would proceed as follows:
  155744. *
  155745. * initialize JPEG object
  155746. * set JPEG parameters
  155747. * set destination to table file
  155748. * jpeg_write_tables(cinfo);
  155749. * set destination to image file
  155750. * jpeg_start_compress(cinfo, FALSE);
  155751. * write data...
  155752. * jpeg_finish_compress(cinfo);
  155753. *
  155754. * jpeg_write_tables has the side effect of marking all tables written
  155755. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  155756. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  155757. */
  155758. GLOBAL(void)
  155759. jpeg_write_tables (j_compress_ptr cinfo)
  155760. {
  155761. if (cinfo->global_state != CSTATE_START)
  155762. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155763. /* (Re)initialize error mgr and destination modules */
  155764. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  155765. (*cinfo->dest->init_destination) (cinfo);
  155766. /* Initialize the marker writer ... bit of a crock to do it here. */
  155767. jinit_marker_writer(cinfo);
  155768. /* Write them tables! */
  155769. (*cinfo->marker->write_tables_only) (cinfo);
  155770. /* And clean up. */
  155771. (*cinfo->dest->term_destination) (cinfo);
  155772. /*
  155773. * In library releases up through v6a, we called jpeg_abort() here to free
  155774. * any working memory allocated by the destination manager and marker
  155775. * writer. Some applications had a problem with that: they allocated space
  155776. * of their own from the library memory manager, and didn't want it to go
  155777. * away during write_tables. So now we do nothing. This will cause a
  155778. * memory leak if an app calls write_tables repeatedly without doing a full
  155779. * compression cycle or otherwise resetting the JPEG object. However, that
  155780. * seems less bad than unexpectedly freeing memory in the normal case.
  155781. * An app that prefers the old behavior can call jpeg_abort for itself after
  155782. * each call to jpeg_write_tables().
  155783. */
  155784. }
  155785. /********* End of inlined file: jcapimin.c *********/
  155786. /********* Start of inlined file: jcapistd.c *********/
  155787. #define JPEG_INTERNALS
  155788. /*
  155789. * Compression initialization.
  155790. * Before calling this, all parameters and a data destination must be set up.
  155791. *
  155792. * We require a write_all_tables parameter as a failsafe check when writing
  155793. * multiple datastreams from the same compression object. Since prior runs
  155794. * will have left all the tables marked sent_table=TRUE, a subsequent run
  155795. * would emit an abbreviated stream (no tables) by default. This may be what
  155796. * is wanted, but for safety's sake it should not be the default behavior:
  155797. * programmers should have to make a deliberate choice to emit abbreviated
  155798. * images. Therefore the documentation and examples should encourage people
  155799. * to pass write_all_tables=TRUE; then it will take active thought to do the
  155800. * wrong thing.
  155801. */
  155802. GLOBAL(void)
  155803. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  155804. {
  155805. if (cinfo->global_state != CSTATE_START)
  155806. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155807. if (write_all_tables)
  155808. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  155809. /* (Re)initialize error mgr and destination modules */
  155810. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  155811. (*cinfo->dest->init_destination) (cinfo);
  155812. /* Perform master selection of active modules */
  155813. jinit_compress_master(cinfo);
  155814. /* Set up for the first pass */
  155815. (*cinfo->master->prepare_for_pass) (cinfo);
  155816. /* Ready for application to drive first pass through jpeg_write_scanlines
  155817. * or jpeg_write_raw_data.
  155818. */
  155819. cinfo->next_scanline = 0;
  155820. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  155821. }
  155822. /*
  155823. * Write some scanlines of data to the JPEG compressor.
  155824. *
  155825. * The return value will be the number of lines actually written.
  155826. * This should be less than the supplied num_lines only in case that
  155827. * the data destination module has requested suspension of the compressor,
  155828. * or if more than image_height scanlines are passed in.
  155829. *
  155830. * Note: we warn about excess calls to jpeg_write_scanlines() since
  155831. * this likely signals an application programmer error. However,
  155832. * excess scanlines passed in the last valid call are *silently* ignored,
  155833. * so that the application need not adjust num_lines for end-of-image
  155834. * when using a multiple-scanline buffer.
  155835. */
  155836. GLOBAL(JDIMENSION)
  155837. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  155838. JDIMENSION num_lines)
  155839. {
  155840. JDIMENSION row_ctr, rows_left;
  155841. if (cinfo->global_state != CSTATE_SCANNING)
  155842. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155843. if (cinfo->next_scanline >= cinfo->image_height)
  155844. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  155845. /* Call progress monitor hook if present */
  155846. if (cinfo->progress != NULL) {
  155847. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  155848. cinfo->progress->pass_limit = (long) cinfo->image_height;
  155849. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  155850. }
  155851. /* Give master control module another chance if this is first call to
  155852. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  155853. * delayed so that application can write COM, etc, markers between
  155854. * jpeg_start_compress and jpeg_write_scanlines.
  155855. */
  155856. if (cinfo->master->call_pass_startup)
  155857. (*cinfo->master->pass_startup) (cinfo);
  155858. /* Ignore any extra scanlines at bottom of image. */
  155859. rows_left = cinfo->image_height - cinfo->next_scanline;
  155860. if (num_lines > rows_left)
  155861. num_lines = rows_left;
  155862. row_ctr = 0;
  155863. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  155864. cinfo->next_scanline += row_ctr;
  155865. return row_ctr;
  155866. }
  155867. /*
  155868. * Alternate entry point to write raw data.
  155869. * Processes exactly one iMCU row per call, unless suspended.
  155870. */
  155871. GLOBAL(JDIMENSION)
  155872. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  155873. JDIMENSION num_lines)
  155874. {
  155875. JDIMENSION lines_per_iMCU_row;
  155876. if (cinfo->global_state != CSTATE_RAW_OK)
  155877. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155878. if (cinfo->next_scanline >= cinfo->image_height) {
  155879. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  155880. return 0;
  155881. }
  155882. /* Call progress monitor hook if present */
  155883. if (cinfo->progress != NULL) {
  155884. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  155885. cinfo->progress->pass_limit = (long) cinfo->image_height;
  155886. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  155887. }
  155888. /* Give master control module another chance if this is first call to
  155889. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  155890. * delayed so that application can write COM, etc, markers between
  155891. * jpeg_start_compress and jpeg_write_raw_data.
  155892. */
  155893. if (cinfo->master->call_pass_startup)
  155894. (*cinfo->master->pass_startup) (cinfo);
  155895. /* Verify that at least one iMCU row has been passed. */
  155896. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  155897. if (num_lines < lines_per_iMCU_row)
  155898. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  155899. /* Directly compress the row. */
  155900. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  155901. /* If compressor did not consume the whole row, suspend processing. */
  155902. return 0;
  155903. }
  155904. /* OK, we processed one iMCU row. */
  155905. cinfo->next_scanline += lines_per_iMCU_row;
  155906. return lines_per_iMCU_row;
  155907. }
  155908. /********* End of inlined file: jcapistd.c *********/
  155909. /********* Start of inlined file: jccoefct.c *********/
  155910. #define JPEG_INTERNALS
  155911. /* We use a full-image coefficient buffer when doing Huffman optimization,
  155912. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  155913. * step is run during the first pass, and subsequent passes need only read
  155914. * the buffered coefficients.
  155915. */
  155916. #ifdef ENTROPY_OPT_SUPPORTED
  155917. #define FULL_COEF_BUFFER_SUPPORTED
  155918. #else
  155919. #ifdef C_MULTISCAN_FILES_SUPPORTED
  155920. #define FULL_COEF_BUFFER_SUPPORTED
  155921. #endif
  155922. #endif
  155923. /* Private buffer controller object */
  155924. typedef struct {
  155925. struct jpeg_c_coef_controller pub; /* public fields */
  155926. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  155927. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  155928. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  155929. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  155930. /* For single-pass compression, it's sufficient to buffer just one MCU
  155931. * (although this may prove a bit slow in practice). We allocate a
  155932. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  155933. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  155934. * it's not really very big; this is to keep the module interfaces unchanged
  155935. * when a large coefficient buffer is necessary.)
  155936. * In multi-pass modes, this array points to the current MCU's blocks
  155937. * within the virtual arrays.
  155938. */
  155939. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  155940. /* In multi-pass modes, we need a virtual block array for each component. */
  155941. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  155942. } my_coef_controller;
  155943. typedef my_coef_controller * my_coef_ptr;
  155944. /* Forward declarations */
  155945. METHODDEF(boolean) compress_data
  155946. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  155947. #ifdef FULL_COEF_BUFFER_SUPPORTED
  155948. METHODDEF(boolean) compress_first_pass
  155949. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  155950. METHODDEF(boolean) compress_output
  155951. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  155952. #endif
  155953. LOCAL(void)
  155954. start_iMCU_row (j_compress_ptr cinfo)
  155955. /* Reset within-iMCU-row counters for a new row */
  155956. {
  155957. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  155958. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  155959. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  155960. * But at the bottom of the image, process only what's left.
  155961. */
  155962. if (cinfo->comps_in_scan > 1) {
  155963. coef->MCU_rows_per_iMCU_row = 1;
  155964. } else {
  155965. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  155966. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  155967. else
  155968. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  155969. }
  155970. coef->mcu_ctr = 0;
  155971. coef->MCU_vert_offset = 0;
  155972. }
  155973. /*
  155974. * Initialize for a processing pass.
  155975. */
  155976. METHODDEF(void)
  155977. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  155978. {
  155979. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  155980. coef->iMCU_row_num = 0;
  155981. start_iMCU_row(cinfo);
  155982. switch (pass_mode) {
  155983. case JBUF_PASS_THRU:
  155984. if (coef->whole_image[0] != NULL)
  155985. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  155986. coef->pub.compress_data = compress_data;
  155987. break;
  155988. #ifdef FULL_COEF_BUFFER_SUPPORTED
  155989. case JBUF_SAVE_AND_PASS:
  155990. if (coef->whole_image[0] == NULL)
  155991. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  155992. coef->pub.compress_data = compress_first_pass;
  155993. break;
  155994. case JBUF_CRANK_DEST:
  155995. if (coef->whole_image[0] == NULL)
  155996. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  155997. coef->pub.compress_data = compress_output;
  155998. break;
  155999. #endif
  156000. default:
  156001. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  156002. break;
  156003. }
  156004. }
  156005. /*
  156006. * Process some data in the single-pass case.
  156007. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  156008. * per call, ie, v_samp_factor block rows for each component in the image.
  156009. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  156010. *
  156011. * NB: input_buf contains a plane for each component in image,
  156012. * which we index according to the component's SOF position.
  156013. */
  156014. METHODDEF(boolean)
  156015. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  156016. {
  156017. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  156018. JDIMENSION MCU_col_num; /* index of current MCU within row */
  156019. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  156020. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  156021. int blkn, bi, ci, yindex, yoffset, blockcnt;
  156022. JDIMENSION ypos, xpos;
  156023. jpeg_component_info *compptr;
  156024. /* Loop to write as much as one whole iMCU row */
  156025. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  156026. yoffset++) {
  156027. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  156028. MCU_col_num++) {
  156029. /* Determine where data comes from in input_buf and do the DCT thing.
  156030. * Each call on forward_DCT processes a horizontal row of DCT blocks
  156031. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  156032. * sequentially. Dummy blocks at the right or bottom edge are filled in
  156033. * specially. The data in them does not matter for image reconstruction,
  156034. * so we fill them with values that will encode to the smallest amount of
  156035. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  156036. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  156037. */
  156038. blkn = 0;
  156039. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  156040. compptr = cinfo->cur_comp_info[ci];
  156041. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  156042. : compptr->last_col_width;
  156043. xpos = MCU_col_num * compptr->MCU_sample_width;
  156044. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  156045. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  156046. if (coef->iMCU_row_num < last_iMCU_row ||
  156047. yoffset+yindex < compptr->last_row_height) {
  156048. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  156049. input_buf[compptr->component_index],
  156050. coef->MCU_buffer[blkn],
  156051. ypos, xpos, (JDIMENSION) blockcnt);
  156052. if (blockcnt < compptr->MCU_width) {
  156053. /* Create some dummy blocks at the right edge of the image. */
  156054. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  156055. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  156056. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  156057. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  156058. }
  156059. }
  156060. } else {
  156061. /* Create a row of dummy blocks at the bottom of the image. */
  156062. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  156063. compptr->MCU_width * SIZEOF(JBLOCK));
  156064. for (bi = 0; bi < compptr->MCU_width; bi++) {
  156065. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  156066. }
  156067. }
  156068. blkn += compptr->MCU_width;
  156069. ypos += DCTSIZE;
  156070. }
  156071. }
  156072. /* Try to write the MCU. In event of a suspension failure, we will
  156073. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  156074. */
  156075. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  156076. /* Suspension forced; update state counters and exit */
  156077. coef->MCU_vert_offset = yoffset;
  156078. coef->mcu_ctr = MCU_col_num;
  156079. return FALSE;
  156080. }
  156081. }
  156082. /* Completed an MCU row, but perhaps not an iMCU row */
  156083. coef->mcu_ctr = 0;
  156084. }
  156085. /* Completed the iMCU row, advance counters for next one */
  156086. coef->iMCU_row_num++;
  156087. start_iMCU_row(cinfo);
  156088. return TRUE;
  156089. }
  156090. #ifdef FULL_COEF_BUFFER_SUPPORTED
  156091. /*
  156092. * Process some data in the first pass of a multi-pass case.
  156093. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  156094. * per call, ie, v_samp_factor block rows for each component in the image.
  156095. * This amount of data is read from the source buffer, DCT'd and quantized,
  156096. * and saved into the virtual arrays. We also generate suitable dummy blocks
  156097. * as needed at the right and lower edges. (The dummy blocks are constructed
  156098. * in the virtual arrays, which have been padded appropriately.) This makes
  156099. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  156100. *
  156101. * We must also emit the data to the entropy encoder. This is conveniently
  156102. * done by calling compress_output() after we've loaded the current strip
  156103. * of the virtual arrays.
  156104. *
  156105. * NB: input_buf contains a plane for each component in image. All
  156106. * components are DCT'd and loaded into the virtual arrays in this pass.
  156107. * However, it may be that only a subset of the components are emitted to
  156108. * the entropy encoder during this first pass; be careful about looking
  156109. * at the scan-dependent variables (MCU dimensions, etc).
  156110. */
  156111. METHODDEF(boolean)
  156112. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  156113. {
  156114. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  156115. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  156116. JDIMENSION blocks_across, MCUs_across, MCUindex;
  156117. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  156118. JCOEF lastDC;
  156119. jpeg_component_info *compptr;
  156120. JBLOCKARRAY buffer;
  156121. JBLOCKROW thisblockrow, lastblockrow;
  156122. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  156123. ci++, compptr++) {
  156124. /* Align the virtual buffer for this component. */
  156125. buffer = (*cinfo->mem->access_virt_barray)
  156126. ((j_common_ptr) cinfo, coef->whole_image[ci],
  156127. coef->iMCU_row_num * compptr->v_samp_factor,
  156128. (JDIMENSION) compptr->v_samp_factor, TRUE);
  156129. /* Count non-dummy DCT block rows in this iMCU row. */
  156130. if (coef->iMCU_row_num < last_iMCU_row)
  156131. block_rows = compptr->v_samp_factor;
  156132. else {
  156133. /* NB: can't use last_row_height here, since may not be set! */
  156134. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  156135. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  156136. }
  156137. blocks_across = compptr->width_in_blocks;
  156138. h_samp_factor = compptr->h_samp_factor;
  156139. /* Count number of dummy blocks to be added at the right margin. */
  156140. ndummy = (int) (blocks_across % h_samp_factor);
  156141. if (ndummy > 0)
  156142. ndummy = h_samp_factor - ndummy;
  156143. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  156144. * on forward_DCT processes a complete horizontal row of DCT blocks.
  156145. */
  156146. for (block_row = 0; block_row < block_rows; block_row++) {
  156147. thisblockrow = buffer[block_row];
  156148. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  156149. input_buf[ci], thisblockrow,
  156150. (JDIMENSION) (block_row * DCTSIZE),
  156151. (JDIMENSION) 0, blocks_across);
  156152. if (ndummy > 0) {
  156153. /* Create dummy blocks at the right edge of the image. */
  156154. thisblockrow += blocks_across; /* => first dummy block */
  156155. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  156156. lastDC = thisblockrow[-1][0];
  156157. for (bi = 0; bi < ndummy; bi++) {
  156158. thisblockrow[bi][0] = lastDC;
  156159. }
  156160. }
  156161. }
  156162. /* If at end of image, create dummy block rows as needed.
  156163. * The tricky part here is that within each MCU, we want the DC values
  156164. * of the dummy blocks to match the last real block's DC value.
  156165. * This squeezes a few more bytes out of the resulting file...
  156166. */
  156167. if (coef->iMCU_row_num == last_iMCU_row) {
  156168. blocks_across += ndummy; /* include lower right corner */
  156169. MCUs_across = blocks_across / h_samp_factor;
  156170. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  156171. block_row++) {
  156172. thisblockrow = buffer[block_row];
  156173. lastblockrow = buffer[block_row-1];
  156174. jzero_far((void FAR *) thisblockrow,
  156175. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  156176. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  156177. lastDC = lastblockrow[h_samp_factor-1][0];
  156178. for (bi = 0; bi < h_samp_factor; bi++) {
  156179. thisblockrow[bi][0] = lastDC;
  156180. }
  156181. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  156182. lastblockrow += h_samp_factor;
  156183. }
  156184. }
  156185. }
  156186. }
  156187. /* NB: compress_output will increment iMCU_row_num if successful.
  156188. * A suspension return will result in redoing all the work above next time.
  156189. */
  156190. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  156191. return compress_output(cinfo, input_buf);
  156192. }
  156193. /*
  156194. * Process some data in subsequent passes of a multi-pass case.
  156195. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  156196. * per call, ie, v_samp_factor block rows for each component in the scan.
  156197. * The data is obtained from the virtual arrays and fed to the entropy coder.
  156198. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  156199. *
  156200. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  156201. */
  156202. METHODDEF(boolean)
  156203. compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  156204. {
  156205. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  156206. JDIMENSION MCU_col_num; /* index of current MCU within row */
  156207. int blkn, ci, xindex, yindex, yoffset;
  156208. JDIMENSION start_col;
  156209. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  156210. JBLOCKROW buffer_ptr;
  156211. jpeg_component_info *compptr;
  156212. /* Align the virtual buffers for the components used in this scan.
  156213. * NB: during first pass, this is safe only because the buffers will
  156214. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  156215. */
  156216. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  156217. compptr = cinfo->cur_comp_info[ci];
  156218. buffer[ci] = (*cinfo->mem->access_virt_barray)
  156219. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  156220. coef->iMCU_row_num * compptr->v_samp_factor,
  156221. (JDIMENSION) compptr->v_samp_factor, FALSE);
  156222. }
  156223. /* Loop to process one whole iMCU row */
  156224. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  156225. yoffset++) {
  156226. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  156227. MCU_col_num++) {
  156228. /* Construct list of pointers to DCT blocks belonging to this MCU */
  156229. blkn = 0; /* index of current DCT block within MCU */
  156230. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  156231. compptr = cinfo->cur_comp_info[ci];
  156232. start_col = MCU_col_num * compptr->MCU_width;
  156233. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  156234. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  156235. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  156236. coef->MCU_buffer[blkn++] = buffer_ptr++;
  156237. }
  156238. }
  156239. }
  156240. /* Try to write the MCU. */
  156241. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  156242. /* Suspension forced; update state counters and exit */
  156243. coef->MCU_vert_offset = yoffset;
  156244. coef->mcu_ctr = MCU_col_num;
  156245. return FALSE;
  156246. }
  156247. }
  156248. /* Completed an MCU row, but perhaps not an iMCU row */
  156249. coef->mcu_ctr = 0;
  156250. }
  156251. /* Completed the iMCU row, advance counters for next one */
  156252. coef->iMCU_row_num++;
  156253. start_iMCU_row(cinfo);
  156254. return TRUE;
  156255. }
  156256. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  156257. /*
  156258. * Initialize coefficient buffer controller.
  156259. */
  156260. GLOBAL(void)
  156261. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  156262. {
  156263. my_coef_ptr coef;
  156264. coef = (my_coef_ptr)
  156265. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156266. SIZEOF(my_coef_controller));
  156267. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  156268. coef->pub.start_pass = start_pass_coef;
  156269. /* Create the coefficient buffer. */
  156270. if (need_full_buffer) {
  156271. #ifdef FULL_COEF_BUFFER_SUPPORTED
  156272. /* Allocate a full-image virtual array for each component, */
  156273. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  156274. int ci;
  156275. jpeg_component_info *compptr;
  156276. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  156277. ci++, compptr++) {
  156278. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  156279. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  156280. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  156281. (long) compptr->h_samp_factor),
  156282. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  156283. (long) compptr->v_samp_factor),
  156284. (JDIMENSION) compptr->v_samp_factor);
  156285. }
  156286. #else
  156287. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  156288. #endif
  156289. } else {
  156290. /* We only need a single-MCU buffer. */
  156291. JBLOCKROW buffer;
  156292. int i;
  156293. buffer = (JBLOCKROW)
  156294. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156295. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  156296. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  156297. coef->MCU_buffer[i] = buffer + i;
  156298. }
  156299. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  156300. }
  156301. }
  156302. /********* End of inlined file: jccoefct.c *********/
  156303. /********* Start of inlined file: jccolor.c *********/
  156304. #define JPEG_INTERNALS
  156305. /* Private subobject */
  156306. typedef struct {
  156307. struct jpeg_color_converter pub; /* public fields */
  156308. /* Private state for RGB->YCC conversion */
  156309. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  156310. } my_color_converter;
  156311. typedef my_color_converter * my_cconvert_ptr;
  156312. /**************** RGB -> YCbCr conversion: most common case **************/
  156313. /*
  156314. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  156315. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  156316. * The conversion equations to be implemented are therefore
  156317. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  156318. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  156319. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  156320. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  156321. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  156322. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  156323. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  156324. * were not represented exactly. Now we sacrifice exact representation of
  156325. * maximum red and maximum blue in order to get exact grayscales.
  156326. *
  156327. * To avoid floating-point arithmetic, we represent the fractional constants
  156328. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  156329. * the products by 2^16, with appropriate rounding, to get the correct answer.
  156330. *
  156331. * For even more speed, we avoid doing any multiplications in the inner loop
  156332. * by precalculating the constants times R,G,B for all possible values.
  156333. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  156334. * for 12-bit samples it is still acceptable. It's not very reasonable for
  156335. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  156336. * colorspace anyway.
  156337. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  156338. * in the tables to save adding them separately in the inner loop.
  156339. */
  156340. #define SCALEBITS 16 /* speediest right-shift on some machines */
  156341. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  156342. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  156343. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  156344. /* We allocate one big table and divide it up into eight parts, instead of
  156345. * doing eight alloc_small requests. This lets us use a single table base
  156346. * address, which can be held in a register in the inner loops on many
  156347. * machines (more than can hold all eight addresses, anyway).
  156348. */
  156349. #define R_Y_OFF 0 /* offset to R => Y section */
  156350. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  156351. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  156352. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  156353. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  156354. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  156355. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  156356. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  156357. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  156358. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  156359. /*
  156360. * Initialize for RGB->YCC colorspace conversion.
  156361. */
  156362. METHODDEF(void)
  156363. rgb_ycc_start (j_compress_ptr cinfo)
  156364. {
  156365. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  156366. INT32 * rgb_ycc_tab;
  156367. INT32 i;
  156368. /* Allocate and fill in the conversion tables. */
  156369. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  156370. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156371. (TABLE_SIZE * SIZEOF(INT32)));
  156372. for (i = 0; i <= MAXJSAMPLE; i++) {
  156373. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  156374. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  156375. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  156376. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  156377. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  156378. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  156379. * This ensures that the maximum output will round to MAXJSAMPLE
  156380. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  156381. */
  156382. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  156383. /* B=>Cb and R=>Cr tables are the same
  156384. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  156385. */
  156386. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  156387. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  156388. }
  156389. }
  156390. /*
  156391. * Convert some rows of samples to the JPEG colorspace.
  156392. *
  156393. * Note that we change from the application's interleaved-pixel format
  156394. * to our internal noninterleaved, one-plane-per-component format.
  156395. * The input buffer is therefore three times as wide as the output buffer.
  156396. *
  156397. * A starting row offset is provided only for the output buffer. The caller
  156398. * can easily adjust the passed input_buf value to accommodate any row
  156399. * offset required on that side.
  156400. */
  156401. METHODDEF(void)
  156402. rgb_ycc_convert (j_compress_ptr cinfo,
  156403. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156404. JDIMENSION output_row, int num_rows)
  156405. {
  156406. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  156407. register int r, g, b;
  156408. register INT32 * ctab = cconvert->rgb_ycc_tab;
  156409. register JSAMPROW inptr;
  156410. register JSAMPROW outptr0, outptr1, outptr2;
  156411. register JDIMENSION col;
  156412. JDIMENSION num_cols = cinfo->image_width;
  156413. while (--num_rows >= 0) {
  156414. inptr = *input_buf++;
  156415. outptr0 = output_buf[0][output_row];
  156416. outptr1 = output_buf[1][output_row];
  156417. outptr2 = output_buf[2][output_row];
  156418. output_row++;
  156419. for (col = 0; col < num_cols; col++) {
  156420. r = GETJSAMPLE(inptr[RGB_RED]);
  156421. g = GETJSAMPLE(inptr[RGB_GREEN]);
  156422. b = GETJSAMPLE(inptr[RGB_BLUE]);
  156423. inptr += RGB_PIXELSIZE;
  156424. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  156425. * must be too; we do not need an explicit range-limiting operation.
  156426. * Hence the value being shifted is never negative, and we don't
  156427. * need the general RIGHT_SHIFT macro.
  156428. */
  156429. /* Y */
  156430. outptr0[col] = (JSAMPLE)
  156431. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  156432. >> SCALEBITS);
  156433. /* Cb */
  156434. outptr1[col] = (JSAMPLE)
  156435. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  156436. >> SCALEBITS);
  156437. /* Cr */
  156438. outptr2[col] = (JSAMPLE)
  156439. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  156440. >> SCALEBITS);
  156441. }
  156442. }
  156443. }
  156444. /**************** Cases other than RGB -> YCbCr **************/
  156445. /*
  156446. * Convert some rows of samples to the JPEG colorspace.
  156447. * This version handles RGB->grayscale conversion, which is the same
  156448. * as the RGB->Y portion of RGB->YCbCr.
  156449. * We assume rgb_ycc_start has been called (we only use the Y tables).
  156450. */
  156451. METHODDEF(void)
  156452. rgb_gray_convert (j_compress_ptr cinfo,
  156453. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156454. JDIMENSION output_row, int num_rows)
  156455. {
  156456. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  156457. register int r, g, b;
  156458. register INT32 * ctab = cconvert->rgb_ycc_tab;
  156459. register JSAMPROW inptr;
  156460. register JSAMPROW outptr;
  156461. register JDIMENSION col;
  156462. JDIMENSION num_cols = cinfo->image_width;
  156463. while (--num_rows >= 0) {
  156464. inptr = *input_buf++;
  156465. outptr = output_buf[0][output_row];
  156466. output_row++;
  156467. for (col = 0; col < num_cols; col++) {
  156468. r = GETJSAMPLE(inptr[RGB_RED]);
  156469. g = GETJSAMPLE(inptr[RGB_GREEN]);
  156470. b = GETJSAMPLE(inptr[RGB_BLUE]);
  156471. inptr += RGB_PIXELSIZE;
  156472. /* Y */
  156473. outptr[col] = (JSAMPLE)
  156474. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  156475. >> SCALEBITS);
  156476. }
  156477. }
  156478. }
  156479. /*
  156480. * Convert some rows of samples to the JPEG colorspace.
  156481. * This version handles Adobe-style CMYK->YCCK conversion,
  156482. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  156483. * conversion as above, while passing K (black) unchanged.
  156484. * We assume rgb_ycc_start has been called.
  156485. */
  156486. METHODDEF(void)
  156487. cmyk_ycck_convert (j_compress_ptr cinfo,
  156488. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156489. JDIMENSION output_row, int num_rows)
  156490. {
  156491. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  156492. register int r, g, b;
  156493. register INT32 * ctab = cconvert->rgb_ycc_tab;
  156494. register JSAMPROW inptr;
  156495. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  156496. register JDIMENSION col;
  156497. JDIMENSION num_cols = cinfo->image_width;
  156498. while (--num_rows >= 0) {
  156499. inptr = *input_buf++;
  156500. outptr0 = output_buf[0][output_row];
  156501. outptr1 = output_buf[1][output_row];
  156502. outptr2 = output_buf[2][output_row];
  156503. outptr3 = output_buf[3][output_row];
  156504. output_row++;
  156505. for (col = 0; col < num_cols; col++) {
  156506. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  156507. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  156508. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  156509. /* K passes through as-is */
  156510. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  156511. inptr += 4;
  156512. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  156513. * must be too; we do not need an explicit range-limiting operation.
  156514. * Hence the value being shifted is never negative, and we don't
  156515. * need the general RIGHT_SHIFT macro.
  156516. */
  156517. /* Y */
  156518. outptr0[col] = (JSAMPLE)
  156519. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  156520. >> SCALEBITS);
  156521. /* Cb */
  156522. outptr1[col] = (JSAMPLE)
  156523. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  156524. >> SCALEBITS);
  156525. /* Cr */
  156526. outptr2[col] = (JSAMPLE)
  156527. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  156528. >> SCALEBITS);
  156529. }
  156530. }
  156531. }
  156532. /*
  156533. * Convert some rows of samples to the JPEG colorspace.
  156534. * This version handles grayscale output with no conversion.
  156535. * The source can be either plain grayscale or YCbCr (since Y == gray).
  156536. */
  156537. METHODDEF(void)
  156538. grayscale_convert (j_compress_ptr cinfo,
  156539. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156540. JDIMENSION output_row, int num_rows)
  156541. {
  156542. register JSAMPROW inptr;
  156543. register JSAMPROW outptr;
  156544. register JDIMENSION col;
  156545. JDIMENSION num_cols = cinfo->image_width;
  156546. int instride = cinfo->input_components;
  156547. while (--num_rows >= 0) {
  156548. inptr = *input_buf++;
  156549. outptr = output_buf[0][output_row];
  156550. output_row++;
  156551. for (col = 0; col < num_cols; col++) {
  156552. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  156553. inptr += instride;
  156554. }
  156555. }
  156556. }
  156557. /*
  156558. * Convert some rows of samples to the JPEG colorspace.
  156559. * This version handles multi-component colorspaces without conversion.
  156560. * We assume input_components == num_components.
  156561. */
  156562. METHODDEF(void)
  156563. null_convert (j_compress_ptr cinfo,
  156564. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156565. JDIMENSION output_row, int num_rows)
  156566. {
  156567. register JSAMPROW inptr;
  156568. register JSAMPROW outptr;
  156569. register JDIMENSION col;
  156570. register int ci;
  156571. int nc = cinfo->num_components;
  156572. JDIMENSION num_cols = cinfo->image_width;
  156573. while (--num_rows >= 0) {
  156574. /* It seems fastest to make a separate pass for each component. */
  156575. for (ci = 0; ci < nc; ci++) {
  156576. inptr = *input_buf;
  156577. outptr = output_buf[ci][output_row];
  156578. for (col = 0; col < num_cols; col++) {
  156579. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  156580. inptr += nc;
  156581. }
  156582. }
  156583. input_buf++;
  156584. output_row++;
  156585. }
  156586. }
  156587. /*
  156588. * Empty method for start_pass.
  156589. */
  156590. METHODDEF(void)
  156591. null_method (j_compress_ptr cinfo)
  156592. {
  156593. /* no work needed */
  156594. }
  156595. /*
  156596. * Module initialization routine for input colorspace conversion.
  156597. */
  156598. GLOBAL(void)
  156599. jinit_color_converter (j_compress_ptr cinfo)
  156600. {
  156601. my_cconvert_ptr cconvert;
  156602. cconvert = (my_cconvert_ptr)
  156603. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156604. SIZEOF(my_color_converter));
  156605. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  156606. /* set start_pass to null method until we find out differently */
  156607. cconvert->pub.start_pass = null_method;
  156608. /* Make sure input_components agrees with in_color_space */
  156609. switch (cinfo->in_color_space) {
  156610. case JCS_GRAYSCALE:
  156611. if (cinfo->input_components != 1)
  156612. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  156613. break;
  156614. case JCS_RGB:
  156615. #if RGB_PIXELSIZE != 3
  156616. if (cinfo->input_components != RGB_PIXELSIZE)
  156617. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  156618. break;
  156619. #endif /* else share code with YCbCr */
  156620. case JCS_YCbCr:
  156621. if (cinfo->input_components != 3)
  156622. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  156623. break;
  156624. case JCS_CMYK:
  156625. case JCS_YCCK:
  156626. if (cinfo->input_components != 4)
  156627. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  156628. break;
  156629. default: /* JCS_UNKNOWN can be anything */
  156630. if (cinfo->input_components < 1)
  156631. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  156632. break;
  156633. }
  156634. /* Check num_components, set conversion method based on requested space */
  156635. switch (cinfo->jpeg_color_space) {
  156636. case JCS_GRAYSCALE:
  156637. if (cinfo->num_components != 1)
  156638. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  156639. if (cinfo->in_color_space == JCS_GRAYSCALE)
  156640. cconvert->pub.color_convert = grayscale_convert;
  156641. else if (cinfo->in_color_space == JCS_RGB) {
  156642. cconvert->pub.start_pass = rgb_ycc_start;
  156643. cconvert->pub.color_convert = rgb_gray_convert;
  156644. } else if (cinfo->in_color_space == JCS_YCbCr)
  156645. cconvert->pub.color_convert = grayscale_convert;
  156646. else
  156647. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156648. break;
  156649. case JCS_RGB:
  156650. if (cinfo->num_components != 3)
  156651. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  156652. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  156653. cconvert->pub.color_convert = null_convert;
  156654. else
  156655. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156656. break;
  156657. case JCS_YCbCr:
  156658. if (cinfo->num_components != 3)
  156659. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  156660. if (cinfo->in_color_space == JCS_RGB) {
  156661. cconvert->pub.start_pass = rgb_ycc_start;
  156662. cconvert->pub.color_convert = rgb_ycc_convert;
  156663. } else if (cinfo->in_color_space == JCS_YCbCr)
  156664. cconvert->pub.color_convert = null_convert;
  156665. else
  156666. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156667. break;
  156668. case JCS_CMYK:
  156669. if (cinfo->num_components != 4)
  156670. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  156671. if (cinfo->in_color_space == JCS_CMYK)
  156672. cconvert->pub.color_convert = null_convert;
  156673. else
  156674. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156675. break;
  156676. case JCS_YCCK:
  156677. if (cinfo->num_components != 4)
  156678. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  156679. if (cinfo->in_color_space == JCS_CMYK) {
  156680. cconvert->pub.start_pass = rgb_ycc_start;
  156681. cconvert->pub.color_convert = cmyk_ycck_convert;
  156682. } else if (cinfo->in_color_space == JCS_YCCK)
  156683. cconvert->pub.color_convert = null_convert;
  156684. else
  156685. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156686. break;
  156687. default: /* allow null conversion of JCS_UNKNOWN */
  156688. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  156689. cinfo->num_components != cinfo->input_components)
  156690. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156691. cconvert->pub.color_convert = null_convert;
  156692. break;
  156693. }
  156694. }
  156695. /********* End of inlined file: jccolor.c *********/
  156696. #undef FIX
  156697. /********* Start of inlined file: jcdctmgr.c *********/
  156698. #define JPEG_INTERNALS
  156699. /********* Start of inlined file: jdct.h *********/
  156700. /*
  156701. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  156702. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  156703. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  156704. * implementations use an array of type FAST_FLOAT, instead.)
  156705. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  156706. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  156707. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  156708. * convention improves accuracy in integer implementations and saves some
  156709. * work in floating-point ones.
  156710. * Quantization of the output coefficients is done by jcdctmgr.c.
  156711. */
  156712. #ifndef __jdct_h__
  156713. #define __jdct_h__
  156714. #if BITS_IN_JSAMPLE == 8
  156715. typedef int DCTELEM; /* 16 or 32 bits is fine */
  156716. #else
  156717. typedef INT32 DCTELEM; /* must have 32 bits */
  156718. #endif
  156719. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  156720. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  156721. /*
  156722. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  156723. * to an output sample array. The routine must dequantize the input data as
  156724. * well as perform the IDCT; for dequantization, it uses the multiplier table
  156725. * pointed to by compptr->dct_table. The output data is to be placed into the
  156726. * sample array starting at a specified column. (Any row offset needed will
  156727. * be applied to the array pointer before it is passed to the IDCT code.)
  156728. * Note that the number of samples emitted by the IDCT routine is
  156729. * DCT_scaled_size * DCT_scaled_size.
  156730. */
  156731. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  156732. /*
  156733. * Each IDCT routine has its own ideas about the best dct_table element type.
  156734. */
  156735. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  156736. #if BITS_IN_JSAMPLE == 8
  156737. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  156738. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  156739. #else
  156740. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  156741. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  156742. #endif
  156743. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  156744. /*
  156745. * Each IDCT routine is responsible for range-limiting its results and
  156746. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  156747. * be quite far out of range if the input data is corrupt, so a bulletproof
  156748. * range-limiting step is required. We use a mask-and-table-lookup method
  156749. * to do the combined operations quickly. See the comments with
  156750. * prepare_range_limit_table (in jdmaster.c) for more info.
  156751. */
  156752. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  156753. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  156754. /* Short forms of external names for systems with brain-damaged linkers. */
  156755. #ifdef NEED_SHORT_EXTERNAL_NAMES
  156756. #define jpeg_fdct_islow jFDislow
  156757. #define jpeg_fdct_ifast jFDifast
  156758. #define jpeg_fdct_float jFDfloat
  156759. #define jpeg_idct_islow jRDislow
  156760. #define jpeg_idct_ifast jRDifast
  156761. #define jpeg_idct_float jRDfloat
  156762. #define jpeg_idct_4x4 jRD4x4
  156763. #define jpeg_idct_2x2 jRD2x2
  156764. #define jpeg_idct_1x1 jRD1x1
  156765. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  156766. /* Extern declarations for the forward and inverse DCT routines. */
  156767. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  156768. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  156769. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  156770. EXTERN(void) jpeg_idct_islow
  156771. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156772. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156773. EXTERN(void) jpeg_idct_ifast
  156774. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156775. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156776. EXTERN(void) jpeg_idct_float
  156777. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156778. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156779. EXTERN(void) jpeg_idct_4x4
  156780. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156781. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156782. EXTERN(void) jpeg_idct_2x2
  156783. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156784. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156785. EXTERN(void) jpeg_idct_1x1
  156786. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156787. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156788. /*
  156789. * Macros for handling fixed-point arithmetic; these are used by many
  156790. * but not all of the DCT/IDCT modules.
  156791. *
  156792. * All values are expected to be of type INT32.
  156793. * Fractional constants are scaled left by CONST_BITS bits.
  156794. * CONST_BITS is defined within each module using these macros,
  156795. * and may differ from one module to the next.
  156796. */
  156797. #define ONE ((INT32) 1)
  156798. #define CONST_SCALE (ONE << CONST_BITS)
  156799. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  156800. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  156801. * thus causing a lot of useless floating-point operations at run time.
  156802. */
  156803. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  156804. /* Descale and correctly round an INT32 value that's scaled by N bits.
  156805. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  156806. * the fudge factor is correct for either sign of X.
  156807. */
  156808. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  156809. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  156810. * This macro is used only when the two inputs will actually be no more than
  156811. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  156812. * full 32x32 multiply. This provides a useful speedup on many machines.
  156813. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  156814. * in C, but some C compilers will do the right thing if you provide the
  156815. * correct combination of casts.
  156816. */
  156817. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  156818. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  156819. #endif
  156820. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  156821. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  156822. #endif
  156823. #ifndef MULTIPLY16C16 /* default definition */
  156824. #define MULTIPLY16C16(var,const) ((var) * (const))
  156825. #endif
  156826. /* Same except both inputs are variables. */
  156827. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  156828. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  156829. #endif
  156830. #ifndef MULTIPLY16V16 /* default definition */
  156831. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  156832. #endif
  156833. #endif
  156834. /********* End of inlined file: jdct.h *********/
  156835. /* Private declarations for DCT subsystem */
  156836. /* Private subobject for this module */
  156837. typedef struct {
  156838. struct jpeg_forward_dct pub; /* public fields */
  156839. /* Pointer to the DCT routine actually in use */
  156840. forward_DCT_method_ptr do_dct;
  156841. /* The actual post-DCT divisors --- not identical to the quant table
  156842. * entries, because of scaling (especially for an unnormalized DCT).
  156843. * Each table is given in normal array order.
  156844. */
  156845. DCTELEM * divisors[NUM_QUANT_TBLS];
  156846. #ifdef DCT_FLOAT_SUPPORTED
  156847. /* Same as above for the floating-point case. */
  156848. float_DCT_method_ptr do_float_dct;
  156849. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  156850. #endif
  156851. } my_fdct_controller;
  156852. typedef my_fdct_controller * my_fdct_ptr;
  156853. /*
  156854. * Initialize for a processing pass.
  156855. * Verify that all referenced Q-tables are present, and set up
  156856. * the divisor table for each one.
  156857. * In the current implementation, DCT of all components is done during
  156858. * the first pass, even if only some components will be output in the
  156859. * first scan. Hence all components should be examined here.
  156860. */
  156861. METHODDEF(void)
  156862. start_pass_fdctmgr (j_compress_ptr cinfo)
  156863. {
  156864. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  156865. int ci, qtblno, i;
  156866. jpeg_component_info *compptr;
  156867. JQUANT_TBL * qtbl;
  156868. DCTELEM * dtbl;
  156869. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  156870. ci++, compptr++) {
  156871. qtblno = compptr->quant_tbl_no;
  156872. /* Make sure specified quantization table is present */
  156873. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  156874. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  156875. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  156876. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  156877. /* Compute divisors for this quant table */
  156878. /* We may do this more than once for same table, but it's not a big deal */
  156879. switch (cinfo->dct_method) {
  156880. #ifdef DCT_ISLOW_SUPPORTED
  156881. case JDCT_ISLOW:
  156882. /* For LL&M IDCT method, divisors are equal to raw quantization
  156883. * coefficients multiplied by 8 (to counteract scaling).
  156884. */
  156885. if (fdct->divisors[qtblno] == NULL) {
  156886. fdct->divisors[qtblno] = (DCTELEM *)
  156887. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156888. DCTSIZE2 * SIZEOF(DCTELEM));
  156889. }
  156890. dtbl = fdct->divisors[qtblno];
  156891. for (i = 0; i < DCTSIZE2; i++) {
  156892. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  156893. }
  156894. break;
  156895. #endif
  156896. #ifdef DCT_IFAST_SUPPORTED
  156897. case JDCT_IFAST:
  156898. {
  156899. /* For AA&N IDCT method, divisors are equal to quantization
  156900. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  156901. * scalefactor[0] = 1
  156902. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  156903. * We apply a further scale factor of 8.
  156904. */
  156905. #define CONST_BITS 14
  156906. static const INT16 aanscales[DCTSIZE2] = {
  156907. /* precomputed values scaled up by 14 bits */
  156908. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  156909. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  156910. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  156911. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  156912. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  156913. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  156914. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  156915. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  156916. };
  156917. SHIFT_TEMPS
  156918. if (fdct->divisors[qtblno] == NULL) {
  156919. fdct->divisors[qtblno] = (DCTELEM *)
  156920. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156921. DCTSIZE2 * SIZEOF(DCTELEM));
  156922. }
  156923. dtbl = fdct->divisors[qtblno];
  156924. for (i = 0; i < DCTSIZE2; i++) {
  156925. dtbl[i] = (DCTELEM)
  156926. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  156927. (INT32) aanscales[i]),
  156928. CONST_BITS-3);
  156929. }
  156930. }
  156931. break;
  156932. #endif
  156933. #ifdef DCT_FLOAT_SUPPORTED
  156934. case JDCT_FLOAT:
  156935. {
  156936. /* For float AA&N IDCT method, divisors are equal to quantization
  156937. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  156938. * scalefactor[0] = 1
  156939. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  156940. * We apply a further scale factor of 8.
  156941. * What's actually stored is 1/divisor so that the inner loop can
  156942. * use a multiplication rather than a division.
  156943. */
  156944. FAST_FLOAT * fdtbl;
  156945. int row, col;
  156946. static const double aanscalefactor[DCTSIZE] = {
  156947. 1.0, 1.387039845, 1.306562965, 1.175875602,
  156948. 1.0, 0.785694958, 0.541196100, 0.275899379
  156949. };
  156950. if (fdct->float_divisors[qtblno] == NULL) {
  156951. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  156952. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156953. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  156954. }
  156955. fdtbl = fdct->float_divisors[qtblno];
  156956. i = 0;
  156957. for (row = 0; row < DCTSIZE; row++) {
  156958. for (col = 0; col < DCTSIZE; col++) {
  156959. fdtbl[i] = (FAST_FLOAT)
  156960. (1.0 / (((double) qtbl->quantval[i] *
  156961. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  156962. i++;
  156963. }
  156964. }
  156965. }
  156966. break;
  156967. #endif
  156968. default:
  156969. ERREXIT(cinfo, JERR_NOT_COMPILED);
  156970. break;
  156971. }
  156972. }
  156973. }
  156974. /*
  156975. * Perform forward DCT on one or more blocks of a component.
  156976. *
  156977. * The input samples are taken from the sample_data[] array starting at
  156978. * position start_row/start_col, and moving to the right for any additional
  156979. * blocks. The quantized coefficients are returned in coef_blocks[].
  156980. */
  156981. METHODDEF(void)
  156982. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  156983. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  156984. JDIMENSION start_row, JDIMENSION start_col,
  156985. JDIMENSION num_blocks)
  156986. /* This version is used for integer DCT implementations. */
  156987. {
  156988. /* This routine is heavily used, so it's worth coding it tightly. */
  156989. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  156990. forward_DCT_method_ptr do_dct = fdct->do_dct;
  156991. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  156992. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  156993. JDIMENSION bi;
  156994. sample_data += start_row; /* fold in the vertical offset once */
  156995. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  156996. /* Load data into workspace, applying unsigned->signed conversion */
  156997. { register DCTELEM *workspaceptr;
  156998. register JSAMPROW elemptr;
  156999. register int elemr;
  157000. workspaceptr = workspace;
  157001. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  157002. elemptr = sample_data[elemr] + start_col;
  157003. #if DCTSIZE == 8 /* unroll the inner loop */
  157004. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157005. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157006. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157007. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157008. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157009. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157010. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157011. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157012. #else
  157013. { register int elemc;
  157014. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  157015. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157016. }
  157017. }
  157018. #endif
  157019. }
  157020. }
  157021. /* Perform the DCT */
  157022. (*do_dct) (workspace);
  157023. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  157024. { register DCTELEM temp, qval;
  157025. register int i;
  157026. register JCOEFPTR output_ptr = coef_blocks[bi];
  157027. for (i = 0; i < DCTSIZE2; i++) {
  157028. qval = divisors[i];
  157029. temp = workspace[i];
  157030. /* Divide the coefficient value by qval, ensuring proper rounding.
  157031. * Since C does not specify the direction of rounding for negative
  157032. * quotients, we have to force the dividend positive for portability.
  157033. *
  157034. * In most files, at least half of the output values will be zero
  157035. * (at default quantization settings, more like three-quarters...)
  157036. * so we should ensure that this case is fast. On many machines,
  157037. * a comparison is enough cheaper than a divide to make a special test
  157038. * a win. Since both inputs will be nonnegative, we need only test
  157039. * for a < b to discover whether a/b is 0.
  157040. * If your machine's division is fast enough, define FAST_DIVIDE.
  157041. */
  157042. #ifdef FAST_DIVIDE
  157043. #define DIVIDE_BY(a,b) a /= b
  157044. #else
  157045. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  157046. #endif
  157047. if (temp < 0) {
  157048. temp = -temp;
  157049. temp += qval>>1; /* for rounding */
  157050. DIVIDE_BY(temp, qval);
  157051. temp = -temp;
  157052. } else {
  157053. temp += qval>>1; /* for rounding */
  157054. DIVIDE_BY(temp, qval);
  157055. }
  157056. output_ptr[i] = (JCOEF) temp;
  157057. }
  157058. }
  157059. }
  157060. }
  157061. #ifdef DCT_FLOAT_SUPPORTED
  157062. METHODDEF(void)
  157063. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  157064. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  157065. JDIMENSION start_row, JDIMENSION start_col,
  157066. JDIMENSION num_blocks)
  157067. /* This version is used for floating-point DCT implementations. */
  157068. {
  157069. /* This routine is heavily used, so it's worth coding it tightly. */
  157070. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  157071. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  157072. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  157073. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  157074. JDIMENSION bi;
  157075. sample_data += start_row; /* fold in the vertical offset once */
  157076. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  157077. /* Load data into workspace, applying unsigned->signed conversion */
  157078. { register FAST_FLOAT *workspaceptr;
  157079. register JSAMPROW elemptr;
  157080. register int elemr;
  157081. workspaceptr = workspace;
  157082. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  157083. elemptr = sample_data[elemr] + start_col;
  157084. #if DCTSIZE == 8 /* unroll the inner loop */
  157085. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157086. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157087. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157088. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157089. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157090. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157091. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157092. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157093. #else
  157094. { register int elemc;
  157095. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  157096. *workspaceptr++ = (FAST_FLOAT)
  157097. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157098. }
  157099. }
  157100. #endif
  157101. }
  157102. }
  157103. /* Perform the DCT */
  157104. (*do_dct) (workspace);
  157105. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  157106. { register FAST_FLOAT temp;
  157107. register int i;
  157108. register JCOEFPTR output_ptr = coef_blocks[bi];
  157109. for (i = 0; i < DCTSIZE2; i++) {
  157110. /* Apply the quantization and scaling factor */
  157111. temp = workspace[i] * divisors[i];
  157112. /* Round to nearest integer.
  157113. * Since C does not specify the direction of rounding for negative
  157114. * quotients, we have to force the dividend positive for portability.
  157115. * The maximum coefficient size is +-16K (for 12-bit data), so this
  157116. * code should work for either 16-bit or 32-bit ints.
  157117. */
  157118. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  157119. }
  157120. }
  157121. }
  157122. }
  157123. #endif /* DCT_FLOAT_SUPPORTED */
  157124. /*
  157125. * Initialize FDCT manager.
  157126. */
  157127. GLOBAL(void)
  157128. jinit_forward_dct (j_compress_ptr cinfo)
  157129. {
  157130. my_fdct_ptr fdct;
  157131. int i;
  157132. fdct = (my_fdct_ptr)
  157133. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157134. SIZEOF(my_fdct_controller));
  157135. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  157136. fdct->pub.start_pass = start_pass_fdctmgr;
  157137. switch (cinfo->dct_method) {
  157138. #ifdef DCT_ISLOW_SUPPORTED
  157139. case JDCT_ISLOW:
  157140. fdct->pub.forward_DCT = forward_DCT;
  157141. fdct->do_dct = jpeg_fdct_islow;
  157142. break;
  157143. #endif
  157144. #ifdef DCT_IFAST_SUPPORTED
  157145. case JDCT_IFAST:
  157146. fdct->pub.forward_DCT = forward_DCT;
  157147. fdct->do_dct = jpeg_fdct_ifast;
  157148. break;
  157149. #endif
  157150. #ifdef DCT_FLOAT_SUPPORTED
  157151. case JDCT_FLOAT:
  157152. fdct->pub.forward_DCT = forward_DCT_float;
  157153. fdct->do_float_dct = jpeg_fdct_float;
  157154. break;
  157155. #endif
  157156. default:
  157157. ERREXIT(cinfo, JERR_NOT_COMPILED);
  157158. break;
  157159. }
  157160. /* Mark divisor tables unallocated */
  157161. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  157162. fdct->divisors[i] = NULL;
  157163. #ifdef DCT_FLOAT_SUPPORTED
  157164. fdct->float_divisors[i] = NULL;
  157165. #endif
  157166. }
  157167. }
  157168. /********* End of inlined file: jcdctmgr.c *********/
  157169. #undef CONST_BITS
  157170. /********* Start of inlined file: jchuff.c *********/
  157171. #define JPEG_INTERNALS
  157172. /********* Start of inlined file: jchuff.h *********/
  157173. /* The legal range of a DCT coefficient is
  157174. * -1024 .. +1023 for 8-bit data;
  157175. * -16384 .. +16383 for 12-bit data.
  157176. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  157177. */
  157178. #ifndef _jchuff_h_
  157179. #define _jchuff_h_
  157180. #if BITS_IN_JSAMPLE == 8
  157181. #define MAX_COEF_BITS 10
  157182. #else
  157183. #define MAX_COEF_BITS 14
  157184. #endif
  157185. /* Derived data constructed for each Huffman table */
  157186. typedef struct {
  157187. unsigned int ehufco[256]; /* code for each symbol */
  157188. char ehufsi[256]; /* length of code for each symbol */
  157189. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  157190. } c_derived_tbl;
  157191. /* Short forms of external names for systems with brain-damaged linkers. */
  157192. #ifdef NEED_SHORT_EXTERNAL_NAMES
  157193. #define jpeg_make_c_derived_tbl jMkCDerived
  157194. #define jpeg_gen_optimal_table jGenOptTbl
  157195. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  157196. /* Expand a Huffman table definition into the derived format */
  157197. EXTERN(void) jpeg_make_c_derived_tbl
  157198. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  157199. c_derived_tbl ** pdtbl));
  157200. /* Generate an optimal table definition given the specified counts */
  157201. EXTERN(void) jpeg_gen_optimal_table
  157202. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  157203. #endif
  157204. /********* End of inlined file: jchuff.h *********/
  157205. /* Declarations shared with jcphuff.c */
  157206. /* Expanded entropy encoder object for Huffman encoding.
  157207. *
  157208. * The savable_state subrecord contains fields that change within an MCU,
  157209. * but must not be updated permanently until we complete the MCU.
  157210. */
  157211. typedef struct {
  157212. INT32 put_buffer; /* current bit-accumulation buffer */
  157213. int put_bits; /* # of bits now in it */
  157214. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  157215. } savable_state;
  157216. /* This macro is to work around compilers with missing or broken
  157217. * structure assignment. You'll need to fix this code if you have
  157218. * such a compiler and you change MAX_COMPS_IN_SCAN.
  157219. */
  157220. #ifndef NO_STRUCT_ASSIGN
  157221. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  157222. #else
  157223. #if MAX_COMPS_IN_SCAN == 4
  157224. #define ASSIGN_STATE(dest,src) \
  157225. ((dest).put_buffer = (src).put_buffer, \
  157226. (dest).put_bits = (src).put_bits, \
  157227. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  157228. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  157229. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  157230. (dest).last_dc_val[3] = (src).last_dc_val[3])
  157231. #endif
  157232. #endif
  157233. typedef struct {
  157234. struct jpeg_entropy_encoder pub; /* public fields */
  157235. savable_state saved; /* Bit buffer & DC state at start of MCU */
  157236. /* These fields are NOT loaded into local working state. */
  157237. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  157238. int next_restart_num; /* next restart number to write (0-7) */
  157239. /* Pointers to derived tables (these workspaces have image lifespan) */
  157240. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  157241. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  157242. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  157243. long * dc_count_ptrs[NUM_HUFF_TBLS];
  157244. long * ac_count_ptrs[NUM_HUFF_TBLS];
  157245. #endif
  157246. } huff_entropy_encoder;
  157247. typedef huff_entropy_encoder * huff_entropy_ptr;
  157248. /* Working state while writing an MCU.
  157249. * This struct contains all the fields that are needed by subroutines.
  157250. */
  157251. typedef struct {
  157252. JOCTET * next_output_byte; /* => next byte to write in buffer */
  157253. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  157254. savable_state cur; /* Current bit buffer & DC state */
  157255. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  157256. } working_state;
  157257. /* Forward declarations */
  157258. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  157259. JBLOCKROW *MCU_data));
  157260. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  157261. #ifdef ENTROPY_OPT_SUPPORTED
  157262. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  157263. JBLOCKROW *MCU_data));
  157264. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  157265. #endif
  157266. /*
  157267. * Initialize for a Huffman-compressed scan.
  157268. * If gather_statistics is TRUE, we do not output anything during the scan,
  157269. * just count the Huffman symbols used and generate Huffman code tables.
  157270. */
  157271. METHODDEF(void)
  157272. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  157273. {
  157274. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157275. int ci, dctbl, actbl;
  157276. jpeg_component_info * compptr;
  157277. if (gather_statistics) {
  157278. #ifdef ENTROPY_OPT_SUPPORTED
  157279. entropy->pub.encode_mcu = encode_mcu_gather;
  157280. entropy->pub.finish_pass = finish_pass_gather;
  157281. #else
  157282. ERREXIT(cinfo, JERR_NOT_COMPILED);
  157283. #endif
  157284. } else {
  157285. entropy->pub.encode_mcu = encode_mcu_huff;
  157286. entropy->pub.finish_pass = finish_pass_huff;
  157287. }
  157288. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157289. compptr = cinfo->cur_comp_info[ci];
  157290. dctbl = compptr->dc_tbl_no;
  157291. actbl = compptr->ac_tbl_no;
  157292. if (gather_statistics) {
  157293. #ifdef ENTROPY_OPT_SUPPORTED
  157294. /* Check for invalid table indexes */
  157295. /* (make_c_derived_tbl does this in the other path) */
  157296. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  157297. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  157298. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  157299. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  157300. /* Allocate and zero the statistics tables */
  157301. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  157302. if (entropy->dc_count_ptrs[dctbl] == NULL)
  157303. entropy->dc_count_ptrs[dctbl] = (long *)
  157304. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157305. 257 * SIZEOF(long));
  157306. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  157307. if (entropy->ac_count_ptrs[actbl] == NULL)
  157308. entropy->ac_count_ptrs[actbl] = (long *)
  157309. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157310. 257 * SIZEOF(long));
  157311. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  157312. #endif
  157313. } else {
  157314. /* Compute derived values for Huffman tables */
  157315. /* We may do this more than once for a table, but it's not expensive */
  157316. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  157317. & entropy->dc_derived_tbls[dctbl]);
  157318. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  157319. & entropy->ac_derived_tbls[actbl]);
  157320. }
  157321. /* Initialize DC predictions to 0 */
  157322. entropy->saved.last_dc_val[ci] = 0;
  157323. }
  157324. /* Initialize bit buffer to empty */
  157325. entropy->saved.put_buffer = 0;
  157326. entropy->saved.put_bits = 0;
  157327. /* Initialize restart stuff */
  157328. entropy->restarts_to_go = cinfo->restart_interval;
  157329. entropy->next_restart_num = 0;
  157330. }
  157331. /*
  157332. * Compute the derived values for a Huffman table.
  157333. * This routine also performs some validation checks on the table.
  157334. *
  157335. * Note this is also used by jcphuff.c.
  157336. */
  157337. GLOBAL(void)
  157338. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  157339. c_derived_tbl ** pdtbl)
  157340. {
  157341. JHUFF_TBL *htbl;
  157342. c_derived_tbl *dtbl;
  157343. int p, i, l, lastp, si, maxsymbol;
  157344. char huffsize[257];
  157345. unsigned int huffcode[257];
  157346. unsigned int code;
  157347. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  157348. * paralleling the order of the symbols themselves in htbl->huffval[].
  157349. */
  157350. /* Find the input Huffman table */
  157351. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  157352. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  157353. htbl =
  157354. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  157355. if (htbl == NULL)
  157356. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  157357. /* Allocate a workspace if we haven't already done so. */
  157358. if (*pdtbl == NULL)
  157359. *pdtbl = (c_derived_tbl *)
  157360. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157361. SIZEOF(c_derived_tbl));
  157362. dtbl = *pdtbl;
  157363. /* Figure C.1: make table of Huffman code length for each symbol */
  157364. p = 0;
  157365. for (l = 1; l <= 16; l++) {
  157366. i = (int) htbl->bits[l];
  157367. if (i < 0 || p + i > 256) /* protect against table overrun */
  157368. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  157369. while (i--)
  157370. huffsize[p++] = (char) l;
  157371. }
  157372. huffsize[p] = 0;
  157373. lastp = p;
  157374. /* Figure C.2: generate the codes themselves */
  157375. /* We also validate that the counts represent a legal Huffman code tree. */
  157376. code = 0;
  157377. si = huffsize[0];
  157378. p = 0;
  157379. while (huffsize[p]) {
  157380. while (((int) huffsize[p]) == si) {
  157381. huffcode[p++] = code;
  157382. code++;
  157383. }
  157384. /* code is now 1 more than the last code used for codelength si; but
  157385. * it must still fit in si bits, since no code is allowed to be all ones.
  157386. */
  157387. if (((INT32) code) >= (((INT32) 1) << si))
  157388. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  157389. code <<= 1;
  157390. si++;
  157391. }
  157392. /* Figure C.3: generate encoding tables */
  157393. /* These are code and size indexed by symbol value */
  157394. /* Set all codeless symbols to have code length 0;
  157395. * this lets us detect duplicate VAL entries here, and later
  157396. * allows emit_bits to detect any attempt to emit such symbols.
  157397. */
  157398. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  157399. /* This is also a convenient place to check for out-of-range
  157400. * and duplicated VAL entries. We allow 0..255 for AC symbols
  157401. * but only 0..15 for DC. (We could constrain them further
  157402. * based on data depth and mode, but this seems enough.)
  157403. */
  157404. maxsymbol = isDC ? 15 : 255;
  157405. for (p = 0; p < lastp; p++) {
  157406. i = htbl->huffval[p];
  157407. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  157408. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  157409. dtbl->ehufco[i] = huffcode[p];
  157410. dtbl->ehufsi[i] = huffsize[p];
  157411. }
  157412. }
  157413. /* Outputting bytes to the file */
  157414. /* Emit a byte, taking 'action' if must suspend. */
  157415. #define emit_byte(state,val,action) \
  157416. { *(state)->next_output_byte++ = (JOCTET) (val); \
  157417. if (--(state)->free_in_buffer == 0) \
  157418. if (! dump_buffer(state)) \
  157419. { action; } }
  157420. LOCAL(boolean)
  157421. dump_buffer (working_state * state)
  157422. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  157423. {
  157424. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  157425. if (! (*dest->empty_output_buffer) (state->cinfo))
  157426. return FALSE;
  157427. /* After a successful buffer dump, must reset buffer pointers */
  157428. state->next_output_byte = dest->next_output_byte;
  157429. state->free_in_buffer = dest->free_in_buffer;
  157430. return TRUE;
  157431. }
  157432. /* Outputting bits to the file */
  157433. /* Only the right 24 bits of put_buffer are used; the valid bits are
  157434. * left-justified in this part. At most 16 bits can be passed to emit_bits
  157435. * in one call, and we never retain more than 7 bits in put_buffer
  157436. * between calls, so 24 bits are sufficient.
  157437. */
  157438. INLINE
  157439. LOCAL(boolean)
  157440. emit_bits (working_state * state, unsigned int code, int size)
  157441. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  157442. {
  157443. /* This routine is heavily used, so it's worth coding tightly. */
  157444. register INT32 put_buffer = (INT32) code;
  157445. register int put_bits = state->cur.put_bits;
  157446. /* if size is 0, caller used an invalid Huffman table entry */
  157447. if (size == 0)
  157448. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  157449. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  157450. put_bits += size; /* new number of bits in buffer */
  157451. put_buffer <<= 24 - put_bits; /* align incoming bits */
  157452. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  157453. while (put_bits >= 8) {
  157454. int c = (int) ((put_buffer >> 16) & 0xFF);
  157455. emit_byte(state, c, return FALSE);
  157456. if (c == 0xFF) { /* need to stuff a zero byte? */
  157457. emit_byte(state, 0, return FALSE);
  157458. }
  157459. put_buffer <<= 8;
  157460. put_bits -= 8;
  157461. }
  157462. state->cur.put_buffer = put_buffer; /* update state variables */
  157463. state->cur.put_bits = put_bits;
  157464. return TRUE;
  157465. }
  157466. LOCAL(boolean)
  157467. flush_bits (working_state * state)
  157468. {
  157469. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  157470. return FALSE;
  157471. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  157472. state->cur.put_bits = 0;
  157473. return TRUE;
  157474. }
  157475. /* Encode a single block's worth of coefficients */
  157476. LOCAL(boolean)
  157477. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  157478. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  157479. {
  157480. register int temp, temp2;
  157481. register int nbits;
  157482. register int k, r, i;
  157483. /* Encode the DC coefficient difference per section F.1.2.1 */
  157484. temp = temp2 = block[0] - last_dc_val;
  157485. if (temp < 0) {
  157486. temp = -temp; /* temp is abs value of input */
  157487. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  157488. /* This code assumes we are on a two's complement machine */
  157489. temp2--;
  157490. }
  157491. /* Find the number of bits needed for the magnitude of the coefficient */
  157492. nbits = 0;
  157493. while (temp) {
  157494. nbits++;
  157495. temp >>= 1;
  157496. }
  157497. /* Check for out-of-range coefficient values.
  157498. * Since we're encoding a difference, the range limit is twice as much.
  157499. */
  157500. if (nbits > MAX_COEF_BITS+1)
  157501. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  157502. /* Emit the Huffman-coded symbol for the number of bits */
  157503. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  157504. return FALSE;
  157505. /* Emit that number of bits of the value, if positive, */
  157506. /* or the complement of its magnitude, if negative. */
  157507. if (nbits) /* emit_bits rejects calls with size 0 */
  157508. if (! emit_bits(state, (unsigned int) temp2, nbits))
  157509. return FALSE;
  157510. /* Encode the AC coefficients per section F.1.2.2 */
  157511. r = 0; /* r = run length of zeros */
  157512. for (k = 1; k < DCTSIZE2; k++) {
  157513. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  157514. r++;
  157515. } else {
  157516. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  157517. while (r > 15) {
  157518. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  157519. return FALSE;
  157520. r -= 16;
  157521. }
  157522. temp2 = temp;
  157523. if (temp < 0) {
  157524. temp = -temp; /* temp is abs value of input */
  157525. /* This code assumes we are on a two's complement machine */
  157526. temp2--;
  157527. }
  157528. /* Find the number of bits needed for the magnitude of the coefficient */
  157529. nbits = 1; /* there must be at least one 1 bit */
  157530. while ((temp >>= 1))
  157531. nbits++;
  157532. /* Check for out-of-range coefficient values */
  157533. if (nbits > MAX_COEF_BITS)
  157534. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  157535. /* Emit Huffman symbol for run length / number of bits */
  157536. i = (r << 4) + nbits;
  157537. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  157538. return FALSE;
  157539. /* Emit that number of bits of the value, if positive, */
  157540. /* or the complement of its magnitude, if negative. */
  157541. if (! emit_bits(state, (unsigned int) temp2, nbits))
  157542. return FALSE;
  157543. r = 0;
  157544. }
  157545. }
  157546. /* If the last coef(s) were zero, emit an end-of-block code */
  157547. if (r > 0)
  157548. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  157549. return FALSE;
  157550. return TRUE;
  157551. }
  157552. /*
  157553. * Emit a restart marker & resynchronize predictions.
  157554. */
  157555. LOCAL(boolean)
  157556. emit_restart (working_state * state, int restart_num)
  157557. {
  157558. int ci;
  157559. if (! flush_bits(state))
  157560. return FALSE;
  157561. emit_byte(state, 0xFF, return FALSE);
  157562. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  157563. /* Re-initialize DC predictions to 0 */
  157564. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  157565. state->cur.last_dc_val[ci] = 0;
  157566. /* The restart counter is not updated until we successfully write the MCU. */
  157567. return TRUE;
  157568. }
  157569. /*
  157570. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  157571. */
  157572. METHODDEF(boolean)
  157573. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  157574. {
  157575. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157576. working_state state;
  157577. int blkn, ci;
  157578. jpeg_component_info * compptr;
  157579. /* Load up working state */
  157580. state.next_output_byte = cinfo->dest->next_output_byte;
  157581. state.free_in_buffer = cinfo->dest->free_in_buffer;
  157582. ASSIGN_STATE(state.cur, entropy->saved);
  157583. state.cinfo = cinfo;
  157584. /* Emit restart marker if needed */
  157585. if (cinfo->restart_interval) {
  157586. if (entropy->restarts_to_go == 0)
  157587. if (! emit_restart(&state, entropy->next_restart_num))
  157588. return FALSE;
  157589. }
  157590. /* Encode the MCU data blocks */
  157591. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  157592. ci = cinfo->MCU_membership[blkn];
  157593. compptr = cinfo->cur_comp_info[ci];
  157594. if (! encode_one_block(&state,
  157595. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  157596. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  157597. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  157598. return FALSE;
  157599. /* Update last_dc_val */
  157600. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  157601. }
  157602. /* Completed MCU, so update state */
  157603. cinfo->dest->next_output_byte = state.next_output_byte;
  157604. cinfo->dest->free_in_buffer = state.free_in_buffer;
  157605. ASSIGN_STATE(entropy->saved, state.cur);
  157606. /* Update restart-interval state too */
  157607. if (cinfo->restart_interval) {
  157608. if (entropy->restarts_to_go == 0) {
  157609. entropy->restarts_to_go = cinfo->restart_interval;
  157610. entropy->next_restart_num++;
  157611. entropy->next_restart_num &= 7;
  157612. }
  157613. entropy->restarts_to_go--;
  157614. }
  157615. return TRUE;
  157616. }
  157617. /*
  157618. * Finish up at the end of a Huffman-compressed scan.
  157619. */
  157620. METHODDEF(void)
  157621. finish_pass_huff (j_compress_ptr cinfo)
  157622. {
  157623. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157624. working_state state;
  157625. /* Load up working state ... flush_bits needs it */
  157626. state.next_output_byte = cinfo->dest->next_output_byte;
  157627. state.free_in_buffer = cinfo->dest->free_in_buffer;
  157628. ASSIGN_STATE(state.cur, entropy->saved);
  157629. state.cinfo = cinfo;
  157630. /* Flush out the last data */
  157631. if (! flush_bits(&state))
  157632. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  157633. /* Update state */
  157634. cinfo->dest->next_output_byte = state.next_output_byte;
  157635. cinfo->dest->free_in_buffer = state.free_in_buffer;
  157636. ASSIGN_STATE(entropy->saved, state.cur);
  157637. }
  157638. /*
  157639. * Huffman coding optimization.
  157640. *
  157641. * We first scan the supplied data and count the number of uses of each symbol
  157642. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  157643. * Then we build a Huffman coding tree for the observed counts.
  157644. * Symbols which are not needed at all for the particular image are not
  157645. * assigned any code, which saves space in the DHT marker as well as in
  157646. * the compressed data.
  157647. */
  157648. #ifdef ENTROPY_OPT_SUPPORTED
  157649. /* Process a single block's worth of coefficients */
  157650. LOCAL(void)
  157651. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  157652. long dc_counts[], long ac_counts[])
  157653. {
  157654. register int temp;
  157655. register int nbits;
  157656. register int k, r;
  157657. /* Encode the DC coefficient difference per section F.1.2.1 */
  157658. temp = block[0] - last_dc_val;
  157659. if (temp < 0)
  157660. temp = -temp;
  157661. /* Find the number of bits needed for the magnitude of the coefficient */
  157662. nbits = 0;
  157663. while (temp) {
  157664. nbits++;
  157665. temp >>= 1;
  157666. }
  157667. /* Check for out-of-range coefficient values.
  157668. * Since we're encoding a difference, the range limit is twice as much.
  157669. */
  157670. if (nbits > MAX_COEF_BITS+1)
  157671. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  157672. /* Count the Huffman symbol for the number of bits */
  157673. dc_counts[nbits]++;
  157674. /* Encode the AC coefficients per section F.1.2.2 */
  157675. r = 0; /* r = run length of zeros */
  157676. for (k = 1; k < DCTSIZE2; k++) {
  157677. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  157678. r++;
  157679. } else {
  157680. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  157681. while (r > 15) {
  157682. ac_counts[0xF0]++;
  157683. r -= 16;
  157684. }
  157685. /* Find the number of bits needed for the magnitude of the coefficient */
  157686. if (temp < 0)
  157687. temp = -temp;
  157688. /* Find the number of bits needed for the magnitude of the coefficient */
  157689. nbits = 1; /* there must be at least one 1 bit */
  157690. while ((temp >>= 1))
  157691. nbits++;
  157692. /* Check for out-of-range coefficient values */
  157693. if (nbits > MAX_COEF_BITS)
  157694. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  157695. /* Count Huffman symbol for run length / number of bits */
  157696. ac_counts[(r << 4) + nbits]++;
  157697. r = 0;
  157698. }
  157699. }
  157700. /* If the last coef(s) were zero, emit an end-of-block code */
  157701. if (r > 0)
  157702. ac_counts[0]++;
  157703. }
  157704. /*
  157705. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  157706. * No data is actually output, so no suspension return is possible.
  157707. */
  157708. METHODDEF(boolean)
  157709. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  157710. {
  157711. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157712. int blkn, ci;
  157713. jpeg_component_info * compptr;
  157714. /* Take care of restart intervals if needed */
  157715. if (cinfo->restart_interval) {
  157716. if (entropy->restarts_to_go == 0) {
  157717. /* Re-initialize DC predictions to 0 */
  157718. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  157719. entropy->saved.last_dc_val[ci] = 0;
  157720. /* Update restart state */
  157721. entropy->restarts_to_go = cinfo->restart_interval;
  157722. }
  157723. entropy->restarts_to_go--;
  157724. }
  157725. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  157726. ci = cinfo->MCU_membership[blkn];
  157727. compptr = cinfo->cur_comp_info[ci];
  157728. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  157729. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  157730. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  157731. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  157732. }
  157733. return TRUE;
  157734. }
  157735. /*
  157736. * Generate the best Huffman code table for the given counts, fill htbl.
  157737. * Note this is also used by jcphuff.c.
  157738. *
  157739. * The JPEG standard requires that no symbol be assigned a codeword of all
  157740. * one bits (so that padding bits added at the end of a compressed segment
  157741. * can't look like a valid code). Because of the canonical ordering of
  157742. * codewords, this just means that there must be an unused slot in the
  157743. * longest codeword length category. Section K.2 of the JPEG spec suggests
  157744. * reserving such a slot by pretending that symbol 256 is a valid symbol
  157745. * with count 1. In theory that's not optimal; giving it count zero but
  157746. * including it in the symbol set anyway should give a better Huffman code.
  157747. * But the theoretically better code actually seems to come out worse in
  157748. * practice, because it produces more all-ones bytes (which incur stuffed
  157749. * zero bytes in the final file). In any case the difference is tiny.
  157750. *
  157751. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  157752. * If some symbols have a very small but nonzero probability, the Huffman tree
  157753. * must be adjusted to meet the code length restriction. We currently use
  157754. * the adjustment method suggested in JPEG section K.2. This method is *not*
  157755. * optimal; it may not choose the best possible limited-length code. But
  157756. * typically only very-low-frequency symbols will be given less-than-optimal
  157757. * lengths, so the code is almost optimal. Experimental comparisons against
  157758. * an optimal limited-length-code algorithm indicate that the difference is
  157759. * microscopic --- usually less than a hundredth of a percent of total size.
  157760. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  157761. */
  157762. GLOBAL(void)
  157763. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  157764. {
  157765. #define MAX_CLEN 32 /* assumed maximum initial code length */
  157766. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  157767. int codesize[257]; /* codesize[k] = code length of symbol k */
  157768. int others[257]; /* next symbol in current branch of tree */
  157769. int c1, c2;
  157770. int p, i, j;
  157771. long v;
  157772. /* This algorithm is explained in section K.2 of the JPEG standard */
  157773. MEMZERO(bits, SIZEOF(bits));
  157774. MEMZERO(codesize, SIZEOF(codesize));
  157775. for (i = 0; i < 257; i++)
  157776. others[i] = -1; /* init links to empty */
  157777. freq[256] = 1; /* make sure 256 has a nonzero count */
  157778. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  157779. * that no real symbol is given code-value of all ones, because 256
  157780. * will be placed last in the largest codeword category.
  157781. */
  157782. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  157783. for (;;) {
  157784. /* Find the smallest nonzero frequency, set c1 = its symbol */
  157785. /* In case of ties, take the larger symbol number */
  157786. c1 = -1;
  157787. v = 1000000000L;
  157788. for (i = 0; i <= 256; i++) {
  157789. if (freq[i] && freq[i] <= v) {
  157790. v = freq[i];
  157791. c1 = i;
  157792. }
  157793. }
  157794. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  157795. /* In case of ties, take the larger symbol number */
  157796. c2 = -1;
  157797. v = 1000000000L;
  157798. for (i = 0; i <= 256; i++) {
  157799. if (freq[i] && freq[i] <= v && i != c1) {
  157800. v = freq[i];
  157801. c2 = i;
  157802. }
  157803. }
  157804. /* Done if we've merged everything into one frequency */
  157805. if (c2 < 0)
  157806. break;
  157807. /* Else merge the two counts/trees */
  157808. freq[c1] += freq[c2];
  157809. freq[c2] = 0;
  157810. /* Increment the codesize of everything in c1's tree branch */
  157811. codesize[c1]++;
  157812. while (others[c1] >= 0) {
  157813. c1 = others[c1];
  157814. codesize[c1]++;
  157815. }
  157816. others[c1] = c2; /* chain c2 onto c1's tree branch */
  157817. /* Increment the codesize of everything in c2's tree branch */
  157818. codesize[c2]++;
  157819. while (others[c2] >= 0) {
  157820. c2 = others[c2];
  157821. codesize[c2]++;
  157822. }
  157823. }
  157824. /* Now count the number of symbols of each code length */
  157825. for (i = 0; i <= 256; i++) {
  157826. if (codesize[i]) {
  157827. /* The JPEG standard seems to think that this can't happen, */
  157828. /* but I'm paranoid... */
  157829. if (codesize[i] > MAX_CLEN)
  157830. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  157831. bits[codesize[i]]++;
  157832. }
  157833. }
  157834. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  157835. * Huffman procedure assigned any such lengths, we must adjust the coding.
  157836. * Here is what the JPEG spec says about how this next bit works:
  157837. * Since symbols are paired for the longest Huffman code, the symbols are
  157838. * removed from this length category two at a time. The prefix for the pair
  157839. * (which is one bit shorter) is allocated to one of the pair; then,
  157840. * skipping the BITS entry for that prefix length, a code word from the next
  157841. * shortest nonzero BITS entry is converted into a prefix for two code words
  157842. * one bit longer.
  157843. */
  157844. for (i = MAX_CLEN; i > 16; i--) {
  157845. while (bits[i] > 0) {
  157846. j = i - 2; /* find length of new prefix to be used */
  157847. while (bits[j] == 0)
  157848. j--;
  157849. bits[i] -= 2; /* remove two symbols */
  157850. bits[i-1]++; /* one goes in this length */
  157851. bits[j+1] += 2; /* two new symbols in this length */
  157852. bits[j]--; /* symbol of this length is now a prefix */
  157853. }
  157854. }
  157855. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  157856. while (bits[i] == 0) /* find largest codelength still in use */
  157857. i--;
  157858. bits[i]--;
  157859. /* Return final symbol counts (only for lengths 0..16) */
  157860. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  157861. /* Return a list of the symbols sorted by code length */
  157862. /* It's not real clear to me why we don't need to consider the codelength
  157863. * changes made above, but the JPEG spec seems to think this works.
  157864. */
  157865. p = 0;
  157866. for (i = 1; i <= MAX_CLEN; i++) {
  157867. for (j = 0; j <= 255; j++) {
  157868. if (codesize[j] == i) {
  157869. htbl->huffval[p] = (UINT8) j;
  157870. p++;
  157871. }
  157872. }
  157873. }
  157874. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  157875. htbl->sent_table = FALSE;
  157876. }
  157877. /*
  157878. * Finish up a statistics-gathering pass and create the new Huffman tables.
  157879. */
  157880. METHODDEF(void)
  157881. finish_pass_gather (j_compress_ptr cinfo)
  157882. {
  157883. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157884. int ci, dctbl, actbl;
  157885. jpeg_component_info * compptr;
  157886. JHUFF_TBL **htblptr;
  157887. boolean did_dc[NUM_HUFF_TBLS];
  157888. boolean did_ac[NUM_HUFF_TBLS];
  157889. /* It's important not to apply jpeg_gen_optimal_table more than once
  157890. * per table, because it clobbers the input frequency counts!
  157891. */
  157892. MEMZERO(did_dc, SIZEOF(did_dc));
  157893. MEMZERO(did_ac, SIZEOF(did_ac));
  157894. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157895. compptr = cinfo->cur_comp_info[ci];
  157896. dctbl = compptr->dc_tbl_no;
  157897. actbl = compptr->ac_tbl_no;
  157898. if (! did_dc[dctbl]) {
  157899. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  157900. if (*htblptr == NULL)
  157901. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  157902. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  157903. did_dc[dctbl] = TRUE;
  157904. }
  157905. if (! did_ac[actbl]) {
  157906. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  157907. if (*htblptr == NULL)
  157908. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  157909. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  157910. did_ac[actbl] = TRUE;
  157911. }
  157912. }
  157913. }
  157914. #endif /* ENTROPY_OPT_SUPPORTED */
  157915. /*
  157916. * Module initialization routine for Huffman entropy encoding.
  157917. */
  157918. GLOBAL(void)
  157919. jinit_huff_encoder (j_compress_ptr cinfo)
  157920. {
  157921. huff_entropy_ptr entropy;
  157922. int i;
  157923. entropy = (huff_entropy_ptr)
  157924. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157925. SIZEOF(huff_entropy_encoder));
  157926. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  157927. entropy->pub.start_pass = start_pass_huff;
  157928. /* Mark tables unallocated */
  157929. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  157930. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  157931. #ifdef ENTROPY_OPT_SUPPORTED
  157932. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  157933. #endif
  157934. }
  157935. }
  157936. /********* End of inlined file: jchuff.c *********/
  157937. #undef emit_byte
  157938. /********* Start of inlined file: jcinit.c *********/
  157939. #define JPEG_INTERNALS
  157940. /*
  157941. * Master selection of compression modules.
  157942. * This is done once at the start of processing an image. We determine
  157943. * which modules will be used and give them appropriate initialization calls.
  157944. */
  157945. GLOBAL(void)
  157946. jinit_compress_master (j_compress_ptr cinfo)
  157947. {
  157948. /* Initialize master control (includes parameter checking/processing) */
  157949. jinit_c_master_control(cinfo, FALSE /* full compression */);
  157950. /* Preprocessing */
  157951. if (! cinfo->raw_data_in) {
  157952. jinit_color_converter(cinfo);
  157953. jinit_downsampler(cinfo);
  157954. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  157955. }
  157956. /* Forward DCT */
  157957. jinit_forward_dct(cinfo);
  157958. /* Entropy encoding: either Huffman or arithmetic coding. */
  157959. if (cinfo->arith_code) {
  157960. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  157961. } else {
  157962. if (cinfo->progressive_mode) {
  157963. #ifdef C_PROGRESSIVE_SUPPORTED
  157964. jinit_phuff_encoder(cinfo);
  157965. #else
  157966. ERREXIT(cinfo, JERR_NOT_COMPILED);
  157967. #endif
  157968. } else
  157969. jinit_huff_encoder(cinfo);
  157970. }
  157971. /* Need a full-image coefficient buffer in any multi-pass mode. */
  157972. jinit_c_coef_controller(cinfo,
  157973. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  157974. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  157975. jinit_marker_writer(cinfo);
  157976. /* We can now tell the memory manager to allocate virtual arrays. */
  157977. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  157978. /* Write the datastream header (SOI) immediately.
  157979. * Frame and scan headers are postponed till later.
  157980. * This lets application insert special markers after the SOI.
  157981. */
  157982. (*cinfo->marker->write_file_header) (cinfo);
  157983. }
  157984. /********* End of inlined file: jcinit.c *********/
  157985. /********* Start of inlined file: jcmainct.c *********/
  157986. #define JPEG_INTERNALS
  157987. /* Note: currently, there is no operating mode in which a full-image buffer
  157988. * is needed at this step. If there were, that mode could not be used with
  157989. * "raw data" input, since this module is bypassed in that case. However,
  157990. * we've left the code here for possible use in special applications.
  157991. */
  157992. #undef FULL_MAIN_BUFFER_SUPPORTED
  157993. /* Private buffer controller object */
  157994. typedef struct {
  157995. struct jpeg_c_main_controller pub; /* public fields */
  157996. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  157997. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  157998. boolean suspended; /* remember if we suspended output */
  157999. J_BUF_MODE pass_mode; /* current operating mode */
  158000. /* If using just a strip buffer, this points to the entire set of buffers
  158001. * (we allocate one for each component). In the full-image case, this
  158002. * points to the currently accessible strips of the virtual arrays.
  158003. */
  158004. JSAMPARRAY buffer[MAX_COMPONENTS];
  158005. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158006. /* If using full-image storage, this array holds pointers to virtual-array
  158007. * control blocks for each component. Unused if not full-image storage.
  158008. */
  158009. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  158010. #endif
  158011. } my_main_controller;
  158012. typedef my_main_controller * my_main_ptr;
  158013. /* Forward declarations */
  158014. METHODDEF(void) process_data_simple_main
  158015. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  158016. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  158017. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158018. METHODDEF(void) process_data_buffer_main
  158019. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  158020. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  158021. #endif
  158022. /*
  158023. * Initialize for a processing pass.
  158024. */
  158025. METHODDEF(void)
  158026. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  158027. {
  158028. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  158029. /* Do nothing in raw-data mode. */
  158030. if (cinfo->raw_data_in)
  158031. return;
  158032. main_->cur_iMCU_row = 0; /* initialize counters */
  158033. main_->rowgroup_ctr = 0;
  158034. main_->suspended = FALSE;
  158035. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  158036. switch (pass_mode) {
  158037. case JBUF_PASS_THRU:
  158038. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158039. if (main_->whole_image[0] != NULL)
  158040. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158041. #endif
  158042. main_->pub.process_data = process_data_simple_main;
  158043. break;
  158044. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158045. case JBUF_SAVE_SOURCE:
  158046. case JBUF_CRANK_DEST:
  158047. case JBUF_SAVE_AND_PASS:
  158048. if (main_->whole_image[0] == NULL)
  158049. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158050. main_->pub.process_data = process_data_buffer_main;
  158051. break;
  158052. #endif
  158053. default:
  158054. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158055. break;
  158056. }
  158057. }
  158058. /*
  158059. * Process some data.
  158060. * This routine handles the simple pass-through mode,
  158061. * where we have only a strip buffer.
  158062. */
  158063. METHODDEF(void)
  158064. process_data_simple_main (j_compress_ptr cinfo,
  158065. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  158066. JDIMENSION in_rows_avail)
  158067. {
  158068. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  158069. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  158070. /* Read input data if we haven't filled the main buffer yet */
  158071. if (main_->rowgroup_ctr < DCTSIZE)
  158072. (*cinfo->prep->pre_process_data) (cinfo,
  158073. input_buf, in_row_ctr, in_rows_avail,
  158074. main_->buffer, &main_->rowgroup_ctr,
  158075. (JDIMENSION) DCTSIZE);
  158076. /* If we don't have a full iMCU row buffered, return to application for
  158077. * more data. Note that preprocessor will always pad to fill the iMCU row
  158078. * at the bottom of the image.
  158079. */
  158080. if (main_->rowgroup_ctr != DCTSIZE)
  158081. return;
  158082. /* Send the completed row to the compressor */
  158083. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  158084. /* If compressor did not consume the whole row, then we must need to
  158085. * suspend processing and return to the application. In this situation
  158086. * we pretend we didn't yet consume the last input row; otherwise, if
  158087. * it happened to be the last row of the image, the application would
  158088. * think we were done.
  158089. */
  158090. if (! main_->suspended) {
  158091. (*in_row_ctr)--;
  158092. main_->suspended = TRUE;
  158093. }
  158094. return;
  158095. }
  158096. /* We did finish the row. Undo our little suspension hack if a previous
  158097. * call suspended; then mark the main buffer empty.
  158098. */
  158099. if (main_->suspended) {
  158100. (*in_row_ctr)++;
  158101. main_->suspended = FALSE;
  158102. }
  158103. main_->rowgroup_ctr = 0;
  158104. main_->cur_iMCU_row++;
  158105. }
  158106. }
  158107. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158108. /*
  158109. * Process some data.
  158110. * This routine handles all of the modes that use a full-size buffer.
  158111. */
  158112. METHODDEF(void)
  158113. process_data_buffer_main (j_compress_ptr cinfo,
  158114. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  158115. JDIMENSION in_rows_avail)
  158116. {
  158117. my_main_ptr main = (my_main_ptr) cinfo->main;
  158118. int ci;
  158119. jpeg_component_info *compptr;
  158120. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  158121. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  158122. /* Realign the virtual buffers if at the start of an iMCU row. */
  158123. if (main->rowgroup_ctr == 0) {
  158124. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158125. ci++, compptr++) {
  158126. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  158127. ((j_common_ptr) cinfo, main->whole_image[ci],
  158128. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  158129. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  158130. }
  158131. /* In a read pass, pretend we just read some source data. */
  158132. if (! writing) {
  158133. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  158134. main->rowgroup_ctr = DCTSIZE;
  158135. }
  158136. }
  158137. /* If a write pass, read input data until the current iMCU row is full. */
  158138. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  158139. if (writing) {
  158140. (*cinfo->prep->pre_process_data) (cinfo,
  158141. input_buf, in_row_ctr, in_rows_avail,
  158142. main->buffer, &main->rowgroup_ctr,
  158143. (JDIMENSION) DCTSIZE);
  158144. /* Return to application if we need more data to fill the iMCU row. */
  158145. if (main->rowgroup_ctr < DCTSIZE)
  158146. return;
  158147. }
  158148. /* Emit data, unless this is a sink-only pass. */
  158149. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  158150. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  158151. /* If compressor did not consume the whole row, then we must need to
  158152. * suspend processing and return to the application. In this situation
  158153. * we pretend we didn't yet consume the last input row; otherwise, if
  158154. * it happened to be the last row of the image, the application would
  158155. * think we were done.
  158156. */
  158157. if (! main->suspended) {
  158158. (*in_row_ctr)--;
  158159. main->suspended = TRUE;
  158160. }
  158161. return;
  158162. }
  158163. /* We did finish the row. Undo our little suspension hack if a previous
  158164. * call suspended; then mark the main buffer empty.
  158165. */
  158166. if (main->suspended) {
  158167. (*in_row_ctr)++;
  158168. main->suspended = FALSE;
  158169. }
  158170. }
  158171. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  158172. main->rowgroup_ctr = 0;
  158173. main->cur_iMCU_row++;
  158174. }
  158175. }
  158176. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  158177. /*
  158178. * Initialize main buffer controller.
  158179. */
  158180. GLOBAL(void)
  158181. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  158182. {
  158183. my_main_ptr main_;
  158184. int ci;
  158185. jpeg_component_info *compptr;
  158186. main_ = (my_main_ptr)
  158187. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158188. SIZEOF(my_main_controller));
  158189. cinfo->main = (struct jpeg_c_main_controller *) main_;
  158190. main_->pub.start_pass = start_pass_main;
  158191. /* We don't need to create a buffer in raw-data mode. */
  158192. if (cinfo->raw_data_in)
  158193. return;
  158194. /* Create the buffer. It holds downsampled data, so each component
  158195. * may be of a different size.
  158196. */
  158197. if (need_full_buffer) {
  158198. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158199. /* Allocate a full-image virtual array for each component */
  158200. /* Note we pad the bottom to a multiple of the iMCU height */
  158201. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158202. ci++, compptr++) {
  158203. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  158204. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  158205. compptr->width_in_blocks * DCTSIZE,
  158206. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  158207. (long) compptr->v_samp_factor) * DCTSIZE,
  158208. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  158209. }
  158210. #else
  158211. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158212. #endif
  158213. } else {
  158214. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158215. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  158216. #endif
  158217. /* Allocate a strip buffer for each component */
  158218. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158219. ci++, compptr++) {
  158220. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  158221. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158222. compptr->width_in_blocks * DCTSIZE,
  158223. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  158224. }
  158225. }
  158226. }
  158227. /********* End of inlined file: jcmainct.c *********/
  158228. /********* Start of inlined file: jcmarker.c *********/
  158229. #define JPEG_INTERNALS
  158230. /* Private state */
  158231. typedef struct {
  158232. struct jpeg_marker_writer pub; /* public fields */
  158233. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  158234. } my_marker_writer;
  158235. typedef my_marker_writer * my_marker_ptr;
  158236. /*
  158237. * Basic output routines.
  158238. *
  158239. * Note that we do not support suspension while writing a marker.
  158240. * Therefore, an application using suspension must ensure that there is
  158241. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  158242. * calling jpeg_start_compress, and enough space to write the trailing EOI
  158243. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  158244. * modes are not supported at all with suspension, so those two are the only
  158245. * points where markers will be written.
  158246. */
  158247. LOCAL(void)
  158248. emit_byte (j_compress_ptr cinfo, int val)
  158249. /* Emit a byte */
  158250. {
  158251. struct jpeg_destination_mgr * dest = cinfo->dest;
  158252. *(dest->next_output_byte)++ = (JOCTET) val;
  158253. if (--dest->free_in_buffer == 0) {
  158254. if (! (*dest->empty_output_buffer) (cinfo))
  158255. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  158256. }
  158257. }
  158258. LOCAL(void)
  158259. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  158260. /* Emit a marker code */
  158261. {
  158262. emit_byte(cinfo, 0xFF);
  158263. emit_byte(cinfo, (int) mark);
  158264. }
  158265. LOCAL(void)
  158266. emit_2bytes (j_compress_ptr cinfo, int value)
  158267. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  158268. {
  158269. emit_byte(cinfo, (value >> 8) & 0xFF);
  158270. emit_byte(cinfo, value & 0xFF);
  158271. }
  158272. /*
  158273. * Routines to write specific marker types.
  158274. */
  158275. LOCAL(int)
  158276. emit_dqt (j_compress_ptr cinfo, int index)
  158277. /* Emit a DQT marker */
  158278. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  158279. {
  158280. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  158281. int prec;
  158282. int i;
  158283. if (qtbl == NULL)
  158284. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  158285. prec = 0;
  158286. for (i = 0; i < DCTSIZE2; i++) {
  158287. if (qtbl->quantval[i] > 255)
  158288. prec = 1;
  158289. }
  158290. if (! qtbl->sent_table) {
  158291. emit_marker(cinfo, M_DQT);
  158292. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  158293. emit_byte(cinfo, index + (prec<<4));
  158294. for (i = 0; i < DCTSIZE2; i++) {
  158295. /* The table entries must be emitted in zigzag order. */
  158296. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  158297. if (prec)
  158298. emit_byte(cinfo, (int) (qval >> 8));
  158299. emit_byte(cinfo, (int) (qval & 0xFF));
  158300. }
  158301. qtbl->sent_table = TRUE;
  158302. }
  158303. return prec;
  158304. }
  158305. LOCAL(void)
  158306. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  158307. /* Emit a DHT marker */
  158308. {
  158309. JHUFF_TBL * htbl;
  158310. int length, i;
  158311. if (is_ac) {
  158312. htbl = cinfo->ac_huff_tbl_ptrs[index];
  158313. index += 0x10; /* output index has AC bit set */
  158314. } else {
  158315. htbl = cinfo->dc_huff_tbl_ptrs[index];
  158316. }
  158317. if (htbl == NULL)
  158318. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  158319. if (! htbl->sent_table) {
  158320. emit_marker(cinfo, M_DHT);
  158321. length = 0;
  158322. for (i = 1; i <= 16; i++)
  158323. length += htbl->bits[i];
  158324. emit_2bytes(cinfo, length + 2 + 1 + 16);
  158325. emit_byte(cinfo, index);
  158326. for (i = 1; i <= 16; i++)
  158327. emit_byte(cinfo, htbl->bits[i]);
  158328. for (i = 0; i < length; i++)
  158329. emit_byte(cinfo, htbl->huffval[i]);
  158330. htbl->sent_table = TRUE;
  158331. }
  158332. }
  158333. LOCAL(void)
  158334. emit_dac (j_compress_ptr cinfo)
  158335. /* Emit a DAC marker */
  158336. /* Since the useful info is so small, we want to emit all the tables in */
  158337. /* one DAC marker. Therefore this routine does its own scan of the table. */
  158338. {
  158339. #ifdef C_ARITH_CODING_SUPPORTED
  158340. char dc_in_use[NUM_ARITH_TBLS];
  158341. char ac_in_use[NUM_ARITH_TBLS];
  158342. int length, i;
  158343. jpeg_component_info *compptr;
  158344. for (i = 0; i < NUM_ARITH_TBLS; i++)
  158345. dc_in_use[i] = ac_in_use[i] = 0;
  158346. for (i = 0; i < cinfo->comps_in_scan; i++) {
  158347. compptr = cinfo->cur_comp_info[i];
  158348. dc_in_use[compptr->dc_tbl_no] = 1;
  158349. ac_in_use[compptr->ac_tbl_no] = 1;
  158350. }
  158351. length = 0;
  158352. for (i = 0; i < NUM_ARITH_TBLS; i++)
  158353. length += dc_in_use[i] + ac_in_use[i];
  158354. emit_marker(cinfo, M_DAC);
  158355. emit_2bytes(cinfo, length*2 + 2);
  158356. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  158357. if (dc_in_use[i]) {
  158358. emit_byte(cinfo, i);
  158359. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  158360. }
  158361. if (ac_in_use[i]) {
  158362. emit_byte(cinfo, i + 0x10);
  158363. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  158364. }
  158365. }
  158366. #endif /* C_ARITH_CODING_SUPPORTED */
  158367. }
  158368. LOCAL(void)
  158369. emit_dri (j_compress_ptr cinfo)
  158370. /* Emit a DRI marker */
  158371. {
  158372. emit_marker(cinfo, M_DRI);
  158373. emit_2bytes(cinfo, 4); /* fixed length */
  158374. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  158375. }
  158376. LOCAL(void)
  158377. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  158378. /* Emit a SOF marker */
  158379. {
  158380. int ci;
  158381. jpeg_component_info *compptr;
  158382. emit_marker(cinfo, code);
  158383. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  158384. /* Make sure image isn't bigger than SOF field can handle */
  158385. if ((long) cinfo->image_height > 65535L ||
  158386. (long) cinfo->image_width > 65535L)
  158387. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  158388. emit_byte(cinfo, cinfo->data_precision);
  158389. emit_2bytes(cinfo, (int) cinfo->image_height);
  158390. emit_2bytes(cinfo, (int) cinfo->image_width);
  158391. emit_byte(cinfo, cinfo->num_components);
  158392. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158393. ci++, compptr++) {
  158394. emit_byte(cinfo, compptr->component_id);
  158395. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  158396. emit_byte(cinfo, compptr->quant_tbl_no);
  158397. }
  158398. }
  158399. LOCAL(void)
  158400. emit_sos (j_compress_ptr cinfo)
  158401. /* Emit a SOS marker */
  158402. {
  158403. int i, td, ta;
  158404. jpeg_component_info *compptr;
  158405. emit_marker(cinfo, M_SOS);
  158406. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  158407. emit_byte(cinfo, cinfo->comps_in_scan);
  158408. for (i = 0; i < cinfo->comps_in_scan; i++) {
  158409. compptr = cinfo->cur_comp_info[i];
  158410. emit_byte(cinfo, compptr->component_id);
  158411. td = compptr->dc_tbl_no;
  158412. ta = compptr->ac_tbl_no;
  158413. if (cinfo->progressive_mode) {
  158414. /* Progressive mode: only DC or only AC tables are used in one scan;
  158415. * furthermore, Huffman coding of DC refinement uses no table at all.
  158416. * We emit 0 for unused field(s); this is recommended by the P&M text
  158417. * but does not seem to be specified in the standard.
  158418. */
  158419. if (cinfo->Ss == 0) {
  158420. ta = 0; /* DC scan */
  158421. if (cinfo->Ah != 0 && !cinfo->arith_code)
  158422. td = 0; /* no DC table either */
  158423. } else {
  158424. td = 0; /* AC scan */
  158425. }
  158426. }
  158427. emit_byte(cinfo, (td << 4) + ta);
  158428. }
  158429. emit_byte(cinfo, cinfo->Ss);
  158430. emit_byte(cinfo, cinfo->Se);
  158431. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  158432. }
  158433. LOCAL(void)
  158434. emit_jfif_app0 (j_compress_ptr cinfo)
  158435. /* Emit a JFIF-compliant APP0 marker */
  158436. {
  158437. /*
  158438. * Length of APP0 block (2 bytes)
  158439. * Block ID (4 bytes - ASCII "JFIF")
  158440. * Zero byte (1 byte to terminate the ID string)
  158441. * Version Major, Minor (2 bytes - major first)
  158442. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  158443. * Xdpu (2 bytes - dots per unit horizontal)
  158444. * Ydpu (2 bytes - dots per unit vertical)
  158445. * Thumbnail X size (1 byte)
  158446. * Thumbnail Y size (1 byte)
  158447. */
  158448. emit_marker(cinfo, M_APP0);
  158449. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  158450. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  158451. emit_byte(cinfo, 0x46);
  158452. emit_byte(cinfo, 0x49);
  158453. emit_byte(cinfo, 0x46);
  158454. emit_byte(cinfo, 0);
  158455. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  158456. emit_byte(cinfo, cinfo->JFIF_minor_version);
  158457. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  158458. emit_2bytes(cinfo, (int) cinfo->X_density);
  158459. emit_2bytes(cinfo, (int) cinfo->Y_density);
  158460. emit_byte(cinfo, 0); /* No thumbnail image */
  158461. emit_byte(cinfo, 0);
  158462. }
  158463. LOCAL(void)
  158464. emit_adobe_app14 (j_compress_ptr cinfo)
  158465. /* Emit an Adobe APP14 marker */
  158466. {
  158467. /*
  158468. * Length of APP14 block (2 bytes)
  158469. * Block ID (5 bytes - ASCII "Adobe")
  158470. * Version Number (2 bytes - currently 100)
  158471. * Flags0 (2 bytes - currently 0)
  158472. * Flags1 (2 bytes - currently 0)
  158473. * Color transform (1 byte)
  158474. *
  158475. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  158476. * now in circulation seem to use Version = 100, so that's what we write.
  158477. *
  158478. * We write the color transform byte as 1 if the JPEG color space is
  158479. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  158480. * whether the encoder performed a transformation, which is pretty useless.
  158481. */
  158482. emit_marker(cinfo, M_APP14);
  158483. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  158484. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  158485. emit_byte(cinfo, 0x64);
  158486. emit_byte(cinfo, 0x6F);
  158487. emit_byte(cinfo, 0x62);
  158488. emit_byte(cinfo, 0x65);
  158489. emit_2bytes(cinfo, 100); /* Version */
  158490. emit_2bytes(cinfo, 0); /* Flags0 */
  158491. emit_2bytes(cinfo, 0); /* Flags1 */
  158492. switch (cinfo->jpeg_color_space) {
  158493. case JCS_YCbCr:
  158494. emit_byte(cinfo, 1); /* Color transform = 1 */
  158495. break;
  158496. case JCS_YCCK:
  158497. emit_byte(cinfo, 2); /* Color transform = 2 */
  158498. break;
  158499. default:
  158500. emit_byte(cinfo, 0); /* Color transform = 0 */
  158501. break;
  158502. }
  158503. }
  158504. /*
  158505. * These routines allow writing an arbitrary marker with parameters.
  158506. * The only intended use is to emit COM or APPn markers after calling
  158507. * write_file_header and before calling write_frame_header.
  158508. * Other uses are not guaranteed to produce desirable results.
  158509. * Counting the parameter bytes properly is the caller's responsibility.
  158510. */
  158511. METHODDEF(void)
  158512. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  158513. /* Emit an arbitrary marker header */
  158514. {
  158515. if (datalen > (unsigned int) 65533) /* safety check */
  158516. ERREXIT(cinfo, JERR_BAD_LENGTH);
  158517. emit_marker(cinfo, (JPEG_MARKER) marker);
  158518. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  158519. }
  158520. METHODDEF(void)
  158521. write_marker_byte (j_compress_ptr cinfo, int val)
  158522. /* Emit one byte of marker parameters following write_marker_header */
  158523. {
  158524. emit_byte(cinfo, val);
  158525. }
  158526. /*
  158527. * Write datastream header.
  158528. * This consists of an SOI and optional APPn markers.
  158529. * We recommend use of the JFIF marker, but not the Adobe marker,
  158530. * when using YCbCr or grayscale data. The JFIF marker should NOT
  158531. * be used for any other JPEG colorspace. The Adobe marker is helpful
  158532. * to distinguish RGB, CMYK, and YCCK colorspaces.
  158533. * Note that an application can write additional header markers after
  158534. * jpeg_start_compress returns.
  158535. */
  158536. METHODDEF(void)
  158537. write_file_header (j_compress_ptr cinfo)
  158538. {
  158539. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  158540. emit_marker(cinfo, M_SOI); /* first the SOI */
  158541. /* SOI is defined to reset restart interval to 0 */
  158542. marker->last_restart_interval = 0;
  158543. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  158544. emit_jfif_app0(cinfo);
  158545. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  158546. emit_adobe_app14(cinfo);
  158547. }
  158548. /*
  158549. * Write frame header.
  158550. * This consists of DQT and SOFn markers.
  158551. * Note that we do not emit the SOF until we have emitted the DQT(s).
  158552. * This avoids compatibility problems with incorrect implementations that
  158553. * try to error-check the quant table numbers as soon as they see the SOF.
  158554. */
  158555. METHODDEF(void)
  158556. write_frame_header (j_compress_ptr cinfo)
  158557. {
  158558. int ci, prec;
  158559. boolean is_baseline;
  158560. jpeg_component_info *compptr;
  158561. /* Emit DQT for each quantization table.
  158562. * Note that emit_dqt() suppresses any duplicate tables.
  158563. */
  158564. prec = 0;
  158565. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158566. ci++, compptr++) {
  158567. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  158568. }
  158569. /* now prec is nonzero iff there are any 16-bit quant tables. */
  158570. /* Check for a non-baseline specification.
  158571. * Note we assume that Huffman table numbers won't be changed later.
  158572. */
  158573. if (cinfo->arith_code || cinfo->progressive_mode ||
  158574. cinfo->data_precision != 8) {
  158575. is_baseline = FALSE;
  158576. } else {
  158577. is_baseline = TRUE;
  158578. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158579. ci++, compptr++) {
  158580. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  158581. is_baseline = FALSE;
  158582. }
  158583. if (prec && is_baseline) {
  158584. is_baseline = FALSE;
  158585. /* If it's baseline except for quantizer size, warn the user */
  158586. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  158587. }
  158588. }
  158589. /* Emit the proper SOF marker */
  158590. if (cinfo->arith_code) {
  158591. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  158592. } else {
  158593. if (cinfo->progressive_mode)
  158594. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  158595. else if (is_baseline)
  158596. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  158597. else
  158598. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  158599. }
  158600. }
  158601. /*
  158602. * Write scan header.
  158603. * This consists of DHT or DAC markers, optional DRI, and SOS.
  158604. * Compressed data will be written following the SOS.
  158605. */
  158606. METHODDEF(void)
  158607. write_scan_header (j_compress_ptr cinfo)
  158608. {
  158609. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  158610. int i;
  158611. jpeg_component_info *compptr;
  158612. if (cinfo->arith_code) {
  158613. /* Emit arith conditioning info. We may have some duplication
  158614. * if the file has multiple scans, but it's so small it's hardly
  158615. * worth worrying about.
  158616. */
  158617. emit_dac(cinfo);
  158618. } else {
  158619. /* Emit Huffman tables.
  158620. * Note that emit_dht() suppresses any duplicate tables.
  158621. */
  158622. for (i = 0; i < cinfo->comps_in_scan; i++) {
  158623. compptr = cinfo->cur_comp_info[i];
  158624. if (cinfo->progressive_mode) {
  158625. /* Progressive mode: only DC or only AC tables are used in one scan */
  158626. if (cinfo->Ss == 0) {
  158627. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  158628. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  158629. } else {
  158630. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  158631. }
  158632. } else {
  158633. /* Sequential mode: need both DC and AC tables */
  158634. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  158635. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  158636. }
  158637. }
  158638. }
  158639. /* Emit DRI if required --- note that DRI value could change for each scan.
  158640. * We avoid wasting space with unnecessary DRIs, however.
  158641. */
  158642. if (cinfo->restart_interval != marker->last_restart_interval) {
  158643. emit_dri(cinfo);
  158644. marker->last_restart_interval = cinfo->restart_interval;
  158645. }
  158646. emit_sos(cinfo);
  158647. }
  158648. /*
  158649. * Write datastream trailer.
  158650. */
  158651. METHODDEF(void)
  158652. write_file_trailer (j_compress_ptr cinfo)
  158653. {
  158654. emit_marker(cinfo, M_EOI);
  158655. }
  158656. /*
  158657. * Write an abbreviated table-specification datastream.
  158658. * This consists of SOI, DQT and DHT tables, and EOI.
  158659. * Any table that is defined and not marked sent_table = TRUE will be
  158660. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  158661. */
  158662. METHODDEF(void)
  158663. write_tables_only (j_compress_ptr cinfo)
  158664. {
  158665. int i;
  158666. emit_marker(cinfo, M_SOI);
  158667. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  158668. if (cinfo->quant_tbl_ptrs[i] != NULL)
  158669. (void) emit_dqt(cinfo, i);
  158670. }
  158671. if (! cinfo->arith_code) {
  158672. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  158673. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  158674. emit_dht(cinfo, i, FALSE);
  158675. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  158676. emit_dht(cinfo, i, TRUE);
  158677. }
  158678. }
  158679. emit_marker(cinfo, M_EOI);
  158680. }
  158681. /*
  158682. * Initialize the marker writer module.
  158683. */
  158684. GLOBAL(void)
  158685. jinit_marker_writer (j_compress_ptr cinfo)
  158686. {
  158687. my_marker_ptr marker;
  158688. /* Create the subobject */
  158689. marker = (my_marker_ptr)
  158690. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158691. SIZEOF(my_marker_writer));
  158692. cinfo->marker = (struct jpeg_marker_writer *) marker;
  158693. /* Initialize method pointers */
  158694. marker->pub.write_file_header = write_file_header;
  158695. marker->pub.write_frame_header = write_frame_header;
  158696. marker->pub.write_scan_header = write_scan_header;
  158697. marker->pub.write_file_trailer = write_file_trailer;
  158698. marker->pub.write_tables_only = write_tables_only;
  158699. marker->pub.write_marker_header = write_marker_header;
  158700. marker->pub.write_marker_byte = write_marker_byte;
  158701. /* Initialize private state */
  158702. marker->last_restart_interval = 0;
  158703. }
  158704. /********* End of inlined file: jcmarker.c *********/
  158705. /********* Start of inlined file: jcmaster.c *********/
  158706. #define JPEG_INTERNALS
  158707. /* Private state */
  158708. typedef enum {
  158709. main_pass, /* input data, also do first output step */
  158710. huff_opt_pass, /* Huffman code optimization pass */
  158711. output_pass /* data output pass */
  158712. } c_pass_type;
  158713. typedef struct {
  158714. struct jpeg_comp_master pub; /* public fields */
  158715. c_pass_type pass_type; /* the type of the current pass */
  158716. int pass_number; /* # of passes completed */
  158717. int total_passes; /* total # of passes needed */
  158718. int scan_number; /* current index in scan_info[] */
  158719. } my_comp_master;
  158720. typedef my_comp_master * my_master_ptr;
  158721. /*
  158722. * Support routines that do various essential calculations.
  158723. */
  158724. LOCAL(void)
  158725. initial_setup (j_compress_ptr cinfo)
  158726. /* Do computations that are needed before master selection phase */
  158727. {
  158728. int ci;
  158729. jpeg_component_info *compptr;
  158730. long samplesperrow;
  158731. JDIMENSION jd_samplesperrow;
  158732. /* Sanity check on image dimensions */
  158733. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  158734. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  158735. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  158736. /* Make sure image isn't bigger than I can handle */
  158737. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  158738. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  158739. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  158740. /* Width of an input scanline must be representable as JDIMENSION. */
  158741. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  158742. jd_samplesperrow = (JDIMENSION) samplesperrow;
  158743. if ((long) jd_samplesperrow != samplesperrow)
  158744. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  158745. /* For now, precision must match compiled-in value... */
  158746. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  158747. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  158748. /* Check that number of components won't exceed internal array sizes */
  158749. if (cinfo->num_components > MAX_COMPONENTS)
  158750. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  158751. MAX_COMPONENTS);
  158752. /* Compute maximum sampling factors; check factor validity */
  158753. cinfo->max_h_samp_factor = 1;
  158754. cinfo->max_v_samp_factor = 1;
  158755. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158756. ci++, compptr++) {
  158757. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  158758. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  158759. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  158760. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  158761. compptr->h_samp_factor);
  158762. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  158763. compptr->v_samp_factor);
  158764. }
  158765. /* Compute dimensions of components */
  158766. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158767. ci++, compptr++) {
  158768. /* Fill in the correct component_index value; don't rely on application */
  158769. compptr->component_index = ci;
  158770. /* For compression, we never do DCT scaling. */
  158771. compptr->DCT_scaled_size = DCTSIZE;
  158772. /* Size in DCT blocks */
  158773. compptr->width_in_blocks = (JDIMENSION)
  158774. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  158775. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  158776. compptr->height_in_blocks = (JDIMENSION)
  158777. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  158778. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  158779. /* Size in samples */
  158780. compptr->downsampled_width = (JDIMENSION)
  158781. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  158782. (long) cinfo->max_h_samp_factor);
  158783. compptr->downsampled_height = (JDIMENSION)
  158784. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  158785. (long) cinfo->max_v_samp_factor);
  158786. /* Mark component needed (this flag isn't actually used for compression) */
  158787. compptr->component_needed = TRUE;
  158788. }
  158789. /* Compute number of fully interleaved MCU rows (number of times that
  158790. * main controller will call coefficient controller).
  158791. */
  158792. cinfo->total_iMCU_rows = (JDIMENSION)
  158793. jdiv_round_up((long) cinfo->image_height,
  158794. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  158795. }
  158796. #ifdef C_MULTISCAN_FILES_SUPPORTED
  158797. LOCAL(void)
  158798. validate_script (j_compress_ptr cinfo)
  158799. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  158800. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  158801. */
  158802. {
  158803. const jpeg_scan_info * scanptr;
  158804. int scanno, ncomps, ci, coefi, thisi;
  158805. int Ss, Se, Ah, Al;
  158806. boolean component_sent[MAX_COMPONENTS];
  158807. #ifdef C_PROGRESSIVE_SUPPORTED
  158808. int * last_bitpos_ptr;
  158809. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  158810. /* -1 until that coefficient has been seen; then last Al for it */
  158811. #endif
  158812. if (cinfo->num_scans <= 0)
  158813. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  158814. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  158815. * for progressive JPEG, no scan can have this.
  158816. */
  158817. scanptr = cinfo->scan_info;
  158818. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  158819. #ifdef C_PROGRESSIVE_SUPPORTED
  158820. cinfo->progressive_mode = TRUE;
  158821. last_bitpos_ptr = & last_bitpos[0][0];
  158822. for (ci = 0; ci < cinfo->num_components; ci++)
  158823. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  158824. *last_bitpos_ptr++ = -1;
  158825. #else
  158826. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158827. #endif
  158828. } else {
  158829. cinfo->progressive_mode = FALSE;
  158830. for (ci = 0; ci < cinfo->num_components; ci++)
  158831. component_sent[ci] = FALSE;
  158832. }
  158833. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  158834. /* Validate component indexes */
  158835. ncomps = scanptr->comps_in_scan;
  158836. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  158837. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  158838. for (ci = 0; ci < ncomps; ci++) {
  158839. thisi = scanptr->component_index[ci];
  158840. if (thisi < 0 || thisi >= cinfo->num_components)
  158841. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  158842. /* Components must appear in SOF order within each scan */
  158843. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  158844. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  158845. }
  158846. /* Validate progression parameters */
  158847. Ss = scanptr->Ss;
  158848. Se = scanptr->Se;
  158849. Ah = scanptr->Ah;
  158850. Al = scanptr->Al;
  158851. if (cinfo->progressive_mode) {
  158852. #ifdef C_PROGRESSIVE_SUPPORTED
  158853. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  158854. * seems wrong: the upper bound ought to depend on data precision.
  158855. * Perhaps they really meant 0..N+1 for N-bit precision.
  158856. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  158857. * out-of-range reconstructed DC values during the first DC scan,
  158858. * which might cause problems for some decoders.
  158859. */
  158860. #if BITS_IN_JSAMPLE == 8
  158861. #define MAX_AH_AL 10
  158862. #else
  158863. #define MAX_AH_AL 13
  158864. #endif
  158865. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  158866. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  158867. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158868. if (Ss == 0) {
  158869. if (Se != 0) /* DC and AC together not OK */
  158870. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158871. } else {
  158872. if (ncomps != 1) /* AC scans must be for only one component */
  158873. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158874. }
  158875. for (ci = 0; ci < ncomps; ci++) {
  158876. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  158877. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  158878. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158879. for (coefi = Ss; coefi <= Se; coefi++) {
  158880. if (last_bitpos_ptr[coefi] < 0) {
  158881. /* first scan of this coefficient */
  158882. if (Ah != 0)
  158883. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158884. } else {
  158885. /* not first scan */
  158886. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  158887. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158888. }
  158889. last_bitpos_ptr[coefi] = Al;
  158890. }
  158891. }
  158892. #endif
  158893. } else {
  158894. /* For sequential JPEG, all progression parameters must be these: */
  158895. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  158896. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158897. /* Make sure components are not sent twice */
  158898. for (ci = 0; ci < ncomps; ci++) {
  158899. thisi = scanptr->component_index[ci];
  158900. if (component_sent[thisi])
  158901. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  158902. component_sent[thisi] = TRUE;
  158903. }
  158904. }
  158905. }
  158906. /* Now verify that everything got sent. */
  158907. if (cinfo->progressive_mode) {
  158908. #ifdef C_PROGRESSIVE_SUPPORTED
  158909. /* For progressive mode, we only check that at least some DC data
  158910. * got sent for each component; the spec does not require that all bits
  158911. * of all coefficients be transmitted. Would it be wiser to enforce
  158912. * transmission of all coefficient bits??
  158913. */
  158914. for (ci = 0; ci < cinfo->num_components; ci++) {
  158915. if (last_bitpos[ci][0] < 0)
  158916. ERREXIT(cinfo, JERR_MISSING_DATA);
  158917. }
  158918. #endif
  158919. } else {
  158920. for (ci = 0; ci < cinfo->num_components; ci++) {
  158921. if (! component_sent[ci])
  158922. ERREXIT(cinfo, JERR_MISSING_DATA);
  158923. }
  158924. }
  158925. }
  158926. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  158927. LOCAL(void)
  158928. select_scan_parameters (j_compress_ptr cinfo)
  158929. /* Set up the scan parameters for the current scan */
  158930. {
  158931. int ci;
  158932. #ifdef C_MULTISCAN_FILES_SUPPORTED
  158933. if (cinfo->scan_info != NULL) {
  158934. /* Prepare for current scan --- the script is already validated */
  158935. my_master_ptr master = (my_master_ptr) cinfo->master;
  158936. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  158937. cinfo->comps_in_scan = scanptr->comps_in_scan;
  158938. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  158939. cinfo->cur_comp_info[ci] =
  158940. &cinfo->comp_info[scanptr->component_index[ci]];
  158941. }
  158942. cinfo->Ss = scanptr->Ss;
  158943. cinfo->Se = scanptr->Se;
  158944. cinfo->Ah = scanptr->Ah;
  158945. cinfo->Al = scanptr->Al;
  158946. }
  158947. else
  158948. #endif
  158949. {
  158950. /* Prepare for single sequential-JPEG scan containing all components */
  158951. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  158952. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  158953. MAX_COMPS_IN_SCAN);
  158954. cinfo->comps_in_scan = cinfo->num_components;
  158955. for (ci = 0; ci < cinfo->num_components; ci++) {
  158956. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  158957. }
  158958. cinfo->Ss = 0;
  158959. cinfo->Se = DCTSIZE2-1;
  158960. cinfo->Ah = 0;
  158961. cinfo->Al = 0;
  158962. }
  158963. }
  158964. LOCAL(void)
  158965. per_scan_setup (j_compress_ptr cinfo)
  158966. /* Do computations that are needed before processing a JPEG scan */
  158967. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  158968. {
  158969. int ci, mcublks, tmp;
  158970. jpeg_component_info *compptr;
  158971. if (cinfo->comps_in_scan == 1) {
  158972. /* Noninterleaved (single-component) scan */
  158973. compptr = cinfo->cur_comp_info[0];
  158974. /* Overall image size in MCUs */
  158975. cinfo->MCUs_per_row = compptr->width_in_blocks;
  158976. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  158977. /* For noninterleaved scan, always one block per MCU */
  158978. compptr->MCU_width = 1;
  158979. compptr->MCU_height = 1;
  158980. compptr->MCU_blocks = 1;
  158981. compptr->MCU_sample_width = DCTSIZE;
  158982. compptr->last_col_width = 1;
  158983. /* For noninterleaved scans, it is convenient to define last_row_height
  158984. * as the number of block rows present in the last iMCU row.
  158985. */
  158986. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  158987. if (tmp == 0) tmp = compptr->v_samp_factor;
  158988. compptr->last_row_height = tmp;
  158989. /* Prepare array describing MCU composition */
  158990. cinfo->blocks_in_MCU = 1;
  158991. cinfo->MCU_membership[0] = 0;
  158992. } else {
  158993. /* Interleaved (multi-component) scan */
  158994. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  158995. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  158996. MAX_COMPS_IN_SCAN);
  158997. /* Overall image size in MCUs */
  158998. cinfo->MCUs_per_row = (JDIMENSION)
  158999. jdiv_round_up((long) cinfo->image_width,
  159000. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  159001. cinfo->MCU_rows_in_scan = (JDIMENSION)
  159002. jdiv_round_up((long) cinfo->image_height,
  159003. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  159004. cinfo->blocks_in_MCU = 0;
  159005. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159006. compptr = cinfo->cur_comp_info[ci];
  159007. /* Sampling factors give # of blocks of component in each MCU */
  159008. compptr->MCU_width = compptr->h_samp_factor;
  159009. compptr->MCU_height = compptr->v_samp_factor;
  159010. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  159011. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  159012. /* Figure number of non-dummy blocks in last MCU column & row */
  159013. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  159014. if (tmp == 0) tmp = compptr->MCU_width;
  159015. compptr->last_col_width = tmp;
  159016. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  159017. if (tmp == 0) tmp = compptr->MCU_height;
  159018. compptr->last_row_height = tmp;
  159019. /* Prepare array describing MCU composition */
  159020. mcublks = compptr->MCU_blocks;
  159021. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  159022. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  159023. while (mcublks-- > 0) {
  159024. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  159025. }
  159026. }
  159027. }
  159028. /* Convert restart specified in rows to actual MCU count. */
  159029. /* Note that count must fit in 16 bits, so we provide limiting. */
  159030. if (cinfo->restart_in_rows > 0) {
  159031. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  159032. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  159033. }
  159034. }
  159035. /*
  159036. * Per-pass setup.
  159037. * This is called at the beginning of each pass. We determine which modules
  159038. * will be active during this pass and give them appropriate start_pass calls.
  159039. * We also set is_last_pass to indicate whether any more passes will be
  159040. * required.
  159041. */
  159042. METHODDEF(void)
  159043. prepare_for_pass (j_compress_ptr cinfo)
  159044. {
  159045. my_master_ptr master = (my_master_ptr) cinfo->master;
  159046. switch (master->pass_type) {
  159047. case main_pass:
  159048. /* Initial pass: will collect input data, and do either Huffman
  159049. * optimization or data output for the first scan.
  159050. */
  159051. select_scan_parameters(cinfo);
  159052. per_scan_setup(cinfo);
  159053. if (! cinfo->raw_data_in) {
  159054. (*cinfo->cconvert->start_pass) (cinfo);
  159055. (*cinfo->downsample->start_pass) (cinfo);
  159056. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  159057. }
  159058. (*cinfo->fdct->start_pass) (cinfo);
  159059. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  159060. (*cinfo->coef->start_pass) (cinfo,
  159061. (master->total_passes > 1 ?
  159062. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  159063. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  159064. if (cinfo->optimize_coding) {
  159065. /* No immediate data output; postpone writing frame/scan headers */
  159066. master->pub.call_pass_startup = FALSE;
  159067. } else {
  159068. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  159069. master->pub.call_pass_startup = TRUE;
  159070. }
  159071. break;
  159072. #ifdef ENTROPY_OPT_SUPPORTED
  159073. case huff_opt_pass:
  159074. /* Do Huffman optimization for a scan after the first one. */
  159075. select_scan_parameters(cinfo);
  159076. per_scan_setup(cinfo);
  159077. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  159078. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  159079. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  159080. master->pub.call_pass_startup = FALSE;
  159081. break;
  159082. }
  159083. /* Special case: Huffman DC refinement scans need no Huffman table
  159084. * and therefore we can skip the optimization pass for them.
  159085. */
  159086. master->pass_type = output_pass;
  159087. master->pass_number++;
  159088. /*FALLTHROUGH*/
  159089. #endif
  159090. case output_pass:
  159091. /* Do a data-output pass. */
  159092. /* We need not repeat per-scan setup if prior optimization pass did it. */
  159093. if (! cinfo->optimize_coding) {
  159094. select_scan_parameters(cinfo);
  159095. per_scan_setup(cinfo);
  159096. }
  159097. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  159098. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  159099. /* We emit frame/scan headers now */
  159100. if (master->scan_number == 0)
  159101. (*cinfo->marker->write_frame_header) (cinfo);
  159102. (*cinfo->marker->write_scan_header) (cinfo);
  159103. master->pub.call_pass_startup = FALSE;
  159104. break;
  159105. default:
  159106. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159107. }
  159108. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  159109. /* Set up progress monitor's pass info if present */
  159110. if (cinfo->progress != NULL) {
  159111. cinfo->progress->completed_passes = master->pass_number;
  159112. cinfo->progress->total_passes = master->total_passes;
  159113. }
  159114. }
  159115. /*
  159116. * Special start-of-pass hook.
  159117. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  159118. * In single-pass processing, we need this hook because we don't want to
  159119. * write frame/scan headers during jpeg_start_compress; we want to let the
  159120. * application write COM markers etc. between jpeg_start_compress and the
  159121. * jpeg_write_scanlines loop.
  159122. * In multi-pass processing, this routine is not used.
  159123. */
  159124. METHODDEF(void)
  159125. pass_startup (j_compress_ptr cinfo)
  159126. {
  159127. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  159128. (*cinfo->marker->write_frame_header) (cinfo);
  159129. (*cinfo->marker->write_scan_header) (cinfo);
  159130. }
  159131. /*
  159132. * Finish up at end of pass.
  159133. */
  159134. METHODDEF(void)
  159135. finish_pass_master (j_compress_ptr cinfo)
  159136. {
  159137. my_master_ptr master = (my_master_ptr) cinfo->master;
  159138. /* The entropy coder always needs an end-of-pass call,
  159139. * either to analyze statistics or to flush its output buffer.
  159140. */
  159141. (*cinfo->entropy->finish_pass) (cinfo);
  159142. /* Update state for next pass */
  159143. switch (master->pass_type) {
  159144. case main_pass:
  159145. /* next pass is either output of scan 0 (after optimization)
  159146. * or output of scan 1 (if no optimization).
  159147. */
  159148. master->pass_type = output_pass;
  159149. if (! cinfo->optimize_coding)
  159150. master->scan_number++;
  159151. break;
  159152. case huff_opt_pass:
  159153. /* next pass is always output of current scan */
  159154. master->pass_type = output_pass;
  159155. break;
  159156. case output_pass:
  159157. /* next pass is either optimization or output of next scan */
  159158. if (cinfo->optimize_coding)
  159159. master->pass_type = huff_opt_pass;
  159160. master->scan_number++;
  159161. break;
  159162. }
  159163. master->pass_number++;
  159164. }
  159165. /*
  159166. * Initialize master compression control.
  159167. */
  159168. GLOBAL(void)
  159169. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  159170. {
  159171. my_master_ptr master;
  159172. master = (my_master_ptr)
  159173. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159174. SIZEOF(my_comp_master));
  159175. cinfo->master = (struct jpeg_comp_master *) master;
  159176. master->pub.prepare_for_pass = prepare_for_pass;
  159177. master->pub.pass_startup = pass_startup;
  159178. master->pub.finish_pass = finish_pass_master;
  159179. master->pub.is_last_pass = FALSE;
  159180. /* Validate parameters, determine derived values */
  159181. initial_setup(cinfo);
  159182. if (cinfo->scan_info != NULL) {
  159183. #ifdef C_MULTISCAN_FILES_SUPPORTED
  159184. validate_script(cinfo);
  159185. #else
  159186. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159187. #endif
  159188. } else {
  159189. cinfo->progressive_mode = FALSE;
  159190. cinfo->num_scans = 1;
  159191. }
  159192. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  159193. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  159194. /* Initialize my private state */
  159195. if (transcode_only) {
  159196. /* no main pass in transcoding */
  159197. if (cinfo->optimize_coding)
  159198. master->pass_type = huff_opt_pass;
  159199. else
  159200. master->pass_type = output_pass;
  159201. } else {
  159202. /* for normal compression, first pass is always this type: */
  159203. master->pass_type = main_pass;
  159204. }
  159205. master->scan_number = 0;
  159206. master->pass_number = 0;
  159207. if (cinfo->optimize_coding)
  159208. master->total_passes = cinfo->num_scans * 2;
  159209. else
  159210. master->total_passes = cinfo->num_scans;
  159211. }
  159212. /********* End of inlined file: jcmaster.c *********/
  159213. /********* Start of inlined file: jcomapi.c *********/
  159214. #define JPEG_INTERNALS
  159215. /*
  159216. * Abort processing of a JPEG compression or decompression operation,
  159217. * but don't destroy the object itself.
  159218. *
  159219. * For this, we merely clean up all the nonpermanent memory pools.
  159220. * Note that temp files (virtual arrays) are not allowed to belong to
  159221. * the permanent pool, so we will be able to close all temp files here.
  159222. * Closing a data source or destination, if necessary, is the application's
  159223. * responsibility.
  159224. */
  159225. GLOBAL(void)
  159226. jpeg_abort (j_common_ptr cinfo)
  159227. {
  159228. int pool;
  159229. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  159230. if (cinfo->mem == NULL)
  159231. return;
  159232. /* Releasing pools in reverse order might help avoid fragmentation
  159233. * with some (brain-damaged) malloc libraries.
  159234. */
  159235. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  159236. (*cinfo->mem->free_pool) (cinfo, pool);
  159237. }
  159238. /* Reset overall state for possible reuse of object */
  159239. if (cinfo->is_decompressor) {
  159240. cinfo->global_state = DSTATE_START;
  159241. /* Try to keep application from accessing now-deleted marker list.
  159242. * A bit kludgy to do it here, but this is the most central place.
  159243. */
  159244. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  159245. } else {
  159246. cinfo->global_state = CSTATE_START;
  159247. }
  159248. }
  159249. /*
  159250. * Destruction of a JPEG object.
  159251. *
  159252. * Everything gets deallocated except the master jpeg_compress_struct itself
  159253. * and the error manager struct. Both of these are supplied by the application
  159254. * and must be freed, if necessary, by the application. (Often they are on
  159255. * the stack and so don't need to be freed anyway.)
  159256. * Closing a data source or destination, if necessary, is the application's
  159257. * responsibility.
  159258. */
  159259. GLOBAL(void)
  159260. jpeg_destroy (j_common_ptr cinfo)
  159261. {
  159262. /* We need only tell the memory manager to release everything. */
  159263. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  159264. if (cinfo->mem != NULL)
  159265. (*cinfo->mem->self_destruct) (cinfo);
  159266. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  159267. cinfo->global_state = 0; /* mark it destroyed */
  159268. }
  159269. /*
  159270. * Convenience routines for allocating quantization and Huffman tables.
  159271. * (Would jutils.c be a more reasonable place to put these?)
  159272. */
  159273. GLOBAL(JQUANT_TBL *)
  159274. jpeg_alloc_quant_table (j_common_ptr cinfo)
  159275. {
  159276. JQUANT_TBL *tbl;
  159277. tbl = (JQUANT_TBL *)
  159278. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  159279. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  159280. return tbl;
  159281. }
  159282. GLOBAL(JHUFF_TBL *)
  159283. jpeg_alloc_huff_table (j_common_ptr cinfo)
  159284. {
  159285. JHUFF_TBL *tbl;
  159286. tbl = (JHUFF_TBL *)
  159287. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  159288. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  159289. return tbl;
  159290. }
  159291. /********* End of inlined file: jcomapi.c *********/
  159292. /********* Start of inlined file: jcparam.c *********/
  159293. #define JPEG_INTERNALS
  159294. /*
  159295. * Quantization table setup routines
  159296. */
  159297. GLOBAL(void)
  159298. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  159299. const unsigned int *basic_table,
  159300. int scale_factor, boolean force_baseline)
  159301. /* Define a quantization table equal to the basic_table times
  159302. * a scale factor (given as a percentage).
  159303. * If force_baseline is TRUE, the computed quantization table entries
  159304. * are limited to 1..255 for JPEG baseline compatibility.
  159305. */
  159306. {
  159307. JQUANT_TBL ** qtblptr;
  159308. int i;
  159309. long temp;
  159310. /* Safety check to ensure start_compress not called yet. */
  159311. if (cinfo->global_state != CSTATE_START)
  159312. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  159313. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  159314. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  159315. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  159316. if (*qtblptr == NULL)
  159317. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  159318. for (i = 0; i < DCTSIZE2; i++) {
  159319. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  159320. /* limit the values to the valid range */
  159321. if (temp <= 0L) temp = 1L;
  159322. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  159323. if (force_baseline && temp > 255L)
  159324. temp = 255L; /* limit to baseline range if requested */
  159325. (*qtblptr)->quantval[i] = (UINT16) temp;
  159326. }
  159327. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  159328. (*qtblptr)->sent_table = FALSE;
  159329. }
  159330. GLOBAL(void)
  159331. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  159332. boolean force_baseline)
  159333. /* Set or change the 'quality' (quantization) setting, using default tables
  159334. * and a straight percentage-scaling quality scale. In most cases it's better
  159335. * to use jpeg_set_quality (below); this entry point is provided for
  159336. * applications that insist on a linear percentage scaling.
  159337. */
  159338. {
  159339. /* These are the sample quantization tables given in JPEG spec section K.1.
  159340. * The spec says that the values given produce "good" quality, and
  159341. * when divided by 2, "very good" quality.
  159342. */
  159343. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  159344. 16, 11, 10, 16, 24, 40, 51, 61,
  159345. 12, 12, 14, 19, 26, 58, 60, 55,
  159346. 14, 13, 16, 24, 40, 57, 69, 56,
  159347. 14, 17, 22, 29, 51, 87, 80, 62,
  159348. 18, 22, 37, 56, 68, 109, 103, 77,
  159349. 24, 35, 55, 64, 81, 104, 113, 92,
  159350. 49, 64, 78, 87, 103, 121, 120, 101,
  159351. 72, 92, 95, 98, 112, 100, 103, 99
  159352. };
  159353. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  159354. 17, 18, 24, 47, 99, 99, 99, 99,
  159355. 18, 21, 26, 66, 99, 99, 99, 99,
  159356. 24, 26, 56, 99, 99, 99, 99, 99,
  159357. 47, 66, 99, 99, 99, 99, 99, 99,
  159358. 99, 99, 99, 99, 99, 99, 99, 99,
  159359. 99, 99, 99, 99, 99, 99, 99, 99,
  159360. 99, 99, 99, 99, 99, 99, 99, 99,
  159361. 99, 99, 99, 99, 99, 99, 99, 99
  159362. };
  159363. /* Set up two quantization tables using the specified scaling */
  159364. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  159365. scale_factor, force_baseline);
  159366. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  159367. scale_factor, force_baseline);
  159368. }
  159369. GLOBAL(int)
  159370. jpeg_quality_scaling (int quality)
  159371. /* Convert a user-specified quality rating to a percentage scaling factor
  159372. * for an underlying quantization table, using our recommended scaling curve.
  159373. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  159374. */
  159375. {
  159376. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  159377. if (quality <= 0) quality = 1;
  159378. if (quality > 100) quality = 100;
  159379. /* The basic table is used as-is (scaling 100) for a quality of 50.
  159380. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  159381. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  159382. * to make all the table entries 1 (hence, minimum quantization loss).
  159383. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  159384. */
  159385. if (quality < 50)
  159386. quality = 5000 / quality;
  159387. else
  159388. quality = 200 - quality*2;
  159389. return quality;
  159390. }
  159391. GLOBAL(void)
  159392. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  159393. /* Set or change the 'quality' (quantization) setting, using default tables.
  159394. * This is the standard quality-adjusting entry point for typical user
  159395. * interfaces; only those who want detailed control over quantization tables
  159396. * would use the preceding three routines directly.
  159397. */
  159398. {
  159399. /* Convert user 0-100 rating to percentage scaling */
  159400. quality = jpeg_quality_scaling(quality);
  159401. /* Set up standard quality tables */
  159402. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  159403. }
  159404. /*
  159405. * Huffman table setup routines
  159406. */
  159407. LOCAL(void)
  159408. add_huff_table (j_compress_ptr cinfo,
  159409. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  159410. /* Define a Huffman table */
  159411. {
  159412. int nsymbols, len;
  159413. if (*htblptr == NULL)
  159414. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  159415. /* Copy the number-of-symbols-of-each-code-length counts */
  159416. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  159417. /* Validate the counts. We do this here mainly so we can copy the right
  159418. * number of symbols from the val[] array, without risking marching off
  159419. * the end of memory. jchuff.c will do a more thorough test later.
  159420. */
  159421. nsymbols = 0;
  159422. for (len = 1; len <= 16; len++)
  159423. nsymbols += bits[len];
  159424. if (nsymbols < 1 || nsymbols > 256)
  159425. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  159426. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  159427. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  159428. (*htblptr)->sent_table = FALSE;
  159429. }
  159430. LOCAL(void)
  159431. std_huff_tables (j_compress_ptr cinfo)
  159432. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  159433. /* IMPORTANT: these are only valid for 8-bit data precision! */
  159434. {
  159435. static const UINT8 bits_dc_luminance[17] =
  159436. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  159437. static const UINT8 val_dc_luminance[] =
  159438. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  159439. static const UINT8 bits_dc_chrominance[17] =
  159440. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  159441. static const UINT8 val_dc_chrominance[] =
  159442. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  159443. static const UINT8 bits_ac_luminance[17] =
  159444. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  159445. static const UINT8 val_ac_luminance[] =
  159446. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  159447. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  159448. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  159449. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  159450. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  159451. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  159452. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  159453. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  159454. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  159455. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  159456. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  159457. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  159458. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  159459. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  159460. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  159461. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  159462. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  159463. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  159464. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  159465. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  159466. 0xf9, 0xfa };
  159467. static const UINT8 bits_ac_chrominance[17] =
  159468. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  159469. static const UINT8 val_ac_chrominance[] =
  159470. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  159471. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  159472. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  159473. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  159474. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  159475. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  159476. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  159477. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  159478. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  159479. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  159480. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  159481. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  159482. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  159483. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  159484. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  159485. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  159486. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  159487. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  159488. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  159489. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  159490. 0xf9, 0xfa };
  159491. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  159492. bits_dc_luminance, val_dc_luminance);
  159493. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  159494. bits_ac_luminance, val_ac_luminance);
  159495. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  159496. bits_dc_chrominance, val_dc_chrominance);
  159497. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  159498. bits_ac_chrominance, val_ac_chrominance);
  159499. }
  159500. /*
  159501. * Default parameter setup for compression.
  159502. *
  159503. * Applications that don't choose to use this routine must do their
  159504. * own setup of all these parameters. Alternately, you can call this
  159505. * to establish defaults and then alter parameters selectively. This
  159506. * is the recommended approach since, if we add any new parameters,
  159507. * your code will still work (they'll be set to reasonable defaults).
  159508. */
  159509. GLOBAL(void)
  159510. jpeg_set_defaults (j_compress_ptr cinfo)
  159511. {
  159512. int i;
  159513. /* Safety check to ensure start_compress not called yet. */
  159514. if (cinfo->global_state != CSTATE_START)
  159515. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  159516. /* Allocate comp_info array large enough for maximum component count.
  159517. * Array is made permanent in case application wants to compress
  159518. * multiple images at same param settings.
  159519. */
  159520. if (cinfo->comp_info == NULL)
  159521. cinfo->comp_info = (jpeg_component_info *)
  159522. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  159523. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  159524. /* Initialize everything not dependent on the color space */
  159525. cinfo->data_precision = BITS_IN_JSAMPLE;
  159526. /* Set up two quantization tables using default quality of 75 */
  159527. jpeg_set_quality(cinfo, 75, TRUE);
  159528. /* Set up two Huffman tables */
  159529. std_huff_tables(cinfo);
  159530. /* Initialize default arithmetic coding conditioning */
  159531. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  159532. cinfo->arith_dc_L[i] = 0;
  159533. cinfo->arith_dc_U[i] = 1;
  159534. cinfo->arith_ac_K[i] = 5;
  159535. }
  159536. /* Default is no multiple-scan output */
  159537. cinfo->scan_info = NULL;
  159538. cinfo->num_scans = 0;
  159539. /* Expect normal source image, not raw downsampled data */
  159540. cinfo->raw_data_in = FALSE;
  159541. /* Use Huffman coding, not arithmetic coding, by default */
  159542. cinfo->arith_code = FALSE;
  159543. /* By default, don't do extra passes to optimize entropy coding */
  159544. cinfo->optimize_coding = FALSE;
  159545. /* The standard Huffman tables are only valid for 8-bit data precision.
  159546. * If the precision is higher, force optimization on so that usable
  159547. * tables will be computed. This test can be removed if default tables
  159548. * are supplied that are valid for the desired precision.
  159549. */
  159550. if (cinfo->data_precision > 8)
  159551. cinfo->optimize_coding = TRUE;
  159552. /* By default, use the simpler non-cosited sampling alignment */
  159553. cinfo->CCIR601_sampling = FALSE;
  159554. /* No input smoothing */
  159555. cinfo->smoothing_factor = 0;
  159556. /* DCT algorithm preference */
  159557. cinfo->dct_method = JDCT_DEFAULT;
  159558. /* No restart markers */
  159559. cinfo->restart_interval = 0;
  159560. cinfo->restart_in_rows = 0;
  159561. /* Fill in default JFIF marker parameters. Note that whether the marker
  159562. * will actually be written is determined by jpeg_set_colorspace.
  159563. *
  159564. * By default, the library emits JFIF version code 1.01.
  159565. * An application that wants to emit JFIF 1.02 extension markers should set
  159566. * JFIF_minor_version to 2. We could probably get away with just defaulting
  159567. * to 1.02, but there may still be some decoders in use that will complain
  159568. * about that; saying 1.01 should minimize compatibility problems.
  159569. */
  159570. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  159571. cinfo->JFIF_minor_version = 1;
  159572. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  159573. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  159574. cinfo->Y_density = 1;
  159575. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  159576. jpeg_default_colorspace(cinfo);
  159577. }
  159578. /*
  159579. * Select an appropriate JPEG colorspace for in_color_space.
  159580. */
  159581. GLOBAL(void)
  159582. jpeg_default_colorspace (j_compress_ptr cinfo)
  159583. {
  159584. switch (cinfo->in_color_space) {
  159585. case JCS_GRAYSCALE:
  159586. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  159587. break;
  159588. case JCS_RGB:
  159589. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  159590. break;
  159591. case JCS_YCbCr:
  159592. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  159593. break;
  159594. case JCS_CMYK:
  159595. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  159596. break;
  159597. case JCS_YCCK:
  159598. jpeg_set_colorspace(cinfo, JCS_YCCK);
  159599. break;
  159600. case JCS_UNKNOWN:
  159601. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  159602. break;
  159603. default:
  159604. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159605. }
  159606. }
  159607. /*
  159608. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  159609. */
  159610. GLOBAL(void)
  159611. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  159612. {
  159613. jpeg_component_info * compptr;
  159614. int ci;
  159615. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  159616. (compptr = &cinfo->comp_info[index], \
  159617. compptr->component_id = (id), \
  159618. compptr->h_samp_factor = (hsamp), \
  159619. compptr->v_samp_factor = (vsamp), \
  159620. compptr->quant_tbl_no = (quant), \
  159621. compptr->dc_tbl_no = (dctbl), \
  159622. compptr->ac_tbl_no = (actbl) )
  159623. /* Safety check to ensure start_compress not called yet. */
  159624. if (cinfo->global_state != CSTATE_START)
  159625. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  159626. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  159627. * tables 1 for chrominance components.
  159628. */
  159629. cinfo->jpeg_color_space = colorspace;
  159630. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  159631. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  159632. switch (colorspace) {
  159633. case JCS_GRAYSCALE:
  159634. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  159635. cinfo->num_components = 1;
  159636. /* JFIF specifies component ID 1 */
  159637. SET_COMP(0, 1, 1,1, 0, 0,0);
  159638. break;
  159639. case JCS_RGB:
  159640. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  159641. cinfo->num_components = 3;
  159642. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  159643. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  159644. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  159645. break;
  159646. case JCS_YCbCr:
  159647. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  159648. cinfo->num_components = 3;
  159649. /* JFIF specifies component IDs 1,2,3 */
  159650. /* We default to 2x2 subsamples of chrominance */
  159651. SET_COMP(0, 1, 2,2, 0, 0,0);
  159652. SET_COMP(1, 2, 1,1, 1, 1,1);
  159653. SET_COMP(2, 3, 1,1, 1, 1,1);
  159654. break;
  159655. case JCS_CMYK:
  159656. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  159657. cinfo->num_components = 4;
  159658. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  159659. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  159660. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  159661. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  159662. break;
  159663. case JCS_YCCK:
  159664. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  159665. cinfo->num_components = 4;
  159666. SET_COMP(0, 1, 2,2, 0, 0,0);
  159667. SET_COMP(1, 2, 1,1, 1, 1,1);
  159668. SET_COMP(2, 3, 1,1, 1, 1,1);
  159669. SET_COMP(3, 4, 2,2, 0, 0,0);
  159670. break;
  159671. case JCS_UNKNOWN:
  159672. cinfo->num_components = cinfo->input_components;
  159673. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  159674. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  159675. MAX_COMPONENTS);
  159676. for (ci = 0; ci < cinfo->num_components; ci++) {
  159677. SET_COMP(ci, ci, 1,1, 0, 0,0);
  159678. }
  159679. break;
  159680. default:
  159681. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159682. }
  159683. }
  159684. #ifdef C_PROGRESSIVE_SUPPORTED
  159685. LOCAL(jpeg_scan_info *)
  159686. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  159687. int Ss, int Se, int Ah, int Al)
  159688. /* Support routine: generate one scan for specified component */
  159689. {
  159690. scanptr->comps_in_scan = 1;
  159691. scanptr->component_index[0] = ci;
  159692. scanptr->Ss = Ss;
  159693. scanptr->Se = Se;
  159694. scanptr->Ah = Ah;
  159695. scanptr->Al = Al;
  159696. scanptr++;
  159697. return scanptr;
  159698. }
  159699. LOCAL(jpeg_scan_info *)
  159700. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  159701. int Ss, int Se, int Ah, int Al)
  159702. /* Support routine: generate one scan for each component */
  159703. {
  159704. int ci;
  159705. for (ci = 0; ci < ncomps; ci++) {
  159706. scanptr->comps_in_scan = 1;
  159707. scanptr->component_index[0] = ci;
  159708. scanptr->Ss = Ss;
  159709. scanptr->Se = Se;
  159710. scanptr->Ah = Ah;
  159711. scanptr->Al = Al;
  159712. scanptr++;
  159713. }
  159714. return scanptr;
  159715. }
  159716. LOCAL(jpeg_scan_info *)
  159717. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  159718. /* Support routine: generate interleaved DC scan if possible, else N scans */
  159719. {
  159720. int ci;
  159721. if (ncomps <= MAX_COMPS_IN_SCAN) {
  159722. /* Single interleaved DC scan */
  159723. scanptr->comps_in_scan = ncomps;
  159724. for (ci = 0; ci < ncomps; ci++)
  159725. scanptr->component_index[ci] = ci;
  159726. scanptr->Ss = scanptr->Se = 0;
  159727. scanptr->Ah = Ah;
  159728. scanptr->Al = Al;
  159729. scanptr++;
  159730. } else {
  159731. /* Noninterleaved DC scan for each component */
  159732. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  159733. }
  159734. return scanptr;
  159735. }
  159736. /*
  159737. * Create a recommended progressive-JPEG script.
  159738. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  159739. */
  159740. GLOBAL(void)
  159741. jpeg_simple_progression (j_compress_ptr cinfo)
  159742. {
  159743. int ncomps = cinfo->num_components;
  159744. int nscans;
  159745. jpeg_scan_info * scanptr;
  159746. /* Safety check to ensure start_compress not called yet. */
  159747. if (cinfo->global_state != CSTATE_START)
  159748. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  159749. /* Figure space needed for script. Calculation must match code below! */
  159750. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  159751. /* Custom script for YCbCr color images. */
  159752. nscans = 10;
  159753. } else {
  159754. /* All-purpose script for other color spaces. */
  159755. if (ncomps > MAX_COMPS_IN_SCAN)
  159756. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  159757. else
  159758. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  159759. }
  159760. /* Allocate space for script.
  159761. * We need to put it in the permanent pool in case the application performs
  159762. * multiple compressions without changing the settings. To avoid a memory
  159763. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  159764. * object, we try to re-use previously allocated space, and we allocate
  159765. * enough space to handle YCbCr even if initially asked for grayscale.
  159766. */
  159767. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  159768. cinfo->script_space_size = MAX(nscans, 10);
  159769. cinfo->script_space = (jpeg_scan_info *)
  159770. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  159771. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  159772. }
  159773. scanptr = cinfo->script_space;
  159774. cinfo->scan_info = scanptr;
  159775. cinfo->num_scans = nscans;
  159776. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  159777. /* Custom script for YCbCr color images. */
  159778. /* Initial DC scan */
  159779. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  159780. /* Initial AC scan: get some luma data out in a hurry */
  159781. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  159782. /* Chroma data is too small to be worth expending many scans on */
  159783. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  159784. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  159785. /* Complete spectral selection for luma AC */
  159786. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  159787. /* Refine next bit of luma AC */
  159788. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  159789. /* Finish DC successive approximation */
  159790. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  159791. /* Finish AC successive approximation */
  159792. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  159793. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  159794. /* Luma bottom bit comes last since it's usually largest scan */
  159795. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  159796. } else {
  159797. /* All-purpose script for other color spaces. */
  159798. /* Successive approximation first pass */
  159799. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  159800. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  159801. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  159802. /* Successive approximation second pass */
  159803. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  159804. /* Successive approximation final pass */
  159805. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  159806. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  159807. }
  159808. }
  159809. #endif /* C_PROGRESSIVE_SUPPORTED */
  159810. /********* End of inlined file: jcparam.c *********/
  159811. /********* Start of inlined file: jcphuff.c *********/
  159812. #define JPEG_INTERNALS
  159813. #ifdef C_PROGRESSIVE_SUPPORTED
  159814. /* Expanded entropy encoder object for progressive Huffman encoding. */
  159815. typedef struct {
  159816. struct jpeg_entropy_encoder pub; /* public fields */
  159817. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  159818. boolean gather_statistics;
  159819. /* Bit-level coding status.
  159820. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  159821. */
  159822. JOCTET * next_output_byte; /* => next byte to write in buffer */
  159823. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  159824. INT32 put_buffer; /* current bit-accumulation buffer */
  159825. int put_bits; /* # of bits now in it */
  159826. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  159827. /* Coding status for DC components */
  159828. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  159829. /* Coding status for AC components */
  159830. int ac_tbl_no; /* the table number of the single component */
  159831. unsigned int EOBRUN; /* run length of EOBs */
  159832. unsigned int BE; /* # of buffered correction bits before MCU */
  159833. char * bit_buffer; /* buffer for correction bits (1 per char) */
  159834. /* packing correction bits tightly would save some space but cost time... */
  159835. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  159836. int next_restart_num; /* next restart number to write (0-7) */
  159837. /* Pointers to derived tables (these workspaces have image lifespan).
  159838. * Since any one scan codes only DC or only AC, we only need one set
  159839. * of tables, not one for DC and one for AC.
  159840. */
  159841. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  159842. /* Statistics tables for optimization; again, one set is enough */
  159843. long * count_ptrs[NUM_HUFF_TBLS];
  159844. } phuff_entropy_encoder;
  159845. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  159846. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  159847. * buffer can hold. Larger sizes may slightly improve compression, but
  159848. * 1000 is already well into the realm of overkill.
  159849. * The minimum safe size is 64 bits.
  159850. */
  159851. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  159852. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  159853. * We assume that int right shift is unsigned if INT32 right shift is,
  159854. * which should be safe.
  159855. */
  159856. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  159857. #define ISHIFT_TEMPS int ishift_temp;
  159858. #define IRIGHT_SHIFT(x,shft) \
  159859. ((ishift_temp = (x)) < 0 ? \
  159860. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  159861. (ishift_temp >> (shft)))
  159862. #else
  159863. #define ISHIFT_TEMPS
  159864. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  159865. #endif
  159866. /* Forward declarations */
  159867. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  159868. JBLOCKROW *MCU_data));
  159869. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  159870. JBLOCKROW *MCU_data));
  159871. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  159872. JBLOCKROW *MCU_data));
  159873. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  159874. JBLOCKROW *MCU_data));
  159875. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  159876. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  159877. /*
  159878. * Initialize for a Huffman-compressed scan using progressive JPEG.
  159879. */
  159880. METHODDEF(void)
  159881. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  159882. {
  159883. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  159884. boolean is_DC_band;
  159885. int ci, tbl;
  159886. jpeg_component_info * compptr;
  159887. entropy->cinfo = cinfo;
  159888. entropy->gather_statistics = gather_statistics;
  159889. is_DC_band = (cinfo->Ss == 0);
  159890. /* We assume jcmaster.c already validated the scan parameters. */
  159891. /* Select execution routines */
  159892. if (cinfo->Ah == 0) {
  159893. if (is_DC_band)
  159894. entropy->pub.encode_mcu = encode_mcu_DC_first;
  159895. else
  159896. entropy->pub.encode_mcu = encode_mcu_AC_first;
  159897. } else {
  159898. if (is_DC_band)
  159899. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  159900. else {
  159901. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  159902. /* AC refinement needs a correction bit buffer */
  159903. if (entropy->bit_buffer == NULL)
  159904. entropy->bit_buffer = (char *)
  159905. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159906. MAX_CORR_BITS * SIZEOF(char));
  159907. }
  159908. }
  159909. if (gather_statistics)
  159910. entropy->pub.finish_pass = finish_pass_gather_phuff;
  159911. else
  159912. entropy->pub.finish_pass = finish_pass_phuff;
  159913. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  159914. * for AC coefficients.
  159915. */
  159916. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159917. compptr = cinfo->cur_comp_info[ci];
  159918. /* Initialize DC predictions to 0 */
  159919. entropy->last_dc_val[ci] = 0;
  159920. /* Get table index */
  159921. if (is_DC_band) {
  159922. if (cinfo->Ah != 0) /* DC refinement needs no table */
  159923. continue;
  159924. tbl = compptr->dc_tbl_no;
  159925. } else {
  159926. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  159927. }
  159928. if (gather_statistics) {
  159929. /* Check for invalid table index */
  159930. /* (make_c_derived_tbl does this in the other path) */
  159931. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  159932. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  159933. /* Allocate and zero the statistics tables */
  159934. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  159935. if (entropy->count_ptrs[tbl] == NULL)
  159936. entropy->count_ptrs[tbl] = (long *)
  159937. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159938. 257 * SIZEOF(long));
  159939. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  159940. } else {
  159941. /* Compute derived values for Huffman table */
  159942. /* We may do this more than once for a table, but it's not expensive */
  159943. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  159944. & entropy->derived_tbls[tbl]);
  159945. }
  159946. }
  159947. /* Initialize AC stuff */
  159948. entropy->EOBRUN = 0;
  159949. entropy->BE = 0;
  159950. /* Initialize bit buffer to empty */
  159951. entropy->put_buffer = 0;
  159952. entropy->put_bits = 0;
  159953. /* Initialize restart stuff */
  159954. entropy->restarts_to_go = cinfo->restart_interval;
  159955. entropy->next_restart_num = 0;
  159956. }
  159957. /* Outputting bytes to the file.
  159958. * NB: these must be called only when actually outputting,
  159959. * that is, entropy->gather_statistics == FALSE.
  159960. */
  159961. /* Emit a byte */
  159962. #define emit_byte(entropy,val) \
  159963. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  159964. if (--(entropy)->free_in_buffer == 0) \
  159965. dump_buffer_p(entropy); }
  159966. LOCAL(void)
  159967. dump_buffer_p (phuff_entropy_ptr entropy)
  159968. /* Empty the output buffer; we do not support suspension in this module. */
  159969. {
  159970. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  159971. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  159972. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  159973. /* After a successful buffer dump, must reset buffer pointers */
  159974. entropy->next_output_byte = dest->next_output_byte;
  159975. entropy->free_in_buffer = dest->free_in_buffer;
  159976. }
  159977. /* Outputting bits to the file */
  159978. /* Only the right 24 bits of put_buffer are used; the valid bits are
  159979. * left-justified in this part. At most 16 bits can be passed to emit_bits
  159980. * in one call, and we never retain more than 7 bits in put_buffer
  159981. * between calls, so 24 bits are sufficient.
  159982. */
  159983. INLINE
  159984. LOCAL(void)
  159985. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  159986. /* Emit some bits, unless we are in gather mode */
  159987. {
  159988. /* This routine is heavily used, so it's worth coding tightly. */
  159989. register INT32 put_buffer = (INT32) code;
  159990. register int put_bits = entropy->put_bits;
  159991. /* if size is 0, caller used an invalid Huffman table entry */
  159992. if (size == 0)
  159993. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  159994. if (entropy->gather_statistics)
  159995. return; /* do nothing if we're only getting stats */
  159996. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  159997. put_bits += size; /* new number of bits in buffer */
  159998. put_buffer <<= 24 - put_bits; /* align incoming bits */
  159999. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  160000. while (put_bits >= 8) {
  160001. int c = (int) ((put_buffer >> 16) & 0xFF);
  160002. emit_byte(entropy, c);
  160003. if (c == 0xFF) { /* need to stuff a zero byte? */
  160004. emit_byte(entropy, 0);
  160005. }
  160006. put_buffer <<= 8;
  160007. put_bits -= 8;
  160008. }
  160009. entropy->put_buffer = put_buffer; /* update variables */
  160010. entropy->put_bits = put_bits;
  160011. }
  160012. LOCAL(void)
  160013. flush_bits_p (phuff_entropy_ptr entropy)
  160014. {
  160015. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  160016. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  160017. entropy->put_bits = 0;
  160018. }
  160019. /*
  160020. * Emit (or just count) a Huffman symbol.
  160021. */
  160022. INLINE
  160023. LOCAL(void)
  160024. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  160025. {
  160026. if (entropy->gather_statistics)
  160027. entropy->count_ptrs[tbl_no][symbol]++;
  160028. else {
  160029. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  160030. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  160031. }
  160032. }
  160033. /*
  160034. * Emit bits from a correction bit buffer.
  160035. */
  160036. LOCAL(void)
  160037. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  160038. unsigned int nbits)
  160039. {
  160040. if (entropy->gather_statistics)
  160041. return; /* no real work */
  160042. while (nbits > 0) {
  160043. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  160044. bufstart++;
  160045. nbits--;
  160046. }
  160047. }
  160048. /*
  160049. * Emit any pending EOBRUN symbol.
  160050. */
  160051. LOCAL(void)
  160052. emit_eobrun (phuff_entropy_ptr entropy)
  160053. {
  160054. register int temp, nbits;
  160055. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  160056. temp = entropy->EOBRUN;
  160057. nbits = 0;
  160058. while ((temp >>= 1))
  160059. nbits++;
  160060. /* safety check: shouldn't happen given limited correction-bit buffer */
  160061. if (nbits > 14)
  160062. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  160063. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  160064. if (nbits)
  160065. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  160066. entropy->EOBRUN = 0;
  160067. /* Emit any buffered correction bits */
  160068. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  160069. entropy->BE = 0;
  160070. }
  160071. }
  160072. /*
  160073. * Emit a restart marker & resynchronize predictions.
  160074. */
  160075. LOCAL(void)
  160076. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  160077. {
  160078. int ci;
  160079. emit_eobrun(entropy);
  160080. if (! entropy->gather_statistics) {
  160081. flush_bits_p(entropy);
  160082. emit_byte(entropy, 0xFF);
  160083. emit_byte(entropy, JPEG_RST0 + restart_num);
  160084. }
  160085. if (entropy->cinfo->Ss == 0) {
  160086. /* Re-initialize DC predictions to 0 */
  160087. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  160088. entropy->last_dc_val[ci] = 0;
  160089. } else {
  160090. /* Re-initialize all AC-related fields to 0 */
  160091. entropy->EOBRUN = 0;
  160092. entropy->BE = 0;
  160093. }
  160094. }
  160095. /*
  160096. * MCU encoding for DC initial scan (either spectral selection,
  160097. * or first pass of successive approximation).
  160098. */
  160099. METHODDEF(boolean)
  160100. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160101. {
  160102. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160103. register int temp, temp2;
  160104. register int nbits;
  160105. int blkn, ci;
  160106. int Al = cinfo->Al;
  160107. JBLOCKROW block;
  160108. jpeg_component_info * compptr;
  160109. ISHIFT_TEMPS
  160110. entropy->next_output_byte = cinfo->dest->next_output_byte;
  160111. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  160112. /* Emit restart marker if needed */
  160113. if (cinfo->restart_interval)
  160114. if (entropy->restarts_to_go == 0)
  160115. emit_restart_p(entropy, entropy->next_restart_num);
  160116. /* Encode the MCU data blocks */
  160117. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  160118. block = MCU_data[blkn];
  160119. ci = cinfo->MCU_membership[blkn];
  160120. compptr = cinfo->cur_comp_info[ci];
  160121. /* Compute the DC value after the required point transform by Al.
  160122. * This is simply an arithmetic right shift.
  160123. */
  160124. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  160125. /* DC differences are figured on the point-transformed values. */
  160126. temp = temp2 - entropy->last_dc_val[ci];
  160127. entropy->last_dc_val[ci] = temp2;
  160128. /* Encode the DC coefficient difference per section G.1.2.1 */
  160129. temp2 = temp;
  160130. if (temp < 0) {
  160131. temp = -temp; /* temp is abs value of input */
  160132. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  160133. /* This code assumes we are on a two's complement machine */
  160134. temp2--;
  160135. }
  160136. /* Find the number of bits needed for the magnitude of the coefficient */
  160137. nbits = 0;
  160138. while (temp) {
  160139. nbits++;
  160140. temp >>= 1;
  160141. }
  160142. /* Check for out-of-range coefficient values.
  160143. * Since we're encoding a difference, the range limit is twice as much.
  160144. */
  160145. if (nbits > MAX_COEF_BITS+1)
  160146. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  160147. /* Count/emit the Huffman-coded symbol for the number of bits */
  160148. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  160149. /* Emit that number of bits of the value, if positive, */
  160150. /* or the complement of its magnitude, if negative. */
  160151. if (nbits) /* emit_bits rejects calls with size 0 */
  160152. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  160153. }
  160154. cinfo->dest->next_output_byte = entropy->next_output_byte;
  160155. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  160156. /* Update restart-interval state too */
  160157. if (cinfo->restart_interval) {
  160158. if (entropy->restarts_to_go == 0) {
  160159. entropy->restarts_to_go = cinfo->restart_interval;
  160160. entropy->next_restart_num++;
  160161. entropy->next_restart_num &= 7;
  160162. }
  160163. entropy->restarts_to_go--;
  160164. }
  160165. return TRUE;
  160166. }
  160167. /*
  160168. * MCU encoding for AC initial scan (either spectral selection,
  160169. * or first pass of successive approximation).
  160170. */
  160171. METHODDEF(boolean)
  160172. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160173. {
  160174. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160175. register int temp, temp2;
  160176. register int nbits;
  160177. register int r, k;
  160178. int Se = cinfo->Se;
  160179. int Al = cinfo->Al;
  160180. JBLOCKROW block;
  160181. entropy->next_output_byte = cinfo->dest->next_output_byte;
  160182. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  160183. /* Emit restart marker if needed */
  160184. if (cinfo->restart_interval)
  160185. if (entropy->restarts_to_go == 0)
  160186. emit_restart_p(entropy, entropy->next_restart_num);
  160187. /* Encode the MCU data block */
  160188. block = MCU_data[0];
  160189. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  160190. r = 0; /* r = run length of zeros */
  160191. for (k = cinfo->Ss; k <= Se; k++) {
  160192. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  160193. r++;
  160194. continue;
  160195. }
  160196. /* We must apply the point transform by Al. For AC coefficients this
  160197. * is an integer division with rounding towards 0. To do this portably
  160198. * in C, we shift after obtaining the absolute value; so the code is
  160199. * interwoven with finding the abs value (temp) and output bits (temp2).
  160200. */
  160201. if (temp < 0) {
  160202. temp = -temp; /* temp is abs value of input */
  160203. temp >>= Al; /* apply the point transform */
  160204. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  160205. temp2 = ~temp;
  160206. } else {
  160207. temp >>= Al; /* apply the point transform */
  160208. temp2 = temp;
  160209. }
  160210. /* Watch out for case that nonzero coef is zero after point transform */
  160211. if (temp == 0) {
  160212. r++;
  160213. continue;
  160214. }
  160215. /* Emit any pending EOBRUN */
  160216. if (entropy->EOBRUN > 0)
  160217. emit_eobrun(entropy);
  160218. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  160219. while (r > 15) {
  160220. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  160221. r -= 16;
  160222. }
  160223. /* Find the number of bits needed for the magnitude of the coefficient */
  160224. nbits = 1; /* there must be at least one 1 bit */
  160225. while ((temp >>= 1))
  160226. nbits++;
  160227. /* Check for out-of-range coefficient values */
  160228. if (nbits > MAX_COEF_BITS)
  160229. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  160230. /* Count/emit Huffman symbol for run length / number of bits */
  160231. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  160232. /* Emit that number of bits of the value, if positive, */
  160233. /* or the complement of its magnitude, if negative. */
  160234. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  160235. r = 0; /* reset zero run length */
  160236. }
  160237. if (r > 0) { /* If there are trailing zeroes, */
  160238. entropy->EOBRUN++; /* count an EOB */
  160239. if (entropy->EOBRUN == 0x7FFF)
  160240. emit_eobrun(entropy); /* force it out to avoid overflow */
  160241. }
  160242. cinfo->dest->next_output_byte = entropy->next_output_byte;
  160243. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  160244. /* Update restart-interval state too */
  160245. if (cinfo->restart_interval) {
  160246. if (entropy->restarts_to_go == 0) {
  160247. entropy->restarts_to_go = cinfo->restart_interval;
  160248. entropy->next_restart_num++;
  160249. entropy->next_restart_num &= 7;
  160250. }
  160251. entropy->restarts_to_go--;
  160252. }
  160253. return TRUE;
  160254. }
  160255. /*
  160256. * MCU encoding for DC successive approximation refinement scan.
  160257. * Note: we assume such scans can be multi-component, although the spec
  160258. * is not very clear on the point.
  160259. */
  160260. METHODDEF(boolean)
  160261. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160262. {
  160263. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160264. register int temp;
  160265. int blkn;
  160266. int Al = cinfo->Al;
  160267. JBLOCKROW block;
  160268. entropy->next_output_byte = cinfo->dest->next_output_byte;
  160269. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  160270. /* Emit restart marker if needed */
  160271. if (cinfo->restart_interval)
  160272. if (entropy->restarts_to_go == 0)
  160273. emit_restart_p(entropy, entropy->next_restart_num);
  160274. /* Encode the MCU data blocks */
  160275. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  160276. block = MCU_data[blkn];
  160277. /* We simply emit the Al'th bit of the DC coefficient value. */
  160278. temp = (*block)[0];
  160279. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  160280. }
  160281. cinfo->dest->next_output_byte = entropy->next_output_byte;
  160282. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  160283. /* Update restart-interval state too */
  160284. if (cinfo->restart_interval) {
  160285. if (entropy->restarts_to_go == 0) {
  160286. entropy->restarts_to_go = cinfo->restart_interval;
  160287. entropy->next_restart_num++;
  160288. entropy->next_restart_num &= 7;
  160289. }
  160290. entropy->restarts_to_go--;
  160291. }
  160292. return TRUE;
  160293. }
  160294. /*
  160295. * MCU encoding for AC successive approximation refinement scan.
  160296. */
  160297. METHODDEF(boolean)
  160298. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160299. {
  160300. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160301. register int temp;
  160302. register int r, k;
  160303. int EOB;
  160304. char *BR_buffer;
  160305. unsigned int BR;
  160306. int Se = cinfo->Se;
  160307. int Al = cinfo->Al;
  160308. JBLOCKROW block;
  160309. int absvalues[DCTSIZE2];
  160310. entropy->next_output_byte = cinfo->dest->next_output_byte;
  160311. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  160312. /* Emit restart marker if needed */
  160313. if (cinfo->restart_interval)
  160314. if (entropy->restarts_to_go == 0)
  160315. emit_restart_p(entropy, entropy->next_restart_num);
  160316. /* Encode the MCU data block */
  160317. block = MCU_data[0];
  160318. /* It is convenient to make a pre-pass to determine the transformed
  160319. * coefficients' absolute values and the EOB position.
  160320. */
  160321. EOB = 0;
  160322. for (k = cinfo->Ss; k <= Se; k++) {
  160323. temp = (*block)[jpeg_natural_order[k]];
  160324. /* We must apply the point transform by Al. For AC coefficients this
  160325. * is an integer division with rounding towards 0. To do this portably
  160326. * in C, we shift after obtaining the absolute value.
  160327. */
  160328. if (temp < 0)
  160329. temp = -temp; /* temp is abs value of input */
  160330. temp >>= Al; /* apply the point transform */
  160331. absvalues[k] = temp; /* save abs value for main pass */
  160332. if (temp == 1)
  160333. EOB = k; /* EOB = index of last newly-nonzero coef */
  160334. }
  160335. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  160336. r = 0; /* r = run length of zeros */
  160337. BR = 0; /* BR = count of buffered bits added now */
  160338. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  160339. for (k = cinfo->Ss; k <= Se; k++) {
  160340. if ((temp = absvalues[k]) == 0) {
  160341. r++;
  160342. continue;
  160343. }
  160344. /* Emit any required ZRLs, but not if they can be folded into EOB */
  160345. while (r > 15 && k <= EOB) {
  160346. /* emit any pending EOBRUN and the BE correction bits */
  160347. emit_eobrun(entropy);
  160348. /* Emit ZRL */
  160349. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  160350. r -= 16;
  160351. /* Emit buffered correction bits that must be associated with ZRL */
  160352. emit_buffered_bits(entropy, BR_buffer, BR);
  160353. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  160354. BR = 0;
  160355. }
  160356. /* If the coef was previously nonzero, it only needs a correction bit.
  160357. * NOTE: a straight translation of the spec's figure G.7 would suggest
  160358. * that we also need to test r > 15. But if r > 15, we can only get here
  160359. * if k > EOB, which implies that this coefficient is not 1.
  160360. */
  160361. if (temp > 1) {
  160362. /* The correction bit is the next bit of the absolute value. */
  160363. BR_buffer[BR++] = (char) (temp & 1);
  160364. continue;
  160365. }
  160366. /* Emit any pending EOBRUN and the BE correction bits */
  160367. emit_eobrun(entropy);
  160368. /* Count/emit Huffman symbol for run length / number of bits */
  160369. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  160370. /* Emit output bit for newly-nonzero coef */
  160371. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  160372. emit_bits_p(entropy, (unsigned int) temp, 1);
  160373. /* Emit buffered correction bits that must be associated with this code */
  160374. emit_buffered_bits(entropy, BR_buffer, BR);
  160375. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  160376. BR = 0;
  160377. r = 0; /* reset zero run length */
  160378. }
  160379. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  160380. entropy->EOBRUN++; /* count an EOB */
  160381. entropy->BE += BR; /* concat my correction bits to older ones */
  160382. /* We force out the EOB if we risk either:
  160383. * 1. overflow of the EOB counter;
  160384. * 2. overflow of the correction bit buffer during the next MCU.
  160385. */
  160386. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  160387. emit_eobrun(entropy);
  160388. }
  160389. cinfo->dest->next_output_byte = entropy->next_output_byte;
  160390. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  160391. /* Update restart-interval state too */
  160392. if (cinfo->restart_interval) {
  160393. if (entropy->restarts_to_go == 0) {
  160394. entropy->restarts_to_go = cinfo->restart_interval;
  160395. entropy->next_restart_num++;
  160396. entropy->next_restart_num &= 7;
  160397. }
  160398. entropy->restarts_to_go--;
  160399. }
  160400. return TRUE;
  160401. }
  160402. /*
  160403. * Finish up at the end of a Huffman-compressed progressive scan.
  160404. */
  160405. METHODDEF(void)
  160406. finish_pass_phuff (j_compress_ptr cinfo)
  160407. {
  160408. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160409. entropy->next_output_byte = cinfo->dest->next_output_byte;
  160410. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  160411. /* Flush out any buffered data */
  160412. emit_eobrun(entropy);
  160413. flush_bits_p(entropy);
  160414. cinfo->dest->next_output_byte = entropy->next_output_byte;
  160415. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  160416. }
  160417. /*
  160418. * Finish up a statistics-gathering pass and create the new Huffman tables.
  160419. */
  160420. METHODDEF(void)
  160421. finish_pass_gather_phuff (j_compress_ptr cinfo)
  160422. {
  160423. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160424. boolean is_DC_band;
  160425. int ci, tbl;
  160426. jpeg_component_info * compptr;
  160427. JHUFF_TBL **htblptr;
  160428. boolean did[NUM_HUFF_TBLS];
  160429. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  160430. emit_eobrun(entropy);
  160431. is_DC_band = (cinfo->Ss == 0);
  160432. /* It's important not to apply jpeg_gen_optimal_table more than once
  160433. * per table, because it clobbers the input frequency counts!
  160434. */
  160435. MEMZERO(did, SIZEOF(did));
  160436. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160437. compptr = cinfo->cur_comp_info[ci];
  160438. if (is_DC_band) {
  160439. if (cinfo->Ah != 0) /* DC refinement needs no table */
  160440. continue;
  160441. tbl = compptr->dc_tbl_no;
  160442. } else {
  160443. tbl = compptr->ac_tbl_no;
  160444. }
  160445. if (! did[tbl]) {
  160446. if (is_DC_band)
  160447. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  160448. else
  160449. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  160450. if (*htblptr == NULL)
  160451. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  160452. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  160453. did[tbl] = TRUE;
  160454. }
  160455. }
  160456. }
  160457. /*
  160458. * Module initialization routine for progressive Huffman entropy encoding.
  160459. */
  160460. GLOBAL(void)
  160461. jinit_phuff_encoder (j_compress_ptr cinfo)
  160462. {
  160463. phuff_entropy_ptr entropy;
  160464. int i;
  160465. entropy = (phuff_entropy_ptr)
  160466. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160467. SIZEOF(phuff_entropy_encoder));
  160468. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  160469. entropy->pub.start_pass = start_pass_phuff;
  160470. /* Mark tables unallocated */
  160471. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160472. entropy->derived_tbls[i] = NULL;
  160473. entropy->count_ptrs[i] = NULL;
  160474. }
  160475. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  160476. }
  160477. #endif /* C_PROGRESSIVE_SUPPORTED */
  160478. /********* End of inlined file: jcphuff.c *********/
  160479. /********* Start of inlined file: jcprepct.c *********/
  160480. #define JPEG_INTERNALS
  160481. /* At present, jcsample.c can request context rows only for smoothing.
  160482. * In the future, we might also need context rows for CCIR601 sampling
  160483. * or other more-complex downsampling procedures. The code to support
  160484. * context rows should be compiled only if needed.
  160485. */
  160486. #ifdef INPUT_SMOOTHING_SUPPORTED
  160487. #define CONTEXT_ROWS_SUPPORTED
  160488. #endif
  160489. /*
  160490. * For the simple (no-context-row) case, we just need to buffer one
  160491. * row group's worth of pixels for the downsampling step. At the bottom of
  160492. * the image, we pad to a full row group by replicating the last pixel row.
  160493. * The downsampler's last output row is then replicated if needed to pad
  160494. * out to a full iMCU row.
  160495. *
  160496. * When providing context rows, we must buffer three row groups' worth of
  160497. * pixels. Three row groups are physically allocated, but the row pointer
  160498. * arrays are made five row groups high, with the extra pointers above and
  160499. * below "wrapping around" to point to the last and first real row groups.
  160500. * This allows the downsampler to access the proper context rows.
  160501. * At the top and bottom of the image, we create dummy context rows by
  160502. * copying the first or last real pixel row. This copying could be avoided
  160503. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  160504. * trouble on the compression side.
  160505. */
  160506. /* Private buffer controller object */
  160507. typedef struct {
  160508. struct jpeg_c_prep_controller pub; /* public fields */
  160509. /* Downsampling input buffer. This buffer holds color-converted data
  160510. * until we have enough to do a downsample step.
  160511. */
  160512. JSAMPARRAY color_buf[MAX_COMPONENTS];
  160513. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  160514. int next_buf_row; /* index of next row to store in color_buf */
  160515. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  160516. int this_row_group; /* starting row index of group to process */
  160517. int next_buf_stop; /* downsample when we reach this index */
  160518. #endif
  160519. } my_prep_controller;
  160520. typedef my_prep_controller * my_prep_ptr;
  160521. /*
  160522. * Initialize for a processing pass.
  160523. */
  160524. METHODDEF(void)
  160525. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  160526. {
  160527. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  160528. if (pass_mode != JBUF_PASS_THRU)
  160529. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160530. /* Initialize total-height counter for detecting bottom of image */
  160531. prep->rows_to_go = cinfo->image_height;
  160532. /* Mark the conversion buffer empty */
  160533. prep->next_buf_row = 0;
  160534. #ifdef CONTEXT_ROWS_SUPPORTED
  160535. /* Preset additional state variables for context mode.
  160536. * These aren't used in non-context mode, so we needn't test which mode.
  160537. */
  160538. prep->this_row_group = 0;
  160539. /* Set next_buf_stop to stop after two row groups have been read in. */
  160540. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  160541. #endif
  160542. }
  160543. /*
  160544. * Expand an image vertically from height input_rows to height output_rows,
  160545. * by duplicating the bottom row.
  160546. */
  160547. LOCAL(void)
  160548. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  160549. int input_rows, int output_rows)
  160550. {
  160551. register int row;
  160552. for (row = input_rows; row < output_rows; row++) {
  160553. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  160554. 1, num_cols);
  160555. }
  160556. }
  160557. /*
  160558. * Process some data in the simple no-context case.
  160559. *
  160560. * Preprocessor output data is counted in "row groups". A row group
  160561. * is defined to be v_samp_factor sample rows of each component.
  160562. * Downsampling will produce this much data from each max_v_samp_factor
  160563. * input rows.
  160564. */
  160565. METHODDEF(void)
  160566. pre_process_data (j_compress_ptr cinfo,
  160567. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160568. JDIMENSION in_rows_avail,
  160569. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  160570. JDIMENSION out_row_groups_avail)
  160571. {
  160572. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  160573. int numrows, ci;
  160574. JDIMENSION inrows;
  160575. jpeg_component_info * compptr;
  160576. while (*in_row_ctr < in_rows_avail &&
  160577. *out_row_group_ctr < out_row_groups_avail) {
  160578. /* Do color conversion to fill the conversion buffer. */
  160579. inrows = in_rows_avail - *in_row_ctr;
  160580. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  160581. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  160582. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  160583. prep->color_buf,
  160584. (JDIMENSION) prep->next_buf_row,
  160585. numrows);
  160586. *in_row_ctr += numrows;
  160587. prep->next_buf_row += numrows;
  160588. prep->rows_to_go -= numrows;
  160589. /* If at bottom of image, pad to fill the conversion buffer. */
  160590. if (prep->rows_to_go == 0 &&
  160591. prep->next_buf_row < cinfo->max_v_samp_factor) {
  160592. for (ci = 0; ci < cinfo->num_components; ci++) {
  160593. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  160594. prep->next_buf_row, cinfo->max_v_samp_factor);
  160595. }
  160596. prep->next_buf_row = cinfo->max_v_samp_factor;
  160597. }
  160598. /* If we've filled the conversion buffer, empty it. */
  160599. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  160600. (*cinfo->downsample->downsample) (cinfo,
  160601. prep->color_buf, (JDIMENSION) 0,
  160602. output_buf, *out_row_group_ctr);
  160603. prep->next_buf_row = 0;
  160604. (*out_row_group_ctr)++;
  160605. }
  160606. /* If at bottom of image, pad the output to a full iMCU height.
  160607. * Note we assume the caller is providing a one-iMCU-height output buffer!
  160608. */
  160609. if (prep->rows_to_go == 0 &&
  160610. *out_row_group_ctr < out_row_groups_avail) {
  160611. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160612. ci++, compptr++) {
  160613. expand_bottom_edge(output_buf[ci],
  160614. compptr->width_in_blocks * DCTSIZE,
  160615. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  160616. (int) (out_row_groups_avail * compptr->v_samp_factor));
  160617. }
  160618. *out_row_group_ctr = out_row_groups_avail;
  160619. break; /* can exit outer loop without test */
  160620. }
  160621. }
  160622. }
  160623. #ifdef CONTEXT_ROWS_SUPPORTED
  160624. /*
  160625. * Process some data in the context case.
  160626. */
  160627. METHODDEF(void)
  160628. pre_process_context (j_compress_ptr cinfo,
  160629. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160630. JDIMENSION in_rows_avail,
  160631. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  160632. JDIMENSION out_row_groups_avail)
  160633. {
  160634. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  160635. int numrows, ci;
  160636. int buf_height = cinfo->max_v_samp_factor * 3;
  160637. JDIMENSION inrows;
  160638. while (*out_row_group_ctr < out_row_groups_avail) {
  160639. if (*in_row_ctr < in_rows_avail) {
  160640. /* Do color conversion to fill the conversion buffer. */
  160641. inrows = in_rows_avail - *in_row_ctr;
  160642. numrows = prep->next_buf_stop - prep->next_buf_row;
  160643. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  160644. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  160645. prep->color_buf,
  160646. (JDIMENSION) prep->next_buf_row,
  160647. numrows);
  160648. /* Pad at top of image, if first time through */
  160649. if (prep->rows_to_go == cinfo->image_height) {
  160650. for (ci = 0; ci < cinfo->num_components; ci++) {
  160651. int row;
  160652. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  160653. jcopy_sample_rows(prep->color_buf[ci], 0,
  160654. prep->color_buf[ci], -row,
  160655. 1, cinfo->image_width);
  160656. }
  160657. }
  160658. }
  160659. *in_row_ctr += numrows;
  160660. prep->next_buf_row += numrows;
  160661. prep->rows_to_go -= numrows;
  160662. } else {
  160663. /* Return for more data, unless we are at the bottom of the image. */
  160664. if (prep->rows_to_go != 0)
  160665. break;
  160666. /* When at bottom of image, pad to fill the conversion buffer. */
  160667. if (prep->next_buf_row < prep->next_buf_stop) {
  160668. for (ci = 0; ci < cinfo->num_components; ci++) {
  160669. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  160670. prep->next_buf_row, prep->next_buf_stop);
  160671. }
  160672. prep->next_buf_row = prep->next_buf_stop;
  160673. }
  160674. }
  160675. /* If we've gotten enough data, downsample a row group. */
  160676. if (prep->next_buf_row == prep->next_buf_stop) {
  160677. (*cinfo->downsample->downsample) (cinfo,
  160678. prep->color_buf,
  160679. (JDIMENSION) prep->this_row_group,
  160680. output_buf, *out_row_group_ctr);
  160681. (*out_row_group_ctr)++;
  160682. /* Advance pointers with wraparound as necessary. */
  160683. prep->this_row_group += cinfo->max_v_samp_factor;
  160684. if (prep->this_row_group >= buf_height)
  160685. prep->this_row_group = 0;
  160686. if (prep->next_buf_row >= buf_height)
  160687. prep->next_buf_row = 0;
  160688. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  160689. }
  160690. }
  160691. }
  160692. /*
  160693. * Create the wrapped-around downsampling input buffer needed for context mode.
  160694. */
  160695. LOCAL(void)
  160696. create_context_buffer (j_compress_ptr cinfo)
  160697. {
  160698. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  160699. int rgroup_height = cinfo->max_v_samp_factor;
  160700. int ci, i;
  160701. jpeg_component_info * compptr;
  160702. JSAMPARRAY true_buffer, fake_buffer;
  160703. /* Grab enough space for fake row pointers for all the components;
  160704. * we need five row groups' worth of pointers for each component.
  160705. */
  160706. fake_buffer = (JSAMPARRAY)
  160707. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160708. (cinfo->num_components * 5 * rgroup_height) *
  160709. SIZEOF(JSAMPROW));
  160710. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160711. ci++, compptr++) {
  160712. /* Allocate the actual buffer space (3 row groups) for this component.
  160713. * We make the buffer wide enough to allow the downsampler to edge-expand
  160714. * horizontally within the buffer, if it so chooses.
  160715. */
  160716. true_buffer = (*cinfo->mem->alloc_sarray)
  160717. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160718. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  160719. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  160720. (JDIMENSION) (3 * rgroup_height));
  160721. /* Copy true buffer row pointers into the middle of the fake row array */
  160722. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  160723. 3 * rgroup_height * SIZEOF(JSAMPROW));
  160724. /* Fill in the above and below wraparound pointers */
  160725. for (i = 0; i < rgroup_height; i++) {
  160726. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  160727. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  160728. }
  160729. prep->color_buf[ci] = fake_buffer + rgroup_height;
  160730. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  160731. }
  160732. }
  160733. #endif /* CONTEXT_ROWS_SUPPORTED */
  160734. /*
  160735. * Initialize preprocessing controller.
  160736. */
  160737. GLOBAL(void)
  160738. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  160739. {
  160740. my_prep_ptr prep;
  160741. int ci;
  160742. jpeg_component_info * compptr;
  160743. if (need_full_buffer) /* safety check */
  160744. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160745. prep = (my_prep_ptr)
  160746. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160747. SIZEOF(my_prep_controller));
  160748. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  160749. prep->pub.start_pass = start_pass_prep;
  160750. /* Allocate the color conversion buffer.
  160751. * We make the buffer wide enough to allow the downsampler to edge-expand
  160752. * horizontally within the buffer, if it so chooses.
  160753. */
  160754. if (cinfo->downsample->need_context_rows) {
  160755. /* Set up to provide context rows */
  160756. #ifdef CONTEXT_ROWS_SUPPORTED
  160757. prep->pub.pre_process_data = pre_process_context;
  160758. create_context_buffer(cinfo);
  160759. #else
  160760. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160761. #endif
  160762. } else {
  160763. /* No context, just make it tall enough for one row group */
  160764. prep->pub.pre_process_data = pre_process_data;
  160765. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160766. ci++, compptr++) {
  160767. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  160768. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160769. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  160770. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  160771. (JDIMENSION) cinfo->max_v_samp_factor);
  160772. }
  160773. }
  160774. }
  160775. /********* End of inlined file: jcprepct.c *********/
  160776. /********* Start of inlined file: jcsample.c *********/
  160777. #define JPEG_INTERNALS
  160778. /* Pointer to routine to downsample a single component */
  160779. typedef JMETHOD(void, downsample1_ptr,
  160780. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160781. JSAMPARRAY input_data, JSAMPARRAY output_data));
  160782. /* Private subobject */
  160783. typedef struct {
  160784. struct jpeg_downsampler pub; /* public fields */
  160785. /* Downsampling method pointers, one per component */
  160786. downsample1_ptr methods[MAX_COMPONENTS];
  160787. } my_downsampler;
  160788. typedef my_downsampler * my_downsample_ptr;
  160789. /*
  160790. * Initialize for a downsampling pass.
  160791. */
  160792. METHODDEF(void)
  160793. start_pass_downsample (j_compress_ptr cinfo)
  160794. {
  160795. /* no work for now */
  160796. }
  160797. /*
  160798. * Expand a component horizontally from width input_cols to width output_cols,
  160799. * by duplicating the rightmost samples.
  160800. */
  160801. LOCAL(void)
  160802. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  160803. JDIMENSION input_cols, JDIMENSION output_cols)
  160804. {
  160805. register JSAMPROW ptr;
  160806. register JSAMPLE pixval;
  160807. register int count;
  160808. int row;
  160809. int numcols = (int) (output_cols - input_cols);
  160810. if (numcols > 0) {
  160811. for (row = 0; row < num_rows; row++) {
  160812. ptr = image_data[row] + input_cols;
  160813. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  160814. for (count = numcols; count > 0; count--)
  160815. *ptr++ = pixval;
  160816. }
  160817. }
  160818. }
  160819. /*
  160820. * Do downsampling for a whole row group (all components).
  160821. *
  160822. * In this version we simply downsample each component independently.
  160823. */
  160824. METHODDEF(void)
  160825. sep_downsample (j_compress_ptr cinfo,
  160826. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160827. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  160828. {
  160829. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  160830. int ci;
  160831. jpeg_component_info * compptr;
  160832. JSAMPARRAY in_ptr, out_ptr;
  160833. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160834. ci++, compptr++) {
  160835. in_ptr = input_buf[ci] + in_row_index;
  160836. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  160837. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  160838. }
  160839. }
  160840. /*
  160841. * Downsample pixel values of a single component.
  160842. * One row group is processed per call.
  160843. * This version handles arbitrary integral sampling ratios, without smoothing.
  160844. * Note that this version is not actually used for customary sampling ratios.
  160845. */
  160846. METHODDEF(void)
  160847. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160848. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160849. {
  160850. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  160851. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  160852. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160853. JSAMPROW inptr, outptr;
  160854. INT32 outvalue;
  160855. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  160856. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  160857. numpix = h_expand * v_expand;
  160858. numpix2 = numpix/2;
  160859. /* Expand input data enough to let all the output samples be generated
  160860. * by the standard loop. Special-casing padded output would be more
  160861. * efficient.
  160862. */
  160863. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  160864. cinfo->image_width, output_cols * h_expand);
  160865. inrow = 0;
  160866. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  160867. outptr = output_data[outrow];
  160868. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  160869. outcol++, outcol_h += h_expand) {
  160870. outvalue = 0;
  160871. for (v = 0; v < v_expand; v++) {
  160872. inptr = input_data[inrow+v] + outcol_h;
  160873. for (h = 0; h < h_expand; h++) {
  160874. outvalue += (INT32) GETJSAMPLE(*inptr++);
  160875. }
  160876. }
  160877. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  160878. }
  160879. inrow += v_expand;
  160880. }
  160881. }
  160882. /*
  160883. * Downsample pixel values of a single component.
  160884. * This version handles the special case of a full-size component,
  160885. * without smoothing.
  160886. */
  160887. METHODDEF(void)
  160888. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160889. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160890. {
  160891. /* Copy the data */
  160892. jcopy_sample_rows(input_data, 0, output_data, 0,
  160893. cinfo->max_v_samp_factor, cinfo->image_width);
  160894. /* Edge-expand */
  160895. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  160896. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  160897. }
  160898. /*
  160899. * Downsample pixel values of a single component.
  160900. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  160901. * without smoothing.
  160902. *
  160903. * A note about the "bias" calculations: when rounding fractional values to
  160904. * integer, we do not want to always round 0.5 up to the next integer.
  160905. * If we did that, we'd introduce a noticeable bias towards larger values.
  160906. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  160907. * alternate pixel locations (a simple ordered dither pattern).
  160908. */
  160909. METHODDEF(void)
  160910. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160911. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160912. {
  160913. int outrow;
  160914. JDIMENSION outcol;
  160915. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160916. register JSAMPROW inptr, outptr;
  160917. register int bias;
  160918. /* Expand input data enough to let all the output samples be generated
  160919. * by the standard loop. Special-casing padded output would be more
  160920. * efficient.
  160921. */
  160922. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  160923. cinfo->image_width, output_cols * 2);
  160924. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  160925. outptr = output_data[outrow];
  160926. inptr = input_data[outrow];
  160927. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  160928. for (outcol = 0; outcol < output_cols; outcol++) {
  160929. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  160930. + bias) >> 1);
  160931. bias ^= 1; /* 0=>1, 1=>0 */
  160932. inptr += 2;
  160933. }
  160934. }
  160935. }
  160936. /*
  160937. * Downsample pixel values of a single component.
  160938. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  160939. * without smoothing.
  160940. */
  160941. METHODDEF(void)
  160942. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160943. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160944. {
  160945. int inrow, outrow;
  160946. JDIMENSION outcol;
  160947. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160948. register JSAMPROW inptr0, inptr1, outptr;
  160949. register int bias;
  160950. /* Expand input data enough to let all the output samples be generated
  160951. * by the standard loop. Special-casing padded output would be more
  160952. * efficient.
  160953. */
  160954. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  160955. cinfo->image_width, output_cols * 2);
  160956. inrow = 0;
  160957. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  160958. outptr = output_data[outrow];
  160959. inptr0 = input_data[inrow];
  160960. inptr1 = input_data[inrow+1];
  160961. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  160962. for (outcol = 0; outcol < output_cols; outcol++) {
  160963. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  160964. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  160965. + bias) >> 2);
  160966. bias ^= 3; /* 1=>2, 2=>1 */
  160967. inptr0 += 2; inptr1 += 2;
  160968. }
  160969. inrow += 2;
  160970. }
  160971. }
  160972. #ifdef INPUT_SMOOTHING_SUPPORTED
  160973. /*
  160974. * Downsample pixel values of a single component.
  160975. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  160976. * with smoothing. One row of context is required.
  160977. */
  160978. METHODDEF(void)
  160979. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160980. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160981. {
  160982. int inrow, outrow;
  160983. JDIMENSION colctr;
  160984. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160985. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  160986. INT32 membersum, neighsum, memberscale, neighscale;
  160987. /* Expand input data enough to let all the output samples be generated
  160988. * by the standard loop. Special-casing padded output would be more
  160989. * efficient.
  160990. */
  160991. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  160992. cinfo->image_width, output_cols * 2);
  160993. /* We don't bother to form the individual "smoothed" input pixel values;
  160994. * we can directly compute the output which is the average of the four
  160995. * smoothed values. Each of the four member pixels contributes a fraction
  160996. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  160997. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  160998. * output. The four corner-adjacent neighbor pixels contribute a fraction
  160999. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  161000. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  161001. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  161002. * factors are scaled by 2^16 = 65536.
  161003. * Also recall that SF = smoothing_factor / 1024.
  161004. */
  161005. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  161006. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  161007. inrow = 0;
  161008. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  161009. outptr = output_data[outrow];
  161010. inptr0 = input_data[inrow];
  161011. inptr1 = input_data[inrow+1];
  161012. above_ptr = input_data[inrow-1];
  161013. below_ptr = input_data[inrow+2];
  161014. /* Special case for first column: pretend column -1 is same as column 0 */
  161015. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  161016. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  161017. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  161018. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  161019. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  161020. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  161021. neighsum += neighsum;
  161022. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  161023. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  161024. membersum = membersum * memberscale + neighsum * neighscale;
  161025. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  161026. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  161027. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  161028. /* sum of pixels directly mapped to this output element */
  161029. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  161030. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  161031. /* sum of edge-neighbor pixels */
  161032. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  161033. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  161034. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  161035. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  161036. /* The edge-neighbors count twice as much as corner-neighbors */
  161037. neighsum += neighsum;
  161038. /* Add in the corner-neighbors */
  161039. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  161040. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  161041. /* form final output scaled up by 2^16 */
  161042. membersum = membersum * memberscale + neighsum * neighscale;
  161043. /* round, descale and output it */
  161044. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  161045. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  161046. }
  161047. /* Special case for last column */
  161048. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  161049. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  161050. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  161051. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  161052. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  161053. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  161054. neighsum += neighsum;
  161055. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  161056. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  161057. membersum = membersum * memberscale + neighsum * neighscale;
  161058. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  161059. inrow += 2;
  161060. }
  161061. }
  161062. /*
  161063. * Downsample pixel values of a single component.
  161064. * This version handles the special case of a full-size component,
  161065. * with smoothing. One row of context is required.
  161066. */
  161067. METHODDEF(void)
  161068. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  161069. JSAMPARRAY input_data, JSAMPARRAY output_data)
  161070. {
  161071. int outrow;
  161072. JDIMENSION colctr;
  161073. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  161074. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  161075. INT32 membersum, neighsum, memberscale, neighscale;
  161076. int colsum, lastcolsum, nextcolsum;
  161077. /* Expand input data enough to let all the output samples be generated
  161078. * by the standard loop. Special-casing padded output would be more
  161079. * efficient.
  161080. */
  161081. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  161082. cinfo->image_width, output_cols);
  161083. /* Each of the eight neighbor pixels contributes a fraction SF to the
  161084. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  161085. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  161086. * Also recall that SF = smoothing_factor / 1024.
  161087. */
  161088. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  161089. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  161090. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  161091. outptr = output_data[outrow];
  161092. inptr = input_data[outrow];
  161093. above_ptr = input_data[outrow-1];
  161094. below_ptr = input_data[outrow+1];
  161095. /* Special case for first column */
  161096. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  161097. GETJSAMPLE(*inptr);
  161098. membersum = GETJSAMPLE(*inptr++);
  161099. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  161100. GETJSAMPLE(*inptr);
  161101. neighsum = colsum + (colsum - membersum) + nextcolsum;
  161102. membersum = membersum * memberscale + neighsum * neighscale;
  161103. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  161104. lastcolsum = colsum; colsum = nextcolsum;
  161105. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  161106. membersum = GETJSAMPLE(*inptr++);
  161107. above_ptr++; below_ptr++;
  161108. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  161109. GETJSAMPLE(*inptr);
  161110. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  161111. membersum = membersum * memberscale + neighsum * neighscale;
  161112. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  161113. lastcolsum = colsum; colsum = nextcolsum;
  161114. }
  161115. /* Special case for last column */
  161116. membersum = GETJSAMPLE(*inptr);
  161117. neighsum = lastcolsum + (colsum - membersum) + colsum;
  161118. membersum = membersum * memberscale + neighsum * neighscale;
  161119. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  161120. }
  161121. }
  161122. #endif /* INPUT_SMOOTHING_SUPPORTED */
  161123. /*
  161124. * Module initialization routine for downsampling.
  161125. * Note that we must select a routine for each component.
  161126. */
  161127. GLOBAL(void)
  161128. jinit_downsampler (j_compress_ptr cinfo)
  161129. {
  161130. my_downsample_ptr downsample;
  161131. int ci;
  161132. jpeg_component_info * compptr;
  161133. boolean smoothok = TRUE;
  161134. downsample = (my_downsample_ptr)
  161135. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161136. SIZEOF(my_downsampler));
  161137. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  161138. downsample->pub.start_pass = start_pass_downsample;
  161139. downsample->pub.downsample = sep_downsample;
  161140. downsample->pub.need_context_rows = FALSE;
  161141. if (cinfo->CCIR601_sampling)
  161142. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  161143. /* Verify we can handle the sampling factors, and set up method pointers */
  161144. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161145. ci++, compptr++) {
  161146. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  161147. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  161148. #ifdef INPUT_SMOOTHING_SUPPORTED
  161149. if (cinfo->smoothing_factor) {
  161150. downsample->methods[ci] = fullsize_smooth_downsample;
  161151. downsample->pub.need_context_rows = TRUE;
  161152. } else
  161153. #endif
  161154. downsample->methods[ci] = fullsize_downsample;
  161155. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  161156. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  161157. smoothok = FALSE;
  161158. downsample->methods[ci] = h2v1_downsample;
  161159. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  161160. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  161161. #ifdef INPUT_SMOOTHING_SUPPORTED
  161162. if (cinfo->smoothing_factor) {
  161163. downsample->methods[ci] = h2v2_smooth_downsample;
  161164. downsample->pub.need_context_rows = TRUE;
  161165. } else
  161166. #endif
  161167. downsample->methods[ci] = h2v2_downsample;
  161168. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  161169. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  161170. smoothok = FALSE;
  161171. downsample->methods[ci] = int_downsample;
  161172. } else
  161173. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  161174. }
  161175. #ifdef INPUT_SMOOTHING_SUPPORTED
  161176. if (cinfo->smoothing_factor && !smoothok)
  161177. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  161178. #endif
  161179. }
  161180. /********* End of inlined file: jcsample.c *********/
  161181. /********* Start of inlined file: jctrans.c *********/
  161182. #define JPEG_INTERNALS
  161183. /* Forward declarations */
  161184. LOCAL(void) transencode_master_selection
  161185. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  161186. LOCAL(void) transencode_coef_controller
  161187. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  161188. /*
  161189. * Compression initialization for writing raw-coefficient data.
  161190. * Before calling this, all parameters and a data destination must be set up.
  161191. * Call jpeg_finish_compress() to actually write the data.
  161192. *
  161193. * The number of passed virtual arrays must match cinfo->num_components.
  161194. * Note that the virtual arrays need not be filled or even realized at
  161195. * the time write_coefficients is called; indeed, if the virtual arrays
  161196. * were requested from this compression object's memory manager, they
  161197. * typically will be realized during this routine and filled afterwards.
  161198. */
  161199. GLOBAL(void)
  161200. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  161201. {
  161202. if (cinfo->global_state != CSTATE_START)
  161203. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161204. /* Mark all tables to be written */
  161205. jpeg_suppress_tables(cinfo, FALSE);
  161206. /* (Re)initialize error mgr and destination modules */
  161207. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161208. (*cinfo->dest->init_destination) (cinfo);
  161209. /* Perform master selection of active modules */
  161210. transencode_master_selection(cinfo, coef_arrays);
  161211. /* Wait for jpeg_finish_compress() call */
  161212. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  161213. cinfo->global_state = CSTATE_WRCOEFS;
  161214. }
  161215. /*
  161216. * Initialize the compression object with default parameters,
  161217. * then copy from the source object all parameters needed for lossless
  161218. * transcoding. Parameters that can be varied without loss (such as
  161219. * scan script and Huffman optimization) are left in their default states.
  161220. */
  161221. GLOBAL(void)
  161222. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  161223. j_compress_ptr dstinfo)
  161224. {
  161225. JQUANT_TBL ** qtblptr;
  161226. jpeg_component_info *incomp, *outcomp;
  161227. JQUANT_TBL *c_quant, *slot_quant;
  161228. int tblno, ci, coefi;
  161229. /* Safety check to ensure start_compress not called yet. */
  161230. if (dstinfo->global_state != CSTATE_START)
  161231. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  161232. /* Copy fundamental image dimensions */
  161233. dstinfo->image_width = srcinfo->image_width;
  161234. dstinfo->image_height = srcinfo->image_height;
  161235. dstinfo->input_components = srcinfo->num_components;
  161236. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  161237. /* Initialize all parameters to default values */
  161238. jpeg_set_defaults(dstinfo);
  161239. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  161240. * Fix it to get the right header markers for the image colorspace.
  161241. */
  161242. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  161243. dstinfo->data_precision = srcinfo->data_precision;
  161244. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  161245. /* Copy the source's quantization tables. */
  161246. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  161247. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  161248. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  161249. if (*qtblptr == NULL)
  161250. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  161251. MEMCOPY((*qtblptr)->quantval,
  161252. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  161253. SIZEOF((*qtblptr)->quantval));
  161254. (*qtblptr)->sent_table = FALSE;
  161255. }
  161256. }
  161257. /* Copy the source's per-component info.
  161258. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  161259. */
  161260. dstinfo->num_components = srcinfo->num_components;
  161261. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  161262. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  161263. MAX_COMPONENTS);
  161264. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  161265. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  161266. outcomp->component_id = incomp->component_id;
  161267. outcomp->h_samp_factor = incomp->h_samp_factor;
  161268. outcomp->v_samp_factor = incomp->v_samp_factor;
  161269. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  161270. /* Make sure saved quantization table for component matches the qtable
  161271. * slot. If not, the input file re-used this qtable slot.
  161272. * IJG encoder currently cannot duplicate this.
  161273. */
  161274. tblno = outcomp->quant_tbl_no;
  161275. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  161276. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  161277. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  161278. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  161279. c_quant = incomp->quant_table;
  161280. if (c_quant != NULL) {
  161281. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  161282. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  161283. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  161284. }
  161285. }
  161286. /* Note: we do not copy the source's Huffman table assignments;
  161287. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  161288. */
  161289. }
  161290. /* Also copy JFIF version and resolution information, if available.
  161291. * Strictly speaking this isn't "critical" info, but it's nearly
  161292. * always appropriate to copy it if available. In particular,
  161293. * if the application chooses to copy JFIF 1.02 extension markers from
  161294. * the source file, we need to copy the version to make sure we don't
  161295. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  161296. * We will *not*, however, copy version info from mislabeled "2.01" files.
  161297. */
  161298. if (srcinfo->saw_JFIF_marker) {
  161299. if (srcinfo->JFIF_major_version == 1) {
  161300. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  161301. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  161302. }
  161303. dstinfo->density_unit = srcinfo->density_unit;
  161304. dstinfo->X_density = srcinfo->X_density;
  161305. dstinfo->Y_density = srcinfo->Y_density;
  161306. }
  161307. }
  161308. /*
  161309. * Master selection of compression modules for transcoding.
  161310. * This substitutes for jcinit.c's initialization of the full compressor.
  161311. */
  161312. LOCAL(void)
  161313. transencode_master_selection (j_compress_ptr cinfo,
  161314. jvirt_barray_ptr * coef_arrays)
  161315. {
  161316. /* Although we don't actually use input_components for transcoding,
  161317. * jcmaster.c's initial_setup will complain if input_components is 0.
  161318. */
  161319. cinfo->input_components = 1;
  161320. /* Initialize master control (includes parameter checking/processing) */
  161321. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  161322. /* Entropy encoding: either Huffman or arithmetic coding. */
  161323. if (cinfo->arith_code) {
  161324. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  161325. } else {
  161326. if (cinfo->progressive_mode) {
  161327. #ifdef C_PROGRESSIVE_SUPPORTED
  161328. jinit_phuff_encoder(cinfo);
  161329. #else
  161330. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161331. #endif
  161332. } else
  161333. jinit_huff_encoder(cinfo);
  161334. }
  161335. /* We need a special coefficient buffer controller. */
  161336. transencode_coef_controller(cinfo, coef_arrays);
  161337. jinit_marker_writer(cinfo);
  161338. /* We can now tell the memory manager to allocate virtual arrays. */
  161339. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  161340. /* Write the datastream header (SOI, JFIF) immediately.
  161341. * Frame and scan headers are postponed till later.
  161342. * This lets application insert special markers after the SOI.
  161343. */
  161344. (*cinfo->marker->write_file_header) (cinfo);
  161345. }
  161346. /*
  161347. * The rest of this file is a special implementation of the coefficient
  161348. * buffer controller. This is similar to jccoefct.c, but it handles only
  161349. * output from presupplied virtual arrays. Furthermore, we generate any
  161350. * dummy padding blocks on-the-fly rather than expecting them to be present
  161351. * in the arrays.
  161352. */
  161353. /* Private buffer controller object */
  161354. typedef struct {
  161355. struct jpeg_c_coef_controller pub; /* public fields */
  161356. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161357. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161358. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161359. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161360. /* Virtual block array for each component. */
  161361. jvirt_barray_ptr * whole_image;
  161362. /* Workspace for constructing dummy blocks at right/bottom edges. */
  161363. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  161364. } my_coef_controller2;
  161365. typedef my_coef_controller2 * my_coef_ptr2;
  161366. LOCAL(void)
  161367. start_iMCU_row2 (j_compress_ptr cinfo)
  161368. /* Reset within-iMCU-row counters for a new row */
  161369. {
  161370. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  161371. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161372. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161373. * But at the bottom of the image, process only what's left.
  161374. */
  161375. if (cinfo->comps_in_scan > 1) {
  161376. coef->MCU_rows_per_iMCU_row = 1;
  161377. } else {
  161378. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161379. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161380. else
  161381. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161382. }
  161383. coef->mcu_ctr = 0;
  161384. coef->MCU_vert_offset = 0;
  161385. }
  161386. /*
  161387. * Initialize for a processing pass.
  161388. */
  161389. METHODDEF(void)
  161390. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161391. {
  161392. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  161393. if (pass_mode != JBUF_CRANK_DEST)
  161394. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161395. coef->iMCU_row_num = 0;
  161396. start_iMCU_row2(cinfo);
  161397. }
  161398. /*
  161399. * Process some data.
  161400. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161401. * per call, ie, v_samp_factor block rows for each component in the scan.
  161402. * The data is obtained from the virtual arrays and fed to the entropy coder.
  161403. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161404. *
  161405. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  161406. */
  161407. METHODDEF(boolean)
  161408. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161409. {
  161410. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  161411. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161412. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161413. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161414. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  161415. JDIMENSION start_col;
  161416. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  161417. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161418. JBLOCKROW buffer_ptr;
  161419. jpeg_component_info *compptr;
  161420. /* Align the virtual buffers for the components used in this scan. */
  161421. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161422. compptr = cinfo->cur_comp_info[ci];
  161423. buffer[ci] = (*cinfo->mem->access_virt_barray)
  161424. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  161425. coef->iMCU_row_num * compptr->v_samp_factor,
  161426. (JDIMENSION) compptr->v_samp_factor, FALSE);
  161427. }
  161428. /* Loop to process one whole iMCU row */
  161429. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161430. yoffset++) {
  161431. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  161432. MCU_col_num++) {
  161433. /* Construct list of pointers to DCT blocks belonging to this MCU */
  161434. blkn = 0; /* index of current DCT block within MCU */
  161435. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161436. compptr = cinfo->cur_comp_info[ci];
  161437. start_col = MCU_col_num * compptr->MCU_width;
  161438. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161439. : compptr->last_col_width;
  161440. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161441. if (coef->iMCU_row_num < last_iMCU_row ||
  161442. yindex+yoffset < compptr->last_row_height) {
  161443. /* Fill in pointers to real blocks in this row */
  161444. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  161445. for (xindex = 0; xindex < blockcnt; xindex++)
  161446. MCU_buffer[blkn++] = buffer_ptr++;
  161447. } else {
  161448. /* At bottom of image, need a whole row of dummy blocks */
  161449. xindex = 0;
  161450. }
  161451. /* Fill in any dummy blocks needed in this row.
  161452. * Dummy blocks are filled in the same way as in jccoefct.c:
  161453. * all zeroes in the AC entries, DC entries equal to previous
  161454. * block's DC value. The init routine has already zeroed the
  161455. * AC entries, so we need only set the DC entries correctly.
  161456. */
  161457. for (; xindex < compptr->MCU_width; xindex++) {
  161458. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  161459. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  161460. blkn++;
  161461. }
  161462. }
  161463. }
  161464. /* Try to write the MCU. */
  161465. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  161466. /* Suspension forced; update state counters and exit */
  161467. coef->MCU_vert_offset = yoffset;
  161468. coef->mcu_ctr = MCU_col_num;
  161469. return FALSE;
  161470. }
  161471. }
  161472. /* Completed an MCU row, but perhaps not an iMCU row */
  161473. coef->mcu_ctr = 0;
  161474. }
  161475. /* Completed the iMCU row, advance counters for next one */
  161476. coef->iMCU_row_num++;
  161477. start_iMCU_row2(cinfo);
  161478. return TRUE;
  161479. }
  161480. /*
  161481. * Initialize coefficient buffer controller.
  161482. *
  161483. * Each passed coefficient array must be the right size for that
  161484. * coefficient: width_in_blocks wide and height_in_blocks high,
  161485. * with unitheight at least v_samp_factor.
  161486. */
  161487. LOCAL(void)
  161488. transencode_coef_controller (j_compress_ptr cinfo,
  161489. jvirt_barray_ptr * coef_arrays)
  161490. {
  161491. my_coef_ptr2 coef;
  161492. JBLOCKROW buffer;
  161493. int i;
  161494. coef = (my_coef_ptr2)
  161495. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161496. SIZEOF(my_coef_controller2));
  161497. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  161498. coef->pub.start_pass = start_pass_coef2;
  161499. coef->pub.compress_data = compress_output2;
  161500. /* Save pointer to virtual arrays */
  161501. coef->whole_image = coef_arrays;
  161502. /* Allocate and pre-zero space for dummy DCT blocks. */
  161503. buffer = (JBLOCKROW)
  161504. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161505. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161506. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161507. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  161508. coef->dummy_buffer[i] = buffer + i;
  161509. }
  161510. }
  161511. /********* End of inlined file: jctrans.c *********/
  161512. /********* Start of inlined file: jdapistd.c *********/
  161513. #define JPEG_INTERNALS
  161514. /* Forward declarations */
  161515. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  161516. /*
  161517. * Decompression initialization.
  161518. * jpeg_read_header must be completed before calling this.
  161519. *
  161520. * If a multipass operating mode was selected, this will do all but the
  161521. * last pass, and thus may take a great deal of time.
  161522. *
  161523. * Returns FALSE if suspended. The return value need be inspected only if
  161524. * a suspending data source is used.
  161525. */
  161526. GLOBAL(boolean)
  161527. jpeg_start_decompress (j_decompress_ptr cinfo)
  161528. {
  161529. if (cinfo->global_state == DSTATE_READY) {
  161530. /* First call: initialize master control, select active modules */
  161531. jinit_master_decompress(cinfo);
  161532. if (cinfo->buffered_image) {
  161533. /* No more work here; expecting jpeg_start_output next */
  161534. cinfo->global_state = DSTATE_BUFIMAGE;
  161535. return TRUE;
  161536. }
  161537. cinfo->global_state = DSTATE_PRELOAD;
  161538. }
  161539. if (cinfo->global_state == DSTATE_PRELOAD) {
  161540. /* If file has multiple scans, absorb them all into the coef buffer */
  161541. if (cinfo->inputctl->has_multiple_scans) {
  161542. #ifdef D_MULTISCAN_FILES_SUPPORTED
  161543. for (;;) {
  161544. int retcode;
  161545. /* Call progress monitor hook if present */
  161546. if (cinfo->progress != NULL)
  161547. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161548. /* Absorb some more input */
  161549. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  161550. if (retcode == JPEG_SUSPENDED)
  161551. return FALSE;
  161552. if (retcode == JPEG_REACHED_EOI)
  161553. break;
  161554. /* Advance progress counter if appropriate */
  161555. if (cinfo->progress != NULL &&
  161556. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  161557. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  161558. /* jdmaster underestimated number of scans; ratchet up one scan */
  161559. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  161560. }
  161561. }
  161562. }
  161563. #else
  161564. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161565. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  161566. }
  161567. cinfo->output_scan_number = cinfo->input_scan_number;
  161568. } else if (cinfo->global_state != DSTATE_PRESCAN)
  161569. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161570. /* Perform any dummy output passes, and set up for the final pass */
  161571. return output_pass_setup(cinfo);
  161572. }
  161573. /*
  161574. * Set up for an output pass, and perform any dummy pass(es) needed.
  161575. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  161576. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  161577. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  161578. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  161579. */
  161580. LOCAL(boolean)
  161581. output_pass_setup (j_decompress_ptr cinfo)
  161582. {
  161583. if (cinfo->global_state != DSTATE_PRESCAN) {
  161584. /* First call: do pass setup */
  161585. (*cinfo->master->prepare_for_output_pass) (cinfo);
  161586. cinfo->output_scanline = 0;
  161587. cinfo->global_state = DSTATE_PRESCAN;
  161588. }
  161589. /* Loop over any required dummy passes */
  161590. while (cinfo->master->is_dummy_pass) {
  161591. #ifdef QUANT_2PASS_SUPPORTED
  161592. /* Crank through the dummy pass */
  161593. while (cinfo->output_scanline < cinfo->output_height) {
  161594. JDIMENSION last_scanline;
  161595. /* Call progress monitor hook if present */
  161596. if (cinfo->progress != NULL) {
  161597. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  161598. cinfo->progress->pass_limit = (long) cinfo->output_height;
  161599. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161600. }
  161601. /* Process some data */
  161602. last_scanline = cinfo->output_scanline;
  161603. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  161604. &cinfo->output_scanline, (JDIMENSION) 0);
  161605. if (cinfo->output_scanline == last_scanline)
  161606. return FALSE; /* No progress made, must suspend */
  161607. }
  161608. /* Finish up dummy pass, and set up for another one */
  161609. (*cinfo->master->finish_output_pass) (cinfo);
  161610. (*cinfo->master->prepare_for_output_pass) (cinfo);
  161611. cinfo->output_scanline = 0;
  161612. #else
  161613. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161614. #endif /* QUANT_2PASS_SUPPORTED */
  161615. }
  161616. /* Ready for application to drive output pass through
  161617. * jpeg_read_scanlines or jpeg_read_raw_data.
  161618. */
  161619. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  161620. return TRUE;
  161621. }
  161622. /*
  161623. * Read some scanlines of data from the JPEG decompressor.
  161624. *
  161625. * The return value will be the number of lines actually read.
  161626. * This may be less than the number requested in several cases,
  161627. * including bottom of image, data source suspension, and operating
  161628. * modes that emit multiple scanlines at a time.
  161629. *
  161630. * Note: we warn about excess calls to jpeg_read_scanlines() since
  161631. * this likely signals an application programmer error. However,
  161632. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  161633. */
  161634. GLOBAL(JDIMENSION)
  161635. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  161636. JDIMENSION max_lines)
  161637. {
  161638. JDIMENSION row_ctr;
  161639. if (cinfo->global_state != DSTATE_SCANNING)
  161640. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161641. if (cinfo->output_scanline >= cinfo->output_height) {
  161642. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161643. return 0;
  161644. }
  161645. /* Call progress monitor hook if present */
  161646. if (cinfo->progress != NULL) {
  161647. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  161648. cinfo->progress->pass_limit = (long) cinfo->output_height;
  161649. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161650. }
  161651. /* Process some data */
  161652. row_ctr = 0;
  161653. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  161654. cinfo->output_scanline += row_ctr;
  161655. return row_ctr;
  161656. }
  161657. /*
  161658. * Alternate entry point to read raw data.
  161659. * Processes exactly one iMCU row per call, unless suspended.
  161660. */
  161661. GLOBAL(JDIMENSION)
  161662. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  161663. JDIMENSION max_lines)
  161664. {
  161665. JDIMENSION lines_per_iMCU_row;
  161666. if (cinfo->global_state != DSTATE_RAW_OK)
  161667. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161668. if (cinfo->output_scanline >= cinfo->output_height) {
  161669. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161670. return 0;
  161671. }
  161672. /* Call progress monitor hook if present */
  161673. if (cinfo->progress != NULL) {
  161674. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  161675. cinfo->progress->pass_limit = (long) cinfo->output_height;
  161676. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161677. }
  161678. /* Verify that at least one iMCU row can be returned. */
  161679. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  161680. if (max_lines < lines_per_iMCU_row)
  161681. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161682. /* Decompress directly into user's buffer. */
  161683. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  161684. return 0; /* suspension forced, can do nothing more */
  161685. /* OK, we processed one iMCU row. */
  161686. cinfo->output_scanline += lines_per_iMCU_row;
  161687. return lines_per_iMCU_row;
  161688. }
  161689. /* Additional entry points for buffered-image mode. */
  161690. #ifdef D_MULTISCAN_FILES_SUPPORTED
  161691. /*
  161692. * Initialize for an output pass in buffered-image mode.
  161693. */
  161694. GLOBAL(boolean)
  161695. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  161696. {
  161697. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  161698. cinfo->global_state != DSTATE_PRESCAN)
  161699. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161700. /* Limit scan number to valid range */
  161701. if (scan_number <= 0)
  161702. scan_number = 1;
  161703. if (cinfo->inputctl->eoi_reached &&
  161704. scan_number > cinfo->input_scan_number)
  161705. scan_number = cinfo->input_scan_number;
  161706. cinfo->output_scan_number = scan_number;
  161707. /* Perform any dummy output passes, and set up for the real pass */
  161708. return output_pass_setup(cinfo);
  161709. }
  161710. /*
  161711. * Finish up after an output pass in buffered-image mode.
  161712. *
  161713. * Returns FALSE if suspended. The return value need be inspected only if
  161714. * a suspending data source is used.
  161715. */
  161716. GLOBAL(boolean)
  161717. jpeg_finish_output (j_decompress_ptr cinfo)
  161718. {
  161719. if ((cinfo->global_state == DSTATE_SCANNING ||
  161720. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  161721. /* Terminate this pass. */
  161722. /* We do not require the whole pass to have been completed. */
  161723. (*cinfo->master->finish_output_pass) (cinfo);
  161724. cinfo->global_state = DSTATE_BUFPOST;
  161725. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  161726. /* BUFPOST = repeat call after a suspension, anything else is error */
  161727. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161728. }
  161729. /* Read markers looking for SOS or EOI */
  161730. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  161731. ! cinfo->inputctl->eoi_reached) {
  161732. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  161733. return FALSE; /* Suspend, come back later */
  161734. }
  161735. cinfo->global_state = DSTATE_BUFIMAGE;
  161736. return TRUE;
  161737. }
  161738. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  161739. /********* End of inlined file: jdapistd.c *********/
  161740. /********* Start of inlined file: jdapimin.c *********/
  161741. #define JPEG_INTERNALS
  161742. /*
  161743. * Initialization of a JPEG decompression object.
  161744. * The error manager must already be set up (in case memory manager fails).
  161745. */
  161746. GLOBAL(void)
  161747. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  161748. {
  161749. int i;
  161750. /* Guard against version mismatches between library and caller. */
  161751. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161752. if (version != JPEG_LIB_VERSION)
  161753. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161754. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  161755. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161756. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  161757. /* For debugging purposes, we zero the whole master structure.
  161758. * But the application has already set the err pointer, and may have set
  161759. * client_data, so we have to save and restore those fields.
  161760. * Note: if application hasn't set client_data, tools like Purify may
  161761. * complain here.
  161762. */
  161763. {
  161764. struct jpeg_error_mgr * err = cinfo->err;
  161765. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161766. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  161767. cinfo->err = err;
  161768. cinfo->client_data = client_data;
  161769. }
  161770. cinfo->is_decompressor = TRUE;
  161771. /* Initialize a memory manager instance for this object */
  161772. jinit_memory_mgr((j_common_ptr) cinfo);
  161773. /* Zero out pointers to permanent structures. */
  161774. cinfo->progress = NULL;
  161775. cinfo->src = NULL;
  161776. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161777. cinfo->quant_tbl_ptrs[i] = NULL;
  161778. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161779. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161780. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161781. }
  161782. /* Initialize marker processor so application can override methods
  161783. * for COM, APPn markers before calling jpeg_read_header.
  161784. */
  161785. cinfo->marker_list = NULL;
  161786. jinit_marker_reader(cinfo);
  161787. /* And initialize the overall input controller. */
  161788. jinit_input_controller(cinfo);
  161789. /* OK, I'm ready */
  161790. cinfo->global_state = DSTATE_START;
  161791. }
  161792. /*
  161793. * Destruction of a JPEG decompression object
  161794. */
  161795. GLOBAL(void)
  161796. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  161797. {
  161798. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161799. }
  161800. /*
  161801. * Abort processing of a JPEG decompression operation,
  161802. * but don't destroy the object itself.
  161803. */
  161804. GLOBAL(void)
  161805. jpeg_abort_decompress (j_decompress_ptr cinfo)
  161806. {
  161807. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161808. }
  161809. /*
  161810. * Set default decompression parameters.
  161811. */
  161812. LOCAL(void)
  161813. default_decompress_parms (j_decompress_ptr cinfo)
  161814. {
  161815. /* Guess the input colorspace, and set output colorspace accordingly. */
  161816. /* (Wish JPEG committee had provided a real way to specify this...) */
  161817. /* Note application may override our guesses. */
  161818. switch (cinfo->num_components) {
  161819. case 1:
  161820. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  161821. cinfo->out_color_space = JCS_GRAYSCALE;
  161822. break;
  161823. case 3:
  161824. if (cinfo->saw_JFIF_marker) {
  161825. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  161826. } else if (cinfo->saw_Adobe_marker) {
  161827. switch (cinfo->Adobe_transform) {
  161828. case 0:
  161829. cinfo->jpeg_color_space = JCS_RGB;
  161830. break;
  161831. case 1:
  161832. cinfo->jpeg_color_space = JCS_YCbCr;
  161833. break;
  161834. default:
  161835. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  161836. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  161837. break;
  161838. }
  161839. } else {
  161840. /* Saw no special markers, try to guess from the component IDs */
  161841. int cid0 = cinfo->comp_info[0].component_id;
  161842. int cid1 = cinfo->comp_info[1].component_id;
  161843. int cid2 = cinfo->comp_info[2].component_id;
  161844. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  161845. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  161846. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  161847. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  161848. else {
  161849. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  161850. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  161851. }
  161852. }
  161853. /* Always guess RGB is proper output colorspace. */
  161854. cinfo->out_color_space = JCS_RGB;
  161855. break;
  161856. case 4:
  161857. if (cinfo->saw_Adobe_marker) {
  161858. switch (cinfo->Adobe_transform) {
  161859. case 0:
  161860. cinfo->jpeg_color_space = JCS_CMYK;
  161861. break;
  161862. case 2:
  161863. cinfo->jpeg_color_space = JCS_YCCK;
  161864. break;
  161865. default:
  161866. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  161867. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  161868. break;
  161869. }
  161870. } else {
  161871. /* No special markers, assume straight CMYK. */
  161872. cinfo->jpeg_color_space = JCS_CMYK;
  161873. }
  161874. cinfo->out_color_space = JCS_CMYK;
  161875. break;
  161876. default:
  161877. cinfo->jpeg_color_space = JCS_UNKNOWN;
  161878. cinfo->out_color_space = JCS_UNKNOWN;
  161879. break;
  161880. }
  161881. /* Set defaults for other decompression parameters. */
  161882. cinfo->scale_num = 1; /* 1:1 scaling */
  161883. cinfo->scale_denom = 1;
  161884. cinfo->output_gamma = 1.0;
  161885. cinfo->buffered_image = FALSE;
  161886. cinfo->raw_data_out = FALSE;
  161887. cinfo->dct_method = JDCT_DEFAULT;
  161888. cinfo->do_fancy_upsampling = TRUE;
  161889. cinfo->do_block_smoothing = TRUE;
  161890. cinfo->quantize_colors = FALSE;
  161891. /* We set these in case application only sets quantize_colors. */
  161892. cinfo->dither_mode = JDITHER_FS;
  161893. #ifdef QUANT_2PASS_SUPPORTED
  161894. cinfo->two_pass_quantize = TRUE;
  161895. #else
  161896. cinfo->two_pass_quantize = FALSE;
  161897. #endif
  161898. cinfo->desired_number_of_colors = 256;
  161899. cinfo->colormap = NULL;
  161900. /* Initialize for no mode change in buffered-image mode. */
  161901. cinfo->enable_1pass_quant = FALSE;
  161902. cinfo->enable_external_quant = FALSE;
  161903. cinfo->enable_2pass_quant = FALSE;
  161904. }
  161905. /*
  161906. * Decompression startup: read start of JPEG datastream to see what's there.
  161907. * Need only initialize JPEG object and supply a data source before calling.
  161908. *
  161909. * This routine will read as far as the first SOS marker (ie, actual start of
  161910. * compressed data), and will save all tables and parameters in the JPEG
  161911. * object. It will also initialize the decompression parameters to default
  161912. * values, and finally return JPEG_HEADER_OK. On return, the application may
  161913. * adjust the decompression parameters and then call jpeg_start_decompress.
  161914. * (Or, if the application only wanted to determine the image parameters,
  161915. * the data need not be decompressed. In that case, call jpeg_abort or
  161916. * jpeg_destroy to release any temporary space.)
  161917. * If an abbreviated (tables only) datastream is presented, the routine will
  161918. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  161919. * re-use the JPEG object to read the abbreviated image datastream(s).
  161920. * It is unnecessary (but OK) to call jpeg_abort in this case.
  161921. * The JPEG_SUSPENDED return code only occurs if the data source module
  161922. * requests suspension of the decompressor. In this case the application
  161923. * should load more source data and then re-call jpeg_read_header to resume
  161924. * processing.
  161925. * If a non-suspending data source is used and require_image is TRUE, then the
  161926. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  161927. *
  161928. * This routine is now just a front end to jpeg_consume_input, with some
  161929. * extra error checking.
  161930. */
  161931. GLOBAL(int)
  161932. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  161933. {
  161934. int retcode;
  161935. if (cinfo->global_state != DSTATE_START &&
  161936. cinfo->global_state != DSTATE_INHEADER)
  161937. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161938. retcode = jpeg_consume_input(cinfo);
  161939. switch (retcode) {
  161940. case JPEG_REACHED_SOS:
  161941. retcode = JPEG_HEADER_OK;
  161942. break;
  161943. case JPEG_REACHED_EOI:
  161944. if (require_image) /* Complain if application wanted an image */
  161945. ERREXIT(cinfo, JERR_NO_IMAGE);
  161946. /* Reset to start state; it would be safer to require the application to
  161947. * call jpeg_abort, but we can't change it now for compatibility reasons.
  161948. * A side effect is to free any temporary memory (there shouldn't be any).
  161949. */
  161950. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  161951. retcode = JPEG_HEADER_TABLES_ONLY;
  161952. break;
  161953. case JPEG_SUSPENDED:
  161954. /* no work */
  161955. break;
  161956. }
  161957. return retcode;
  161958. }
  161959. /*
  161960. * Consume data in advance of what the decompressor requires.
  161961. * This can be called at any time once the decompressor object has
  161962. * been created and a data source has been set up.
  161963. *
  161964. * This routine is essentially a state machine that handles a couple
  161965. * of critical state-transition actions, namely initial setup and
  161966. * transition from header scanning to ready-for-start_decompress.
  161967. * All the actual input is done via the input controller's consume_input
  161968. * method.
  161969. */
  161970. GLOBAL(int)
  161971. jpeg_consume_input (j_decompress_ptr cinfo)
  161972. {
  161973. int retcode = JPEG_SUSPENDED;
  161974. /* NB: every possible DSTATE value should be listed in this switch */
  161975. switch (cinfo->global_state) {
  161976. case DSTATE_START:
  161977. /* Start-of-datastream actions: reset appropriate modules */
  161978. (*cinfo->inputctl->reset_input_controller) (cinfo);
  161979. /* Initialize application's data source module */
  161980. (*cinfo->src->init_source) (cinfo);
  161981. cinfo->global_state = DSTATE_INHEADER;
  161982. /*FALLTHROUGH*/
  161983. case DSTATE_INHEADER:
  161984. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  161985. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  161986. /* Set up default parameters based on header data */
  161987. default_decompress_parms(cinfo);
  161988. /* Set global state: ready for start_decompress */
  161989. cinfo->global_state = DSTATE_READY;
  161990. }
  161991. break;
  161992. case DSTATE_READY:
  161993. /* Can't advance past first SOS until start_decompress is called */
  161994. retcode = JPEG_REACHED_SOS;
  161995. break;
  161996. case DSTATE_PRELOAD:
  161997. case DSTATE_PRESCAN:
  161998. case DSTATE_SCANNING:
  161999. case DSTATE_RAW_OK:
  162000. case DSTATE_BUFIMAGE:
  162001. case DSTATE_BUFPOST:
  162002. case DSTATE_STOPPING:
  162003. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  162004. break;
  162005. default:
  162006. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162007. }
  162008. return retcode;
  162009. }
  162010. /*
  162011. * Have we finished reading the input file?
  162012. */
  162013. GLOBAL(boolean)
  162014. jpeg_input_complete (j_decompress_ptr cinfo)
  162015. {
  162016. /* Check for valid jpeg object */
  162017. if (cinfo->global_state < DSTATE_START ||
  162018. cinfo->global_state > DSTATE_STOPPING)
  162019. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162020. return cinfo->inputctl->eoi_reached;
  162021. }
  162022. /*
  162023. * Is there more than one scan?
  162024. */
  162025. GLOBAL(boolean)
  162026. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  162027. {
  162028. /* Only valid after jpeg_read_header completes */
  162029. if (cinfo->global_state < DSTATE_READY ||
  162030. cinfo->global_state > DSTATE_STOPPING)
  162031. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162032. return cinfo->inputctl->has_multiple_scans;
  162033. }
  162034. /*
  162035. * Finish JPEG decompression.
  162036. *
  162037. * This will normally just verify the file trailer and release temp storage.
  162038. *
  162039. * Returns FALSE if suspended. The return value need be inspected only if
  162040. * a suspending data source is used.
  162041. */
  162042. GLOBAL(boolean)
  162043. jpeg_finish_decompress (j_decompress_ptr cinfo)
  162044. {
  162045. if ((cinfo->global_state == DSTATE_SCANNING ||
  162046. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  162047. /* Terminate final pass of non-buffered mode */
  162048. if (cinfo->output_scanline < cinfo->output_height)
  162049. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  162050. (*cinfo->master->finish_output_pass) (cinfo);
  162051. cinfo->global_state = DSTATE_STOPPING;
  162052. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  162053. /* Finishing after a buffered-image operation */
  162054. cinfo->global_state = DSTATE_STOPPING;
  162055. } else if (cinfo->global_state != DSTATE_STOPPING) {
  162056. /* STOPPING = repeat call after a suspension, anything else is error */
  162057. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162058. }
  162059. /* Read until EOI */
  162060. while (! cinfo->inputctl->eoi_reached) {
  162061. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  162062. return FALSE; /* Suspend, come back later */
  162063. }
  162064. /* Do final cleanup */
  162065. (*cinfo->src->term_source) (cinfo);
  162066. /* We can use jpeg_abort to release memory and reset global_state */
  162067. jpeg_abort((j_common_ptr) cinfo);
  162068. return TRUE;
  162069. }
  162070. /********* End of inlined file: jdapimin.c *********/
  162071. /********* Start of inlined file: jdatasrc.c *********/
  162072. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  162073. /********* Start of inlined file: jerror.h *********/
  162074. /*
  162075. * To define the enum list of message codes, include this file without
  162076. * defining macro JMESSAGE. To create a message string table, include it
  162077. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  162078. */
  162079. #ifndef JMESSAGE
  162080. #ifndef JERROR_H
  162081. /* First time through, define the enum list */
  162082. #define JMAKE_ENUM_LIST
  162083. #else
  162084. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  162085. #define JMESSAGE(code,string)
  162086. #endif /* JERROR_H */
  162087. #endif /* JMESSAGE */
  162088. #ifdef JMAKE_ENUM_LIST
  162089. typedef enum {
  162090. #define JMESSAGE(code,string) code ,
  162091. #endif /* JMAKE_ENUM_LIST */
  162092. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  162093. /* For maintenance convenience, list is alphabetical by message code name */
  162094. JMESSAGE(JERR_ARITH_NOTIMPL,
  162095. "Sorry, there are legal restrictions on arithmetic coding")
  162096. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  162097. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  162098. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  162099. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  162100. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  162101. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  162102. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  162103. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  162104. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  162105. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  162106. JMESSAGE(JERR_BAD_LIB_VERSION,
  162107. "Wrong JPEG library version: library is %d, caller expects %d")
  162108. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  162109. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  162110. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  162111. JMESSAGE(JERR_BAD_PROGRESSION,
  162112. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  162113. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  162114. "Invalid progressive parameters at scan script entry %d")
  162115. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  162116. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  162117. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  162118. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  162119. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  162120. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  162121. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  162122. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  162123. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  162124. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  162125. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  162126. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  162127. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  162128. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  162129. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  162130. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  162131. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  162132. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  162133. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  162134. JMESSAGE(JERR_FILE_READ, "Input file read error")
  162135. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  162136. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  162137. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  162138. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  162139. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  162140. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  162141. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  162142. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  162143. "Cannot transcode due to multiple use of quantization table %d")
  162144. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  162145. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  162146. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  162147. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  162148. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  162149. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  162150. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  162151. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  162152. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  162153. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  162154. JMESSAGE(JERR_QUANT_COMPONENTS,
  162155. "Cannot quantize more than %d color components")
  162156. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  162157. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  162158. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  162159. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  162160. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  162161. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  162162. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  162163. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  162164. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  162165. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  162166. JMESSAGE(JERR_TFILE_WRITE,
  162167. "Write failed on temporary file --- out of disk space?")
  162168. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  162169. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  162170. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  162171. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  162172. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  162173. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  162174. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  162175. JMESSAGE(JMSG_VERSION, JVERSION)
  162176. JMESSAGE(JTRC_16BIT_TABLES,
  162177. "Caution: quantization tables are too coarse for baseline JPEG")
  162178. JMESSAGE(JTRC_ADOBE,
  162179. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  162180. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  162181. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  162182. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  162183. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  162184. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  162185. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  162186. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  162187. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  162188. JMESSAGE(JTRC_EOI, "End Of Image")
  162189. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  162190. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  162191. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  162192. "Warning: thumbnail image size does not match data length %u")
  162193. JMESSAGE(JTRC_JFIF_EXTENSION,
  162194. "JFIF extension marker: type 0x%02x, length %u")
  162195. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  162196. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  162197. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  162198. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  162199. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  162200. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  162201. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  162202. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  162203. JMESSAGE(JTRC_RST, "RST%d")
  162204. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  162205. "Smoothing not supported with nonstandard sampling ratios")
  162206. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  162207. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  162208. JMESSAGE(JTRC_SOI, "Start of Image")
  162209. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  162210. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  162211. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  162212. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  162213. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  162214. JMESSAGE(JTRC_THUMB_JPEG,
  162215. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  162216. JMESSAGE(JTRC_THUMB_PALETTE,
  162217. "JFIF extension marker: palette thumbnail image, length %u")
  162218. JMESSAGE(JTRC_THUMB_RGB,
  162219. "JFIF extension marker: RGB thumbnail image, length %u")
  162220. JMESSAGE(JTRC_UNKNOWN_IDS,
  162221. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  162222. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  162223. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  162224. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  162225. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  162226. "Inconsistent progression sequence for component %d coefficient %d")
  162227. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  162228. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  162229. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  162230. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  162231. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  162232. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  162233. JMESSAGE(JWRN_MUST_RESYNC,
  162234. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  162235. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  162236. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  162237. #ifdef JMAKE_ENUM_LIST
  162238. JMSG_LASTMSGCODE
  162239. } J_MESSAGE_CODE;
  162240. #undef JMAKE_ENUM_LIST
  162241. #endif /* JMAKE_ENUM_LIST */
  162242. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  162243. #undef JMESSAGE
  162244. #ifndef JERROR_H
  162245. #define JERROR_H
  162246. /* Macros to simplify using the error and trace message stuff */
  162247. /* The first parameter is either type of cinfo pointer */
  162248. /* Fatal errors (print message and exit) */
  162249. #define ERREXIT(cinfo,code) \
  162250. ((cinfo)->err->msg_code = (code), \
  162251. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162252. #define ERREXIT1(cinfo,code,p1) \
  162253. ((cinfo)->err->msg_code = (code), \
  162254. (cinfo)->err->msg_parm.i[0] = (p1), \
  162255. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162256. #define ERREXIT2(cinfo,code,p1,p2) \
  162257. ((cinfo)->err->msg_code = (code), \
  162258. (cinfo)->err->msg_parm.i[0] = (p1), \
  162259. (cinfo)->err->msg_parm.i[1] = (p2), \
  162260. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162261. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  162262. ((cinfo)->err->msg_code = (code), \
  162263. (cinfo)->err->msg_parm.i[0] = (p1), \
  162264. (cinfo)->err->msg_parm.i[1] = (p2), \
  162265. (cinfo)->err->msg_parm.i[2] = (p3), \
  162266. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162267. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  162268. ((cinfo)->err->msg_code = (code), \
  162269. (cinfo)->err->msg_parm.i[0] = (p1), \
  162270. (cinfo)->err->msg_parm.i[1] = (p2), \
  162271. (cinfo)->err->msg_parm.i[2] = (p3), \
  162272. (cinfo)->err->msg_parm.i[3] = (p4), \
  162273. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162274. #define ERREXITS(cinfo,code,str) \
  162275. ((cinfo)->err->msg_code = (code), \
  162276. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  162277. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162278. #define MAKESTMT(stuff) do { stuff } while (0)
  162279. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  162280. #define WARNMS(cinfo,code) \
  162281. ((cinfo)->err->msg_code = (code), \
  162282. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  162283. #define WARNMS1(cinfo,code,p1) \
  162284. ((cinfo)->err->msg_code = (code), \
  162285. (cinfo)->err->msg_parm.i[0] = (p1), \
  162286. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  162287. #define WARNMS2(cinfo,code,p1,p2) \
  162288. ((cinfo)->err->msg_code = (code), \
  162289. (cinfo)->err->msg_parm.i[0] = (p1), \
  162290. (cinfo)->err->msg_parm.i[1] = (p2), \
  162291. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  162292. /* Informational/debugging messages */
  162293. #define TRACEMS(cinfo,lvl,code) \
  162294. ((cinfo)->err->msg_code = (code), \
  162295. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  162296. #define TRACEMS1(cinfo,lvl,code,p1) \
  162297. ((cinfo)->err->msg_code = (code), \
  162298. (cinfo)->err->msg_parm.i[0] = (p1), \
  162299. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  162300. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  162301. ((cinfo)->err->msg_code = (code), \
  162302. (cinfo)->err->msg_parm.i[0] = (p1), \
  162303. (cinfo)->err->msg_parm.i[1] = (p2), \
  162304. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  162305. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  162306. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  162307. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  162308. (cinfo)->err->msg_code = (code); \
  162309. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  162310. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  162311. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  162312. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  162313. (cinfo)->err->msg_code = (code); \
  162314. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  162315. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  162316. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  162317. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  162318. _mp[4] = (p5); \
  162319. (cinfo)->err->msg_code = (code); \
  162320. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  162321. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  162322. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  162323. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  162324. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  162325. (cinfo)->err->msg_code = (code); \
  162326. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  162327. #define TRACEMSS(cinfo,lvl,code,str) \
  162328. ((cinfo)->err->msg_code = (code), \
  162329. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  162330. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  162331. #endif /* JERROR_H */
  162332. /********* End of inlined file: jerror.h *********/
  162333. /* Expanded data source object for stdio input */
  162334. typedef struct {
  162335. struct jpeg_source_mgr pub; /* public fields */
  162336. FILE * infile; /* source stream */
  162337. JOCTET * buffer; /* start of buffer */
  162338. boolean start_of_file; /* have we gotten any data yet? */
  162339. } my_source_mgr;
  162340. typedef my_source_mgr * my_src_ptr;
  162341. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  162342. /*
  162343. * Initialize source --- called by jpeg_read_header
  162344. * before any data is actually read.
  162345. */
  162346. METHODDEF(void)
  162347. init_source (j_decompress_ptr cinfo)
  162348. {
  162349. my_src_ptr src = (my_src_ptr) cinfo->src;
  162350. /* We reset the empty-input-file flag for each image,
  162351. * but we don't clear the input buffer.
  162352. * This is correct behavior for reading a series of images from one source.
  162353. */
  162354. src->start_of_file = TRUE;
  162355. }
  162356. /*
  162357. * Fill the input buffer --- called whenever buffer is emptied.
  162358. *
  162359. * In typical applications, this should read fresh data into the buffer
  162360. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  162361. * reset the pointer & count to the start of the buffer, and return TRUE
  162362. * indicating that the buffer has been reloaded. It is not necessary to
  162363. * fill the buffer entirely, only to obtain at least one more byte.
  162364. *
  162365. * There is no such thing as an EOF return. If the end of the file has been
  162366. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  162367. * the buffer. In most cases, generating a warning message and inserting a
  162368. * fake EOI marker is the best course of action --- this will allow the
  162369. * decompressor to output however much of the image is there. However,
  162370. * the resulting error message is misleading if the real problem is an empty
  162371. * input file, so we handle that case specially.
  162372. *
  162373. * In applications that need to be able to suspend compression due to input
  162374. * not being available yet, a FALSE return indicates that no more data can be
  162375. * obtained right now, but more may be forthcoming later. In this situation,
  162376. * the decompressor will return to its caller (with an indication of the
  162377. * number of scanlines it has read, if any). The application should resume
  162378. * decompression after it has loaded more data into the input buffer. Note
  162379. * that there are substantial restrictions on the use of suspension --- see
  162380. * the documentation.
  162381. *
  162382. * When suspending, the decompressor will back up to a convenient restart point
  162383. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  162384. * indicate where the restart point will be if the current call returns FALSE.
  162385. * Data beyond this point must be rescanned after resumption, so move it to
  162386. * the front of the buffer rather than discarding it.
  162387. */
  162388. METHODDEF(boolean)
  162389. fill_input_buffer (j_decompress_ptr cinfo)
  162390. {
  162391. my_src_ptr src = (my_src_ptr) cinfo->src;
  162392. size_t nbytes;
  162393. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  162394. if (nbytes <= 0) {
  162395. if (src->start_of_file) /* Treat empty input file as fatal error */
  162396. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  162397. WARNMS(cinfo, JWRN_JPEG_EOF);
  162398. /* Insert a fake EOI marker */
  162399. src->buffer[0] = (JOCTET) 0xFF;
  162400. src->buffer[1] = (JOCTET) JPEG_EOI;
  162401. nbytes = 2;
  162402. }
  162403. src->pub.next_input_byte = src->buffer;
  162404. src->pub.bytes_in_buffer = nbytes;
  162405. src->start_of_file = FALSE;
  162406. return TRUE;
  162407. }
  162408. /*
  162409. * Skip data --- used to skip over a potentially large amount of
  162410. * uninteresting data (such as an APPn marker).
  162411. *
  162412. * Writers of suspendable-input applications must note that skip_input_data
  162413. * is not granted the right to give a suspension return. If the skip extends
  162414. * beyond the data currently in the buffer, the buffer can be marked empty so
  162415. * that the next read will cause a fill_input_buffer call that can suspend.
  162416. * Arranging for additional bytes to be discarded before reloading the input
  162417. * buffer is the application writer's problem.
  162418. */
  162419. METHODDEF(void)
  162420. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  162421. {
  162422. my_src_ptr src = (my_src_ptr) cinfo->src;
  162423. /* Just a dumb implementation for now. Could use fseek() except
  162424. * it doesn't work on pipes. Not clear that being smart is worth
  162425. * any trouble anyway --- large skips are infrequent.
  162426. */
  162427. if (num_bytes > 0) {
  162428. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  162429. num_bytes -= (long) src->pub.bytes_in_buffer;
  162430. (void) fill_input_buffer(cinfo);
  162431. /* note we assume that fill_input_buffer will never return FALSE,
  162432. * so suspension need not be handled.
  162433. */
  162434. }
  162435. src->pub.next_input_byte += (size_t) num_bytes;
  162436. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  162437. }
  162438. }
  162439. /*
  162440. * An additional method that can be provided by data source modules is the
  162441. * resync_to_restart method for error recovery in the presence of RST markers.
  162442. * For the moment, this source module just uses the default resync method
  162443. * provided by the JPEG library. That method assumes that no backtracking
  162444. * is possible.
  162445. */
  162446. /*
  162447. * Terminate source --- called by jpeg_finish_decompress
  162448. * after all data has been read. Often a no-op.
  162449. *
  162450. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  162451. * application must deal with any cleanup that should happen even
  162452. * for error exit.
  162453. */
  162454. METHODDEF(void)
  162455. term_source (j_decompress_ptr cinfo)
  162456. {
  162457. /* no work necessary here */
  162458. }
  162459. /*
  162460. * Prepare for input from a stdio stream.
  162461. * The caller must have already opened the stream, and is responsible
  162462. * for closing it after finishing decompression.
  162463. */
  162464. GLOBAL(void)
  162465. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  162466. {
  162467. my_src_ptr src;
  162468. /* The source object and input buffer are made permanent so that a series
  162469. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  162470. * only before the first one. (If we discarded the buffer at the end of
  162471. * one image, we'd likely lose the start of the next one.)
  162472. * This makes it unsafe to use this manager and a different source
  162473. * manager serially with the same JPEG object. Caveat programmer.
  162474. */
  162475. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  162476. cinfo->src = (struct jpeg_source_mgr *)
  162477. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  162478. SIZEOF(my_source_mgr));
  162479. src = (my_src_ptr) cinfo->src;
  162480. src->buffer = (JOCTET *)
  162481. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  162482. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  162483. }
  162484. src = (my_src_ptr) cinfo->src;
  162485. src->pub.init_source = init_source;
  162486. src->pub.fill_input_buffer = fill_input_buffer;
  162487. src->pub.skip_input_data = skip_input_data;
  162488. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  162489. src->pub.term_source = term_source;
  162490. src->infile = infile;
  162491. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  162492. src->pub.next_input_byte = NULL; /* until buffer loaded */
  162493. }
  162494. /********* End of inlined file: jdatasrc.c *********/
  162495. /********* Start of inlined file: jdcoefct.c *********/
  162496. #define JPEG_INTERNALS
  162497. /* Block smoothing is only applicable for progressive JPEG, so: */
  162498. #ifndef D_PROGRESSIVE_SUPPORTED
  162499. #undef BLOCK_SMOOTHING_SUPPORTED
  162500. #endif
  162501. /* Private buffer controller object */
  162502. typedef struct {
  162503. struct jpeg_d_coef_controller pub; /* public fields */
  162504. /* These variables keep track of the current location of the input side. */
  162505. /* cinfo->input_iMCU_row is also used for this. */
  162506. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  162507. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  162508. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  162509. /* The output side's location is represented by cinfo->output_iMCU_row. */
  162510. /* In single-pass modes, it's sufficient to buffer just one MCU.
  162511. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  162512. * and let the entropy decoder write into that workspace each time.
  162513. * (On 80x86, the workspace is FAR even though it's not really very big;
  162514. * this is to keep the module interfaces unchanged when a large coefficient
  162515. * buffer is necessary.)
  162516. * In multi-pass modes, this array points to the current MCU's blocks
  162517. * within the virtual arrays; it is used only by the input side.
  162518. */
  162519. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  162520. #ifdef D_MULTISCAN_FILES_SUPPORTED
  162521. /* In multi-pass modes, we need a virtual block array for each component. */
  162522. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  162523. #endif
  162524. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162525. /* When doing block smoothing, we latch coefficient Al values here */
  162526. int * coef_bits_latch;
  162527. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  162528. #endif
  162529. } my_coef_controller3;
  162530. typedef my_coef_controller3 * my_coef_ptr3;
  162531. /* Forward declarations */
  162532. METHODDEF(int) decompress_onepass
  162533. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  162534. #ifdef D_MULTISCAN_FILES_SUPPORTED
  162535. METHODDEF(int) decompress_data
  162536. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  162537. #endif
  162538. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162539. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  162540. METHODDEF(int) decompress_smooth_data
  162541. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  162542. #endif
  162543. LOCAL(void)
  162544. start_iMCU_row3 (j_decompress_ptr cinfo)
  162545. /* Reset within-iMCU-row counters for a new row (input side) */
  162546. {
  162547. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162548. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  162549. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  162550. * But at the bottom of the image, process only what's left.
  162551. */
  162552. if (cinfo->comps_in_scan > 1) {
  162553. coef->MCU_rows_per_iMCU_row = 1;
  162554. } else {
  162555. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  162556. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  162557. else
  162558. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  162559. }
  162560. coef->MCU_ctr = 0;
  162561. coef->MCU_vert_offset = 0;
  162562. }
  162563. /*
  162564. * Initialize for an input processing pass.
  162565. */
  162566. METHODDEF(void)
  162567. start_input_pass (j_decompress_ptr cinfo)
  162568. {
  162569. cinfo->input_iMCU_row = 0;
  162570. start_iMCU_row3(cinfo);
  162571. }
  162572. /*
  162573. * Initialize for an output processing pass.
  162574. */
  162575. METHODDEF(void)
  162576. start_output_pass (j_decompress_ptr cinfo)
  162577. {
  162578. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162579. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162580. /* If multipass, check to see whether to use block smoothing on this pass */
  162581. if (coef->pub.coef_arrays != NULL) {
  162582. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  162583. coef->pub.decompress_data = decompress_smooth_data;
  162584. else
  162585. coef->pub.decompress_data = decompress_data;
  162586. }
  162587. #endif
  162588. cinfo->output_iMCU_row = 0;
  162589. }
  162590. /*
  162591. * Decompress and return some data in the single-pass case.
  162592. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  162593. * Input and output must run in lockstep since we have only a one-MCU buffer.
  162594. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  162595. *
  162596. * NB: output_buf contains a plane for each component in image,
  162597. * which we index according to the component's SOF position.
  162598. */
  162599. METHODDEF(int)
  162600. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  162601. {
  162602. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162603. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162604. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162605. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162606. int blkn, ci, xindex, yindex, yoffset, useful_width;
  162607. JSAMPARRAY output_ptr;
  162608. JDIMENSION start_col, output_col;
  162609. jpeg_component_info *compptr;
  162610. inverse_DCT_method_ptr inverse_DCT;
  162611. /* Loop to process as much as one whole iMCU row */
  162612. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162613. yoffset++) {
  162614. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  162615. MCU_col_num++) {
  162616. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  162617. jzero_far((void FAR *) coef->MCU_buffer[0],
  162618. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  162619. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  162620. /* Suspension forced; update state counters and exit */
  162621. coef->MCU_vert_offset = yoffset;
  162622. coef->MCU_ctr = MCU_col_num;
  162623. return JPEG_SUSPENDED;
  162624. }
  162625. /* Determine where data should go in output_buf and do the IDCT thing.
  162626. * We skip dummy blocks at the right and bottom edges (but blkn gets
  162627. * incremented past them!). Note the inner loop relies on having
  162628. * allocated the MCU_buffer[] blocks sequentially.
  162629. */
  162630. blkn = 0; /* index of current DCT block within MCU */
  162631. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162632. compptr = cinfo->cur_comp_info[ci];
  162633. /* Don't bother to IDCT an uninteresting component. */
  162634. if (! compptr->component_needed) {
  162635. blkn += compptr->MCU_blocks;
  162636. continue;
  162637. }
  162638. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  162639. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162640. : compptr->last_col_width;
  162641. output_ptr = output_buf[compptr->component_index] +
  162642. yoffset * compptr->DCT_scaled_size;
  162643. start_col = MCU_col_num * compptr->MCU_sample_width;
  162644. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162645. if (cinfo->input_iMCU_row < last_iMCU_row ||
  162646. yoffset+yindex < compptr->last_row_height) {
  162647. output_col = start_col;
  162648. for (xindex = 0; xindex < useful_width; xindex++) {
  162649. (*inverse_DCT) (cinfo, compptr,
  162650. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  162651. output_ptr, output_col);
  162652. output_col += compptr->DCT_scaled_size;
  162653. }
  162654. }
  162655. blkn += compptr->MCU_width;
  162656. output_ptr += compptr->DCT_scaled_size;
  162657. }
  162658. }
  162659. }
  162660. /* Completed an MCU row, but perhaps not an iMCU row */
  162661. coef->MCU_ctr = 0;
  162662. }
  162663. /* Completed the iMCU row, advance counters for next one */
  162664. cinfo->output_iMCU_row++;
  162665. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  162666. start_iMCU_row3(cinfo);
  162667. return JPEG_ROW_COMPLETED;
  162668. }
  162669. /* Completed the scan */
  162670. (*cinfo->inputctl->finish_input_pass) (cinfo);
  162671. return JPEG_SCAN_COMPLETED;
  162672. }
  162673. /*
  162674. * Dummy consume-input routine for single-pass operation.
  162675. */
  162676. METHODDEF(int)
  162677. dummy_consume_data (j_decompress_ptr cinfo)
  162678. {
  162679. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  162680. }
  162681. #ifdef D_MULTISCAN_FILES_SUPPORTED
  162682. /*
  162683. * Consume input data and store it in the full-image coefficient buffer.
  162684. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  162685. * ie, v_samp_factor block rows for each component in the scan.
  162686. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  162687. */
  162688. METHODDEF(int)
  162689. consume_data (j_decompress_ptr cinfo)
  162690. {
  162691. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162692. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162693. int blkn, ci, xindex, yindex, yoffset;
  162694. JDIMENSION start_col;
  162695. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162696. JBLOCKROW buffer_ptr;
  162697. jpeg_component_info *compptr;
  162698. /* Align the virtual buffers for the components used in this scan. */
  162699. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162700. compptr = cinfo->cur_comp_info[ci];
  162701. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162702. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162703. cinfo->input_iMCU_row * compptr->v_samp_factor,
  162704. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162705. /* Note: entropy decoder expects buffer to be zeroed,
  162706. * but this is handled automatically by the memory manager
  162707. * because we requested a pre-zeroed array.
  162708. */
  162709. }
  162710. /* Loop to process one whole iMCU row */
  162711. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162712. yoffset++) {
  162713. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162714. MCU_col_num++) {
  162715. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162716. blkn = 0; /* index of current DCT block within MCU */
  162717. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162718. compptr = cinfo->cur_comp_info[ci];
  162719. start_col = MCU_col_num * compptr->MCU_width;
  162720. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162721. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162722. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162723. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162724. }
  162725. }
  162726. }
  162727. /* Try to fetch the MCU. */
  162728. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  162729. /* Suspension forced; update state counters and exit */
  162730. coef->MCU_vert_offset = yoffset;
  162731. coef->MCU_ctr = MCU_col_num;
  162732. return JPEG_SUSPENDED;
  162733. }
  162734. }
  162735. /* Completed an MCU row, but perhaps not an iMCU row */
  162736. coef->MCU_ctr = 0;
  162737. }
  162738. /* Completed the iMCU row, advance counters for next one */
  162739. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  162740. start_iMCU_row3(cinfo);
  162741. return JPEG_ROW_COMPLETED;
  162742. }
  162743. /* Completed the scan */
  162744. (*cinfo->inputctl->finish_input_pass) (cinfo);
  162745. return JPEG_SCAN_COMPLETED;
  162746. }
  162747. /*
  162748. * Decompress and return some data in the multi-pass case.
  162749. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  162750. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  162751. *
  162752. * NB: output_buf contains a plane for each component in image.
  162753. */
  162754. METHODDEF(int)
  162755. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  162756. {
  162757. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162758. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162759. JDIMENSION block_num;
  162760. int ci, block_row, block_rows;
  162761. JBLOCKARRAY buffer;
  162762. JBLOCKROW buffer_ptr;
  162763. JSAMPARRAY output_ptr;
  162764. JDIMENSION output_col;
  162765. jpeg_component_info *compptr;
  162766. inverse_DCT_method_ptr inverse_DCT;
  162767. /* Force some input to be done if we are getting ahead of the input. */
  162768. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  162769. (cinfo->input_scan_number == cinfo->output_scan_number &&
  162770. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  162771. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  162772. return JPEG_SUSPENDED;
  162773. }
  162774. /* OK, output from the virtual arrays. */
  162775. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162776. ci++, compptr++) {
  162777. /* Don't bother to IDCT an uninteresting component. */
  162778. if (! compptr->component_needed)
  162779. continue;
  162780. /* Align the virtual buffer for this component. */
  162781. buffer = (*cinfo->mem->access_virt_barray)
  162782. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162783. cinfo->output_iMCU_row * compptr->v_samp_factor,
  162784. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162785. /* Count non-dummy DCT block rows in this iMCU row. */
  162786. if (cinfo->output_iMCU_row < last_iMCU_row)
  162787. block_rows = compptr->v_samp_factor;
  162788. else {
  162789. /* NB: can't use last_row_height here; it is input-side-dependent! */
  162790. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162791. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162792. }
  162793. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  162794. output_ptr = output_buf[ci];
  162795. /* Loop over all DCT blocks to be processed. */
  162796. for (block_row = 0; block_row < block_rows; block_row++) {
  162797. buffer_ptr = buffer[block_row];
  162798. output_col = 0;
  162799. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  162800. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  162801. output_ptr, output_col);
  162802. buffer_ptr++;
  162803. output_col += compptr->DCT_scaled_size;
  162804. }
  162805. output_ptr += compptr->DCT_scaled_size;
  162806. }
  162807. }
  162808. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  162809. return JPEG_ROW_COMPLETED;
  162810. return JPEG_SCAN_COMPLETED;
  162811. }
  162812. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  162813. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162814. /*
  162815. * This code applies interblock smoothing as described by section K.8
  162816. * of the JPEG standard: the first 5 AC coefficients are estimated from
  162817. * the DC values of a DCT block and its 8 neighboring blocks.
  162818. * We apply smoothing only for progressive JPEG decoding, and only if
  162819. * the coefficients it can estimate are not yet known to full precision.
  162820. */
  162821. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  162822. #define Q01_POS 1
  162823. #define Q10_POS 8
  162824. #define Q20_POS 16
  162825. #define Q11_POS 9
  162826. #define Q02_POS 2
  162827. /*
  162828. * Determine whether block smoothing is applicable and safe.
  162829. * We also latch the current states of the coef_bits[] entries for the
  162830. * AC coefficients; otherwise, if the input side of the decompressor
  162831. * advances into a new scan, we might think the coefficients are known
  162832. * more accurately than they really are.
  162833. */
  162834. LOCAL(boolean)
  162835. smoothing_ok (j_decompress_ptr cinfo)
  162836. {
  162837. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162838. boolean smoothing_useful = FALSE;
  162839. int ci, coefi;
  162840. jpeg_component_info *compptr;
  162841. JQUANT_TBL * qtable;
  162842. int * coef_bits;
  162843. int * coef_bits_latch;
  162844. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  162845. return FALSE;
  162846. /* Allocate latch area if not already done */
  162847. if (coef->coef_bits_latch == NULL)
  162848. coef->coef_bits_latch = (int *)
  162849. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162850. cinfo->num_components *
  162851. (SAVED_COEFS * SIZEOF(int)));
  162852. coef_bits_latch = coef->coef_bits_latch;
  162853. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162854. ci++, compptr++) {
  162855. /* All components' quantization values must already be latched. */
  162856. if ((qtable = compptr->quant_table) == NULL)
  162857. return FALSE;
  162858. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  162859. if (qtable->quantval[0] == 0 ||
  162860. qtable->quantval[Q01_POS] == 0 ||
  162861. qtable->quantval[Q10_POS] == 0 ||
  162862. qtable->quantval[Q20_POS] == 0 ||
  162863. qtable->quantval[Q11_POS] == 0 ||
  162864. qtable->quantval[Q02_POS] == 0)
  162865. return FALSE;
  162866. /* DC values must be at least partly known for all components. */
  162867. coef_bits = cinfo->coef_bits[ci];
  162868. if (coef_bits[0] < 0)
  162869. return FALSE;
  162870. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  162871. for (coefi = 1; coefi <= 5; coefi++) {
  162872. coef_bits_latch[coefi] = coef_bits[coefi];
  162873. if (coef_bits[coefi] != 0)
  162874. smoothing_useful = TRUE;
  162875. }
  162876. coef_bits_latch += SAVED_COEFS;
  162877. }
  162878. return smoothing_useful;
  162879. }
  162880. /*
  162881. * Variant of decompress_data for use when doing block smoothing.
  162882. */
  162883. METHODDEF(int)
  162884. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  162885. {
  162886. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162887. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162888. JDIMENSION block_num, last_block_column;
  162889. int ci, block_row, block_rows, access_rows;
  162890. JBLOCKARRAY buffer;
  162891. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  162892. JSAMPARRAY output_ptr;
  162893. JDIMENSION output_col;
  162894. jpeg_component_info *compptr;
  162895. inverse_DCT_method_ptr inverse_DCT;
  162896. boolean first_row, last_row;
  162897. JBLOCK workspace;
  162898. int *coef_bits;
  162899. JQUANT_TBL *quanttbl;
  162900. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  162901. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  162902. int Al, pred;
  162903. /* Force some input to be done if we are getting ahead of the input. */
  162904. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  162905. ! cinfo->inputctl->eoi_reached) {
  162906. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  162907. /* If input is working on current scan, we ordinarily want it to
  162908. * have completed the current row. But if input scan is DC,
  162909. * we want it to keep one row ahead so that next block row's DC
  162910. * values are up to date.
  162911. */
  162912. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  162913. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  162914. break;
  162915. }
  162916. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  162917. return JPEG_SUSPENDED;
  162918. }
  162919. /* OK, output from the virtual arrays. */
  162920. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162921. ci++, compptr++) {
  162922. /* Don't bother to IDCT an uninteresting component. */
  162923. if (! compptr->component_needed)
  162924. continue;
  162925. /* Count non-dummy DCT block rows in this iMCU row. */
  162926. if (cinfo->output_iMCU_row < last_iMCU_row) {
  162927. block_rows = compptr->v_samp_factor;
  162928. access_rows = block_rows * 2; /* this and next iMCU row */
  162929. last_row = FALSE;
  162930. } else {
  162931. /* NB: can't use last_row_height here; it is input-side-dependent! */
  162932. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162933. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162934. access_rows = block_rows; /* this iMCU row only */
  162935. last_row = TRUE;
  162936. }
  162937. /* Align the virtual buffer for this component. */
  162938. if (cinfo->output_iMCU_row > 0) {
  162939. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  162940. buffer = (*cinfo->mem->access_virt_barray)
  162941. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162942. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  162943. (JDIMENSION) access_rows, FALSE);
  162944. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  162945. first_row = FALSE;
  162946. } else {
  162947. buffer = (*cinfo->mem->access_virt_barray)
  162948. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162949. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  162950. first_row = TRUE;
  162951. }
  162952. /* Fetch component-dependent info */
  162953. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  162954. quanttbl = compptr->quant_table;
  162955. Q00 = quanttbl->quantval[0];
  162956. Q01 = quanttbl->quantval[Q01_POS];
  162957. Q10 = quanttbl->quantval[Q10_POS];
  162958. Q20 = quanttbl->quantval[Q20_POS];
  162959. Q11 = quanttbl->quantval[Q11_POS];
  162960. Q02 = quanttbl->quantval[Q02_POS];
  162961. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  162962. output_ptr = output_buf[ci];
  162963. /* Loop over all DCT blocks to be processed. */
  162964. for (block_row = 0; block_row < block_rows; block_row++) {
  162965. buffer_ptr = buffer[block_row];
  162966. if (first_row && block_row == 0)
  162967. prev_block_row = buffer_ptr;
  162968. else
  162969. prev_block_row = buffer[block_row-1];
  162970. if (last_row && block_row == block_rows-1)
  162971. next_block_row = buffer_ptr;
  162972. else
  162973. next_block_row = buffer[block_row+1];
  162974. /* We fetch the surrounding DC values using a sliding-register approach.
  162975. * Initialize all nine here so as to do the right thing on narrow pics.
  162976. */
  162977. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  162978. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  162979. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  162980. output_col = 0;
  162981. last_block_column = compptr->width_in_blocks - 1;
  162982. for (block_num = 0; block_num <= last_block_column; block_num++) {
  162983. /* Fetch current DCT block into workspace so we can modify it. */
  162984. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  162985. /* Update DC values */
  162986. if (block_num < last_block_column) {
  162987. DC3 = (int) prev_block_row[1][0];
  162988. DC6 = (int) buffer_ptr[1][0];
  162989. DC9 = (int) next_block_row[1][0];
  162990. }
  162991. /* Compute coefficient estimates per K.8.
  162992. * An estimate is applied only if coefficient is still zero,
  162993. * and is not known to be fully accurate.
  162994. */
  162995. /* AC01 */
  162996. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  162997. num = 36 * Q00 * (DC4 - DC6);
  162998. if (num >= 0) {
  162999. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  163000. if (Al > 0 && pred >= (1<<Al))
  163001. pred = (1<<Al)-1;
  163002. } else {
  163003. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  163004. if (Al > 0 && pred >= (1<<Al))
  163005. pred = (1<<Al)-1;
  163006. pred = -pred;
  163007. }
  163008. workspace[1] = (JCOEF) pred;
  163009. }
  163010. /* AC10 */
  163011. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  163012. num = 36 * Q00 * (DC2 - DC8);
  163013. if (num >= 0) {
  163014. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  163015. if (Al > 0 && pred >= (1<<Al))
  163016. pred = (1<<Al)-1;
  163017. } else {
  163018. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  163019. if (Al > 0 && pred >= (1<<Al))
  163020. pred = (1<<Al)-1;
  163021. pred = -pred;
  163022. }
  163023. workspace[8] = (JCOEF) pred;
  163024. }
  163025. /* AC20 */
  163026. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  163027. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  163028. if (num >= 0) {
  163029. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  163030. if (Al > 0 && pred >= (1<<Al))
  163031. pred = (1<<Al)-1;
  163032. } else {
  163033. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  163034. if (Al > 0 && pred >= (1<<Al))
  163035. pred = (1<<Al)-1;
  163036. pred = -pred;
  163037. }
  163038. workspace[16] = (JCOEF) pred;
  163039. }
  163040. /* AC11 */
  163041. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  163042. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  163043. if (num >= 0) {
  163044. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  163045. if (Al > 0 && pred >= (1<<Al))
  163046. pred = (1<<Al)-1;
  163047. } else {
  163048. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  163049. if (Al > 0 && pred >= (1<<Al))
  163050. pred = (1<<Al)-1;
  163051. pred = -pred;
  163052. }
  163053. workspace[9] = (JCOEF) pred;
  163054. }
  163055. /* AC02 */
  163056. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  163057. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  163058. if (num >= 0) {
  163059. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  163060. if (Al > 0 && pred >= (1<<Al))
  163061. pred = (1<<Al)-1;
  163062. } else {
  163063. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  163064. if (Al > 0 && pred >= (1<<Al))
  163065. pred = (1<<Al)-1;
  163066. pred = -pred;
  163067. }
  163068. workspace[2] = (JCOEF) pred;
  163069. }
  163070. /* OK, do the IDCT */
  163071. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  163072. output_ptr, output_col);
  163073. /* Advance for next column */
  163074. DC1 = DC2; DC2 = DC3;
  163075. DC4 = DC5; DC5 = DC6;
  163076. DC7 = DC8; DC8 = DC9;
  163077. buffer_ptr++, prev_block_row++, next_block_row++;
  163078. output_col += compptr->DCT_scaled_size;
  163079. }
  163080. output_ptr += compptr->DCT_scaled_size;
  163081. }
  163082. }
  163083. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  163084. return JPEG_ROW_COMPLETED;
  163085. return JPEG_SCAN_COMPLETED;
  163086. }
  163087. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  163088. /*
  163089. * Initialize coefficient buffer controller.
  163090. */
  163091. GLOBAL(void)
  163092. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  163093. {
  163094. my_coef_ptr3 coef;
  163095. coef = (my_coef_ptr3)
  163096. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163097. SIZEOF(my_coef_controller3));
  163098. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  163099. coef->pub.start_input_pass = start_input_pass;
  163100. coef->pub.start_output_pass = start_output_pass;
  163101. #ifdef BLOCK_SMOOTHING_SUPPORTED
  163102. coef->coef_bits_latch = NULL;
  163103. #endif
  163104. /* Create the coefficient buffer. */
  163105. if (need_full_buffer) {
  163106. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163107. /* Allocate a full-image virtual array for each component, */
  163108. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  163109. /* Note we ask for a pre-zeroed array. */
  163110. int ci, access_rows;
  163111. jpeg_component_info *compptr;
  163112. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163113. ci++, compptr++) {
  163114. access_rows = compptr->v_samp_factor;
  163115. #ifdef BLOCK_SMOOTHING_SUPPORTED
  163116. /* If block smoothing could be used, need a bigger window */
  163117. if (cinfo->progressive_mode)
  163118. access_rows *= 3;
  163119. #endif
  163120. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  163121. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  163122. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  163123. (long) compptr->h_samp_factor),
  163124. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  163125. (long) compptr->v_samp_factor),
  163126. (JDIMENSION) access_rows);
  163127. }
  163128. coef->pub.consume_data = consume_data;
  163129. coef->pub.decompress_data = decompress_data;
  163130. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  163131. #else
  163132. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163133. #endif
  163134. } else {
  163135. /* We only need a single-MCU buffer. */
  163136. JBLOCKROW buffer;
  163137. int i;
  163138. buffer = (JBLOCKROW)
  163139. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163140. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  163141. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  163142. coef->MCU_buffer[i] = buffer + i;
  163143. }
  163144. coef->pub.consume_data = dummy_consume_data;
  163145. coef->pub.decompress_data = decompress_onepass;
  163146. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  163147. }
  163148. }
  163149. /********* End of inlined file: jdcoefct.c *********/
  163150. #undef FIX
  163151. /********* Start of inlined file: jdcolor.c *********/
  163152. #define JPEG_INTERNALS
  163153. /* Private subobject */
  163154. typedef struct {
  163155. struct jpeg_color_deconverter pub; /* public fields */
  163156. /* Private state for YCC->RGB conversion */
  163157. int * Cr_r_tab; /* => table for Cr to R conversion */
  163158. int * Cb_b_tab; /* => table for Cb to B conversion */
  163159. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  163160. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  163161. } my_color_deconverter2;
  163162. typedef my_color_deconverter2 * my_cconvert_ptr2;
  163163. /**************** YCbCr -> RGB conversion: most common case **************/
  163164. /*
  163165. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  163166. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  163167. * The conversion equations to be implemented are therefore
  163168. * R = Y + 1.40200 * Cr
  163169. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  163170. * B = Y + 1.77200 * Cb
  163171. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  163172. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  163173. *
  163174. * To avoid floating-point arithmetic, we represent the fractional constants
  163175. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  163176. * the products by 2^16, with appropriate rounding, to get the correct answer.
  163177. * Notice that Y, being an integral input, does not contribute any fraction
  163178. * so it need not participate in the rounding.
  163179. *
  163180. * For even more speed, we avoid doing any multiplications in the inner loop
  163181. * by precalculating the constants times Cb and Cr for all possible values.
  163182. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  163183. * for 12-bit samples it is still acceptable. It's not very reasonable for
  163184. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  163185. * colorspace anyway.
  163186. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  163187. * values for the G calculation are left scaled up, since we must add them
  163188. * together before rounding.
  163189. */
  163190. #define SCALEBITS 16 /* speediest right-shift on some machines */
  163191. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  163192. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  163193. /*
  163194. * Initialize tables for YCC->RGB colorspace conversion.
  163195. */
  163196. LOCAL(void)
  163197. build_ycc_rgb_table (j_decompress_ptr cinfo)
  163198. {
  163199. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  163200. int i;
  163201. INT32 x;
  163202. SHIFT_TEMPS
  163203. cconvert->Cr_r_tab = (int *)
  163204. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163205. (MAXJSAMPLE+1) * SIZEOF(int));
  163206. cconvert->Cb_b_tab = (int *)
  163207. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163208. (MAXJSAMPLE+1) * SIZEOF(int));
  163209. cconvert->Cr_g_tab = (INT32 *)
  163210. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163211. (MAXJSAMPLE+1) * SIZEOF(INT32));
  163212. cconvert->Cb_g_tab = (INT32 *)
  163213. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163214. (MAXJSAMPLE+1) * SIZEOF(INT32));
  163215. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  163216. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  163217. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  163218. /* Cr=>R value is nearest int to 1.40200 * x */
  163219. cconvert->Cr_r_tab[i] = (int)
  163220. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  163221. /* Cb=>B value is nearest int to 1.77200 * x */
  163222. cconvert->Cb_b_tab[i] = (int)
  163223. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  163224. /* Cr=>G value is scaled-up -0.71414 * x */
  163225. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  163226. /* Cb=>G value is scaled-up -0.34414 * x */
  163227. /* We also add in ONE_HALF so that need not do it in inner loop */
  163228. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  163229. }
  163230. }
  163231. /*
  163232. * Convert some rows of samples to the output colorspace.
  163233. *
  163234. * Note that we change from noninterleaved, one-plane-per-component format
  163235. * to interleaved-pixel format. The output buffer is therefore three times
  163236. * as wide as the input buffer.
  163237. * A starting row offset is provided only for the input buffer. The caller
  163238. * can easily adjust the passed output_buf value to accommodate any row
  163239. * offset required on that side.
  163240. */
  163241. METHODDEF(void)
  163242. ycc_rgb_convert (j_decompress_ptr cinfo,
  163243. JSAMPIMAGE input_buf, JDIMENSION input_row,
  163244. JSAMPARRAY output_buf, int num_rows)
  163245. {
  163246. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  163247. register int y, cb, cr;
  163248. register JSAMPROW outptr;
  163249. register JSAMPROW inptr0, inptr1, inptr2;
  163250. register JDIMENSION col;
  163251. JDIMENSION num_cols = cinfo->output_width;
  163252. /* copy these pointers into registers if possible */
  163253. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  163254. register int * Crrtab = cconvert->Cr_r_tab;
  163255. register int * Cbbtab = cconvert->Cb_b_tab;
  163256. register INT32 * Crgtab = cconvert->Cr_g_tab;
  163257. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  163258. SHIFT_TEMPS
  163259. while (--num_rows >= 0) {
  163260. inptr0 = input_buf[0][input_row];
  163261. inptr1 = input_buf[1][input_row];
  163262. inptr2 = input_buf[2][input_row];
  163263. input_row++;
  163264. outptr = *output_buf++;
  163265. for (col = 0; col < num_cols; col++) {
  163266. y = GETJSAMPLE(inptr0[col]);
  163267. cb = GETJSAMPLE(inptr1[col]);
  163268. cr = GETJSAMPLE(inptr2[col]);
  163269. /* Range-limiting is essential due to noise introduced by DCT losses. */
  163270. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  163271. outptr[RGB_GREEN] = range_limit[y +
  163272. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  163273. SCALEBITS))];
  163274. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  163275. outptr += RGB_PIXELSIZE;
  163276. }
  163277. }
  163278. }
  163279. /**************** Cases other than YCbCr -> RGB **************/
  163280. /*
  163281. * Color conversion for no colorspace change: just copy the data,
  163282. * converting from separate-planes to interleaved representation.
  163283. */
  163284. METHODDEF(void)
  163285. null_convert2 (j_decompress_ptr cinfo,
  163286. JSAMPIMAGE input_buf, JDIMENSION input_row,
  163287. JSAMPARRAY output_buf, int num_rows)
  163288. {
  163289. register JSAMPROW inptr, outptr;
  163290. register JDIMENSION count;
  163291. register int num_components = cinfo->num_components;
  163292. JDIMENSION num_cols = cinfo->output_width;
  163293. int ci;
  163294. while (--num_rows >= 0) {
  163295. for (ci = 0; ci < num_components; ci++) {
  163296. inptr = input_buf[ci][input_row];
  163297. outptr = output_buf[0] + ci;
  163298. for (count = num_cols; count > 0; count--) {
  163299. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  163300. outptr += num_components;
  163301. }
  163302. }
  163303. input_row++;
  163304. output_buf++;
  163305. }
  163306. }
  163307. /*
  163308. * Color conversion for grayscale: just copy the data.
  163309. * This also works for YCbCr -> grayscale conversion, in which
  163310. * we just copy the Y (luminance) component and ignore chrominance.
  163311. */
  163312. METHODDEF(void)
  163313. grayscale_convert2 (j_decompress_ptr cinfo,
  163314. JSAMPIMAGE input_buf, JDIMENSION input_row,
  163315. JSAMPARRAY output_buf, int num_rows)
  163316. {
  163317. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  163318. num_rows, cinfo->output_width);
  163319. }
  163320. /*
  163321. * Convert grayscale to RGB: just duplicate the graylevel three times.
  163322. * This is provided to support applications that don't want to cope
  163323. * with grayscale as a separate case.
  163324. */
  163325. METHODDEF(void)
  163326. gray_rgb_convert (j_decompress_ptr cinfo,
  163327. JSAMPIMAGE input_buf, JDIMENSION input_row,
  163328. JSAMPARRAY output_buf, int num_rows)
  163329. {
  163330. register JSAMPROW inptr, outptr;
  163331. register JDIMENSION col;
  163332. JDIMENSION num_cols = cinfo->output_width;
  163333. while (--num_rows >= 0) {
  163334. inptr = input_buf[0][input_row++];
  163335. outptr = *output_buf++;
  163336. for (col = 0; col < num_cols; col++) {
  163337. /* We can dispense with GETJSAMPLE() here */
  163338. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  163339. outptr += RGB_PIXELSIZE;
  163340. }
  163341. }
  163342. }
  163343. /*
  163344. * Adobe-style YCCK->CMYK conversion.
  163345. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  163346. * conversion as above, while passing K (black) unchanged.
  163347. * We assume build_ycc_rgb_table has been called.
  163348. */
  163349. METHODDEF(void)
  163350. ycck_cmyk_convert (j_decompress_ptr cinfo,
  163351. JSAMPIMAGE input_buf, JDIMENSION input_row,
  163352. JSAMPARRAY output_buf, int num_rows)
  163353. {
  163354. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  163355. register int y, cb, cr;
  163356. register JSAMPROW outptr;
  163357. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  163358. register JDIMENSION col;
  163359. JDIMENSION num_cols = cinfo->output_width;
  163360. /* copy these pointers into registers if possible */
  163361. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  163362. register int * Crrtab = cconvert->Cr_r_tab;
  163363. register int * Cbbtab = cconvert->Cb_b_tab;
  163364. register INT32 * Crgtab = cconvert->Cr_g_tab;
  163365. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  163366. SHIFT_TEMPS
  163367. while (--num_rows >= 0) {
  163368. inptr0 = input_buf[0][input_row];
  163369. inptr1 = input_buf[1][input_row];
  163370. inptr2 = input_buf[2][input_row];
  163371. inptr3 = input_buf[3][input_row];
  163372. input_row++;
  163373. outptr = *output_buf++;
  163374. for (col = 0; col < num_cols; col++) {
  163375. y = GETJSAMPLE(inptr0[col]);
  163376. cb = GETJSAMPLE(inptr1[col]);
  163377. cr = GETJSAMPLE(inptr2[col]);
  163378. /* Range-limiting is essential due to noise introduced by DCT losses. */
  163379. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  163380. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  163381. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  163382. SCALEBITS)))];
  163383. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  163384. /* K passes through unchanged */
  163385. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  163386. outptr += 4;
  163387. }
  163388. }
  163389. }
  163390. /*
  163391. * Empty method for start_pass.
  163392. */
  163393. METHODDEF(void)
  163394. start_pass_dcolor (j_decompress_ptr cinfo)
  163395. {
  163396. /* no work needed */
  163397. }
  163398. /*
  163399. * Module initialization routine for output colorspace conversion.
  163400. */
  163401. GLOBAL(void)
  163402. jinit_color_deconverter (j_decompress_ptr cinfo)
  163403. {
  163404. my_cconvert_ptr2 cconvert;
  163405. int ci;
  163406. cconvert = (my_cconvert_ptr2)
  163407. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163408. SIZEOF(my_color_deconverter2));
  163409. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  163410. cconvert->pub.start_pass = start_pass_dcolor;
  163411. /* Make sure num_components agrees with jpeg_color_space */
  163412. switch (cinfo->jpeg_color_space) {
  163413. case JCS_GRAYSCALE:
  163414. if (cinfo->num_components != 1)
  163415. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  163416. break;
  163417. case JCS_RGB:
  163418. case JCS_YCbCr:
  163419. if (cinfo->num_components != 3)
  163420. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  163421. break;
  163422. case JCS_CMYK:
  163423. case JCS_YCCK:
  163424. if (cinfo->num_components != 4)
  163425. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  163426. break;
  163427. default: /* JCS_UNKNOWN can be anything */
  163428. if (cinfo->num_components < 1)
  163429. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  163430. break;
  163431. }
  163432. /* Set out_color_components and conversion method based on requested space.
  163433. * Also clear the component_needed flags for any unused components,
  163434. * so that earlier pipeline stages can avoid useless computation.
  163435. */
  163436. switch (cinfo->out_color_space) {
  163437. case JCS_GRAYSCALE:
  163438. cinfo->out_color_components = 1;
  163439. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  163440. cinfo->jpeg_color_space == JCS_YCbCr) {
  163441. cconvert->pub.color_convert = grayscale_convert2;
  163442. /* For color->grayscale conversion, only the Y (0) component is needed */
  163443. for (ci = 1; ci < cinfo->num_components; ci++)
  163444. cinfo->comp_info[ci].component_needed = FALSE;
  163445. } else
  163446. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163447. break;
  163448. case JCS_RGB:
  163449. cinfo->out_color_components = RGB_PIXELSIZE;
  163450. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  163451. cconvert->pub.color_convert = ycc_rgb_convert;
  163452. build_ycc_rgb_table(cinfo);
  163453. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  163454. cconvert->pub.color_convert = gray_rgb_convert;
  163455. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  163456. cconvert->pub.color_convert = null_convert2;
  163457. } else
  163458. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163459. break;
  163460. case JCS_CMYK:
  163461. cinfo->out_color_components = 4;
  163462. if (cinfo->jpeg_color_space == JCS_YCCK) {
  163463. cconvert->pub.color_convert = ycck_cmyk_convert;
  163464. build_ycc_rgb_table(cinfo);
  163465. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  163466. cconvert->pub.color_convert = null_convert2;
  163467. } else
  163468. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163469. break;
  163470. default:
  163471. /* Permit null conversion to same output space */
  163472. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  163473. cinfo->out_color_components = cinfo->num_components;
  163474. cconvert->pub.color_convert = null_convert2;
  163475. } else /* unsupported non-null conversion */
  163476. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163477. break;
  163478. }
  163479. if (cinfo->quantize_colors)
  163480. cinfo->output_components = 1; /* single colormapped output component */
  163481. else
  163482. cinfo->output_components = cinfo->out_color_components;
  163483. }
  163484. /********* End of inlined file: jdcolor.c *********/
  163485. #undef FIX
  163486. /********* Start of inlined file: jddctmgr.c *********/
  163487. #define JPEG_INTERNALS
  163488. /*
  163489. * The decompressor input side (jdinput.c) saves away the appropriate
  163490. * quantization table for each component at the start of the first scan
  163491. * involving that component. (This is necessary in order to correctly
  163492. * decode files that reuse Q-table slots.)
  163493. * When we are ready to make an output pass, the saved Q-table is converted
  163494. * to a multiplier table that will actually be used by the IDCT routine.
  163495. * The multiplier table contents are IDCT-method-dependent. To support
  163496. * application changes in IDCT method between scans, we can remake the
  163497. * multiplier tables if necessary.
  163498. * In buffered-image mode, the first output pass may occur before any data
  163499. * has been seen for some components, and thus before their Q-tables have
  163500. * been saved away. To handle this case, multiplier tables are preset
  163501. * to zeroes; the result of the IDCT will be a neutral gray level.
  163502. */
  163503. /* Private subobject for this module */
  163504. typedef struct {
  163505. struct jpeg_inverse_dct pub; /* public fields */
  163506. /* This array contains the IDCT method code that each multiplier table
  163507. * is currently set up for, or -1 if it's not yet set up.
  163508. * The actual multiplier tables are pointed to by dct_table in the
  163509. * per-component comp_info structures.
  163510. */
  163511. int cur_method[MAX_COMPONENTS];
  163512. } my_idct_controller;
  163513. typedef my_idct_controller * my_idct_ptr;
  163514. /* Allocated multiplier tables: big enough for any supported variant */
  163515. typedef union {
  163516. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  163517. #ifdef DCT_IFAST_SUPPORTED
  163518. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  163519. #endif
  163520. #ifdef DCT_FLOAT_SUPPORTED
  163521. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  163522. #endif
  163523. } multiplier_table;
  163524. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  163525. * so be sure to compile that code if either ISLOW or SCALING is requested.
  163526. */
  163527. #ifdef DCT_ISLOW_SUPPORTED
  163528. #define PROVIDE_ISLOW_TABLES
  163529. #else
  163530. #ifdef IDCT_SCALING_SUPPORTED
  163531. #define PROVIDE_ISLOW_TABLES
  163532. #endif
  163533. #endif
  163534. /*
  163535. * Prepare for an output pass.
  163536. * Here we select the proper IDCT routine for each component and build
  163537. * a matching multiplier table.
  163538. */
  163539. METHODDEF(void)
  163540. start_pass (j_decompress_ptr cinfo)
  163541. {
  163542. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  163543. int ci, i;
  163544. jpeg_component_info *compptr;
  163545. int method = 0;
  163546. inverse_DCT_method_ptr method_ptr = NULL;
  163547. JQUANT_TBL * qtbl;
  163548. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163549. ci++, compptr++) {
  163550. /* Select the proper IDCT routine for this component's scaling */
  163551. switch (compptr->DCT_scaled_size) {
  163552. #ifdef IDCT_SCALING_SUPPORTED
  163553. case 1:
  163554. method_ptr = jpeg_idct_1x1;
  163555. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  163556. break;
  163557. case 2:
  163558. method_ptr = jpeg_idct_2x2;
  163559. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  163560. break;
  163561. case 4:
  163562. method_ptr = jpeg_idct_4x4;
  163563. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  163564. break;
  163565. #endif
  163566. case DCTSIZE:
  163567. switch (cinfo->dct_method) {
  163568. #ifdef DCT_ISLOW_SUPPORTED
  163569. case JDCT_ISLOW:
  163570. method_ptr = jpeg_idct_islow;
  163571. method = JDCT_ISLOW;
  163572. break;
  163573. #endif
  163574. #ifdef DCT_IFAST_SUPPORTED
  163575. case JDCT_IFAST:
  163576. method_ptr = jpeg_idct_ifast;
  163577. method = JDCT_IFAST;
  163578. break;
  163579. #endif
  163580. #ifdef DCT_FLOAT_SUPPORTED
  163581. case JDCT_FLOAT:
  163582. method_ptr = jpeg_idct_float;
  163583. method = JDCT_FLOAT;
  163584. break;
  163585. #endif
  163586. default:
  163587. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163588. break;
  163589. }
  163590. break;
  163591. default:
  163592. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  163593. break;
  163594. }
  163595. idct->pub.inverse_DCT[ci] = method_ptr;
  163596. /* Create multiplier table from quant table.
  163597. * However, we can skip this if the component is uninteresting
  163598. * or if we already built the table. Also, if no quant table
  163599. * has yet been saved for the component, we leave the
  163600. * multiplier table all-zero; we'll be reading zeroes from the
  163601. * coefficient controller's buffer anyway.
  163602. */
  163603. if (! compptr->component_needed || idct->cur_method[ci] == method)
  163604. continue;
  163605. qtbl = compptr->quant_table;
  163606. if (qtbl == NULL) /* happens if no data yet for component */
  163607. continue;
  163608. idct->cur_method[ci] = method;
  163609. switch (method) {
  163610. #ifdef PROVIDE_ISLOW_TABLES
  163611. case JDCT_ISLOW:
  163612. {
  163613. /* For LL&M IDCT method, multipliers are equal to raw quantization
  163614. * coefficients, but are stored as ints to ensure access efficiency.
  163615. */
  163616. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  163617. for (i = 0; i < DCTSIZE2; i++) {
  163618. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  163619. }
  163620. }
  163621. break;
  163622. #endif
  163623. #ifdef DCT_IFAST_SUPPORTED
  163624. case JDCT_IFAST:
  163625. {
  163626. /* For AA&N IDCT method, multipliers are equal to quantization
  163627. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163628. * scalefactor[0] = 1
  163629. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163630. * For integer operation, the multiplier table is to be scaled by
  163631. * IFAST_SCALE_BITS.
  163632. */
  163633. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  163634. #define CONST_BITS 14
  163635. static const INT16 aanscales[DCTSIZE2] = {
  163636. /* precomputed values scaled up by 14 bits */
  163637. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163638. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  163639. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  163640. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  163641. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163642. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  163643. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  163644. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  163645. };
  163646. SHIFT_TEMPS
  163647. for (i = 0; i < DCTSIZE2; i++) {
  163648. ifmtbl[i] = (IFAST_MULT_TYPE)
  163649. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  163650. (INT32) aanscales[i]),
  163651. CONST_BITS-IFAST_SCALE_BITS);
  163652. }
  163653. }
  163654. break;
  163655. #endif
  163656. #ifdef DCT_FLOAT_SUPPORTED
  163657. case JDCT_FLOAT:
  163658. {
  163659. /* For float AA&N IDCT method, multipliers are equal to quantization
  163660. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163661. * scalefactor[0] = 1
  163662. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163663. */
  163664. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  163665. int row, col;
  163666. static const double aanscalefactor[DCTSIZE] = {
  163667. 1.0, 1.387039845, 1.306562965, 1.175875602,
  163668. 1.0, 0.785694958, 0.541196100, 0.275899379
  163669. };
  163670. i = 0;
  163671. for (row = 0; row < DCTSIZE; row++) {
  163672. for (col = 0; col < DCTSIZE; col++) {
  163673. fmtbl[i] = (FLOAT_MULT_TYPE)
  163674. ((double) qtbl->quantval[i] *
  163675. aanscalefactor[row] * aanscalefactor[col]);
  163676. i++;
  163677. }
  163678. }
  163679. }
  163680. break;
  163681. #endif
  163682. default:
  163683. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163684. break;
  163685. }
  163686. }
  163687. }
  163688. /*
  163689. * Initialize IDCT manager.
  163690. */
  163691. GLOBAL(void)
  163692. jinit_inverse_dct (j_decompress_ptr cinfo)
  163693. {
  163694. my_idct_ptr idct;
  163695. int ci;
  163696. jpeg_component_info *compptr;
  163697. idct = (my_idct_ptr)
  163698. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163699. SIZEOF(my_idct_controller));
  163700. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  163701. idct->pub.start_pass = start_pass;
  163702. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163703. ci++, compptr++) {
  163704. /* Allocate and pre-zero a multiplier table for each component */
  163705. compptr->dct_table =
  163706. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163707. SIZEOF(multiplier_table));
  163708. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  163709. /* Mark multiplier table not yet set up for any method */
  163710. idct->cur_method[ci] = -1;
  163711. }
  163712. }
  163713. /********* End of inlined file: jddctmgr.c *********/
  163714. #undef CONST_BITS
  163715. #undef ASSIGN_STATE
  163716. /********* Start of inlined file: jdhuff.c *********/
  163717. #define JPEG_INTERNALS
  163718. /********* Start of inlined file: jdhuff.h *********/
  163719. /* Short forms of external names for systems with brain-damaged linkers. */
  163720. #ifndef __jdhuff_h__
  163721. #define __jdhuff_h__
  163722. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163723. #define jpeg_make_d_derived_tbl jMkDDerived
  163724. #define jpeg_fill_bit_buffer jFilBitBuf
  163725. #define jpeg_huff_decode jHufDecode
  163726. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163727. /* Derived data constructed for each Huffman table */
  163728. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  163729. typedef struct {
  163730. /* Basic tables: (element [0] of each array is unused) */
  163731. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  163732. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  163733. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  163734. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  163735. * the smallest code of length k; so given a code of length k, the
  163736. * corresponding symbol is huffval[code + valoffset[k]]
  163737. */
  163738. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  163739. JHUFF_TBL *pub;
  163740. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  163741. * the input data stream. If the next Huffman code is no more
  163742. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  163743. * the corresponding symbol directly from these tables.
  163744. */
  163745. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  163746. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  163747. } d_derived_tbl;
  163748. /* Expand a Huffman table definition into the derived format */
  163749. EXTERN(void) jpeg_make_d_derived_tbl
  163750. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  163751. d_derived_tbl ** pdtbl));
  163752. /*
  163753. * Fetching the next N bits from the input stream is a time-critical operation
  163754. * for the Huffman decoders. We implement it with a combination of inline
  163755. * macros and out-of-line subroutines. Note that N (the number of bits
  163756. * demanded at one time) never exceeds 15 for JPEG use.
  163757. *
  163758. * We read source bytes into get_buffer and dole out bits as needed.
  163759. * If get_buffer already contains enough bits, they are fetched in-line
  163760. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  163761. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  163762. * as full as possible (not just to the number of bits needed; this
  163763. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  163764. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  163765. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  163766. * at least the requested number of bits --- dummy zeroes are inserted if
  163767. * necessary.
  163768. */
  163769. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  163770. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  163771. /* If long is > 32 bits on your machine, and shifting/masking longs is
  163772. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  163773. * appropriately should be a win. Unfortunately we can't define the size
  163774. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  163775. * because not all machines measure sizeof in 8-bit bytes.
  163776. */
  163777. typedef struct { /* Bitreading state saved across MCUs */
  163778. bit_buf_type get_buffer; /* current bit-extraction buffer */
  163779. int bits_left; /* # of unused bits in it */
  163780. } bitread_perm_state;
  163781. typedef struct { /* Bitreading working state within an MCU */
  163782. /* Current data source location */
  163783. /* We need a copy, rather than munging the original, in case of suspension */
  163784. const JOCTET * next_input_byte; /* => next byte to read from source */
  163785. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  163786. /* Bit input buffer --- note these values are kept in register variables,
  163787. * not in this struct, inside the inner loops.
  163788. */
  163789. bit_buf_type get_buffer; /* current bit-extraction buffer */
  163790. int bits_left; /* # of unused bits in it */
  163791. /* Pointer needed by jpeg_fill_bit_buffer. */
  163792. j_decompress_ptr cinfo; /* back link to decompress master record */
  163793. } bitread_working_state;
  163794. /* Macros to declare and load/save bitread local variables. */
  163795. #define BITREAD_STATE_VARS \
  163796. register bit_buf_type get_buffer; \
  163797. register int bits_left; \
  163798. bitread_working_state br_state
  163799. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  163800. br_state.cinfo = cinfop; \
  163801. br_state.next_input_byte = cinfop->src->next_input_byte; \
  163802. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  163803. get_buffer = permstate.get_buffer; \
  163804. bits_left = permstate.bits_left;
  163805. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  163806. cinfop->src->next_input_byte = br_state.next_input_byte; \
  163807. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  163808. permstate.get_buffer = get_buffer; \
  163809. permstate.bits_left = bits_left
  163810. /*
  163811. * These macros provide the in-line portion of bit fetching.
  163812. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  163813. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  163814. * The variables get_buffer and bits_left are assumed to be locals,
  163815. * but the state struct might not be (jpeg_huff_decode needs this).
  163816. * CHECK_BIT_BUFFER(state,n,action);
  163817. * Ensure there are N bits in get_buffer; if suspend, take action.
  163818. * val = GET_BITS(n);
  163819. * Fetch next N bits.
  163820. * val = PEEK_BITS(n);
  163821. * Fetch next N bits without removing them from the buffer.
  163822. * DROP_BITS(n);
  163823. * Discard next N bits.
  163824. * The value N should be a simple variable, not an expression, because it
  163825. * is evaluated multiple times.
  163826. */
  163827. #define CHECK_BIT_BUFFER(state,nbits,action) \
  163828. { if (bits_left < (nbits)) { \
  163829. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  163830. { action; } \
  163831. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  163832. #define GET_BITS(nbits) \
  163833. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  163834. #define PEEK_BITS(nbits) \
  163835. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  163836. #define DROP_BITS(nbits) \
  163837. (bits_left -= (nbits))
  163838. /* Load up the bit buffer to a depth of at least nbits */
  163839. EXTERN(boolean) jpeg_fill_bit_buffer
  163840. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  163841. register int bits_left, int nbits));
  163842. /*
  163843. * Code for extracting next Huffman-coded symbol from input bit stream.
  163844. * Again, this is time-critical and we make the main paths be macros.
  163845. *
  163846. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  163847. * without looping. Usually, more than 95% of the Huffman codes will be 8
  163848. * or fewer bits long. The few overlength codes are handled with a loop,
  163849. * which need not be inline code.
  163850. *
  163851. * Notes about the HUFF_DECODE macro:
  163852. * 1. Near the end of the data segment, we may fail to get enough bits
  163853. * for a lookahead. In that case, we do it the hard way.
  163854. * 2. If the lookahead table contains no entry, the next code must be
  163855. * more than HUFF_LOOKAHEAD bits long.
  163856. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  163857. */
  163858. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  163859. { register int nb, look; \
  163860. if (bits_left < HUFF_LOOKAHEAD) { \
  163861. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  163862. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  163863. if (bits_left < HUFF_LOOKAHEAD) { \
  163864. nb = 1; goto slowlabel; \
  163865. } \
  163866. } \
  163867. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  163868. if ((nb = htbl->look_nbits[look]) != 0) { \
  163869. DROP_BITS(nb); \
  163870. result = htbl->look_sym[look]; \
  163871. } else { \
  163872. nb = HUFF_LOOKAHEAD+1; \
  163873. slowlabel: \
  163874. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  163875. { failaction; } \
  163876. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  163877. } \
  163878. }
  163879. /* Out-of-line case for Huffman code fetching */
  163880. EXTERN(int) jpeg_huff_decode
  163881. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  163882. register int bits_left, d_derived_tbl * htbl, int min_bits));
  163883. #endif
  163884. /********* End of inlined file: jdhuff.h *********/
  163885. /* Declarations shared with jdphuff.c */
  163886. /*
  163887. * Expanded entropy decoder object for Huffman decoding.
  163888. *
  163889. * The savable_state subrecord contains fields that change within an MCU,
  163890. * but must not be updated permanently until we complete the MCU.
  163891. */
  163892. typedef struct {
  163893. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163894. } savable_state2;
  163895. /* This macro is to work around compilers with missing or broken
  163896. * structure assignment. You'll need to fix this code if you have
  163897. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163898. */
  163899. #ifndef NO_STRUCT_ASSIGN
  163900. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163901. #else
  163902. #if MAX_COMPS_IN_SCAN == 4
  163903. #define ASSIGN_STATE(dest,src) \
  163904. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  163905. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163906. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163907. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163908. #endif
  163909. #endif
  163910. typedef struct {
  163911. struct jpeg_entropy_decoder pub; /* public fields */
  163912. /* These fields are loaded into local variables at start of each MCU.
  163913. * In case of suspension, we exit WITHOUT updating them.
  163914. */
  163915. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  163916. savable_state2 saved; /* Other state at start of MCU */
  163917. /* These fields are NOT loaded into local working state. */
  163918. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163919. /* Pointers to derived tables (these workspaces have image lifespan) */
  163920. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163921. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163922. /* Precalculated info set up by start_pass for use in decode_mcu: */
  163923. /* Pointers to derived tables to be used for each block within an MCU */
  163924. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  163925. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  163926. /* Whether we care about the DC and AC coefficient values for each block */
  163927. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  163928. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  163929. } huff_entropy_decoder2;
  163930. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  163931. /*
  163932. * Initialize for a Huffman-compressed scan.
  163933. */
  163934. METHODDEF(void)
  163935. start_pass_huff_decoder (j_decompress_ptr cinfo)
  163936. {
  163937. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  163938. int ci, blkn, dctbl, actbl;
  163939. jpeg_component_info * compptr;
  163940. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  163941. * This ought to be an error condition, but we make it a warning because
  163942. * there are some baseline files out there with all zeroes in these bytes.
  163943. */
  163944. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  163945. cinfo->Ah != 0 || cinfo->Al != 0)
  163946. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  163947. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163948. compptr = cinfo->cur_comp_info[ci];
  163949. dctbl = compptr->dc_tbl_no;
  163950. actbl = compptr->ac_tbl_no;
  163951. /* Compute derived values for Huffman tables */
  163952. /* We may do this more than once for a table, but it's not expensive */
  163953. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  163954. & entropy->dc_derived_tbls[dctbl]);
  163955. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  163956. & entropy->ac_derived_tbls[actbl]);
  163957. /* Initialize DC predictions to 0 */
  163958. entropy->saved.last_dc_val[ci] = 0;
  163959. }
  163960. /* Precalculate decoding info for each block in an MCU of this scan */
  163961. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163962. ci = cinfo->MCU_membership[blkn];
  163963. compptr = cinfo->cur_comp_info[ci];
  163964. /* Precalculate which table to use for each block */
  163965. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  163966. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  163967. /* Decide whether we really care about the coefficient values */
  163968. if (compptr->component_needed) {
  163969. entropy->dc_needed[blkn] = TRUE;
  163970. /* we don't need the ACs if producing a 1/8th-size image */
  163971. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  163972. } else {
  163973. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  163974. }
  163975. }
  163976. /* Initialize bitread state variables */
  163977. entropy->bitstate.bits_left = 0;
  163978. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  163979. entropy->pub.insufficient_data = FALSE;
  163980. /* Initialize restart counter */
  163981. entropy->restarts_to_go = cinfo->restart_interval;
  163982. }
  163983. /*
  163984. * Compute the derived values for a Huffman table.
  163985. * This routine also performs some validation checks on the table.
  163986. *
  163987. * Note this is also used by jdphuff.c.
  163988. */
  163989. GLOBAL(void)
  163990. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  163991. d_derived_tbl ** pdtbl)
  163992. {
  163993. JHUFF_TBL *htbl;
  163994. d_derived_tbl *dtbl;
  163995. int p, i, l, si, numsymbols;
  163996. int lookbits, ctr;
  163997. char huffsize[257];
  163998. unsigned int huffcode[257];
  163999. unsigned int code;
  164000. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  164001. * paralleling the order of the symbols themselves in htbl->huffval[].
  164002. */
  164003. /* Find the input Huffman table */
  164004. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  164005. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  164006. htbl =
  164007. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  164008. if (htbl == NULL)
  164009. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  164010. /* Allocate a workspace if we haven't already done so. */
  164011. if (*pdtbl == NULL)
  164012. *pdtbl = (d_derived_tbl *)
  164013. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164014. SIZEOF(d_derived_tbl));
  164015. dtbl = *pdtbl;
  164016. dtbl->pub = htbl; /* fill in back link */
  164017. /* Figure C.1: make table of Huffman code length for each symbol */
  164018. p = 0;
  164019. for (l = 1; l <= 16; l++) {
  164020. i = (int) htbl->bits[l];
  164021. if (i < 0 || p + i > 256) /* protect against table overrun */
  164022. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164023. while (i--)
  164024. huffsize[p++] = (char) l;
  164025. }
  164026. huffsize[p] = 0;
  164027. numsymbols = p;
  164028. /* Figure C.2: generate the codes themselves */
  164029. /* We also validate that the counts represent a legal Huffman code tree. */
  164030. code = 0;
  164031. si = huffsize[0];
  164032. p = 0;
  164033. while (huffsize[p]) {
  164034. while (((int) huffsize[p]) == si) {
  164035. huffcode[p++] = code;
  164036. code++;
  164037. }
  164038. /* code is now 1 more than the last code used for codelength si; but
  164039. * it must still fit in si bits, since no code is allowed to be all ones.
  164040. */
  164041. if (((INT32) code) >= (((INT32) 1) << si))
  164042. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164043. code <<= 1;
  164044. si++;
  164045. }
  164046. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  164047. p = 0;
  164048. for (l = 1; l <= 16; l++) {
  164049. if (htbl->bits[l]) {
  164050. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  164051. * minus the minimum code of length l
  164052. */
  164053. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  164054. p += htbl->bits[l];
  164055. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  164056. } else {
  164057. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  164058. }
  164059. }
  164060. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  164061. /* Compute lookahead tables to speed up decoding.
  164062. * First we set all the table entries to 0, indicating "too long";
  164063. * then we iterate through the Huffman codes that are short enough and
  164064. * fill in all the entries that correspond to bit sequences starting
  164065. * with that code.
  164066. */
  164067. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  164068. p = 0;
  164069. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  164070. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  164071. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  164072. /* Generate left-justified code followed by all possible bit sequences */
  164073. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  164074. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  164075. dtbl->look_nbits[lookbits] = l;
  164076. dtbl->look_sym[lookbits] = htbl->huffval[p];
  164077. lookbits++;
  164078. }
  164079. }
  164080. }
  164081. /* Validate symbols as being reasonable.
  164082. * For AC tables, we make no check, but accept all byte values 0..255.
  164083. * For DC tables, we require the symbols to be in range 0..15.
  164084. * (Tighter bounds could be applied depending on the data depth and mode,
  164085. * but this is sufficient to ensure safe decoding.)
  164086. */
  164087. if (isDC) {
  164088. for (i = 0; i < numsymbols; i++) {
  164089. int sym = htbl->huffval[i];
  164090. if (sym < 0 || sym > 15)
  164091. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164092. }
  164093. }
  164094. }
  164095. /*
  164096. * Out-of-line code for bit fetching (shared with jdphuff.c).
  164097. * See jdhuff.h for info about usage.
  164098. * Note: current values of get_buffer and bits_left are passed as parameters,
  164099. * but are returned in the corresponding fields of the state struct.
  164100. *
  164101. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  164102. * of get_buffer to be used. (On machines with wider words, an even larger
  164103. * buffer could be used.) However, on some machines 32-bit shifts are
  164104. * quite slow and take time proportional to the number of places shifted.
  164105. * (This is true with most PC compilers, for instance.) In this case it may
  164106. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  164107. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  164108. */
  164109. #ifdef SLOW_SHIFT_32
  164110. #define MIN_GET_BITS 15 /* minimum allowable value */
  164111. #else
  164112. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  164113. #endif
  164114. GLOBAL(boolean)
  164115. jpeg_fill_bit_buffer (bitread_working_state * state,
  164116. register bit_buf_type get_buffer, register int bits_left,
  164117. int nbits)
  164118. /* Load up the bit buffer to a depth of at least nbits */
  164119. {
  164120. /* Copy heavily used state fields into locals (hopefully registers) */
  164121. register const JOCTET * next_input_byte = state->next_input_byte;
  164122. register size_t bytes_in_buffer = state->bytes_in_buffer;
  164123. j_decompress_ptr cinfo = state->cinfo;
  164124. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  164125. /* (It is assumed that no request will be for more than that many bits.) */
  164126. /* We fail to do so only if we hit a marker or are forced to suspend. */
  164127. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  164128. while (bits_left < MIN_GET_BITS) {
  164129. register int c;
  164130. /* Attempt to read a byte */
  164131. if (bytes_in_buffer == 0) {
  164132. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  164133. return FALSE;
  164134. next_input_byte = cinfo->src->next_input_byte;
  164135. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  164136. }
  164137. bytes_in_buffer--;
  164138. c = GETJOCTET(*next_input_byte++);
  164139. /* If it's 0xFF, check and discard stuffed zero byte */
  164140. if (c == 0xFF) {
  164141. /* Loop here to discard any padding FF's on terminating marker,
  164142. * so that we can save a valid unread_marker value. NOTE: we will
  164143. * accept multiple FF's followed by a 0 as meaning a single FF data
  164144. * byte. This data pattern is not valid according to the standard.
  164145. */
  164146. do {
  164147. if (bytes_in_buffer == 0) {
  164148. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  164149. return FALSE;
  164150. next_input_byte = cinfo->src->next_input_byte;
  164151. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  164152. }
  164153. bytes_in_buffer--;
  164154. c = GETJOCTET(*next_input_byte++);
  164155. } while (c == 0xFF);
  164156. if (c == 0) {
  164157. /* Found FF/00, which represents an FF data byte */
  164158. c = 0xFF;
  164159. } else {
  164160. /* Oops, it's actually a marker indicating end of compressed data.
  164161. * Save the marker code for later use.
  164162. * Fine point: it might appear that we should save the marker into
  164163. * bitread working state, not straight into permanent state. But
  164164. * once we have hit a marker, we cannot need to suspend within the
  164165. * current MCU, because we will read no more bytes from the data
  164166. * source. So it is OK to update permanent state right away.
  164167. */
  164168. cinfo->unread_marker = c;
  164169. /* See if we need to insert some fake zero bits. */
  164170. goto no_more_bytes;
  164171. }
  164172. }
  164173. /* OK, load c into get_buffer */
  164174. get_buffer = (get_buffer << 8) | c;
  164175. bits_left += 8;
  164176. } /* end while */
  164177. } else {
  164178. no_more_bytes:
  164179. /* We get here if we've read the marker that terminates the compressed
  164180. * data segment. There should be enough bits in the buffer register
  164181. * to satisfy the request; if so, no problem.
  164182. */
  164183. if (nbits > bits_left) {
  164184. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  164185. * the data stream, so that we can produce some kind of image.
  164186. * We use a nonvolatile flag to ensure that only one warning message
  164187. * appears per data segment.
  164188. */
  164189. if (! cinfo->entropy->insufficient_data) {
  164190. WARNMS(cinfo, JWRN_HIT_MARKER);
  164191. cinfo->entropy->insufficient_data = TRUE;
  164192. }
  164193. /* Fill the buffer with zero bits */
  164194. get_buffer <<= MIN_GET_BITS - bits_left;
  164195. bits_left = MIN_GET_BITS;
  164196. }
  164197. }
  164198. /* Unload the local registers */
  164199. state->next_input_byte = next_input_byte;
  164200. state->bytes_in_buffer = bytes_in_buffer;
  164201. state->get_buffer = get_buffer;
  164202. state->bits_left = bits_left;
  164203. return TRUE;
  164204. }
  164205. /*
  164206. * Out-of-line code for Huffman code decoding.
  164207. * See jdhuff.h for info about usage.
  164208. */
  164209. GLOBAL(int)
  164210. jpeg_huff_decode (bitread_working_state * state,
  164211. register bit_buf_type get_buffer, register int bits_left,
  164212. d_derived_tbl * htbl, int min_bits)
  164213. {
  164214. register int l = min_bits;
  164215. register INT32 code;
  164216. /* HUFF_DECODE has determined that the code is at least min_bits */
  164217. /* bits long, so fetch that many bits in one swoop. */
  164218. CHECK_BIT_BUFFER(*state, l, return -1);
  164219. code = GET_BITS(l);
  164220. /* Collect the rest of the Huffman code one bit at a time. */
  164221. /* This is per Figure F.16 in the JPEG spec. */
  164222. while (code > htbl->maxcode[l]) {
  164223. code <<= 1;
  164224. CHECK_BIT_BUFFER(*state, 1, return -1);
  164225. code |= GET_BITS(1);
  164226. l++;
  164227. }
  164228. /* Unload the local registers */
  164229. state->get_buffer = get_buffer;
  164230. state->bits_left = bits_left;
  164231. /* With garbage input we may reach the sentinel value l = 17. */
  164232. if (l > 16) {
  164233. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  164234. return 0; /* fake a zero as the safest result */
  164235. }
  164236. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  164237. }
  164238. /*
  164239. * Check for a restart marker & resynchronize decoder.
  164240. * Returns FALSE if must suspend.
  164241. */
  164242. LOCAL(boolean)
  164243. process_restart (j_decompress_ptr cinfo)
  164244. {
  164245. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  164246. int ci;
  164247. /* Throw away any unused bits remaining in bit buffer; */
  164248. /* include any full bytes in next_marker's count of discarded bytes */
  164249. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  164250. entropy->bitstate.bits_left = 0;
  164251. /* Advance past the RSTn marker */
  164252. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  164253. return FALSE;
  164254. /* Re-initialize DC predictions to 0 */
  164255. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  164256. entropy->saved.last_dc_val[ci] = 0;
  164257. /* Reset restart counter */
  164258. entropy->restarts_to_go = cinfo->restart_interval;
  164259. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  164260. * against a marker. In that case we will end up treating the next data
  164261. * segment as empty, and we can avoid producing bogus output pixels by
  164262. * leaving the flag set.
  164263. */
  164264. if (cinfo->unread_marker == 0)
  164265. entropy->pub.insufficient_data = FALSE;
  164266. return TRUE;
  164267. }
  164268. /*
  164269. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  164270. * The coefficients are reordered from zigzag order into natural array order,
  164271. * but are not dequantized.
  164272. *
  164273. * The i'th block of the MCU is stored into the block pointed to by
  164274. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  164275. * (Wholesale zeroing is usually a little faster than retail...)
  164276. *
  164277. * Returns FALSE if data source requested suspension. In that case no
  164278. * changes have been made to permanent state. (Exception: some output
  164279. * coefficients may already have been assigned. This is harmless for
  164280. * this module, since we'll just re-assign them on the next call.)
  164281. */
  164282. METHODDEF(boolean)
  164283. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  164284. {
  164285. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  164286. int blkn;
  164287. BITREAD_STATE_VARS;
  164288. savable_state2 state;
  164289. /* Process restart marker if needed; may have to suspend */
  164290. if (cinfo->restart_interval) {
  164291. if (entropy->restarts_to_go == 0)
  164292. if (! process_restart(cinfo))
  164293. return FALSE;
  164294. }
  164295. /* If we've run out of data, just leave the MCU set to zeroes.
  164296. * This way, we return uniform gray for the remainder of the segment.
  164297. */
  164298. if (! entropy->pub.insufficient_data) {
  164299. /* Load up working state */
  164300. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  164301. ASSIGN_STATE(state, entropy->saved);
  164302. /* Outer loop handles each block in the MCU */
  164303. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  164304. JBLOCKROW block = MCU_data[blkn];
  164305. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  164306. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  164307. register int s, k, r;
  164308. /* Decode a single block's worth of coefficients */
  164309. /* Section F.2.2.1: decode the DC coefficient difference */
  164310. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  164311. if (s) {
  164312. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  164313. r = GET_BITS(s);
  164314. s = HUFF_EXTEND(r, s);
  164315. }
  164316. if (entropy->dc_needed[blkn]) {
  164317. /* Convert DC difference to actual value, update last_dc_val */
  164318. int ci = cinfo->MCU_membership[blkn];
  164319. s += state.last_dc_val[ci];
  164320. state.last_dc_val[ci] = s;
  164321. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  164322. (*block)[0] = (JCOEF) s;
  164323. }
  164324. if (entropy->ac_needed[blkn]) {
  164325. /* Section F.2.2.2: decode the AC coefficients */
  164326. /* Since zeroes are skipped, output area must be cleared beforehand */
  164327. for (k = 1; k < DCTSIZE2; k++) {
  164328. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  164329. r = s >> 4;
  164330. s &= 15;
  164331. if (s) {
  164332. k += r;
  164333. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  164334. r = GET_BITS(s);
  164335. s = HUFF_EXTEND(r, s);
  164336. /* Output coefficient in natural (dezigzagged) order.
  164337. * Note: the extra entries in jpeg_natural_order[] will save us
  164338. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  164339. */
  164340. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  164341. } else {
  164342. if (r != 15)
  164343. break;
  164344. k += 15;
  164345. }
  164346. }
  164347. } else {
  164348. /* Section F.2.2.2: decode the AC coefficients */
  164349. /* In this path we just discard the values */
  164350. for (k = 1; k < DCTSIZE2; k++) {
  164351. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  164352. r = s >> 4;
  164353. s &= 15;
  164354. if (s) {
  164355. k += r;
  164356. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  164357. DROP_BITS(s);
  164358. } else {
  164359. if (r != 15)
  164360. break;
  164361. k += 15;
  164362. }
  164363. }
  164364. }
  164365. }
  164366. /* Completed MCU, so update state */
  164367. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  164368. ASSIGN_STATE(entropy->saved, state);
  164369. }
  164370. /* Account for restart interval (no-op if not using restarts) */
  164371. entropy->restarts_to_go--;
  164372. return TRUE;
  164373. }
  164374. /*
  164375. * Module initialization routine for Huffman entropy decoding.
  164376. */
  164377. GLOBAL(void)
  164378. jinit_huff_decoder (j_decompress_ptr cinfo)
  164379. {
  164380. huff_entropy_ptr2 entropy;
  164381. int i;
  164382. entropy = (huff_entropy_ptr2)
  164383. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164384. SIZEOF(huff_entropy_decoder2));
  164385. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  164386. entropy->pub.start_pass = start_pass_huff_decoder;
  164387. entropy->pub.decode_mcu = decode_mcu;
  164388. /* Mark tables unallocated */
  164389. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164390. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  164391. }
  164392. }
  164393. /********* End of inlined file: jdhuff.c *********/
  164394. /********* Start of inlined file: jdinput.c *********/
  164395. #define JPEG_INTERNALS
  164396. /* Private state */
  164397. typedef struct {
  164398. struct jpeg_input_controller pub; /* public fields */
  164399. boolean inheaders; /* TRUE until first SOS is reached */
  164400. } my_input_controller;
  164401. typedef my_input_controller * my_inputctl_ptr;
  164402. /* Forward declarations */
  164403. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  164404. /*
  164405. * Routines to calculate various quantities related to the size of the image.
  164406. */
  164407. LOCAL(void)
  164408. initial_setup2 (j_decompress_ptr cinfo)
  164409. /* Called once, when first SOS marker is reached */
  164410. {
  164411. int ci;
  164412. jpeg_component_info *compptr;
  164413. /* Make sure image isn't bigger than I can handle */
  164414. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164415. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164416. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164417. /* For now, precision must match compiled-in value... */
  164418. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164419. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164420. /* Check that number of components won't exceed internal array sizes */
  164421. if (cinfo->num_components > MAX_COMPONENTS)
  164422. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164423. MAX_COMPONENTS);
  164424. /* Compute maximum sampling factors; check factor validity */
  164425. cinfo->max_h_samp_factor = 1;
  164426. cinfo->max_v_samp_factor = 1;
  164427. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164428. ci++, compptr++) {
  164429. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164430. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164431. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164432. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164433. compptr->h_samp_factor);
  164434. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164435. compptr->v_samp_factor);
  164436. }
  164437. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  164438. * In the full decompressor, this will be overridden by jdmaster.c;
  164439. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  164440. */
  164441. cinfo->min_DCT_scaled_size = DCTSIZE;
  164442. /* Compute dimensions of components */
  164443. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164444. ci++, compptr++) {
  164445. compptr->DCT_scaled_size = DCTSIZE;
  164446. /* Size in DCT blocks */
  164447. compptr->width_in_blocks = (JDIMENSION)
  164448. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164449. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164450. compptr->height_in_blocks = (JDIMENSION)
  164451. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164452. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164453. /* downsampled_width and downsampled_height will also be overridden by
  164454. * jdmaster.c if we are doing full decompression. The transcoder library
  164455. * doesn't use these values, but the calling application might.
  164456. */
  164457. /* Size in samples */
  164458. compptr->downsampled_width = (JDIMENSION)
  164459. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164460. (long) cinfo->max_h_samp_factor);
  164461. compptr->downsampled_height = (JDIMENSION)
  164462. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164463. (long) cinfo->max_v_samp_factor);
  164464. /* Mark component needed, until color conversion says otherwise */
  164465. compptr->component_needed = TRUE;
  164466. /* Mark no quantization table yet saved for component */
  164467. compptr->quant_table = NULL;
  164468. }
  164469. /* Compute number of fully interleaved MCU rows. */
  164470. cinfo->total_iMCU_rows = (JDIMENSION)
  164471. jdiv_round_up((long) cinfo->image_height,
  164472. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164473. /* Decide whether file contains multiple scans */
  164474. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  164475. cinfo->inputctl->has_multiple_scans = TRUE;
  164476. else
  164477. cinfo->inputctl->has_multiple_scans = FALSE;
  164478. }
  164479. LOCAL(void)
  164480. per_scan_setup2 (j_decompress_ptr cinfo)
  164481. /* Do computations that are needed before processing a JPEG scan */
  164482. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  164483. {
  164484. int ci, mcublks, tmp;
  164485. jpeg_component_info *compptr;
  164486. if (cinfo->comps_in_scan == 1) {
  164487. /* Noninterleaved (single-component) scan */
  164488. compptr = cinfo->cur_comp_info[0];
  164489. /* Overall image size in MCUs */
  164490. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164491. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164492. /* For noninterleaved scan, always one block per MCU */
  164493. compptr->MCU_width = 1;
  164494. compptr->MCU_height = 1;
  164495. compptr->MCU_blocks = 1;
  164496. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  164497. compptr->last_col_width = 1;
  164498. /* For noninterleaved scans, it is convenient to define last_row_height
  164499. * as the number of block rows present in the last iMCU row.
  164500. */
  164501. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164502. if (tmp == 0) tmp = compptr->v_samp_factor;
  164503. compptr->last_row_height = tmp;
  164504. /* Prepare array describing MCU composition */
  164505. cinfo->blocks_in_MCU = 1;
  164506. cinfo->MCU_membership[0] = 0;
  164507. } else {
  164508. /* Interleaved (multi-component) scan */
  164509. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164510. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164511. MAX_COMPS_IN_SCAN);
  164512. /* Overall image size in MCUs */
  164513. cinfo->MCUs_per_row = (JDIMENSION)
  164514. jdiv_round_up((long) cinfo->image_width,
  164515. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164516. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164517. jdiv_round_up((long) cinfo->image_height,
  164518. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164519. cinfo->blocks_in_MCU = 0;
  164520. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164521. compptr = cinfo->cur_comp_info[ci];
  164522. /* Sampling factors give # of blocks of component in each MCU */
  164523. compptr->MCU_width = compptr->h_samp_factor;
  164524. compptr->MCU_height = compptr->v_samp_factor;
  164525. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164526. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  164527. /* Figure number of non-dummy blocks in last MCU column & row */
  164528. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164529. if (tmp == 0) tmp = compptr->MCU_width;
  164530. compptr->last_col_width = tmp;
  164531. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164532. if (tmp == 0) tmp = compptr->MCU_height;
  164533. compptr->last_row_height = tmp;
  164534. /* Prepare array describing MCU composition */
  164535. mcublks = compptr->MCU_blocks;
  164536. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  164537. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164538. while (mcublks-- > 0) {
  164539. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164540. }
  164541. }
  164542. }
  164543. }
  164544. /*
  164545. * Save away a copy of the Q-table referenced by each component present
  164546. * in the current scan, unless already saved during a prior scan.
  164547. *
  164548. * In a multiple-scan JPEG file, the encoder could assign different components
  164549. * the same Q-table slot number, but change table definitions between scans
  164550. * so that each component uses a different Q-table. (The IJG encoder is not
  164551. * currently capable of doing this, but other encoders might.) Since we want
  164552. * to be able to dequantize all the components at the end of the file, this
  164553. * means that we have to save away the table actually used for each component.
  164554. * We do this by copying the table at the start of the first scan containing
  164555. * the component.
  164556. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  164557. * slot between scans of a component using that slot. If the encoder does so
  164558. * anyway, this decoder will simply use the Q-table values that were current
  164559. * at the start of the first scan for the component.
  164560. *
  164561. * The decompressor output side looks only at the saved quant tables,
  164562. * not at the current Q-table slots.
  164563. */
  164564. LOCAL(void)
  164565. latch_quant_tables (j_decompress_ptr cinfo)
  164566. {
  164567. int ci, qtblno;
  164568. jpeg_component_info *compptr;
  164569. JQUANT_TBL * qtbl;
  164570. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164571. compptr = cinfo->cur_comp_info[ci];
  164572. /* No work if we already saved Q-table for this component */
  164573. if (compptr->quant_table != NULL)
  164574. continue;
  164575. /* Make sure specified quantization table is present */
  164576. qtblno = compptr->quant_tbl_no;
  164577. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  164578. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  164579. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  164580. /* OK, save away the quantization table */
  164581. qtbl = (JQUANT_TBL *)
  164582. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164583. SIZEOF(JQUANT_TBL));
  164584. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  164585. compptr->quant_table = qtbl;
  164586. }
  164587. }
  164588. /*
  164589. * Initialize the input modules to read a scan of compressed data.
  164590. * The first call to this is done by jdmaster.c after initializing
  164591. * the entire decompressor (during jpeg_start_decompress).
  164592. * Subsequent calls come from consume_markers, below.
  164593. */
  164594. METHODDEF(void)
  164595. start_input_pass2 (j_decompress_ptr cinfo)
  164596. {
  164597. per_scan_setup2(cinfo);
  164598. latch_quant_tables(cinfo);
  164599. (*cinfo->entropy->start_pass) (cinfo);
  164600. (*cinfo->coef->start_input_pass) (cinfo);
  164601. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  164602. }
  164603. /*
  164604. * Finish up after inputting a compressed-data scan.
  164605. * This is called by the coefficient controller after it's read all
  164606. * the expected data of the scan.
  164607. */
  164608. METHODDEF(void)
  164609. finish_input_pass (j_decompress_ptr cinfo)
  164610. {
  164611. cinfo->inputctl->consume_input = consume_markers;
  164612. }
  164613. /*
  164614. * Read JPEG markers before, between, or after compressed-data scans.
  164615. * Change state as necessary when a new scan is reached.
  164616. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  164617. *
  164618. * The consume_input method pointer points either here or to the
  164619. * coefficient controller's consume_data routine, depending on whether
  164620. * we are reading a compressed data segment or inter-segment markers.
  164621. */
  164622. METHODDEF(int)
  164623. consume_markers (j_decompress_ptr cinfo)
  164624. {
  164625. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  164626. int val;
  164627. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  164628. return JPEG_REACHED_EOI;
  164629. val = (*cinfo->marker->read_markers) (cinfo);
  164630. switch (val) {
  164631. case JPEG_REACHED_SOS: /* Found SOS */
  164632. if (inputctl->inheaders) { /* 1st SOS */
  164633. initial_setup2(cinfo);
  164634. inputctl->inheaders = FALSE;
  164635. /* Note: start_input_pass must be called by jdmaster.c
  164636. * before any more input can be consumed. jdapimin.c is
  164637. * responsible for enforcing this sequencing.
  164638. */
  164639. } else { /* 2nd or later SOS marker */
  164640. if (! inputctl->pub.has_multiple_scans)
  164641. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  164642. start_input_pass2(cinfo);
  164643. }
  164644. break;
  164645. case JPEG_REACHED_EOI: /* Found EOI */
  164646. inputctl->pub.eoi_reached = TRUE;
  164647. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  164648. if (cinfo->marker->saw_SOF)
  164649. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  164650. } else {
  164651. /* Prevent infinite loop in coef ctlr's decompress_data routine
  164652. * if user set output_scan_number larger than number of scans.
  164653. */
  164654. if (cinfo->output_scan_number > cinfo->input_scan_number)
  164655. cinfo->output_scan_number = cinfo->input_scan_number;
  164656. }
  164657. break;
  164658. case JPEG_SUSPENDED:
  164659. break;
  164660. }
  164661. return val;
  164662. }
  164663. /*
  164664. * Reset state to begin a fresh datastream.
  164665. */
  164666. METHODDEF(void)
  164667. reset_input_controller (j_decompress_ptr cinfo)
  164668. {
  164669. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  164670. inputctl->pub.consume_input = consume_markers;
  164671. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  164672. inputctl->pub.eoi_reached = FALSE;
  164673. inputctl->inheaders = TRUE;
  164674. /* Reset other modules */
  164675. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  164676. (*cinfo->marker->reset_marker_reader) (cinfo);
  164677. /* Reset progression state -- would be cleaner if entropy decoder did this */
  164678. cinfo->coef_bits = NULL;
  164679. }
  164680. /*
  164681. * Initialize the input controller module.
  164682. * This is called only once, when the decompression object is created.
  164683. */
  164684. GLOBAL(void)
  164685. jinit_input_controller (j_decompress_ptr cinfo)
  164686. {
  164687. my_inputctl_ptr inputctl;
  164688. /* Create subobject in permanent pool */
  164689. inputctl = (my_inputctl_ptr)
  164690. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164691. SIZEOF(my_input_controller));
  164692. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  164693. /* Initialize method pointers */
  164694. inputctl->pub.consume_input = consume_markers;
  164695. inputctl->pub.reset_input_controller = reset_input_controller;
  164696. inputctl->pub.start_input_pass = start_input_pass2;
  164697. inputctl->pub.finish_input_pass = finish_input_pass;
  164698. /* Initialize state: can't use reset_input_controller since we don't
  164699. * want to try to reset other modules yet.
  164700. */
  164701. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  164702. inputctl->pub.eoi_reached = FALSE;
  164703. inputctl->inheaders = TRUE;
  164704. }
  164705. /********* End of inlined file: jdinput.c *********/
  164706. /********* Start of inlined file: jdmainct.c *********/
  164707. #define JPEG_INTERNALS
  164708. /*
  164709. * In the current system design, the main buffer need never be a full-image
  164710. * buffer; any full-height buffers will be found inside the coefficient or
  164711. * postprocessing controllers. Nonetheless, the main controller is not
  164712. * trivial. Its responsibility is to provide context rows for upsampling/
  164713. * rescaling, and doing this in an efficient fashion is a bit tricky.
  164714. *
  164715. * Postprocessor input data is counted in "row groups". A row group
  164716. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  164717. * sample rows of each component. (We require DCT_scaled_size values to be
  164718. * chosen such that these numbers are integers. In practice DCT_scaled_size
  164719. * values will likely be powers of two, so we actually have the stronger
  164720. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  164721. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  164722. * row group (times any additional scale factor that the upsampler is
  164723. * applying).
  164724. *
  164725. * The coefficient controller will deliver data to us one iMCU row at a time;
  164726. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  164727. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  164728. * to one row of MCUs when the image is fully interleaved.) Note that the
  164729. * number of sample rows varies across components, but the number of row
  164730. * groups does not. Some garbage sample rows may be included in the last iMCU
  164731. * row at the bottom of the image.
  164732. *
  164733. * Depending on the vertical scaling algorithm used, the upsampler may need
  164734. * access to the sample row(s) above and below its current input row group.
  164735. * The upsampler is required to set need_context_rows TRUE at global selection
  164736. * time if so. When need_context_rows is FALSE, this controller can simply
  164737. * obtain one iMCU row at a time from the coefficient controller and dole it
  164738. * out as row groups to the postprocessor.
  164739. *
  164740. * When need_context_rows is TRUE, this controller guarantees that the buffer
  164741. * passed to postprocessing contains at least one row group's worth of samples
  164742. * above and below the row group(s) being processed. Note that the context
  164743. * rows "above" the first passed row group appear at negative row offsets in
  164744. * the passed buffer. At the top and bottom of the image, the required
  164745. * context rows are manufactured by duplicating the first or last real sample
  164746. * row; this avoids having special cases in the upsampling inner loops.
  164747. *
  164748. * The amount of context is fixed at one row group just because that's a
  164749. * convenient number for this controller to work with. The existing
  164750. * upsamplers really only need one sample row of context. An upsampler
  164751. * supporting arbitrary output rescaling might wish for more than one row
  164752. * group of context when shrinking the image; tough, we don't handle that.
  164753. * (This is justified by the assumption that downsizing will be handled mostly
  164754. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  164755. * the upsample step needn't be much less than one.)
  164756. *
  164757. * To provide the desired context, we have to retain the last two row groups
  164758. * of one iMCU row while reading in the next iMCU row. (The last row group
  164759. * can't be processed until we have another row group for its below-context,
  164760. * and so we have to save the next-to-last group too for its above-context.)
  164761. * We could do this most simply by copying data around in our buffer, but
  164762. * that'd be very slow. We can avoid copying any data by creating a rather
  164763. * strange pointer structure. Here's how it works. We allocate a workspace
  164764. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  164765. * of row groups per iMCU row). We create two sets of redundant pointers to
  164766. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  164767. * pointer lists look like this:
  164768. * M+1 M-1
  164769. * master pointer --> 0 master pointer --> 0
  164770. * 1 1
  164771. * ... ...
  164772. * M-3 M-3
  164773. * M-2 M
  164774. * M-1 M+1
  164775. * M M-2
  164776. * M+1 M-1
  164777. * 0 0
  164778. * We read alternate iMCU rows using each master pointer; thus the last two
  164779. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  164780. * The pointer lists are set up so that the required context rows appear to
  164781. * be adjacent to the proper places when we pass the pointer lists to the
  164782. * upsampler.
  164783. *
  164784. * The above pictures describe the normal state of the pointer lists.
  164785. * At top and bottom of the image, we diddle the pointer lists to duplicate
  164786. * the first or last sample row as necessary (this is cheaper than copying
  164787. * sample rows around).
  164788. *
  164789. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  164790. * situation each iMCU row provides only one row group so the buffering logic
  164791. * must be different (eg, we must read two iMCU rows before we can emit the
  164792. * first row group). For now, we simply do not support providing context
  164793. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  164794. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  164795. * want it quick and dirty, so a context-free upsampler is sufficient.
  164796. */
  164797. /* Private buffer controller object */
  164798. typedef struct {
  164799. struct jpeg_d_main_controller pub; /* public fields */
  164800. /* Pointer to allocated workspace (M or M+2 row groups). */
  164801. JSAMPARRAY buffer[MAX_COMPONENTS];
  164802. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  164803. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  164804. /* Remaining fields are only used in the context case. */
  164805. /* These are the master pointers to the funny-order pointer lists. */
  164806. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  164807. int whichptr; /* indicates which pointer set is now in use */
  164808. int context_state; /* process_data state machine status */
  164809. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  164810. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  164811. } my_main_controller4;
  164812. typedef my_main_controller4 * my_main_ptr4;
  164813. /* context_state values: */
  164814. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  164815. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  164816. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  164817. /* Forward declarations */
  164818. METHODDEF(void) process_data_simple_main2
  164819. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  164820. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  164821. METHODDEF(void) process_data_context_main
  164822. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  164823. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  164824. #ifdef QUANT_2PASS_SUPPORTED
  164825. METHODDEF(void) process_data_crank_post
  164826. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  164827. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  164828. #endif
  164829. LOCAL(void)
  164830. alloc_funny_pointers (j_decompress_ptr cinfo)
  164831. /* Allocate space for the funny pointer lists.
  164832. * This is done only once, not once per pass.
  164833. */
  164834. {
  164835. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164836. int ci, rgroup;
  164837. int M = cinfo->min_DCT_scaled_size;
  164838. jpeg_component_info *compptr;
  164839. JSAMPARRAY xbuf;
  164840. /* Get top-level space for component array pointers.
  164841. * We alloc both arrays with one call to save a few cycles.
  164842. */
  164843. main_->xbuffer[0] = (JSAMPIMAGE)
  164844. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164845. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  164846. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  164847. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164848. ci++, compptr++) {
  164849. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  164850. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  164851. /* Get space for pointer lists --- M+4 row groups in each list.
  164852. * We alloc both pointer lists with one call to save a few cycles.
  164853. */
  164854. xbuf = (JSAMPARRAY)
  164855. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164856. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  164857. xbuf += rgroup; /* want one row group at negative offsets */
  164858. main_->xbuffer[0][ci] = xbuf;
  164859. xbuf += rgroup * (M + 4);
  164860. main_->xbuffer[1][ci] = xbuf;
  164861. }
  164862. }
  164863. LOCAL(void)
  164864. make_funny_pointers (j_decompress_ptr cinfo)
  164865. /* Create the funny pointer lists discussed in the comments above.
  164866. * The actual workspace is already allocated (in main->buffer),
  164867. * and the space for the pointer lists is allocated too.
  164868. * This routine just fills in the curiously ordered lists.
  164869. * This will be repeated at the beginning of each pass.
  164870. */
  164871. {
  164872. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164873. int ci, i, rgroup;
  164874. int M = cinfo->min_DCT_scaled_size;
  164875. jpeg_component_info *compptr;
  164876. JSAMPARRAY buf, xbuf0, xbuf1;
  164877. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164878. ci++, compptr++) {
  164879. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  164880. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  164881. xbuf0 = main_->xbuffer[0][ci];
  164882. xbuf1 = main_->xbuffer[1][ci];
  164883. /* First copy the workspace pointers as-is */
  164884. buf = main_->buffer[ci];
  164885. for (i = 0; i < rgroup * (M + 2); i++) {
  164886. xbuf0[i] = xbuf1[i] = buf[i];
  164887. }
  164888. /* In the second list, put the last four row groups in swapped order */
  164889. for (i = 0; i < rgroup * 2; i++) {
  164890. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  164891. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  164892. }
  164893. /* The wraparound pointers at top and bottom will be filled later
  164894. * (see set_wraparound_pointers, below). Initially we want the "above"
  164895. * pointers to duplicate the first actual data line. This only needs
  164896. * to happen in xbuffer[0].
  164897. */
  164898. for (i = 0; i < rgroup; i++) {
  164899. xbuf0[i - rgroup] = xbuf0[0];
  164900. }
  164901. }
  164902. }
  164903. LOCAL(void)
  164904. set_wraparound_pointers (j_decompress_ptr cinfo)
  164905. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  164906. * This changes the pointer list state from top-of-image to the normal state.
  164907. */
  164908. {
  164909. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164910. int ci, i, rgroup;
  164911. int M = cinfo->min_DCT_scaled_size;
  164912. jpeg_component_info *compptr;
  164913. JSAMPARRAY xbuf0, xbuf1;
  164914. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164915. ci++, compptr++) {
  164916. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  164917. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  164918. xbuf0 = main_->xbuffer[0][ci];
  164919. xbuf1 = main_->xbuffer[1][ci];
  164920. for (i = 0; i < rgroup; i++) {
  164921. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  164922. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  164923. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  164924. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  164925. }
  164926. }
  164927. }
  164928. LOCAL(void)
  164929. set_bottom_pointers (j_decompress_ptr cinfo)
  164930. /* Change the pointer lists to duplicate the last sample row at the bottom
  164931. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  164932. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  164933. */
  164934. {
  164935. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164936. int ci, i, rgroup, iMCUheight, rows_left;
  164937. jpeg_component_info *compptr;
  164938. JSAMPARRAY xbuf;
  164939. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164940. ci++, compptr++) {
  164941. /* Count sample rows in one iMCU row and in one row group */
  164942. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  164943. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  164944. /* Count nondummy sample rows remaining for this component */
  164945. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  164946. if (rows_left == 0) rows_left = iMCUheight;
  164947. /* Count nondummy row groups. Should get same answer for each component,
  164948. * so we need only do it once.
  164949. */
  164950. if (ci == 0) {
  164951. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  164952. }
  164953. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  164954. * last partial rowgroup and ensures at least one full rowgroup of context.
  164955. */
  164956. xbuf = main_->xbuffer[main_->whichptr][ci];
  164957. for (i = 0; i < rgroup * 2; i++) {
  164958. xbuf[rows_left + i] = xbuf[rows_left-1];
  164959. }
  164960. }
  164961. }
  164962. /*
  164963. * Initialize for a processing pass.
  164964. */
  164965. METHODDEF(void)
  164966. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  164967. {
  164968. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164969. switch (pass_mode) {
  164970. case JBUF_PASS_THRU:
  164971. if (cinfo->upsample->need_context_rows) {
  164972. main_->pub.process_data = process_data_context_main;
  164973. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  164974. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  164975. main_->context_state = CTX_PREPARE_FOR_IMCU;
  164976. main_->iMCU_row_ctr = 0;
  164977. } else {
  164978. /* Simple case with no context needed */
  164979. main_->pub.process_data = process_data_simple_main2;
  164980. }
  164981. main_->buffer_full = FALSE; /* Mark buffer empty */
  164982. main_->rowgroup_ctr = 0;
  164983. break;
  164984. #ifdef QUANT_2PASS_SUPPORTED
  164985. case JBUF_CRANK_DEST:
  164986. /* For last pass of 2-pass quantization, just crank the postprocessor */
  164987. main_->pub.process_data = process_data_crank_post;
  164988. break;
  164989. #endif
  164990. default:
  164991. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164992. break;
  164993. }
  164994. }
  164995. /*
  164996. * Process some data.
  164997. * This handles the simple case where no context is required.
  164998. */
  164999. METHODDEF(void)
  165000. process_data_simple_main2 (j_decompress_ptr cinfo,
  165001. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  165002. JDIMENSION out_rows_avail)
  165003. {
  165004. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165005. JDIMENSION rowgroups_avail;
  165006. /* Read input data if we haven't filled the main buffer yet */
  165007. if (! main_->buffer_full) {
  165008. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  165009. return; /* suspension forced, can do nothing more */
  165010. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  165011. }
  165012. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  165013. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  165014. /* Note: at the bottom of the image, we may pass extra garbage row groups
  165015. * to the postprocessor. The postprocessor has to check for bottom
  165016. * of image anyway (at row resolution), so no point in us doing it too.
  165017. */
  165018. /* Feed the postprocessor */
  165019. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  165020. &main_->rowgroup_ctr, rowgroups_avail,
  165021. output_buf, out_row_ctr, out_rows_avail);
  165022. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  165023. if (main_->rowgroup_ctr >= rowgroups_avail) {
  165024. main_->buffer_full = FALSE;
  165025. main_->rowgroup_ctr = 0;
  165026. }
  165027. }
  165028. /*
  165029. * Process some data.
  165030. * This handles the case where context rows must be provided.
  165031. */
  165032. METHODDEF(void)
  165033. process_data_context_main (j_decompress_ptr cinfo,
  165034. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  165035. JDIMENSION out_rows_avail)
  165036. {
  165037. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165038. /* Read input data if we haven't filled the main buffer yet */
  165039. if (! main_->buffer_full) {
  165040. if (! (*cinfo->coef->decompress_data) (cinfo,
  165041. main_->xbuffer[main_->whichptr]))
  165042. return; /* suspension forced, can do nothing more */
  165043. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  165044. main_->iMCU_row_ctr++; /* count rows received */
  165045. }
  165046. /* Postprocessor typically will not swallow all the input data it is handed
  165047. * in one call (due to filling the output buffer first). Must be prepared
  165048. * to exit and restart. This switch lets us keep track of how far we got.
  165049. * Note that each case falls through to the next on successful completion.
  165050. */
  165051. switch (main_->context_state) {
  165052. case CTX_POSTPONED_ROW:
  165053. /* Call postprocessor using previously set pointers for postponed row */
  165054. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  165055. &main_->rowgroup_ctr, main_->rowgroups_avail,
  165056. output_buf, out_row_ctr, out_rows_avail);
  165057. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  165058. return; /* Need to suspend */
  165059. main_->context_state = CTX_PREPARE_FOR_IMCU;
  165060. if (*out_row_ctr >= out_rows_avail)
  165061. return; /* Postprocessor exactly filled output buf */
  165062. /*FALLTHROUGH*/
  165063. case CTX_PREPARE_FOR_IMCU:
  165064. /* Prepare to process first M-1 row groups of this iMCU row */
  165065. main_->rowgroup_ctr = 0;
  165066. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  165067. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  165068. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  165069. */
  165070. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  165071. set_bottom_pointers(cinfo);
  165072. main_->context_state = CTX_PROCESS_IMCU;
  165073. /*FALLTHROUGH*/
  165074. case CTX_PROCESS_IMCU:
  165075. /* Call postprocessor using previously set pointers */
  165076. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  165077. &main_->rowgroup_ctr, main_->rowgroups_avail,
  165078. output_buf, out_row_ctr, out_rows_avail);
  165079. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  165080. return; /* Need to suspend */
  165081. /* After the first iMCU, change wraparound pointers to normal state */
  165082. if (main_->iMCU_row_ctr == 1)
  165083. set_wraparound_pointers(cinfo);
  165084. /* Prepare to load new iMCU row using other xbuffer list */
  165085. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  165086. main_->buffer_full = FALSE;
  165087. /* Still need to process last row group of this iMCU row, */
  165088. /* which is saved at index M+1 of the other xbuffer */
  165089. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  165090. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  165091. main_->context_state = CTX_POSTPONED_ROW;
  165092. }
  165093. }
  165094. /*
  165095. * Process some data.
  165096. * Final pass of two-pass quantization: just call the postprocessor.
  165097. * Source data will be the postprocessor controller's internal buffer.
  165098. */
  165099. #ifdef QUANT_2PASS_SUPPORTED
  165100. METHODDEF(void)
  165101. process_data_crank_post (j_decompress_ptr cinfo,
  165102. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  165103. JDIMENSION out_rows_avail)
  165104. {
  165105. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  165106. (JDIMENSION *) NULL, (JDIMENSION) 0,
  165107. output_buf, out_row_ctr, out_rows_avail);
  165108. }
  165109. #endif /* QUANT_2PASS_SUPPORTED */
  165110. /*
  165111. * Initialize main buffer controller.
  165112. */
  165113. GLOBAL(void)
  165114. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  165115. {
  165116. my_main_ptr4 main_;
  165117. int ci, rgroup, ngroups;
  165118. jpeg_component_info *compptr;
  165119. main_ = (my_main_ptr4)
  165120. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165121. SIZEOF(my_main_controller4));
  165122. cinfo->main = (struct jpeg_d_main_controller *) main_;
  165123. main_->pub.start_pass = start_pass_main2;
  165124. if (need_full_buffer) /* shouldn't happen */
  165125. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165126. /* Allocate the workspace.
  165127. * ngroups is the number of row groups we need.
  165128. */
  165129. if (cinfo->upsample->need_context_rows) {
  165130. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  165131. ERREXIT(cinfo, JERR_NOTIMPL);
  165132. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  165133. ngroups = cinfo->min_DCT_scaled_size + 2;
  165134. } else {
  165135. ngroups = cinfo->min_DCT_scaled_size;
  165136. }
  165137. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165138. ci++, compptr++) {
  165139. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  165140. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  165141. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  165142. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165143. compptr->width_in_blocks * compptr->DCT_scaled_size,
  165144. (JDIMENSION) (rgroup * ngroups));
  165145. }
  165146. }
  165147. /********* End of inlined file: jdmainct.c *********/
  165148. /********* Start of inlined file: jdmarker.c *********/
  165149. #define JPEG_INTERNALS
  165150. /* Private state */
  165151. typedef struct {
  165152. struct jpeg_marker_reader pub; /* public fields */
  165153. /* Application-overridable marker processing methods */
  165154. jpeg_marker_parser_method process_COM;
  165155. jpeg_marker_parser_method process_APPn[16];
  165156. /* Limit on marker data length to save for each marker type */
  165157. unsigned int length_limit_COM;
  165158. unsigned int length_limit_APPn[16];
  165159. /* Status of COM/APPn marker saving */
  165160. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  165161. unsigned int bytes_read; /* data bytes read so far in marker */
  165162. /* Note: cur_marker is not linked into marker_list until it's all read. */
  165163. } my_marker_reader;
  165164. typedef my_marker_reader * my_marker_ptr2;
  165165. /*
  165166. * Macros for fetching data from the data source module.
  165167. *
  165168. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  165169. * the current restart point; we update them only when we have reached a
  165170. * suitable place to restart if a suspension occurs.
  165171. */
  165172. /* Declare and initialize local copies of input pointer/count */
  165173. #define INPUT_VARS(cinfo) \
  165174. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  165175. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  165176. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  165177. /* Unload the local copies --- do this only at a restart boundary */
  165178. #define INPUT_SYNC(cinfo) \
  165179. ( datasrc->next_input_byte = next_input_byte, \
  165180. datasrc->bytes_in_buffer = bytes_in_buffer )
  165181. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  165182. #define INPUT_RELOAD(cinfo) \
  165183. ( next_input_byte = datasrc->next_input_byte, \
  165184. bytes_in_buffer = datasrc->bytes_in_buffer )
  165185. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  165186. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  165187. * but we must reload the local copies after a successful fill.
  165188. */
  165189. #define MAKE_BYTE_AVAIL(cinfo,action) \
  165190. if (bytes_in_buffer == 0) { \
  165191. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  165192. { action; } \
  165193. INPUT_RELOAD(cinfo); \
  165194. }
  165195. /* Read a byte into variable V.
  165196. * If must suspend, take the specified action (typically "return FALSE").
  165197. */
  165198. #define INPUT_BYTE(cinfo,V,action) \
  165199. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  165200. bytes_in_buffer--; \
  165201. V = GETJOCTET(*next_input_byte++); )
  165202. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  165203. * V should be declared unsigned int or perhaps INT32.
  165204. */
  165205. #define INPUT_2BYTES(cinfo,V,action) \
  165206. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  165207. bytes_in_buffer--; \
  165208. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  165209. MAKE_BYTE_AVAIL(cinfo,action); \
  165210. bytes_in_buffer--; \
  165211. V += GETJOCTET(*next_input_byte++); )
  165212. /*
  165213. * Routines to process JPEG markers.
  165214. *
  165215. * Entry condition: JPEG marker itself has been read and its code saved
  165216. * in cinfo->unread_marker; input restart point is just after the marker.
  165217. *
  165218. * Exit: if return TRUE, have read and processed any parameters, and have
  165219. * updated the restart point to point after the parameters.
  165220. * If return FALSE, was forced to suspend before reaching end of
  165221. * marker parameters; restart point has not been moved. Same routine
  165222. * will be called again after application supplies more input data.
  165223. *
  165224. * This approach to suspension assumes that all of a marker's parameters
  165225. * can fit into a single input bufferload. This should hold for "normal"
  165226. * markers. Some COM/APPn markers might have large parameter segments
  165227. * that might not fit. If we are simply dropping such a marker, we use
  165228. * skip_input_data to get past it, and thereby put the problem on the
  165229. * source manager's shoulders. If we are saving the marker's contents
  165230. * into memory, we use a slightly different convention: when forced to
  165231. * suspend, the marker processor updates the restart point to the end of
  165232. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  165233. * On resumption, cinfo->unread_marker still contains the marker code,
  165234. * but the data source will point to the next chunk of marker data.
  165235. * The marker processor must retain internal state to deal with this.
  165236. *
  165237. * Note that we don't bother to avoid duplicate trace messages if a
  165238. * suspension occurs within marker parameters. Other side effects
  165239. * require more care.
  165240. */
  165241. LOCAL(boolean)
  165242. get_soi (j_decompress_ptr cinfo)
  165243. /* Process an SOI marker */
  165244. {
  165245. int i;
  165246. TRACEMS(cinfo, 1, JTRC_SOI);
  165247. if (cinfo->marker->saw_SOI)
  165248. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  165249. /* Reset all parameters that are defined to be reset by SOI */
  165250. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165251. cinfo->arith_dc_L[i] = 0;
  165252. cinfo->arith_dc_U[i] = 1;
  165253. cinfo->arith_ac_K[i] = 5;
  165254. }
  165255. cinfo->restart_interval = 0;
  165256. /* Set initial assumptions for colorspace etc */
  165257. cinfo->jpeg_color_space = JCS_UNKNOWN;
  165258. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  165259. cinfo->saw_JFIF_marker = FALSE;
  165260. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  165261. cinfo->JFIF_minor_version = 1;
  165262. cinfo->density_unit = 0;
  165263. cinfo->X_density = 1;
  165264. cinfo->Y_density = 1;
  165265. cinfo->saw_Adobe_marker = FALSE;
  165266. cinfo->Adobe_transform = 0;
  165267. cinfo->marker->saw_SOI = TRUE;
  165268. return TRUE;
  165269. }
  165270. LOCAL(boolean)
  165271. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  165272. /* Process a SOFn marker */
  165273. {
  165274. INT32 length;
  165275. int c, ci;
  165276. jpeg_component_info * compptr;
  165277. INPUT_VARS(cinfo);
  165278. cinfo->progressive_mode = is_prog;
  165279. cinfo->arith_code = is_arith;
  165280. INPUT_2BYTES(cinfo, length, return FALSE);
  165281. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  165282. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  165283. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  165284. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  165285. length -= 8;
  165286. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  165287. (int) cinfo->image_width, (int) cinfo->image_height,
  165288. cinfo->num_components);
  165289. if (cinfo->marker->saw_SOF)
  165290. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  165291. /* We don't support files in which the image height is initially specified */
  165292. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  165293. /* might as well have a general sanity check. */
  165294. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  165295. || cinfo->num_components <= 0)
  165296. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  165297. if (length != (cinfo->num_components * 3))
  165298. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165299. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  165300. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  165301. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165302. cinfo->num_components * SIZEOF(jpeg_component_info));
  165303. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165304. ci++, compptr++) {
  165305. compptr->component_index = ci;
  165306. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  165307. INPUT_BYTE(cinfo, c, return FALSE);
  165308. compptr->h_samp_factor = (c >> 4) & 15;
  165309. compptr->v_samp_factor = (c ) & 15;
  165310. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  165311. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  165312. compptr->component_id, compptr->h_samp_factor,
  165313. compptr->v_samp_factor, compptr->quant_tbl_no);
  165314. }
  165315. cinfo->marker->saw_SOF = TRUE;
  165316. INPUT_SYNC(cinfo);
  165317. return TRUE;
  165318. }
  165319. LOCAL(boolean)
  165320. get_sos (j_decompress_ptr cinfo)
  165321. /* Process a SOS marker */
  165322. {
  165323. INT32 length;
  165324. int i, ci, n, c, cc;
  165325. jpeg_component_info * compptr;
  165326. INPUT_VARS(cinfo);
  165327. if (! cinfo->marker->saw_SOF)
  165328. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  165329. INPUT_2BYTES(cinfo, length, return FALSE);
  165330. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  165331. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  165332. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  165333. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165334. cinfo->comps_in_scan = n;
  165335. /* Collect the component-spec parameters */
  165336. for (i = 0; i < n; i++) {
  165337. INPUT_BYTE(cinfo, cc, return FALSE);
  165338. INPUT_BYTE(cinfo, c, return FALSE);
  165339. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165340. ci++, compptr++) {
  165341. if (cc == compptr->component_id)
  165342. goto id_found;
  165343. }
  165344. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  165345. id_found:
  165346. cinfo->cur_comp_info[i] = compptr;
  165347. compptr->dc_tbl_no = (c >> 4) & 15;
  165348. compptr->ac_tbl_no = (c ) & 15;
  165349. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  165350. compptr->dc_tbl_no, compptr->ac_tbl_no);
  165351. }
  165352. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  165353. INPUT_BYTE(cinfo, c, return FALSE);
  165354. cinfo->Ss = c;
  165355. INPUT_BYTE(cinfo, c, return FALSE);
  165356. cinfo->Se = c;
  165357. INPUT_BYTE(cinfo, c, return FALSE);
  165358. cinfo->Ah = (c >> 4) & 15;
  165359. cinfo->Al = (c ) & 15;
  165360. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  165361. cinfo->Ah, cinfo->Al);
  165362. /* Prepare to scan data & restart markers */
  165363. cinfo->marker->next_restart_num = 0;
  165364. /* Count another SOS marker */
  165365. cinfo->input_scan_number++;
  165366. INPUT_SYNC(cinfo);
  165367. return TRUE;
  165368. }
  165369. #ifdef D_ARITH_CODING_SUPPORTED
  165370. LOCAL(boolean)
  165371. get_dac (j_decompress_ptr cinfo)
  165372. /* Process a DAC marker */
  165373. {
  165374. INT32 length;
  165375. int index, val;
  165376. INPUT_VARS(cinfo);
  165377. INPUT_2BYTES(cinfo, length, return FALSE);
  165378. length -= 2;
  165379. while (length > 0) {
  165380. INPUT_BYTE(cinfo, index, return FALSE);
  165381. INPUT_BYTE(cinfo, val, return FALSE);
  165382. length -= 2;
  165383. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  165384. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  165385. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  165386. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  165387. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  165388. } else { /* define DC table */
  165389. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  165390. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  165391. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  165392. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  165393. }
  165394. }
  165395. if (length != 0)
  165396. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165397. INPUT_SYNC(cinfo);
  165398. return TRUE;
  165399. }
  165400. #else /* ! D_ARITH_CODING_SUPPORTED */
  165401. #define get_dac(cinfo) skip_variable(cinfo)
  165402. #endif /* D_ARITH_CODING_SUPPORTED */
  165403. LOCAL(boolean)
  165404. get_dht (j_decompress_ptr cinfo)
  165405. /* Process a DHT marker */
  165406. {
  165407. INT32 length;
  165408. UINT8 bits[17];
  165409. UINT8 huffval[256];
  165410. int i, index, count;
  165411. JHUFF_TBL **htblptr;
  165412. INPUT_VARS(cinfo);
  165413. INPUT_2BYTES(cinfo, length, return FALSE);
  165414. length -= 2;
  165415. while (length > 16) {
  165416. INPUT_BYTE(cinfo, index, return FALSE);
  165417. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  165418. bits[0] = 0;
  165419. count = 0;
  165420. for (i = 1; i <= 16; i++) {
  165421. INPUT_BYTE(cinfo, bits[i], return FALSE);
  165422. count += bits[i];
  165423. }
  165424. length -= 1 + 16;
  165425. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  165426. bits[1], bits[2], bits[3], bits[4],
  165427. bits[5], bits[6], bits[7], bits[8]);
  165428. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  165429. bits[9], bits[10], bits[11], bits[12],
  165430. bits[13], bits[14], bits[15], bits[16]);
  165431. /* Here we just do minimal validation of the counts to avoid walking
  165432. * off the end of our table space. jdhuff.c will check more carefully.
  165433. */
  165434. if (count > 256 || ((INT32) count) > length)
  165435. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165436. for (i = 0; i < count; i++)
  165437. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  165438. length -= count;
  165439. if (index & 0x10) { /* AC table definition */
  165440. index -= 0x10;
  165441. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  165442. } else { /* DC table definition */
  165443. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  165444. }
  165445. if (index < 0 || index >= NUM_HUFF_TBLS)
  165446. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  165447. if (*htblptr == NULL)
  165448. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165449. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165450. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  165451. }
  165452. if (length != 0)
  165453. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165454. INPUT_SYNC(cinfo);
  165455. return TRUE;
  165456. }
  165457. LOCAL(boolean)
  165458. get_dqt (j_decompress_ptr cinfo)
  165459. /* Process a DQT marker */
  165460. {
  165461. INT32 length;
  165462. int n, i, prec;
  165463. unsigned int tmp;
  165464. JQUANT_TBL *quant_ptr;
  165465. INPUT_VARS(cinfo);
  165466. INPUT_2BYTES(cinfo, length, return FALSE);
  165467. length -= 2;
  165468. while (length > 0) {
  165469. INPUT_BYTE(cinfo, n, return FALSE);
  165470. prec = n >> 4;
  165471. n &= 0x0F;
  165472. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  165473. if (n >= NUM_QUANT_TBLS)
  165474. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  165475. if (cinfo->quant_tbl_ptrs[n] == NULL)
  165476. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165477. quant_ptr = cinfo->quant_tbl_ptrs[n];
  165478. for (i = 0; i < DCTSIZE2; i++) {
  165479. if (prec)
  165480. INPUT_2BYTES(cinfo, tmp, return FALSE);
  165481. else
  165482. INPUT_BYTE(cinfo, tmp, return FALSE);
  165483. /* We convert the zigzag-order table to natural array order. */
  165484. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  165485. }
  165486. if (cinfo->err->trace_level >= 2) {
  165487. for (i = 0; i < DCTSIZE2; i += 8) {
  165488. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  165489. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  165490. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  165491. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  165492. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  165493. }
  165494. }
  165495. length -= DCTSIZE2+1;
  165496. if (prec) length -= DCTSIZE2;
  165497. }
  165498. if (length != 0)
  165499. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165500. INPUT_SYNC(cinfo);
  165501. return TRUE;
  165502. }
  165503. LOCAL(boolean)
  165504. get_dri (j_decompress_ptr cinfo)
  165505. /* Process a DRI marker */
  165506. {
  165507. INT32 length;
  165508. unsigned int tmp;
  165509. INPUT_VARS(cinfo);
  165510. INPUT_2BYTES(cinfo, length, return FALSE);
  165511. if (length != 4)
  165512. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165513. INPUT_2BYTES(cinfo, tmp, return FALSE);
  165514. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  165515. cinfo->restart_interval = tmp;
  165516. INPUT_SYNC(cinfo);
  165517. return TRUE;
  165518. }
  165519. /*
  165520. * Routines for processing APPn and COM markers.
  165521. * These are either saved in memory or discarded, per application request.
  165522. * APP0 and APP14 are specially checked to see if they are
  165523. * JFIF and Adobe markers, respectively.
  165524. */
  165525. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  165526. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  165527. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  165528. LOCAL(void)
  165529. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  165530. unsigned int datalen, INT32 remaining)
  165531. /* Examine first few bytes from an APP0.
  165532. * Take appropriate action if it is a JFIF marker.
  165533. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  165534. */
  165535. {
  165536. INT32 totallen = (INT32) datalen + remaining;
  165537. if (datalen >= APP0_DATA_LEN &&
  165538. GETJOCTET(data[0]) == 0x4A &&
  165539. GETJOCTET(data[1]) == 0x46 &&
  165540. GETJOCTET(data[2]) == 0x49 &&
  165541. GETJOCTET(data[3]) == 0x46 &&
  165542. GETJOCTET(data[4]) == 0) {
  165543. /* Found JFIF APP0 marker: save info */
  165544. cinfo->saw_JFIF_marker = TRUE;
  165545. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  165546. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  165547. cinfo->density_unit = GETJOCTET(data[7]);
  165548. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  165549. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  165550. /* Check version.
  165551. * Major version must be 1, anything else signals an incompatible change.
  165552. * (We used to treat this as an error, but now it's a nonfatal warning,
  165553. * because some bozo at Hijaak couldn't read the spec.)
  165554. * Minor version should be 0..2, but process anyway if newer.
  165555. */
  165556. if (cinfo->JFIF_major_version != 1)
  165557. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  165558. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  165559. /* Generate trace messages */
  165560. TRACEMS5(cinfo, 1, JTRC_JFIF,
  165561. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  165562. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  165563. /* Validate thumbnail dimensions and issue appropriate messages */
  165564. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  165565. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  165566. GETJOCTET(data[12]), GETJOCTET(data[13]));
  165567. totallen -= APP0_DATA_LEN;
  165568. if (totallen !=
  165569. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  165570. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  165571. } else if (datalen >= 6 &&
  165572. GETJOCTET(data[0]) == 0x4A &&
  165573. GETJOCTET(data[1]) == 0x46 &&
  165574. GETJOCTET(data[2]) == 0x58 &&
  165575. GETJOCTET(data[3]) == 0x58 &&
  165576. GETJOCTET(data[4]) == 0) {
  165577. /* Found JFIF "JFXX" extension APP0 marker */
  165578. /* The library doesn't actually do anything with these,
  165579. * but we try to produce a helpful trace message.
  165580. */
  165581. switch (GETJOCTET(data[5])) {
  165582. case 0x10:
  165583. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  165584. break;
  165585. case 0x11:
  165586. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  165587. break;
  165588. case 0x13:
  165589. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  165590. break;
  165591. default:
  165592. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  165593. GETJOCTET(data[5]), (int) totallen);
  165594. break;
  165595. }
  165596. } else {
  165597. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  165598. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  165599. }
  165600. }
  165601. LOCAL(void)
  165602. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  165603. unsigned int datalen, INT32 remaining)
  165604. /* Examine first few bytes from an APP14.
  165605. * Take appropriate action if it is an Adobe marker.
  165606. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  165607. */
  165608. {
  165609. unsigned int version, flags0, flags1, transform;
  165610. if (datalen >= APP14_DATA_LEN &&
  165611. GETJOCTET(data[0]) == 0x41 &&
  165612. GETJOCTET(data[1]) == 0x64 &&
  165613. GETJOCTET(data[2]) == 0x6F &&
  165614. GETJOCTET(data[3]) == 0x62 &&
  165615. GETJOCTET(data[4]) == 0x65) {
  165616. /* Found Adobe APP14 marker */
  165617. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  165618. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  165619. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  165620. transform = GETJOCTET(data[11]);
  165621. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  165622. cinfo->saw_Adobe_marker = TRUE;
  165623. cinfo->Adobe_transform = (UINT8) transform;
  165624. } else {
  165625. /* Start of APP14 does not match "Adobe", or too short */
  165626. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  165627. }
  165628. }
  165629. METHODDEF(boolean)
  165630. get_interesting_appn (j_decompress_ptr cinfo)
  165631. /* Process an APP0 or APP14 marker without saving it */
  165632. {
  165633. INT32 length;
  165634. JOCTET b[APPN_DATA_LEN];
  165635. unsigned int i, numtoread;
  165636. INPUT_VARS(cinfo);
  165637. INPUT_2BYTES(cinfo, length, return FALSE);
  165638. length -= 2;
  165639. /* get the interesting part of the marker data */
  165640. if (length >= APPN_DATA_LEN)
  165641. numtoread = APPN_DATA_LEN;
  165642. else if (length > 0)
  165643. numtoread = (unsigned int) length;
  165644. else
  165645. numtoread = 0;
  165646. for (i = 0; i < numtoread; i++)
  165647. INPUT_BYTE(cinfo, b[i], return FALSE);
  165648. length -= numtoread;
  165649. /* process it */
  165650. switch (cinfo->unread_marker) {
  165651. case M_APP0:
  165652. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  165653. break;
  165654. case M_APP14:
  165655. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  165656. break;
  165657. default:
  165658. /* can't get here unless jpeg_save_markers chooses wrong processor */
  165659. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  165660. break;
  165661. }
  165662. /* skip any remaining data -- could be lots */
  165663. INPUT_SYNC(cinfo);
  165664. if (length > 0)
  165665. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  165666. return TRUE;
  165667. }
  165668. #ifdef SAVE_MARKERS_SUPPORTED
  165669. METHODDEF(boolean)
  165670. save_marker (j_decompress_ptr cinfo)
  165671. /* Save an APPn or COM marker into the marker list */
  165672. {
  165673. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  165674. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  165675. unsigned int bytes_read, data_length;
  165676. JOCTET FAR * data;
  165677. INT32 length = 0;
  165678. INPUT_VARS(cinfo);
  165679. if (cur_marker == NULL) {
  165680. /* begin reading a marker */
  165681. INPUT_2BYTES(cinfo, length, return FALSE);
  165682. length -= 2;
  165683. if (length >= 0) { /* watch out for bogus length word */
  165684. /* figure out how much we want to save */
  165685. unsigned int limit;
  165686. if (cinfo->unread_marker == (int) M_COM)
  165687. limit = marker->length_limit_COM;
  165688. else
  165689. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  165690. if ((unsigned int) length < limit)
  165691. limit = (unsigned int) length;
  165692. /* allocate and initialize the marker item */
  165693. cur_marker = (jpeg_saved_marker_ptr)
  165694. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165695. SIZEOF(struct jpeg_marker_struct) + limit);
  165696. cur_marker->next = NULL;
  165697. cur_marker->marker = (UINT8) cinfo->unread_marker;
  165698. cur_marker->original_length = (unsigned int) length;
  165699. cur_marker->data_length = limit;
  165700. /* data area is just beyond the jpeg_marker_struct */
  165701. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  165702. marker->cur_marker = cur_marker;
  165703. marker->bytes_read = 0;
  165704. bytes_read = 0;
  165705. data_length = limit;
  165706. } else {
  165707. /* deal with bogus length word */
  165708. bytes_read = data_length = 0;
  165709. data = NULL;
  165710. }
  165711. } else {
  165712. /* resume reading a marker */
  165713. bytes_read = marker->bytes_read;
  165714. data_length = cur_marker->data_length;
  165715. data = cur_marker->data + bytes_read;
  165716. }
  165717. while (bytes_read < data_length) {
  165718. INPUT_SYNC(cinfo); /* move the restart point to here */
  165719. marker->bytes_read = bytes_read;
  165720. /* If there's not at least one byte in buffer, suspend */
  165721. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  165722. /* Copy bytes with reasonable rapidity */
  165723. while (bytes_read < data_length && bytes_in_buffer > 0) {
  165724. *data++ = *next_input_byte++;
  165725. bytes_in_buffer--;
  165726. bytes_read++;
  165727. }
  165728. }
  165729. /* Done reading what we want to read */
  165730. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  165731. /* Add new marker to end of list */
  165732. if (cinfo->marker_list == NULL) {
  165733. cinfo->marker_list = cur_marker;
  165734. } else {
  165735. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  165736. while (prev->next != NULL)
  165737. prev = prev->next;
  165738. prev->next = cur_marker;
  165739. }
  165740. /* Reset pointer & calc remaining data length */
  165741. data = cur_marker->data;
  165742. length = cur_marker->original_length - data_length;
  165743. }
  165744. /* Reset to initial state for next marker */
  165745. marker->cur_marker = NULL;
  165746. /* Process the marker if interesting; else just make a generic trace msg */
  165747. switch (cinfo->unread_marker) {
  165748. case M_APP0:
  165749. examine_app0(cinfo, data, data_length, length);
  165750. break;
  165751. case M_APP14:
  165752. examine_app14(cinfo, data, data_length, length);
  165753. break;
  165754. default:
  165755. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  165756. (int) (data_length + length));
  165757. break;
  165758. }
  165759. /* skip any remaining data -- could be lots */
  165760. INPUT_SYNC(cinfo); /* do before skip_input_data */
  165761. if (length > 0)
  165762. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  165763. return TRUE;
  165764. }
  165765. #endif /* SAVE_MARKERS_SUPPORTED */
  165766. METHODDEF(boolean)
  165767. skip_variable (j_decompress_ptr cinfo)
  165768. /* Skip over an unknown or uninteresting variable-length marker */
  165769. {
  165770. INT32 length;
  165771. INPUT_VARS(cinfo);
  165772. INPUT_2BYTES(cinfo, length, return FALSE);
  165773. length -= 2;
  165774. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  165775. INPUT_SYNC(cinfo); /* do before skip_input_data */
  165776. if (length > 0)
  165777. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  165778. return TRUE;
  165779. }
  165780. /*
  165781. * Find the next JPEG marker, save it in cinfo->unread_marker.
  165782. * Returns FALSE if had to suspend before reaching a marker;
  165783. * in that case cinfo->unread_marker is unchanged.
  165784. *
  165785. * Note that the result might not be a valid marker code,
  165786. * but it will never be 0 or FF.
  165787. */
  165788. LOCAL(boolean)
  165789. next_marker (j_decompress_ptr cinfo)
  165790. {
  165791. int c;
  165792. INPUT_VARS(cinfo);
  165793. for (;;) {
  165794. INPUT_BYTE(cinfo, c, return FALSE);
  165795. /* Skip any non-FF bytes.
  165796. * This may look a bit inefficient, but it will not occur in a valid file.
  165797. * We sync after each discarded byte so that a suspending data source
  165798. * can discard the byte from its buffer.
  165799. */
  165800. while (c != 0xFF) {
  165801. cinfo->marker->discarded_bytes++;
  165802. INPUT_SYNC(cinfo);
  165803. INPUT_BYTE(cinfo, c, return FALSE);
  165804. }
  165805. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  165806. * pad bytes, so don't count them in discarded_bytes. We assume there
  165807. * will not be so many consecutive FF bytes as to overflow a suspending
  165808. * data source's input buffer.
  165809. */
  165810. do {
  165811. INPUT_BYTE(cinfo, c, return FALSE);
  165812. } while (c == 0xFF);
  165813. if (c != 0)
  165814. break; /* found a valid marker, exit loop */
  165815. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  165816. * Discard it and loop back to try again.
  165817. */
  165818. cinfo->marker->discarded_bytes += 2;
  165819. INPUT_SYNC(cinfo);
  165820. }
  165821. if (cinfo->marker->discarded_bytes != 0) {
  165822. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  165823. cinfo->marker->discarded_bytes = 0;
  165824. }
  165825. cinfo->unread_marker = c;
  165826. INPUT_SYNC(cinfo);
  165827. return TRUE;
  165828. }
  165829. LOCAL(boolean)
  165830. first_marker (j_decompress_ptr cinfo)
  165831. /* Like next_marker, but used to obtain the initial SOI marker. */
  165832. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  165833. * we might well scan an entire input file before realizing it ain't JPEG.
  165834. * If an application wants to process non-JFIF files, it must seek to the
  165835. * SOI before calling the JPEG library.
  165836. */
  165837. {
  165838. int c, c2;
  165839. INPUT_VARS(cinfo);
  165840. INPUT_BYTE(cinfo, c, return FALSE);
  165841. INPUT_BYTE(cinfo, c2, return FALSE);
  165842. if (c != 0xFF || c2 != (int) M_SOI)
  165843. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  165844. cinfo->unread_marker = c2;
  165845. INPUT_SYNC(cinfo);
  165846. return TRUE;
  165847. }
  165848. /*
  165849. * Read markers until SOS or EOI.
  165850. *
  165851. * Returns same codes as are defined for jpeg_consume_input:
  165852. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  165853. */
  165854. METHODDEF(int)
  165855. read_markers (j_decompress_ptr cinfo)
  165856. {
  165857. /* Outer loop repeats once for each marker. */
  165858. for (;;) {
  165859. /* Collect the marker proper, unless we already did. */
  165860. /* NB: first_marker() enforces the requirement that SOI appear first. */
  165861. if (cinfo->unread_marker == 0) {
  165862. if (! cinfo->marker->saw_SOI) {
  165863. if (! first_marker(cinfo))
  165864. return JPEG_SUSPENDED;
  165865. } else {
  165866. if (! next_marker(cinfo))
  165867. return JPEG_SUSPENDED;
  165868. }
  165869. }
  165870. /* At this point cinfo->unread_marker contains the marker code and the
  165871. * input point is just past the marker proper, but before any parameters.
  165872. * A suspension will cause us to return with this state still true.
  165873. */
  165874. switch (cinfo->unread_marker) {
  165875. case M_SOI:
  165876. if (! get_soi(cinfo))
  165877. return JPEG_SUSPENDED;
  165878. break;
  165879. case M_SOF0: /* Baseline */
  165880. case M_SOF1: /* Extended sequential, Huffman */
  165881. if (! get_sof(cinfo, FALSE, FALSE))
  165882. return JPEG_SUSPENDED;
  165883. break;
  165884. case M_SOF2: /* Progressive, Huffman */
  165885. if (! get_sof(cinfo, TRUE, FALSE))
  165886. return JPEG_SUSPENDED;
  165887. break;
  165888. case M_SOF9: /* Extended sequential, arithmetic */
  165889. if (! get_sof(cinfo, FALSE, TRUE))
  165890. return JPEG_SUSPENDED;
  165891. break;
  165892. case M_SOF10: /* Progressive, arithmetic */
  165893. if (! get_sof(cinfo, TRUE, TRUE))
  165894. return JPEG_SUSPENDED;
  165895. break;
  165896. /* Currently unsupported SOFn types */
  165897. case M_SOF3: /* Lossless, Huffman */
  165898. case M_SOF5: /* Differential sequential, Huffman */
  165899. case M_SOF6: /* Differential progressive, Huffman */
  165900. case M_SOF7: /* Differential lossless, Huffman */
  165901. case M_JPG: /* Reserved for JPEG extensions */
  165902. case M_SOF11: /* Lossless, arithmetic */
  165903. case M_SOF13: /* Differential sequential, arithmetic */
  165904. case M_SOF14: /* Differential progressive, arithmetic */
  165905. case M_SOF15: /* Differential lossless, arithmetic */
  165906. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  165907. break;
  165908. case M_SOS:
  165909. if (! get_sos(cinfo))
  165910. return JPEG_SUSPENDED;
  165911. cinfo->unread_marker = 0; /* processed the marker */
  165912. return JPEG_REACHED_SOS;
  165913. case M_EOI:
  165914. TRACEMS(cinfo, 1, JTRC_EOI);
  165915. cinfo->unread_marker = 0; /* processed the marker */
  165916. return JPEG_REACHED_EOI;
  165917. case M_DAC:
  165918. if (! get_dac(cinfo))
  165919. return JPEG_SUSPENDED;
  165920. break;
  165921. case M_DHT:
  165922. if (! get_dht(cinfo))
  165923. return JPEG_SUSPENDED;
  165924. break;
  165925. case M_DQT:
  165926. if (! get_dqt(cinfo))
  165927. return JPEG_SUSPENDED;
  165928. break;
  165929. case M_DRI:
  165930. if (! get_dri(cinfo))
  165931. return JPEG_SUSPENDED;
  165932. break;
  165933. case M_APP0:
  165934. case M_APP1:
  165935. case M_APP2:
  165936. case M_APP3:
  165937. case M_APP4:
  165938. case M_APP5:
  165939. case M_APP6:
  165940. case M_APP7:
  165941. case M_APP8:
  165942. case M_APP9:
  165943. case M_APP10:
  165944. case M_APP11:
  165945. case M_APP12:
  165946. case M_APP13:
  165947. case M_APP14:
  165948. case M_APP15:
  165949. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  165950. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  165951. return JPEG_SUSPENDED;
  165952. break;
  165953. case M_COM:
  165954. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  165955. return JPEG_SUSPENDED;
  165956. break;
  165957. case M_RST0: /* these are all parameterless */
  165958. case M_RST1:
  165959. case M_RST2:
  165960. case M_RST3:
  165961. case M_RST4:
  165962. case M_RST5:
  165963. case M_RST6:
  165964. case M_RST7:
  165965. case M_TEM:
  165966. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  165967. break;
  165968. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  165969. if (! skip_variable(cinfo))
  165970. return JPEG_SUSPENDED;
  165971. break;
  165972. default: /* must be DHP, EXP, JPGn, or RESn */
  165973. /* For now, we treat the reserved markers as fatal errors since they are
  165974. * likely to be used to signal incompatible JPEG Part 3 extensions.
  165975. * Once the JPEG 3 version-number marker is well defined, this code
  165976. * ought to change!
  165977. */
  165978. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  165979. break;
  165980. }
  165981. /* Successfully processed marker, so reset state variable */
  165982. cinfo->unread_marker = 0;
  165983. } /* end loop */
  165984. }
  165985. /*
  165986. * Read a restart marker, which is expected to appear next in the datastream;
  165987. * if the marker is not there, take appropriate recovery action.
  165988. * Returns FALSE if suspension is required.
  165989. *
  165990. * This is called by the entropy decoder after it has read an appropriate
  165991. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  165992. * has already read a marker from the data source. Under normal conditions
  165993. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  165994. * it holds a marker which the decoder will be unable to read past.
  165995. */
  165996. METHODDEF(boolean)
  165997. read_restart_marker (j_decompress_ptr cinfo)
  165998. {
  165999. /* Obtain a marker unless we already did. */
  166000. /* Note that next_marker will complain if it skips any data. */
  166001. if (cinfo->unread_marker == 0) {
  166002. if (! next_marker(cinfo))
  166003. return FALSE;
  166004. }
  166005. if (cinfo->unread_marker ==
  166006. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  166007. /* Normal case --- swallow the marker and let entropy decoder continue */
  166008. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  166009. cinfo->unread_marker = 0;
  166010. } else {
  166011. /* Uh-oh, the restart markers have been messed up. */
  166012. /* Let the data source manager determine how to resync. */
  166013. if (! (*cinfo->src->resync_to_restart) (cinfo,
  166014. cinfo->marker->next_restart_num))
  166015. return FALSE;
  166016. }
  166017. /* Update next-restart state */
  166018. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  166019. return TRUE;
  166020. }
  166021. /*
  166022. * This is the default resync_to_restart method for data source managers
  166023. * to use if they don't have any better approach. Some data source managers
  166024. * may be able to back up, or may have additional knowledge about the data
  166025. * which permits a more intelligent recovery strategy; such managers would
  166026. * presumably supply their own resync method.
  166027. *
  166028. * read_restart_marker calls resync_to_restart if it finds a marker other than
  166029. * the restart marker it was expecting. (This code is *not* used unless
  166030. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  166031. * the marker code actually found (might be anything, except 0 or FF).
  166032. * The desired restart marker number (0..7) is passed as a parameter.
  166033. * This routine is supposed to apply whatever error recovery strategy seems
  166034. * appropriate in order to position the input stream to the next data segment.
  166035. * Note that cinfo->unread_marker is treated as a marker appearing before
  166036. * the current data-source input point; usually it should be reset to zero
  166037. * before returning.
  166038. * Returns FALSE if suspension is required.
  166039. *
  166040. * This implementation is substantially constrained by wanting to treat the
  166041. * input as a data stream; this means we can't back up. Therefore, we have
  166042. * only the following actions to work with:
  166043. * 1. Simply discard the marker and let the entropy decoder resume at next
  166044. * byte of file.
  166045. * 2. Read forward until we find another marker, discarding intervening
  166046. * data. (In theory we could look ahead within the current bufferload,
  166047. * without having to discard data if we don't find the desired marker.
  166048. * This idea is not implemented here, in part because it makes behavior
  166049. * dependent on buffer size and chance buffer-boundary positions.)
  166050. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  166051. * This will cause the entropy decoder to process an empty data segment,
  166052. * inserting dummy zeroes, and then we will reprocess the marker.
  166053. *
  166054. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  166055. * appropriate if the found marker is a future restart marker (indicating
  166056. * that we have missed the desired restart marker, probably because it got
  166057. * corrupted).
  166058. * We apply #2 or #3 if the found marker is a restart marker no more than
  166059. * two counts behind or ahead of the expected one. We also apply #2 if the
  166060. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  166061. * If the found marker is a restart marker more than 2 counts away, we do #1
  166062. * (too much risk that the marker is erroneous; with luck we will be able to
  166063. * resync at some future point).
  166064. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  166065. * overrunning the end of a scan. An implementation limited to single-scan
  166066. * files might find it better to apply #2 for markers other than EOI, since
  166067. * any other marker would have to be bogus data in that case.
  166068. */
  166069. GLOBAL(boolean)
  166070. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  166071. {
  166072. int marker = cinfo->unread_marker;
  166073. int action = 1;
  166074. /* Always put up a warning. */
  166075. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  166076. /* Outer loop handles repeated decision after scanning forward. */
  166077. for (;;) {
  166078. if (marker < (int) M_SOF0)
  166079. action = 2; /* invalid marker */
  166080. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  166081. action = 3; /* valid non-restart marker */
  166082. else {
  166083. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  166084. marker == ((int) M_RST0 + ((desired+2) & 7)))
  166085. action = 3; /* one of the next two expected restarts */
  166086. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  166087. marker == ((int) M_RST0 + ((desired-2) & 7)))
  166088. action = 2; /* a prior restart, so advance */
  166089. else
  166090. action = 1; /* desired restart or too far away */
  166091. }
  166092. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  166093. switch (action) {
  166094. case 1:
  166095. /* Discard marker and let entropy decoder resume processing. */
  166096. cinfo->unread_marker = 0;
  166097. return TRUE;
  166098. case 2:
  166099. /* Scan to the next marker, and repeat the decision loop. */
  166100. if (! next_marker(cinfo))
  166101. return FALSE;
  166102. marker = cinfo->unread_marker;
  166103. break;
  166104. case 3:
  166105. /* Return without advancing past this marker. */
  166106. /* Entropy decoder will be forced to process an empty segment. */
  166107. return TRUE;
  166108. }
  166109. } /* end loop */
  166110. }
  166111. /*
  166112. * Reset marker processing state to begin a fresh datastream.
  166113. */
  166114. METHODDEF(void)
  166115. reset_marker_reader (j_decompress_ptr cinfo)
  166116. {
  166117. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  166118. cinfo->comp_info = NULL; /* until allocated by get_sof */
  166119. cinfo->input_scan_number = 0; /* no SOS seen yet */
  166120. cinfo->unread_marker = 0; /* no pending marker */
  166121. marker->pub.saw_SOI = FALSE; /* set internal state too */
  166122. marker->pub.saw_SOF = FALSE;
  166123. marker->pub.discarded_bytes = 0;
  166124. marker->cur_marker = NULL;
  166125. }
  166126. /*
  166127. * Initialize the marker reader module.
  166128. * This is called only once, when the decompression object is created.
  166129. */
  166130. GLOBAL(void)
  166131. jinit_marker_reader (j_decompress_ptr cinfo)
  166132. {
  166133. my_marker_ptr2 marker;
  166134. int i;
  166135. /* Create subobject in permanent pool */
  166136. marker = (my_marker_ptr2)
  166137. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  166138. SIZEOF(my_marker_reader));
  166139. cinfo->marker = (struct jpeg_marker_reader *) marker;
  166140. /* Initialize public method pointers */
  166141. marker->pub.reset_marker_reader = reset_marker_reader;
  166142. marker->pub.read_markers = read_markers;
  166143. marker->pub.read_restart_marker = read_restart_marker;
  166144. /* Initialize COM/APPn processing.
  166145. * By default, we examine and then discard APP0 and APP14,
  166146. * but simply discard COM and all other APPn.
  166147. */
  166148. marker->process_COM = skip_variable;
  166149. marker->length_limit_COM = 0;
  166150. for (i = 0; i < 16; i++) {
  166151. marker->process_APPn[i] = skip_variable;
  166152. marker->length_limit_APPn[i] = 0;
  166153. }
  166154. marker->process_APPn[0] = get_interesting_appn;
  166155. marker->process_APPn[14] = get_interesting_appn;
  166156. /* Reset marker processing state */
  166157. reset_marker_reader(cinfo);
  166158. }
  166159. /*
  166160. * Control saving of COM and APPn markers into marker_list.
  166161. */
  166162. #ifdef SAVE_MARKERS_SUPPORTED
  166163. GLOBAL(void)
  166164. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  166165. unsigned int length_limit)
  166166. {
  166167. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  166168. long maxlength;
  166169. jpeg_marker_parser_method processor;
  166170. /* Length limit mustn't be larger than what we can allocate
  166171. * (should only be a concern in a 16-bit environment).
  166172. */
  166173. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  166174. if (((long) length_limit) > maxlength)
  166175. length_limit = (unsigned int) maxlength;
  166176. /* Choose processor routine to use.
  166177. * APP0/APP14 have special requirements.
  166178. */
  166179. if (length_limit) {
  166180. processor = save_marker;
  166181. /* If saving APP0/APP14, save at least enough for our internal use. */
  166182. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  166183. length_limit = APP0_DATA_LEN;
  166184. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  166185. length_limit = APP14_DATA_LEN;
  166186. } else {
  166187. processor = skip_variable;
  166188. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  166189. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  166190. processor = get_interesting_appn;
  166191. }
  166192. if (marker_code == (int) M_COM) {
  166193. marker->process_COM = processor;
  166194. marker->length_limit_COM = length_limit;
  166195. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  166196. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  166197. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  166198. } else
  166199. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  166200. }
  166201. #endif /* SAVE_MARKERS_SUPPORTED */
  166202. /*
  166203. * Install a special processing method for COM or APPn markers.
  166204. */
  166205. GLOBAL(void)
  166206. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  166207. jpeg_marker_parser_method routine)
  166208. {
  166209. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  166210. if (marker_code == (int) M_COM)
  166211. marker->process_COM = routine;
  166212. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  166213. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  166214. else
  166215. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  166216. }
  166217. /********* End of inlined file: jdmarker.c *********/
  166218. /********* Start of inlined file: jdmaster.c *********/
  166219. #define JPEG_INTERNALS
  166220. /* Private state */
  166221. typedef struct {
  166222. struct jpeg_decomp_master pub; /* public fields */
  166223. int pass_number; /* # of passes completed */
  166224. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  166225. /* Saved references to initialized quantizer modules,
  166226. * in case we need to switch modes.
  166227. */
  166228. struct jpeg_color_quantizer * quantizer_1pass;
  166229. struct jpeg_color_quantizer * quantizer_2pass;
  166230. } my_decomp_master;
  166231. typedef my_decomp_master * my_master_ptr6;
  166232. /*
  166233. * Determine whether merged upsample/color conversion should be used.
  166234. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  166235. */
  166236. LOCAL(boolean)
  166237. use_merged_upsample (j_decompress_ptr cinfo)
  166238. {
  166239. #ifdef UPSAMPLE_MERGING_SUPPORTED
  166240. /* Merging is the equivalent of plain box-filter upsampling */
  166241. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  166242. return FALSE;
  166243. /* jdmerge.c only supports YCC=>RGB color conversion */
  166244. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  166245. cinfo->out_color_space != JCS_RGB ||
  166246. cinfo->out_color_components != RGB_PIXELSIZE)
  166247. return FALSE;
  166248. /* and it only handles 2h1v or 2h2v sampling ratios */
  166249. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  166250. cinfo->comp_info[1].h_samp_factor != 1 ||
  166251. cinfo->comp_info[2].h_samp_factor != 1 ||
  166252. cinfo->comp_info[0].v_samp_factor > 2 ||
  166253. cinfo->comp_info[1].v_samp_factor != 1 ||
  166254. cinfo->comp_info[2].v_samp_factor != 1)
  166255. return FALSE;
  166256. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  166257. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  166258. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  166259. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  166260. return FALSE;
  166261. /* ??? also need to test for upsample-time rescaling, when & if supported */
  166262. return TRUE; /* by golly, it'll work... */
  166263. #else
  166264. return FALSE;
  166265. #endif
  166266. }
  166267. /*
  166268. * Compute output image dimensions and related values.
  166269. * NOTE: this is exported for possible use by application.
  166270. * Hence it mustn't do anything that can't be done twice.
  166271. * Also note that it may be called before the master module is initialized!
  166272. */
  166273. GLOBAL(void)
  166274. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  166275. /* Do computations that are needed before master selection phase */
  166276. {
  166277. #ifdef IDCT_SCALING_SUPPORTED
  166278. int ci;
  166279. jpeg_component_info *compptr;
  166280. #endif
  166281. /* Prevent application from calling me at wrong times */
  166282. if (cinfo->global_state != DSTATE_READY)
  166283. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166284. #ifdef IDCT_SCALING_SUPPORTED
  166285. /* Compute actual output image dimensions and DCT scaling choices. */
  166286. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  166287. /* Provide 1/8 scaling */
  166288. cinfo->output_width = (JDIMENSION)
  166289. jdiv_round_up((long) cinfo->image_width, 8L);
  166290. cinfo->output_height = (JDIMENSION)
  166291. jdiv_round_up((long) cinfo->image_height, 8L);
  166292. cinfo->min_DCT_scaled_size = 1;
  166293. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  166294. /* Provide 1/4 scaling */
  166295. cinfo->output_width = (JDIMENSION)
  166296. jdiv_round_up((long) cinfo->image_width, 4L);
  166297. cinfo->output_height = (JDIMENSION)
  166298. jdiv_round_up((long) cinfo->image_height, 4L);
  166299. cinfo->min_DCT_scaled_size = 2;
  166300. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  166301. /* Provide 1/2 scaling */
  166302. cinfo->output_width = (JDIMENSION)
  166303. jdiv_round_up((long) cinfo->image_width, 2L);
  166304. cinfo->output_height = (JDIMENSION)
  166305. jdiv_round_up((long) cinfo->image_height, 2L);
  166306. cinfo->min_DCT_scaled_size = 4;
  166307. } else {
  166308. /* Provide 1/1 scaling */
  166309. cinfo->output_width = cinfo->image_width;
  166310. cinfo->output_height = cinfo->image_height;
  166311. cinfo->min_DCT_scaled_size = DCTSIZE;
  166312. }
  166313. /* In selecting the actual DCT scaling for each component, we try to
  166314. * scale up the chroma components via IDCT scaling rather than upsampling.
  166315. * This saves time if the upsampler gets to use 1:1 scaling.
  166316. * Note this code assumes that the supported DCT scalings are powers of 2.
  166317. */
  166318. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166319. ci++, compptr++) {
  166320. int ssize = cinfo->min_DCT_scaled_size;
  166321. while (ssize < DCTSIZE &&
  166322. (compptr->h_samp_factor * ssize * 2 <=
  166323. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  166324. (compptr->v_samp_factor * ssize * 2 <=
  166325. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  166326. ssize = ssize * 2;
  166327. }
  166328. compptr->DCT_scaled_size = ssize;
  166329. }
  166330. /* Recompute downsampled dimensions of components;
  166331. * application needs to know these if using raw downsampled data.
  166332. */
  166333. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166334. ci++, compptr++) {
  166335. /* Size in samples, after IDCT scaling */
  166336. compptr->downsampled_width = (JDIMENSION)
  166337. jdiv_round_up((long) cinfo->image_width *
  166338. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  166339. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  166340. compptr->downsampled_height = (JDIMENSION)
  166341. jdiv_round_up((long) cinfo->image_height *
  166342. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  166343. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  166344. }
  166345. #else /* !IDCT_SCALING_SUPPORTED */
  166346. /* Hardwire it to "no scaling" */
  166347. cinfo->output_width = cinfo->image_width;
  166348. cinfo->output_height = cinfo->image_height;
  166349. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  166350. * and has computed unscaled downsampled_width and downsampled_height.
  166351. */
  166352. #endif /* IDCT_SCALING_SUPPORTED */
  166353. /* Report number of components in selected colorspace. */
  166354. /* Probably this should be in the color conversion module... */
  166355. switch (cinfo->out_color_space) {
  166356. case JCS_GRAYSCALE:
  166357. cinfo->out_color_components = 1;
  166358. break;
  166359. case JCS_RGB:
  166360. #if RGB_PIXELSIZE != 3
  166361. cinfo->out_color_components = RGB_PIXELSIZE;
  166362. break;
  166363. #endif /* else share code with YCbCr */
  166364. case JCS_YCbCr:
  166365. cinfo->out_color_components = 3;
  166366. break;
  166367. case JCS_CMYK:
  166368. case JCS_YCCK:
  166369. cinfo->out_color_components = 4;
  166370. break;
  166371. default: /* else must be same colorspace as in file */
  166372. cinfo->out_color_components = cinfo->num_components;
  166373. break;
  166374. }
  166375. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  166376. cinfo->out_color_components);
  166377. /* See if upsampler will want to emit more than one row at a time */
  166378. if (use_merged_upsample(cinfo))
  166379. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  166380. else
  166381. cinfo->rec_outbuf_height = 1;
  166382. }
  166383. /*
  166384. * Several decompression processes need to range-limit values to the range
  166385. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  166386. * due to noise introduced by quantization, roundoff error, etc. These
  166387. * processes are inner loops and need to be as fast as possible. On most
  166388. * machines, particularly CPUs with pipelines or instruction prefetch,
  166389. * a (subscript-check-less) C table lookup
  166390. * x = sample_range_limit[x];
  166391. * is faster than explicit tests
  166392. * if (x < 0) x = 0;
  166393. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  166394. * These processes all use a common table prepared by the routine below.
  166395. *
  166396. * For most steps we can mathematically guarantee that the initial value
  166397. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  166398. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  166399. * limiting step (just after the IDCT), a wildly out-of-range value is
  166400. * possible if the input data is corrupt. To avoid any chance of indexing
  166401. * off the end of memory and getting a bad-pointer trap, we perform the
  166402. * post-IDCT limiting thus:
  166403. * x = range_limit[x & MASK];
  166404. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  166405. * samples. Under normal circumstances this is more than enough range and
  166406. * a correct output will be generated; with bogus input data the mask will
  166407. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  166408. * For the post-IDCT step, we want to convert the data from signed to unsigned
  166409. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  166410. * So the post-IDCT limiting table ends up looking like this:
  166411. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  166412. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  166413. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  166414. * 0,1,...,CENTERJSAMPLE-1
  166415. * Negative inputs select values from the upper half of the table after
  166416. * masking.
  166417. *
  166418. * We can save some space by overlapping the start of the post-IDCT table
  166419. * with the simpler range limiting table. The post-IDCT table begins at
  166420. * sample_range_limit + CENTERJSAMPLE.
  166421. *
  166422. * Note that the table is allocated in near data space on PCs; it's small
  166423. * enough and used often enough to justify this.
  166424. */
  166425. LOCAL(void)
  166426. prepare_range_limit_table (j_decompress_ptr cinfo)
  166427. /* Allocate and fill in the sample_range_limit table */
  166428. {
  166429. JSAMPLE * table;
  166430. int i;
  166431. table = (JSAMPLE *)
  166432. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166433. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  166434. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  166435. cinfo->sample_range_limit = table;
  166436. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  166437. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  166438. /* Main part of "simple" table: limit[x] = x */
  166439. for (i = 0; i <= MAXJSAMPLE; i++)
  166440. table[i] = (JSAMPLE) i;
  166441. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  166442. /* End of simple table, rest of first half of post-IDCT table */
  166443. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  166444. table[i] = MAXJSAMPLE;
  166445. /* Second half of post-IDCT table */
  166446. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  166447. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  166448. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  166449. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  166450. }
  166451. /*
  166452. * Master selection of decompression modules.
  166453. * This is done once at jpeg_start_decompress time. We determine
  166454. * which modules will be used and give them appropriate initialization calls.
  166455. * We also initialize the decompressor input side to begin consuming data.
  166456. *
  166457. * Since jpeg_read_header has finished, we know what is in the SOF
  166458. * and (first) SOS markers. We also have all the application parameter
  166459. * settings.
  166460. */
  166461. LOCAL(void)
  166462. master_selection (j_decompress_ptr cinfo)
  166463. {
  166464. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  166465. boolean use_c_buffer;
  166466. long samplesperrow;
  166467. JDIMENSION jd_samplesperrow;
  166468. /* Initialize dimensions and other stuff */
  166469. jpeg_calc_output_dimensions(cinfo);
  166470. prepare_range_limit_table(cinfo);
  166471. /* Width of an output scanline must be representable as JDIMENSION. */
  166472. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  166473. jd_samplesperrow = (JDIMENSION) samplesperrow;
  166474. if ((long) jd_samplesperrow != samplesperrow)
  166475. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  166476. /* Initialize my private state */
  166477. master->pass_number = 0;
  166478. master->using_merged_upsample = use_merged_upsample(cinfo);
  166479. /* Color quantizer selection */
  166480. master->quantizer_1pass = NULL;
  166481. master->quantizer_2pass = NULL;
  166482. /* No mode changes if not using buffered-image mode. */
  166483. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  166484. cinfo->enable_1pass_quant = FALSE;
  166485. cinfo->enable_external_quant = FALSE;
  166486. cinfo->enable_2pass_quant = FALSE;
  166487. }
  166488. if (cinfo->quantize_colors) {
  166489. if (cinfo->raw_data_out)
  166490. ERREXIT(cinfo, JERR_NOTIMPL);
  166491. /* 2-pass quantizer only works in 3-component color space. */
  166492. if (cinfo->out_color_components != 3) {
  166493. cinfo->enable_1pass_quant = TRUE;
  166494. cinfo->enable_external_quant = FALSE;
  166495. cinfo->enable_2pass_quant = FALSE;
  166496. cinfo->colormap = NULL;
  166497. } else if (cinfo->colormap != NULL) {
  166498. cinfo->enable_external_quant = TRUE;
  166499. } else if (cinfo->two_pass_quantize) {
  166500. cinfo->enable_2pass_quant = TRUE;
  166501. } else {
  166502. cinfo->enable_1pass_quant = TRUE;
  166503. }
  166504. if (cinfo->enable_1pass_quant) {
  166505. #ifdef QUANT_1PASS_SUPPORTED
  166506. jinit_1pass_quantizer(cinfo);
  166507. master->quantizer_1pass = cinfo->cquantize;
  166508. #else
  166509. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166510. #endif
  166511. }
  166512. /* We use the 2-pass code to map to external colormaps. */
  166513. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  166514. #ifdef QUANT_2PASS_SUPPORTED
  166515. jinit_2pass_quantizer(cinfo);
  166516. master->quantizer_2pass = cinfo->cquantize;
  166517. #else
  166518. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166519. #endif
  166520. }
  166521. /* If both quantizers are initialized, the 2-pass one is left active;
  166522. * this is necessary for starting with quantization to an external map.
  166523. */
  166524. }
  166525. /* Post-processing: in particular, color conversion first */
  166526. if (! cinfo->raw_data_out) {
  166527. if (master->using_merged_upsample) {
  166528. #ifdef UPSAMPLE_MERGING_SUPPORTED
  166529. jinit_merged_upsampler(cinfo); /* does color conversion too */
  166530. #else
  166531. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166532. #endif
  166533. } else {
  166534. jinit_color_deconverter(cinfo);
  166535. jinit_upsampler(cinfo);
  166536. }
  166537. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  166538. }
  166539. /* Inverse DCT */
  166540. jinit_inverse_dct(cinfo);
  166541. /* Entropy decoding: either Huffman or arithmetic coding. */
  166542. if (cinfo->arith_code) {
  166543. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  166544. } else {
  166545. if (cinfo->progressive_mode) {
  166546. #ifdef D_PROGRESSIVE_SUPPORTED
  166547. jinit_phuff_decoder(cinfo);
  166548. #else
  166549. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166550. #endif
  166551. } else
  166552. jinit_huff_decoder(cinfo);
  166553. }
  166554. /* Initialize principal buffer controllers. */
  166555. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  166556. jinit_d_coef_controller(cinfo, use_c_buffer);
  166557. if (! cinfo->raw_data_out)
  166558. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  166559. /* We can now tell the memory manager to allocate virtual arrays. */
  166560. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  166561. /* Initialize input side of decompressor to consume first scan. */
  166562. (*cinfo->inputctl->start_input_pass) (cinfo);
  166563. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166564. /* If jpeg_start_decompress will read the whole file, initialize
  166565. * progress monitoring appropriately. The input step is counted
  166566. * as one pass.
  166567. */
  166568. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  166569. cinfo->inputctl->has_multiple_scans) {
  166570. int nscans;
  166571. /* Estimate number of scans to set pass_limit. */
  166572. if (cinfo->progressive_mode) {
  166573. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  166574. nscans = 2 + 3 * cinfo->num_components;
  166575. } else {
  166576. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  166577. nscans = cinfo->num_components;
  166578. }
  166579. cinfo->progress->pass_counter = 0L;
  166580. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  166581. cinfo->progress->completed_passes = 0;
  166582. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  166583. /* Count the input pass as done */
  166584. master->pass_number++;
  166585. }
  166586. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166587. }
  166588. /*
  166589. * Per-pass setup.
  166590. * This is called at the beginning of each output pass. We determine which
  166591. * modules will be active during this pass and give them appropriate
  166592. * start_pass calls. We also set is_dummy_pass to indicate whether this
  166593. * is a "real" output pass or a dummy pass for color quantization.
  166594. * (In the latter case, jdapistd.c will crank the pass to completion.)
  166595. */
  166596. METHODDEF(void)
  166597. prepare_for_output_pass (j_decompress_ptr cinfo)
  166598. {
  166599. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  166600. if (master->pub.is_dummy_pass) {
  166601. #ifdef QUANT_2PASS_SUPPORTED
  166602. /* Final pass of 2-pass quantization */
  166603. master->pub.is_dummy_pass = FALSE;
  166604. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  166605. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  166606. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  166607. #else
  166608. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166609. #endif /* QUANT_2PASS_SUPPORTED */
  166610. } else {
  166611. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  166612. /* Select new quantization method */
  166613. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  166614. cinfo->cquantize = master->quantizer_2pass;
  166615. master->pub.is_dummy_pass = TRUE;
  166616. } else if (cinfo->enable_1pass_quant) {
  166617. cinfo->cquantize = master->quantizer_1pass;
  166618. } else {
  166619. ERREXIT(cinfo, JERR_MODE_CHANGE);
  166620. }
  166621. }
  166622. (*cinfo->idct->start_pass) (cinfo);
  166623. (*cinfo->coef->start_output_pass) (cinfo);
  166624. if (! cinfo->raw_data_out) {
  166625. if (! master->using_merged_upsample)
  166626. (*cinfo->cconvert->start_pass) (cinfo);
  166627. (*cinfo->upsample->start_pass) (cinfo);
  166628. if (cinfo->quantize_colors)
  166629. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  166630. (*cinfo->post->start_pass) (cinfo,
  166631. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  166632. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  166633. }
  166634. }
  166635. /* Set up progress monitor's pass info if present */
  166636. if (cinfo->progress != NULL) {
  166637. cinfo->progress->completed_passes = master->pass_number;
  166638. cinfo->progress->total_passes = master->pass_number +
  166639. (master->pub.is_dummy_pass ? 2 : 1);
  166640. /* In buffered-image mode, we assume one more output pass if EOI not
  166641. * yet reached, but no more passes if EOI has been reached.
  166642. */
  166643. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  166644. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  166645. }
  166646. }
  166647. }
  166648. /*
  166649. * Finish up at end of an output pass.
  166650. */
  166651. METHODDEF(void)
  166652. finish_output_pass (j_decompress_ptr cinfo)
  166653. {
  166654. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  166655. if (cinfo->quantize_colors)
  166656. (*cinfo->cquantize->finish_pass) (cinfo);
  166657. master->pass_number++;
  166658. }
  166659. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166660. /*
  166661. * Switch to a new external colormap between output passes.
  166662. */
  166663. GLOBAL(void)
  166664. jpeg_new_colormap (j_decompress_ptr cinfo)
  166665. {
  166666. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  166667. /* Prevent application from calling me at wrong times */
  166668. if (cinfo->global_state != DSTATE_BUFIMAGE)
  166669. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166670. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  166671. cinfo->colormap != NULL) {
  166672. /* Select 2-pass quantizer for external colormap use */
  166673. cinfo->cquantize = master->quantizer_2pass;
  166674. /* Notify quantizer of colormap change */
  166675. (*cinfo->cquantize->new_color_map) (cinfo);
  166676. master->pub.is_dummy_pass = FALSE; /* just in case */
  166677. } else
  166678. ERREXIT(cinfo, JERR_MODE_CHANGE);
  166679. }
  166680. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166681. /*
  166682. * Initialize master decompression control and select active modules.
  166683. * This is performed at the start of jpeg_start_decompress.
  166684. */
  166685. GLOBAL(void)
  166686. jinit_master_decompress (j_decompress_ptr cinfo)
  166687. {
  166688. my_master_ptr6 master;
  166689. master = (my_master_ptr6)
  166690. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166691. SIZEOF(my_decomp_master));
  166692. cinfo->master = (struct jpeg_decomp_master *) master;
  166693. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  166694. master->pub.finish_output_pass = finish_output_pass;
  166695. master->pub.is_dummy_pass = FALSE;
  166696. master_selection(cinfo);
  166697. }
  166698. /********* End of inlined file: jdmaster.c *********/
  166699. #undef FIX
  166700. /********* Start of inlined file: jdmerge.c *********/
  166701. #define JPEG_INTERNALS
  166702. #ifdef UPSAMPLE_MERGING_SUPPORTED
  166703. /* Private subobject */
  166704. typedef struct {
  166705. struct jpeg_upsampler pub; /* public fields */
  166706. /* Pointer to routine to do actual upsampling/conversion of one row group */
  166707. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  166708. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  166709. JSAMPARRAY output_buf));
  166710. /* Private state for YCC->RGB conversion */
  166711. int * Cr_r_tab; /* => table for Cr to R conversion */
  166712. int * Cb_b_tab; /* => table for Cb to B conversion */
  166713. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  166714. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  166715. /* For 2:1 vertical sampling, we produce two output rows at a time.
  166716. * We need a "spare" row buffer to hold the second output row if the
  166717. * application provides just a one-row buffer; we also use the spare
  166718. * to discard the dummy last row if the image height is odd.
  166719. */
  166720. JSAMPROW spare_row;
  166721. boolean spare_full; /* T if spare buffer is occupied */
  166722. JDIMENSION out_row_width; /* samples per output row */
  166723. JDIMENSION rows_to_go; /* counts rows remaining in image */
  166724. } my_upsampler;
  166725. typedef my_upsampler * my_upsample_ptr;
  166726. #define SCALEBITS 16 /* speediest right-shift on some machines */
  166727. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  166728. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  166729. /*
  166730. * Initialize tables for YCC->RGB colorspace conversion.
  166731. * This is taken directly from jdcolor.c; see that file for more info.
  166732. */
  166733. LOCAL(void)
  166734. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  166735. {
  166736. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166737. int i;
  166738. INT32 x;
  166739. SHIFT_TEMPS
  166740. upsample->Cr_r_tab = (int *)
  166741. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166742. (MAXJSAMPLE+1) * SIZEOF(int));
  166743. upsample->Cb_b_tab = (int *)
  166744. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166745. (MAXJSAMPLE+1) * SIZEOF(int));
  166746. upsample->Cr_g_tab = (INT32 *)
  166747. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166748. (MAXJSAMPLE+1) * SIZEOF(INT32));
  166749. upsample->Cb_g_tab = (INT32 *)
  166750. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166751. (MAXJSAMPLE+1) * SIZEOF(INT32));
  166752. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  166753. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  166754. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  166755. /* Cr=>R value is nearest int to 1.40200 * x */
  166756. upsample->Cr_r_tab[i] = (int)
  166757. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  166758. /* Cb=>B value is nearest int to 1.77200 * x */
  166759. upsample->Cb_b_tab[i] = (int)
  166760. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  166761. /* Cr=>G value is scaled-up -0.71414 * x */
  166762. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  166763. /* Cb=>G value is scaled-up -0.34414 * x */
  166764. /* We also add in ONE_HALF so that need not do it in inner loop */
  166765. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  166766. }
  166767. }
  166768. /*
  166769. * Initialize for an upsampling pass.
  166770. */
  166771. METHODDEF(void)
  166772. start_pass_merged_upsample (j_decompress_ptr cinfo)
  166773. {
  166774. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166775. /* Mark the spare buffer empty */
  166776. upsample->spare_full = FALSE;
  166777. /* Initialize total-height counter for detecting bottom of image */
  166778. upsample->rows_to_go = cinfo->output_height;
  166779. }
  166780. /*
  166781. * Control routine to do upsampling (and color conversion).
  166782. *
  166783. * The control routine just handles the row buffering considerations.
  166784. */
  166785. METHODDEF(void)
  166786. merged_2v_upsample (j_decompress_ptr cinfo,
  166787. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166788. JDIMENSION in_row_groups_avail,
  166789. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166790. JDIMENSION out_rows_avail)
  166791. /* 2:1 vertical sampling case: may need a spare row. */
  166792. {
  166793. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166794. JSAMPROW work_ptrs[2];
  166795. JDIMENSION num_rows; /* number of rows returned to caller */
  166796. if (upsample->spare_full) {
  166797. /* If we have a spare row saved from a previous cycle, just return it. */
  166798. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  166799. 1, upsample->out_row_width);
  166800. num_rows = 1;
  166801. upsample->spare_full = FALSE;
  166802. } else {
  166803. /* Figure number of rows to return to caller. */
  166804. num_rows = 2;
  166805. /* Not more than the distance to the end of the image. */
  166806. if (num_rows > upsample->rows_to_go)
  166807. num_rows = upsample->rows_to_go;
  166808. /* And not more than what the client can accept: */
  166809. out_rows_avail -= *out_row_ctr;
  166810. if (num_rows > out_rows_avail)
  166811. num_rows = out_rows_avail;
  166812. /* Create output pointer array for upsampler. */
  166813. work_ptrs[0] = output_buf[*out_row_ctr];
  166814. if (num_rows > 1) {
  166815. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  166816. } else {
  166817. work_ptrs[1] = upsample->spare_row;
  166818. upsample->spare_full = TRUE;
  166819. }
  166820. /* Now do the upsampling. */
  166821. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  166822. }
  166823. /* Adjust counts */
  166824. *out_row_ctr += num_rows;
  166825. upsample->rows_to_go -= num_rows;
  166826. /* When the buffer is emptied, declare this input row group consumed */
  166827. if (! upsample->spare_full)
  166828. (*in_row_group_ctr)++;
  166829. }
  166830. METHODDEF(void)
  166831. merged_1v_upsample (j_decompress_ptr cinfo,
  166832. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166833. JDIMENSION in_row_groups_avail,
  166834. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166835. JDIMENSION out_rows_avail)
  166836. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  166837. {
  166838. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166839. /* Just do the upsampling. */
  166840. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  166841. output_buf + *out_row_ctr);
  166842. /* Adjust counts */
  166843. (*out_row_ctr)++;
  166844. (*in_row_group_ctr)++;
  166845. }
  166846. /*
  166847. * These are the routines invoked by the control routines to do
  166848. * the actual upsampling/conversion. One row group is processed per call.
  166849. *
  166850. * Note: since we may be writing directly into application-supplied buffers,
  166851. * we have to be honest about the output width; we can't assume the buffer
  166852. * has been rounded up to an even width.
  166853. */
  166854. /*
  166855. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  166856. */
  166857. METHODDEF(void)
  166858. h2v1_merged_upsample (j_decompress_ptr cinfo,
  166859. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  166860. JSAMPARRAY output_buf)
  166861. {
  166862. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166863. register int y, cred, cgreen, cblue;
  166864. int cb, cr;
  166865. register JSAMPROW outptr;
  166866. JSAMPROW inptr0, inptr1, inptr2;
  166867. JDIMENSION col;
  166868. /* copy these pointers into registers if possible */
  166869. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  166870. int * Crrtab = upsample->Cr_r_tab;
  166871. int * Cbbtab = upsample->Cb_b_tab;
  166872. INT32 * Crgtab = upsample->Cr_g_tab;
  166873. INT32 * Cbgtab = upsample->Cb_g_tab;
  166874. SHIFT_TEMPS
  166875. inptr0 = input_buf[0][in_row_group_ctr];
  166876. inptr1 = input_buf[1][in_row_group_ctr];
  166877. inptr2 = input_buf[2][in_row_group_ctr];
  166878. outptr = output_buf[0];
  166879. /* Loop for each pair of output pixels */
  166880. for (col = cinfo->output_width >> 1; col > 0; col--) {
  166881. /* Do the chroma part of the calculation */
  166882. cb = GETJSAMPLE(*inptr1++);
  166883. cr = GETJSAMPLE(*inptr2++);
  166884. cred = Crrtab[cr];
  166885. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  166886. cblue = Cbbtab[cb];
  166887. /* Fetch 2 Y values and emit 2 pixels */
  166888. y = GETJSAMPLE(*inptr0++);
  166889. outptr[RGB_RED] = range_limit[y + cred];
  166890. outptr[RGB_GREEN] = range_limit[y + cgreen];
  166891. outptr[RGB_BLUE] = range_limit[y + cblue];
  166892. outptr += RGB_PIXELSIZE;
  166893. y = GETJSAMPLE(*inptr0++);
  166894. outptr[RGB_RED] = range_limit[y + cred];
  166895. outptr[RGB_GREEN] = range_limit[y + cgreen];
  166896. outptr[RGB_BLUE] = range_limit[y + cblue];
  166897. outptr += RGB_PIXELSIZE;
  166898. }
  166899. /* If image width is odd, do the last output column separately */
  166900. if (cinfo->output_width & 1) {
  166901. cb = GETJSAMPLE(*inptr1);
  166902. cr = GETJSAMPLE(*inptr2);
  166903. cred = Crrtab[cr];
  166904. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  166905. cblue = Cbbtab[cb];
  166906. y = GETJSAMPLE(*inptr0);
  166907. outptr[RGB_RED] = range_limit[y + cred];
  166908. outptr[RGB_GREEN] = range_limit[y + cgreen];
  166909. outptr[RGB_BLUE] = range_limit[y + cblue];
  166910. }
  166911. }
  166912. /*
  166913. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  166914. */
  166915. METHODDEF(void)
  166916. h2v2_merged_upsample (j_decompress_ptr cinfo,
  166917. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  166918. JSAMPARRAY output_buf)
  166919. {
  166920. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166921. register int y, cred, cgreen, cblue;
  166922. int cb, cr;
  166923. register JSAMPROW outptr0, outptr1;
  166924. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  166925. JDIMENSION col;
  166926. /* copy these pointers into registers if possible */
  166927. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  166928. int * Crrtab = upsample->Cr_r_tab;
  166929. int * Cbbtab = upsample->Cb_b_tab;
  166930. INT32 * Crgtab = upsample->Cr_g_tab;
  166931. INT32 * Cbgtab = upsample->Cb_g_tab;
  166932. SHIFT_TEMPS
  166933. inptr00 = input_buf[0][in_row_group_ctr*2];
  166934. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  166935. inptr1 = input_buf[1][in_row_group_ctr];
  166936. inptr2 = input_buf[2][in_row_group_ctr];
  166937. outptr0 = output_buf[0];
  166938. outptr1 = output_buf[1];
  166939. /* Loop for each group of output pixels */
  166940. for (col = cinfo->output_width >> 1; col > 0; col--) {
  166941. /* Do the chroma part of the calculation */
  166942. cb = GETJSAMPLE(*inptr1++);
  166943. cr = GETJSAMPLE(*inptr2++);
  166944. cred = Crrtab[cr];
  166945. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  166946. cblue = Cbbtab[cb];
  166947. /* Fetch 4 Y values and emit 4 pixels */
  166948. y = GETJSAMPLE(*inptr00++);
  166949. outptr0[RGB_RED] = range_limit[y + cred];
  166950. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  166951. outptr0[RGB_BLUE] = range_limit[y + cblue];
  166952. outptr0 += RGB_PIXELSIZE;
  166953. y = GETJSAMPLE(*inptr00++);
  166954. outptr0[RGB_RED] = range_limit[y + cred];
  166955. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  166956. outptr0[RGB_BLUE] = range_limit[y + cblue];
  166957. outptr0 += RGB_PIXELSIZE;
  166958. y = GETJSAMPLE(*inptr01++);
  166959. outptr1[RGB_RED] = range_limit[y + cred];
  166960. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  166961. outptr1[RGB_BLUE] = range_limit[y + cblue];
  166962. outptr1 += RGB_PIXELSIZE;
  166963. y = GETJSAMPLE(*inptr01++);
  166964. outptr1[RGB_RED] = range_limit[y + cred];
  166965. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  166966. outptr1[RGB_BLUE] = range_limit[y + cblue];
  166967. outptr1 += RGB_PIXELSIZE;
  166968. }
  166969. /* If image width is odd, do the last output column separately */
  166970. if (cinfo->output_width & 1) {
  166971. cb = GETJSAMPLE(*inptr1);
  166972. cr = GETJSAMPLE(*inptr2);
  166973. cred = Crrtab[cr];
  166974. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  166975. cblue = Cbbtab[cb];
  166976. y = GETJSAMPLE(*inptr00);
  166977. outptr0[RGB_RED] = range_limit[y + cred];
  166978. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  166979. outptr0[RGB_BLUE] = range_limit[y + cblue];
  166980. y = GETJSAMPLE(*inptr01);
  166981. outptr1[RGB_RED] = range_limit[y + cred];
  166982. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  166983. outptr1[RGB_BLUE] = range_limit[y + cblue];
  166984. }
  166985. }
  166986. /*
  166987. * Module initialization routine for merged upsampling/color conversion.
  166988. *
  166989. * NB: this is called under the conditions determined by use_merged_upsample()
  166990. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  166991. * of this module; no safety checks are made here.
  166992. */
  166993. GLOBAL(void)
  166994. jinit_merged_upsampler (j_decompress_ptr cinfo)
  166995. {
  166996. my_upsample_ptr upsample;
  166997. upsample = (my_upsample_ptr)
  166998. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166999. SIZEOF(my_upsampler));
  167000. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  167001. upsample->pub.start_pass = start_pass_merged_upsample;
  167002. upsample->pub.need_context_rows = FALSE;
  167003. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  167004. if (cinfo->max_v_samp_factor == 2) {
  167005. upsample->pub.upsample = merged_2v_upsample;
  167006. upsample->upmethod = h2v2_merged_upsample;
  167007. /* Allocate a spare row buffer */
  167008. upsample->spare_row = (JSAMPROW)
  167009. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167010. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  167011. } else {
  167012. upsample->pub.upsample = merged_1v_upsample;
  167013. upsample->upmethod = h2v1_merged_upsample;
  167014. /* No spare row needed */
  167015. upsample->spare_row = NULL;
  167016. }
  167017. build_ycc_rgb_table2(cinfo);
  167018. }
  167019. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  167020. /********* End of inlined file: jdmerge.c *********/
  167021. #undef ASSIGN_STATE
  167022. /********* Start of inlined file: jdphuff.c *********/
  167023. #define JPEG_INTERNALS
  167024. #ifdef D_PROGRESSIVE_SUPPORTED
  167025. /*
  167026. * Expanded entropy decoder object for progressive Huffman decoding.
  167027. *
  167028. * The savable_state subrecord contains fields that change within an MCU,
  167029. * but must not be updated permanently until we complete the MCU.
  167030. */
  167031. typedef struct {
  167032. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  167033. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  167034. } savable_state3;
  167035. /* This macro is to work around compilers with missing or broken
  167036. * structure assignment. You'll need to fix this code if you have
  167037. * such a compiler and you change MAX_COMPS_IN_SCAN.
  167038. */
  167039. #ifndef NO_STRUCT_ASSIGN
  167040. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  167041. #else
  167042. #if MAX_COMPS_IN_SCAN == 4
  167043. #define ASSIGN_STATE(dest,src) \
  167044. ((dest).EOBRUN = (src).EOBRUN, \
  167045. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  167046. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  167047. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  167048. (dest).last_dc_val[3] = (src).last_dc_val[3])
  167049. #endif
  167050. #endif
  167051. typedef struct {
  167052. struct jpeg_entropy_decoder pub; /* public fields */
  167053. /* These fields are loaded into local variables at start of each MCU.
  167054. * In case of suspension, we exit WITHOUT updating them.
  167055. */
  167056. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  167057. savable_state3 saved; /* Other state at start of MCU */
  167058. /* These fields are NOT loaded into local working state. */
  167059. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  167060. /* Pointers to derived tables (these workspaces have image lifespan) */
  167061. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  167062. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  167063. } phuff_entropy_decoder;
  167064. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  167065. /* Forward declarations */
  167066. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  167067. JBLOCKROW *MCU_data));
  167068. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  167069. JBLOCKROW *MCU_data));
  167070. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  167071. JBLOCKROW *MCU_data));
  167072. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  167073. JBLOCKROW *MCU_data));
  167074. /*
  167075. * Initialize for a Huffman-compressed scan.
  167076. */
  167077. METHODDEF(void)
  167078. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  167079. {
  167080. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167081. boolean is_DC_band, bad;
  167082. int ci, coefi, tbl;
  167083. int *coef_bit_ptr;
  167084. jpeg_component_info * compptr;
  167085. is_DC_band = (cinfo->Ss == 0);
  167086. /* Validate scan parameters */
  167087. bad = FALSE;
  167088. if (is_DC_band) {
  167089. if (cinfo->Se != 0)
  167090. bad = TRUE;
  167091. } else {
  167092. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  167093. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  167094. bad = TRUE;
  167095. /* AC scans may have only one component */
  167096. if (cinfo->comps_in_scan != 1)
  167097. bad = TRUE;
  167098. }
  167099. if (cinfo->Ah != 0) {
  167100. /* Successive approximation refinement scan: must have Al = Ah-1. */
  167101. if (cinfo->Al != cinfo->Ah-1)
  167102. bad = TRUE;
  167103. }
  167104. if (cinfo->Al > 13) /* need not check for < 0 */
  167105. bad = TRUE;
  167106. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  167107. * but the spec doesn't say so, and we try to be liberal about what we
  167108. * accept. Note: large Al values could result in out-of-range DC
  167109. * coefficients during early scans, leading to bizarre displays due to
  167110. * overflows in the IDCT math. But we won't crash.
  167111. */
  167112. if (bad)
  167113. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  167114. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  167115. /* Update progression status, and verify that scan order is legal.
  167116. * Note that inter-scan inconsistencies are treated as warnings
  167117. * not fatal errors ... not clear if this is right way to behave.
  167118. */
  167119. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167120. int cindex = cinfo->cur_comp_info[ci]->component_index;
  167121. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  167122. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  167123. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  167124. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  167125. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  167126. if (cinfo->Ah != expected)
  167127. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  167128. coef_bit_ptr[coefi] = cinfo->Al;
  167129. }
  167130. }
  167131. /* Select MCU decoding routine */
  167132. if (cinfo->Ah == 0) {
  167133. if (is_DC_band)
  167134. entropy->pub.decode_mcu = decode_mcu_DC_first;
  167135. else
  167136. entropy->pub.decode_mcu = decode_mcu_AC_first;
  167137. } else {
  167138. if (is_DC_band)
  167139. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  167140. else
  167141. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  167142. }
  167143. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167144. compptr = cinfo->cur_comp_info[ci];
  167145. /* Make sure requested tables are present, and compute derived tables.
  167146. * We may build same derived table more than once, but it's not expensive.
  167147. */
  167148. if (is_DC_band) {
  167149. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  167150. tbl = compptr->dc_tbl_no;
  167151. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  167152. & entropy->derived_tbls[tbl]);
  167153. }
  167154. } else {
  167155. tbl = compptr->ac_tbl_no;
  167156. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  167157. & entropy->derived_tbls[tbl]);
  167158. /* remember the single active table */
  167159. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  167160. }
  167161. /* Initialize DC predictions to 0 */
  167162. entropy->saved.last_dc_val[ci] = 0;
  167163. }
  167164. /* Initialize bitread state variables */
  167165. entropy->bitstate.bits_left = 0;
  167166. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  167167. entropy->pub.insufficient_data = FALSE;
  167168. /* Initialize private state variables */
  167169. entropy->saved.EOBRUN = 0;
  167170. /* Initialize restart counter */
  167171. entropy->restarts_to_go = cinfo->restart_interval;
  167172. }
  167173. /*
  167174. * Check for a restart marker & resynchronize decoder.
  167175. * Returns FALSE if must suspend.
  167176. */
  167177. LOCAL(boolean)
  167178. process_restartp (j_decompress_ptr cinfo)
  167179. {
  167180. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167181. int ci;
  167182. /* Throw away any unused bits remaining in bit buffer; */
  167183. /* include any full bytes in next_marker's count of discarded bytes */
  167184. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  167185. entropy->bitstate.bits_left = 0;
  167186. /* Advance past the RSTn marker */
  167187. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  167188. return FALSE;
  167189. /* Re-initialize DC predictions to 0 */
  167190. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  167191. entropy->saved.last_dc_val[ci] = 0;
  167192. /* Re-init EOB run count, too */
  167193. entropy->saved.EOBRUN = 0;
  167194. /* Reset restart counter */
  167195. entropy->restarts_to_go = cinfo->restart_interval;
  167196. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  167197. * against a marker. In that case we will end up treating the next data
  167198. * segment as empty, and we can avoid producing bogus output pixels by
  167199. * leaving the flag set.
  167200. */
  167201. if (cinfo->unread_marker == 0)
  167202. entropy->pub.insufficient_data = FALSE;
  167203. return TRUE;
  167204. }
  167205. /*
  167206. * Huffman MCU decoding.
  167207. * Each of these routines decodes and returns one MCU's worth of
  167208. * Huffman-compressed coefficients.
  167209. * The coefficients are reordered from zigzag order into natural array order,
  167210. * but are not dequantized.
  167211. *
  167212. * The i'th block of the MCU is stored into the block pointed to by
  167213. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  167214. *
  167215. * We return FALSE if data source requested suspension. In that case no
  167216. * changes have been made to permanent state. (Exception: some output
  167217. * coefficients may already have been assigned. This is harmless for
  167218. * spectral selection, since we'll just re-assign them on the next call.
  167219. * Successive approximation AC refinement has to be more careful, however.)
  167220. */
  167221. /*
  167222. * MCU decoding for DC initial scan (either spectral selection,
  167223. * or first pass of successive approximation).
  167224. */
  167225. METHODDEF(boolean)
  167226. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  167227. {
  167228. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167229. int Al = cinfo->Al;
  167230. register int s, r;
  167231. int blkn, ci;
  167232. JBLOCKROW block;
  167233. BITREAD_STATE_VARS;
  167234. savable_state3 state;
  167235. d_derived_tbl * tbl;
  167236. jpeg_component_info * compptr;
  167237. /* Process restart marker if needed; may have to suspend */
  167238. if (cinfo->restart_interval) {
  167239. if (entropy->restarts_to_go == 0)
  167240. if (! process_restartp(cinfo))
  167241. return FALSE;
  167242. }
  167243. /* If we've run out of data, just leave the MCU set to zeroes.
  167244. * This way, we return uniform gray for the remainder of the segment.
  167245. */
  167246. if (! entropy->pub.insufficient_data) {
  167247. /* Load up working state */
  167248. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  167249. ASSIGN_STATE(state, entropy->saved);
  167250. /* Outer loop handles each block in the MCU */
  167251. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  167252. block = MCU_data[blkn];
  167253. ci = cinfo->MCU_membership[blkn];
  167254. compptr = cinfo->cur_comp_info[ci];
  167255. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  167256. /* Decode a single block's worth of coefficients */
  167257. /* Section F.2.2.1: decode the DC coefficient difference */
  167258. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  167259. if (s) {
  167260. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  167261. r = GET_BITS(s);
  167262. s = HUFF_EXTEND(r, s);
  167263. }
  167264. /* Convert DC difference to actual value, update last_dc_val */
  167265. s += state.last_dc_val[ci];
  167266. state.last_dc_val[ci] = s;
  167267. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  167268. (*block)[0] = (JCOEF) (s << Al);
  167269. }
  167270. /* Completed MCU, so update state */
  167271. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  167272. ASSIGN_STATE(entropy->saved, state);
  167273. }
  167274. /* Account for restart interval (no-op if not using restarts) */
  167275. entropy->restarts_to_go--;
  167276. return TRUE;
  167277. }
  167278. /*
  167279. * MCU decoding for AC initial scan (either spectral selection,
  167280. * or first pass of successive approximation).
  167281. */
  167282. METHODDEF(boolean)
  167283. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  167284. {
  167285. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167286. int Se = cinfo->Se;
  167287. int Al = cinfo->Al;
  167288. register int s, k, r;
  167289. unsigned int EOBRUN;
  167290. JBLOCKROW block;
  167291. BITREAD_STATE_VARS;
  167292. d_derived_tbl * tbl;
  167293. /* Process restart marker if needed; may have to suspend */
  167294. if (cinfo->restart_interval) {
  167295. if (entropy->restarts_to_go == 0)
  167296. if (! process_restartp(cinfo))
  167297. return FALSE;
  167298. }
  167299. /* If we've run out of data, just leave the MCU set to zeroes.
  167300. * This way, we return uniform gray for the remainder of the segment.
  167301. */
  167302. if (! entropy->pub.insufficient_data) {
  167303. /* Load up working state.
  167304. * We can avoid loading/saving bitread state if in an EOB run.
  167305. */
  167306. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  167307. /* There is always only one block per MCU */
  167308. if (EOBRUN > 0) /* if it's a band of zeroes... */
  167309. EOBRUN--; /* ...process it now (we do nothing) */
  167310. else {
  167311. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  167312. block = MCU_data[0];
  167313. tbl = entropy->ac_derived_tbl;
  167314. for (k = cinfo->Ss; k <= Se; k++) {
  167315. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  167316. r = s >> 4;
  167317. s &= 15;
  167318. if (s) {
  167319. k += r;
  167320. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  167321. r = GET_BITS(s);
  167322. s = HUFF_EXTEND(r, s);
  167323. /* Scale and output coefficient in natural (dezigzagged) order */
  167324. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  167325. } else {
  167326. if (r == 15) { /* ZRL */
  167327. k += 15; /* skip 15 zeroes in band */
  167328. } else { /* EOBr, run length is 2^r + appended bits */
  167329. EOBRUN = 1 << r;
  167330. if (r) { /* EOBr, r > 0 */
  167331. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  167332. r = GET_BITS(r);
  167333. EOBRUN += r;
  167334. }
  167335. EOBRUN--; /* this band is processed at this moment */
  167336. break; /* force end-of-band */
  167337. }
  167338. }
  167339. }
  167340. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  167341. }
  167342. /* Completed MCU, so update state */
  167343. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  167344. }
  167345. /* Account for restart interval (no-op if not using restarts) */
  167346. entropy->restarts_to_go--;
  167347. return TRUE;
  167348. }
  167349. /*
  167350. * MCU decoding for DC successive approximation refinement scan.
  167351. * Note: we assume such scans can be multi-component, although the spec
  167352. * is not very clear on the point.
  167353. */
  167354. METHODDEF(boolean)
  167355. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  167356. {
  167357. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167358. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  167359. int blkn;
  167360. JBLOCKROW block;
  167361. BITREAD_STATE_VARS;
  167362. /* Process restart marker if needed; may have to suspend */
  167363. if (cinfo->restart_interval) {
  167364. if (entropy->restarts_to_go == 0)
  167365. if (! process_restartp(cinfo))
  167366. return FALSE;
  167367. }
  167368. /* Not worth the cycles to check insufficient_data here,
  167369. * since we will not change the data anyway if we read zeroes.
  167370. */
  167371. /* Load up working state */
  167372. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  167373. /* Outer loop handles each block in the MCU */
  167374. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  167375. block = MCU_data[blkn];
  167376. /* Encoded data is simply the next bit of the two's-complement DC value */
  167377. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  167378. if (GET_BITS(1))
  167379. (*block)[0] |= p1;
  167380. /* Note: since we use |=, repeating the assignment later is safe */
  167381. }
  167382. /* Completed MCU, so update state */
  167383. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  167384. /* Account for restart interval (no-op if not using restarts) */
  167385. entropy->restarts_to_go--;
  167386. return TRUE;
  167387. }
  167388. /*
  167389. * MCU decoding for AC successive approximation refinement scan.
  167390. */
  167391. METHODDEF(boolean)
  167392. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  167393. {
  167394. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167395. int Se = cinfo->Se;
  167396. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  167397. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  167398. register int s, k, r;
  167399. unsigned int EOBRUN;
  167400. JBLOCKROW block;
  167401. JCOEFPTR thiscoef;
  167402. BITREAD_STATE_VARS;
  167403. d_derived_tbl * tbl;
  167404. int num_newnz;
  167405. int newnz_pos[DCTSIZE2];
  167406. /* Process restart marker if needed; may have to suspend */
  167407. if (cinfo->restart_interval) {
  167408. if (entropy->restarts_to_go == 0)
  167409. if (! process_restartp(cinfo))
  167410. return FALSE;
  167411. }
  167412. /* If we've run out of data, don't modify the MCU.
  167413. */
  167414. if (! entropy->pub.insufficient_data) {
  167415. /* Load up working state */
  167416. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  167417. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  167418. /* There is always only one block per MCU */
  167419. block = MCU_data[0];
  167420. tbl = entropy->ac_derived_tbl;
  167421. /* If we are forced to suspend, we must undo the assignments to any newly
  167422. * nonzero coefficients in the block, because otherwise we'd get confused
  167423. * next time about which coefficients were already nonzero.
  167424. * But we need not undo addition of bits to already-nonzero coefficients;
  167425. * instead, we can test the current bit to see if we already did it.
  167426. */
  167427. num_newnz = 0;
  167428. /* initialize coefficient loop counter to start of band */
  167429. k = cinfo->Ss;
  167430. if (EOBRUN == 0) {
  167431. for (; k <= Se; k++) {
  167432. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  167433. r = s >> 4;
  167434. s &= 15;
  167435. if (s) {
  167436. if (s != 1) /* size of new coef should always be 1 */
  167437. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  167438. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  167439. if (GET_BITS(1))
  167440. s = p1; /* newly nonzero coef is positive */
  167441. else
  167442. s = m1; /* newly nonzero coef is negative */
  167443. } else {
  167444. if (r != 15) {
  167445. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  167446. if (r) {
  167447. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  167448. r = GET_BITS(r);
  167449. EOBRUN += r;
  167450. }
  167451. break; /* rest of block is handled by EOB logic */
  167452. }
  167453. /* note s = 0 for processing ZRL */
  167454. }
  167455. /* Advance over already-nonzero coefs and r still-zero coefs,
  167456. * appending correction bits to the nonzeroes. A correction bit is 1
  167457. * if the absolute value of the coefficient must be increased.
  167458. */
  167459. do {
  167460. thiscoef = *block + jpeg_natural_order[k];
  167461. if (*thiscoef != 0) {
  167462. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  167463. if (GET_BITS(1)) {
  167464. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  167465. if (*thiscoef >= 0)
  167466. *thiscoef += p1;
  167467. else
  167468. *thiscoef += m1;
  167469. }
  167470. }
  167471. } else {
  167472. if (--r < 0)
  167473. break; /* reached target zero coefficient */
  167474. }
  167475. k++;
  167476. } while (k <= Se);
  167477. if (s) {
  167478. int pos = jpeg_natural_order[k];
  167479. /* Output newly nonzero coefficient */
  167480. (*block)[pos] = (JCOEF) s;
  167481. /* Remember its position in case we have to suspend */
  167482. newnz_pos[num_newnz++] = pos;
  167483. }
  167484. }
  167485. }
  167486. if (EOBRUN > 0) {
  167487. /* Scan any remaining coefficient positions after the end-of-band
  167488. * (the last newly nonzero coefficient, if any). Append a correction
  167489. * bit to each already-nonzero coefficient. A correction bit is 1
  167490. * if the absolute value of the coefficient must be increased.
  167491. */
  167492. for (; k <= Se; k++) {
  167493. thiscoef = *block + jpeg_natural_order[k];
  167494. if (*thiscoef != 0) {
  167495. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  167496. if (GET_BITS(1)) {
  167497. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  167498. if (*thiscoef >= 0)
  167499. *thiscoef += p1;
  167500. else
  167501. *thiscoef += m1;
  167502. }
  167503. }
  167504. }
  167505. }
  167506. /* Count one block completed in EOB run */
  167507. EOBRUN--;
  167508. }
  167509. /* Completed MCU, so update state */
  167510. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  167511. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  167512. }
  167513. /* Account for restart interval (no-op if not using restarts) */
  167514. entropy->restarts_to_go--;
  167515. return TRUE;
  167516. undoit:
  167517. /* Re-zero any output coefficients that we made newly nonzero */
  167518. while (num_newnz > 0)
  167519. (*block)[newnz_pos[--num_newnz]] = 0;
  167520. return FALSE;
  167521. }
  167522. /*
  167523. * Module initialization routine for progressive Huffman entropy decoding.
  167524. */
  167525. GLOBAL(void)
  167526. jinit_phuff_decoder (j_decompress_ptr cinfo)
  167527. {
  167528. phuff_entropy_ptr2 entropy;
  167529. int *coef_bit_ptr;
  167530. int ci, i;
  167531. entropy = (phuff_entropy_ptr2)
  167532. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167533. SIZEOF(phuff_entropy_decoder));
  167534. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  167535. entropy->pub.start_pass = start_pass_phuff_decoder;
  167536. /* Mark derived tables unallocated */
  167537. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167538. entropy->derived_tbls[i] = NULL;
  167539. }
  167540. /* Create progression status table */
  167541. cinfo->coef_bits = (int (*)[DCTSIZE2])
  167542. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167543. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  167544. coef_bit_ptr = & cinfo->coef_bits[0][0];
  167545. for (ci = 0; ci < cinfo->num_components; ci++)
  167546. for (i = 0; i < DCTSIZE2; i++)
  167547. *coef_bit_ptr++ = -1;
  167548. }
  167549. #endif /* D_PROGRESSIVE_SUPPORTED */
  167550. /********* End of inlined file: jdphuff.c *********/
  167551. /********* Start of inlined file: jdpostct.c *********/
  167552. #define JPEG_INTERNALS
  167553. /* Private buffer controller object */
  167554. typedef struct {
  167555. struct jpeg_d_post_controller pub; /* public fields */
  167556. /* Color quantization source buffer: this holds output data from
  167557. * the upsample/color conversion step to be passed to the quantizer.
  167558. * For two-pass color quantization, we need a full-image buffer;
  167559. * for one-pass operation, a strip buffer is sufficient.
  167560. */
  167561. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  167562. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  167563. JDIMENSION strip_height; /* buffer size in rows */
  167564. /* for two-pass mode only: */
  167565. JDIMENSION starting_row; /* row # of first row in current strip */
  167566. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  167567. } my_post_controller;
  167568. typedef my_post_controller * my_post_ptr;
  167569. /* Forward declarations */
  167570. METHODDEF(void) post_process_1pass
  167571. JPP((j_decompress_ptr cinfo,
  167572. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167573. JDIMENSION in_row_groups_avail,
  167574. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167575. JDIMENSION out_rows_avail));
  167576. #ifdef QUANT_2PASS_SUPPORTED
  167577. METHODDEF(void) post_process_prepass
  167578. JPP((j_decompress_ptr cinfo,
  167579. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167580. JDIMENSION in_row_groups_avail,
  167581. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167582. JDIMENSION out_rows_avail));
  167583. METHODDEF(void) post_process_2pass
  167584. JPP((j_decompress_ptr cinfo,
  167585. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167586. JDIMENSION in_row_groups_avail,
  167587. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167588. JDIMENSION out_rows_avail));
  167589. #endif
  167590. /*
  167591. * Initialize for a processing pass.
  167592. */
  167593. METHODDEF(void)
  167594. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  167595. {
  167596. my_post_ptr post = (my_post_ptr) cinfo->post;
  167597. switch (pass_mode) {
  167598. case JBUF_PASS_THRU:
  167599. if (cinfo->quantize_colors) {
  167600. /* Single-pass processing with color quantization. */
  167601. post->pub.post_process_data = post_process_1pass;
  167602. /* We could be doing buffered-image output before starting a 2-pass
  167603. * color quantization; in that case, jinit_d_post_controller did not
  167604. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  167605. */
  167606. if (post->buffer == NULL) {
  167607. post->buffer = (*cinfo->mem->access_virt_sarray)
  167608. ((j_common_ptr) cinfo, post->whole_image,
  167609. (JDIMENSION) 0, post->strip_height, TRUE);
  167610. }
  167611. } else {
  167612. /* For single-pass processing without color quantization,
  167613. * I have no work to do; just call the upsampler directly.
  167614. */
  167615. post->pub.post_process_data = cinfo->upsample->upsample;
  167616. }
  167617. break;
  167618. #ifdef QUANT_2PASS_SUPPORTED
  167619. case JBUF_SAVE_AND_PASS:
  167620. /* First pass of 2-pass quantization */
  167621. if (post->whole_image == NULL)
  167622. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167623. post->pub.post_process_data = post_process_prepass;
  167624. break;
  167625. case JBUF_CRANK_DEST:
  167626. /* Second pass of 2-pass quantization */
  167627. if (post->whole_image == NULL)
  167628. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167629. post->pub.post_process_data = post_process_2pass;
  167630. break;
  167631. #endif /* QUANT_2PASS_SUPPORTED */
  167632. default:
  167633. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167634. break;
  167635. }
  167636. post->starting_row = post->next_row = 0;
  167637. }
  167638. /*
  167639. * Process some data in the one-pass (strip buffer) case.
  167640. * This is used for color precision reduction as well as one-pass quantization.
  167641. */
  167642. METHODDEF(void)
  167643. post_process_1pass (j_decompress_ptr cinfo,
  167644. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167645. JDIMENSION in_row_groups_avail,
  167646. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167647. JDIMENSION out_rows_avail)
  167648. {
  167649. my_post_ptr post = (my_post_ptr) cinfo->post;
  167650. JDIMENSION num_rows, max_rows;
  167651. /* Fill the buffer, but not more than what we can dump out in one go. */
  167652. /* Note we rely on the upsampler to detect bottom of image. */
  167653. max_rows = out_rows_avail - *out_row_ctr;
  167654. if (max_rows > post->strip_height)
  167655. max_rows = post->strip_height;
  167656. num_rows = 0;
  167657. (*cinfo->upsample->upsample) (cinfo,
  167658. input_buf, in_row_group_ctr, in_row_groups_avail,
  167659. post->buffer, &num_rows, max_rows);
  167660. /* Quantize and emit data. */
  167661. (*cinfo->cquantize->color_quantize) (cinfo,
  167662. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  167663. *out_row_ctr += num_rows;
  167664. }
  167665. #ifdef QUANT_2PASS_SUPPORTED
  167666. /*
  167667. * Process some data in the first pass of 2-pass quantization.
  167668. */
  167669. METHODDEF(void)
  167670. post_process_prepass (j_decompress_ptr cinfo,
  167671. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167672. JDIMENSION in_row_groups_avail,
  167673. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167674. JDIMENSION out_rows_avail)
  167675. {
  167676. my_post_ptr post = (my_post_ptr) cinfo->post;
  167677. JDIMENSION old_next_row, num_rows;
  167678. /* Reposition virtual buffer if at start of strip. */
  167679. if (post->next_row == 0) {
  167680. post->buffer = (*cinfo->mem->access_virt_sarray)
  167681. ((j_common_ptr) cinfo, post->whole_image,
  167682. post->starting_row, post->strip_height, TRUE);
  167683. }
  167684. /* Upsample some data (up to a strip height's worth). */
  167685. old_next_row = post->next_row;
  167686. (*cinfo->upsample->upsample) (cinfo,
  167687. input_buf, in_row_group_ctr, in_row_groups_avail,
  167688. post->buffer, &post->next_row, post->strip_height);
  167689. /* Allow quantizer to scan new data. No data is emitted, */
  167690. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  167691. if (post->next_row > old_next_row) {
  167692. num_rows = post->next_row - old_next_row;
  167693. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  167694. (JSAMPARRAY) NULL, (int) num_rows);
  167695. *out_row_ctr += num_rows;
  167696. }
  167697. /* Advance if we filled the strip. */
  167698. if (post->next_row >= post->strip_height) {
  167699. post->starting_row += post->strip_height;
  167700. post->next_row = 0;
  167701. }
  167702. }
  167703. /*
  167704. * Process some data in the second pass of 2-pass quantization.
  167705. */
  167706. METHODDEF(void)
  167707. post_process_2pass (j_decompress_ptr cinfo,
  167708. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167709. JDIMENSION in_row_groups_avail,
  167710. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167711. JDIMENSION out_rows_avail)
  167712. {
  167713. my_post_ptr post = (my_post_ptr) cinfo->post;
  167714. JDIMENSION num_rows, max_rows;
  167715. /* Reposition virtual buffer if at start of strip. */
  167716. if (post->next_row == 0) {
  167717. post->buffer = (*cinfo->mem->access_virt_sarray)
  167718. ((j_common_ptr) cinfo, post->whole_image,
  167719. post->starting_row, post->strip_height, FALSE);
  167720. }
  167721. /* Determine number of rows to emit. */
  167722. num_rows = post->strip_height - post->next_row; /* available in strip */
  167723. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  167724. if (num_rows > max_rows)
  167725. num_rows = max_rows;
  167726. /* We have to check bottom of image here, can't depend on upsampler. */
  167727. max_rows = cinfo->output_height - post->starting_row;
  167728. if (num_rows > max_rows)
  167729. num_rows = max_rows;
  167730. /* Quantize and emit data. */
  167731. (*cinfo->cquantize->color_quantize) (cinfo,
  167732. post->buffer + post->next_row, output_buf + *out_row_ctr,
  167733. (int) num_rows);
  167734. *out_row_ctr += num_rows;
  167735. /* Advance if we filled the strip. */
  167736. post->next_row += num_rows;
  167737. if (post->next_row >= post->strip_height) {
  167738. post->starting_row += post->strip_height;
  167739. post->next_row = 0;
  167740. }
  167741. }
  167742. #endif /* QUANT_2PASS_SUPPORTED */
  167743. /*
  167744. * Initialize postprocessing controller.
  167745. */
  167746. GLOBAL(void)
  167747. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  167748. {
  167749. my_post_ptr post;
  167750. post = (my_post_ptr)
  167751. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167752. SIZEOF(my_post_controller));
  167753. cinfo->post = (struct jpeg_d_post_controller *) post;
  167754. post->pub.start_pass = start_pass_dpost;
  167755. post->whole_image = NULL; /* flag for no virtual arrays */
  167756. post->buffer = NULL; /* flag for no strip buffer */
  167757. /* Create the quantization buffer, if needed */
  167758. if (cinfo->quantize_colors) {
  167759. /* The buffer strip height is max_v_samp_factor, which is typically
  167760. * an efficient number of rows for upsampling to return.
  167761. * (In the presence of output rescaling, we might want to be smarter?)
  167762. */
  167763. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  167764. if (need_full_buffer) {
  167765. /* Two-pass color quantization: need full-image storage. */
  167766. /* We round up the number of rows to a multiple of the strip height. */
  167767. #ifdef QUANT_2PASS_SUPPORTED
  167768. post->whole_image = (*cinfo->mem->request_virt_sarray)
  167769. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  167770. cinfo->output_width * cinfo->out_color_components,
  167771. (JDIMENSION) jround_up((long) cinfo->output_height,
  167772. (long) post->strip_height),
  167773. post->strip_height);
  167774. #else
  167775. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167776. #endif /* QUANT_2PASS_SUPPORTED */
  167777. } else {
  167778. /* One-pass color quantization: just make a strip buffer. */
  167779. post->buffer = (*cinfo->mem->alloc_sarray)
  167780. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167781. cinfo->output_width * cinfo->out_color_components,
  167782. post->strip_height);
  167783. }
  167784. }
  167785. }
  167786. /********* End of inlined file: jdpostct.c *********/
  167787. #undef FIX
  167788. /********* Start of inlined file: jdsample.c *********/
  167789. #define JPEG_INTERNALS
  167790. /* Pointer to routine to upsample a single component */
  167791. typedef JMETHOD(void, upsample1_ptr,
  167792. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167793. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  167794. /* Private subobject */
  167795. typedef struct {
  167796. struct jpeg_upsampler pub; /* public fields */
  167797. /* Color conversion buffer. When using separate upsampling and color
  167798. * conversion steps, this buffer holds one upsampled row group until it
  167799. * has been color converted and output.
  167800. * Note: we do not allocate any storage for component(s) which are full-size,
  167801. * ie do not need rescaling. The corresponding entry of color_buf[] is
  167802. * simply set to point to the input data array, thereby avoiding copying.
  167803. */
  167804. JSAMPARRAY color_buf[MAX_COMPONENTS];
  167805. /* Per-component upsampling method pointers */
  167806. upsample1_ptr methods[MAX_COMPONENTS];
  167807. int next_row_out; /* counts rows emitted from color_buf */
  167808. JDIMENSION rows_to_go; /* counts rows remaining in image */
  167809. /* Height of an input row group for each component. */
  167810. int rowgroup_height[MAX_COMPONENTS];
  167811. /* These arrays save pixel expansion factors so that int_expand need not
  167812. * recompute them each time. They are unused for other upsampling methods.
  167813. */
  167814. UINT8 h_expand[MAX_COMPONENTS];
  167815. UINT8 v_expand[MAX_COMPONENTS];
  167816. } my_upsampler2;
  167817. typedef my_upsampler2 * my_upsample_ptr2;
  167818. /*
  167819. * Initialize for an upsampling pass.
  167820. */
  167821. METHODDEF(void)
  167822. start_pass_upsample (j_decompress_ptr cinfo)
  167823. {
  167824. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  167825. /* Mark the conversion buffer empty */
  167826. upsample->next_row_out = cinfo->max_v_samp_factor;
  167827. /* Initialize total-height counter for detecting bottom of image */
  167828. upsample->rows_to_go = cinfo->output_height;
  167829. }
  167830. /*
  167831. * Control routine to do upsampling (and color conversion).
  167832. *
  167833. * In this version we upsample each component independently.
  167834. * We upsample one row group into the conversion buffer, then apply
  167835. * color conversion a row at a time.
  167836. */
  167837. METHODDEF(void)
  167838. sep_upsample (j_decompress_ptr cinfo,
  167839. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167840. JDIMENSION in_row_groups_avail,
  167841. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167842. JDIMENSION out_rows_avail)
  167843. {
  167844. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  167845. int ci;
  167846. jpeg_component_info * compptr;
  167847. JDIMENSION num_rows;
  167848. /* Fill the conversion buffer, if it's empty */
  167849. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  167850. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167851. ci++, compptr++) {
  167852. /* Invoke per-component upsample method. Notice we pass a POINTER
  167853. * to color_buf[ci], so that fullsize_upsample can change it.
  167854. */
  167855. (*upsample->methods[ci]) (cinfo, compptr,
  167856. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  167857. upsample->color_buf + ci);
  167858. }
  167859. upsample->next_row_out = 0;
  167860. }
  167861. /* Color-convert and emit rows */
  167862. /* How many we have in the buffer: */
  167863. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  167864. /* Not more than the distance to the end of the image. Need this test
  167865. * in case the image height is not a multiple of max_v_samp_factor:
  167866. */
  167867. if (num_rows > upsample->rows_to_go)
  167868. num_rows = upsample->rows_to_go;
  167869. /* And not more than what the client can accept: */
  167870. out_rows_avail -= *out_row_ctr;
  167871. if (num_rows > out_rows_avail)
  167872. num_rows = out_rows_avail;
  167873. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  167874. (JDIMENSION) upsample->next_row_out,
  167875. output_buf + *out_row_ctr,
  167876. (int) num_rows);
  167877. /* Adjust counts */
  167878. *out_row_ctr += num_rows;
  167879. upsample->rows_to_go -= num_rows;
  167880. upsample->next_row_out += num_rows;
  167881. /* When the buffer is emptied, declare this input row group consumed */
  167882. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  167883. (*in_row_group_ctr)++;
  167884. }
  167885. /*
  167886. * These are the routines invoked by sep_upsample to upsample pixel values
  167887. * of a single component. One row group is processed per call.
  167888. */
  167889. /*
  167890. * For full-size components, we just make color_buf[ci] point at the
  167891. * input buffer, and thus avoid copying any data. Note that this is
  167892. * safe only because sep_upsample doesn't declare the input row group
  167893. * "consumed" until we are done color converting and emitting it.
  167894. */
  167895. METHODDEF(void)
  167896. fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167897. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167898. {
  167899. *output_data_ptr = input_data;
  167900. }
  167901. /*
  167902. * This is a no-op version used for "uninteresting" components.
  167903. * These components will not be referenced by color conversion.
  167904. */
  167905. METHODDEF(void)
  167906. noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167907. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167908. {
  167909. *output_data_ptr = NULL; /* safety check */
  167910. }
  167911. /*
  167912. * This version handles any integral sampling ratios.
  167913. * This is not used for typical JPEG files, so it need not be fast.
  167914. * Nor, for that matter, is it particularly accurate: the algorithm is
  167915. * simple replication of the input pixel onto the corresponding output
  167916. * pixels. The hi-falutin sampling literature refers to this as a
  167917. * "box filter". A box filter tends to introduce visible artifacts,
  167918. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  167919. * you would be well advised to improve this code.
  167920. */
  167921. METHODDEF(void)
  167922. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167923. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167924. {
  167925. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  167926. JSAMPARRAY output_data = *output_data_ptr;
  167927. register JSAMPROW inptr, outptr;
  167928. register JSAMPLE invalue;
  167929. register int h;
  167930. JSAMPROW outend;
  167931. int h_expand, v_expand;
  167932. int inrow, outrow;
  167933. h_expand = upsample->h_expand[compptr->component_index];
  167934. v_expand = upsample->v_expand[compptr->component_index];
  167935. inrow = outrow = 0;
  167936. while (outrow < cinfo->max_v_samp_factor) {
  167937. /* Generate one output row with proper horizontal expansion */
  167938. inptr = input_data[inrow];
  167939. outptr = output_data[outrow];
  167940. outend = outptr + cinfo->output_width;
  167941. while (outptr < outend) {
  167942. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  167943. for (h = h_expand; h > 0; h--) {
  167944. *outptr++ = invalue;
  167945. }
  167946. }
  167947. /* Generate any additional output rows by duplicating the first one */
  167948. if (v_expand > 1) {
  167949. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  167950. v_expand-1, cinfo->output_width);
  167951. }
  167952. inrow++;
  167953. outrow += v_expand;
  167954. }
  167955. }
  167956. /*
  167957. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  167958. * It's still a box filter.
  167959. */
  167960. METHODDEF(void)
  167961. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167962. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167963. {
  167964. JSAMPARRAY output_data = *output_data_ptr;
  167965. register JSAMPROW inptr, outptr;
  167966. register JSAMPLE invalue;
  167967. JSAMPROW outend;
  167968. int inrow;
  167969. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  167970. inptr = input_data[inrow];
  167971. outptr = output_data[inrow];
  167972. outend = outptr + cinfo->output_width;
  167973. while (outptr < outend) {
  167974. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  167975. *outptr++ = invalue;
  167976. *outptr++ = invalue;
  167977. }
  167978. }
  167979. }
  167980. /*
  167981. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  167982. * It's still a box filter.
  167983. */
  167984. METHODDEF(void)
  167985. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167986. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167987. {
  167988. JSAMPARRAY output_data = *output_data_ptr;
  167989. register JSAMPROW inptr, outptr;
  167990. register JSAMPLE invalue;
  167991. JSAMPROW outend;
  167992. int inrow, outrow;
  167993. inrow = outrow = 0;
  167994. while (outrow < cinfo->max_v_samp_factor) {
  167995. inptr = input_data[inrow];
  167996. outptr = output_data[outrow];
  167997. outend = outptr + cinfo->output_width;
  167998. while (outptr < outend) {
  167999. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  168000. *outptr++ = invalue;
  168001. *outptr++ = invalue;
  168002. }
  168003. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  168004. 1, cinfo->output_width);
  168005. inrow++;
  168006. outrow += 2;
  168007. }
  168008. }
  168009. /*
  168010. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  168011. *
  168012. * The upsampling algorithm is linear interpolation between pixel centers,
  168013. * also known as a "triangle filter". This is a good compromise between
  168014. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  168015. * of the way between input pixel centers.
  168016. *
  168017. * A note about the "bias" calculations: when rounding fractional values to
  168018. * integer, we do not want to always round 0.5 up to the next integer.
  168019. * If we did that, we'd introduce a noticeable bias towards larger values.
  168020. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  168021. * alternate pixel locations (a simple ordered dither pattern).
  168022. */
  168023. METHODDEF(void)
  168024. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168025. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168026. {
  168027. JSAMPARRAY output_data = *output_data_ptr;
  168028. register JSAMPROW inptr, outptr;
  168029. register int invalue;
  168030. register JDIMENSION colctr;
  168031. int inrow;
  168032. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  168033. inptr = input_data[inrow];
  168034. outptr = output_data[inrow];
  168035. /* Special case for first column */
  168036. invalue = GETJSAMPLE(*inptr++);
  168037. *outptr++ = (JSAMPLE) invalue;
  168038. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  168039. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  168040. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  168041. invalue = GETJSAMPLE(*inptr++) * 3;
  168042. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  168043. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  168044. }
  168045. /* Special case for last column */
  168046. invalue = GETJSAMPLE(*inptr);
  168047. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  168048. *outptr++ = (JSAMPLE) invalue;
  168049. }
  168050. }
  168051. /*
  168052. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  168053. * Again a triangle filter; see comments for h2v1 case, above.
  168054. *
  168055. * It is OK for us to reference the adjacent input rows because we demanded
  168056. * context from the main buffer controller (see initialization code).
  168057. */
  168058. METHODDEF(void)
  168059. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168060. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168061. {
  168062. JSAMPARRAY output_data = *output_data_ptr;
  168063. register JSAMPROW inptr0, inptr1, outptr;
  168064. #if BITS_IN_JSAMPLE == 8
  168065. register int thiscolsum, lastcolsum, nextcolsum;
  168066. #else
  168067. register INT32 thiscolsum, lastcolsum, nextcolsum;
  168068. #endif
  168069. register JDIMENSION colctr;
  168070. int inrow, outrow, v;
  168071. inrow = outrow = 0;
  168072. while (outrow < cinfo->max_v_samp_factor) {
  168073. for (v = 0; v < 2; v++) {
  168074. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  168075. inptr0 = input_data[inrow];
  168076. if (v == 0) /* next nearest is row above */
  168077. inptr1 = input_data[inrow-1];
  168078. else /* next nearest is row below */
  168079. inptr1 = input_data[inrow+1];
  168080. outptr = output_data[outrow++];
  168081. /* Special case for first column */
  168082. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  168083. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  168084. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  168085. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  168086. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  168087. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  168088. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  168089. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  168090. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  168091. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  168092. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  168093. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  168094. }
  168095. /* Special case for last column */
  168096. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  168097. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  168098. }
  168099. inrow++;
  168100. }
  168101. }
  168102. /*
  168103. * Module initialization routine for upsampling.
  168104. */
  168105. GLOBAL(void)
  168106. jinit_upsampler (j_decompress_ptr cinfo)
  168107. {
  168108. my_upsample_ptr2 upsample;
  168109. int ci;
  168110. jpeg_component_info * compptr;
  168111. boolean need_buffer, do_fancy;
  168112. int h_in_group, v_in_group, h_out_group, v_out_group;
  168113. upsample = (my_upsample_ptr2)
  168114. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168115. SIZEOF(my_upsampler2));
  168116. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  168117. upsample->pub.start_pass = start_pass_upsample;
  168118. upsample->pub.upsample = sep_upsample;
  168119. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  168120. if (cinfo->CCIR601_sampling) /* this isn't supported */
  168121. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  168122. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  168123. * so don't ask for it.
  168124. */
  168125. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  168126. /* Verify we can handle the sampling factors, select per-component methods,
  168127. * and create storage as needed.
  168128. */
  168129. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168130. ci++, compptr++) {
  168131. /* Compute size of an "input group" after IDCT scaling. This many samples
  168132. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  168133. */
  168134. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  168135. cinfo->min_DCT_scaled_size;
  168136. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  168137. cinfo->min_DCT_scaled_size;
  168138. h_out_group = cinfo->max_h_samp_factor;
  168139. v_out_group = cinfo->max_v_samp_factor;
  168140. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  168141. need_buffer = TRUE;
  168142. if (! compptr->component_needed) {
  168143. /* Don't bother to upsample an uninteresting component. */
  168144. upsample->methods[ci] = noop_upsample;
  168145. need_buffer = FALSE;
  168146. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  168147. /* Fullsize components can be processed without any work. */
  168148. upsample->methods[ci] = fullsize_upsample;
  168149. need_buffer = FALSE;
  168150. } else if (h_in_group * 2 == h_out_group &&
  168151. v_in_group == v_out_group) {
  168152. /* Special cases for 2h1v upsampling */
  168153. if (do_fancy && compptr->downsampled_width > 2)
  168154. upsample->methods[ci] = h2v1_fancy_upsample;
  168155. else
  168156. upsample->methods[ci] = h2v1_upsample;
  168157. } else if (h_in_group * 2 == h_out_group &&
  168158. v_in_group * 2 == v_out_group) {
  168159. /* Special cases for 2h2v upsampling */
  168160. if (do_fancy && compptr->downsampled_width > 2) {
  168161. upsample->methods[ci] = h2v2_fancy_upsample;
  168162. upsample->pub.need_context_rows = TRUE;
  168163. } else
  168164. upsample->methods[ci] = h2v2_upsample;
  168165. } else if ((h_out_group % h_in_group) == 0 &&
  168166. (v_out_group % v_in_group) == 0) {
  168167. /* Generic integral-factors upsampling method */
  168168. upsample->methods[ci] = int_upsample;
  168169. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  168170. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  168171. } else
  168172. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  168173. if (need_buffer) {
  168174. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  168175. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168176. (JDIMENSION) jround_up((long) cinfo->output_width,
  168177. (long) cinfo->max_h_samp_factor),
  168178. (JDIMENSION) cinfo->max_v_samp_factor);
  168179. }
  168180. }
  168181. }
  168182. /********* End of inlined file: jdsample.c *********/
  168183. /********* Start of inlined file: jdtrans.c *********/
  168184. #define JPEG_INTERNALS
  168185. /* Forward declarations */
  168186. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  168187. /*
  168188. * Read the coefficient arrays from a JPEG file.
  168189. * jpeg_read_header must be completed before calling this.
  168190. *
  168191. * The entire image is read into a set of virtual coefficient-block arrays,
  168192. * one per component. The return value is a pointer to the array of
  168193. * virtual-array descriptors. These can be manipulated directly via the
  168194. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  168195. * To release the memory occupied by the virtual arrays, call
  168196. * jpeg_finish_decompress() when done with the data.
  168197. *
  168198. * An alternative usage is to simply obtain access to the coefficient arrays
  168199. * during a buffered-image-mode decompression operation. This is allowed
  168200. * after any jpeg_finish_output() call. The arrays can be accessed until
  168201. * jpeg_finish_decompress() is called. (Note that any call to the library
  168202. * may reposition the arrays, so don't rely on access_virt_barray() results
  168203. * to stay valid across library calls.)
  168204. *
  168205. * Returns NULL if suspended. This case need be checked only if
  168206. * a suspending data source is used.
  168207. */
  168208. GLOBAL(jvirt_barray_ptr *)
  168209. jpeg_read_coefficients (j_decompress_ptr cinfo)
  168210. {
  168211. if (cinfo->global_state == DSTATE_READY) {
  168212. /* First call: initialize active modules */
  168213. transdecode_master_selection(cinfo);
  168214. cinfo->global_state = DSTATE_RDCOEFS;
  168215. }
  168216. if (cinfo->global_state == DSTATE_RDCOEFS) {
  168217. /* Absorb whole file into the coef buffer */
  168218. for (;;) {
  168219. int retcode;
  168220. /* Call progress monitor hook if present */
  168221. if (cinfo->progress != NULL)
  168222. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  168223. /* Absorb some more input */
  168224. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168225. if (retcode == JPEG_SUSPENDED)
  168226. return NULL;
  168227. if (retcode == JPEG_REACHED_EOI)
  168228. break;
  168229. /* Advance progress counter if appropriate */
  168230. if (cinfo->progress != NULL &&
  168231. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  168232. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  168233. /* startup underestimated number of scans; ratchet up one scan */
  168234. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  168235. }
  168236. }
  168237. }
  168238. /* Set state so that jpeg_finish_decompress does the right thing */
  168239. cinfo->global_state = DSTATE_STOPPING;
  168240. }
  168241. /* At this point we should be in state DSTATE_STOPPING if being used
  168242. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  168243. * to the coefficients during a full buffered-image-mode decompression.
  168244. */
  168245. if ((cinfo->global_state == DSTATE_STOPPING ||
  168246. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  168247. return cinfo->coef->coef_arrays;
  168248. }
  168249. /* Oops, improper usage */
  168250. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168251. return NULL; /* keep compiler happy */
  168252. }
  168253. /*
  168254. * Master selection of decompression modules for transcoding.
  168255. * This substitutes for jdmaster.c's initialization of the full decompressor.
  168256. */
  168257. LOCAL(void)
  168258. transdecode_master_selection (j_decompress_ptr cinfo)
  168259. {
  168260. /* This is effectively a buffered-image operation. */
  168261. cinfo->buffered_image = TRUE;
  168262. /* Entropy decoding: either Huffman or arithmetic coding. */
  168263. if (cinfo->arith_code) {
  168264. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  168265. } else {
  168266. if (cinfo->progressive_mode) {
  168267. #ifdef D_PROGRESSIVE_SUPPORTED
  168268. jinit_phuff_decoder(cinfo);
  168269. #else
  168270. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168271. #endif
  168272. } else
  168273. jinit_huff_decoder(cinfo);
  168274. }
  168275. /* Always get a full-image coefficient buffer. */
  168276. jinit_d_coef_controller(cinfo, TRUE);
  168277. /* We can now tell the memory manager to allocate virtual arrays. */
  168278. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  168279. /* Initialize input side of decompressor to consume first scan. */
  168280. (*cinfo->inputctl->start_input_pass) (cinfo);
  168281. /* Initialize progress monitoring. */
  168282. if (cinfo->progress != NULL) {
  168283. int nscans;
  168284. /* Estimate number of scans to set pass_limit. */
  168285. if (cinfo->progressive_mode) {
  168286. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  168287. nscans = 2 + 3 * cinfo->num_components;
  168288. } else if (cinfo->inputctl->has_multiple_scans) {
  168289. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  168290. nscans = cinfo->num_components;
  168291. } else {
  168292. nscans = 1;
  168293. }
  168294. cinfo->progress->pass_counter = 0L;
  168295. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  168296. cinfo->progress->completed_passes = 0;
  168297. cinfo->progress->total_passes = 1;
  168298. }
  168299. }
  168300. /********* End of inlined file: jdtrans.c *********/
  168301. /********* Start of inlined file: jfdctflt.c *********/
  168302. #define JPEG_INTERNALS
  168303. #ifdef DCT_FLOAT_SUPPORTED
  168304. /*
  168305. * This module is specialized to the case DCTSIZE = 8.
  168306. */
  168307. #if DCTSIZE != 8
  168308. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168309. #endif
  168310. /*
  168311. * Perform the forward DCT on one block of samples.
  168312. */
  168313. GLOBAL(void)
  168314. jpeg_fdct_float (FAST_FLOAT * data)
  168315. {
  168316. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  168317. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  168318. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  168319. FAST_FLOAT *dataptr;
  168320. int ctr;
  168321. /* Pass 1: process rows. */
  168322. dataptr = data;
  168323. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168324. tmp0 = dataptr[0] + dataptr[7];
  168325. tmp7 = dataptr[0] - dataptr[7];
  168326. tmp1 = dataptr[1] + dataptr[6];
  168327. tmp6 = dataptr[1] - dataptr[6];
  168328. tmp2 = dataptr[2] + dataptr[5];
  168329. tmp5 = dataptr[2] - dataptr[5];
  168330. tmp3 = dataptr[3] + dataptr[4];
  168331. tmp4 = dataptr[3] - dataptr[4];
  168332. /* Even part */
  168333. tmp10 = tmp0 + tmp3; /* phase 2 */
  168334. tmp13 = tmp0 - tmp3;
  168335. tmp11 = tmp1 + tmp2;
  168336. tmp12 = tmp1 - tmp2;
  168337. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  168338. dataptr[4] = tmp10 - tmp11;
  168339. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  168340. dataptr[2] = tmp13 + z1; /* phase 5 */
  168341. dataptr[6] = tmp13 - z1;
  168342. /* Odd part */
  168343. tmp10 = tmp4 + tmp5; /* phase 2 */
  168344. tmp11 = tmp5 + tmp6;
  168345. tmp12 = tmp6 + tmp7;
  168346. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  168347. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  168348. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  168349. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  168350. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  168351. z11 = tmp7 + z3; /* phase 5 */
  168352. z13 = tmp7 - z3;
  168353. dataptr[5] = z13 + z2; /* phase 6 */
  168354. dataptr[3] = z13 - z2;
  168355. dataptr[1] = z11 + z4;
  168356. dataptr[7] = z11 - z4;
  168357. dataptr += DCTSIZE; /* advance pointer to next row */
  168358. }
  168359. /* Pass 2: process columns. */
  168360. dataptr = data;
  168361. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168362. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  168363. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  168364. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  168365. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  168366. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  168367. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  168368. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  168369. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  168370. /* Even part */
  168371. tmp10 = tmp0 + tmp3; /* phase 2 */
  168372. tmp13 = tmp0 - tmp3;
  168373. tmp11 = tmp1 + tmp2;
  168374. tmp12 = tmp1 - tmp2;
  168375. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  168376. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  168377. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  168378. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  168379. dataptr[DCTSIZE*6] = tmp13 - z1;
  168380. /* Odd part */
  168381. tmp10 = tmp4 + tmp5; /* phase 2 */
  168382. tmp11 = tmp5 + tmp6;
  168383. tmp12 = tmp6 + tmp7;
  168384. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  168385. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  168386. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  168387. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  168388. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  168389. z11 = tmp7 + z3; /* phase 5 */
  168390. z13 = tmp7 - z3;
  168391. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  168392. dataptr[DCTSIZE*3] = z13 - z2;
  168393. dataptr[DCTSIZE*1] = z11 + z4;
  168394. dataptr[DCTSIZE*7] = z11 - z4;
  168395. dataptr++; /* advance pointer to next column */
  168396. }
  168397. }
  168398. #endif /* DCT_FLOAT_SUPPORTED */
  168399. /********* End of inlined file: jfdctflt.c *********/
  168400. /********* Start of inlined file: jfdctint.c *********/
  168401. #define JPEG_INTERNALS
  168402. #ifdef DCT_ISLOW_SUPPORTED
  168403. /*
  168404. * This module is specialized to the case DCTSIZE = 8.
  168405. */
  168406. #if DCTSIZE != 8
  168407. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168408. #endif
  168409. /*
  168410. * The poop on this scaling stuff is as follows:
  168411. *
  168412. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  168413. * larger than the true DCT outputs. The final outputs are therefore
  168414. * a factor of N larger than desired; since N=8 this can be cured by
  168415. * a simple right shift at the end of the algorithm. The advantage of
  168416. * this arrangement is that we save two multiplications per 1-D DCT,
  168417. * because the y0 and y4 outputs need not be divided by sqrt(N).
  168418. * In the IJG code, this factor of 8 is removed by the quantization step
  168419. * (in jcdctmgr.c), NOT in this module.
  168420. *
  168421. * We have to do addition and subtraction of the integer inputs, which
  168422. * is no problem, and multiplication by fractional constants, which is
  168423. * a problem to do in integer arithmetic. We multiply all the constants
  168424. * by CONST_SCALE and convert them to integer constants (thus retaining
  168425. * CONST_BITS bits of precision in the constants). After doing a
  168426. * multiplication we have to divide the product by CONST_SCALE, with proper
  168427. * rounding, to produce the correct output. This division can be done
  168428. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  168429. * as long as possible so that partial sums can be added together with
  168430. * full fractional precision.
  168431. *
  168432. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  168433. * they are represented to better-than-integral precision. These outputs
  168434. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  168435. * with the recommended scaling. (For 12-bit sample data, the intermediate
  168436. * array is INT32 anyway.)
  168437. *
  168438. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  168439. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  168440. * shows that the values given below are the most effective.
  168441. */
  168442. #if BITS_IN_JSAMPLE == 8
  168443. #define CONST_BITS 13
  168444. #define PASS1_BITS 2
  168445. #else
  168446. #define CONST_BITS 13
  168447. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  168448. #endif
  168449. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  168450. * causing a lot of useless floating-point operations at run time.
  168451. * To get around this we use the following pre-calculated constants.
  168452. * If you change CONST_BITS you may want to add appropriate values.
  168453. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  168454. */
  168455. #if CONST_BITS == 13
  168456. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  168457. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  168458. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  168459. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  168460. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  168461. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  168462. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  168463. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  168464. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  168465. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  168466. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  168467. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  168468. #else
  168469. #define FIX_0_298631336 FIX(0.298631336)
  168470. #define FIX_0_390180644 FIX(0.390180644)
  168471. #define FIX_0_541196100 FIX(0.541196100)
  168472. #define FIX_0_765366865 FIX(0.765366865)
  168473. #define FIX_0_899976223 FIX(0.899976223)
  168474. #define FIX_1_175875602 FIX(1.175875602)
  168475. #define FIX_1_501321110 FIX(1.501321110)
  168476. #define FIX_1_847759065 FIX(1.847759065)
  168477. #define FIX_1_961570560 FIX(1.961570560)
  168478. #define FIX_2_053119869 FIX(2.053119869)
  168479. #define FIX_2_562915447 FIX(2.562915447)
  168480. #define FIX_3_072711026 FIX(3.072711026)
  168481. #endif
  168482. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  168483. * For 8-bit samples with the recommended scaling, all the variable
  168484. * and constant values involved are no more than 16 bits wide, so a
  168485. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  168486. * For 12-bit samples, a full 32-bit multiplication will be needed.
  168487. */
  168488. #if BITS_IN_JSAMPLE == 8
  168489. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  168490. #else
  168491. #define MULTIPLY(var,const) ((var) * (const))
  168492. #endif
  168493. /*
  168494. * Perform the forward DCT on one block of samples.
  168495. */
  168496. GLOBAL(void)
  168497. jpeg_fdct_islow (DCTELEM * data)
  168498. {
  168499. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  168500. INT32 tmp10, tmp11, tmp12, tmp13;
  168501. INT32 z1, z2, z3, z4, z5;
  168502. DCTELEM *dataptr;
  168503. int ctr;
  168504. SHIFT_TEMPS
  168505. /* Pass 1: process rows. */
  168506. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  168507. /* furthermore, we scale the results by 2**PASS1_BITS. */
  168508. dataptr = data;
  168509. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168510. tmp0 = dataptr[0] + dataptr[7];
  168511. tmp7 = dataptr[0] - dataptr[7];
  168512. tmp1 = dataptr[1] + dataptr[6];
  168513. tmp6 = dataptr[1] - dataptr[6];
  168514. tmp2 = dataptr[2] + dataptr[5];
  168515. tmp5 = dataptr[2] - dataptr[5];
  168516. tmp3 = dataptr[3] + dataptr[4];
  168517. tmp4 = dataptr[3] - dataptr[4];
  168518. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  168519. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  168520. */
  168521. tmp10 = tmp0 + tmp3;
  168522. tmp13 = tmp0 - tmp3;
  168523. tmp11 = tmp1 + tmp2;
  168524. tmp12 = tmp1 - tmp2;
  168525. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  168526. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  168527. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  168528. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  168529. CONST_BITS-PASS1_BITS);
  168530. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  168531. CONST_BITS-PASS1_BITS);
  168532. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  168533. * cK represents cos(K*pi/16).
  168534. * i0..i3 in the paper are tmp4..tmp7 here.
  168535. */
  168536. z1 = tmp4 + tmp7;
  168537. z2 = tmp5 + tmp6;
  168538. z3 = tmp4 + tmp6;
  168539. z4 = tmp5 + tmp7;
  168540. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  168541. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  168542. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  168543. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  168544. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  168545. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  168546. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  168547. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  168548. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  168549. z3 += z5;
  168550. z4 += z5;
  168551. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  168552. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  168553. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  168554. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  168555. dataptr += DCTSIZE; /* advance pointer to next row */
  168556. }
  168557. /* Pass 2: process columns.
  168558. * We remove the PASS1_BITS scaling, but leave the results scaled up
  168559. * by an overall factor of 8.
  168560. */
  168561. dataptr = data;
  168562. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168563. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  168564. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  168565. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  168566. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  168567. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  168568. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  168569. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  168570. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  168571. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  168572. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  168573. */
  168574. tmp10 = tmp0 + tmp3;
  168575. tmp13 = tmp0 - tmp3;
  168576. tmp11 = tmp1 + tmp2;
  168577. tmp12 = tmp1 - tmp2;
  168578. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  168579. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  168580. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  168581. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  168582. CONST_BITS+PASS1_BITS);
  168583. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  168584. CONST_BITS+PASS1_BITS);
  168585. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  168586. * cK represents cos(K*pi/16).
  168587. * i0..i3 in the paper are tmp4..tmp7 here.
  168588. */
  168589. z1 = tmp4 + tmp7;
  168590. z2 = tmp5 + tmp6;
  168591. z3 = tmp4 + tmp6;
  168592. z4 = tmp5 + tmp7;
  168593. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  168594. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  168595. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  168596. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  168597. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  168598. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  168599. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  168600. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  168601. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  168602. z3 += z5;
  168603. z4 += z5;
  168604. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  168605. CONST_BITS+PASS1_BITS);
  168606. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  168607. CONST_BITS+PASS1_BITS);
  168608. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  168609. CONST_BITS+PASS1_BITS);
  168610. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  168611. CONST_BITS+PASS1_BITS);
  168612. dataptr++; /* advance pointer to next column */
  168613. }
  168614. }
  168615. #endif /* DCT_ISLOW_SUPPORTED */
  168616. /********* End of inlined file: jfdctint.c *********/
  168617. #undef CONST_BITS
  168618. #undef MULTIPLY
  168619. #undef FIX_0_541196100
  168620. /********* Start of inlined file: jfdctfst.c *********/
  168621. #define JPEG_INTERNALS
  168622. #ifdef DCT_IFAST_SUPPORTED
  168623. /*
  168624. * This module is specialized to the case DCTSIZE = 8.
  168625. */
  168626. #if DCTSIZE != 8
  168627. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168628. #endif
  168629. /* Scaling decisions are generally the same as in the LL&M algorithm;
  168630. * see jfdctint.c for more details. However, we choose to descale
  168631. * (right shift) multiplication products as soon as they are formed,
  168632. * rather than carrying additional fractional bits into subsequent additions.
  168633. * This compromises accuracy slightly, but it lets us save a few shifts.
  168634. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  168635. * everywhere except in the multiplications proper; this saves a good deal
  168636. * of work on 16-bit-int machines.
  168637. *
  168638. * Again to save a few shifts, the intermediate results between pass 1 and
  168639. * pass 2 are not upscaled, but are represented only to integral precision.
  168640. *
  168641. * A final compromise is to represent the multiplicative constants to only
  168642. * 8 fractional bits, rather than 13. This saves some shifting work on some
  168643. * machines, and may also reduce the cost of multiplication (since there
  168644. * are fewer one-bits in the constants).
  168645. */
  168646. #define CONST_BITS 8
  168647. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  168648. * causing a lot of useless floating-point operations at run time.
  168649. * To get around this we use the following pre-calculated constants.
  168650. * If you change CONST_BITS you may want to add appropriate values.
  168651. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  168652. */
  168653. #if CONST_BITS == 8
  168654. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  168655. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  168656. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  168657. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  168658. #else
  168659. #define FIX_0_382683433 FIX(0.382683433)
  168660. #define FIX_0_541196100 FIX(0.541196100)
  168661. #define FIX_0_707106781 FIX(0.707106781)
  168662. #define FIX_1_306562965 FIX(1.306562965)
  168663. #endif
  168664. /* We can gain a little more speed, with a further compromise in accuracy,
  168665. * by omitting the addition in a descaling shift. This yields an incorrectly
  168666. * rounded result half the time...
  168667. */
  168668. #ifndef USE_ACCURATE_ROUNDING
  168669. #undef DESCALE
  168670. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  168671. #endif
  168672. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  168673. * descale to yield a DCTELEM result.
  168674. */
  168675. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  168676. /*
  168677. * Perform the forward DCT on one block of samples.
  168678. */
  168679. GLOBAL(void)
  168680. jpeg_fdct_ifast (DCTELEM * data)
  168681. {
  168682. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  168683. DCTELEM tmp10, tmp11, tmp12, tmp13;
  168684. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  168685. DCTELEM *dataptr;
  168686. int ctr;
  168687. SHIFT_TEMPS
  168688. /* Pass 1: process rows. */
  168689. dataptr = data;
  168690. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168691. tmp0 = dataptr[0] + dataptr[7];
  168692. tmp7 = dataptr[0] - dataptr[7];
  168693. tmp1 = dataptr[1] + dataptr[6];
  168694. tmp6 = dataptr[1] - dataptr[6];
  168695. tmp2 = dataptr[2] + dataptr[5];
  168696. tmp5 = dataptr[2] - dataptr[5];
  168697. tmp3 = dataptr[3] + dataptr[4];
  168698. tmp4 = dataptr[3] - dataptr[4];
  168699. /* Even part */
  168700. tmp10 = tmp0 + tmp3; /* phase 2 */
  168701. tmp13 = tmp0 - tmp3;
  168702. tmp11 = tmp1 + tmp2;
  168703. tmp12 = tmp1 - tmp2;
  168704. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  168705. dataptr[4] = tmp10 - tmp11;
  168706. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  168707. dataptr[2] = tmp13 + z1; /* phase 5 */
  168708. dataptr[6] = tmp13 - z1;
  168709. /* Odd part */
  168710. tmp10 = tmp4 + tmp5; /* phase 2 */
  168711. tmp11 = tmp5 + tmp6;
  168712. tmp12 = tmp6 + tmp7;
  168713. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  168714. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  168715. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  168716. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  168717. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  168718. z11 = tmp7 + z3; /* phase 5 */
  168719. z13 = tmp7 - z3;
  168720. dataptr[5] = z13 + z2; /* phase 6 */
  168721. dataptr[3] = z13 - z2;
  168722. dataptr[1] = z11 + z4;
  168723. dataptr[7] = z11 - z4;
  168724. dataptr += DCTSIZE; /* advance pointer to next row */
  168725. }
  168726. /* Pass 2: process columns. */
  168727. dataptr = data;
  168728. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168729. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  168730. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  168731. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  168732. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  168733. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  168734. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  168735. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  168736. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  168737. /* Even part */
  168738. tmp10 = tmp0 + tmp3; /* phase 2 */
  168739. tmp13 = tmp0 - tmp3;
  168740. tmp11 = tmp1 + tmp2;
  168741. tmp12 = tmp1 - tmp2;
  168742. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  168743. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  168744. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  168745. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  168746. dataptr[DCTSIZE*6] = tmp13 - z1;
  168747. /* Odd part */
  168748. tmp10 = tmp4 + tmp5; /* phase 2 */
  168749. tmp11 = tmp5 + tmp6;
  168750. tmp12 = tmp6 + tmp7;
  168751. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  168752. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  168753. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  168754. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  168755. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  168756. z11 = tmp7 + z3; /* phase 5 */
  168757. z13 = tmp7 - z3;
  168758. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  168759. dataptr[DCTSIZE*3] = z13 - z2;
  168760. dataptr[DCTSIZE*1] = z11 + z4;
  168761. dataptr[DCTSIZE*7] = z11 - z4;
  168762. dataptr++; /* advance pointer to next column */
  168763. }
  168764. }
  168765. #endif /* DCT_IFAST_SUPPORTED */
  168766. /********* End of inlined file: jfdctfst.c *********/
  168767. #undef FIX_0_541196100
  168768. /********* Start of inlined file: jidctflt.c *********/
  168769. #define JPEG_INTERNALS
  168770. #ifdef DCT_FLOAT_SUPPORTED
  168771. /*
  168772. * This module is specialized to the case DCTSIZE = 8.
  168773. */
  168774. #if DCTSIZE != 8
  168775. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168776. #endif
  168777. /* Dequantize a coefficient by multiplying it by the multiplier-table
  168778. * entry; produce a float result.
  168779. */
  168780. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  168781. /*
  168782. * Perform dequantization and inverse DCT on one block of coefficients.
  168783. */
  168784. GLOBAL(void)
  168785. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168786. JCOEFPTR coef_block,
  168787. JSAMPARRAY output_buf, JDIMENSION output_col)
  168788. {
  168789. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  168790. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  168791. FAST_FLOAT z5, z10, z11, z12, z13;
  168792. JCOEFPTR inptr;
  168793. FLOAT_MULT_TYPE * quantptr;
  168794. FAST_FLOAT * wsptr;
  168795. JSAMPROW outptr;
  168796. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  168797. int ctr;
  168798. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  168799. SHIFT_TEMPS
  168800. /* Pass 1: process columns from input, store into work array. */
  168801. inptr = coef_block;
  168802. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  168803. wsptr = workspace;
  168804. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  168805. /* Due to quantization, we will usually find that many of the input
  168806. * coefficients are zero, especially the AC terms. We can exploit this
  168807. * by short-circuiting the IDCT calculation for any column in which all
  168808. * the AC terms are zero. In that case each output is equal to the
  168809. * DC coefficient (with scale factor as needed).
  168810. * With typical images and quantization tables, half or more of the
  168811. * column DCT calculations can be simplified this way.
  168812. */
  168813. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  168814. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  168815. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  168816. inptr[DCTSIZE*7] == 0) {
  168817. /* AC terms all zero */
  168818. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168819. wsptr[DCTSIZE*0] = dcval;
  168820. wsptr[DCTSIZE*1] = dcval;
  168821. wsptr[DCTSIZE*2] = dcval;
  168822. wsptr[DCTSIZE*3] = dcval;
  168823. wsptr[DCTSIZE*4] = dcval;
  168824. wsptr[DCTSIZE*5] = dcval;
  168825. wsptr[DCTSIZE*6] = dcval;
  168826. wsptr[DCTSIZE*7] = dcval;
  168827. inptr++; /* advance pointers to next column */
  168828. quantptr++;
  168829. wsptr++;
  168830. continue;
  168831. }
  168832. /* Even part */
  168833. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168834. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  168835. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  168836. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  168837. tmp10 = tmp0 + tmp2; /* phase 3 */
  168838. tmp11 = tmp0 - tmp2;
  168839. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  168840. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  168841. tmp0 = tmp10 + tmp13; /* phase 2 */
  168842. tmp3 = tmp10 - tmp13;
  168843. tmp1 = tmp11 + tmp12;
  168844. tmp2 = tmp11 - tmp12;
  168845. /* Odd part */
  168846. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  168847. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  168848. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  168849. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  168850. z13 = tmp6 + tmp5; /* phase 6 */
  168851. z10 = tmp6 - tmp5;
  168852. z11 = tmp4 + tmp7;
  168853. z12 = tmp4 - tmp7;
  168854. tmp7 = z11 + z13; /* phase 5 */
  168855. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  168856. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  168857. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  168858. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  168859. tmp6 = tmp12 - tmp7; /* phase 2 */
  168860. tmp5 = tmp11 - tmp6;
  168861. tmp4 = tmp10 + tmp5;
  168862. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  168863. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  168864. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  168865. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  168866. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  168867. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  168868. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  168869. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  168870. inptr++; /* advance pointers to next column */
  168871. quantptr++;
  168872. wsptr++;
  168873. }
  168874. /* Pass 2: process rows from work array, store into output array. */
  168875. /* Note that we must descale the results by a factor of 8 == 2**3. */
  168876. wsptr = workspace;
  168877. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  168878. outptr = output_buf[ctr] + output_col;
  168879. /* Rows of zeroes can be exploited in the same way as we did with columns.
  168880. * However, the column calculation has created many nonzero AC terms, so
  168881. * the simplification applies less often (typically 5% to 10% of the time).
  168882. * And testing floats for zero is relatively expensive, so we don't bother.
  168883. */
  168884. /* Even part */
  168885. tmp10 = wsptr[0] + wsptr[4];
  168886. tmp11 = wsptr[0] - wsptr[4];
  168887. tmp13 = wsptr[2] + wsptr[6];
  168888. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  168889. tmp0 = tmp10 + tmp13;
  168890. tmp3 = tmp10 - tmp13;
  168891. tmp1 = tmp11 + tmp12;
  168892. tmp2 = tmp11 - tmp12;
  168893. /* Odd part */
  168894. z13 = wsptr[5] + wsptr[3];
  168895. z10 = wsptr[5] - wsptr[3];
  168896. z11 = wsptr[1] + wsptr[7];
  168897. z12 = wsptr[1] - wsptr[7];
  168898. tmp7 = z11 + z13;
  168899. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  168900. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  168901. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  168902. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  168903. tmp6 = tmp12 - tmp7;
  168904. tmp5 = tmp11 - tmp6;
  168905. tmp4 = tmp10 + tmp5;
  168906. /* Final output stage: scale down by a factor of 8 and range-limit */
  168907. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  168908. & RANGE_MASK];
  168909. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  168910. & RANGE_MASK];
  168911. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  168912. & RANGE_MASK];
  168913. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  168914. & RANGE_MASK];
  168915. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  168916. & RANGE_MASK];
  168917. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  168918. & RANGE_MASK];
  168919. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  168920. & RANGE_MASK];
  168921. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  168922. & RANGE_MASK];
  168923. wsptr += DCTSIZE; /* advance pointer to next row */
  168924. }
  168925. }
  168926. #endif /* DCT_FLOAT_SUPPORTED */
  168927. /********* End of inlined file: jidctflt.c *********/
  168928. #undef CONST_BITS
  168929. #undef FIX_1_847759065
  168930. #undef MULTIPLY
  168931. #undef DEQUANTIZE
  168932. #undef DESCALE
  168933. /********* Start of inlined file: jidctfst.c *********/
  168934. #define JPEG_INTERNALS
  168935. #ifdef DCT_IFAST_SUPPORTED
  168936. /*
  168937. * This module is specialized to the case DCTSIZE = 8.
  168938. */
  168939. #if DCTSIZE != 8
  168940. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168941. #endif
  168942. /* Scaling decisions are generally the same as in the LL&M algorithm;
  168943. * see jidctint.c for more details. However, we choose to descale
  168944. * (right shift) multiplication products as soon as they are formed,
  168945. * rather than carrying additional fractional bits into subsequent additions.
  168946. * This compromises accuracy slightly, but it lets us save a few shifts.
  168947. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  168948. * everywhere except in the multiplications proper; this saves a good deal
  168949. * of work on 16-bit-int machines.
  168950. *
  168951. * The dequantized coefficients are not integers because the AA&N scaling
  168952. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  168953. * so that the first and second IDCT rounds have the same input scaling.
  168954. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  168955. * avoid a descaling shift; this compromises accuracy rather drastically
  168956. * for small quantization table entries, but it saves a lot of shifts.
  168957. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  168958. * so we use a much larger scaling factor to preserve accuracy.
  168959. *
  168960. * A final compromise is to represent the multiplicative constants to only
  168961. * 8 fractional bits, rather than 13. This saves some shifting work on some
  168962. * machines, and may also reduce the cost of multiplication (since there
  168963. * are fewer one-bits in the constants).
  168964. */
  168965. #if BITS_IN_JSAMPLE == 8
  168966. #define CONST_BITS 8
  168967. #define PASS1_BITS 2
  168968. #else
  168969. #define CONST_BITS 8
  168970. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  168971. #endif
  168972. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  168973. * causing a lot of useless floating-point operations at run time.
  168974. * To get around this we use the following pre-calculated constants.
  168975. * If you change CONST_BITS you may want to add appropriate values.
  168976. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  168977. */
  168978. #if CONST_BITS == 8
  168979. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  168980. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  168981. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  168982. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  168983. #else
  168984. #define FIX_1_082392200 FIX(1.082392200)
  168985. #define FIX_1_414213562 FIX(1.414213562)
  168986. #define FIX_1_847759065 FIX(1.847759065)
  168987. #define FIX_2_613125930 FIX(2.613125930)
  168988. #endif
  168989. /* We can gain a little more speed, with a further compromise in accuracy,
  168990. * by omitting the addition in a descaling shift. This yields an incorrectly
  168991. * rounded result half the time...
  168992. */
  168993. #ifndef USE_ACCURATE_ROUNDING
  168994. #undef DESCALE
  168995. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  168996. #endif
  168997. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  168998. * descale to yield a DCTELEM result.
  168999. */
  169000. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  169001. /* Dequantize a coefficient by multiplying it by the multiplier-table
  169002. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  169003. * multiplication will do. For 12-bit data, the multiplier table is
  169004. * declared INT32, so a 32-bit multiply will be used.
  169005. */
  169006. #if BITS_IN_JSAMPLE == 8
  169007. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  169008. #else
  169009. #define DEQUANTIZE(coef,quantval) \
  169010. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  169011. #endif
  169012. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  169013. * We assume that int right shift is unsigned if INT32 right shift is.
  169014. */
  169015. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  169016. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  169017. #if BITS_IN_JSAMPLE == 8
  169018. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  169019. #else
  169020. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  169021. #endif
  169022. #define IRIGHT_SHIFT(x,shft) \
  169023. ((ishift_temp = (x)) < 0 ? \
  169024. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  169025. (ishift_temp >> (shft)))
  169026. #else
  169027. #define ISHIFT_TEMPS
  169028. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  169029. #endif
  169030. #ifdef USE_ACCURATE_ROUNDING
  169031. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  169032. #else
  169033. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  169034. #endif
  169035. /*
  169036. * Perform dequantization and inverse DCT on one block of coefficients.
  169037. */
  169038. GLOBAL(void)
  169039. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169040. JCOEFPTR coef_block,
  169041. JSAMPARRAY output_buf, JDIMENSION output_col)
  169042. {
  169043. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  169044. DCTELEM tmp10, tmp11, tmp12, tmp13;
  169045. DCTELEM z5, z10, z11, z12, z13;
  169046. JCOEFPTR inptr;
  169047. IFAST_MULT_TYPE * quantptr;
  169048. int * wsptr;
  169049. JSAMPROW outptr;
  169050. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169051. int ctr;
  169052. int workspace[DCTSIZE2]; /* buffers data between passes */
  169053. SHIFT_TEMPS /* for DESCALE */
  169054. ISHIFT_TEMPS /* for IDESCALE */
  169055. /* Pass 1: process columns from input, store into work array. */
  169056. inptr = coef_block;
  169057. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  169058. wsptr = workspace;
  169059. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  169060. /* Due to quantization, we will usually find that many of the input
  169061. * coefficients are zero, especially the AC terms. We can exploit this
  169062. * by short-circuiting the IDCT calculation for any column in which all
  169063. * the AC terms are zero. In that case each output is equal to the
  169064. * DC coefficient (with scale factor as needed).
  169065. * With typical images and quantization tables, half or more of the
  169066. * column DCT calculations can be simplified this way.
  169067. */
  169068. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  169069. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  169070. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  169071. inptr[DCTSIZE*7] == 0) {
  169072. /* AC terms all zero */
  169073. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169074. wsptr[DCTSIZE*0] = dcval;
  169075. wsptr[DCTSIZE*1] = dcval;
  169076. wsptr[DCTSIZE*2] = dcval;
  169077. wsptr[DCTSIZE*3] = dcval;
  169078. wsptr[DCTSIZE*4] = dcval;
  169079. wsptr[DCTSIZE*5] = dcval;
  169080. wsptr[DCTSIZE*6] = dcval;
  169081. wsptr[DCTSIZE*7] = dcval;
  169082. inptr++; /* advance pointers to next column */
  169083. quantptr++;
  169084. wsptr++;
  169085. continue;
  169086. }
  169087. /* Even part */
  169088. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169089. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  169090. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  169091. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  169092. tmp10 = tmp0 + tmp2; /* phase 3 */
  169093. tmp11 = tmp0 - tmp2;
  169094. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  169095. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  169096. tmp0 = tmp10 + tmp13; /* phase 2 */
  169097. tmp3 = tmp10 - tmp13;
  169098. tmp1 = tmp11 + tmp12;
  169099. tmp2 = tmp11 - tmp12;
  169100. /* Odd part */
  169101. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  169102. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  169103. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  169104. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  169105. z13 = tmp6 + tmp5; /* phase 6 */
  169106. z10 = tmp6 - tmp5;
  169107. z11 = tmp4 + tmp7;
  169108. z12 = tmp4 - tmp7;
  169109. tmp7 = z11 + z13; /* phase 5 */
  169110. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  169111. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  169112. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  169113. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  169114. tmp6 = tmp12 - tmp7; /* phase 2 */
  169115. tmp5 = tmp11 - tmp6;
  169116. tmp4 = tmp10 + tmp5;
  169117. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  169118. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  169119. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  169120. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  169121. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  169122. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  169123. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  169124. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  169125. inptr++; /* advance pointers to next column */
  169126. quantptr++;
  169127. wsptr++;
  169128. }
  169129. /* Pass 2: process rows from work array, store into output array. */
  169130. /* Note that we must descale the results by a factor of 8 == 2**3, */
  169131. /* and also undo the PASS1_BITS scaling. */
  169132. wsptr = workspace;
  169133. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  169134. outptr = output_buf[ctr] + output_col;
  169135. /* Rows of zeroes can be exploited in the same way as we did with columns.
  169136. * However, the column calculation has created many nonzero AC terms, so
  169137. * the simplification applies less often (typically 5% to 10% of the time).
  169138. * On machines with very fast multiplication, it's possible that the
  169139. * test takes more time than it's worth. In that case this section
  169140. * may be commented out.
  169141. */
  169142. #ifndef NO_ZERO_ROW_TEST
  169143. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  169144. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  169145. /* AC terms all zero */
  169146. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  169147. & RANGE_MASK];
  169148. outptr[0] = dcval;
  169149. outptr[1] = dcval;
  169150. outptr[2] = dcval;
  169151. outptr[3] = dcval;
  169152. outptr[4] = dcval;
  169153. outptr[5] = dcval;
  169154. outptr[6] = dcval;
  169155. outptr[7] = dcval;
  169156. wsptr += DCTSIZE; /* advance pointer to next row */
  169157. continue;
  169158. }
  169159. #endif
  169160. /* Even part */
  169161. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  169162. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  169163. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  169164. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  169165. - tmp13;
  169166. tmp0 = tmp10 + tmp13;
  169167. tmp3 = tmp10 - tmp13;
  169168. tmp1 = tmp11 + tmp12;
  169169. tmp2 = tmp11 - tmp12;
  169170. /* Odd part */
  169171. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  169172. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  169173. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  169174. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  169175. tmp7 = z11 + z13; /* phase 5 */
  169176. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  169177. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  169178. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  169179. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  169180. tmp6 = tmp12 - tmp7; /* phase 2 */
  169181. tmp5 = tmp11 - tmp6;
  169182. tmp4 = tmp10 + tmp5;
  169183. /* Final output stage: scale down by a factor of 8 and range-limit */
  169184. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  169185. & RANGE_MASK];
  169186. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  169187. & RANGE_MASK];
  169188. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  169189. & RANGE_MASK];
  169190. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  169191. & RANGE_MASK];
  169192. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  169193. & RANGE_MASK];
  169194. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  169195. & RANGE_MASK];
  169196. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  169197. & RANGE_MASK];
  169198. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  169199. & RANGE_MASK];
  169200. wsptr += DCTSIZE; /* advance pointer to next row */
  169201. }
  169202. }
  169203. #endif /* DCT_IFAST_SUPPORTED */
  169204. /********* End of inlined file: jidctfst.c *********/
  169205. #undef CONST_BITS
  169206. #undef FIX_1_847759065
  169207. #undef MULTIPLY
  169208. #undef DEQUANTIZE
  169209. /********* Start of inlined file: jidctint.c *********/
  169210. #define JPEG_INTERNALS
  169211. #ifdef DCT_ISLOW_SUPPORTED
  169212. /*
  169213. * This module is specialized to the case DCTSIZE = 8.
  169214. */
  169215. #if DCTSIZE != 8
  169216. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169217. #endif
  169218. /*
  169219. * The poop on this scaling stuff is as follows:
  169220. *
  169221. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  169222. * larger than the true IDCT outputs. The final outputs are therefore
  169223. * a factor of N larger than desired; since N=8 this can be cured by
  169224. * a simple right shift at the end of the algorithm. The advantage of
  169225. * this arrangement is that we save two multiplications per 1-D IDCT,
  169226. * because the y0 and y4 inputs need not be divided by sqrt(N).
  169227. *
  169228. * We have to do addition and subtraction of the integer inputs, which
  169229. * is no problem, and multiplication by fractional constants, which is
  169230. * a problem to do in integer arithmetic. We multiply all the constants
  169231. * by CONST_SCALE and convert them to integer constants (thus retaining
  169232. * CONST_BITS bits of precision in the constants). After doing a
  169233. * multiplication we have to divide the product by CONST_SCALE, with proper
  169234. * rounding, to produce the correct output. This division can be done
  169235. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  169236. * as long as possible so that partial sums can be added together with
  169237. * full fractional precision.
  169238. *
  169239. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  169240. * they are represented to better-than-integral precision. These outputs
  169241. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  169242. * with the recommended scaling. (To scale up 12-bit sample data further, an
  169243. * intermediate INT32 array would be needed.)
  169244. *
  169245. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  169246. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  169247. * shows that the values given below are the most effective.
  169248. */
  169249. #if BITS_IN_JSAMPLE == 8
  169250. #define CONST_BITS 13
  169251. #define PASS1_BITS 2
  169252. #else
  169253. #define CONST_BITS 13
  169254. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  169255. #endif
  169256. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  169257. * causing a lot of useless floating-point operations at run time.
  169258. * To get around this we use the following pre-calculated constants.
  169259. * If you change CONST_BITS you may want to add appropriate values.
  169260. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  169261. */
  169262. #if CONST_BITS == 13
  169263. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  169264. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  169265. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  169266. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  169267. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  169268. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  169269. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  169270. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  169271. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  169272. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  169273. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  169274. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  169275. #else
  169276. #define FIX_0_298631336 FIX(0.298631336)
  169277. #define FIX_0_390180644 FIX(0.390180644)
  169278. #define FIX_0_541196100 FIX(0.541196100)
  169279. #define FIX_0_765366865 FIX(0.765366865)
  169280. #define FIX_0_899976223 FIX(0.899976223)
  169281. #define FIX_1_175875602 FIX(1.175875602)
  169282. #define FIX_1_501321110 FIX(1.501321110)
  169283. #define FIX_1_847759065 FIX(1.847759065)
  169284. #define FIX_1_961570560 FIX(1.961570560)
  169285. #define FIX_2_053119869 FIX(2.053119869)
  169286. #define FIX_2_562915447 FIX(2.562915447)
  169287. #define FIX_3_072711026 FIX(3.072711026)
  169288. #endif
  169289. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  169290. * For 8-bit samples with the recommended scaling, all the variable
  169291. * and constant values involved are no more than 16 bits wide, so a
  169292. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  169293. * For 12-bit samples, a full 32-bit multiplication will be needed.
  169294. */
  169295. #if BITS_IN_JSAMPLE == 8
  169296. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  169297. #else
  169298. #define MULTIPLY(var,const) ((var) * (const))
  169299. #endif
  169300. /* Dequantize a coefficient by multiplying it by the multiplier-table
  169301. * entry; produce an int result. In this module, both inputs and result
  169302. * are 16 bits or less, so either int or short multiply will work.
  169303. */
  169304. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  169305. /*
  169306. * Perform dequantization and inverse DCT on one block of coefficients.
  169307. */
  169308. GLOBAL(void)
  169309. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169310. JCOEFPTR coef_block,
  169311. JSAMPARRAY output_buf, JDIMENSION output_col)
  169312. {
  169313. INT32 tmp0, tmp1, tmp2, tmp3;
  169314. INT32 tmp10, tmp11, tmp12, tmp13;
  169315. INT32 z1, z2, z3, z4, z5;
  169316. JCOEFPTR inptr;
  169317. ISLOW_MULT_TYPE * quantptr;
  169318. int * wsptr;
  169319. JSAMPROW outptr;
  169320. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169321. int ctr;
  169322. int workspace[DCTSIZE2]; /* buffers data between passes */
  169323. SHIFT_TEMPS
  169324. /* Pass 1: process columns from input, store into work array. */
  169325. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  169326. /* furthermore, we scale the results by 2**PASS1_BITS. */
  169327. inptr = coef_block;
  169328. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169329. wsptr = workspace;
  169330. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  169331. /* Due to quantization, we will usually find that many of the input
  169332. * coefficients are zero, especially the AC terms. We can exploit this
  169333. * by short-circuiting the IDCT calculation for any column in which all
  169334. * the AC terms are zero. In that case each output is equal to the
  169335. * DC coefficient (with scale factor as needed).
  169336. * With typical images and quantization tables, half or more of the
  169337. * column DCT calculations can be simplified this way.
  169338. */
  169339. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  169340. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  169341. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  169342. inptr[DCTSIZE*7] == 0) {
  169343. /* AC terms all zero */
  169344. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  169345. wsptr[DCTSIZE*0] = dcval;
  169346. wsptr[DCTSIZE*1] = dcval;
  169347. wsptr[DCTSIZE*2] = dcval;
  169348. wsptr[DCTSIZE*3] = dcval;
  169349. wsptr[DCTSIZE*4] = dcval;
  169350. wsptr[DCTSIZE*5] = dcval;
  169351. wsptr[DCTSIZE*6] = dcval;
  169352. wsptr[DCTSIZE*7] = dcval;
  169353. inptr++; /* advance pointers to next column */
  169354. quantptr++;
  169355. wsptr++;
  169356. continue;
  169357. }
  169358. /* Even part: reverse the even part of the forward DCT. */
  169359. /* The rotator is sqrt(2)*c(-6). */
  169360. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  169361. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  169362. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  169363. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  169364. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  169365. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169366. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  169367. tmp0 = (z2 + z3) << CONST_BITS;
  169368. tmp1 = (z2 - z3) << CONST_BITS;
  169369. tmp10 = tmp0 + tmp3;
  169370. tmp13 = tmp0 - tmp3;
  169371. tmp11 = tmp1 + tmp2;
  169372. tmp12 = tmp1 - tmp2;
  169373. /* Odd part per figure 8; the matrix is unitary and hence its
  169374. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  169375. */
  169376. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  169377. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  169378. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  169379. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  169380. z1 = tmp0 + tmp3;
  169381. z2 = tmp1 + tmp2;
  169382. z3 = tmp0 + tmp2;
  169383. z4 = tmp1 + tmp3;
  169384. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  169385. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  169386. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  169387. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  169388. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  169389. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  169390. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  169391. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  169392. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  169393. z3 += z5;
  169394. z4 += z5;
  169395. tmp0 += z1 + z3;
  169396. tmp1 += z2 + z4;
  169397. tmp2 += z2 + z3;
  169398. tmp3 += z1 + z4;
  169399. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  169400. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  169401. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  169402. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  169403. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  169404. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  169405. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  169406. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  169407. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  169408. inptr++; /* advance pointers to next column */
  169409. quantptr++;
  169410. wsptr++;
  169411. }
  169412. /* Pass 2: process rows from work array, store into output array. */
  169413. /* Note that we must descale the results by a factor of 8 == 2**3, */
  169414. /* and also undo the PASS1_BITS scaling. */
  169415. wsptr = workspace;
  169416. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  169417. outptr = output_buf[ctr] + output_col;
  169418. /* Rows of zeroes can be exploited in the same way as we did with columns.
  169419. * However, the column calculation has created many nonzero AC terms, so
  169420. * the simplification applies less often (typically 5% to 10% of the time).
  169421. * On machines with very fast multiplication, it's possible that the
  169422. * test takes more time than it's worth. In that case this section
  169423. * may be commented out.
  169424. */
  169425. #ifndef NO_ZERO_ROW_TEST
  169426. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  169427. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  169428. /* AC terms all zero */
  169429. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  169430. & RANGE_MASK];
  169431. outptr[0] = dcval;
  169432. outptr[1] = dcval;
  169433. outptr[2] = dcval;
  169434. outptr[3] = dcval;
  169435. outptr[4] = dcval;
  169436. outptr[5] = dcval;
  169437. outptr[6] = dcval;
  169438. outptr[7] = dcval;
  169439. wsptr += DCTSIZE; /* advance pointer to next row */
  169440. continue;
  169441. }
  169442. #endif
  169443. /* Even part: reverse the even part of the forward DCT. */
  169444. /* The rotator is sqrt(2)*c(-6). */
  169445. z2 = (INT32) wsptr[2];
  169446. z3 = (INT32) wsptr[6];
  169447. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  169448. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  169449. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  169450. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  169451. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  169452. tmp10 = tmp0 + tmp3;
  169453. tmp13 = tmp0 - tmp3;
  169454. tmp11 = tmp1 + tmp2;
  169455. tmp12 = tmp1 - tmp2;
  169456. /* Odd part per figure 8; the matrix is unitary and hence its
  169457. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  169458. */
  169459. tmp0 = (INT32) wsptr[7];
  169460. tmp1 = (INT32) wsptr[5];
  169461. tmp2 = (INT32) wsptr[3];
  169462. tmp3 = (INT32) wsptr[1];
  169463. z1 = tmp0 + tmp3;
  169464. z2 = tmp1 + tmp2;
  169465. z3 = tmp0 + tmp2;
  169466. z4 = tmp1 + tmp3;
  169467. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  169468. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  169469. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  169470. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  169471. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  169472. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  169473. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  169474. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  169475. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  169476. z3 += z5;
  169477. z4 += z5;
  169478. tmp0 += z1 + z3;
  169479. tmp1 += z2 + z4;
  169480. tmp2 += z2 + z3;
  169481. tmp3 += z1 + z4;
  169482. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  169483. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  169484. CONST_BITS+PASS1_BITS+3)
  169485. & RANGE_MASK];
  169486. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  169487. CONST_BITS+PASS1_BITS+3)
  169488. & RANGE_MASK];
  169489. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  169490. CONST_BITS+PASS1_BITS+3)
  169491. & RANGE_MASK];
  169492. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  169493. CONST_BITS+PASS1_BITS+3)
  169494. & RANGE_MASK];
  169495. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  169496. CONST_BITS+PASS1_BITS+3)
  169497. & RANGE_MASK];
  169498. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  169499. CONST_BITS+PASS1_BITS+3)
  169500. & RANGE_MASK];
  169501. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  169502. CONST_BITS+PASS1_BITS+3)
  169503. & RANGE_MASK];
  169504. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  169505. CONST_BITS+PASS1_BITS+3)
  169506. & RANGE_MASK];
  169507. wsptr += DCTSIZE; /* advance pointer to next row */
  169508. }
  169509. }
  169510. #endif /* DCT_ISLOW_SUPPORTED */
  169511. /********* End of inlined file: jidctint.c *********/
  169512. /********* Start of inlined file: jidctred.c *********/
  169513. #define JPEG_INTERNALS
  169514. #ifdef IDCT_SCALING_SUPPORTED
  169515. /*
  169516. * This module is specialized to the case DCTSIZE = 8.
  169517. */
  169518. #if DCTSIZE != 8
  169519. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169520. #endif
  169521. /* Scaling is the same as in jidctint.c. */
  169522. #if BITS_IN_JSAMPLE == 8
  169523. #define CONST_BITS 13
  169524. #define PASS1_BITS 2
  169525. #else
  169526. #define CONST_BITS 13
  169527. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  169528. #endif
  169529. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  169530. * causing a lot of useless floating-point operations at run time.
  169531. * To get around this we use the following pre-calculated constants.
  169532. * If you change CONST_BITS you may want to add appropriate values.
  169533. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  169534. */
  169535. #if CONST_BITS == 13
  169536. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  169537. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  169538. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  169539. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  169540. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  169541. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  169542. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  169543. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  169544. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  169545. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  169546. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  169547. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  169548. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  169549. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  169550. #else
  169551. #define FIX_0_211164243 FIX(0.211164243)
  169552. #define FIX_0_509795579 FIX(0.509795579)
  169553. #define FIX_0_601344887 FIX(0.601344887)
  169554. #define FIX_0_720959822 FIX(0.720959822)
  169555. #define FIX_0_765366865 FIX(0.765366865)
  169556. #define FIX_0_850430095 FIX(0.850430095)
  169557. #define FIX_0_899976223 FIX(0.899976223)
  169558. #define FIX_1_061594337 FIX(1.061594337)
  169559. #define FIX_1_272758580 FIX(1.272758580)
  169560. #define FIX_1_451774981 FIX(1.451774981)
  169561. #define FIX_1_847759065 FIX(1.847759065)
  169562. #define FIX_2_172734803 FIX(2.172734803)
  169563. #define FIX_2_562915447 FIX(2.562915447)
  169564. #define FIX_3_624509785 FIX(3.624509785)
  169565. #endif
  169566. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  169567. * For 8-bit samples with the recommended scaling, all the variable
  169568. * and constant values involved are no more than 16 bits wide, so a
  169569. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  169570. * For 12-bit samples, a full 32-bit multiplication will be needed.
  169571. */
  169572. #if BITS_IN_JSAMPLE == 8
  169573. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  169574. #else
  169575. #define MULTIPLY(var,const) ((var) * (const))
  169576. #endif
  169577. /* Dequantize a coefficient by multiplying it by the multiplier-table
  169578. * entry; produce an int result. In this module, both inputs and result
  169579. * are 16 bits or less, so either int or short multiply will work.
  169580. */
  169581. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  169582. /*
  169583. * Perform dequantization and inverse DCT on one block of coefficients,
  169584. * producing a reduced-size 4x4 output block.
  169585. */
  169586. GLOBAL(void)
  169587. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169588. JCOEFPTR coef_block,
  169589. JSAMPARRAY output_buf, JDIMENSION output_col)
  169590. {
  169591. INT32 tmp0, tmp2, tmp10, tmp12;
  169592. INT32 z1, z2, z3, z4;
  169593. JCOEFPTR inptr;
  169594. ISLOW_MULT_TYPE * quantptr;
  169595. int * wsptr;
  169596. JSAMPROW outptr;
  169597. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169598. int ctr;
  169599. int workspace[DCTSIZE*4]; /* buffers data between passes */
  169600. SHIFT_TEMPS
  169601. /* Pass 1: process columns from input, store into work array. */
  169602. inptr = coef_block;
  169603. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169604. wsptr = workspace;
  169605. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  169606. /* Don't bother to process column 4, because second pass won't use it */
  169607. if (ctr == DCTSIZE-4)
  169608. continue;
  169609. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  169610. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  169611. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  169612. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  169613. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  169614. wsptr[DCTSIZE*0] = dcval;
  169615. wsptr[DCTSIZE*1] = dcval;
  169616. wsptr[DCTSIZE*2] = dcval;
  169617. wsptr[DCTSIZE*3] = dcval;
  169618. continue;
  169619. }
  169620. /* Even part */
  169621. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169622. tmp0 <<= (CONST_BITS+1);
  169623. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  169624. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  169625. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  169626. tmp10 = tmp0 + tmp2;
  169627. tmp12 = tmp0 - tmp2;
  169628. /* Odd part */
  169629. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  169630. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  169631. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  169632. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  169633. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  169634. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  169635. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  169636. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  169637. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  169638. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  169639. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  169640. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  169641. /* Final output stage */
  169642. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  169643. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  169644. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  169645. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  169646. }
  169647. /* Pass 2: process 4 rows from work array, store into output array. */
  169648. wsptr = workspace;
  169649. for (ctr = 0; ctr < 4; ctr++) {
  169650. outptr = output_buf[ctr] + output_col;
  169651. /* It's not clear whether a zero row test is worthwhile here ... */
  169652. #ifndef NO_ZERO_ROW_TEST
  169653. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  169654. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  169655. /* AC terms all zero */
  169656. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  169657. & RANGE_MASK];
  169658. outptr[0] = dcval;
  169659. outptr[1] = dcval;
  169660. outptr[2] = dcval;
  169661. outptr[3] = dcval;
  169662. wsptr += DCTSIZE; /* advance pointer to next row */
  169663. continue;
  169664. }
  169665. #endif
  169666. /* Even part */
  169667. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  169668. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  169669. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  169670. tmp10 = tmp0 + tmp2;
  169671. tmp12 = tmp0 - tmp2;
  169672. /* Odd part */
  169673. z1 = (INT32) wsptr[7];
  169674. z2 = (INT32) wsptr[5];
  169675. z3 = (INT32) wsptr[3];
  169676. z4 = (INT32) wsptr[1];
  169677. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  169678. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  169679. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  169680. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  169681. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  169682. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  169683. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  169684. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  169685. /* Final output stage */
  169686. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  169687. CONST_BITS+PASS1_BITS+3+1)
  169688. & RANGE_MASK];
  169689. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  169690. CONST_BITS+PASS1_BITS+3+1)
  169691. & RANGE_MASK];
  169692. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  169693. CONST_BITS+PASS1_BITS+3+1)
  169694. & RANGE_MASK];
  169695. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  169696. CONST_BITS+PASS1_BITS+3+1)
  169697. & RANGE_MASK];
  169698. wsptr += DCTSIZE; /* advance pointer to next row */
  169699. }
  169700. }
  169701. /*
  169702. * Perform dequantization and inverse DCT on one block of coefficients,
  169703. * producing a reduced-size 2x2 output block.
  169704. */
  169705. GLOBAL(void)
  169706. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169707. JCOEFPTR coef_block,
  169708. JSAMPARRAY output_buf, JDIMENSION output_col)
  169709. {
  169710. INT32 tmp0, tmp10, z1;
  169711. JCOEFPTR inptr;
  169712. ISLOW_MULT_TYPE * quantptr;
  169713. int * wsptr;
  169714. JSAMPROW outptr;
  169715. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169716. int ctr;
  169717. int workspace[DCTSIZE*2]; /* buffers data between passes */
  169718. SHIFT_TEMPS
  169719. /* Pass 1: process columns from input, store into work array. */
  169720. inptr = coef_block;
  169721. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169722. wsptr = workspace;
  169723. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  169724. /* Don't bother to process columns 2,4,6 */
  169725. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  169726. continue;
  169727. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  169728. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  169729. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  169730. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  169731. wsptr[DCTSIZE*0] = dcval;
  169732. wsptr[DCTSIZE*1] = dcval;
  169733. continue;
  169734. }
  169735. /* Even part */
  169736. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169737. tmp10 = z1 << (CONST_BITS+2);
  169738. /* Odd part */
  169739. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  169740. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  169741. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  169742. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  169743. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  169744. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  169745. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  169746. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  169747. /* Final output stage */
  169748. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  169749. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  169750. }
  169751. /* Pass 2: process 2 rows from work array, store into output array. */
  169752. wsptr = workspace;
  169753. for (ctr = 0; ctr < 2; ctr++) {
  169754. outptr = output_buf[ctr] + output_col;
  169755. /* It's not clear whether a zero row test is worthwhile here ... */
  169756. #ifndef NO_ZERO_ROW_TEST
  169757. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  169758. /* AC terms all zero */
  169759. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  169760. & RANGE_MASK];
  169761. outptr[0] = dcval;
  169762. outptr[1] = dcval;
  169763. wsptr += DCTSIZE; /* advance pointer to next row */
  169764. continue;
  169765. }
  169766. #endif
  169767. /* Even part */
  169768. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  169769. /* Odd part */
  169770. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  169771. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  169772. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  169773. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  169774. /* Final output stage */
  169775. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  169776. CONST_BITS+PASS1_BITS+3+2)
  169777. & RANGE_MASK];
  169778. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  169779. CONST_BITS+PASS1_BITS+3+2)
  169780. & RANGE_MASK];
  169781. wsptr += DCTSIZE; /* advance pointer to next row */
  169782. }
  169783. }
  169784. /*
  169785. * Perform dequantization and inverse DCT on one block of coefficients,
  169786. * producing a reduced-size 1x1 output block.
  169787. */
  169788. GLOBAL(void)
  169789. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169790. JCOEFPTR coef_block,
  169791. JSAMPARRAY output_buf, JDIMENSION output_col)
  169792. {
  169793. int dcval;
  169794. ISLOW_MULT_TYPE * quantptr;
  169795. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169796. SHIFT_TEMPS
  169797. /* We hardly need an inverse DCT routine for this: just take the
  169798. * average pixel value, which is one-eighth of the DC coefficient.
  169799. */
  169800. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169801. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  169802. dcval = (int) DESCALE((INT32) dcval, 3);
  169803. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  169804. }
  169805. #endif /* IDCT_SCALING_SUPPORTED */
  169806. /********* End of inlined file: jidctred.c *********/
  169807. /********* Start of inlined file: jmemmgr.c *********/
  169808. #define JPEG_INTERNALS
  169809. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  169810. /********* Start of inlined file: jmemsys.h *********/
  169811. #ifndef __jmemsys_h__
  169812. #define __jmemsys_h__
  169813. /* Short forms of external names for systems with brain-damaged linkers. */
  169814. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169815. #define jpeg_get_small jGetSmall
  169816. #define jpeg_free_small jFreeSmall
  169817. #define jpeg_get_large jGetLarge
  169818. #define jpeg_free_large jFreeLarge
  169819. #define jpeg_mem_available jMemAvail
  169820. #define jpeg_open_backing_store jOpenBackStore
  169821. #define jpeg_mem_init jMemInit
  169822. #define jpeg_mem_term jMemTerm
  169823. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169824. /*
  169825. * These two functions are used to allocate and release small chunks of
  169826. * memory. (Typically the total amount requested through jpeg_get_small is
  169827. * no more than 20K or so; this will be requested in chunks of a few K each.)
  169828. * Behavior should be the same as for the standard library functions malloc
  169829. * and free; in particular, jpeg_get_small must return NULL on failure.
  169830. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  169831. * size of the object being freed, just in case it's needed.
  169832. * On an 80x86 machine using small-data memory model, these manage near heap.
  169833. */
  169834. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  169835. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  169836. size_t sizeofobject));
  169837. /*
  169838. * These two functions are used to allocate and release large chunks of
  169839. * memory (up to the total free space designated by jpeg_mem_available).
  169840. * The interface is the same as above, except that on an 80x86 machine,
  169841. * far pointers are used. On most other machines these are identical to
  169842. * the jpeg_get/free_small routines; but we keep them separate anyway,
  169843. * in case a different allocation strategy is desirable for large chunks.
  169844. */
  169845. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  169846. size_t sizeofobject));
  169847. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  169848. size_t sizeofobject));
  169849. /*
  169850. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  169851. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  169852. * matter, but that case should never come into play). This macro is needed
  169853. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  169854. * On those machines, we expect that jconfig.h will provide a proper value.
  169855. * On machines with 32-bit flat address spaces, any large constant may be used.
  169856. *
  169857. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  169858. * size_t and will be a multiple of sizeof(align_type).
  169859. */
  169860. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  169861. #define MAX_ALLOC_CHUNK 1000000000L
  169862. #endif
  169863. /*
  169864. * This routine computes the total space still available for allocation by
  169865. * jpeg_get_large. If more space than this is needed, backing store will be
  169866. * used. NOTE: any memory already allocated must not be counted.
  169867. *
  169868. * There is a minimum space requirement, corresponding to the minimum
  169869. * feasible buffer sizes; jmemmgr.c will request that much space even if
  169870. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  169871. * all working storage in memory, is also passed in case it is useful.
  169872. * Finally, the total space already allocated is passed. If no better
  169873. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  169874. * is often a suitable calculation.
  169875. *
  169876. * It is OK for jpeg_mem_available to underestimate the space available
  169877. * (that'll just lead to more backing-store access than is really necessary).
  169878. * However, an overestimate will lead to failure. Hence it's wise to subtract
  169879. * a slop factor from the true available space. 5% should be enough.
  169880. *
  169881. * On machines with lots of virtual memory, any large constant may be returned.
  169882. * Conversely, zero may be returned to always use the minimum amount of memory.
  169883. */
  169884. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  169885. long min_bytes_needed,
  169886. long max_bytes_needed,
  169887. long already_allocated));
  169888. /*
  169889. * This structure holds whatever state is needed to access a single
  169890. * backing-store object. The read/write/close method pointers are called
  169891. * by jmemmgr.c to manipulate the backing-store object; all other fields
  169892. * are private to the system-dependent backing store routines.
  169893. */
  169894. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  169895. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  169896. typedef unsigned short XMSH; /* type of extended-memory handles */
  169897. typedef unsigned short EMSH; /* type of expanded-memory handles */
  169898. typedef union {
  169899. short file_handle; /* DOS file handle if it's a temp file */
  169900. XMSH xms_handle; /* handle if it's a chunk of XMS */
  169901. EMSH ems_handle; /* handle if it's a chunk of EMS */
  169902. } handle_union;
  169903. #endif /* USE_MSDOS_MEMMGR */
  169904. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  169905. #include <Files.h>
  169906. #endif /* USE_MAC_MEMMGR */
  169907. //typedef struct backing_store_struct * backing_store_ptr;
  169908. typedef struct backing_store_struct {
  169909. /* Methods for reading/writing/closing this backing-store object */
  169910. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  169911. struct backing_store_struct *info,
  169912. void FAR * buffer_address,
  169913. long file_offset, long byte_count));
  169914. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  169915. struct backing_store_struct *info,
  169916. void FAR * buffer_address,
  169917. long file_offset, long byte_count));
  169918. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  169919. struct backing_store_struct *info));
  169920. /* Private fields for system-dependent backing-store management */
  169921. #ifdef USE_MSDOS_MEMMGR
  169922. /* For the MS-DOS manager (jmemdos.c), we need: */
  169923. handle_union handle; /* reference to backing-store storage object */
  169924. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  169925. #else
  169926. #ifdef USE_MAC_MEMMGR
  169927. /* For the Mac manager (jmemmac.c), we need: */
  169928. short temp_file; /* file reference number to temp file */
  169929. FSSpec tempSpec; /* the FSSpec for the temp file */
  169930. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  169931. #else
  169932. /* For a typical implementation with temp files, we need: */
  169933. FILE * temp_file; /* stdio reference to temp file */
  169934. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  169935. #endif
  169936. #endif
  169937. } backing_store_info;
  169938. /*
  169939. * Initial opening of a backing-store object. This must fill in the
  169940. * read/write/close pointers in the object. The read/write routines
  169941. * may take an error exit if the specified maximum file size is exceeded.
  169942. * (If jpeg_mem_available always returns a large value, this routine can
  169943. * just take an error exit.)
  169944. */
  169945. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  169946. struct backing_store_struct *info,
  169947. long total_bytes_needed));
  169948. /*
  169949. * These routines take care of any system-dependent initialization and
  169950. * cleanup required. jpeg_mem_init will be called before anything is
  169951. * allocated (and, therefore, nothing in cinfo is of use except the error
  169952. * manager pointer). It should return a suitable default value for
  169953. * max_memory_to_use; this may subsequently be overridden by the surrounding
  169954. * application. (Note that max_memory_to_use is only important if
  169955. * jpeg_mem_available chooses to consult it ... no one else will.)
  169956. * jpeg_mem_term may assume that all requested memory has been freed and that
  169957. * all opened backing-store objects have been closed.
  169958. */
  169959. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  169960. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  169961. #endif
  169962. /********* End of inlined file: jmemsys.h *********/
  169963. /* import the system-dependent declarations */
  169964. #ifndef NO_GETENV
  169965. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  169966. extern char * getenv JPP((const char * name));
  169967. #endif
  169968. #endif
  169969. /*
  169970. * Some important notes:
  169971. * The allocation routines provided here must never return NULL.
  169972. * They should exit to error_exit if unsuccessful.
  169973. *
  169974. * It's not a good idea to try to merge the sarray and barray routines,
  169975. * even though they are textually almost the same, because samples are
  169976. * usually stored as bytes while coefficients are shorts or ints. Thus,
  169977. * in machines where byte pointers have a different representation from
  169978. * word pointers, the resulting machine code could not be the same.
  169979. */
  169980. /*
  169981. * Many machines require storage alignment: longs must start on 4-byte
  169982. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  169983. * always returns pointers that are multiples of the worst-case alignment
  169984. * requirement, and we had better do so too.
  169985. * There isn't any really portable way to determine the worst-case alignment
  169986. * requirement. This module assumes that the alignment requirement is
  169987. * multiples of sizeof(ALIGN_TYPE).
  169988. * By default, we define ALIGN_TYPE as double. This is necessary on some
  169989. * workstations (where doubles really do need 8-byte alignment) and will work
  169990. * fine on nearly everything. If your machine has lesser alignment needs,
  169991. * you can save a few bytes by making ALIGN_TYPE smaller.
  169992. * The only place I know of where this will NOT work is certain Macintosh
  169993. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  169994. * Doing 10-byte alignment is counterproductive because longwords won't be
  169995. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  169996. * such a compiler.
  169997. */
  169998. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  169999. #define ALIGN_TYPE double
  170000. #endif
  170001. /*
  170002. * We allocate objects from "pools", where each pool is gotten with a single
  170003. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  170004. * overhead within a pool, except for alignment padding. Each pool has a
  170005. * header with a link to the next pool of the same class.
  170006. * Small and large pool headers are identical except that the latter's
  170007. * link pointer must be FAR on 80x86 machines.
  170008. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  170009. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  170010. * of the alignment requirement of ALIGN_TYPE.
  170011. */
  170012. typedef union small_pool_struct * small_pool_ptr;
  170013. typedef union small_pool_struct {
  170014. struct {
  170015. small_pool_ptr next; /* next in list of pools */
  170016. size_t bytes_used; /* how many bytes already used within pool */
  170017. size_t bytes_left; /* bytes still available in this pool */
  170018. } hdr;
  170019. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  170020. } small_pool_hdr;
  170021. typedef union large_pool_struct FAR * large_pool_ptr;
  170022. typedef union large_pool_struct {
  170023. struct {
  170024. large_pool_ptr next; /* next in list of pools */
  170025. size_t bytes_used; /* how many bytes already used within pool */
  170026. size_t bytes_left; /* bytes still available in this pool */
  170027. } hdr;
  170028. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  170029. } large_pool_hdr;
  170030. /*
  170031. * Here is the full definition of a memory manager object.
  170032. */
  170033. typedef struct {
  170034. struct jpeg_memory_mgr pub; /* public fields */
  170035. /* Each pool identifier (lifetime class) names a linked list of pools. */
  170036. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  170037. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  170038. /* Since we only have one lifetime class of virtual arrays, only one
  170039. * linked list is necessary (for each datatype). Note that the virtual
  170040. * array control blocks being linked together are actually stored somewhere
  170041. * in the small-pool list.
  170042. */
  170043. jvirt_sarray_ptr virt_sarray_list;
  170044. jvirt_barray_ptr virt_barray_list;
  170045. /* This counts total space obtained from jpeg_get_small/large */
  170046. long total_space_allocated;
  170047. /* alloc_sarray and alloc_barray set this value for use by virtual
  170048. * array routines.
  170049. */
  170050. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  170051. } my_memory_mgr;
  170052. typedef my_memory_mgr * my_mem_ptr;
  170053. /*
  170054. * The control blocks for virtual arrays.
  170055. * Note that these blocks are allocated in the "small" pool area.
  170056. * System-dependent info for the associated backing store (if any) is hidden
  170057. * inside the backing_store_info struct.
  170058. */
  170059. struct jvirt_sarray_control {
  170060. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  170061. JDIMENSION rows_in_array; /* total virtual array height */
  170062. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  170063. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  170064. JDIMENSION rows_in_mem; /* height of memory buffer */
  170065. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  170066. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  170067. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  170068. boolean pre_zero; /* pre-zero mode requested? */
  170069. boolean dirty; /* do current buffer contents need written? */
  170070. boolean b_s_open; /* is backing-store data valid? */
  170071. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  170072. backing_store_info b_s_info; /* System-dependent control info */
  170073. };
  170074. struct jvirt_barray_control {
  170075. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  170076. JDIMENSION rows_in_array; /* total virtual array height */
  170077. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  170078. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  170079. JDIMENSION rows_in_mem; /* height of memory buffer */
  170080. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  170081. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  170082. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  170083. boolean pre_zero; /* pre-zero mode requested? */
  170084. boolean dirty; /* do current buffer contents need written? */
  170085. boolean b_s_open; /* is backing-store data valid? */
  170086. jvirt_barray_ptr next; /* link to next virtual barray control block */
  170087. backing_store_info b_s_info; /* System-dependent control info */
  170088. };
  170089. #ifdef MEM_STATS /* optional extra stuff for statistics */
  170090. LOCAL(void)
  170091. print_mem_stats (j_common_ptr cinfo, int pool_id)
  170092. {
  170093. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170094. small_pool_ptr shdr_ptr;
  170095. large_pool_ptr lhdr_ptr;
  170096. /* Since this is only a debugging stub, we can cheat a little by using
  170097. * fprintf directly rather than going through the trace message code.
  170098. * This is helpful because message parm array can't handle longs.
  170099. */
  170100. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  170101. pool_id, mem->total_space_allocated);
  170102. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  170103. lhdr_ptr = lhdr_ptr->hdr.next) {
  170104. fprintf(stderr, " Large chunk used %ld\n",
  170105. (long) lhdr_ptr->hdr.bytes_used);
  170106. }
  170107. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  170108. shdr_ptr = shdr_ptr->hdr.next) {
  170109. fprintf(stderr, " Small chunk used %ld free %ld\n",
  170110. (long) shdr_ptr->hdr.bytes_used,
  170111. (long) shdr_ptr->hdr.bytes_left);
  170112. }
  170113. }
  170114. #endif /* MEM_STATS */
  170115. LOCAL(void)
  170116. out_of_memory (j_common_ptr cinfo, int which)
  170117. /* Report an out-of-memory error and stop execution */
  170118. /* If we compiled MEM_STATS support, report alloc requests before dying */
  170119. {
  170120. #ifdef MEM_STATS
  170121. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  170122. #endif
  170123. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  170124. }
  170125. /*
  170126. * Allocation of "small" objects.
  170127. *
  170128. * For these, we use pooled storage. When a new pool must be created,
  170129. * we try to get enough space for the current request plus a "slop" factor,
  170130. * where the slop will be the amount of leftover space in the new pool.
  170131. * The speed vs. space tradeoff is largely determined by the slop values.
  170132. * A different slop value is provided for each pool class (lifetime),
  170133. * and we also distinguish the first pool of a class from later ones.
  170134. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  170135. * machines, but may be too small if longs are 64 bits or more.
  170136. */
  170137. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  170138. {
  170139. 1600, /* first PERMANENT pool */
  170140. 16000 /* first IMAGE pool */
  170141. };
  170142. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  170143. {
  170144. 0, /* additional PERMANENT pools */
  170145. 5000 /* additional IMAGE pools */
  170146. };
  170147. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  170148. METHODDEF(void *)
  170149. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  170150. /* Allocate a "small" object */
  170151. {
  170152. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170153. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  170154. char * data_ptr;
  170155. size_t odd_bytes, min_request, slop;
  170156. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  170157. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  170158. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  170159. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  170160. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  170161. if (odd_bytes > 0)
  170162. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  170163. /* See if space is available in any existing pool */
  170164. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  170165. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  170166. prev_hdr_ptr = NULL;
  170167. hdr_ptr = mem->small_list[pool_id];
  170168. while (hdr_ptr != NULL) {
  170169. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  170170. break; /* found pool with enough space */
  170171. prev_hdr_ptr = hdr_ptr;
  170172. hdr_ptr = hdr_ptr->hdr.next;
  170173. }
  170174. /* Time to make a new pool? */
  170175. if (hdr_ptr == NULL) {
  170176. /* min_request is what we need now, slop is what will be leftover */
  170177. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  170178. if (prev_hdr_ptr == NULL) /* first pool in class? */
  170179. slop = first_pool_slop[pool_id];
  170180. else
  170181. slop = extra_pool_slop[pool_id];
  170182. /* Don't ask for more than MAX_ALLOC_CHUNK */
  170183. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  170184. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  170185. /* Try to get space, if fail reduce slop and try again */
  170186. for (;;) {
  170187. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  170188. if (hdr_ptr != NULL)
  170189. break;
  170190. slop /= 2;
  170191. if (slop < MIN_SLOP) /* give up when it gets real small */
  170192. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  170193. }
  170194. mem->total_space_allocated += min_request + slop;
  170195. /* Success, initialize the new pool header and add to end of list */
  170196. hdr_ptr->hdr.next = NULL;
  170197. hdr_ptr->hdr.bytes_used = 0;
  170198. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  170199. if (prev_hdr_ptr == NULL) /* first pool in class? */
  170200. mem->small_list[pool_id] = hdr_ptr;
  170201. else
  170202. prev_hdr_ptr->hdr.next = hdr_ptr;
  170203. }
  170204. /* OK, allocate the object from the current pool */
  170205. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  170206. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  170207. hdr_ptr->hdr.bytes_used += sizeofobject;
  170208. hdr_ptr->hdr.bytes_left -= sizeofobject;
  170209. return (void *) data_ptr;
  170210. }
  170211. /*
  170212. * Allocation of "large" objects.
  170213. *
  170214. * The external semantics of these are the same as "small" objects,
  170215. * except that FAR pointers are used on 80x86. However the pool
  170216. * management heuristics are quite different. We assume that each
  170217. * request is large enough that it may as well be passed directly to
  170218. * jpeg_get_large; the pool management just links everything together
  170219. * so that we can free it all on demand.
  170220. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  170221. * structures. The routines that create these structures (see below)
  170222. * deliberately bunch rows together to ensure a large request size.
  170223. */
  170224. METHODDEF(void FAR *)
  170225. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  170226. /* Allocate a "large" object */
  170227. {
  170228. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170229. large_pool_ptr hdr_ptr;
  170230. size_t odd_bytes;
  170231. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  170232. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  170233. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  170234. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  170235. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  170236. if (odd_bytes > 0)
  170237. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  170238. /* Always make a new pool */
  170239. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  170240. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  170241. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  170242. SIZEOF(large_pool_hdr));
  170243. if (hdr_ptr == NULL)
  170244. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  170245. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  170246. /* Success, initialize the new pool header and add to list */
  170247. hdr_ptr->hdr.next = mem->large_list[pool_id];
  170248. /* We maintain space counts in each pool header for statistical purposes,
  170249. * even though they are not needed for allocation.
  170250. */
  170251. hdr_ptr->hdr.bytes_used = sizeofobject;
  170252. hdr_ptr->hdr.bytes_left = 0;
  170253. mem->large_list[pool_id] = hdr_ptr;
  170254. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  170255. }
  170256. /*
  170257. * Creation of 2-D sample arrays.
  170258. * The pointers are in near heap, the samples themselves in FAR heap.
  170259. *
  170260. * To minimize allocation overhead and to allow I/O of large contiguous
  170261. * blocks, we allocate the sample rows in groups of as many rows as possible
  170262. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  170263. * NB: the virtual array control routines, later in this file, know about
  170264. * this chunking of rows. The rowsperchunk value is left in the mem manager
  170265. * object so that it can be saved away if this sarray is the workspace for
  170266. * a virtual array.
  170267. */
  170268. METHODDEF(JSAMPARRAY)
  170269. alloc_sarray (j_common_ptr cinfo, int pool_id,
  170270. JDIMENSION samplesperrow, JDIMENSION numrows)
  170271. /* Allocate a 2-D sample array */
  170272. {
  170273. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170274. JSAMPARRAY result;
  170275. JSAMPROW workspace;
  170276. JDIMENSION rowsperchunk, currow, i;
  170277. long ltemp;
  170278. /* Calculate max # of rows allowed in one allocation chunk */
  170279. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  170280. ((long) samplesperrow * SIZEOF(JSAMPLE));
  170281. if (ltemp <= 0)
  170282. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  170283. if (ltemp < (long) numrows)
  170284. rowsperchunk = (JDIMENSION) ltemp;
  170285. else
  170286. rowsperchunk = numrows;
  170287. mem->last_rowsperchunk = rowsperchunk;
  170288. /* Get space for row pointers (small object) */
  170289. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  170290. (size_t) (numrows * SIZEOF(JSAMPROW)));
  170291. /* Get the rows themselves (large objects) */
  170292. currow = 0;
  170293. while (currow < numrows) {
  170294. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  170295. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  170296. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  170297. * SIZEOF(JSAMPLE)));
  170298. for (i = rowsperchunk; i > 0; i--) {
  170299. result[currow++] = workspace;
  170300. workspace += samplesperrow;
  170301. }
  170302. }
  170303. return result;
  170304. }
  170305. /*
  170306. * Creation of 2-D coefficient-block arrays.
  170307. * This is essentially the same as the code for sample arrays, above.
  170308. */
  170309. METHODDEF(JBLOCKARRAY)
  170310. alloc_barray (j_common_ptr cinfo, int pool_id,
  170311. JDIMENSION blocksperrow, JDIMENSION numrows)
  170312. /* Allocate a 2-D coefficient-block array */
  170313. {
  170314. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170315. JBLOCKARRAY result;
  170316. JBLOCKROW workspace;
  170317. JDIMENSION rowsperchunk, currow, i;
  170318. long ltemp;
  170319. /* Calculate max # of rows allowed in one allocation chunk */
  170320. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  170321. ((long) blocksperrow * SIZEOF(JBLOCK));
  170322. if (ltemp <= 0)
  170323. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  170324. if (ltemp < (long) numrows)
  170325. rowsperchunk = (JDIMENSION) ltemp;
  170326. else
  170327. rowsperchunk = numrows;
  170328. mem->last_rowsperchunk = rowsperchunk;
  170329. /* Get space for row pointers (small object) */
  170330. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  170331. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  170332. /* Get the rows themselves (large objects) */
  170333. currow = 0;
  170334. while (currow < numrows) {
  170335. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  170336. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  170337. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  170338. * SIZEOF(JBLOCK)));
  170339. for (i = rowsperchunk; i > 0; i--) {
  170340. result[currow++] = workspace;
  170341. workspace += blocksperrow;
  170342. }
  170343. }
  170344. return result;
  170345. }
  170346. /*
  170347. * About virtual array management:
  170348. *
  170349. * The above "normal" array routines are only used to allocate strip buffers
  170350. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  170351. * are handled as "virtual" arrays. The array is still accessed a strip at a
  170352. * time, but the memory manager must save the whole array for repeated
  170353. * accesses. The intended implementation is that there is a strip buffer in
  170354. * memory (as high as is possible given the desired memory limit), plus a
  170355. * backing file that holds the rest of the array.
  170356. *
  170357. * The request_virt_array routines are told the total size of the image and
  170358. * the maximum number of rows that will be accessed at once. The in-memory
  170359. * buffer must be at least as large as the maxaccess value.
  170360. *
  170361. * The request routines create control blocks but not the in-memory buffers.
  170362. * That is postponed until realize_virt_arrays is called. At that time the
  170363. * total amount of space needed is known (approximately, anyway), so free
  170364. * memory can be divided up fairly.
  170365. *
  170366. * The access_virt_array routines are responsible for making a specific strip
  170367. * area accessible (after reading or writing the backing file, if necessary).
  170368. * Note that the access routines are told whether the caller intends to modify
  170369. * the accessed strip; during a read-only pass this saves having to rewrite
  170370. * data to disk. The access routines are also responsible for pre-zeroing
  170371. * any newly accessed rows, if pre-zeroing was requested.
  170372. *
  170373. * In current usage, the access requests are usually for nonoverlapping
  170374. * strips; that is, successive access start_row numbers differ by exactly
  170375. * num_rows = maxaccess. This means we can get good performance with simple
  170376. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  170377. * of the access height; then there will never be accesses across bufferload
  170378. * boundaries. The code will still work with overlapping access requests,
  170379. * but it doesn't handle bufferload overlaps very efficiently.
  170380. */
  170381. METHODDEF(jvirt_sarray_ptr)
  170382. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  170383. JDIMENSION samplesperrow, JDIMENSION numrows,
  170384. JDIMENSION maxaccess)
  170385. /* Request a virtual 2-D sample array */
  170386. {
  170387. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170388. jvirt_sarray_ptr result;
  170389. /* Only IMAGE-lifetime virtual arrays are currently supported */
  170390. if (pool_id != JPOOL_IMAGE)
  170391. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  170392. /* get control block */
  170393. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  170394. SIZEOF(struct jvirt_sarray_control));
  170395. result->mem_buffer = NULL; /* marks array not yet realized */
  170396. result->rows_in_array = numrows;
  170397. result->samplesperrow = samplesperrow;
  170398. result->maxaccess = maxaccess;
  170399. result->pre_zero = pre_zero;
  170400. result->b_s_open = FALSE; /* no associated backing-store object */
  170401. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  170402. mem->virt_sarray_list = result;
  170403. return result;
  170404. }
  170405. METHODDEF(jvirt_barray_ptr)
  170406. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  170407. JDIMENSION blocksperrow, JDIMENSION numrows,
  170408. JDIMENSION maxaccess)
  170409. /* Request a virtual 2-D coefficient-block array */
  170410. {
  170411. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170412. jvirt_barray_ptr result;
  170413. /* Only IMAGE-lifetime virtual arrays are currently supported */
  170414. if (pool_id != JPOOL_IMAGE)
  170415. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  170416. /* get control block */
  170417. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  170418. SIZEOF(struct jvirt_barray_control));
  170419. result->mem_buffer = NULL; /* marks array not yet realized */
  170420. result->rows_in_array = numrows;
  170421. result->blocksperrow = blocksperrow;
  170422. result->maxaccess = maxaccess;
  170423. result->pre_zero = pre_zero;
  170424. result->b_s_open = FALSE; /* no associated backing-store object */
  170425. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  170426. mem->virt_barray_list = result;
  170427. return result;
  170428. }
  170429. METHODDEF(void)
  170430. realize_virt_arrays (j_common_ptr cinfo)
  170431. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  170432. {
  170433. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170434. long space_per_minheight, maximum_space, avail_mem;
  170435. long minheights, max_minheights;
  170436. jvirt_sarray_ptr sptr;
  170437. jvirt_barray_ptr bptr;
  170438. /* Compute the minimum space needed (maxaccess rows in each buffer)
  170439. * and the maximum space needed (full image height in each buffer).
  170440. * These may be of use to the system-dependent jpeg_mem_available routine.
  170441. */
  170442. space_per_minheight = 0;
  170443. maximum_space = 0;
  170444. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  170445. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  170446. space_per_minheight += (long) sptr->maxaccess *
  170447. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  170448. maximum_space += (long) sptr->rows_in_array *
  170449. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  170450. }
  170451. }
  170452. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  170453. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  170454. space_per_minheight += (long) bptr->maxaccess *
  170455. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  170456. maximum_space += (long) bptr->rows_in_array *
  170457. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  170458. }
  170459. }
  170460. if (space_per_minheight <= 0)
  170461. return; /* no unrealized arrays, no work */
  170462. /* Determine amount of memory to actually use; this is system-dependent. */
  170463. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  170464. mem->total_space_allocated);
  170465. /* If the maximum space needed is available, make all the buffers full
  170466. * height; otherwise parcel it out with the same number of minheights
  170467. * in each buffer.
  170468. */
  170469. if (avail_mem >= maximum_space)
  170470. max_minheights = 1000000000L;
  170471. else {
  170472. max_minheights = avail_mem / space_per_minheight;
  170473. /* If there doesn't seem to be enough space, try to get the minimum
  170474. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  170475. */
  170476. if (max_minheights <= 0)
  170477. max_minheights = 1;
  170478. }
  170479. /* Allocate the in-memory buffers and initialize backing store as needed. */
  170480. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  170481. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  170482. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  170483. if (minheights <= max_minheights) {
  170484. /* This buffer fits in memory */
  170485. sptr->rows_in_mem = sptr->rows_in_array;
  170486. } else {
  170487. /* It doesn't fit in memory, create backing store. */
  170488. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  170489. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  170490. (long) sptr->rows_in_array *
  170491. (long) sptr->samplesperrow *
  170492. (long) SIZEOF(JSAMPLE));
  170493. sptr->b_s_open = TRUE;
  170494. }
  170495. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  170496. sptr->samplesperrow, sptr->rows_in_mem);
  170497. sptr->rowsperchunk = mem->last_rowsperchunk;
  170498. sptr->cur_start_row = 0;
  170499. sptr->first_undef_row = 0;
  170500. sptr->dirty = FALSE;
  170501. }
  170502. }
  170503. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  170504. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  170505. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  170506. if (minheights <= max_minheights) {
  170507. /* This buffer fits in memory */
  170508. bptr->rows_in_mem = bptr->rows_in_array;
  170509. } else {
  170510. /* It doesn't fit in memory, create backing store. */
  170511. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  170512. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  170513. (long) bptr->rows_in_array *
  170514. (long) bptr->blocksperrow *
  170515. (long) SIZEOF(JBLOCK));
  170516. bptr->b_s_open = TRUE;
  170517. }
  170518. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  170519. bptr->blocksperrow, bptr->rows_in_mem);
  170520. bptr->rowsperchunk = mem->last_rowsperchunk;
  170521. bptr->cur_start_row = 0;
  170522. bptr->first_undef_row = 0;
  170523. bptr->dirty = FALSE;
  170524. }
  170525. }
  170526. }
  170527. LOCAL(void)
  170528. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  170529. /* Do backing store read or write of a virtual sample array */
  170530. {
  170531. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  170532. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  170533. file_offset = ptr->cur_start_row * bytesperrow;
  170534. /* Loop to read or write each allocation chunk in mem_buffer */
  170535. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  170536. /* One chunk, but check for short chunk at end of buffer */
  170537. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  170538. /* Transfer no more than is currently defined */
  170539. thisrow = (long) ptr->cur_start_row + i;
  170540. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  170541. /* Transfer no more than fits in file */
  170542. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  170543. if (rows <= 0) /* this chunk might be past end of file! */
  170544. break;
  170545. byte_count = rows * bytesperrow;
  170546. if (writing)
  170547. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  170548. (void FAR *) ptr->mem_buffer[i],
  170549. file_offset, byte_count);
  170550. else
  170551. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  170552. (void FAR *) ptr->mem_buffer[i],
  170553. file_offset, byte_count);
  170554. file_offset += byte_count;
  170555. }
  170556. }
  170557. LOCAL(void)
  170558. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  170559. /* Do backing store read or write of a virtual coefficient-block array */
  170560. {
  170561. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  170562. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  170563. file_offset = ptr->cur_start_row * bytesperrow;
  170564. /* Loop to read or write each allocation chunk in mem_buffer */
  170565. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  170566. /* One chunk, but check for short chunk at end of buffer */
  170567. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  170568. /* Transfer no more than is currently defined */
  170569. thisrow = (long) ptr->cur_start_row + i;
  170570. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  170571. /* Transfer no more than fits in file */
  170572. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  170573. if (rows <= 0) /* this chunk might be past end of file! */
  170574. break;
  170575. byte_count = rows * bytesperrow;
  170576. if (writing)
  170577. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  170578. (void FAR *) ptr->mem_buffer[i],
  170579. file_offset, byte_count);
  170580. else
  170581. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  170582. (void FAR *) ptr->mem_buffer[i],
  170583. file_offset, byte_count);
  170584. file_offset += byte_count;
  170585. }
  170586. }
  170587. METHODDEF(JSAMPARRAY)
  170588. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  170589. JDIMENSION start_row, JDIMENSION num_rows,
  170590. boolean writable)
  170591. /* Access the part of a virtual sample array starting at start_row */
  170592. /* and extending for num_rows rows. writable is true if */
  170593. /* caller intends to modify the accessed area. */
  170594. {
  170595. JDIMENSION end_row = start_row + num_rows;
  170596. JDIMENSION undef_row;
  170597. /* debugging check */
  170598. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  170599. ptr->mem_buffer == NULL)
  170600. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170601. /* Make the desired part of the virtual array accessible */
  170602. if (start_row < ptr->cur_start_row ||
  170603. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  170604. if (! ptr->b_s_open)
  170605. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  170606. /* Flush old buffer contents if necessary */
  170607. if (ptr->dirty) {
  170608. do_sarray_io(cinfo, ptr, TRUE);
  170609. ptr->dirty = FALSE;
  170610. }
  170611. /* Decide what part of virtual array to access.
  170612. * Algorithm: if target address > current window, assume forward scan,
  170613. * load starting at target address. If target address < current window,
  170614. * assume backward scan, load so that target area is top of window.
  170615. * Note that when switching from forward write to forward read, will have
  170616. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  170617. */
  170618. if (start_row > ptr->cur_start_row) {
  170619. ptr->cur_start_row = start_row;
  170620. } else {
  170621. /* use long arithmetic here to avoid overflow & unsigned problems */
  170622. long ltemp;
  170623. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  170624. if (ltemp < 0)
  170625. ltemp = 0; /* don't fall off front end of file */
  170626. ptr->cur_start_row = (JDIMENSION) ltemp;
  170627. }
  170628. /* Read in the selected part of the array.
  170629. * During the initial write pass, we will do no actual read
  170630. * because the selected part is all undefined.
  170631. */
  170632. do_sarray_io(cinfo, ptr, FALSE);
  170633. }
  170634. /* Ensure the accessed part of the array is defined; prezero if needed.
  170635. * To improve locality of access, we only prezero the part of the array
  170636. * that the caller is about to access, not the entire in-memory array.
  170637. */
  170638. if (ptr->first_undef_row < end_row) {
  170639. if (ptr->first_undef_row < start_row) {
  170640. if (writable) /* writer skipped over a section of array */
  170641. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170642. undef_row = start_row; /* but reader is allowed to read ahead */
  170643. } else {
  170644. undef_row = ptr->first_undef_row;
  170645. }
  170646. if (writable)
  170647. ptr->first_undef_row = end_row;
  170648. if (ptr->pre_zero) {
  170649. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  170650. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  170651. end_row -= ptr->cur_start_row;
  170652. while (undef_row < end_row) {
  170653. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  170654. undef_row++;
  170655. }
  170656. } else {
  170657. if (! writable) /* reader looking at undefined data */
  170658. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170659. }
  170660. }
  170661. /* Flag the buffer dirty if caller will write in it */
  170662. if (writable)
  170663. ptr->dirty = TRUE;
  170664. /* Return address of proper part of the buffer */
  170665. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  170666. }
  170667. METHODDEF(JBLOCKARRAY)
  170668. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  170669. JDIMENSION start_row, JDIMENSION num_rows,
  170670. boolean writable)
  170671. /* Access the part of a virtual block array starting at start_row */
  170672. /* and extending for num_rows rows. writable is true if */
  170673. /* caller intends to modify the accessed area. */
  170674. {
  170675. JDIMENSION end_row = start_row + num_rows;
  170676. JDIMENSION undef_row;
  170677. /* debugging check */
  170678. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  170679. ptr->mem_buffer == NULL)
  170680. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170681. /* Make the desired part of the virtual array accessible */
  170682. if (start_row < ptr->cur_start_row ||
  170683. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  170684. if (! ptr->b_s_open)
  170685. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  170686. /* Flush old buffer contents if necessary */
  170687. if (ptr->dirty) {
  170688. do_barray_io(cinfo, ptr, TRUE);
  170689. ptr->dirty = FALSE;
  170690. }
  170691. /* Decide what part of virtual array to access.
  170692. * Algorithm: if target address > current window, assume forward scan,
  170693. * load starting at target address. If target address < current window,
  170694. * assume backward scan, load so that target area is top of window.
  170695. * Note that when switching from forward write to forward read, will have
  170696. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  170697. */
  170698. if (start_row > ptr->cur_start_row) {
  170699. ptr->cur_start_row = start_row;
  170700. } else {
  170701. /* use long arithmetic here to avoid overflow & unsigned problems */
  170702. long ltemp;
  170703. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  170704. if (ltemp < 0)
  170705. ltemp = 0; /* don't fall off front end of file */
  170706. ptr->cur_start_row = (JDIMENSION) ltemp;
  170707. }
  170708. /* Read in the selected part of the array.
  170709. * During the initial write pass, we will do no actual read
  170710. * because the selected part is all undefined.
  170711. */
  170712. do_barray_io(cinfo, ptr, FALSE);
  170713. }
  170714. /* Ensure the accessed part of the array is defined; prezero if needed.
  170715. * To improve locality of access, we only prezero the part of the array
  170716. * that the caller is about to access, not the entire in-memory array.
  170717. */
  170718. if (ptr->first_undef_row < end_row) {
  170719. if (ptr->first_undef_row < start_row) {
  170720. if (writable) /* writer skipped over a section of array */
  170721. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170722. undef_row = start_row; /* but reader is allowed to read ahead */
  170723. } else {
  170724. undef_row = ptr->first_undef_row;
  170725. }
  170726. if (writable)
  170727. ptr->first_undef_row = end_row;
  170728. if (ptr->pre_zero) {
  170729. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  170730. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  170731. end_row -= ptr->cur_start_row;
  170732. while (undef_row < end_row) {
  170733. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  170734. undef_row++;
  170735. }
  170736. } else {
  170737. if (! writable) /* reader looking at undefined data */
  170738. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170739. }
  170740. }
  170741. /* Flag the buffer dirty if caller will write in it */
  170742. if (writable)
  170743. ptr->dirty = TRUE;
  170744. /* Return address of proper part of the buffer */
  170745. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  170746. }
  170747. /*
  170748. * Release all objects belonging to a specified pool.
  170749. */
  170750. METHODDEF(void)
  170751. free_pool (j_common_ptr cinfo, int pool_id)
  170752. {
  170753. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170754. small_pool_ptr shdr_ptr;
  170755. large_pool_ptr lhdr_ptr;
  170756. size_t space_freed;
  170757. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  170758. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  170759. #ifdef MEM_STATS
  170760. if (cinfo->err->trace_level > 1)
  170761. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  170762. #endif
  170763. /* If freeing IMAGE pool, close any virtual arrays first */
  170764. if (pool_id == JPOOL_IMAGE) {
  170765. jvirt_sarray_ptr sptr;
  170766. jvirt_barray_ptr bptr;
  170767. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  170768. if (sptr->b_s_open) { /* there may be no backing store */
  170769. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  170770. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  170771. }
  170772. }
  170773. mem->virt_sarray_list = NULL;
  170774. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  170775. if (bptr->b_s_open) { /* there may be no backing store */
  170776. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  170777. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  170778. }
  170779. }
  170780. mem->virt_barray_list = NULL;
  170781. }
  170782. /* Release large objects */
  170783. lhdr_ptr = mem->large_list[pool_id];
  170784. mem->large_list[pool_id] = NULL;
  170785. while (lhdr_ptr != NULL) {
  170786. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  170787. space_freed = lhdr_ptr->hdr.bytes_used +
  170788. lhdr_ptr->hdr.bytes_left +
  170789. SIZEOF(large_pool_hdr);
  170790. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  170791. mem->total_space_allocated -= space_freed;
  170792. lhdr_ptr = next_lhdr_ptr;
  170793. }
  170794. /* Release small objects */
  170795. shdr_ptr = mem->small_list[pool_id];
  170796. mem->small_list[pool_id] = NULL;
  170797. while (shdr_ptr != NULL) {
  170798. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  170799. space_freed = shdr_ptr->hdr.bytes_used +
  170800. shdr_ptr->hdr.bytes_left +
  170801. SIZEOF(small_pool_hdr);
  170802. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  170803. mem->total_space_allocated -= space_freed;
  170804. shdr_ptr = next_shdr_ptr;
  170805. }
  170806. }
  170807. /*
  170808. * Close up shop entirely.
  170809. * Note that this cannot be called unless cinfo->mem is non-NULL.
  170810. */
  170811. METHODDEF(void)
  170812. self_destruct (j_common_ptr cinfo)
  170813. {
  170814. int pool;
  170815. /* Close all backing store, release all memory.
  170816. * Releasing pools in reverse order might help avoid fragmentation
  170817. * with some (brain-damaged) malloc libraries.
  170818. */
  170819. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  170820. free_pool(cinfo, pool);
  170821. }
  170822. /* Release the memory manager control block too. */
  170823. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  170824. cinfo->mem = NULL; /* ensures I will be called only once */
  170825. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  170826. }
  170827. /*
  170828. * Memory manager initialization.
  170829. * When this is called, only the error manager pointer is valid in cinfo!
  170830. */
  170831. GLOBAL(void)
  170832. jinit_memory_mgr (j_common_ptr cinfo)
  170833. {
  170834. my_mem_ptr mem;
  170835. long max_to_use;
  170836. int pool;
  170837. size_t test_mac;
  170838. cinfo->mem = NULL; /* for safety if init fails */
  170839. /* Check for configuration errors.
  170840. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  170841. * doesn't reflect any real hardware alignment requirement.
  170842. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  170843. * in common if and only if X is a power of 2, ie has only one one-bit.
  170844. * Some compilers may give an "unreachable code" warning here; ignore it.
  170845. */
  170846. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  170847. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  170848. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  170849. * a multiple of SIZEOF(ALIGN_TYPE).
  170850. * Again, an "unreachable code" warning may be ignored here.
  170851. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  170852. */
  170853. test_mac = (size_t) MAX_ALLOC_CHUNK;
  170854. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  170855. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  170856. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  170857. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  170858. /* Attempt to allocate memory manager's control block */
  170859. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  170860. if (mem == NULL) {
  170861. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  170862. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  170863. }
  170864. /* OK, fill in the method pointers */
  170865. mem->pub.alloc_small = alloc_small;
  170866. mem->pub.alloc_large = alloc_large;
  170867. mem->pub.alloc_sarray = alloc_sarray;
  170868. mem->pub.alloc_barray = alloc_barray;
  170869. mem->pub.request_virt_sarray = request_virt_sarray;
  170870. mem->pub.request_virt_barray = request_virt_barray;
  170871. mem->pub.realize_virt_arrays = realize_virt_arrays;
  170872. mem->pub.access_virt_sarray = access_virt_sarray;
  170873. mem->pub.access_virt_barray = access_virt_barray;
  170874. mem->pub.free_pool = free_pool;
  170875. mem->pub.self_destruct = self_destruct;
  170876. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  170877. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  170878. /* Initialize working state */
  170879. mem->pub.max_memory_to_use = max_to_use;
  170880. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  170881. mem->small_list[pool] = NULL;
  170882. mem->large_list[pool] = NULL;
  170883. }
  170884. mem->virt_sarray_list = NULL;
  170885. mem->virt_barray_list = NULL;
  170886. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  170887. /* Declare ourselves open for business */
  170888. cinfo->mem = & mem->pub;
  170889. /* Check for an environment variable JPEGMEM; if found, override the
  170890. * default max_memory setting from jpeg_mem_init. Note that the
  170891. * surrounding application may again override this value.
  170892. * If your system doesn't support getenv(), define NO_GETENV to disable
  170893. * this feature.
  170894. */
  170895. #ifndef NO_GETENV
  170896. { char * memenv;
  170897. if ((memenv = getenv("JPEGMEM")) != NULL) {
  170898. char ch = 'x';
  170899. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  170900. if (ch == 'm' || ch == 'M')
  170901. max_to_use *= 1000L;
  170902. mem->pub.max_memory_to_use = max_to_use * 1000L;
  170903. }
  170904. }
  170905. }
  170906. #endif
  170907. }
  170908. /********* End of inlined file: jmemmgr.c *********/
  170909. /********* Start of inlined file: jmemnobs.c *********/
  170910. #define JPEG_INTERNALS
  170911. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  170912. extern void * malloc JPP((size_t size));
  170913. extern void free JPP((void *ptr));
  170914. #endif
  170915. /*
  170916. * Memory allocation and freeing are controlled by the regular library
  170917. * routines malloc() and free().
  170918. */
  170919. GLOBAL(void *)
  170920. jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
  170921. {
  170922. return (void *) malloc(sizeofobject);
  170923. }
  170924. GLOBAL(void)
  170925. jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
  170926. {
  170927. free(object);
  170928. }
  170929. /*
  170930. * "Large" objects are treated the same as "small" ones.
  170931. * NB: although we include FAR keywords in the routine declarations,
  170932. * this file won't actually work in 80x86 small/medium model; at least,
  170933. * you probably won't be able to process useful-size images in only 64KB.
  170934. */
  170935. GLOBAL(void FAR *)
  170936. jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
  170937. {
  170938. return (void FAR *) malloc(sizeofobject);
  170939. }
  170940. GLOBAL(void)
  170941. jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
  170942. {
  170943. free(object);
  170944. }
  170945. /*
  170946. * This routine computes the total memory space available for allocation.
  170947. * Here we always say, "we got all you want bud!"
  170948. */
  170949. GLOBAL(long)
  170950. jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
  170951. long max_bytes_needed, long already_allocated)
  170952. {
  170953. return max_bytes_needed;
  170954. }
  170955. /*
  170956. * Backing store (temporary file) management.
  170957. * Since jpeg_mem_available always promised the moon,
  170958. * this should never be called and we can just error out.
  170959. */
  170960. GLOBAL(void)
  170961. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *info,
  170962. long total_bytes_needed)
  170963. {
  170964. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  170965. }
  170966. /*
  170967. * These routines take care of any system-dependent initialization and
  170968. * cleanup required. Here, there isn't any.
  170969. */
  170970. GLOBAL(long)
  170971. jpeg_mem_init (j_common_ptr cinfo)
  170972. {
  170973. return 0; /* just set max_memory_to_use to 0 */
  170974. }
  170975. GLOBAL(void)
  170976. jpeg_mem_term (j_common_ptr cinfo)
  170977. {
  170978. /* no work */
  170979. }
  170980. /********* End of inlined file: jmemnobs.c *********/
  170981. /********* Start of inlined file: jquant1.c *********/
  170982. #define JPEG_INTERNALS
  170983. #ifdef QUANT_1PASS_SUPPORTED
  170984. /*
  170985. * The main purpose of 1-pass quantization is to provide a fast, if not very
  170986. * high quality, colormapped output capability. A 2-pass quantizer usually
  170987. * gives better visual quality; however, for quantized grayscale output this
  170988. * quantizer is perfectly adequate. Dithering is highly recommended with this
  170989. * quantizer, though you can turn it off if you really want to.
  170990. *
  170991. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  170992. * image. We use a map consisting of all combinations of Ncolors[i] color
  170993. * values for the i'th component. The Ncolors[] values are chosen so that
  170994. * their product, the total number of colors, is no more than that requested.
  170995. * (In most cases, the product will be somewhat less.)
  170996. *
  170997. * Since the colormap is orthogonal, the representative value for each color
  170998. * component can be determined without considering the other components;
  170999. * then these indexes can be combined into a colormap index by a standard
  171000. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  171001. * can be precalculated and stored in the lookup table colorindex[].
  171002. * colorindex[i][j] maps pixel value j in component i to the nearest
  171003. * representative value (grid plane) for that component; this index is
  171004. * multiplied by the array stride for component i, so that the
  171005. * index of the colormap entry closest to a given pixel value is just
  171006. * sum( colorindex[component-number][pixel-component-value] )
  171007. * Aside from being fast, this scheme allows for variable spacing between
  171008. * representative values with no additional lookup cost.
  171009. *
  171010. * If gamma correction has been applied in color conversion, it might be wise
  171011. * to adjust the color grid spacing so that the representative colors are
  171012. * equidistant in linear space. At this writing, gamma correction is not
  171013. * implemented by jdcolor, so nothing is done here.
  171014. */
  171015. /* Declarations for ordered dithering.
  171016. *
  171017. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  171018. * dithering is described in many references, for instance Dale Schumacher's
  171019. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  171020. * In place of Schumacher's comparisons against a "threshold" value, we add a
  171021. * "dither" value to the input pixel and then round the result to the nearest
  171022. * output value. The dither value is equivalent to (0.5 - threshold) times
  171023. * the distance between output values. For ordered dithering, we assume that
  171024. * the output colors are equally spaced; if not, results will probably be
  171025. * worse, since the dither may be too much or too little at a given point.
  171026. *
  171027. * The normal calculation would be to form pixel value + dither, range-limit
  171028. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  171029. * We can skip the separate range-limiting step by extending the colorindex
  171030. * table in both directions.
  171031. */
  171032. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  171033. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  171034. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  171035. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  171036. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  171037. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  171038. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  171039. /* Bayer's order-4 dither array. Generated by the code given in
  171040. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  171041. * The values in this array must range from 0 to ODITHER_CELLS-1.
  171042. */
  171043. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  171044. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  171045. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  171046. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  171047. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  171048. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  171049. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  171050. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  171051. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  171052. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  171053. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  171054. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  171055. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  171056. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  171057. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  171058. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  171059. };
  171060. /* Declarations for Floyd-Steinberg dithering.
  171061. *
  171062. * Errors are accumulated into the array fserrors[], at a resolution of
  171063. * 1/16th of a pixel count. The error at a given pixel is propagated
  171064. * to its not-yet-processed neighbors using the standard F-S fractions,
  171065. * ... (here) 7/16
  171066. * 3/16 5/16 1/16
  171067. * We work left-to-right on even rows, right-to-left on odd rows.
  171068. *
  171069. * We can get away with a single array (holding one row's worth of errors)
  171070. * by using it to store the current row's errors at pixel columns not yet
  171071. * processed, but the next row's errors at columns already processed. We
  171072. * need only a few extra variables to hold the errors immediately around the
  171073. * current column. (If we are lucky, those variables are in registers, but
  171074. * even if not, they're probably cheaper to access than array elements are.)
  171075. *
  171076. * The fserrors[] array is indexed [component#][position].
  171077. * We provide (#columns + 2) entries per component; the extra entry at each
  171078. * end saves us from special-casing the first and last pixels.
  171079. *
  171080. * Note: on a wide image, we might not have enough room in a PC's near data
  171081. * segment to hold the error array; so it is allocated with alloc_large.
  171082. */
  171083. #if BITS_IN_JSAMPLE == 8
  171084. typedef INT16 FSERROR; /* 16 bits should be enough */
  171085. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  171086. #else
  171087. typedef INT32 FSERROR; /* may need more than 16 bits */
  171088. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  171089. #endif
  171090. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  171091. /* Private subobject */
  171092. #define MAX_Q_COMPS 4 /* max components I can handle */
  171093. typedef struct {
  171094. struct jpeg_color_quantizer pub; /* public fields */
  171095. /* Initially allocated colormap is saved here */
  171096. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  171097. int sv_actual; /* number of entries in use */
  171098. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  171099. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  171100. * premultiplied as described above. Since colormap indexes must fit into
  171101. * JSAMPLEs, the entries of this array will too.
  171102. */
  171103. boolean is_padded; /* is the colorindex padded for odither? */
  171104. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  171105. /* Variables for ordered dithering */
  171106. int row_index; /* cur row's vertical index in dither matrix */
  171107. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  171108. /* Variables for Floyd-Steinberg dithering */
  171109. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  171110. boolean on_odd_row; /* flag to remember which row we are on */
  171111. } my_cquantizer;
  171112. typedef my_cquantizer * my_cquantize_ptr;
  171113. /*
  171114. * Policy-making subroutines for create_colormap and create_colorindex.
  171115. * These routines determine the colormap to be used. The rest of the module
  171116. * only assumes that the colormap is orthogonal.
  171117. *
  171118. * * select_ncolors decides how to divvy up the available colors
  171119. * among the components.
  171120. * * output_value defines the set of representative values for a component.
  171121. * * largest_input_value defines the mapping from input values to
  171122. * representative values for a component.
  171123. * Note that the latter two routines may impose different policies for
  171124. * different components, though this is not currently done.
  171125. */
  171126. LOCAL(int)
  171127. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  171128. /* Determine allocation of desired colors to components, */
  171129. /* and fill in Ncolors[] array to indicate choice. */
  171130. /* Return value is total number of colors (product of Ncolors[] values). */
  171131. {
  171132. int nc = cinfo->out_color_components; /* number of color components */
  171133. int max_colors = cinfo->desired_number_of_colors;
  171134. int total_colors, iroot, i, j;
  171135. boolean changed;
  171136. long temp;
  171137. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  171138. /* We can allocate at least the nc'th root of max_colors per component. */
  171139. /* Compute floor(nc'th root of max_colors). */
  171140. iroot = 1;
  171141. do {
  171142. iroot++;
  171143. temp = iroot; /* set temp = iroot ** nc */
  171144. for (i = 1; i < nc; i++)
  171145. temp *= iroot;
  171146. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  171147. iroot--; /* now iroot = floor(root) */
  171148. /* Must have at least 2 color values per component */
  171149. if (iroot < 2)
  171150. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  171151. /* Initialize to iroot color values for each component */
  171152. total_colors = 1;
  171153. for (i = 0; i < nc; i++) {
  171154. Ncolors[i] = iroot;
  171155. total_colors *= iroot;
  171156. }
  171157. /* We may be able to increment the count for one or more components without
  171158. * exceeding max_colors, though we know not all can be incremented.
  171159. * Sometimes, the first component can be incremented more than once!
  171160. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  171161. * In RGB colorspace, try to increment G first, then R, then B.
  171162. */
  171163. do {
  171164. changed = FALSE;
  171165. for (i = 0; i < nc; i++) {
  171166. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  171167. /* calculate new total_colors if Ncolors[j] is incremented */
  171168. temp = total_colors / Ncolors[j];
  171169. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  171170. if (temp > (long) max_colors)
  171171. break; /* won't fit, done with this pass */
  171172. Ncolors[j]++; /* OK, apply the increment */
  171173. total_colors = (int) temp;
  171174. changed = TRUE;
  171175. }
  171176. } while (changed);
  171177. return total_colors;
  171178. }
  171179. LOCAL(int)
  171180. output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  171181. /* Return j'th output value, where j will range from 0 to maxj */
  171182. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  171183. {
  171184. /* We always provide values 0 and MAXJSAMPLE for each component;
  171185. * any additional values are equally spaced between these limits.
  171186. * (Forcing the upper and lower values to the limits ensures that
  171187. * dithering can't produce a color outside the selected gamut.)
  171188. */
  171189. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  171190. }
  171191. LOCAL(int)
  171192. largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  171193. /* Return largest input value that should map to j'th output value */
  171194. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  171195. {
  171196. /* Breakpoints are halfway between values returned by output_value */
  171197. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  171198. }
  171199. /*
  171200. * Create the colormap.
  171201. */
  171202. LOCAL(void)
  171203. create_colormap (j_decompress_ptr cinfo)
  171204. {
  171205. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171206. JSAMPARRAY colormap; /* Created colormap */
  171207. int total_colors; /* Number of distinct output colors */
  171208. int i,j,k, nci, blksize, blkdist, ptr, val;
  171209. /* Select number of colors for each component */
  171210. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  171211. /* Report selected color counts */
  171212. if (cinfo->out_color_components == 3)
  171213. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  171214. total_colors, cquantize->Ncolors[0],
  171215. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  171216. else
  171217. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  171218. /* Allocate and fill in the colormap. */
  171219. /* The colors are ordered in the map in standard row-major order, */
  171220. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  171221. colormap = (*cinfo->mem->alloc_sarray)
  171222. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171223. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  171224. /* blksize is number of adjacent repeated entries for a component */
  171225. /* blkdist is distance between groups of identical entries for a component */
  171226. blkdist = total_colors;
  171227. for (i = 0; i < cinfo->out_color_components; i++) {
  171228. /* fill in colormap entries for i'th color component */
  171229. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  171230. blksize = blkdist / nci;
  171231. for (j = 0; j < nci; j++) {
  171232. /* Compute j'th output value (out of nci) for component */
  171233. val = output_value(cinfo, i, j, nci-1);
  171234. /* Fill in all colormap entries that have this value of this component */
  171235. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  171236. /* fill in blksize entries beginning at ptr */
  171237. for (k = 0; k < blksize; k++)
  171238. colormap[i][ptr+k] = (JSAMPLE) val;
  171239. }
  171240. }
  171241. blkdist = blksize; /* blksize of this color is blkdist of next */
  171242. }
  171243. /* Save the colormap in private storage,
  171244. * where it will survive color quantization mode changes.
  171245. */
  171246. cquantize->sv_colormap = colormap;
  171247. cquantize->sv_actual = total_colors;
  171248. }
  171249. /*
  171250. * Create the color index table.
  171251. */
  171252. LOCAL(void)
  171253. create_colorindex (j_decompress_ptr cinfo)
  171254. {
  171255. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171256. JSAMPROW indexptr;
  171257. int i,j,k, nci, blksize, val, pad;
  171258. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  171259. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  171260. * This is not necessary in the other dithering modes. However, we
  171261. * flag whether it was done in case user changes dithering mode.
  171262. */
  171263. if (cinfo->dither_mode == JDITHER_ORDERED) {
  171264. pad = MAXJSAMPLE*2;
  171265. cquantize->is_padded = TRUE;
  171266. } else {
  171267. pad = 0;
  171268. cquantize->is_padded = FALSE;
  171269. }
  171270. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  171271. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171272. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  171273. (JDIMENSION) cinfo->out_color_components);
  171274. /* blksize is number of adjacent repeated entries for a component */
  171275. blksize = cquantize->sv_actual;
  171276. for (i = 0; i < cinfo->out_color_components; i++) {
  171277. /* fill in colorindex entries for i'th color component */
  171278. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  171279. blksize = blksize / nci;
  171280. /* adjust colorindex pointers to provide padding at negative indexes. */
  171281. if (pad)
  171282. cquantize->colorindex[i] += MAXJSAMPLE;
  171283. /* in loop, val = index of current output value, */
  171284. /* and k = largest j that maps to current val */
  171285. indexptr = cquantize->colorindex[i];
  171286. val = 0;
  171287. k = largest_input_value(cinfo, i, 0, nci-1);
  171288. for (j = 0; j <= MAXJSAMPLE; j++) {
  171289. while (j > k) /* advance val if past boundary */
  171290. k = largest_input_value(cinfo, i, ++val, nci-1);
  171291. /* premultiply so that no multiplication needed in main processing */
  171292. indexptr[j] = (JSAMPLE) (val * blksize);
  171293. }
  171294. /* Pad at both ends if necessary */
  171295. if (pad)
  171296. for (j = 1; j <= MAXJSAMPLE; j++) {
  171297. indexptr[-j] = indexptr[0];
  171298. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  171299. }
  171300. }
  171301. }
  171302. /*
  171303. * Create an ordered-dither array for a component having ncolors
  171304. * distinct output values.
  171305. */
  171306. LOCAL(ODITHER_MATRIX_PTR)
  171307. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  171308. {
  171309. ODITHER_MATRIX_PTR odither;
  171310. int j,k;
  171311. INT32 num,den;
  171312. odither = (ODITHER_MATRIX_PTR)
  171313. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171314. SIZEOF(ODITHER_MATRIX));
  171315. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  171316. * Hence the dither value for the matrix cell with fill order f
  171317. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  171318. * On 16-bit-int machine, be careful to avoid overflow.
  171319. */
  171320. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  171321. for (j = 0; j < ODITHER_SIZE; j++) {
  171322. for (k = 0; k < ODITHER_SIZE; k++) {
  171323. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  171324. * MAXJSAMPLE;
  171325. /* Ensure round towards zero despite C's lack of consistency
  171326. * about rounding negative values in integer division...
  171327. */
  171328. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  171329. }
  171330. }
  171331. return odither;
  171332. }
  171333. /*
  171334. * Create the ordered-dither tables.
  171335. * Components having the same number of representative colors may
  171336. * share a dither table.
  171337. */
  171338. LOCAL(void)
  171339. create_odither_tables (j_decompress_ptr cinfo)
  171340. {
  171341. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171342. ODITHER_MATRIX_PTR odither;
  171343. int i, j, nci;
  171344. for (i = 0; i < cinfo->out_color_components; i++) {
  171345. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  171346. odither = NULL; /* search for matching prior component */
  171347. for (j = 0; j < i; j++) {
  171348. if (nci == cquantize->Ncolors[j]) {
  171349. odither = cquantize->odither[j];
  171350. break;
  171351. }
  171352. }
  171353. if (odither == NULL) /* need a new table? */
  171354. odither = make_odither_array(cinfo, nci);
  171355. cquantize->odither[i] = odither;
  171356. }
  171357. }
  171358. /*
  171359. * Map some rows of pixels to the output colormapped representation.
  171360. */
  171361. METHODDEF(void)
  171362. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171363. JSAMPARRAY output_buf, int num_rows)
  171364. /* General case, no dithering */
  171365. {
  171366. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171367. JSAMPARRAY colorindex = cquantize->colorindex;
  171368. register int pixcode, ci;
  171369. register JSAMPROW ptrin, ptrout;
  171370. int row;
  171371. JDIMENSION col;
  171372. JDIMENSION width = cinfo->output_width;
  171373. register int nc = cinfo->out_color_components;
  171374. for (row = 0; row < num_rows; row++) {
  171375. ptrin = input_buf[row];
  171376. ptrout = output_buf[row];
  171377. for (col = width; col > 0; col--) {
  171378. pixcode = 0;
  171379. for (ci = 0; ci < nc; ci++) {
  171380. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  171381. }
  171382. *ptrout++ = (JSAMPLE) pixcode;
  171383. }
  171384. }
  171385. }
  171386. METHODDEF(void)
  171387. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171388. JSAMPARRAY output_buf, int num_rows)
  171389. /* Fast path for out_color_components==3, no dithering */
  171390. {
  171391. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171392. register int pixcode;
  171393. register JSAMPROW ptrin, ptrout;
  171394. JSAMPROW colorindex0 = cquantize->colorindex[0];
  171395. JSAMPROW colorindex1 = cquantize->colorindex[1];
  171396. JSAMPROW colorindex2 = cquantize->colorindex[2];
  171397. int row;
  171398. JDIMENSION col;
  171399. JDIMENSION width = cinfo->output_width;
  171400. for (row = 0; row < num_rows; row++) {
  171401. ptrin = input_buf[row];
  171402. ptrout = output_buf[row];
  171403. for (col = width; col > 0; col--) {
  171404. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  171405. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  171406. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  171407. *ptrout++ = (JSAMPLE) pixcode;
  171408. }
  171409. }
  171410. }
  171411. METHODDEF(void)
  171412. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171413. JSAMPARRAY output_buf, int num_rows)
  171414. /* General case, with ordered dithering */
  171415. {
  171416. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171417. register JSAMPROW input_ptr;
  171418. register JSAMPROW output_ptr;
  171419. JSAMPROW colorindex_ci;
  171420. int * dither; /* points to active row of dither matrix */
  171421. int row_index, col_index; /* current indexes into dither matrix */
  171422. int nc = cinfo->out_color_components;
  171423. int ci;
  171424. int row;
  171425. JDIMENSION col;
  171426. JDIMENSION width = cinfo->output_width;
  171427. for (row = 0; row < num_rows; row++) {
  171428. /* Initialize output values to 0 so can process components separately */
  171429. jzero_far((void FAR *) output_buf[row],
  171430. (size_t) (width * SIZEOF(JSAMPLE)));
  171431. row_index = cquantize->row_index;
  171432. for (ci = 0; ci < nc; ci++) {
  171433. input_ptr = input_buf[row] + ci;
  171434. output_ptr = output_buf[row];
  171435. colorindex_ci = cquantize->colorindex[ci];
  171436. dither = cquantize->odither[ci][row_index];
  171437. col_index = 0;
  171438. for (col = width; col > 0; col--) {
  171439. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  171440. * select output value, accumulate into output code for this pixel.
  171441. * Range-limiting need not be done explicitly, as we have extended
  171442. * the colorindex table to produce the right answers for out-of-range
  171443. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  171444. * required amount of padding.
  171445. */
  171446. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  171447. input_ptr += nc;
  171448. output_ptr++;
  171449. col_index = (col_index + 1) & ODITHER_MASK;
  171450. }
  171451. }
  171452. /* Advance row index for next row */
  171453. row_index = (row_index + 1) & ODITHER_MASK;
  171454. cquantize->row_index = row_index;
  171455. }
  171456. }
  171457. METHODDEF(void)
  171458. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171459. JSAMPARRAY output_buf, int num_rows)
  171460. /* Fast path for out_color_components==3, with ordered dithering */
  171461. {
  171462. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171463. register int pixcode;
  171464. register JSAMPROW input_ptr;
  171465. register JSAMPROW output_ptr;
  171466. JSAMPROW colorindex0 = cquantize->colorindex[0];
  171467. JSAMPROW colorindex1 = cquantize->colorindex[1];
  171468. JSAMPROW colorindex2 = cquantize->colorindex[2];
  171469. int * dither0; /* points to active row of dither matrix */
  171470. int * dither1;
  171471. int * dither2;
  171472. int row_index, col_index; /* current indexes into dither matrix */
  171473. int row;
  171474. JDIMENSION col;
  171475. JDIMENSION width = cinfo->output_width;
  171476. for (row = 0; row < num_rows; row++) {
  171477. row_index = cquantize->row_index;
  171478. input_ptr = input_buf[row];
  171479. output_ptr = output_buf[row];
  171480. dither0 = cquantize->odither[0][row_index];
  171481. dither1 = cquantize->odither[1][row_index];
  171482. dither2 = cquantize->odither[2][row_index];
  171483. col_index = 0;
  171484. for (col = width; col > 0; col--) {
  171485. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  171486. dither0[col_index]]);
  171487. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  171488. dither1[col_index]]);
  171489. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  171490. dither2[col_index]]);
  171491. *output_ptr++ = (JSAMPLE) pixcode;
  171492. col_index = (col_index + 1) & ODITHER_MASK;
  171493. }
  171494. row_index = (row_index + 1) & ODITHER_MASK;
  171495. cquantize->row_index = row_index;
  171496. }
  171497. }
  171498. METHODDEF(void)
  171499. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171500. JSAMPARRAY output_buf, int num_rows)
  171501. /* General case, with Floyd-Steinberg dithering */
  171502. {
  171503. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171504. register LOCFSERROR cur; /* current error or pixel value */
  171505. LOCFSERROR belowerr; /* error for pixel below cur */
  171506. LOCFSERROR bpreverr; /* error for below/prev col */
  171507. LOCFSERROR bnexterr; /* error for below/next col */
  171508. LOCFSERROR delta;
  171509. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  171510. register JSAMPROW input_ptr;
  171511. register JSAMPROW output_ptr;
  171512. JSAMPROW colorindex_ci;
  171513. JSAMPROW colormap_ci;
  171514. int pixcode;
  171515. int nc = cinfo->out_color_components;
  171516. int dir; /* 1 for left-to-right, -1 for right-to-left */
  171517. int dirnc; /* dir * nc */
  171518. int ci;
  171519. int row;
  171520. JDIMENSION col;
  171521. JDIMENSION width = cinfo->output_width;
  171522. JSAMPLE *range_limit = cinfo->sample_range_limit;
  171523. SHIFT_TEMPS
  171524. for (row = 0; row < num_rows; row++) {
  171525. /* Initialize output values to 0 so can process components separately */
  171526. jzero_far((void FAR *) output_buf[row],
  171527. (size_t) (width * SIZEOF(JSAMPLE)));
  171528. for (ci = 0; ci < nc; ci++) {
  171529. input_ptr = input_buf[row] + ci;
  171530. output_ptr = output_buf[row];
  171531. if (cquantize->on_odd_row) {
  171532. /* work right to left in this row */
  171533. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  171534. output_ptr += width-1;
  171535. dir = -1;
  171536. dirnc = -nc;
  171537. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  171538. } else {
  171539. /* work left to right in this row */
  171540. dir = 1;
  171541. dirnc = nc;
  171542. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  171543. }
  171544. colorindex_ci = cquantize->colorindex[ci];
  171545. colormap_ci = cquantize->sv_colormap[ci];
  171546. /* Preset error values: no error propagated to first pixel from left */
  171547. cur = 0;
  171548. /* and no error propagated to row below yet */
  171549. belowerr = bpreverr = 0;
  171550. for (col = width; col > 0; col--) {
  171551. /* cur holds the error propagated from the previous pixel on the
  171552. * current line. Add the error propagated from the previous line
  171553. * to form the complete error correction term for this pixel, and
  171554. * round the error term (which is expressed * 16) to an integer.
  171555. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  171556. * for either sign of the error value.
  171557. * Note: errorptr points to *previous* column's array entry.
  171558. */
  171559. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  171560. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  171561. * The maximum error is +- MAXJSAMPLE; this sets the required size
  171562. * of the range_limit array.
  171563. */
  171564. cur += GETJSAMPLE(*input_ptr);
  171565. cur = GETJSAMPLE(range_limit[cur]);
  171566. /* Select output value, accumulate into output code for this pixel */
  171567. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  171568. *output_ptr += (JSAMPLE) pixcode;
  171569. /* Compute actual representation error at this pixel */
  171570. /* Note: we can do this even though we don't have the final */
  171571. /* pixel code, because the colormap is orthogonal. */
  171572. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  171573. /* Compute error fractions to be propagated to adjacent pixels.
  171574. * Add these into the running sums, and simultaneously shift the
  171575. * next-line error sums left by 1 column.
  171576. */
  171577. bnexterr = cur;
  171578. delta = cur * 2;
  171579. cur += delta; /* form error * 3 */
  171580. errorptr[0] = (FSERROR) (bpreverr + cur);
  171581. cur += delta; /* form error * 5 */
  171582. bpreverr = belowerr + cur;
  171583. belowerr = bnexterr;
  171584. cur += delta; /* form error * 7 */
  171585. /* At this point cur contains the 7/16 error value to be propagated
  171586. * to the next pixel on the current line, and all the errors for the
  171587. * next line have been shifted over. We are therefore ready to move on.
  171588. */
  171589. input_ptr += dirnc; /* advance input ptr to next column */
  171590. output_ptr += dir; /* advance output ptr to next column */
  171591. errorptr += dir; /* advance errorptr to current column */
  171592. }
  171593. /* Post-loop cleanup: we must unload the final error value into the
  171594. * final fserrors[] entry. Note we need not unload belowerr because
  171595. * it is for the dummy column before or after the actual array.
  171596. */
  171597. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  171598. }
  171599. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  171600. }
  171601. }
  171602. /*
  171603. * Allocate workspace for Floyd-Steinberg errors.
  171604. */
  171605. LOCAL(void)
  171606. alloc_fs_workspace (j_decompress_ptr cinfo)
  171607. {
  171608. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171609. size_t arraysize;
  171610. int i;
  171611. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  171612. for (i = 0; i < cinfo->out_color_components; i++) {
  171613. cquantize->fserrors[i] = (FSERRPTR)
  171614. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  171615. }
  171616. }
  171617. /*
  171618. * Initialize for one-pass color quantization.
  171619. */
  171620. METHODDEF(void)
  171621. start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  171622. {
  171623. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171624. size_t arraysize;
  171625. int i;
  171626. /* Install my colormap. */
  171627. cinfo->colormap = cquantize->sv_colormap;
  171628. cinfo->actual_number_of_colors = cquantize->sv_actual;
  171629. /* Initialize for desired dithering mode. */
  171630. switch (cinfo->dither_mode) {
  171631. case JDITHER_NONE:
  171632. if (cinfo->out_color_components == 3)
  171633. cquantize->pub.color_quantize = color_quantize3;
  171634. else
  171635. cquantize->pub.color_quantize = color_quantize;
  171636. break;
  171637. case JDITHER_ORDERED:
  171638. if (cinfo->out_color_components == 3)
  171639. cquantize->pub.color_quantize = quantize3_ord_dither;
  171640. else
  171641. cquantize->pub.color_quantize = quantize_ord_dither;
  171642. cquantize->row_index = 0; /* initialize state for ordered dither */
  171643. /* If user changed to ordered dither from another mode,
  171644. * we must recreate the color index table with padding.
  171645. * This will cost extra space, but probably isn't very likely.
  171646. */
  171647. if (! cquantize->is_padded)
  171648. create_colorindex(cinfo);
  171649. /* Create ordered-dither tables if we didn't already. */
  171650. if (cquantize->odither[0] == NULL)
  171651. create_odither_tables(cinfo);
  171652. break;
  171653. case JDITHER_FS:
  171654. cquantize->pub.color_quantize = quantize_fs_dither;
  171655. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  171656. /* Allocate Floyd-Steinberg workspace if didn't already. */
  171657. if (cquantize->fserrors[0] == NULL)
  171658. alloc_fs_workspace(cinfo);
  171659. /* Initialize the propagated errors to zero. */
  171660. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  171661. for (i = 0; i < cinfo->out_color_components; i++)
  171662. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  171663. break;
  171664. default:
  171665. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171666. break;
  171667. }
  171668. }
  171669. /*
  171670. * Finish up at the end of the pass.
  171671. */
  171672. METHODDEF(void)
  171673. finish_pass_1_quant (j_decompress_ptr cinfo)
  171674. {
  171675. /* no work in 1-pass case */
  171676. }
  171677. /*
  171678. * Switch to a new external colormap between output passes.
  171679. * Shouldn't get to this module!
  171680. */
  171681. METHODDEF(void)
  171682. new_color_map_1_quant (j_decompress_ptr cinfo)
  171683. {
  171684. ERREXIT(cinfo, JERR_MODE_CHANGE);
  171685. }
  171686. /*
  171687. * Module initialization routine for 1-pass color quantization.
  171688. */
  171689. GLOBAL(void)
  171690. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  171691. {
  171692. my_cquantize_ptr cquantize;
  171693. cquantize = (my_cquantize_ptr)
  171694. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171695. SIZEOF(my_cquantizer));
  171696. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  171697. cquantize->pub.start_pass = start_pass_1_quant;
  171698. cquantize->pub.finish_pass = finish_pass_1_quant;
  171699. cquantize->pub.new_color_map = new_color_map_1_quant;
  171700. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  171701. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  171702. /* Make sure my internal arrays won't overflow */
  171703. if (cinfo->out_color_components > MAX_Q_COMPS)
  171704. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  171705. /* Make sure colormap indexes can be represented by JSAMPLEs */
  171706. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  171707. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  171708. /* Create the colormap and color index table. */
  171709. create_colormap(cinfo);
  171710. create_colorindex(cinfo);
  171711. /* Allocate Floyd-Steinberg workspace now if requested.
  171712. * We do this now since it is FAR storage and may affect the memory
  171713. * manager's space calculations. If the user changes to FS dither
  171714. * mode in a later pass, we will allocate the space then, and will
  171715. * possibly overrun the max_memory_to_use setting.
  171716. */
  171717. if (cinfo->dither_mode == JDITHER_FS)
  171718. alloc_fs_workspace(cinfo);
  171719. }
  171720. #endif /* QUANT_1PASS_SUPPORTED */
  171721. /********* End of inlined file: jquant1.c *********/
  171722. /********* Start of inlined file: jquant2.c *********/
  171723. #define JPEG_INTERNALS
  171724. #ifdef QUANT_2PASS_SUPPORTED
  171725. /*
  171726. * This module implements the well-known Heckbert paradigm for color
  171727. * quantization. Most of the ideas used here can be traced back to
  171728. * Heckbert's seminal paper
  171729. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  171730. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  171731. *
  171732. * In the first pass over the image, we accumulate a histogram showing the
  171733. * usage count of each possible color. To keep the histogram to a reasonable
  171734. * size, we reduce the precision of the input; typical practice is to retain
  171735. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  171736. * in the same histogram cell.
  171737. *
  171738. * Next, the color-selection step begins with a box representing the whole
  171739. * color space, and repeatedly splits the "largest" remaining box until we
  171740. * have as many boxes as desired colors. Then the mean color in each
  171741. * remaining box becomes one of the possible output colors.
  171742. *
  171743. * The second pass over the image maps each input pixel to the closest output
  171744. * color (optionally after applying a Floyd-Steinberg dithering correction).
  171745. * This mapping is logically trivial, but making it go fast enough requires
  171746. * considerable care.
  171747. *
  171748. * Heckbert-style quantizers vary a good deal in their policies for choosing
  171749. * the "largest" box and deciding where to cut it. The particular policies
  171750. * used here have proved out well in experimental comparisons, but better ones
  171751. * may yet be found.
  171752. *
  171753. * In earlier versions of the IJG code, this module quantized in YCbCr color
  171754. * space, processing the raw upsampled data without a color conversion step.
  171755. * This allowed the color conversion math to be done only once per colormap
  171756. * entry, not once per pixel. However, that optimization precluded other
  171757. * useful optimizations (such as merging color conversion with upsampling)
  171758. * and it also interfered with desired capabilities such as quantizing to an
  171759. * externally-supplied colormap. We have therefore abandoned that approach.
  171760. * The present code works in the post-conversion color space, typically RGB.
  171761. *
  171762. * To improve the visual quality of the results, we actually work in scaled
  171763. * RGB space, giving G distances more weight than R, and R in turn more than
  171764. * B. To do everything in integer math, we must use integer scale factors.
  171765. * The 2/3/1 scale factors used here correspond loosely to the relative
  171766. * weights of the colors in the NTSC grayscale equation.
  171767. * If you want to use this code to quantize a non-RGB color space, you'll
  171768. * probably need to change these scale factors.
  171769. */
  171770. #define R_SCALE 2 /* scale R distances by this much */
  171771. #define G_SCALE 3 /* scale G distances by this much */
  171772. #define B_SCALE 1 /* and B by this much */
  171773. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  171774. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  171775. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  171776. * you'll get compile errors until you extend this logic. In that case
  171777. * you'll probably want to tweak the histogram sizes too.
  171778. */
  171779. #if RGB_RED == 0
  171780. #define C0_SCALE R_SCALE
  171781. #endif
  171782. #if RGB_BLUE == 0
  171783. #define C0_SCALE B_SCALE
  171784. #endif
  171785. #if RGB_GREEN == 1
  171786. #define C1_SCALE G_SCALE
  171787. #endif
  171788. #if RGB_RED == 2
  171789. #define C2_SCALE R_SCALE
  171790. #endif
  171791. #if RGB_BLUE == 2
  171792. #define C2_SCALE B_SCALE
  171793. #endif
  171794. /*
  171795. * First we have the histogram data structure and routines for creating it.
  171796. *
  171797. * The number of bits of precision can be adjusted by changing these symbols.
  171798. * We recommend keeping 6 bits for G and 5 each for R and B.
  171799. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  171800. * better results; if you are short of memory, 5 bits all around will save
  171801. * some space but degrade the results.
  171802. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  171803. * (preferably unsigned long) for each cell. In practice this is overkill;
  171804. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  171805. * and clamping those that do overflow to the maximum value will give close-
  171806. * enough results. This reduces the recommended histogram size from 256Kb
  171807. * to 128Kb, which is a useful savings on PC-class machines.
  171808. * (In the second pass the histogram space is re-used for pixel mapping data;
  171809. * in that capacity, each cell must be able to store zero to the number of
  171810. * desired colors. 16 bits/cell is plenty for that too.)
  171811. * Since the JPEG code is intended to run in small memory model on 80x86
  171812. * machines, we can't just allocate the histogram in one chunk. Instead
  171813. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  171814. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  171815. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  171816. * on 80x86 machines, the pointer row is in near memory but the actual
  171817. * arrays are in far memory (same arrangement as we use for image arrays).
  171818. */
  171819. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  171820. /* These will do the right thing for either R,G,B or B,G,R color order,
  171821. * but you may not like the results for other color orders.
  171822. */
  171823. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  171824. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  171825. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  171826. /* Number of elements along histogram axes. */
  171827. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  171828. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  171829. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  171830. /* These are the amounts to shift an input value to get a histogram index. */
  171831. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  171832. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  171833. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  171834. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  171835. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  171836. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  171837. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  171838. typedef hist2d * hist3d; /* type for top-level pointer */
  171839. /* Declarations for Floyd-Steinberg dithering.
  171840. *
  171841. * Errors are accumulated into the array fserrors[], at a resolution of
  171842. * 1/16th of a pixel count. The error at a given pixel is propagated
  171843. * to its not-yet-processed neighbors using the standard F-S fractions,
  171844. * ... (here) 7/16
  171845. * 3/16 5/16 1/16
  171846. * We work left-to-right on even rows, right-to-left on odd rows.
  171847. *
  171848. * We can get away with a single array (holding one row's worth of errors)
  171849. * by using it to store the current row's errors at pixel columns not yet
  171850. * processed, but the next row's errors at columns already processed. We
  171851. * need only a few extra variables to hold the errors immediately around the
  171852. * current column. (If we are lucky, those variables are in registers, but
  171853. * even if not, they're probably cheaper to access than array elements are.)
  171854. *
  171855. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  171856. * each end saves us from special-casing the first and last pixels.
  171857. * Each entry is three values long, one value for each color component.
  171858. *
  171859. * Note: on a wide image, we might not have enough room in a PC's near data
  171860. * segment to hold the error array; so it is allocated with alloc_large.
  171861. */
  171862. #if BITS_IN_JSAMPLE == 8
  171863. typedef INT16 FSERROR; /* 16 bits should be enough */
  171864. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  171865. #else
  171866. typedef INT32 FSERROR; /* may need more than 16 bits */
  171867. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  171868. #endif
  171869. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  171870. /* Private subobject */
  171871. typedef struct {
  171872. struct jpeg_color_quantizer pub; /* public fields */
  171873. /* Space for the eventually created colormap is stashed here */
  171874. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  171875. int desired; /* desired # of colors = size of colormap */
  171876. /* Variables for accumulating image statistics */
  171877. hist3d histogram; /* pointer to the histogram */
  171878. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  171879. /* Variables for Floyd-Steinberg dithering */
  171880. FSERRPTR fserrors; /* accumulated errors */
  171881. boolean on_odd_row; /* flag to remember which row we are on */
  171882. int * error_limiter; /* table for clamping the applied error */
  171883. } my_cquantizer2;
  171884. typedef my_cquantizer2 * my_cquantize_ptr2;
  171885. /*
  171886. * Prescan some rows of pixels.
  171887. * In this module the prescan simply updates the histogram, which has been
  171888. * initialized to zeroes by start_pass.
  171889. * An output_buf parameter is required by the method signature, but no data
  171890. * is actually output (in fact the buffer controller is probably passing a
  171891. * NULL pointer).
  171892. */
  171893. METHODDEF(void)
  171894. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171895. JSAMPARRAY output_buf, int num_rows)
  171896. {
  171897. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  171898. register JSAMPROW ptr;
  171899. register histptr histp;
  171900. register hist3d histogram = cquantize->histogram;
  171901. int row;
  171902. JDIMENSION col;
  171903. JDIMENSION width = cinfo->output_width;
  171904. for (row = 0; row < num_rows; row++) {
  171905. ptr = input_buf[row];
  171906. for (col = width; col > 0; col--) {
  171907. /* get pixel value and index into the histogram */
  171908. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  171909. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  171910. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  171911. /* increment, check for overflow and undo increment if so. */
  171912. if (++(*histp) <= 0)
  171913. (*histp)--;
  171914. ptr += 3;
  171915. }
  171916. }
  171917. }
  171918. /*
  171919. * Next we have the really interesting routines: selection of a colormap
  171920. * given the completed histogram.
  171921. * These routines work with a list of "boxes", each representing a rectangular
  171922. * subset of the input color space (to histogram precision).
  171923. */
  171924. typedef struct {
  171925. /* The bounds of the box (inclusive); expressed as histogram indexes */
  171926. int c0min, c0max;
  171927. int c1min, c1max;
  171928. int c2min, c2max;
  171929. /* The volume (actually 2-norm) of the box */
  171930. INT32 volume;
  171931. /* The number of nonzero histogram cells within this box */
  171932. long colorcount;
  171933. } box;
  171934. typedef box * boxptr;
  171935. LOCAL(boxptr)
  171936. find_biggest_color_pop (boxptr boxlist, int numboxes)
  171937. /* Find the splittable box with the largest color population */
  171938. /* Returns NULL if no splittable boxes remain */
  171939. {
  171940. register boxptr boxp;
  171941. register int i;
  171942. register long maxc = 0;
  171943. boxptr which = NULL;
  171944. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  171945. if (boxp->colorcount > maxc && boxp->volume > 0) {
  171946. which = boxp;
  171947. maxc = boxp->colorcount;
  171948. }
  171949. }
  171950. return which;
  171951. }
  171952. LOCAL(boxptr)
  171953. find_biggest_volume (boxptr boxlist, int numboxes)
  171954. /* Find the splittable box with the largest (scaled) volume */
  171955. /* Returns NULL if no splittable boxes remain */
  171956. {
  171957. register boxptr boxp;
  171958. register int i;
  171959. register INT32 maxv = 0;
  171960. boxptr which = NULL;
  171961. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  171962. if (boxp->volume > maxv) {
  171963. which = boxp;
  171964. maxv = boxp->volume;
  171965. }
  171966. }
  171967. return which;
  171968. }
  171969. LOCAL(void)
  171970. update_box (j_decompress_ptr cinfo, boxptr boxp)
  171971. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  171972. /* and recompute its volume and population */
  171973. {
  171974. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  171975. hist3d histogram = cquantize->histogram;
  171976. histptr histp;
  171977. int c0,c1,c2;
  171978. int c0min,c0max,c1min,c1max,c2min,c2max;
  171979. INT32 dist0,dist1,dist2;
  171980. long ccount;
  171981. c0min = boxp->c0min; c0max = boxp->c0max;
  171982. c1min = boxp->c1min; c1max = boxp->c1max;
  171983. c2min = boxp->c2min; c2max = boxp->c2max;
  171984. if (c0max > c0min)
  171985. for (c0 = c0min; c0 <= c0max; c0++)
  171986. for (c1 = c1min; c1 <= c1max; c1++) {
  171987. histp = & histogram[c0][c1][c2min];
  171988. for (c2 = c2min; c2 <= c2max; c2++)
  171989. if (*histp++ != 0) {
  171990. boxp->c0min = c0min = c0;
  171991. goto have_c0min;
  171992. }
  171993. }
  171994. have_c0min:
  171995. if (c0max > c0min)
  171996. for (c0 = c0max; c0 >= c0min; c0--)
  171997. for (c1 = c1min; c1 <= c1max; c1++) {
  171998. histp = & histogram[c0][c1][c2min];
  171999. for (c2 = c2min; c2 <= c2max; c2++)
  172000. if (*histp++ != 0) {
  172001. boxp->c0max = c0max = c0;
  172002. goto have_c0max;
  172003. }
  172004. }
  172005. have_c0max:
  172006. if (c1max > c1min)
  172007. for (c1 = c1min; c1 <= c1max; c1++)
  172008. for (c0 = c0min; c0 <= c0max; c0++) {
  172009. histp = & histogram[c0][c1][c2min];
  172010. for (c2 = c2min; c2 <= c2max; c2++)
  172011. if (*histp++ != 0) {
  172012. boxp->c1min = c1min = c1;
  172013. goto have_c1min;
  172014. }
  172015. }
  172016. have_c1min:
  172017. if (c1max > c1min)
  172018. for (c1 = c1max; c1 >= c1min; c1--)
  172019. for (c0 = c0min; c0 <= c0max; c0++) {
  172020. histp = & histogram[c0][c1][c2min];
  172021. for (c2 = c2min; c2 <= c2max; c2++)
  172022. if (*histp++ != 0) {
  172023. boxp->c1max = c1max = c1;
  172024. goto have_c1max;
  172025. }
  172026. }
  172027. have_c1max:
  172028. if (c2max > c2min)
  172029. for (c2 = c2min; c2 <= c2max; c2++)
  172030. for (c0 = c0min; c0 <= c0max; c0++) {
  172031. histp = & histogram[c0][c1min][c2];
  172032. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  172033. if (*histp != 0) {
  172034. boxp->c2min = c2min = c2;
  172035. goto have_c2min;
  172036. }
  172037. }
  172038. have_c2min:
  172039. if (c2max > c2min)
  172040. for (c2 = c2max; c2 >= c2min; c2--)
  172041. for (c0 = c0min; c0 <= c0max; c0++) {
  172042. histp = & histogram[c0][c1min][c2];
  172043. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  172044. if (*histp != 0) {
  172045. boxp->c2max = c2max = c2;
  172046. goto have_c2max;
  172047. }
  172048. }
  172049. have_c2max:
  172050. /* Update box volume.
  172051. * We use 2-norm rather than real volume here; this biases the method
  172052. * against making long narrow boxes, and it has the side benefit that
  172053. * a box is splittable iff norm > 0.
  172054. * Since the differences are expressed in histogram-cell units,
  172055. * we have to shift back to JSAMPLE units to get consistent distances;
  172056. * after which, we scale according to the selected distance scale factors.
  172057. */
  172058. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  172059. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  172060. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  172061. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  172062. /* Now scan remaining volume of box and compute population */
  172063. ccount = 0;
  172064. for (c0 = c0min; c0 <= c0max; c0++)
  172065. for (c1 = c1min; c1 <= c1max; c1++) {
  172066. histp = & histogram[c0][c1][c2min];
  172067. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  172068. if (*histp != 0) {
  172069. ccount++;
  172070. }
  172071. }
  172072. boxp->colorcount = ccount;
  172073. }
  172074. LOCAL(int)
  172075. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  172076. int desired_colors)
  172077. /* Repeatedly select and split the largest box until we have enough boxes */
  172078. {
  172079. int n,lb;
  172080. int c0,c1,c2,cmax;
  172081. register boxptr b1,b2;
  172082. while (numboxes < desired_colors) {
  172083. /* Select box to split.
  172084. * Current algorithm: by population for first half, then by volume.
  172085. */
  172086. if (numboxes*2 <= desired_colors) {
  172087. b1 = find_biggest_color_pop(boxlist, numboxes);
  172088. } else {
  172089. b1 = find_biggest_volume(boxlist, numboxes);
  172090. }
  172091. if (b1 == NULL) /* no splittable boxes left! */
  172092. break;
  172093. b2 = &boxlist[numboxes]; /* where new box will go */
  172094. /* Copy the color bounds to the new box. */
  172095. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  172096. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  172097. /* Choose which axis to split the box on.
  172098. * Current algorithm: longest scaled axis.
  172099. * See notes in update_box about scaling distances.
  172100. */
  172101. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  172102. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  172103. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  172104. /* We want to break any ties in favor of green, then red, blue last.
  172105. * This code does the right thing for R,G,B or B,G,R color orders only.
  172106. */
  172107. #if RGB_RED == 0
  172108. cmax = c1; n = 1;
  172109. if (c0 > cmax) { cmax = c0; n = 0; }
  172110. if (c2 > cmax) { n = 2; }
  172111. #else
  172112. cmax = c1; n = 1;
  172113. if (c2 > cmax) { cmax = c2; n = 2; }
  172114. if (c0 > cmax) { n = 0; }
  172115. #endif
  172116. /* Choose split point along selected axis, and update box bounds.
  172117. * Current algorithm: split at halfway point.
  172118. * (Since the box has been shrunk to minimum volume,
  172119. * any split will produce two nonempty subboxes.)
  172120. * Note that lb value is max for lower box, so must be < old max.
  172121. */
  172122. switch (n) {
  172123. case 0:
  172124. lb = (b1->c0max + b1->c0min) / 2;
  172125. b1->c0max = lb;
  172126. b2->c0min = lb+1;
  172127. break;
  172128. case 1:
  172129. lb = (b1->c1max + b1->c1min) / 2;
  172130. b1->c1max = lb;
  172131. b2->c1min = lb+1;
  172132. break;
  172133. case 2:
  172134. lb = (b1->c2max + b1->c2min) / 2;
  172135. b1->c2max = lb;
  172136. b2->c2min = lb+1;
  172137. break;
  172138. }
  172139. /* Update stats for boxes */
  172140. update_box(cinfo, b1);
  172141. update_box(cinfo, b2);
  172142. numboxes++;
  172143. }
  172144. return numboxes;
  172145. }
  172146. LOCAL(void)
  172147. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  172148. /* Compute representative color for a box, put it in colormap[icolor] */
  172149. {
  172150. /* Current algorithm: mean weighted by pixels (not colors) */
  172151. /* Note it is important to get the rounding correct! */
  172152. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172153. hist3d histogram = cquantize->histogram;
  172154. histptr histp;
  172155. int c0,c1,c2;
  172156. int c0min,c0max,c1min,c1max,c2min,c2max;
  172157. long count;
  172158. long total = 0;
  172159. long c0total = 0;
  172160. long c1total = 0;
  172161. long c2total = 0;
  172162. c0min = boxp->c0min; c0max = boxp->c0max;
  172163. c1min = boxp->c1min; c1max = boxp->c1max;
  172164. c2min = boxp->c2min; c2max = boxp->c2max;
  172165. for (c0 = c0min; c0 <= c0max; c0++)
  172166. for (c1 = c1min; c1 <= c1max; c1++) {
  172167. histp = & histogram[c0][c1][c2min];
  172168. for (c2 = c2min; c2 <= c2max; c2++) {
  172169. if ((count = *histp++) != 0) {
  172170. total += count;
  172171. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  172172. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  172173. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  172174. }
  172175. }
  172176. }
  172177. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  172178. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  172179. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  172180. }
  172181. LOCAL(void)
  172182. select_colors (j_decompress_ptr cinfo, int desired_colors)
  172183. /* Master routine for color selection */
  172184. {
  172185. boxptr boxlist;
  172186. int numboxes;
  172187. int i;
  172188. /* Allocate workspace for box list */
  172189. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  172190. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  172191. /* Initialize one box containing whole space */
  172192. numboxes = 1;
  172193. boxlist[0].c0min = 0;
  172194. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  172195. boxlist[0].c1min = 0;
  172196. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  172197. boxlist[0].c2min = 0;
  172198. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  172199. /* Shrink it to actually-used volume and set its statistics */
  172200. update_box(cinfo, & boxlist[0]);
  172201. /* Perform median-cut to produce final box list */
  172202. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  172203. /* Compute the representative color for each box, fill colormap */
  172204. for (i = 0; i < numboxes; i++)
  172205. compute_color(cinfo, & boxlist[i], i);
  172206. cinfo->actual_number_of_colors = numboxes;
  172207. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  172208. }
  172209. /*
  172210. * These routines are concerned with the time-critical task of mapping input
  172211. * colors to the nearest color in the selected colormap.
  172212. *
  172213. * We re-use the histogram space as an "inverse color map", essentially a
  172214. * cache for the results of nearest-color searches. All colors within a
  172215. * histogram cell will be mapped to the same colormap entry, namely the one
  172216. * closest to the cell's center. This may not be quite the closest entry to
  172217. * the actual input color, but it's almost as good. A zero in the cache
  172218. * indicates we haven't found the nearest color for that cell yet; the array
  172219. * is cleared to zeroes before starting the mapping pass. When we find the
  172220. * nearest color for a cell, its colormap index plus one is recorded in the
  172221. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  172222. * when they need to use an unfilled entry in the cache.
  172223. *
  172224. * Our method of efficiently finding nearest colors is based on the "locally
  172225. * sorted search" idea described by Heckbert and on the incremental distance
  172226. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  172227. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  172228. * the distances from a given colormap entry to each cell of the histogram can
  172229. * be computed quickly using an incremental method: the differences between
  172230. * distances to adjacent cells themselves differ by a constant. This allows a
  172231. * fairly fast implementation of the "brute force" approach of computing the
  172232. * distance from every colormap entry to every histogram cell. Unfortunately,
  172233. * it needs a work array to hold the best-distance-so-far for each histogram
  172234. * cell (because the inner loop has to be over cells, not colormap entries).
  172235. * The work array elements have to be INT32s, so the work array would need
  172236. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  172237. *
  172238. * To get around these problems, we apply Thomas' method to compute the
  172239. * nearest colors for only the cells within a small subbox of the histogram.
  172240. * The work array need be only as big as the subbox, so the memory usage
  172241. * problem is solved. Furthermore, we need not fill subboxes that are never
  172242. * referenced in pass2; many images use only part of the color gamut, so a
  172243. * fair amount of work is saved. An additional advantage of this
  172244. * approach is that we can apply Heckbert's locality criterion to quickly
  172245. * eliminate colormap entries that are far away from the subbox; typically
  172246. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  172247. * and we need not compute their distances to individual cells in the subbox.
  172248. * The speed of this approach is heavily influenced by the subbox size: too
  172249. * small means too much overhead, too big loses because Heckbert's criterion
  172250. * can't eliminate as many colormap entries. Empirically the best subbox
  172251. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  172252. *
  172253. * Thomas' article also describes a refined method which is asymptotically
  172254. * faster than the brute-force method, but it is also far more complex and
  172255. * cannot efficiently be applied to small subboxes. It is therefore not
  172256. * useful for programs intended to be portable to DOS machines. On machines
  172257. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  172258. * refined method might be faster than the present code --- but then again,
  172259. * it might not be any faster, and it's certainly more complicated.
  172260. */
  172261. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  172262. #define BOX_C0_LOG (HIST_C0_BITS-3)
  172263. #define BOX_C1_LOG (HIST_C1_BITS-3)
  172264. #define BOX_C2_LOG (HIST_C2_BITS-3)
  172265. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  172266. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  172267. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  172268. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  172269. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  172270. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  172271. /*
  172272. * The next three routines implement inverse colormap filling. They could
  172273. * all be folded into one big routine, but splitting them up this way saves
  172274. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  172275. * and may allow some compilers to produce better code by registerizing more
  172276. * inner-loop variables.
  172277. */
  172278. LOCAL(int)
  172279. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  172280. JSAMPLE colorlist[])
  172281. /* Locate the colormap entries close enough to an update box to be candidates
  172282. * for the nearest entry to some cell(s) in the update box. The update box
  172283. * is specified by the center coordinates of its first cell. The number of
  172284. * candidate colormap entries is returned, and their colormap indexes are
  172285. * placed in colorlist[].
  172286. * This routine uses Heckbert's "locally sorted search" criterion to select
  172287. * the colors that need further consideration.
  172288. */
  172289. {
  172290. int numcolors = cinfo->actual_number_of_colors;
  172291. int maxc0, maxc1, maxc2;
  172292. int centerc0, centerc1, centerc2;
  172293. int i, x, ncolors;
  172294. INT32 minmaxdist, min_dist, max_dist, tdist;
  172295. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  172296. /* Compute true coordinates of update box's upper corner and center.
  172297. * Actually we compute the coordinates of the center of the upper-corner
  172298. * histogram cell, which are the upper bounds of the volume we care about.
  172299. * Note that since ">>" rounds down, the "center" values may be closer to
  172300. * min than to max; hence comparisons to them must be "<=", not "<".
  172301. */
  172302. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  172303. centerc0 = (minc0 + maxc0) >> 1;
  172304. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  172305. centerc1 = (minc1 + maxc1) >> 1;
  172306. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  172307. centerc2 = (minc2 + maxc2) >> 1;
  172308. /* For each color in colormap, find:
  172309. * 1. its minimum squared-distance to any point in the update box
  172310. * (zero if color is within update box);
  172311. * 2. its maximum squared-distance to any point in the update box.
  172312. * Both of these can be found by considering only the corners of the box.
  172313. * We save the minimum distance for each color in mindist[];
  172314. * only the smallest maximum distance is of interest.
  172315. */
  172316. minmaxdist = 0x7FFFFFFFL;
  172317. for (i = 0; i < numcolors; i++) {
  172318. /* We compute the squared-c0-distance term, then add in the other two. */
  172319. x = GETJSAMPLE(cinfo->colormap[0][i]);
  172320. if (x < minc0) {
  172321. tdist = (x - minc0) * C0_SCALE;
  172322. min_dist = tdist*tdist;
  172323. tdist = (x - maxc0) * C0_SCALE;
  172324. max_dist = tdist*tdist;
  172325. } else if (x > maxc0) {
  172326. tdist = (x - maxc0) * C0_SCALE;
  172327. min_dist = tdist*tdist;
  172328. tdist = (x - minc0) * C0_SCALE;
  172329. max_dist = tdist*tdist;
  172330. } else {
  172331. /* within cell range so no contribution to min_dist */
  172332. min_dist = 0;
  172333. if (x <= centerc0) {
  172334. tdist = (x - maxc0) * C0_SCALE;
  172335. max_dist = tdist*tdist;
  172336. } else {
  172337. tdist = (x - minc0) * C0_SCALE;
  172338. max_dist = tdist*tdist;
  172339. }
  172340. }
  172341. x = GETJSAMPLE(cinfo->colormap[1][i]);
  172342. if (x < minc1) {
  172343. tdist = (x - minc1) * C1_SCALE;
  172344. min_dist += tdist*tdist;
  172345. tdist = (x - maxc1) * C1_SCALE;
  172346. max_dist += tdist*tdist;
  172347. } else if (x > maxc1) {
  172348. tdist = (x - maxc1) * C1_SCALE;
  172349. min_dist += tdist*tdist;
  172350. tdist = (x - minc1) * C1_SCALE;
  172351. max_dist += tdist*tdist;
  172352. } else {
  172353. /* within cell range so no contribution to min_dist */
  172354. if (x <= centerc1) {
  172355. tdist = (x - maxc1) * C1_SCALE;
  172356. max_dist += tdist*tdist;
  172357. } else {
  172358. tdist = (x - minc1) * C1_SCALE;
  172359. max_dist += tdist*tdist;
  172360. }
  172361. }
  172362. x = GETJSAMPLE(cinfo->colormap[2][i]);
  172363. if (x < minc2) {
  172364. tdist = (x - minc2) * C2_SCALE;
  172365. min_dist += tdist*tdist;
  172366. tdist = (x - maxc2) * C2_SCALE;
  172367. max_dist += tdist*tdist;
  172368. } else if (x > maxc2) {
  172369. tdist = (x - maxc2) * C2_SCALE;
  172370. min_dist += tdist*tdist;
  172371. tdist = (x - minc2) * C2_SCALE;
  172372. max_dist += tdist*tdist;
  172373. } else {
  172374. /* within cell range so no contribution to min_dist */
  172375. if (x <= centerc2) {
  172376. tdist = (x - maxc2) * C2_SCALE;
  172377. max_dist += tdist*tdist;
  172378. } else {
  172379. tdist = (x - minc2) * C2_SCALE;
  172380. max_dist += tdist*tdist;
  172381. }
  172382. }
  172383. mindist[i] = min_dist; /* save away the results */
  172384. if (max_dist < minmaxdist)
  172385. minmaxdist = max_dist;
  172386. }
  172387. /* Now we know that no cell in the update box is more than minmaxdist
  172388. * away from some colormap entry. Therefore, only colors that are
  172389. * within minmaxdist of some part of the box need be considered.
  172390. */
  172391. ncolors = 0;
  172392. for (i = 0; i < numcolors; i++) {
  172393. if (mindist[i] <= minmaxdist)
  172394. colorlist[ncolors++] = (JSAMPLE) i;
  172395. }
  172396. return ncolors;
  172397. }
  172398. LOCAL(void)
  172399. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  172400. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  172401. /* Find the closest colormap entry for each cell in the update box,
  172402. * given the list of candidate colors prepared by find_nearby_colors.
  172403. * Return the indexes of the closest entries in the bestcolor[] array.
  172404. * This routine uses Thomas' incremental distance calculation method to
  172405. * find the distance from a colormap entry to successive cells in the box.
  172406. */
  172407. {
  172408. int ic0, ic1, ic2;
  172409. int i, icolor;
  172410. register INT32 * bptr; /* pointer into bestdist[] array */
  172411. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  172412. INT32 dist0, dist1; /* initial distance values */
  172413. register INT32 dist2; /* current distance in inner loop */
  172414. INT32 xx0, xx1; /* distance increments */
  172415. register INT32 xx2;
  172416. INT32 inc0, inc1, inc2; /* initial values for increments */
  172417. /* This array holds the distance to the nearest-so-far color for each cell */
  172418. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  172419. /* Initialize best-distance for each cell of the update box */
  172420. bptr = bestdist;
  172421. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  172422. *bptr++ = 0x7FFFFFFFL;
  172423. /* For each color selected by find_nearby_colors,
  172424. * compute its distance to the center of each cell in the box.
  172425. * If that's less than best-so-far, update best distance and color number.
  172426. */
  172427. /* Nominal steps between cell centers ("x" in Thomas article) */
  172428. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  172429. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  172430. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  172431. for (i = 0; i < numcolors; i++) {
  172432. icolor = GETJSAMPLE(colorlist[i]);
  172433. /* Compute (square of) distance from minc0/c1/c2 to this color */
  172434. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  172435. dist0 = inc0*inc0;
  172436. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  172437. dist0 += inc1*inc1;
  172438. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  172439. dist0 += inc2*inc2;
  172440. /* Form the initial difference increments */
  172441. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  172442. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  172443. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  172444. /* Now loop over all cells in box, updating distance per Thomas method */
  172445. bptr = bestdist;
  172446. cptr = bestcolor;
  172447. xx0 = inc0;
  172448. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  172449. dist1 = dist0;
  172450. xx1 = inc1;
  172451. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  172452. dist2 = dist1;
  172453. xx2 = inc2;
  172454. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  172455. if (dist2 < *bptr) {
  172456. *bptr = dist2;
  172457. *cptr = (JSAMPLE) icolor;
  172458. }
  172459. dist2 += xx2;
  172460. xx2 += 2 * STEP_C2 * STEP_C2;
  172461. bptr++;
  172462. cptr++;
  172463. }
  172464. dist1 += xx1;
  172465. xx1 += 2 * STEP_C1 * STEP_C1;
  172466. }
  172467. dist0 += xx0;
  172468. xx0 += 2 * STEP_C0 * STEP_C0;
  172469. }
  172470. }
  172471. }
  172472. LOCAL(void)
  172473. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  172474. /* Fill the inverse-colormap entries in the update box that contains */
  172475. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  172476. /* we can fill as many others as we wish.) */
  172477. {
  172478. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172479. hist3d histogram = cquantize->histogram;
  172480. int minc0, minc1, minc2; /* lower left corner of update box */
  172481. int ic0, ic1, ic2;
  172482. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  172483. register histptr cachep; /* pointer into main cache array */
  172484. /* This array lists the candidate colormap indexes. */
  172485. JSAMPLE colorlist[MAXNUMCOLORS];
  172486. int numcolors; /* number of candidate colors */
  172487. /* This array holds the actually closest colormap index for each cell. */
  172488. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  172489. /* Convert cell coordinates to update box ID */
  172490. c0 >>= BOX_C0_LOG;
  172491. c1 >>= BOX_C1_LOG;
  172492. c2 >>= BOX_C2_LOG;
  172493. /* Compute true coordinates of update box's origin corner.
  172494. * Actually we compute the coordinates of the center of the corner
  172495. * histogram cell, which are the lower bounds of the volume we care about.
  172496. */
  172497. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  172498. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  172499. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  172500. /* Determine which colormap entries are close enough to be candidates
  172501. * for the nearest entry to some cell in the update box.
  172502. */
  172503. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  172504. /* Determine the actually nearest colors. */
  172505. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  172506. bestcolor);
  172507. /* Save the best color numbers (plus 1) in the main cache array */
  172508. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  172509. c1 <<= BOX_C1_LOG;
  172510. c2 <<= BOX_C2_LOG;
  172511. cptr = bestcolor;
  172512. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  172513. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  172514. cachep = & histogram[c0+ic0][c1+ic1][c2];
  172515. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  172516. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  172517. }
  172518. }
  172519. }
  172520. }
  172521. /*
  172522. * Map some rows of pixels to the output colormapped representation.
  172523. */
  172524. METHODDEF(void)
  172525. pass2_no_dither (j_decompress_ptr cinfo,
  172526. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  172527. /* This version performs no dithering */
  172528. {
  172529. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172530. hist3d histogram = cquantize->histogram;
  172531. register JSAMPROW inptr, outptr;
  172532. register histptr cachep;
  172533. register int c0, c1, c2;
  172534. int row;
  172535. JDIMENSION col;
  172536. JDIMENSION width = cinfo->output_width;
  172537. for (row = 0; row < num_rows; row++) {
  172538. inptr = input_buf[row];
  172539. outptr = output_buf[row];
  172540. for (col = width; col > 0; col--) {
  172541. /* get pixel value and index into the cache */
  172542. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  172543. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  172544. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  172545. cachep = & histogram[c0][c1][c2];
  172546. /* If we have not seen this color before, find nearest colormap entry */
  172547. /* and update the cache */
  172548. if (*cachep == 0)
  172549. fill_inverse_cmap(cinfo, c0,c1,c2);
  172550. /* Now emit the colormap index for this cell */
  172551. *outptr++ = (JSAMPLE) (*cachep - 1);
  172552. }
  172553. }
  172554. }
  172555. METHODDEF(void)
  172556. pass2_fs_dither (j_decompress_ptr cinfo,
  172557. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  172558. /* This version performs Floyd-Steinberg dithering */
  172559. {
  172560. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172561. hist3d histogram = cquantize->histogram;
  172562. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  172563. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  172564. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  172565. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  172566. JSAMPROW inptr; /* => current input pixel */
  172567. JSAMPROW outptr; /* => current output pixel */
  172568. histptr cachep;
  172569. int dir; /* +1 or -1 depending on direction */
  172570. int dir3; /* 3*dir, for advancing inptr & errorptr */
  172571. int row;
  172572. JDIMENSION col;
  172573. JDIMENSION width = cinfo->output_width;
  172574. JSAMPLE *range_limit = cinfo->sample_range_limit;
  172575. int *error_limit = cquantize->error_limiter;
  172576. JSAMPROW colormap0 = cinfo->colormap[0];
  172577. JSAMPROW colormap1 = cinfo->colormap[1];
  172578. JSAMPROW colormap2 = cinfo->colormap[2];
  172579. SHIFT_TEMPS
  172580. for (row = 0; row < num_rows; row++) {
  172581. inptr = input_buf[row];
  172582. outptr = output_buf[row];
  172583. if (cquantize->on_odd_row) {
  172584. /* work right to left in this row */
  172585. inptr += (width-1) * 3; /* so point to rightmost pixel */
  172586. outptr += width-1;
  172587. dir = -1;
  172588. dir3 = -3;
  172589. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  172590. cquantize->on_odd_row = FALSE; /* flip for next time */
  172591. } else {
  172592. /* work left to right in this row */
  172593. dir = 1;
  172594. dir3 = 3;
  172595. errorptr = cquantize->fserrors; /* => entry before first real column */
  172596. cquantize->on_odd_row = TRUE; /* flip for next time */
  172597. }
  172598. /* Preset error values: no error propagated to first pixel from left */
  172599. cur0 = cur1 = cur2 = 0;
  172600. /* and no error propagated to row below yet */
  172601. belowerr0 = belowerr1 = belowerr2 = 0;
  172602. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  172603. for (col = width; col > 0; col--) {
  172604. /* curN holds the error propagated from the previous pixel on the
  172605. * current line. Add the error propagated from the previous line
  172606. * to form the complete error correction term for this pixel, and
  172607. * round the error term (which is expressed * 16) to an integer.
  172608. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  172609. * for either sign of the error value.
  172610. * Note: errorptr points to *previous* column's array entry.
  172611. */
  172612. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  172613. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  172614. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  172615. /* Limit the error using transfer function set by init_error_limit.
  172616. * See comments with init_error_limit for rationale.
  172617. */
  172618. cur0 = error_limit[cur0];
  172619. cur1 = error_limit[cur1];
  172620. cur2 = error_limit[cur2];
  172621. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  172622. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  172623. * this sets the required size of the range_limit array.
  172624. */
  172625. cur0 += GETJSAMPLE(inptr[0]);
  172626. cur1 += GETJSAMPLE(inptr[1]);
  172627. cur2 += GETJSAMPLE(inptr[2]);
  172628. cur0 = GETJSAMPLE(range_limit[cur0]);
  172629. cur1 = GETJSAMPLE(range_limit[cur1]);
  172630. cur2 = GETJSAMPLE(range_limit[cur2]);
  172631. /* Index into the cache with adjusted pixel value */
  172632. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  172633. /* If we have not seen this color before, find nearest colormap */
  172634. /* entry and update the cache */
  172635. if (*cachep == 0)
  172636. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  172637. /* Now emit the colormap index for this cell */
  172638. { register int pixcode = *cachep - 1;
  172639. *outptr = (JSAMPLE) pixcode;
  172640. /* Compute representation error for this pixel */
  172641. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  172642. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  172643. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  172644. }
  172645. /* Compute error fractions to be propagated to adjacent pixels.
  172646. * Add these into the running sums, and simultaneously shift the
  172647. * next-line error sums left by 1 column.
  172648. */
  172649. { register LOCFSERROR bnexterr, delta;
  172650. bnexterr = cur0; /* Process component 0 */
  172651. delta = cur0 * 2;
  172652. cur0 += delta; /* form error * 3 */
  172653. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  172654. cur0 += delta; /* form error * 5 */
  172655. bpreverr0 = belowerr0 + cur0;
  172656. belowerr0 = bnexterr;
  172657. cur0 += delta; /* form error * 7 */
  172658. bnexterr = cur1; /* Process component 1 */
  172659. delta = cur1 * 2;
  172660. cur1 += delta; /* form error * 3 */
  172661. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  172662. cur1 += delta; /* form error * 5 */
  172663. bpreverr1 = belowerr1 + cur1;
  172664. belowerr1 = bnexterr;
  172665. cur1 += delta; /* form error * 7 */
  172666. bnexterr = cur2; /* Process component 2 */
  172667. delta = cur2 * 2;
  172668. cur2 += delta; /* form error * 3 */
  172669. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  172670. cur2 += delta; /* form error * 5 */
  172671. bpreverr2 = belowerr2 + cur2;
  172672. belowerr2 = bnexterr;
  172673. cur2 += delta; /* form error * 7 */
  172674. }
  172675. /* At this point curN contains the 7/16 error value to be propagated
  172676. * to the next pixel on the current line, and all the errors for the
  172677. * next line have been shifted over. We are therefore ready to move on.
  172678. */
  172679. inptr += dir3; /* Advance pixel pointers to next column */
  172680. outptr += dir;
  172681. errorptr += dir3; /* advance errorptr to current column */
  172682. }
  172683. /* Post-loop cleanup: we must unload the final error values into the
  172684. * final fserrors[] entry. Note we need not unload belowerrN because
  172685. * it is for the dummy column before or after the actual array.
  172686. */
  172687. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  172688. errorptr[1] = (FSERROR) bpreverr1;
  172689. errorptr[2] = (FSERROR) bpreverr2;
  172690. }
  172691. }
  172692. /*
  172693. * Initialize the error-limiting transfer function (lookup table).
  172694. * The raw F-S error computation can potentially compute error values of up to
  172695. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  172696. * much less, otherwise obviously wrong pixels will be created. (Typical
  172697. * effects include weird fringes at color-area boundaries, isolated bright
  172698. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  172699. * is to ensure that the "corners" of the color cube are allocated as output
  172700. * colors; then repeated errors in the same direction cannot cause cascading
  172701. * error buildup. However, that only prevents the error from getting
  172702. * completely out of hand; Aaron Giles reports that error limiting improves
  172703. * the results even with corner colors allocated.
  172704. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  172705. * well, but the smoother transfer function used below is even better. Thanks
  172706. * to Aaron Giles for this idea.
  172707. */
  172708. LOCAL(void)
  172709. init_error_limit (j_decompress_ptr cinfo)
  172710. /* Allocate and fill in the error_limiter table */
  172711. {
  172712. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172713. int * table;
  172714. int in, out;
  172715. table = (int *) (*cinfo->mem->alloc_small)
  172716. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  172717. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  172718. cquantize->error_limiter = table;
  172719. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  172720. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  172721. out = 0;
  172722. for (in = 0; in < STEPSIZE; in++, out++) {
  172723. table[in] = out; table[-in] = -out;
  172724. }
  172725. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  172726. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  172727. table[in] = out; table[-in] = -out;
  172728. }
  172729. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  172730. for (; in <= MAXJSAMPLE; in++) {
  172731. table[in] = out; table[-in] = -out;
  172732. }
  172733. #undef STEPSIZE
  172734. }
  172735. /*
  172736. * Finish up at the end of each pass.
  172737. */
  172738. METHODDEF(void)
  172739. finish_pass1 (j_decompress_ptr cinfo)
  172740. {
  172741. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172742. /* Select the representative colors and fill in cinfo->colormap */
  172743. cinfo->colormap = cquantize->sv_colormap;
  172744. select_colors(cinfo, cquantize->desired);
  172745. /* Force next pass to zero the color index table */
  172746. cquantize->needs_zeroed = TRUE;
  172747. }
  172748. METHODDEF(void)
  172749. finish_pass2 (j_decompress_ptr cinfo)
  172750. {
  172751. /* no work */
  172752. }
  172753. /*
  172754. * Initialize for each processing pass.
  172755. */
  172756. METHODDEF(void)
  172757. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  172758. {
  172759. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172760. hist3d histogram = cquantize->histogram;
  172761. int i;
  172762. /* Only F-S dithering or no dithering is supported. */
  172763. /* If user asks for ordered dither, give him F-S. */
  172764. if (cinfo->dither_mode != JDITHER_NONE)
  172765. cinfo->dither_mode = JDITHER_FS;
  172766. if (is_pre_scan) {
  172767. /* Set up method pointers */
  172768. cquantize->pub.color_quantize = prescan_quantize;
  172769. cquantize->pub.finish_pass = finish_pass1;
  172770. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  172771. } else {
  172772. /* Set up method pointers */
  172773. if (cinfo->dither_mode == JDITHER_FS)
  172774. cquantize->pub.color_quantize = pass2_fs_dither;
  172775. else
  172776. cquantize->pub.color_quantize = pass2_no_dither;
  172777. cquantize->pub.finish_pass = finish_pass2;
  172778. /* Make sure color count is acceptable */
  172779. i = cinfo->actual_number_of_colors;
  172780. if (i < 1)
  172781. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  172782. if (i > MAXNUMCOLORS)
  172783. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  172784. if (cinfo->dither_mode == JDITHER_FS) {
  172785. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  172786. (3 * SIZEOF(FSERROR)));
  172787. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  172788. if (cquantize->fserrors == NULL)
  172789. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  172790. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  172791. /* Initialize the propagated errors to zero. */
  172792. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  172793. /* Make the error-limit table if we didn't already. */
  172794. if (cquantize->error_limiter == NULL)
  172795. init_error_limit(cinfo);
  172796. cquantize->on_odd_row = FALSE;
  172797. }
  172798. }
  172799. /* Zero the histogram or inverse color map, if necessary */
  172800. if (cquantize->needs_zeroed) {
  172801. for (i = 0; i < HIST_C0_ELEMS; i++) {
  172802. jzero_far((void FAR *) histogram[i],
  172803. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  172804. }
  172805. cquantize->needs_zeroed = FALSE;
  172806. }
  172807. }
  172808. /*
  172809. * Switch to a new external colormap between output passes.
  172810. */
  172811. METHODDEF(void)
  172812. new_color_map_2_quant (j_decompress_ptr cinfo)
  172813. {
  172814. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172815. /* Reset the inverse color map */
  172816. cquantize->needs_zeroed = TRUE;
  172817. }
  172818. /*
  172819. * Module initialization routine for 2-pass color quantization.
  172820. */
  172821. GLOBAL(void)
  172822. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  172823. {
  172824. my_cquantize_ptr2 cquantize;
  172825. int i;
  172826. cquantize = (my_cquantize_ptr2)
  172827. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172828. SIZEOF(my_cquantizer2));
  172829. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  172830. cquantize->pub.start_pass = start_pass_2_quant;
  172831. cquantize->pub.new_color_map = new_color_map_2_quant;
  172832. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  172833. cquantize->error_limiter = NULL;
  172834. /* Make sure jdmaster didn't give me a case I can't handle */
  172835. if (cinfo->out_color_components != 3)
  172836. ERREXIT(cinfo, JERR_NOTIMPL);
  172837. /* Allocate the histogram/inverse colormap storage */
  172838. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  172839. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  172840. for (i = 0; i < HIST_C0_ELEMS; i++) {
  172841. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  172842. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172843. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  172844. }
  172845. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  172846. /* Allocate storage for the completed colormap, if required.
  172847. * We do this now since it is FAR storage and may affect
  172848. * the memory manager's space calculations.
  172849. */
  172850. if (cinfo->enable_2pass_quant) {
  172851. /* Make sure color count is acceptable */
  172852. int desired = cinfo->desired_number_of_colors;
  172853. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  172854. if (desired < 8)
  172855. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  172856. /* Make sure colormap indexes can be represented by JSAMPLEs */
  172857. if (desired > MAXNUMCOLORS)
  172858. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  172859. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  172860. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  172861. cquantize->desired = desired;
  172862. } else
  172863. cquantize->sv_colormap = NULL;
  172864. /* Only F-S dithering or no dithering is supported. */
  172865. /* If user asks for ordered dither, give him F-S. */
  172866. if (cinfo->dither_mode != JDITHER_NONE)
  172867. cinfo->dither_mode = JDITHER_FS;
  172868. /* Allocate Floyd-Steinberg workspace if necessary.
  172869. * This isn't really needed until pass 2, but again it is FAR storage.
  172870. * Although we will cope with a later change in dither_mode,
  172871. * we do not promise to honor max_memory_to_use if dither_mode changes.
  172872. */
  172873. if (cinfo->dither_mode == JDITHER_FS) {
  172874. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  172875. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172876. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  172877. /* Might as well create the error-limiting table too. */
  172878. init_error_limit(cinfo);
  172879. }
  172880. }
  172881. #endif /* QUANT_2PASS_SUPPORTED */
  172882. /********* End of inlined file: jquant2.c *********/
  172883. /********* Start of inlined file: jutils.c *********/
  172884. #define JPEG_INTERNALS
  172885. /*
  172886. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  172887. * of a DCT block read in natural order (left to right, top to bottom).
  172888. */
  172889. #if 0 /* This table is not actually needed in v6a */
  172890. const int jpeg_zigzag_order[DCTSIZE2] = {
  172891. 0, 1, 5, 6, 14, 15, 27, 28,
  172892. 2, 4, 7, 13, 16, 26, 29, 42,
  172893. 3, 8, 12, 17, 25, 30, 41, 43,
  172894. 9, 11, 18, 24, 31, 40, 44, 53,
  172895. 10, 19, 23, 32, 39, 45, 52, 54,
  172896. 20, 22, 33, 38, 46, 51, 55, 60,
  172897. 21, 34, 37, 47, 50, 56, 59, 61,
  172898. 35, 36, 48, 49, 57, 58, 62, 63
  172899. };
  172900. #endif
  172901. /*
  172902. * jpeg_natural_order[i] is the natural-order position of the i'th element
  172903. * of zigzag order.
  172904. *
  172905. * When reading corrupted data, the Huffman decoders could attempt
  172906. * to reference an entry beyond the end of this array (if the decoded
  172907. * zero run length reaches past the end of the block). To prevent
  172908. * wild stores without adding an inner-loop test, we put some extra
  172909. * "63"s after the real entries. This will cause the extra coefficient
  172910. * to be stored in location 63 of the block, not somewhere random.
  172911. * The worst case would be a run-length of 15, which means we need 16
  172912. * fake entries.
  172913. */
  172914. const int jpeg_natural_order[DCTSIZE2+16] = {
  172915. 0, 1, 8, 16, 9, 2, 3, 10,
  172916. 17, 24, 32, 25, 18, 11, 4, 5,
  172917. 12, 19, 26, 33, 40, 48, 41, 34,
  172918. 27, 20, 13, 6, 7, 14, 21, 28,
  172919. 35, 42, 49, 56, 57, 50, 43, 36,
  172920. 29, 22, 15, 23, 30, 37, 44, 51,
  172921. 58, 59, 52, 45, 38, 31, 39, 46,
  172922. 53, 60, 61, 54, 47, 55, 62, 63,
  172923. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  172924. 63, 63, 63, 63, 63, 63, 63, 63
  172925. };
  172926. /*
  172927. * Arithmetic utilities
  172928. */
  172929. GLOBAL(long)
  172930. jdiv_round_up (long a, long b)
  172931. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  172932. /* Assumes a >= 0, b > 0 */
  172933. {
  172934. return (a + b - 1L) / b;
  172935. }
  172936. GLOBAL(long)
  172937. jround_up (long a, long b)
  172938. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  172939. /* Assumes a >= 0, b > 0 */
  172940. {
  172941. a += b - 1L;
  172942. return a - (a % b);
  172943. }
  172944. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  172945. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  172946. * are FAR and we're assuming a small-pointer memory model. However, some
  172947. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  172948. * in the small-model libraries. These will be used if USE_FMEM is defined.
  172949. * Otherwise, the routines below do it the hard way. (The performance cost
  172950. * is not all that great, because these routines aren't very heavily used.)
  172951. */
  172952. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  172953. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  172954. #define FMEMZERO(target,size) MEMZERO(target,size)
  172955. #else /* 80x86 case, define if we can */
  172956. #ifdef USE_FMEM
  172957. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  172958. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  172959. #endif
  172960. #endif
  172961. GLOBAL(void)
  172962. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  172963. JSAMPARRAY output_array, int dest_row,
  172964. int num_rows, JDIMENSION num_cols)
  172965. /* Copy some rows of samples from one place to another.
  172966. * num_rows rows are copied from input_array[source_row++]
  172967. * to output_array[dest_row++]; these areas may overlap for duplication.
  172968. * The source and destination arrays must be at least as wide as num_cols.
  172969. */
  172970. {
  172971. register JSAMPROW inptr, outptr;
  172972. #ifdef FMEMCOPY
  172973. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  172974. #else
  172975. register JDIMENSION count;
  172976. #endif
  172977. register int row;
  172978. input_array += source_row;
  172979. output_array += dest_row;
  172980. for (row = num_rows; row > 0; row--) {
  172981. inptr = *input_array++;
  172982. outptr = *output_array++;
  172983. #ifdef FMEMCOPY
  172984. FMEMCOPY(outptr, inptr, count);
  172985. #else
  172986. for (count = num_cols; count > 0; count--)
  172987. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  172988. #endif
  172989. }
  172990. }
  172991. GLOBAL(void)
  172992. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  172993. JDIMENSION num_blocks)
  172994. /* Copy a row of coefficient blocks from one place to another. */
  172995. {
  172996. #ifdef FMEMCOPY
  172997. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  172998. #else
  172999. register JCOEFPTR inptr, outptr;
  173000. register long count;
  173001. inptr = (JCOEFPTR) input_row;
  173002. outptr = (JCOEFPTR) output_row;
  173003. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  173004. *outptr++ = *inptr++;
  173005. }
  173006. #endif
  173007. }
  173008. GLOBAL(void)
  173009. jzero_far (void FAR * target, size_t bytestozero)
  173010. /* Zero out a chunk of FAR memory. */
  173011. /* This might be sample-array data, block-array data, or alloc_large data. */
  173012. {
  173013. #ifdef FMEMZERO
  173014. FMEMZERO(target, bytestozero);
  173015. #else
  173016. register char FAR * ptr = (char FAR *) target;
  173017. register size_t count;
  173018. for (count = bytestozero; count > 0; count--) {
  173019. *ptr++ = 0;
  173020. }
  173021. #endif
  173022. }
  173023. /********* End of inlined file: jutils.c *********/
  173024. /********* Start of inlined file: transupp.c *********/
  173025. /* Although this file really shouldn't have access to the library internals,
  173026. * it's helpful to let it call jround_up() and jcopy_block_row().
  173027. */
  173028. #define JPEG_INTERNALS
  173029. /********* Start of inlined file: transupp.h *********/
  173030. /* If you happen not to want the image transform support, disable it here */
  173031. #ifndef TRANSFORMS_SUPPORTED
  173032. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  173033. #endif
  173034. /* Short forms of external names for systems with brain-damaged linkers. */
  173035. #ifdef NEED_SHORT_EXTERNAL_NAMES
  173036. #define jtransform_request_workspace jTrRequest
  173037. #define jtransform_adjust_parameters jTrAdjust
  173038. #define jtransform_execute_transformation jTrExec
  173039. #define jcopy_markers_setup jCMrkSetup
  173040. #define jcopy_markers_execute jCMrkExec
  173041. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  173042. /*
  173043. * Codes for supported types of image transformations.
  173044. */
  173045. typedef enum {
  173046. JXFORM_NONE, /* no transformation */
  173047. JXFORM_FLIP_H, /* horizontal flip */
  173048. JXFORM_FLIP_V, /* vertical flip */
  173049. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  173050. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  173051. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  173052. JXFORM_ROT_180, /* 180-degree rotation */
  173053. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  173054. } JXFORM_CODE;
  173055. /*
  173056. * Although rotating and flipping data expressed as DCT coefficients is not
  173057. * hard, there is an asymmetry in the JPEG format specification for images
  173058. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  173059. * image edges are padded out to the next iMCU boundary with junk data; but
  173060. * no padding is possible at the top and left edges. If we were to flip
  173061. * the whole image including the pad data, then pad garbage would become
  173062. * visible at the top and/or left, and real pixels would disappear into the
  173063. * pad margins --- perhaps permanently, since encoders & decoders may not
  173064. * bother to preserve DCT blocks that appear to be completely outside the
  173065. * nominal image area. So, we have to exclude any partial iMCUs from the
  173066. * basic transformation.
  173067. *
  173068. * Transpose is the only transformation that can handle partial iMCUs at the
  173069. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  173070. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  173071. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  173072. * The other transforms are defined as combinations of these basic transforms
  173073. * and process edge blocks in a way that preserves the equivalence.
  173074. *
  173075. * The "trim" option causes untransformable partial iMCUs to be dropped;
  173076. * this is not strictly lossless, but it usually gives the best-looking
  173077. * result for odd-size images. Note that when this option is active,
  173078. * the expected mathematical equivalences between the transforms may not hold.
  173079. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  173080. * followed by -rot 180 -trim trims both edges.)
  173081. *
  173082. * We also offer a "force to grayscale" option, which simply discards the
  173083. * chrominance channels of a YCbCr image. This is lossless in the sense that
  173084. * the luminance channel is preserved exactly. It's not the same kind of
  173085. * thing as the rotate/flip transformations, but it's convenient to handle it
  173086. * as part of this package, mainly because the transformation routines have to
  173087. * be aware of the option to know how many components to work on.
  173088. */
  173089. typedef struct {
  173090. /* Options: set by caller */
  173091. JXFORM_CODE transform; /* image transform operator */
  173092. boolean trim; /* if TRUE, trim partial MCUs as needed */
  173093. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  173094. /* Internal workspace: caller should not touch these */
  173095. int num_components; /* # of components in workspace */
  173096. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  173097. } jpeg_transform_info;
  173098. #if TRANSFORMS_SUPPORTED
  173099. /* Request any required workspace */
  173100. EXTERN(void) jtransform_request_workspace
  173101. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  173102. /* Adjust output image parameters */
  173103. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  173104. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173105. jvirt_barray_ptr *src_coef_arrays,
  173106. jpeg_transform_info *info));
  173107. /* Execute the actual transformation, if any */
  173108. EXTERN(void) jtransform_execute_transformation
  173109. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173110. jvirt_barray_ptr *src_coef_arrays,
  173111. jpeg_transform_info *info));
  173112. #endif /* TRANSFORMS_SUPPORTED */
  173113. /*
  173114. * Support for copying optional markers from source to destination file.
  173115. */
  173116. typedef enum {
  173117. JCOPYOPT_NONE, /* copy no optional markers */
  173118. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  173119. JCOPYOPT_ALL /* copy all optional markers */
  173120. } JCOPY_OPTION;
  173121. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  173122. /* Setup decompression object to save desired markers in memory */
  173123. EXTERN(void) jcopy_markers_setup
  173124. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  173125. /* Copy markers saved in the given source object to the destination object */
  173126. EXTERN(void) jcopy_markers_execute
  173127. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173128. JCOPY_OPTION option));
  173129. /********* End of inlined file: transupp.h *********/
  173130. /* My own external interface */
  173131. #if TRANSFORMS_SUPPORTED
  173132. /*
  173133. * Lossless image transformation routines. These routines work on DCT
  173134. * coefficient arrays and thus do not require any lossy decompression
  173135. * or recompression of the image.
  173136. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  173137. *
  173138. * Horizontal flipping is done in-place, using a single top-to-bottom
  173139. * pass through the virtual source array. It will thus be much the
  173140. * fastest option for images larger than main memory.
  173141. *
  173142. * The other routines require a set of destination virtual arrays, so they
  173143. * need twice as much memory as jpegtran normally does. The destination
  173144. * arrays are always written in normal scan order (top to bottom) because
  173145. * the virtual array manager expects this. The source arrays will be scanned
  173146. * in the corresponding order, which means multiple passes through the source
  173147. * arrays for most of the transforms. That could result in much thrashing
  173148. * if the image is larger than main memory.
  173149. *
  173150. * Some notes about the operating environment of the individual transform
  173151. * routines:
  173152. * 1. Both the source and destination virtual arrays are allocated from the
  173153. * source JPEG object, and therefore should be manipulated by calling the
  173154. * source's memory manager.
  173155. * 2. The destination's component count should be used. It may be smaller
  173156. * than the source's when forcing to grayscale.
  173157. * 3. Likewise the destination's sampling factors should be used. When
  173158. * forcing to grayscale the destination's sampling factors will be all 1,
  173159. * and we may as well take that as the effective iMCU size.
  173160. * 4. When "trim" is in effect, the destination's dimensions will be the
  173161. * trimmed values but the source's will be untrimmed.
  173162. * 5. All the routines assume that the source and destination buffers are
  173163. * padded out to a full iMCU boundary. This is true, although for the
  173164. * source buffer it is an undocumented property of jdcoefct.c.
  173165. * Notes 2,3,4 boil down to this: generally we should use the destination's
  173166. * dimensions and ignore the source's.
  173167. */
  173168. LOCAL(void)
  173169. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173170. jvirt_barray_ptr *src_coef_arrays)
  173171. /* Horizontal flip; done in-place, so no separate dest array is required */
  173172. {
  173173. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  173174. int ci, k, offset_y;
  173175. JBLOCKARRAY buffer;
  173176. JCOEFPTR ptr1, ptr2;
  173177. JCOEF temp1, temp2;
  173178. jpeg_component_info *compptr;
  173179. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  173180. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  173181. * mirroring by changing the signs of odd-numbered columns.
  173182. * Partial iMCUs at the right edge are left untouched.
  173183. */
  173184. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  173185. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173186. compptr = dstinfo->comp_info + ci;
  173187. comp_width = MCU_cols * compptr->h_samp_factor;
  173188. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  173189. blk_y += compptr->v_samp_factor) {
  173190. buffer = (*srcinfo->mem->access_virt_barray)
  173191. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  173192. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173193. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173194. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  173195. ptr1 = buffer[offset_y][blk_x];
  173196. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  173197. /* this unrolled loop doesn't need to know which row it's on... */
  173198. for (k = 0; k < DCTSIZE2; k += 2) {
  173199. temp1 = *ptr1; /* swap even column */
  173200. temp2 = *ptr2;
  173201. *ptr1++ = temp2;
  173202. *ptr2++ = temp1;
  173203. temp1 = *ptr1; /* swap odd column with sign change */
  173204. temp2 = *ptr2;
  173205. *ptr1++ = -temp2;
  173206. *ptr2++ = -temp1;
  173207. }
  173208. }
  173209. }
  173210. }
  173211. }
  173212. }
  173213. LOCAL(void)
  173214. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173215. jvirt_barray_ptr *src_coef_arrays,
  173216. jvirt_barray_ptr *dst_coef_arrays)
  173217. /* Vertical flip */
  173218. {
  173219. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  173220. int ci, i, j, offset_y;
  173221. JBLOCKARRAY src_buffer, dst_buffer;
  173222. JBLOCKROW src_row_ptr, dst_row_ptr;
  173223. JCOEFPTR src_ptr, dst_ptr;
  173224. jpeg_component_info *compptr;
  173225. /* We output into a separate array because we can't touch different
  173226. * rows of the source virtual array simultaneously. Otherwise, this
  173227. * is a pretty straightforward analog of horizontal flip.
  173228. * Within a DCT block, vertical mirroring is done by changing the signs
  173229. * of odd-numbered rows.
  173230. * Partial iMCUs at the bottom edge are copied verbatim.
  173231. */
  173232. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  173233. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173234. compptr = dstinfo->comp_info + ci;
  173235. comp_height = MCU_rows * compptr->v_samp_factor;
  173236. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  173237. dst_blk_y += compptr->v_samp_factor) {
  173238. dst_buffer = (*srcinfo->mem->access_virt_barray)
  173239. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  173240. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173241. if (dst_blk_y < comp_height) {
  173242. /* Row is within the mirrorable area. */
  173243. src_buffer = (*srcinfo->mem->access_virt_barray)
  173244. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  173245. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  173246. (JDIMENSION) compptr->v_samp_factor, FALSE);
  173247. } else {
  173248. /* Bottom-edge blocks will be copied verbatim. */
  173249. src_buffer = (*srcinfo->mem->access_virt_barray)
  173250. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  173251. (JDIMENSION) compptr->v_samp_factor, FALSE);
  173252. }
  173253. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173254. if (dst_blk_y < comp_height) {
  173255. /* Row is within the mirrorable area. */
  173256. dst_row_ptr = dst_buffer[offset_y];
  173257. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  173258. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  173259. dst_blk_x++) {
  173260. dst_ptr = dst_row_ptr[dst_blk_x];
  173261. src_ptr = src_row_ptr[dst_blk_x];
  173262. for (i = 0; i < DCTSIZE; i += 2) {
  173263. /* copy even row */
  173264. for (j = 0; j < DCTSIZE; j++)
  173265. *dst_ptr++ = *src_ptr++;
  173266. /* copy odd row with sign change */
  173267. for (j = 0; j < DCTSIZE; j++)
  173268. *dst_ptr++ = - *src_ptr++;
  173269. }
  173270. }
  173271. } else {
  173272. /* Just copy row verbatim. */
  173273. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  173274. compptr->width_in_blocks);
  173275. }
  173276. }
  173277. }
  173278. }
  173279. }
  173280. LOCAL(void)
  173281. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173282. jvirt_barray_ptr *src_coef_arrays,
  173283. jvirt_barray_ptr *dst_coef_arrays)
  173284. /* Transpose source into destination */
  173285. {
  173286. JDIMENSION dst_blk_x, dst_blk_y;
  173287. int ci, i, j, offset_x, offset_y;
  173288. JBLOCKARRAY src_buffer, dst_buffer;
  173289. JCOEFPTR src_ptr, dst_ptr;
  173290. jpeg_component_info *compptr;
  173291. /* Transposing pixels within a block just requires transposing the
  173292. * DCT coefficients.
  173293. * Partial iMCUs at the edges require no special treatment; we simply
  173294. * process all the available DCT blocks for every component.
  173295. */
  173296. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173297. compptr = dstinfo->comp_info + ci;
  173298. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  173299. dst_blk_y += compptr->v_samp_factor) {
  173300. dst_buffer = (*srcinfo->mem->access_virt_barray)
  173301. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  173302. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173303. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173304. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  173305. dst_blk_x += compptr->h_samp_factor) {
  173306. src_buffer = (*srcinfo->mem->access_virt_barray)
  173307. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  173308. (JDIMENSION) compptr->h_samp_factor, FALSE);
  173309. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  173310. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  173311. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  173312. for (i = 0; i < DCTSIZE; i++)
  173313. for (j = 0; j < DCTSIZE; j++)
  173314. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173315. }
  173316. }
  173317. }
  173318. }
  173319. }
  173320. }
  173321. LOCAL(void)
  173322. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173323. jvirt_barray_ptr *src_coef_arrays,
  173324. jvirt_barray_ptr *dst_coef_arrays)
  173325. /* 90 degree rotation is equivalent to
  173326. * 1. Transposing the image;
  173327. * 2. Horizontal mirroring.
  173328. * These two steps are merged into a single processing routine.
  173329. */
  173330. {
  173331. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  173332. int ci, i, j, offset_x, offset_y;
  173333. JBLOCKARRAY src_buffer, dst_buffer;
  173334. JCOEFPTR src_ptr, dst_ptr;
  173335. jpeg_component_info *compptr;
  173336. /* Because of the horizontal mirror step, we can't process partial iMCUs
  173337. * at the (output) right edge properly. They just get transposed and
  173338. * not mirrored.
  173339. */
  173340. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  173341. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173342. compptr = dstinfo->comp_info + ci;
  173343. comp_width = MCU_cols * compptr->h_samp_factor;
  173344. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  173345. dst_blk_y += compptr->v_samp_factor) {
  173346. dst_buffer = (*srcinfo->mem->access_virt_barray)
  173347. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  173348. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173349. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173350. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  173351. dst_blk_x += compptr->h_samp_factor) {
  173352. src_buffer = (*srcinfo->mem->access_virt_barray)
  173353. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  173354. (JDIMENSION) compptr->h_samp_factor, FALSE);
  173355. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  173356. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  173357. if (dst_blk_x < comp_width) {
  173358. /* Block is within the mirrorable area. */
  173359. dst_ptr = dst_buffer[offset_y]
  173360. [comp_width - dst_blk_x - offset_x - 1];
  173361. for (i = 0; i < DCTSIZE; i++) {
  173362. for (j = 0; j < DCTSIZE; j++)
  173363. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173364. i++;
  173365. for (j = 0; j < DCTSIZE; j++)
  173366. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173367. }
  173368. } else {
  173369. /* Edge blocks are transposed but not mirrored. */
  173370. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  173371. for (i = 0; i < DCTSIZE; i++)
  173372. for (j = 0; j < DCTSIZE; j++)
  173373. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173374. }
  173375. }
  173376. }
  173377. }
  173378. }
  173379. }
  173380. }
  173381. LOCAL(void)
  173382. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173383. jvirt_barray_ptr *src_coef_arrays,
  173384. jvirt_barray_ptr *dst_coef_arrays)
  173385. /* 270 degree rotation is equivalent to
  173386. * 1. Horizontal mirroring;
  173387. * 2. Transposing the image.
  173388. * These two steps are merged into a single processing routine.
  173389. */
  173390. {
  173391. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  173392. int ci, i, j, offset_x, offset_y;
  173393. JBLOCKARRAY src_buffer, dst_buffer;
  173394. JCOEFPTR src_ptr, dst_ptr;
  173395. jpeg_component_info *compptr;
  173396. /* Because of the horizontal mirror step, we can't process partial iMCUs
  173397. * at the (output) bottom edge properly. They just get transposed and
  173398. * not mirrored.
  173399. */
  173400. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  173401. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173402. compptr = dstinfo->comp_info + ci;
  173403. comp_height = MCU_rows * compptr->v_samp_factor;
  173404. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  173405. dst_blk_y += compptr->v_samp_factor) {
  173406. dst_buffer = (*srcinfo->mem->access_virt_barray)
  173407. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  173408. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173409. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173410. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  173411. dst_blk_x += compptr->h_samp_factor) {
  173412. src_buffer = (*srcinfo->mem->access_virt_barray)
  173413. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  173414. (JDIMENSION) compptr->h_samp_factor, FALSE);
  173415. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  173416. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  173417. if (dst_blk_y < comp_height) {
  173418. /* Block is within the mirrorable area. */
  173419. src_ptr = src_buffer[offset_x]
  173420. [comp_height - dst_blk_y - offset_y - 1];
  173421. for (i = 0; i < DCTSIZE; i++) {
  173422. for (j = 0; j < DCTSIZE; j++) {
  173423. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173424. j++;
  173425. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173426. }
  173427. }
  173428. } else {
  173429. /* Edge blocks are transposed but not mirrored. */
  173430. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  173431. for (i = 0; i < DCTSIZE; i++)
  173432. for (j = 0; j < DCTSIZE; j++)
  173433. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173434. }
  173435. }
  173436. }
  173437. }
  173438. }
  173439. }
  173440. }
  173441. LOCAL(void)
  173442. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173443. jvirt_barray_ptr *src_coef_arrays,
  173444. jvirt_barray_ptr *dst_coef_arrays)
  173445. /* 180 degree rotation is equivalent to
  173446. * 1. Vertical mirroring;
  173447. * 2. Horizontal mirroring.
  173448. * These two steps are merged into a single processing routine.
  173449. */
  173450. {
  173451. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  173452. int ci, i, j, offset_y;
  173453. JBLOCKARRAY src_buffer, dst_buffer;
  173454. JBLOCKROW src_row_ptr, dst_row_ptr;
  173455. JCOEFPTR src_ptr, dst_ptr;
  173456. jpeg_component_info *compptr;
  173457. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  173458. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  173459. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173460. compptr = dstinfo->comp_info + ci;
  173461. comp_width = MCU_cols * compptr->h_samp_factor;
  173462. comp_height = MCU_rows * compptr->v_samp_factor;
  173463. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  173464. dst_blk_y += compptr->v_samp_factor) {
  173465. dst_buffer = (*srcinfo->mem->access_virt_barray)
  173466. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  173467. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173468. if (dst_blk_y < comp_height) {
  173469. /* Row is within the vertically mirrorable area. */
  173470. src_buffer = (*srcinfo->mem->access_virt_barray)
  173471. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  173472. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  173473. (JDIMENSION) compptr->v_samp_factor, FALSE);
  173474. } else {
  173475. /* Bottom-edge rows are only mirrored horizontally. */
  173476. src_buffer = (*srcinfo->mem->access_virt_barray)
  173477. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  173478. (JDIMENSION) compptr->v_samp_factor, FALSE);
  173479. }
  173480. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173481. if (dst_blk_y < comp_height) {
  173482. /* Row is within the mirrorable area. */
  173483. dst_row_ptr = dst_buffer[offset_y];
  173484. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  173485. /* Process the blocks that can be mirrored both ways. */
  173486. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  173487. dst_ptr = dst_row_ptr[dst_blk_x];
  173488. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  173489. for (i = 0; i < DCTSIZE; i += 2) {
  173490. /* For even row, negate every odd column. */
  173491. for (j = 0; j < DCTSIZE; j += 2) {
  173492. *dst_ptr++ = *src_ptr++;
  173493. *dst_ptr++ = - *src_ptr++;
  173494. }
  173495. /* For odd row, negate every even column. */
  173496. for (j = 0; j < DCTSIZE; j += 2) {
  173497. *dst_ptr++ = - *src_ptr++;
  173498. *dst_ptr++ = *src_ptr++;
  173499. }
  173500. }
  173501. }
  173502. /* Any remaining right-edge blocks are only mirrored vertically. */
  173503. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  173504. dst_ptr = dst_row_ptr[dst_blk_x];
  173505. src_ptr = src_row_ptr[dst_blk_x];
  173506. for (i = 0; i < DCTSIZE; i += 2) {
  173507. for (j = 0; j < DCTSIZE; j++)
  173508. *dst_ptr++ = *src_ptr++;
  173509. for (j = 0; j < DCTSIZE; j++)
  173510. *dst_ptr++ = - *src_ptr++;
  173511. }
  173512. }
  173513. } else {
  173514. /* Remaining rows are just mirrored horizontally. */
  173515. dst_row_ptr = dst_buffer[offset_y];
  173516. src_row_ptr = src_buffer[offset_y];
  173517. /* Process the blocks that can be mirrored. */
  173518. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  173519. dst_ptr = dst_row_ptr[dst_blk_x];
  173520. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  173521. for (i = 0; i < DCTSIZE2; i += 2) {
  173522. *dst_ptr++ = *src_ptr++;
  173523. *dst_ptr++ = - *src_ptr++;
  173524. }
  173525. }
  173526. /* Any remaining right-edge blocks are only copied. */
  173527. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  173528. dst_ptr = dst_row_ptr[dst_blk_x];
  173529. src_ptr = src_row_ptr[dst_blk_x];
  173530. for (i = 0; i < DCTSIZE2; i++)
  173531. *dst_ptr++ = *src_ptr++;
  173532. }
  173533. }
  173534. }
  173535. }
  173536. }
  173537. }
  173538. LOCAL(void)
  173539. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173540. jvirt_barray_ptr *src_coef_arrays,
  173541. jvirt_barray_ptr *dst_coef_arrays)
  173542. /* Transverse transpose is equivalent to
  173543. * 1. 180 degree rotation;
  173544. * 2. Transposition;
  173545. * or
  173546. * 1. Horizontal mirroring;
  173547. * 2. Transposition;
  173548. * 3. Horizontal mirroring.
  173549. * These steps are merged into a single processing routine.
  173550. */
  173551. {
  173552. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  173553. int ci, i, j, offset_x, offset_y;
  173554. JBLOCKARRAY src_buffer, dst_buffer;
  173555. JCOEFPTR src_ptr, dst_ptr;
  173556. jpeg_component_info *compptr;
  173557. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  173558. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  173559. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173560. compptr = dstinfo->comp_info + ci;
  173561. comp_width = MCU_cols * compptr->h_samp_factor;
  173562. comp_height = MCU_rows * compptr->v_samp_factor;
  173563. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  173564. dst_blk_y += compptr->v_samp_factor) {
  173565. dst_buffer = (*srcinfo->mem->access_virt_barray)
  173566. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  173567. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173568. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173569. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  173570. dst_blk_x += compptr->h_samp_factor) {
  173571. src_buffer = (*srcinfo->mem->access_virt_barray)
  173572. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  173573. (JDIMENSION) compptr->h_samp_factor, FALSE);
  173574. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  173575. if (dst_blk_y < comp_height) {
  173576. src_ptr = src_buffer[offset_x]
  173577. [comp_height - dst_blk_y - offset_y - 1];
  173578. if (dst_blk_x < comp_width) {
  173579. /* Block is within the mirrorable area. */
  173580. dst_ptr = dst_buffer[offset_y]
  173581. [comp_width - dst_blk_x - offset_x - 1];
  173582. for (i = 0; i < DCTSIZE; i++) {
  173583. for (j = 0; j < DCTSIZE; j++) {
  173584. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173585. j++;
  173586. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173587. }
  173588. i++;
  173589. for (j = 0; j < DCTSIZE; j++) {
  173590. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173591. j++;
  173592. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173593. }
  173594. }
  173595. } else {
  173596. /* Right-edge blocks are mirrored in y only */
  173597. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  173598. for (i = 0; i < DCTSIZE; i++) {
  173599. for (j = 0; j < DCTSIZE; j++) {
  173600. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173601. j++;
  173602. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173603. }
  173604. }
  173605. }
  173606. } else {
  173607. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  173608. if (dst_blk_x < comp_width) {
  173609. /* Bottom-edge blocks are mirrored in x only */
  173610. dst_ptr = dst_buffer[offset_y]
  173611. [comp_width - dst_blk_x - offset_x - 1];
  173612. for (i = 0; i < DCTSIZE; i++) {
  173613. for (j = 0; j < DCTSIZE; j++)
  173614. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173615. i++;
  173616. for (j = 0; j < DCTSIZE; j++)
  173617. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173618. }
  173619. } else {
  173620. /* At lower right corner, just transpose, no mirroring */
  173621. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  173622. for (i = 0; i < DCTSIZE; i++)
  173623. for (j = 0; j < DCTSIZE; j++)
  173624. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173625. }
  173626. }
  173627. }
  173628. }
  173629. }
  173630. }
  173631. }
  173632. }
  173633. /* Request any required workspace.
  173634. *
  173635. * We allocate the workspace virtual arrays from the source decompression
  173636. * object, so that all the arrays (both the original data and the workspace)
  173637. * will be taken into account while making memory management decisions.
  173638. * Hence, this routine must be called after jpeg_read_header (which reads
  173639. * the image dimensions) and before jpeg_read_coefficients (which realizes
  173640. * the source's virtual arrays).
  173641. */
  173642. GLOBAL(void)
  173643. jtransform_request_workspace (j_decompress_ptr srcinfo,
  173644. jpeg_transform_info *info)
  173645. {
  173646. jvirt_barray_ptr *coef_arrays = NULL;
  173647. jpeg_component_info *compptr;
  173648. int ci;
  173649. if (info->force_grayscale &&
  173650. srcinfo->jpeg_color_space == JCS_YCbCr &&
  173651. srcinfo->num_components == 3) {
  173652. /* We'll only process the first component */
  173653. info->num_components = 1;
  173654. } else {
  173655. /* Process all the components */
  173656. info->num_components = srcinfo->num_components;
  173657. }
  173658. switch (info->transform) {
  173659. case JXFORM_NONE:
  173660. case JXFORM_FLIP_H:
  173661. /* Don't need a workspace array */
  173662. break;
  173663. case JXFORM_FLIP_V:
  173664. case JXFORM_ROT_180:
  173665. /* Need workspace arrays having same dimensions as source image.
  173666. * Note that we allocate arrays padded out to the next iMCU boundary,
  173667. * so that transform routines need not worry about missing edge blocks.
  173668. */
  173669. coef_arrays = (jvirt_barray_ptr *)
  173670. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  173671. SIZEOF(jvirt_barray_ptr) * info->num_components);
  173672. for (ci = 0; ci < info->num_components; ci++) {
  173673. compptr = srcinfo->comp_info + ci;
  173674. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  173675. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  173676. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  173677. (long) compptr->h_samp_factor),
  173678. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  173679. (long) compptr->v_samp_factor),
  173680. (JDIMENSION) compptr->v_samp_factor);
  173681. }
  173682. break;
  173683. case JXFORM_TRANSPOSE:
  173684. case JXFORM_TRANSVERSE:
  173685. case JXFORM_ROT_90:
  173686. case JXFORM_ROT_270:
  173687. /* Need workspace arrays having transposed dimensions.
  173688. * Note that we allocate arrays padded out to the next iMCU boundary,
  173689. * so that transform routines need not worry about missing edge blocks.
  173690. */
  173691. coef_arrays = (jvirt_barray_ptr *)
  173692. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  173693. SIZEOF(jvirt_barray_ptr) * info->num_components);
  173694. for (ci = 0; ci < info->num_components; ci++) {
  173695. compptr = srcinfo->comp_info + ci;
  173696. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  173697. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  173698. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  173699. (long) compptr->v_samp_factor),
  173700. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  173701. (long) compptr->h_samp_factor),
  173702. (JDIMENSION) compptr->h_samp_factor);
  173703. }
  173704. break;
  173705. }
  173706. info->workspace_coef_arrays = coef_arrays;
  173707. }
  173708. /* Transpose destination image parameters */
  173709. LOCAL(void)
  173710. transpose_critical_parameters (j_compress_ptr dstinfo)
  173711. {
  173712. int tblno, i, j, ci, itemp;
  173713. jpeg_component_info *compptr;
  173714. JQUANT_TBL *qtblptr;
  173715. JDIMENSION dtemp;
  173716. UINT16 qtemp;
  173717. /* Transpose basic image dimensions */
  173718. dtemp = dstinfo->image_width;
  173719. dstinfo->image_width = dstinfo->image_height;
  173720. dstinfo->image_height = dtemp;
  173721. /* Transpose sampling factors */
  173722. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173723. compptr = dstinfo->comp_info + ci;
  173724. itemp = compptr->h_samp_factor;
  173725. compptr->h_samp_factor = compptr->v_samp_factor;
  173726. compptr->v_samp_factor = itemp;
  173727. }
  173728. /* Transpose quantization tables */
  173729. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  173730. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  173731. if (qtblptr != NULL) {
  173732. for (i = 0; i < DCTSIZE; i++) {
  173733. for (j = 0; j < i; j++) {
  173734. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  173735. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  173736. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  173737. }
  173738. }
  173739. }
  173740. }
  173741. }
  173742. /* Trim off any partial iMCUs on the indicated destination edge */
  173743. LOCAL(void)
  173744. trim_right_edge (j_compress_ptr dstinfo)
  173745. {
  173746. int ci, max_h_samp_factor;
  173747. JDIMENSION MCU_cols;
  173748. /* We have to compute max_h_samp_factor ourselves,
  173749. * because it hasn't been set yet in the destination
  173750. * (and we don't want to use the source's value).
  173751. */
  173752. max_h_samp_factor = 1;
  173753. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173754. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  173755. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  173756. }
  173757. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  173758. if (MCU_cols > 0) /* can't trim to 0 pixels */
  173759. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  173760. }
  173761. LOCAL(void)
  173762. trim_bottom_edge (j_compress_ptr dstinfo)
  173763. {
  173764. int ci, max_v_samp_factor;
  173765. JDIMENSION MCU_rows;
  173766. /* We have to compute max_v_samp_factor ourselves,
  173767. * because it hasn't been set yet in the destination
  173768. * (and we don't want to use the source's value).
  173769. */
  173770. max_v_samp_factor = 1;
  173771. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173772. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  173773. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  173774. }
  173775. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  173776. if (MCU_rows > 0) /* can't trim to 0 pixels */
  173777. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  173778. }
  173779. /* Adjust output image parameters as needed.
  173780. *
  173781. * This must be called after jpeg_copy_critical_parameters()
  173782. * and before jpeg_write_coefficients().
  173783. *
  173784. * The return value is the set of virtual coefficient arrays to be written
  173785. * (either the ones allocated by jtransform_request_workspace, or the
  173786. * original source data arrays). The caller will need to pass this value
  173787. * to jpeg_write_coefficients().
  173788. */
  173789. GLOBAL(jvirt_barray_ptr *)
  173790. jtransform_adjust_parameters (j_decompress_ptr srcinfo,
  173791. j_compress_ptr dstinfo,
  173792. jvirt_barray_ptr *src_coef_arrays,
  173793. jpeg_transform_info *info)
  173794. {
  173795. /* If force-to-grayscale is requested, adjust destination parameters */
  173796. if (info->force_grayscale) {
  173797. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  173798. * properly. Among other things, the target h_samp_factor & v_samp_factor
  173799. * will get set to 1, which typically won't match the source.
  173800. * In fact we do this even if the source is already grayscale; that
  173801. * provides an easy way of coercing a grayscale JPEG with funny sampling
  173802. * factors to the customary 1,1. (Some decoders fail on other factors.)
  173803. */
  173804. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  173805. dstinfo->num_components == 3) ||
  173806. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  173807. dstinfo->num_components == 1)) {
  173808. /* We have to preserve the source's quantization table number. */
  173809. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  173810. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  173811. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  173812. } else {
  173813. /* Sorry, can't do it */
  173814. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  173815. }
  173816. }
  173817. /* Correct the destination's image dimensions etc if necessary */
  173818. switch (info->transform) {
  173819. case JXFORM_NONE:
  173820. /* Nothing to do */
  173821. break;
  173822. case JXFORM_FLIP_H:
  173823. if (info->trim)
  173824. trim_right_edge(dstinfo);
  173825. break;
  173826. case JXFORM_FLIP_V:
  173827. if (info->trim)
  173828. trim_bottom_edge(dstinfo);
  173829. break;
  173830. case JXFORM_TRANSPOSE:
  173831. transpose_critical_parameters(dstinfo);
  173832. /* transpose does NOT have to trim anything */
  173833. break;
  173834. case JXFORM_TRANSVERSE:
  173835. transpose_critical_parameters(dstinfo);
  173836. if (info->trim) {
  173837. trim_right_edge(dstinfo);
  173838. trim_bottom_edge(dstinfo);
  173839. }
  173840. break;
  173841. case JXFORM_ROT_90:
  173842. transpose_critical_parameters(dstinfo);
  173843. if (info->trim)
  173844. trim_right_edge(dstinfo);
  173845. break;
  173846. case JXFORM_ROT_180:
  173847. if (info->trim) {
  173848. trim_right_edge(dstinfo);
  173849. trim_bottom_edge(dstinfo);
  173850. }
  173851. break;
  173852. case JXFORM_ROT_270:
  173853. transpose_critical_parameters(dstinfo);
  173854. if (info->trim)
  173855. trim_bottom_edge(dstinfo);
  173856. break;
  173857. }
  173858. /* Return the appropriate output data set */
  173859. if (info->workspace_coef_arrays != NULL)
  173860. return info->workspace_coef_arrays;
  173861. return src_coef_arrays;
  173862. }
  173863. /* Execute the actual transformation, if any.
  173864. *
  173865. * This must be called *after* jpeg_write_coefficients, because it depends
  173866. * on jpeg_write_coefficients to have computed subsidiary values such as
  173867. * the per-component width and height fields in the destination object.
  173868. *
  173869. * Note that some transformations will modify the source data arrays!
  173870. */
  173871. GLOBAL(void)
  173872. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  173873. j_compress_ptr dstinfo,
  173874. jvirt_barray_ptr *src_coef_arrays,
  173875. jpeg_transform_info *info)
  173876. {
  173877. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  173878. switch (info->transform) {
  173879. case JXFORM_NONE:
  173880. break;
  173881. case JXFORM_FLIP_H:
  173882. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  173883. break;
  173884. case JXFORM_FLIP_V:
  173885. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173886. break;
  173887. case JXFORM_TRANSPOSE:
  173888. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173889. break;
  173890. case JXFORM_TRANSVERSE:
  173891. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173892. break;
  173893. case JXFORM_ROT_90:
  173894. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173895. break;
  173896. case JXFORM_ROT_180:
  173897. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173898. break;
  173899. case JXFORM_ROT_270:
  173900. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173901. break;
  173902. }
  173903. }
  173904. #endif /* TRANSFORMS_SUPPORTED */
  173905. /* Setup decompression object to save desired markers in memory.
  173906. * This must be called before jpeg_read_header() to have the desired effect.
  173907. */
  173908. GLOBAL(void)
  173909. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  173910. {
  173911. #ifdef SAVE_MARKERS_SUPPORTED
  173912. int m;
  173913. /* Save comments except under NONE option */
  173914. if (option != JCOPYOPT_NONE) {
  173915. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  173916. }
  173917. /* Save all types of APPn markers iff ALL option */
  173918. if (option == JCOPYOPT_ALL) {
  173919. for (m = 0; m < 16; m++)
  173920. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  173921. }
  173922. #endif /* SAVE_MARKERS_SUPPORTED */
  173923. }
  173924. /* Copy markers saved in the given source object to the destination object.
  173925. * This should be called just after jpeg_start_compress() or
  173926. * jpeg_write_coefficients().
  173927. * Note that those routines will have written the SOI, and also the
  173928. * JFIF APP0 or Adobe APP14 markers if selected.
  173929. */
  173930. GLOBAL(void)
  173931. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173932. JCOPY_OPTION option)
  173933. {
  173934. jpeg_saved_marker_ptr marker;
  173935. /* In the current implementation, we don't actually need to examine the
  173936. * option flag here; we just copy everything that got saved.
  173937. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  173938. * if the encoder library already wrote one.
  173939. */
  173940. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  173941. if (dstinfo->write_JFIF_header &&
  173942. marker->marker == JPEG_APP0 &&
  173943. marker->data_length >= 5 &&
  173944. GETJOCTET(marker->data[0]) == 0x4A &&
  173945. GETJOCTET(marker->data[1]) == 0x46 &&
  173946. GETJOCTET(marker->data[2]) == 0x49 &&
  173947. GETJOCTET(marker->data[3]) == 0x46 &&
  173948. GETJOCTET(marker->data[4]) == 0)
  173949. continue; /* reject duplicate JFIF */
  173950. if (dstinfo->write_Adobe_marker &&
  173951. marker->marker == JPEG_APP0+14 &&
  173952. marker->data_length >= 5 &&
  173953. GETJOCTET(marker->data[0]) == 0x41 &&
  173954. GETJOCTET(marker->data[1]) == 0x64 &&
  173955. GETJOCTET(marker->data[2]) == 0x6F &&
  173956. GETJOCTET(marker->data[3]) == 0x62 &&
  173957. GETJOCTET(marker->data[4]) == 0x65)
  173958. continue; /* reject duplicate Adobe */
  173959. #ifdef NEED_FAR_POINTERS
  173960. /* We could use jpeg_write_marker if the data weren't FAR... */
  173961. {
  173962. unsigned int i;
  173963. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  173964. for (i = 0; i < marker->data_length; i++)
  173965. jpeg_write_m_byte(dstinfo, marker->data[i]);
  173966. }
  173967. #else
  173968. jpeg_write_marker(dstinfo, marker->marker,
  173969. marker->data, marker->data_length);
  173970. #endif
  173971. }
  173972. }
  173973. /********* End of inlined file: transupp.c *********/
  173974. }
  173975. }
  173976. #if JUCE_MSVC
  173977. #pragma warning (pop)
  173978. #endif
  173979. BEGIN_JUCE_NAMESPACE
  173980. using namespace jpeglibNamespace;
  173981. struct JPEGDecodingFailure {};
  173982. static void fatalErrorHandler (j_common_ptr)
  173983. {
  173984. throw JPEGDecodingFailure();
  173985. }
  173986. static void silentErrorCallback1 (j_common_ptr) {}
  173987. static void silentErrorCallback2 (j_common_ptr, int) {}
  173988. static void silentErrorCallback3 (j_common_ptr, char*) {}
  173989. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  173990. {
  173991. zerostruct (err);
  173992. err.error_exit = fatalErrorHandler;
  173993. err.emit_message = silentErrorCallback2;
  173994. err.output_message = silentErrorCallback1;
  173995. err.format_message = silentErrorCallback3;
  173996. err.reset_error_mgr = silentErrorCallback1;
  173997. }
  173998. static void dummyCallback1 (j_decompress_ptr) throw()
  173999. {
  174000. }
  174001. static void jpegSkip (j_decompress_ptr decompStruct, long num) throw()
  174002. {
  174003. decompStruct->src->next_input_byte += num;
  174004. num = jmin (num, (int) decompStruct->src->bytes_in_buffer);
  174005. decompStruct->src->bytes_in_buffer -= num;
  174006. }
  174007. static boolean jpegFill (j_decompress_ptr) throw()
  174008. {
  174009. return 0;
  174010. }
  174011. Image* juce_loadJPEGImageFromStream (InputStream& in) throw()
  174012. {
  174013. MemoryBlock mb;
  174014. in.readIntoMemoryBlock (mb);
  174015. Image* image = 0;
  174016. if (mb.getSize() > 16)
  174017. {
  174018. struct jpeg_decompress_struct jpegDecompStruct;
  174019. struct jpeg_error_mgr jerr;
  174020. setupSilentErrorHandler (jerr);
  174021. jpegDecompStruct.err = &jerr;
  174022. jpeg_create_decompress (&jpegDecompStruct);
  174023. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  174024. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  174025. jpegDecompStruct.src->init_source = dummyCallback1;
  174026. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  174027. jpegDecompStruct.src->skip_input_data = jpegSkip;
  174028. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  174029. jpegDecompStruct.src->term_source = dummyCallback1;
  174030. jpegDecompStruct.src->next_input_byte = (const unsigned char*) mb.getData();
  174031. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  174032. try
  174033. {
  174034. jpeg_read_header (&jpegDecompStruct, TRUE);
  174035. jpeg_calc_output_dimensions (&jpegDecompStruct);
  174036. const int width = jpegDecompStruct.output_width;
  174037. const int height = jpegDecompStruct.output_height;
  174038. jpegDecompStruct.out_color_space = JCS_RGB;
  174039. JSAMPARRAY buffer
  174040. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  174041. JPOOL_IMAGE,
  174042. width * 3, 1);
  174043. if (jpeg_start_decompress (&jpegDecompStruct))
  174044. {
  174045. image = new Image (Image::RGB, width, height, false);
  174046. for (int y = 0; y < height; ++y)
  174047. {
  174048. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  174049. int stride, pixelStride;
  174050. uint8* pixels = image->lockPixelDataReadWrite (0, y, width, 1, stride, pixelStride);
  174051. const uint8* src = *buffer;
  174052. uint8* dest = pixels;
  174053. for (int i = width; --i >= 0;)
  174054. {
  174055. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  174056. dest += pixelStride;
  174057. src += 3;
  174058. }
  174059. image->releasePixelDataReadWrite (pixels);
  174060. }
  174061. jpeg_finish_decompress (&jpegDecompStruct);
  174062. }
  174063. jpeg_destroy_decompress (&jpegDecompStruct);
  174064. }
  174065. catch (...)
  174066. {}
  174067. }
  174068. return image;
  174069. }
  174070. static const int bufferSize = 512;
  174071. struct JuceJpegDest : public jpeg_destination_mgr
  174072. {
  174073. OutputStream* output;
  174074. char* buffer;
  174075. };
  174076. static void jpegWriteInit (j_compress_ptr) throw()
  174077. {
  174078. }
  174079. static void jpegWriteTerminate (j_compress_ptr cinfo) throw()
  174080. {
  174081. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  174082. const int numToWrite = bufferSize - dest->free_in_buffer;
  174083. dest->output->write (dest->buffer, numToWrite);
  174084. }
  174085. static boolean jpegWriteFlush (j_compress_ptr cinfo) throw()
  174086. {
  174087. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  174088. const int numToWrite = bufferSize;
  174089. dest->next_output_byte = (JOCTET*) dest->buffer;
  174090. dest->free_in_buffer = bufferSize;
  174091. return dest->output->write (dest->buffer, numToWrite);
  174092. }
  174093. bool juce_writeJPEGImageToStream (const Image& image,
  174094. OutputStream& out,
  174095. float quality) throw()
  174096. {
  174097. if (image.hasAlphaChannel())
  174098. {
  174099. // this method could fill the background in white and still save the image..
  174100. jassertfalse
  174101. return true;
  174102. }
  174103. struct jpeg_compress_struct jpegCompStruct;
  174104. struct jpeg_error_mgr jerr;
  174105. setupSilentErrorHandler (jerr);
  174106. jpegCompStruct.err = &jerr;
  174107. jpeg_create_compress (&jpegCompStruct);
  174108. JuceJpegDest dest;
  174109. jpegCompStruct.dest = &dest;
  174110. dest.output = &out;
  174111. dest.buffer = (char*) juce_malloc (bufferSize);
  174112. dest.next_output_byte = (JOCTET*) dest.buffer;
  174113. dest.free_in_buffer = bufferSize;
  174114. dest.init_destination = jpegWriteInit;
  174115. dest.empty_output_buffer = jpegWriteFlush;
  174116. dest.term_destination = jpegWriteTerminate;
  174117. jpegCompStruct.image_width = image.getWidth();
  174118. jpegCompStruct.image_height = image.getHeight();
  174119. jpegCompStruct.input_components = 3;
  174120. jpegCompStruct.in_color_space = JCS_RGB;
  174121. jpegCompStruct.write_JFIF_header = 1;
  174122. jpegCompStruct.X_density = 72;
  174123. jpegCompStruct.Y_density = 72;
  174124. jpeg_set_defaults (&jpegCompStruct);
  174125. jpegCompStruct.dct_method = JDCT_FLOAT;
  174126. jpegCompStruct.optimize_coding = 1;
  174127. // jpegCompStruct.smoothing_factor = 10;
  174128. if (quality < 0.0f)
  174129. quality = 6.0f;
  174130. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundFloatToInt (quality * 100.0f)), TRUE);
  174131. jpeg_start_compress (&jpegCompStruct, TRUE);
  174132. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  174133. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  174134. JPOOL_IMAGE,
  174135. strideBytes, 1);
  174136. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  174137. {
  174138. int stride, pixelStride;
  174139. const uint8* pixels = image.lockPixelDataReadOnly (0, jpegCompStruct.next_scanline, jpegCompStruct.image_width, 1, stride, pixelStride);
  174140. const uint8* src = pixels;
  174141. uint8* dst = *buffer;
  174142. for (int i = jpegCompStruct.image_width; --i >= 0;)
  174143. {
  174144. *dst++ = ((const PixelRGB*) src)->getRed();
  174145. *dst++ = ((const PixelRGB*) src)->getGreen();
  174146. *dst++ = ((const PixelRGB*) src)->getBlue();
  174147. src += pixelStride;
  174148. }
  174149. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  174150. image.releasePixelDataReadOnly (pixels);
  174151. }
  174152. jpeg_finish_compress (&jpegCompStruct);
  174153. jpeg_destroy_compress (&jpegCompStruct);
  174154. juce_free (dest.buffer);
  174155. out.flush();
  174156. return true;
  174157. }
  174158. END_JUCE_NAMESPACE
  174159. /********* End of inlined file: juce_JPEGLoader.cpp *********/
  174160. /********* Start of inlined file: juce_PNGLoader.cpp *********/
  174161. #ifdef _MSC_VER
  174162. #pragma warning (push)
  174163. #pragma warning (disable: 4390 4611)
  174164. #endif
  174165. namespace zlibNamespace
  174166. {
  174167. #undef OS_CODE
  174168. #undef fdopen
  174169. #undef OS_CODE
  174170. }
  174171. namespace pnglibNamespace
  174172. {
  174173. using namespace zlibNamespace;
  174174. using ::malloc;
  174175. using ::free;
  174176. extern "C"
  174177. {
  174178. using ::abs;
  174179. #define PNG_INTERNAL
  174180. #define NO_DUMMY_DECL
  174181. #define PNG_SETJMP_NOT_SUPPORTED
  174182. /********* Start of inlined file: png.h *********/
  174183. /* png.h - header file for PNG reference library
  174184. *
  174185. * libpng version 1.2.21 - October 4, 2007
  174186. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  174187. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  174188. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  174189. *
  174190. * Authors and maintainers:
  174191. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  174192. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  174193. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  174194. * See also "Contributing Authors", below.
  174195. *
  174196. * Note about libpng version numbers:
  174197. *
  174198. * Due to various miscommunications, unforeseen code incompatibilities
  174199. * and occasional factors outside the authors' control, version numbering
  174200. * on the library has not always been consistent and straightforward.
  174201. * The following table summarizes matters since version 0.89c, which was
  174202. * the first widely used release:
  174203. *
  174204. * source png.h png.h shared-lib
  174205. * version string int version
  174206. * ------- ------ ----- ----------
  174207. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  174208. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  174209. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  174210. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  174211. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  174212. * 0.97c 0.97 97 2.0.97
  174213. * 0.98 0.98 98 2.0.98
  174214. * 0.99 0.99 98 2.0.99
  174215. * 0.99a-m 0.99 99 2.0.99
  174216. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  174217. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  174218. * 1.0.1 png.h string is 10001 2.1.0
  174219. * 1.0.1a-e identical to the 10002 from here on, the shared library
  174220. * 1.0.2 source version) 10002 is 2.V where V is the source code
  174221. * 1.0.2a-b 10003 version, except as noted.
  174222. * 1.0.3 10003
  174223. * 1.0.3a-d 10004
  174224. * 1.0.4 10004
  174225. * 1.0.4a-f 10005
  174226. * 1.0.5 (+ 2 patches) 10005
  174227. * 1.0.5a-d 10006
  174228. * 1.0.5e-r 10100 (not source compatible)
  174229. * 1.0.5s-v 10006 (not binary compatible)
  174230. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  174231. * 1.0.6d-f 10007 (still binary incompatible)
  174232. * 1.0.6g 10007
  174233. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  174234. * 1.0.6i 10007 10.6i
  174235. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  174236. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  174237. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  174238. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  174239. * 1.0.7 1 10007 (still compatible)
  174240. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  174241. * 1.0.8rc1 1 10008 2.1.0.8rc1
  174242. * 1.0.8 1 10008 2.1.0.8
  174243. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  174244. * 1.0.9rc1 1 10009 2.1.0.9rc1
  174245. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  174246. * 1.0.9rc2 1 10009 2.1.0.9rc2
  174247. * 1.0.9 1 10009 2.1.0.9
  174248. * 1.0.10beta1 1 10010 2.1.0.10beta1
  174249. * 1.0.10rc1 1 10010 2.1.0.10rc1
  174250. * 1.0.10 1 10010 2.1.0.10
  174251. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  174252. * 1.0.11rc1 1 10011 2.1.0.11rc1
  174253. * 1.0.11 1 10011 2.1.0.11
  174254. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  174255. * 1.0.12rc1 2 10012 2.1.0.12rc1
  174256. * 1.0.12 2 10012 2.1.0.12
  174257. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  174258. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  174259. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  174260. * 1.2.0rc1 3 10200 3.1.2.0rc1
  174261. * 1.2.0 3 10200 3.1.2.0
  174262. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  174263. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  174264. * 1.2.1 3 10201 3.1.2.1
  174265. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  174266. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  174267. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  174268. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  174269. * 1.0.13 10 10013 10.so.0.1.0.13
  174270. * 1.2.2 12 10202 12.so.0.1.2.2
  174271. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  174272. * 1.2.3 12 10203 12.so.0.1.2.3
  174273. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  174274. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  174275. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  174276. * 1.0.14 10 10014 10.so.0.1.0.14
  174277. * 1.2.4 13 10204 12.so.0.1.2.4
  174278. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  174279. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  174280. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  174281. * 1.0.15 10 10015 10.so.0.1.0.15
  174282. * 1.2.5 13 10205 12.so.0.1.2.5
  174283. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  174284. * 1.0.16 10 10016 10.so.0.1.0.16
  174285. * 1.2.6 13 10206 12.so.0.1.2.6
  174286. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  174287. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  174288. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  174289. * 1.0.17 10 10017 10.so.0.1.0.17
  174290. * 1.2.7 13 10207 12.so.0.1.2.7
  174291. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  174292. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  174293. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  174294. * 1.0.18 10 10018 10.so.0.1.0.18
  174295. * 1.2.8 13 10208 12.so.0.1.2.8
  174296. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  174297. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  174298. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  174299. * 1.2.9 13 10209 12.so.0.9[.0]
  174300. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  174301. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  174302. * 1.2.10 13 10210 12.so.0.10[.0]
  174303. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  174304. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  174305. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  174306. * 1.0.19 10 10019 10.so.0.19[.0]
  174307. * 1.2.11 13 10211 12.so.0.11[.0]
  174308. * 1.0.20 10 10020 10.so.0.20[.0]
  174309. * 1.2.12 13 10212 12.so.0.12[.0]
  174310. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  174311. * 1.0.21 10 10021 10.so.0.21[.0]
  174312. * 1.2.13 13 10213 12.so.0.13[.0]
  174313. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  174314. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  174315. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  174316. * 1.0.22 10 10022 10.so.0.22[.0]
  174317. * 1.2.14 13 10214 12.so.0.14[.0]
  174318. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  174319. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  174320. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  174321. * 1.0.23 10 10023 10.so.0.23[.0]
  174322. * 1.2.15 13 10215 12.so.0.15[.0]
  174323. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  174324. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  174325. * 1.0.24 10 10024 10.so.0.24[.0]
  174326. * 1.2.16 13 10216 12.so.0.16[.0]
  174327. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  174328. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  174329. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  174330. * 1.0.25 10 10025 10.so.0.25[.0]
  174331. * 1.2.17 13 10217 12.so.0.17[.0]
  174332. * 1.0.26 10 10026 10.so.0.26[.0]
  174333. * 1.2.18 13 10218 12.so.0.18[.0]
  174334. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  174335. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  174336. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  174337. * 1.0.27 10 10027 10.so.0.27[.0]
  174338. * 1.2.19 13 10219 12.so.0.19[.0]
  174339. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  174340. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  174341. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  174342. * 1.0.28 10 10028 10.so.0.28[.0]
  174343. * 1.2.20 13 10220 12.so.0.20[.0]
  174344. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  174345. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  174346. * 1.0.29 10 10029 10.so.0.29[.0]
  174347. * 1.2.21 13 10221 12.so.0.21[.0]
  174348. *
  174349. * Henceforth the source version will match the shared-library major
  174350. * and minor numbers; the shared-library major version number will be
  174351. * used for changes in backward compatibility, as it is intended. The
  174352. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  174353. * for applications, is an unsigned integer of the form xyyzz corresponding
  174354. * to the source version x.y.z (leading zeros in y and z). Beta versions
  174355. * were given the previous public release number plus a letter, until
  174356. * version 1.0.6j; from then on they were given the upcoming public
  174357. * release number plus "betaNN" or "rcN".
  174358. *
  174359. * Binary incompatibility exists only when applications make direct access
  174360. * to the info_ptr or png_ptr members through png.h, and the compiled
  174361. * application is loaded with a different version of the library.
  174362. *
  174363. * DLLNUM will change each time there are forward or backward changes
  174364. * in binary compatibility (e.g., when a new feature is added).
  174365. *
  174366. * See libpng.txt or libpng.3 for more information. The PNG specification
  174367. * is available as a W3C Recommendation and as an ISO Specification,
  174368. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  174369. */
  174370. /*
  174371. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  174372. *
  174373. * If you modify libpng you may insert additional notices immediately following
  174374. * this sentence.
  174375. *
  174376. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  174377. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  174378. * distributed according to the same disclaimer and license as libpng-1.2.5
  174379. * with the following individual added to the list of Contributing Authors:
  174380. *
  174381. * Cosmin Truta
  174382. *
  174383. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  174384. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  174385. * distributed according to the same disclaimer and license as libpng-1.0.6
  174386. * with the following individuals added to the list of Contributing Authors:
  174387. *
  174388. * Simon-Pierre Cadieux
  174389. * Eric S. Raymond
  174390. * Gilles Vollant
  174391. *
  174392. * and with the following additions to the disclaimer:
  174393. *
  174394. * There is no warranty against interference with your enjoyment of the
  174395. * library or against infringement. There is no warranty that our
  174396. * efforts or the library will fulfill any of your particular purposes
  174397. * or needs. This library is provided with all faults, and the entire
  174398. * risk of satisfactory quality, performance, accuracy, and effort is with
  174399. * the user.
  174400. *
  174401. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  174402. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  174403. * distributed according to the same disclaimer and license as libpng-0.96,
  174404. * with the following individuals added to the list of Contributing Authors:
  174405. *
  174406. * Tom Lane
  174407. * Glenn Randers-Pehrson
  174408. * Willem van Schaik
  174409. *
  174410. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  174411. * Copyright (c) 1996, 1997 Andreas Dilger
  174412. * Distributed according to the same disclaimer and license as libpng-0.88,
  174413. * with the following individuals added to the list of Contributing Authors:
  174414. *
  174415. * John Bowler
  174416. * Kevin Bracey
  174417. * Sam Bushell
  174418. * Magnus Holmgren
  174419. * Greg Roelofs
  174420. * Tom Tanner
  174421. *
  174422. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  174423. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  174424. *
  174425. * For the purposes of this copyright and license, "Contributing Authors"
  174426. * is defined as the following set of individuals:
  174427. *
  174428. * Andreas Dilger
  174429. * Dave Martindale
  174430. * Guy Eric Schalnat
  174431. * Paul Schmidt
  174432. * Tim Wegner
  174433. *
  174434. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  174435. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  174436. * including, without limitation, the warranties of merchantability and of
  174437. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  174438. * assume no liability for direct, indirect, incidental, special, exemplary,
  174439. * or consequential damages, which may result from the use of the PNG
  174440. * Reference Library, even if advised of the possibility of such damage.
  174441. *
  174442. * Permission is hereby granted to use, copy, modify, and distribute this
  174443. * source code, or portions hereof, for any purpose, without fee, subject
  174444. * to the following restrictions:
  174445. *
  174446. * 1. The origin of this source code must not be misrepresented.
  174447. *
  174448. * 2. Altered versions must be plainly marked as such and
  174449. * must not be misrepresented as being the original source.
  174450. *
  174451. * 3. This Copyright notice may not be removed or altered from
  174452. * any source or altered source distribution.
  174453. *
  174454. * The Contributing Authors and Group 42, Inc. specifically permit, without
  174455. * fee, and encourage the use of this source code as a component to
  174456. * supporting the PNG file format in commercial products. If you use this
  174457. * source code in a product, acknowledgment is not required but would be
  174458. * appreciated.
  174459. */
  174460. /*
  174461. * A "png_get_copyright" function is available, for convenient use in "about"
  174462. * boxes and the like:
  174463. *
  174464. * printf("%s",png_get_copyright(NULL));
  174465. *
  174466. * Also, the PNG logo (in PNG format, of course) is supplied in the
  174467. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  174468. */
  174469. /*
  174470. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  174471. * certification mark of the Open Source Initiative.
  174472. */
  174473. /*
  174474. * The contributing authors would like to thank all those who helped
  174475. * with testing, bug fixes, and patience. This wouldn't have been
  174476. * possible without all of you.
  174477. *
  174478. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  174479. */
  174480. /*
  174481. * Y2K compliance in libpng:
  174482. * =========================
  174483. *
  174484. * October 4, 2007
  174485. *
  174486. * Since the PNG Development group is an ad-hoc body, we can't make
  174487. * an official declaration.
  174488. *
  174489. * This is your unofficial assurance that libpng from version 0.71 and
  174490. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  174491. * versions were also Y2K compliant.
  174492. *
  174493. * Libpng only has three year fields. One is a 2-byte unsigned integer
  174494. * that will hold years up to 65535. The other two hold the date in text
  174495. * format, and will hold years up to 9999.
  174496. *
  174497. * The integer is
  174498. * "png_uint_16 year" in png_time_struct.
  174499. *
  174500. * The strings are
  174501. * "png_charp time_buffer" in png_struct and
  174502. * "near_time_buffer", which is a local character string in png.c.
  174503. *
  174504. * There are seven time-related functions:
  174505. * png.c: png_convert_to_rfc_1123() in png.c
  174506. * (formerly png_convert_to_rfc_1152() in error)
  174507. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  174508. * png_convert_from_time_t() in pngwrite.c
  174509. * png_get_tIME() in pngget.c
  174510. * png_handle_tIME() in pngrutil.c, called in pngread.c
  174511. * png_set_tIME() in pngset.c
  174512. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  174513. *
  174514. * All handle dates properly in a Y2K environment. The
  174515. * png_convert_from_time_t() function calls gmtime() to convert from system
  174516. * clock time, which returns (year - 1900), which we properly convert to
  174517. * the full 4-digit year. There is a possibility that applications using
  174518. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  174519. * function, or that they are incorrectly passing only a 2-digit year
  174520. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  174521. * but this is not under our control. The libpng documentation has always
  174522. * stated that it works with 4-digit years, and the APIs have been
  174523. * documented as such.
  174524. *
  174525. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  174526. * integer to hold the year, and can hold years as large as 65535.
  174527. *
  174528. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  174529. * no date-related code.
  174530. *
  174531. * Glenn Randers-Pehrson
  174532. * libpng maintainer
  174533. * PNG Development Group
  174534. */
  174535. #ifndef PNG_H
  174536. #define PNG_H
  174537. /* This is not the place to learn how to use libpng. The file libpng.txt
  174538. * describes how to use libpng, and the file example.c summarizes it
  174539. * with some code on which to build. This file is useful for looking
  174540. * at the actual function definitions and structure components.
  174541. */
  174542. /* Version information for png.h - this should match the version in png.c */
  174543. #define PNG_LIBPNG_VER_STRING "1.2.21"
  174544. #define PNG_HEADER_VERSION_STRING \
  174545. " libpng version 1.2.21 - October 4, 2007\n"
  174546. #define PNG_LIBPNG_VER_SONUM 0
  174547. #define PNG_LIBPNG_VER_DLLNUM 13
  174548. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  174549. #define PNG_LIBPNG_VER_MAJOR 1
  174550. #define PNG_LIBPNG_VER_MINOR 2
  174551. #define PNG_LIBPNG_VER_RELEASE 21
  174552. /* This should match the numeric part of the final component of
  174553. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  174554. #define PNG_LIBPNG_VER_BUILD 0
  174555. /* Release Status */
  174556. #define PNG_LIBPNG_BUILD_ALPHA 1
  174557. #define PNG_LIBPNG_BUILD_BETA 2
  174558. #define PNG_LIBPNG_BUILD_RC 3
  174559. #define PNG_LIBPNG_BUILD_STABLE 4
  174560. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  174561. /* Release-Specific Flags */
  174562. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  174563. PNG_LIBPNG_BUILD_STABLE only */
  174564. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  174565. PNG_LIBPNG_BUILD_SPECIAL */
  174566. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  174567. PNG_LIBPNG_BUILD_PRIVATE */
  174568. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  174569. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  174570. * We must not include leading zeros.
  174571. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  174572. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  174573. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  174574. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  174575. #ifndef PNG_VERSION_INFO_ONLY
  174576. /* include the compression library's header */
  174577. #endif
  174578. /* include all user configurable info, including optional assembler routines */
  174579. /********* Start of inlined file: pngconf.h *********/
  174580. /* pngconf.h - machine configurable file for libpng
  174581. *
  174582. * libpng version 1.2.21 - October 4, 2007
  174583. * For conditions of distribution and use, see copyright notice in png.h
  174584. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  174585. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  174586. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  174587. */
  174588. /* Any machine specific code is near the front of this file, so if you
  174589. * are configuring libpng for a machine, you may want to read the section
  174590. * starting here down to where it starts to typedef png_color, png_text,
  174591. * and png_info.
  174592. */
  174593. #ifndef PNGCONF_H
  174594. #define PNGCONF_H
  174595. #define PNG_1_2_X
  174596. // These are some Juce config settings that should remove any unnecessary code bloat..
  174597. #define PNG_NO_STDIO 1
  174598. #define PNG_DEBUG 0
  174599. #define PNG_NO_WARNINGS 1
  174600. #define PNG_NO_ERROR_TEXT 1
  174601. #define PNG_NO_ERROR_NUMBERS 1
  174602. #define PNG_NO_USER_MEM 1
  174603. #define PNG_NO_READ_iCCP 1
  174604. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  174605. #define PNG_NO_READ_USER_CHUNKS 1
  174606. #define PNG_NO_READ_iTXt 1
  174607. #define PNG_NO_READ_sCAL 1
  174608. #define PNG_NO_READ_sPLT 1
  174609. #define png_error(a, b) png_err(a)
  174610. #define png_warning(a, b)
  174611. #define png_chunk_error(a, b) png_err(a)
  174612. #define png_chunk_warning(a, b)
  174613. /*
  174614. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  174615. * includes the resource compiler for Windows DLL configurations.
  174616. */
  174617. #ifdef PNG_USER_CONFIG
  174618. # ifndef PNG_USER_PRIVATEBUILD
  174619. # define PNG_USER_PRIVATEBUILD
  174620. # endif
  174621. #include "pngusr.h"
  174622. #endif
  174623. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  174624. #ifdef PNG_CONFIGURE_LIBPNG
  174625. #ifdef HAVE_CONFIG_H
  174626. #include "config.h"
  174627. #endif
  174628. #endif
  174629. /*
  174630. * Added at libpng-1.2.8
  174631. *
  174632. * If you create a private DLL you need to define in "pngusr.h" the followings:
  174633. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  174634. * the DLL was built>
  174635. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  174636. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  174637. * distinguish your DLL from those of the official release. These
  174638. * correspond to the trailing letters that come after the version
  174639. * number and must match your private DLL name>
  174640. * e.g. // private DLL "libpng13gx.dll"
  174641. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  174642. *
  174643. * The following macros are also at your disposal if you want to complete the
  174644. * DLL VERSIONINFO structure.
  174645. * - PNG_USER_VERSIONINFO_COMMENTS
  174646. * - PNG_USER_VERSIONINFO_COMPANYNAME
  174647. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  174648. */
  174649. #ifdef __STDC__
  174650. #ifdef SPECIALBUILD
  174651. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  174652. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  174653. #endif
  174654. #ifdef PRIVATEBUILD
  174655. # pragma message("PRIVATEBUILD is deprecated.\
  174656. Use PNG_USER_PRIVATEBUILD instead.")
  174657. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  174658. #endif
  174659. #endif /* __STDC__ */
  174660. #ifndef PNG_VERSION_INFO_ONLY
  174661. /* End of material added to libpng-1.2.8 */
  174662. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  174663. Restored at libpng-1.2.21 */
  174664. # define PNG_WARN_UNINITIALIZED_ROW 1
  174665. /* End of material added at libpng-1.2.19/1.2.21 */
  174666. /* This is the size of the compression buffer, and thus the size of
  174667. * an IDAT chunk. Make this whatever size you feel is best for your
  174668. * machine. One of these will be allocated per png_struct. When this
  174669. * is full, it writes the data to the disk, and does some other
  174670. * calculations. Making this an extremely small size will slow
  174671. * the library down, but you may want to experiment to determine
  174672. * where it becomes significant, if you are concerned with memory
  174673. * usage. Note that zlib allocates at least 32Kb also. For readers,
  174674. * this describes the size of the buffer available to read the data in.
  174675. * Unless this gets smaller than the size of a row (compressed),
  174676. * it should not make much difference how big this is.
  174677. */
  174678. #ifndef PNG_ZBUF_SIZE
  174679. # define PNG_ZBUF_SIZE 8192
  174680. #endif
  174681. /* Enable if you want a write-only libpng */
  174682. #ifndef PNG_NO_READ_SUPPORTED
  174683. # define PNG_READ_SUPPORTED
  174684. #endif
  174685. /* Enable if you want a read-only libpng */
  174686. #ifndef PNG_NO_WRITE_SUPPORTED
  174687. # define PNG_WRITE_SUPPORTED
  174688. #endif
  174689. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  174690. support PNGs that are embedded in MNG datastreams */
  174691. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  174692. # ifndef PNG_MNG_FEATURES_SUPPORTED
  174693. # define PNG_MNG_FEATURES_SUPPORTED
  174694. # endif
  174695. #endif
  174696. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  174697. # ifndef PNG_FLOATING_POINT_SUPPORTED
  174698. # define PNG_FLOATING_POINT_SUPPORTED
  174699. # endif
  174700. #endif
  174701. /* If you are running on a machine where you cannot allocate more
  174702. * than 64K of memory at once, uncomment this. While libpng will not
  174703. * normally need that much memory in a chunk (unless you load up a very
  174704. * large file), zlib needs to know how big of a chunk it can use, and
  174705. * libpng thus makes sure to check any memory allocation to verify it
  174706. * will fit into memory.
  174707. #define PNG_MAX_MALLOC_64K
  174708. */
  174709. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  174710. # define PNG_MAX_MALLOC_64K
  174711. #endif
  174712. /* Special munging to support doing things the 'cygwin' way:
  174713. * 'Normal' png-on-win32 defines/defaults:
  174714. * PNG_BUILD_DLL -- building dll
  174715. * PNG_USE_DLL -- building an application, linking to dll
  174716. * (no define) -- building static library, or building an
  174717. * application and linking to the static lib
  174718. * 'Cygwin' defines/defaults:
  174719. * PNG_BUILD_DLL -- (ignored) building the dll
  174720. * (no define) -- (ignored) building an application, linking to the dll
  174721. * PNG_STATIC -- (ignored) building the static lib, or building an
  174722. * application that links to the static lib.
  174723. * ALL_STATIC -- (ignored) building various static libs, or building an
  174724. * application that links to the static libs.
  174725. * Thus,
  174726. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  174727. * this bit of #ifdefs will define the 'correct' config variables based on
  174728. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  174729. * unnecessary.
  174730. *
  174731. * Also, the precedence order is:
  174732. * ALL_STATIC (since we can't #undef something outside our namespace)
  174733. * PNG_BUILD_DLL
  174734. * PNG_STATIC
  174735. * (nothing) == PNG_USE_DLL
  174736. *
  174737. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  174738. * of auto-import in binutils, we no longer need to worry about
  174739. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  174740. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  174741. * to __declspec() stuff. However, we DO need to worry about
  174742. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  174743. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  174744. */
  174745. #if defined(__CYGWIN__)
  174746. # if defined(ALL_STATIC)
  174747. # if defined(PNG_BUILD_DLL)
  174748. # undef PNG_BUILD_DLL
  174749. # endif
  174750. # if defined(PNG_USE_DLL)
  174751. # undef PNG_USE_DLL
  174752. # endif
  174753. # if defined(PNG_DLL)
  174754. # undef PNG_DLL
  174755. # endif
  174756. # if !defined(PNG_STATIC)
  174757. # define PNG_STATIC
  174758. # endif
  174759. # else
  174760. # if defined (PNG_BUILD_DLL)
  174761. # if defined(PNG_STATIC)
  174762. # undef PNG_STATIC
  174763. # endif
  174764. # if defined(PNG_USE_DLL)
  174765. # undef PNG_USE_DLL
  174766. # endif
  174767. # if !defined(PNG_DLL)
  174768. # define PNG_DLL
  174769. # endif
  174770. # else
  174771. # if defined(PNG_STATIC)
  174772. # if defined(PNG_USE_DLL)
  174773. # undef PNG_USE_DLL
  174774. # endif
  174775. # if defined(PNG_DLL)
  174776. # undef PNG_DLL
  174777. # endif
  174778. # else
  174779. # if !defined(PNG_USE_DLL)
  174780. # define PNG_USE_DLL
  174781. # endif
  174782. # if !defined(PNG_DLL)
  174783. # define PNG_DLL
  174784. # endif
  174785. # endif
  174786. # endif
  174787. # endif
  174788. #endif
  174789. /* This protects us against compilers that run on a windowing system
  174790. * and thus don't have or would rather us not use the stdio types:
  174791. * stdin, stdout, and stderr. The only one currently used is stderr
  174792. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  174793. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  174794. * will also prevent these, plus will prevent the entire set of stdio
  174795. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  174796. * unless (PNG_DEBUG > 0) has been #defined.
  174797. *
  174798. * #define PNG_NO_CONSOLE_IO
  174799. * #define PNG_NO_STDIO
  174800. */
  174801. #if defined(_WIN32_WCE)
  174802. # include <windows.h>
  174803. /* Console I/O functions are not supported on WindowsCE */
  174804. # define PNG_NO_CONSOLE_IO
  174805. # ifdef PNG_DEBUG
  174806. # undef PNG_DEBUG
  174807. # endif
  174808. #endif
  174809. #ifdef PNG_BUILD_DLL
  174810. # ifndef PNG_CONSOLE_IO_SUPPORTED
  174811. # ifndef PNG_NO_CONSOLE_IO
  174812. # define PNG_NO_CONSOLE_IO
  174813. # endif
  174814. # endif
  174815. #endif
  174816. # ifdef PNG_NO_STDIO
  174817. # ifndef PNG_NO_CONSOLE_IO
  174818. # define PNG_NO_CONSOLE_IO
  174819. # endif
  174820. # ifdef PNG_DEBUG
  174821. # if (PNG_DEBUG > 0)
  174822. # include <stdio.h>
  174823. # endif
  174824. # endif
  174825. # else
  174826. # if !defined(_WIN32_WCE)
  174827. /* "stdio.h" functions are not supported on WindowsCE */
  174828. # include <stdio.h>
  174829. # endif
  174830. # endif
  174831. /* This macro protects us against machines that don't have function
  174832. * prototypes (ie K&R style headers). If your compiler does not handle
  174833. * function prototypes, define this macro and use the included ansi2knr.
  174834. * I've always been able to use _NO_PROTO as the indicator, but you may
  174835. * need to drag the empty declaration out in front of here, or change the
  174836. * ifdef to suit your own needs.
  174837. */
  174838. #ifndef PNGARG
  174839. #ifdef OF /* zlib prototype munger */
  174840. # define PNGARG(arglist) OF(arglist)
  174841. #else
  174842. #ifdef _NO_PROTO
  174843. # define PNGARG(arglist) ()
  174844. # ifndef PNG_TYPECAST_NULL
  174845. # define PNG_TYPECAST_NULL
  174846. # endif
  174847. #else
  174848. # define PNGARG(arglist) arglist
  174849. #endif /* _NO_PROTO */
  174850. #endif /* OF */
  174851. #endif /* PNGARG */
  174852. /* Try to determine if we are compiling on a Mac. Note that testing for
  174853. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  174854. * on non-Mac platforms.
  174855. */
  174856. #ifndef MACOS
  174857. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  174858. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  174859. # define MACOS
  174860. # endif
  174861. #endif
  174862. /* enough people need this for various reasons to include it here */
  174863. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  174864. # include <sys/types.h>
  174865. #endif
  174866. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  174867. # define PNG_SETJMP_SUPPORTED
  174868. #endif
  174869. #ifdef PNG_SETJMP_SUPPORTED
  174870. /* This is an attempt to force a single setjmp behaviour on Linux. If
  174871. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  174872. */
  174873. # ifdef __linux__
  174874. # ifdef _BSD_SOURCE
  174875. # define PNG_SAVE_BSD_SOURCE
  174876. # undef _BSD_SOURCE
  174877. # endif
  174878. # ifdef _SETJMP_H
  174879. /* If you encounter a compiler error here, see the explanation
  174880. * near the end of INSTALL.
  174881. */
  174882. __png.h__ already includes setjmp.h;
  174883. __dont__ include it again.;
  174884. # endif
  174885. # endif /* __linux__ */
  174886. /* include setjmp.h for error handling */
  174887. # include <setjmp.h>
  174888. # ifdef __linux__
  174889. # ifdef PNG_SAVE_BSD_SOURCE
  174890. # define _BSD_SOURCE
  174891. # undef PNG_SAVE_BSD_SOURCE
  174892. # endif
  174893. # endif /* __linux__ */
  174894. #endif /* PNG_SETJMP_SUPPORTED */
  174895. #ifdef BSD
  174896. # include <strings.h>
  174897. #else
  174898. # include <string.h>
  174899. #endif
  174900. /* Other defines for things like memory and the like can go here. */
  174901. #ifdef PNG_INTERNAL
  174902. #include <stdlib.h>
  174903. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  174904. * aren't usually used outside the library (as far as I know), so it is
  174905. * debatable if they should be exported at all. In the future, when it is
  174906. * possible to have run-time registry of chunk-handling functions, some of
  174907. * these will be made available again.
  174908. #define PNG_EXTERN extern
  174909. */
  174910. #define PNG_EXTERN
  174911. /* Other defines specific to compilers can go here. Try to keep
  174912. * them inside an appropriate ifdef/endif pair for portability.
  174913. */
  174914. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  174915. # if defined(MACOS)
  174916. /* We need to check that <math.h> hasn't already been included earlier
  174917. * as it seems it doesn't agree with <fp.h>, yet we should really use
  174918. * <fp.h> if possible.
  174919. */
  174920. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  174921. # include <fp.h>
  174922. # endif
  174923. # else
  174924. # include <math.h>
  174925. # endif
  174926. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  174927. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  174928. * MATH=68881
  174929. */
  174930. # include <m68881.h>
  174931. # endif
  174932. #endif
  174933. /* Codewarrior on NT has linking problems without this. */
  174934. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  174935. # define PNG_ALWAYS_EXTERN
  174936. #endif
  174937. /* This provides the non-ANSI (far) memory allocation routines. */
  174938. #if defined(__TURBOC__) && defined(__MSDOS__)
  174939. # include <mem.h>
  174940. # include <alloc.h>
  174941. #endif
  174942. /* I have no idea why is this necessary... */
  174943. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  174944. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  174945. # include <malloc.h>
  174946. #endif
  174947. /* This controls how fine the dithering gets. As this allocates
  174948. * a largish chunk of memory (32K), those who are not as concerned
  174949. * with dithering quality can decrease some or all of these.
  174950. */
  174951. #ifndef PNG_DITHER_RED_BITS
  174952. # define PNG_DITHER_RED_BITS 5
  174953. #endif
  174954. #ifndef PNG_DITHER_GREEN_BITS
  174955. # define PNG_DITHER_GREEN_BITS 5
  174956. #endif
  174957. #ifndef PNG_DITHER_BLUE_BITS
  174958. # define PNG_DITHER_BLUE_BITS 5
  174959. #endif
  174960. /* This controls how fine the gamma correction becomes when you
  174961. * are only interested in 8 bits anyway. Increasing this value
  174962. * results in more memory being used, and more pow() functions
  174963. * being called to fill in the gamma tables. Don't set this value
  174964. * less then 8, and even that may not work (I haven't tested it).
  174965. */
  174966. #ifndef PNG_MAX_GAMMA_8
  174967. # define PNG_MAX_GAMMA_8 11
  174968. #endif
  174969. /* This controls how much a difference in gamma we can tolerate before
  174970. * we actually start doing gamma conversion.
  174971. */
  174972. #ifndef PNG_GAMMA_THRESHOLD
  174973. # define PNG_GAMMA_THRESHOLD 0.05
  174974. #endif
  174975. #endif /* PNG_INTERNAL */
  174976. /* The following uses const char * instead of char * for error
  174977. * and warning message functions, so some compilers won't complain.
  174978. * If you do not want to use const, define PNG_NO_CONST here.
  174979. */
  174980. #ifndef PNG_NO_CONST
  174981. # define PNG_CONST const
  174982. #else
  174983. # define PNG_CONST
  174984. #endif
  174985. /* The following defines give you the ability to remove code from the
  174986. * library that you will not be using. I wish I could figure out how to
  174987. * automate this, but I can't do that without making it seriously hard
  174988. * on the users. So if you are not using an ability, change the #define
  174989. * to and #undef, and that part of the library will not be compiled. If
  174990. * your linker can't find a function, you may want to make sure the
  174991. * ability is defined here. Some of these depend upon some others being
  174992. * defined. I haven't figured out all the interactions here, so you may
  174993. * have to experiment awhile to get everything to compile. If you are
  174994. * creating or using a shared library, you probably shouldn't touch this,
  174995. * as it will affect the size of the structures, and this will cause bad
  174996. * things to happen if the library and/or application ever change.
  174997. */
  174998. /* Any features you will not be using can be undef'ed here */
  174999. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  175000. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  175001. * on the compile line, then pick and choose which ones to define without
  175002. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  175003. * if you only want to have a png-compliant reader/writer but don't need
  175004. * any of the extra transformations. This saves about 80 kbytes in a
  175005. * typical installation of the library. (PNG_NO_* form added in version
  175006. * 1.0.1c, for consistency)
  175007. */
  175008. /* The size of the png_text structure changed in libpng-1.0.6 when
  175009. * iTXt support was added. iTXt support was turned off by default through
  175010. * libpng-1.2.x, to support old apps that malloc the png_text structure
  175011. * instead of calling png_set_text() and letting libpng malloc it. It
  175012. * was turned on by default in libpng-1.3.0.
  175013. */
  175014. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  175015. # ifndef PNG_NO_iTXt_SUPPORTED
  175016. # define PNG_NO_iTXt_SUPPORTED
  175017. # endif
  175018. # ifndef PNG_NO_READ_iTXt
  175019. # define PNG_NO_READ_iTXt
  175020. # endif
  175021. # ifndef PNG_NO_WRITE_iTXt
  175022. # define PNG_NO_WRITE_iTXt
  175023. # endif
  175024. #endif
  175025. #if !defined(PNG_NO_iTXt_SUPPORTED)
  175026. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  175027. # define PNG_READ_iTXt
  175028. # endif
  175029. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  175030. # define PNG_WRITE_iTXt
  175031. # endif
  175032. #endif
  175033. /* The following support, added after version 1.0.0, can be turned off here en
  175034. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  175035. * with old applications that require the length of png_struct and png_info
  175036. * to remain unchanged.
  175037. */
  175038. #ifdef PNG_LEGACY_SUPPORTED
  175039. # define PNG_NO_FREE_ME
  175040. # define PNG_NO_READ_UNKNOWN_CHUNKS
  175041. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  175042. # define PNG_NO_READ_USER_CHUNKS
  175043. # define PNG_NO_READ_iCCP
  175044. # define PNG_NO_WRITE_iCCP
  175045. # define PNG_NO_READ_iTXt
  175046. # define PNG_NO_WRITE_iTXt
  175047. # define PNG_NO_READ_sCAL
  175048. # define PNG_NO_WRITE_sCAL
  175049. # define PNG_NO_READ_sPLT
  175050. # define PNG_NO_WRITE_sPLT
  175051. # define PNG_NO_INFO_IMAGE
  175052. # define PNG_NO_READ_RGB_TO_GRAY
  175053. # define PNG_NO_READ_USER_TRANSFORM
  175054. # define PNG_NO_WRITE_USER_TRANSFORM
  175055. # define PNG_NO_USER_MEM
  175056. # define PNG_NO_READ_EMPTY_PLTE
  175057. # define PNG_NO_MNG_FEATURES
  175058. # define PNG_NO_FIXED_POINT_SUPPORTED
  175059. #endif
  175060. /* Ignore attempt to turn off both floating and fixed point support */
  175061. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  175062. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  175063. # define PNG_FIXED_POINT_SUPPORTED
  175064. #endif
  175065. #ifndef PNG_NO_FREE_ME
  175066. # define PNG_FREE_ME_SUPPORTED
  175067. #endif
  175068. #if defined(PNG_READ_SUPPORTED)
  175069. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  175070. !defined(PNG_NO_READ_TRANSFORMS)
  175071. # define PNG_READ_TRANSFORMS_SUPPORTED
  175072. #endif
  175073. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  175074. # ifndef PNG_NO_READ_EXPAND
  175075. # define PNG_READ_EXPAND_SUPPORTED
  175076. # endif
  175077. # ifndef PNG_NO_READ_SHIFT
  175078. # define PNG_READ_SHIFT_SUPPORTED
  175079. # endif
  175080. # ifndef PNG_NO_READ_PACK
  175081. # define PNG_READ_PACK_SUPPORTED
  175082. # endif
  175083. # ifndef PNG_NO_READ_BGR
  175084. # define PNG_READ_BGR_SUPPORTED
  175085. # endif
  175086. # ifndef PNG_NO_READ_SWAP
  175087. # define PNG_READ_SWAP_SUPPORTED
  175088. # endif
  175089. # ifndef PNG_NO_READ_PACKSWAP
  175090. # define PNG_READ_PACKSWAP_SUPPORTED
  175091. # endif
  175092. # ifndef PNG_NO_READ_INVERT
  175093. # define PNG_READ_INVERT_SUPPORTED
  175094. # endif
  175095. # ifndef PNG_NO_READ_DITHER
  175096. # define PNG_READ_DITHER_SUPPORTED
  175097. # endif
  175098. # ifndef PNG_NO_READ_BACKGROUND
  175099. # define PNG_READ_BACKGROUND_SUPPORTED
  175100. # endif
  175101. # ifndef PNG_NO_READ_16_TO_8
  175102. # define PNG_READ_16_TO_8_SUPPORTED
  175103. # endif
  175104. # ifndef PNG_NO_READ_FILLER
  175105. # define PNG_READ_FILLER_SUPPORTED
  175106. # endif
  175107. # ifndef PNG_NO_READ_GAMMA
  175108. # define PNG_READ_GAMMA_SUPPORTED
  175109. # endif
  175110. # ifndef PNG_NO_READ_GRAY_TO_RGB
  175111. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  175112. # endif
  175113. # ifndef PNG_NO_READ_SWAP_ALPHA
  175114. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  175115. # endif
  175116. # ifndef PNG_NO_READ_INVERT_ALPHA
  175117. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  175118. # endif
  175119. # ifndef PNG_NO_READ_STRIP_ALPHA
  175120. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  175121. # endif
  175122. # ifndef PNG_NO_READ_USER_TRANSFORM
  175123. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  175124. # endif
  175125. # ifndef PNG_NO_READ_RGB_TO_GRAY
  175126. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  175127. # endif
  175128. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  175129. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  175130. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  175131. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  175132. #endif /* about interlacing capability! You'll */
  175133. /* still have interlacing unless you change the following line: */
  175134. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  175135. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  175136. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  175137. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  175138. # endif
  175139. #endif
  175140. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  175141. /* Deprecated, will be removed from version 2.0.0.
  175142. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  175143. #ifndef PNG_NO_READ_EMPTY_PLTE
  175144. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  175145. #endif
  175146. #endif
  175147. #endif /* PNG_READ_SUPPORTED */
  175148. #if defined(PNG_WRITE_SUPPORTED)
  175149. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  175150. !defined(PNG_NO_WRITE_TRANSFORMS)
  175151. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  175152. #endif
  175153. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  175154. # ifndef PNG_NO_WRITE_SHIFT
  175155. # define PNG_WRITE_SHIFT_SUPPORTED
  175156. # endif
  175157. # ifndef PNG_NO_WRITE_PACK
  175158. # define PNG_WRITE_PACK_SUPPORTED
  175159. # endif
  175160. # ifndef PNG_NO_WRITE_BGR
  175161. # define PNG_WRITE_BGR_SUPPORTED
  175162. # endif
  175163. # ifndef PNG_NO_WRITE_SWAP
  175164. # define PNG_WRITE_SWAP_SUPPORTED
  175165. # endif
  175166. # ifndef PNG_NO_WRITE_PACKSWAP
  175167. # define PNG_WRITE_PACKSWAP_SUPPORTED
  175168. # endif
  175169. # ifndef PNG_NO_WRITE_INVERT
  175170. # define PNG_WRITE_INVERT_SUPPORTED
  175171. # endif
  175172. # ifndef PNG_NO_WRITE_FILLER
  175173. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  175174. # endif
  175175. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  175176. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  175177. # endif
  175178. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  175179. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  175180. # endif
  175181. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  175182. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  175183. # endif
  175184. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  175185. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  175186. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  175187. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  175188. encoders, but can cause trouble
  175189. if left undefined */
  175190. #endif
  175191. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  175192. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  175193. defined(PNG_FLOATING_POINT_SUPPORTED)
  175194. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  175195. #endif
  175196. #ifndef PNG_NO_WRITE_FLUSH
  175197. # define PNG_WRITE_FLUSH_SUPPORTED
  175198. #endif
  175199. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  175200. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  175201. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  175202. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  175203. #endif
  175204. #endif
  175205. #endif /* PNG_WRITE_SUPPORTED */
  175206. #ifndef PNG_1_0_X
  175207. # ifndef PNG_NO_ERROR_NUMBERS
  175208. # define PNG_ERROR_NUMBERS_SUPPORTED
  175209. # endif
  175210. #endif /* PNG_1_0_X */
  175211. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  175212. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  175213. # ifndef PNG_NO_USER_TRANSFORM_PTR
  175214. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  175215. # endif
  175216. #endif
  175217. #ifndef PNG_NO_STDIO
  175218. # define PNG_TIME_RFC1123_SUPPORTED
  175219. #endif
  175220. /* This adds extra functions in pngget.c for accessing data from the
  175221. * info pointer (added in version 0.99)
  175222. * png_get_image_width()
  175223. * png_get_image_height()
  175224. * png_get_bit_depth()
  175225. * png_get_color_type()
  175226. * png_get_compression_type()
  175227. * png_get_filter_type()
  175228. * png_get_interlace_type()
  175229. * png_get_pixel_aspect_ratio()
  175230. * png_get_pixels_per_meter()
  175231. * png_get_x_offset_pixels()
  175232. * png_get_y_offset_pixels()
  175233. * png_get_x_offset_microns()
  175234. * png_get_y_offset_microns()
  175235. */
  175236. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  175237. # define PNG_EASY_ACCESS_SUPPORTED
  175238. #endif
  175239. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  175240. * and removed from version 1.2.20. The following will be removed
  175241. * from libpng-1.4.0
  175242. */
  175243. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  175244. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  175245. # define PNG_OPTIMIZED_CODE_SUPPORTED
  175246. # endif
  175247. #endif
  175248. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  175249. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  175250. # define PNG_ASSEMBLER_CODE_SUPPORTED
  175251. # endif
  175252. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  175253. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  175254. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  175255. # define PNG_NO_MMX_CODE
  175256. # endif
  175257. # endif
  175258. # if defined(__APPLE__)
  175259. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  175260. # define PNG_NO_MMX_CODE
  175261. # endif
  175262. # endif
  175263. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  175264. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  175265. # define PNG_NO_MMX_CODE
  175266. # endif
  175267. # endif
  175268. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  175269. # define PNG_MMX_CODE_SUPPORTED
  175270. # endif
  175271. #endif
  175272. /* end of obsolete code to be removed from libpng-1.4.0 */
  175273. #if !defined(PNG_1_0_X)
  175274. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  175275. # define PNG_USER_MEM_SUPPORTED
  175276. #endif
  175277. #endif /* PNG_1_0_X */
  175278. /* Added at libpng-1.2.6 */
  175279. #if !defined(PNG_1_0_X)
  175280. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  175281. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  175282. # define PNG_SET_USER_LIMITS_SUPPORTED
  175283. #endif
  175284. #endif
  175285. #endif /* PNG_1_0_X */
  175286. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  175287. * how large, set these limits to 0x7fffffffL
  175288. */
  175289. #ifndef PNG_USER_WIDTH_MAX
  175290. # define PNG_USER_WIDTH_MAX 1000000L
  175291. #endif
  175292. #ifndef PNG_USER_HEIGHT_MAX
  175293. # define PNG_USER_HEIGHT_MAX 1000000L
  175294. #endif
  175295. /* These are currently experimental features, define them if you want */
  175296. /* very little testing */
  175297. /*
  175298. #ifdef PNG_READ_SUPPORTED
  175299. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  175300. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  175301. # endif
  175302. #endif
  175303. */
  175304. /* This is only for PowerPC big-endian and 680x0 systems */
  175305. /* some testing */
  175306. /*
  175307. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  175308. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  175309. #endif
  175310. */
  175311. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  175312. /*
  175313. #define PNG_NO_POINTER_INDEXING
  175314. */
  175315. /* These functions are turned off by default, as they will be phased out. */
  175316. /*
  175317. #define PNG_USELESS_TESTS_SUPPORTED
  175318. #define PNG_CORRECT_PALETTE_SUPPORTED
  175319. */
  175320. /* Any chunks you are not interested in, you can undef here. The
  175321. * ones that allocate memory may be expecially important (hIST,
  175322. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  175323. * a bit smaller.
  175324. */
  175325. #if defined(PNG_READ_SUPPORTED) && \
  175326. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  175327. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  175328. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  175329. #endif
  175330. #if defined(PNG_WRITE_SUPPORTED) && \
  175331. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  175332. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  175333. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  175334. #endif
  175335. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  175336. #ifdef PNG_NO_READ_TEXT
  175337. # define PNG_NO_READ_iTXt
  175338. # define PNG_NO_READ_tEXt
  175339. # define PNG_NO_READ_zTXt
  175340. #endif
  175341. #ifndef PNG_NO_READ_bKGD
  175342. # define PNG_READ_bKGD_SUPPORTED
  175343. # define PNG_bKGD_SUPPORTED
  175344. #endif
  175345. #ifndef PNG_NO_READ_cHRM
  175346. # define PNG_READ_cHRM_SUPPORTED
  175347. # define PNG_cHRM_SUPPORTED
  175348. #endif
  175349. #ifndef PNG_NO_READ_gAMA
  175350. # define PNG_READ_gAMA_SUPPORTED
  175351. # define PNG_gAMA_SUPPORTED
  175352. #endif
  175353. #ifndef PNG_NO_READ_hIST
  175354. # define PNG_READ_hIST_SUPPORTED
  175355. # define PNG_hIST_SUPPORTED
  175356. #endif
  175357. #ifndef PNG_NO_READ_iCCP
  175358. # define PNG_READ_iCCP_SUPPORTED
  175359. # define PNG_iCCP_SUPPORTED
  175360. #endif
  175361. #ifndef PNG_NO_READ_iTXt
  175362. # ifndef PNG_READ_iTXt_SUPPORTED
  175363. # define PNG_READ_iTXt_SUPPORTED
  175364. # endif
  175365. # ifndef PNG_iTXt_SUPPORTED
  175366. # define PNG_iTXt_SUPPORTED
  175367. # endif
  175368. #endif
  175369. #ifndef PNG_NO_READ_oFFs
  175370. # define PNG_READ_oFFs_SUPPORTED
  175371. # define PNG_oFFs_SUPPORTED
  175372. #endif
  175373. #ifndef PNG_NO_READ_pCAL
  175374. # define PNG_READ_pCAL_SUPPORTED
  175375. # define PNG_pCAL_SUPPORTED
  175376. #endif
  175377. #ifndef PNG_NO_READ_sCAL
  175378. # define PNG_READ_sCAL_SUPPORTED
  175379. # define PNG_sCAL_SUPPORTED
  175380. #endif
  175381. #ifndef PNG_NO_READ_pHYs
  175382. # define PNG_READ_pHYs_SUPPORTED
  175383. # define PNG_pHYs_SUPPORTED
  175384. #endif
  175385. #ifndef PNG_NO_READ_sBIT
  175386. # define PNG_READ_sBIT_SUPPORTED
  175387. # define PNG_sBIT_SUPPORTED
  175388. #endif
  175389. #ifndef PNG_NO_READ_sPLT
  175390. # define PNG_READ_sPLT_SUPPORTED
  175391. # define PNG_sPLT_SUPPORTED
  175392. #endif
  175393. #ifndef PNG_NO_READ_sRGB
  175394. # define PNG_READ_sRGB_SUPPORTED
  175395. # define PNG_sRGB_SUPPORTED
  175396. #endif
  175397. #ifndef PNG_NO_READ_tEXt
  175398. # define PNG_READ_tEXt_SUPPORTED
  175399. # define PNG_tEXt_SUPPORTED
  175400. #endif
  175401. #ifndef PNG_NO_READ_tIME
  175402. # define PNG_READ_tIME_SUPPORTED
  175403. # define PNG_tIME_SUPPORTED
  175404. #endif
  175405. #ifndef PNG_NO_READ_tRNS
  175406. # define PNG_READ_tRNS_SUPPORTED
  175407. # define PNG_tRNS_SUPPORTED
  175408. #endif
  175409. #ifndef PNG_NO_READ_zTXt
  175410. # define PNG_READ_zTXt_SUPPORTED
  175411. # define PNG_zTXt_SUPPORTED
  175412. #endif
  175413. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  175414. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  175415. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  175416. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  175417. # endif
  175418. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  175419. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  175420. # endif
  175421. #endif
  175422. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  175423. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  175424. # define PNG_READ_USER_CHUNKS_SUPPORTED
  175425. # define PNG_USER_CHUNKS_SUPPORTED
  175426. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  175427. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  175428. # endif
  175429. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  175430. # undef PNG_NO_HANDLE_AS_UNKNOWN
  175431. # endif
  175432. #endif
  175433. #ifndef PNG_NO_READ_OPT_PLTE
  175434. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  175435. #endif /* optional PLTE chunk in RGB and RGBA images */
  175436. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  175437. defined(PNG_READ_zTXt_SUPPORTED)
  175438. # define PNG_READ_TEXT_SUPPORTED
  175439. # define PNG_TEXT_SUPPORTED
  175440. #endif
  175441. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  175442. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  175443. #ifdef PNG_NO_WRITE_TEXT
  175444. # define PNG_NO_WRITE_iTXt
  175445. # define PNG_NO_WRITE_tEXt
  175446. # define PNG_NO_WRITE_zTXt
  175447. #endif
  175448. #ifndef PNG_NO_WRITE_bKGD
  175449. # define PNG_WRITE_bKGD_SUPPORTED
  175450. # ifndef PNG_bKGD_SUPPORTED
  175451. # define PNG_bKGD_SUPPORTED
  175452. # endif
  175453. #endif
  175454. #ifndef PNG_NO_WRITE_cHRM
  175455. # define PNG_WRITE_cHRM_SUPPORTED
  175456. # ifndef PNG_cHRM_SUPPORTED
  175457. # define PNG_cHRM_SUPPORTED
  175458. # endif
  175459. #endif
  175460. #ifndef PNG_NO_WRITE_gAMA
  175461. # define PNG_WRITE_gAMA_SUPPORTED
  175462. # ifndef PNG_gAMA_SUPPORTED
  175463. # define PNG_gAMA_SUPPORTED
  175464. # endif
  175465. #endif
  175466. #ifndef PNG_NO_WRITE_hIST
  175467. # define PNG_WRITE_hIST_SUPPORTED
  175468. # ifndef PNG_hIST_SUPPORTED
  175469. # define PNG_hIST_SUPPORTED
  175470. # endif
  175471. #endif
  175472. #ifndef PNG_NO_WRITE_iCCP
  175473. # define PNG_WRITE_iCCP_SUPPORTED
  175474. # ifndef PNG_iCCP_SUPPORTED
  175475. # define PNG_iCCP_SUPPORTED
  175476. # endif
  175477. #endif
  175478. #ifndef PNG_NO_WRITE_iTXt
  175479. # ifndef PNG_WRITE_iTXt_SUPPORTED
  175480. # define PNG_WRITE_iTXt_SUPPORTED
  175481. # endif
  175482. # ifndef PNG_iTXt_SUPPORTED
  175483. # define PNG_iTXt_SUPPORTED
  175484. # endif
  175485. #endif
  175486. #ifndef PNG_NO_WRITE_oFFs
  175487. # define PNG_WRITE_oFFs_SUPPORTED
  175488. # ifndef PNG_oFFs_SUPPORTED
  175489. # define PNG_oFFs_SUPPORTED
  175490. # endif
  175491. #endif
  175492. #ifndef PNG_NO_WRITE_pCAL
  175493. # define PNG_WRITE_pCAL_SUPPORTED
  175494. # ifndef PNG_pCAL_SUPPORTED
  175495. # define PNG_pCAL_SUPPORTED
  175496. # endif
  175497. #endif
  175498. #ifndef PNG_NO_WRITE_sCAL
  175499. # define PNG_WRITE_sCAL_SUPPORTED
  175500. # ifndef PNG_sCAL_SUPPORTED
  175501. # define PNG_sCAL_SUPPORTED
  175502. # endif
  175503. #endif
  175504. #ifndef PNG_NO_WRITE_pHYs
  175505. # define PNG_WRITE_pHYs_SUPPORTED
  175506. # ifndef PNG_pHYs_SUPPORTED
  175507. # define PNG_pHYs_SUPPORTED
  175508. # endif
  175509. #endif
  175510. #ifndef PNG_NO_WRITE_sBIT
  175511. # define PNG_WRITE_sBIT_SUPPORTED
  175512. # ifndef PNG_sBIT_SUPPORTED
  175513. # define PNG_sBIT_SUPPORTED
  175514. # endif
  175515. #endif
  175516. #ifndef PNG_NO_WRITE_sPLT
  175517. # define PNG_WRITE_sPLT_SUPPORTED
  175518. # ifndef PNG_sPLT_SUPPORTED
  175519. # define PNG_sPLT_SUPPORTED
  175520. # endif
  175521. #endif
  175522. #ifndef PNG_NO_WRITE_sRGB
  175523. # define PNG_WRITE_sRGB_SUPPORTED
  175524. # ifndef PNG_sRGB_SUPPORTED
  175525. # define PNG_sRGB_SUPPORTED
  175526. # endif
  175527. #endif
  175528. #ifndef PNG_NO_WRITE_tEXt
  175529. # define PNG_WRITE_tEXt_SUPPORTED
  175530. # ifndef PNG_tEXt_SUPPORTED
  175531. # define PNG_tEXt_SUPPORTED
  175532. # endif
  175533. #endif
  175534. #ifndef PNG_NO_WRITE_tIME
  175535. # define PNG_WRITE_tIME_SUPPORTED
  175536. # ifndef PNG_tIME_SUPPORTED
  175537. # define PNG_tIME_SUPPORTED
  175538. # endif
  175539. #endif
  175540. #ifndef PNG_NO_WRITE_tRNS
  175541. # define PNG_WRITE_tRNS_SUPPORTED
  175542. # ifndef PNG_tRNS_SUPPORTED
  175543. # define PNG_tRNS_SUPPORTED
  175544. # endif
  175545. #endif
  175546. #ifndef PNG_NO_WRITE_zTXt
  175547. # define PNG_WRITE_zTXt_SUPPORTED
  175548. # ifndef PNG_zTXt_SUPPORTED
  175549. # define PNG_zTXt_SUPPORTED
  175550. # endif
  175551. #endif
  175552. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  175553. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  175554. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  175555. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  175556. # endif
  175557. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  175558. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  175559. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  175560. # endif
  175561. # endif
  175562. #endif
  175563. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  175564. defined(PNG_WRITE_zTXt_SUPPORTED)
  175565. # define PNG_WRITE_TEXT_SUPPORTED
  175566. # ifndef PNG_TEXT_SUPPORTED
  175567. # define PNG_TEXT_SUPPORTED
  175568. # endif
  175569. #endif
  175570. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  175571. /* Turn this off to disable png_read_png() and
  175572. * png_write_png() and leave the row_pointers member
  175573. * out of the info structure.
  175574. */
  175575. #ifndef PNG_NO_INFO_IMAGE
  175576. # define PNG_INFO_IMAGE_SUPPORTED
  175577. #endif
  175578. /* need the time information for reading tIME chunks */
  175579. #if defined(PNG_tIME_SUPPORTED)
  175580. # if !defined(_WIN32_WCE)
  175581. /* "time.h" functions are not supported on WindowsCE */
  175582. # include <time.h>
  175583. # endif
  175584. #endif
  175585. /* Some typedefs to get us started. These should be safe on most of the
  175586. * common platforms. The typedefs should be at least as large as the
  175587. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  175588. * don't have to be exactly that size. Some compilers dislike passing
  175589. * unsigned shorts as function parameters, so you may be better off using
  175590. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  175591. * want to have unsigned int for png_uint_32 instead of unsigned long.
  175592. */
  175593. typedef unsigned long png_uint_32;
  175594. typedef long png_int_32;
  175595. typedef unsigned short png_uint_16;
  175596. typedef short png_int_16;
  175597. typedef unsigned char png_byte;
  175598. /* This is usually size_t. It is typedef'ed just in case you need it to
  175599. change (I'm not sure if you will or not, so I thought I'd be safe) */
  175600. #ifdef PNG_SIZE_T
  175601. typedef PNG_SIZE_T png_size_t;
  175602. # define png_sizeof(x) png_convert_size(sizeof (x))
  175603. #else
  175604. typedef size_t png_size_t;
  175605. # define png_sizeof(x) sizeof (x)
  175606. #endif
  175607. /* The following is needed for medium model support. It cannot be in the
  175608. * PNG_INTERNAL section. Needs modification for other compilers besides
  175609. * MSC. Model independent support declares all arrays and pointers to be
  175610. * large using the far keyword. The zlib version used must also support
  175611. * model independent data. As of version zlib 1.0.4, the necessary changes
  175612. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  175613. * changes that are needed. (Tim Wegner)
  175614. */
  175615. /* Separate compiler dependencies (problem here is that zlib.h always
  175616. defines FAR. (SJT) */
  175617. #ifdef __BORLANDC__
  175618. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  175619. # define LDATA 1
  175620. # else
  175621. # define LDATA 0
  175622. # endif
  175623. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  175624. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  175625. # define PNG_MAX_MALLOC_64K
  175626. # if (LDATA != 1)
  175627. # ifndef FAR
  175628. # define FAR __far
  175629. # endif
  175630. # define USE_FAR_KEYWORD
  175631. # endif /* LDATA != 1 */
  175632. /* Possibly useful for moving data out of default segment.
  175633. * Uncomment it if you want. Could also define FARDATA as
  175634. * const if your compiler supports it. (SJT)
  175635. # define FARDATA FAR
  175636. */
  175637. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  175638. #endif /* __BORLANDC__ */
  175639. /* Suggest testing for specific compiler first before testing for
  175640. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  175641. * making reliance oncertain keywords suspect. (SJT)
  175642. */
  175643. /* MSC Medium model */
  175644. #if defined(FAR)
  175645. # if defined(M_I86MM)
  175646. # define USE_FAR_KEYWORD
  175647. # define FARDATA FAR
  175648. # include <dos.h>
  175649. # endif
  175650. #endif
  175651. /* SJT: default case */
  175652. #ifndef FAR
  175653. # define FAR
  175654. #endif
  175655. /* At this point FAR is always defined */
  175656. #ifndef FARDATA
  175657. # define FARDATA
  175658. #endif
  175659. /* Typedef for floating-point numbers that are converted
  175660. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  175661. typedef png_int_32 png_fixed_point;
  175662. /* Add typedefs for pointers */
  175663. typedef void FAR * png_voidp;
  175664. typedef png_byte FAR * png_bytep;
  175665. typedef png_uint_32 FAR * png_uint_32p;
  175666. typedef png_int_32 FAR * png_int_32p;
  175667. typedef png_uint_16 FAR * png_uint_16p;
  175668. typedef png_int_16 FAR * png_int_16p;
  175669. typedef PNG_CONST char FAR * png_const_charp;
  175670. typedef char FAR * png_charp;
  175671. typedef png_fixed_point FAR * png_fixed_point_p;
  175672. #ifndef PNG_NO_STDIO
  175673. #if defined(_WIN32_WCE)
  175674. typedef HANDLE png_FILE_p;
  175675. #else
  175676. typedef FILE * png_FILE_p;
  175677. #endif
  175678. #endif
  175679. #ifdef PNG_FLOATING_POINT_SUPPORTED
  175680. typedef double FAR * png_doublep;
  175681. #endif
  175682. /* Pointers to pointers; i.e. arrays */
  175683. typedef png_byte FAR * FAR * png_bytepp;
  175684. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  175685. typedef png_int_32 FAR * FAR * png_int_32pp;
  175686. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  175687. typedef png_int_16 FAR * FAR * png_int_16pp;
  175688. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  175689. typedef char FAR * FAR * png_charpp;
  175690. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  175691. #ifdef PNG_FLOATING_POINT_SUPPORTED
  175692. typedef double FAR * FAR * png_doublepp;
  175693. #endif
  175694. /* Pointers to pointers to pointers; i.e., pointer to array */
  175695. typedef char FAR * FAR * FAR * png_charppp;
  175696. #if 0
  175697. /* SPC - Is this stuff deprecated? */
  175698. /* It'll be removed as of libpng-1.3.0 - GR-P */
  175699. /* libpng typedefs for types in zlib. If zlib changes
  175700. * or another compression library is used, then change these.
  175701. * Eliminates need to change all the source files.
  175702. */
  175703. typedef charf * png_zcharp;
  175704. typedef charf * FAR * png_zcharpp;
  175705. typedef z_stream FAR * png_zstreamp;
  175706. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  175707. /*
  175708. * Define PNG_BUILD_DLL if the module being built is a Windows
  175709. * LIBPNG DLL.
  175710. *
  175711. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  175712. * It is equivalent to Microsoft predefined macro _DLL that is
  175713. * automatically defined when you compile using the share
  175714. * version of the CRT (C Run-Time library)
  175715. *
  175716. * The cygwin mods make this behavior a little different:
  175717. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  175718. * Define PNG_STATIC if you are building a static library for use with cygwin,
  175719. * -or- if you are building an application that you want to link to the
  175720. * static library.
  175721. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  175722. * the other flags is defined.
  175723. */
  175724. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  175725. # define PNG_DLL
  175726. #endif
  175727. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  175728. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  175729. * command-line override
  175730. */
  175731. #if defined(__CYGWIN__)
  175732. # if !defined(PNG_STATIC)
  175733. # if defined(PNG_USE_GLOBAL_ARRAYS)
  175734. # undef PNG_USE_GLOBAL_ARRAYS
  175735. # endif
  175736. # if !defined(PNG_USE_LOCAL_ARRAYS)
  175737. # define PNG_USE_LOCAL_ARRAYS
  175738. # endif
  175739. # else
  175740. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  175741. # if defined(PNG_USE_GLOBAL_ARRAYS)
  175742. # undef PNG_USE_GLOBAL_ARRAYS
  175743. # endif
  175744. # endif
  175745. # endif
  175746. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  175747. # define PNG_USE_LOCAL_ARRAYS
  175748. # endif
  175749. #endif
  175750. /* Do not use global arrays (helps with building DLL's)
  175751. * They are no longer used in libpng itself, since version 1.0.5c,
  175752. * but might be required for some pre-1.0.5c applications.
  175753. */
  175754. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  175755. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  175756. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  175757. # define PNG_USE_LOCAL_ARRAYS
  175758. # else
  175759. # define PNG_USE_GLOBAL_ARRAYS
  175760. # endif
  175761. #endif
  175762. #if defined(__CYGWIN__)
  175763. # undef PNGAPI
  175764. # define PNGAPI __cdecl
  175765. # undef PNG_IMPEXP
  175766. # define PNG_IMPEXP
  175767. #endif
  175768. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  175769. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  175770. * Don't ignore those warnings; you must also reset the default calling
  175771. * convention in your compiler to match your PNGAPI, and you must build
  175772. * zlib and your applications the same way you build libpng.
  175773. */
  175774. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  175775. # ifndef PNG_NO_MODULEDEF
  175776. # define PNG_NO_MODULEDEF
  175777. # endif
  175778. #endif
  175779. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  175780. # define PNG_IMPEXP
  175781. #endif
  175782. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  175783. (( defined(_Windows) || defined(_WINDOWS) || \
  175784. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  175785. # ifndef PNGAPI
  175786. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  175787. # define PNGAPI __cdecl
  175788. # else
  175789. # define PNGAPI _cdecl
  175790. # endif
  175791. # endif
  175792. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  175793. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  175794. # define PNG_IMPEXP
  175795. # endif
  175796. # if !defined(PNG_IMPEXP)
  175797. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  175798. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  175799. /* Borland/Microsoft */
  175800. # if defined(_MSC_VER) || defined(__BORLANDC__)
  175801. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  175802. # define PNG_EXPORT PNG_EXPORT_TYPE1
  175803. # else
  175804. # define PNG_EXPORT PNG_EXPORT_TYPE2
  175805. # if defined(PNG_BUILD_DLL)
  175806. # define PNG_IMPEXP __export
  175807. # else
  175808. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  175809. VC++ */
  175810. # endif /* Exists in Borland C++ for
  175811. C++ classes (== huge) */
  175812. # endif
  175813. # endif
  175814. # if !defined(PNG_IMPEXP)
  175815. # if defined(PNG_BUILD_DLL)
  175816. # define PNG_IMPEXP __declspec(dllexport)
  175817. # else
  175818. # define PNG_IMPEXP __declspec(dllimport)
  175819. # endif
  175820. # endif
  175821. # endif /* PNG_IMPEXP */
  175822. #else /* !(DLL || non-cygwin WINDOWS) */
  175823. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  175824. # ifndef PNGAPI
  175825. # define PNGAPI _System
  175826. # endif
  175827. # else
  175828. # if 0 /* ... other platforms, with other meanings */
  175829. # endif
  175830. # endif
  175831. #endif
  175832. #ifndef PNGAPI
  175833. # define PNGAPI
  175834. #endif
  175835. #ifndef PNG_IMPEXP
  175836. # define PNG_IMPEXP
  175837. #endif
  175838. #ifdef PNG_BUILDSYMS
  175839. # ifndef PNG_EXPORT
  175840. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  175841. # endif
  175842. # ifdef PNG_USE_GLOBAL_ARRAYS
  175843. # ifndef PNG_EXPORT_VAR
  175844. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  175845. # endif
  175846. # endif
  175847. #endif
  175848. #ifndef PNG_EXPORT
  175849. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  175850. #endif
  175851. #ifdef PNG_USE_GLOBAL_ARRAYS
  175852. # ifndef PNG_EXPORT_VAR
  175853. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  175854. # endif
  175855. #endif
  175856. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  175857. * functions that are passed far data must be model independent.
  175858. */
  175859. #ifndef PNG_ABORT
  175860. # define PNG_ABORT() abort()
  175861. #endif
  175862. #ifdef PNG_SETJMP_SUPPORTED
  175863. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  175864. #else
  175865. # define png_jmpbuf(png_ptr) \
  175866. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  175867. #endif
  175868. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  175869. /* use this to make far-to-near assignments */
  175870. # define CHECK 1
  175871. # define NOCHECK 0
  175872. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  175873. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  175874. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  175875. # define png_strcpy _fstrcpy
  175876. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  175877. # define png_strlen _fstrlen
  175878. # define png_memcmp _fmemcmp /* SJT: added */
  175879. # define png_memcpy _fmemcpy
  175880. # define png_memset _fmemset
  175881. #else /* use the usual functions */
  175882. # define CVT_PTR(ptr) (ptr)
  175883. # define CVT_PTR_NOCHECK(ptr) (ptr)
  175884. # ifndef PNG_NO_SNPRINTF
  175885. # ifdef _MSC_VER
  175886. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  175887. # define png_snprintf2 _snprintf
  175888. # define png_snprintf6 _snprintf
  175889. # else
  175890. # define png_snprintf snprintf /* Added to v 1.2.19 */
  175891. # define png_snprintf2 snprintf
  175892. # define png_snprintf6 snprintf
  175893. # endif
  175894. # else
  175895. /* You don't have or don't want to use snprintf(). Caution: Using
  175896. * sprintf instead of snprintf exposes your application to accidental
  175897. * or malevolent buffer overflows. If you don't have snprintf()
  175898. * as a general rule you should provide one (you can get one from
  175899. * Portable OpenSSH). */
  175900. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  175901. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  175902. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  175903. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  175904. # endif
  175905. # define png_strcpy strcpy
  175906. # define png_strncpy strncpy /* Added to v 1.2.6 */
  175907. # define png_strlen strlen
  175908. # define png_memcmp memcmp /* SJT: added */
  175909. # define png_memcpy memcpy
  175910. # define png_memset memset
  175911. #endif
  175912. /* End of memory model independent support */
  175913. /* Just a little check that someone hasn't tried to define something
  175914. * contradictory.
  175915. */
  175916. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  175917. # undef PNG_ZBUF_SIZE
  175918. # define PNG_ZBUF_SIZE 65536L
  175919. #endif
  175920. /* Added at libpng-1.2.8 */
  175921. #endif /* PNG_VERSION_INFO_ONLY */
  175922. #endif /* PNGCONF_H */
  175923. /********* End of inlined file: pngconf.h *********/
  175924. #ifdef _MSC_VER
  175925. #pragma warning (disable: 4996 4100)
  175926. #endif
  175927. /*
  175928. * Added at libpng-1.2.8 */
  175929. /* Ref MSDN: Private as priority over Special
  175930. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  175931. * procedures. If this value is given, the StringFileInfo block must
  175932. * contain a PrivateBuild string.
  175933. *
  175934. * VS_FF_SPECIALBUILD File *was* built by the original company using
  175935. * standard release procedures but is a variation of the standard
  175936. * file of the same version number. If this value is given, the
  175937. * StringFileInfo block must contain a SpecialBuild string.
  175938. */
  175939. #if defined(PNG_USER_PRIVATEBUILD)
  175940. # define PNG_LIBPNG_BUILD_TYPE \
  175941. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  175942. #else
  175943. # if defined(PNG_LIBPNG_SPECIALBUILD)
  175944. # define PNG_LIBPNG_BUILD_TYPE \
  175945. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  175946. # else
  175947. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  175948. # endif
  175949. #endif
  175950. #ifndef PNG_VERSION_INFO_ONLY
  175951. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  175952. #ifdef __cplusplus
  175953. extern "C" {
  175954. #endif /* __cplusplus */
  175955. /* This file is arranged in several sections. The first section contains
  175956. * structure and type definitions. The second section contains the external
  175957. * library functions, while the third has the internal library functions,
  175958. * which applications aren't expected to use directly.
  175959. */
  175960. #ifndef PNG_NO_TYPECAST_NULL
  175961. #define int_p_NULL (int *)NULL
  175962. #define png_bytep_NULL (png_bytep)NULL
  175963. #define png_bytepp_NULL (png_bytepp)NULL
  175964. #define png_doublep_NULL (png_doublep)NULL
  175965. #define png_error_ptr_NULL (png_error_ptr)NULL
  175966. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  175967. #define png_free_ptr_NULL (png_free_ptr)NULL
  175968. #define png_infopp_NULL (png_infopp)NULL
  175969. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  175970. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  175971. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  175972. #define png_structp_NULL (png_structp)NULL
  175973. #define png_uint_16p_NULL (png_uint_16p)NULL
  175974. #define png_voidp_NULL (png_voidp)NULL
  175975. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  175976. #else
  175977. #define int_p_NULL NULL
  175978. #define png_bytep_NULL NULL
  175979. #define png_bytepp_NULL NULL
  175980. #define png_doublep_NULL NULL
  175981. #define png_error_ptr_NULL NULL
  175982. #define png_flush_ptr_NULL NULL
  175983. #define png_free_ptr_NULL NULL
  175984. #define png_infopp_NULL NULL
  175985. #define png_malloc_ptr_NULL NULL
  175986. #define png_read_status_ptr_NULL NULL
  175987. #define png_rw_ptr_NULL NULL
  175988. #define png_structp_NULL NULL
  175989. #define png_uint_16p_NULL NULL
  175990. #define png_voidp_NULL NULL
  175991. #define png_write_status_ptr_NULL NULL
  175992. #endif
  175993. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  175994. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  175995. /* Version information for C files, stored in png.c. This had better match
  175996. * the version above.
  175997. */
  175998. #ifdef PNG_USE_GLOBAL_ARRAYS
  175999. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  176000. /* need room for 99.99.99beta99z */
  176001. #else
  176002. #define png_libpng_ver png_get_header_ver(NULL)
  176003. #endif
  176004. #ifdef PNG_USE_GLOBAL_ARRAYS
  176005. /* This was removed in version 1.0.5c */
  176006. /* Structures to facilitate easy interlacing. See png.c for more details */
  176007. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  176008. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  176009. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  176010. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  176011. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  176012. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  176013. /* This isn't currently used. If you need it, see png.c for more details.
  176014. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  176015. */
  176016. #endif
  176017. #endif /* PNG_NO_EXTERN */
  176018. /* Three color definitions. The order of the red, green, and blue, (and the
  176019. * exact size) is not important, although the size of the fields need to
  176020. * be png_byte or png_uint_16 (as defined below).
  176021. */
  176022. typedef struct png_color_struct
  176023. {
  176024. png_byte red;
  176025. png_byte green;
  176026. png_byte blue;
  176027. } png_color;
  176028. typedef png_color FAR * png_colorp;
  176029. typedef png_color FAR * FAR * png_colorpp;
  176030. typedef struct png_color_16_struct
  176031. {
  176032. png_byte index; /* used for palette files */
  176033. png_uint_16 red; /* for use in red green blue files */
  176034. png_uint_16 green;
  176035. png_uint_16 blue;
  176036. png_uint_16 gray; /* for use in grayscale files */
  176037. } png_color_16;
  176038. typedef png_color_16 FAR * png_color_16p;
  176039. typedef png_color_16 FAR * FAR * png_color_16pp;
  176040. typedef struct png_color_8_struct
  176041. {
  176042. png_byte red; /* for use in red green blue files */
  176043. png_byte green;
  176044. png_byte blue;
  176045. png_byte gray; /* for use in grayscale files */
  176046. png_byte alpha; /* for alpha channel files */
  176047. } png_color_8;
  176048. typedef png_color_8 FAR * png_color_8p;
  176049. typedef png_color_8 FAR * FAR * png_color_8pp;
  176050. /*
  176051. * The following two structures are used for the in-core representation
  176052. * of sPLT chunks.
  176053. */
  176054. typedef struct png_sPLT_entry_struct
  176055. {
  176056. png_uint_16 red;
  176057. png_uint_16 green;
  176058. png_uint_16 blue;
  176059. png_uint_16 alpha;
  176060. png_uint_16 frequency;
  176061. } png_sPLT_entry;
  176062. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  176063. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  176064. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  176065. * occupy the LSB of their respective members, and the MSB of each member
  176066. * is zero-filled. The frequency member always occupies the full 16 bits.
  176067. */
  176068. typedef struct png_sPLT_struct
  176069. {
  176070. png_charp name; /* palette name */
  176071. png_byte depth; /* depth of palette samples */
  176072. png_sPLT_entryp entries; /* palette entries */
  176073. png_int_32 nentries; /* number of palette entries */
  176074. } png_sPLT_t;
  176075. typedef png_sPLT_t FAR * png_sPLT_tp;
  176076. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  176077. #ifdef PNG_TEXT_SUPPORTED
  176078. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  176079. * and whether that contents is compressed or not. The "key" field
  176080. * points to a regular zero-terminated C string. The "text", "lang", and
  176081. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  176082. * However, the * structure returned by png_get_text() will always contain
  176083. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  176084. * so they can be safely used in printf() and other string-handling functions.
  176085. */
  176086. typedef struct png_text_struct
  176087. {
  176088. int compression; /* compression value:
  176089. -1: tEXt, none
  176090. 0: zTXt, deflate
  176091. 1: iTXt, none
  176092. 2: iTXt, deflate */
  176093. png_charp key; /* keyword, 1-79 character description of "text" */
  176094. png_charp text; /* comment, may be an empty string (ie "")
  176095. or a NULL pointer */
  176096. png_size_t text_length; /* length of the text string */
  176097. #ifdef PNG_iTXt_SUPPORTED
  176098. png_size_t itxt_length; /* length of the itxt string */
  176099. png_charp lang; /* language code, 0-79 characters
  176100. or a NULL pointer */
  176101. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  176102. chars or a NULL pointer */
  176103. #endif
  176104. } png_text;
  176105. typedef png_text FAR * png_textp;
  176106. typedef png_text FAR * FAR * png_textpp;
  176107. #endif
  176108. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  176109. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  176110. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  176111. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  176112. #define PNG_TEXT_COMPRESSION_NONE -1
  176113. #define PNG_TEXT_COMPRESSION_zTXt 0
  176114. #define PNG_ITXT_COMPRESSION_NONE 1
  176115. #define PNG_ITXT_COMPRESSION_zTXt 2
  176116. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  176117. /* png_time is a way to hold the time in an machine independent way.
  176118. * Two conversions are provided, both from time_t and struct tm. There
  176119. * is no portable way to convert to either of these structures, as far
  176120. * as I know. If you know of a portable way, send it to me. As a side
  176121. * note - PNG has always been Year 2000 compliant!
  176122. */
  176123. typedef struct png_time_struct
  176124. {
  176125. png_uint_16 year; /* full year, as in, 1995 */
  176126. png_byte month; /* month of year, 1 - 12 */
  176127. png_byte day; /* day of month, 1 - 31 */
  176128. png_byte hour; /* hour of day, 0 - 23 */
  176129. png_byte minute; /* minute of hour, 0 - 59 */
  176130. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  176131. } png_time;
  176132. typedef png_time FAR * png_timep;
  176133. typedef png_time FAR * FAR * png_timepp;
  176134. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176135. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  176136. * no specific support. The idea is that we can use this to queue
  176137. * up private chunks for output even though the library doesn't actually
  176138. * know about their semantics.
  176139. */
  176140. typedef struct png_unknown_chunk_t
  176141. {
  176142. png_byte name[5];
  176143. png_byte *data;
  176144. png_size_t size;
  176145. /* libpng-using applications should NOT directly modify this byte. */
  176146. png_byte location; /* mode of operation at read time */
  176147. }
  176148. png_unknown_chunk;
  176149. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  176150. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  176151. #endif
  176152. /* png_info is a structure that holds the information in a PNG file so
  176153. * that the application can find out the characteristics of the image.
  176154. * If you are reading the file, this structure will tell you what is
  176155. * in the PNG file. If you are writing the file, fill in the information
  176156. * you want to put into the PNG file, then call png_write_info().
  176157. * The names chosen should be very close to the PNG specification, so
  176158. * consult that document for information about the meaning of each field.
  176159. *
  176160. * With libpng < 0.95, it was only possible to directly set and read the
  176161. * the values in the png_info_struct, which meant that the contents and
  176162. * order of the values had to remain fixed. With libpng 0.95 and later,
  176163. * however, there are now functions that abstract the contents of
  176164. * png_info_struct from the application, so this makes it easier to use
  176165. * libpng with dynamic libraries, and even makes it possible to use
  176166. * libraries that don't have all of the libpng ancillary chunk-handing
  176167. * functionality.
  176168. *
  176169. * In any case, the order of the parameters in png_info_struct should NOT
  176170. * be changed for as long as possible to keep compatibility with applications
  176171. * that use the old direct-access method with png_info_struct.
  176172. *
  176173. * The following members may have allocated storage attached that should be
  176174. * cleaned up before the structure is discarded: palette, trans, text,
  176175. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  176176. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  176177. * are automatically freed when the info structure is deallocated, if they were
  176178. * allocated internally by libpng. This behavior can be changed by means
  176179. * of the png_data_freer() function.
  176180. *
  176181. * More allocation details: all the chunk-reading functions that
  176182. * change these members go through the corresponding png_set_*
  176183. * functions. A function to clear these members is available: see
  176184. * png_free_data(). The png_set_* functions do not depend on being
  176185. * able to point info structure members to any of the storage they are
  176186. * passed (they make their own copies), EXCEPT that the png_set_text
  176187. * functions use the same storage passed to them in the text_ptr or
  176188. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  176189. * functions do not make their own copies.
  176190. */
  176191. typedef struct png_info_struct
  176192. {
  176193. /* the following are necessary for every PNG file */
  176194. png_uint_32 width; /* width of image in pixels (from IHDR) */
  176195. png_uint_32 height; /* height of image in pixels (from IHDR) */
  176196. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  176197. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  176198. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  176199. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  176200. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  176201. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  176202. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  176203. /* The following three should have been named *_method not *_type */
  176204. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  176205. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  176206. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  176207. /* The following is informational only on read, and not used on writes. */
  176208. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  176209. png_byte pixel_depth; /* number of bits per pixel */
  176210. png_byte spare_byte; /* to align the data, and for future use */
  176211. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  176212. /* The rest of the data is optional. If you are reading, check the
  176213. * valid field to see if the information in these are valid. If you
  176214. * are writing, set the valid field to those chunks you want written,
  176215. * and initialize the appropriate fields below.
  176216. */
  176217. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  176218. /* The gAMA chunk describes the gamma characteristics of the system
  176219. * on which the image was created, normally in the range [1.0, 2.5].
  176220. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  176221. */
  176222. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  176223. #endif
  176224. #if defined(PNG_sRGB_SUPPORTED)
  176225. /* GR-P, 0.96a */
  176226. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  176227. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  176228. #endif
  176229. #if defined(PNG_TEXT_SUPPORTED)
  176230. /* The tEXt, and zTXt chunks contain human-readable textual data in
  176231. * uncompressed, compressed, and optionally compressed forms, respectively.
  176232. * The data in "text" is an array of pointers to uncompressed,
  176233. * null-terminated C strings. Each chunk has a keyword that describes the
  176234. * textual data contained in that chunk. Keywords are not required to be
  176235. * unique, and the text string may be empty. Any number of text chunks may
  176236. * be in an image.
  176237. */
  176238. int num_text; /* number of comments read/to write */
  176239. int max_text; /* current size of text array */
  176240. png_textp text; /* array of comments read/to write */
  176241. #endif /* PNG_TEXT_SUPPORTED */
  176242. #if defined(PNG_tIME_SUPPORTED)
  176243. /* The tIME chunk holds the last time the displayed image data was
  176244. * modified. See the png_time struct for the contents of this struct.
  176245. */
  176246. png_time mod_time;
  176247. #endif
  176248. #if defined(PNG_sBIT_SUPPORTED)
  176249. /* The sBIT chunk specifies the number of significant high-order bits
  176250. * in the pixel data. Values are in the range [1, bit_depth], and are
  176251. * only specified for the channels in the pixel data. The contents of
  176252. * the low-order bits is not specified. Data is valid if
  176253. * (valid & PNG_INFO_sBIT) is non-zero.
  176254. */
  176255. png_color_8 sig_bit; /* significant bits in color channels */
  176256. #endif
  176257. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  176258. defined(PNG_READ_BACKGROUND_SUPPORTED)
  176259. /* The tRNS chunk supplies transparency data for paletted images and
  176260. * other image types that don't need a full alpha channel. There are
  176261. * "num_trans" transparency values for a paletted image, stored in the
  176262. * same order as the palette colors, starting from index 0. Values
  176263. * for the data are in the range [0, 255], ranging from fully transparent
  176264. * to fully opaque, respectively. For non-paletted images, there is a
  176265. * single color specified that should be treated as fully transparent.
  176266. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  176267. */
  176268. png_bytep trans; /* transparent values for paletted image */
  176269. png_color_16 trans_values; /* transparent color for non-palette image */
  176270. #endif
  176271. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  176272. /* The bKGD chunk gives the suggested image background color if the
  176273. * display program does not have its own background color and the image
  176274. * is needs to composited onto a background before display. The colors
  176275. * in "background" are normally in the same color space/depth as the
  176276. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  176277. */
  176278. png_color_16 background;
  176279. #endif
  176280. #if defined(PNG_oFFs_SUPPORTED)
  176281. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  176282. * and downwards from the top-left corner of the display, page, or other
  176283. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  176284. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  176285. */
  176286. png_int_32 x_offset; /* x offset on page */
  176287. png_int_32 y_offset; /* y offset on page */
  176288. png_byte offset_unit_type; /* offset units type */
  176289. #endif
  176290. #if defined(PNG_pHYs_SUPPORTED)
  176291. /* The pHYs chunk gives the physical pixel density of the image for
  176292. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  176293. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  176294. */
  176295. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  176296. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  176297. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  176298. #endif
  176299. #if defined(PNG_hIST_SUPPORTED)
  176300. /* The hIST chunk contains the relative frequency or importance of the
  176301. * various palette entries, so that a viewer can intelligently select a
  176302. * reduced-color palette, if required. Data is an array of "num_palette"
  176303. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  176304. * is non-zero.
  176305. */
  176306. png_uint_16p hist;
  176307. #endif
  176308. #ifdef PNG_cHRM_SUPPORTED
  176309. /* The cHRM chunk describes the CIE color characteristics of the monitor
  176310. * on which the PNG was created. This data allows the viewer to do gamut
  176311. * mapping of the input image to ensure that the viewer sees the same
  176312. * colors in the image as the creator. Values are in the range
  176313. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  176314. */
  176315. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176316. float x_white;
  176317. float y_white;
  176318. float x_red;
  176319. float y_red;
  176320. float x_green;
  176321. float y_green;
  176322. float x_blue;
  176323. float y_blue;
  176324. #endif
  176325. #endif
  176326. #if defined(PNG_pCAL_SUPPORTED)
  176327. /* The pCAL chunk describes a transformation between the stored pixel
  176328. * values and original physical data values used to create the image.
  176329. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  176330. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  176331. * (possibly non-linear) transformation function given by "pcal_type"
  176332. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  176333. * defines below, and the PNG-Group's PNG extensions document for a
  176334. * complete description of the transformations and how they should be
  176335. * implemented, and for a description of the ASCII parameter strings.
  176336. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  176337. */
  176338. png_charp pcal_purpose; /* pCAL chunk description string */
  176339. png_int_32 pcal_X0; /* minimum value */
  176340. png_int_32 pcal_X1; /* maximum value */
  176341. png_charp pcal_units; /* Latin-1 string giving physical units */
  176342. png_charpp pcal_params; /* ASCII strings containing parameter values */
  176343. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  176344. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  176345. #endif
  176346. /* New members added in libpng-1.0.6 */
  176347. #ifdef PNG_FREE_ME_SUPPORTED
  176348. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  176349. #endif
  176350. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176351. /* storage for unknown chunks that the library doesn't recognize. */
  176352. png_unknown_chunkp unknown_chunks;
  176353. png_size_t unknown_chunks_num;
  176354. #endif
  176355. #if defined(PNG_iCCP_SUPPORTED)
  176356. /* iCCP chunk data. */
  176357. png_charp iccp_name; /* profile name */
  176358. png_charp iccp_profile; /* International Color Consortium profile data */
  176359. /* Note to maintainer: should be png_bytep */
  176360. png_uint_32 iccp_proflen; /* ICC profile data length */
  176361. png_byte iccp_compression; /* Always zero */
  176362. #endif
  176363. #if defined(PNG_sPLT_SUPPORTED)
  176364. /* data on sPLT chunks (there may be more than one). */
  176365. png_sPLT_tp splt_palettes;
  176366. png_uint_32 splt_palettes_num;
  176367. #endif
  176368. #if defined(PNG_sCAL_SUPPORTED)
  176369. /* The sCAL chunk describes the actual physical dimensions of the
  176370. * subject matter of the graphic. The chunk contains a unit specification
  176371. * a byte value, and two ASCII strings representing floating-point
  176372. * values. The values are width and height corresponsing to one pixel
  176373. * in the image. This external representation is converted to double
  176374. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  176375. */
  176376. png_byte scal_unit; /* unit of physical scale */
  176377. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176378. double scal_pixel_width; /* width of one pixel */
  176379. double scal_pixel_height; /* height of one pixel */
  176380. #endif
  176381. #ifdef PNG_FIXED_POINT_SUPPORTED
  176382. png_charp scal_s_width; /* string containing height */
  176383. png_charp scal_s_height; /* string containing width */
  176384. #endif
  176385. #endif
  176386. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  176387. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  176388. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  176389. png_bytepp row_pointers; /* the image bits */
  176390. #endif
  176391. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  176392. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  176393. #endif
  176394. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  176395. png_fixed_point int_x_white;
  176396. png_fixed_point int_y_white;
  176397. png_fixed_point int_x_red;
  176398. png_fixed_point int_y_red;
  176399. png_fixed_point int_x_green;
  176400. png_fixed_point int_y_green;
  176401. png_fixed_point int_x_blue;
  176402. png_fixed_point int_y_blue;
  176403. #endif
  176404. } png_info;
  176405. typedef png_info FAR * png_infop;
  176406. typedef png_info FAR * FAR * png_infopp;
  176407. /* Maximum positive integer used in PNG is (2^31)-1 */
  176408. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  176409. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  176410. #define PNG_SIZE_MAX ((png_size_t)(-1))
  176411. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176412. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  176413. #define PNG_MAX_UINT PNG_UINT_31_MAX
  176414. #endif
  176415. /* These describe the color_type field in png_info. */
  176416. /* color type masks */
  176417. #define PNG_COLOR_MASK_PALETTE 1
  176418. #define PNG_COLOR_MASK_COLOR 2
  176419. #define PNG_COLOR_MASK_ALPHA 4
  176420. /* color types. Note that not all combinations are legal */
  176421. #define PNG_COLOR_TYPE_GRAY 0
  176422. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  176423. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  176424. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  176425. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  176426. /* aliases */
  176427. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  176428. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  176429. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  176430. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  176431. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  176432. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  176433. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  176434. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  176435. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  176436. /* These are for the interlacing type. These values should NOT be changed. */
  176437. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  176438. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  176439. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  176440. /* These are for the oFFs chunk. These values should NOT be changed. */
  176441. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  176442. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  176443. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  176444. /* These are for the pCAL chunk. These values should NOT be changed. */
  176445. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  176446. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  176447. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  176448. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  176449. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  176450. /* These are for the sCAL chunk. These values should NOT be changed. */
  176451. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  176452. #define PNG_SCALE_METER 1 /* meters per pixel */
  176453. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  176454. #define PNG_SCALE_LAST 3 /* Not a valid value */
  176455. /* These are for the pHYs chunk. These values should NOT be changed. */
  176456. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  176457. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  176458. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  176459. /* These are for the sRGB chunk. These values should NOT be changed. */
  176460. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  176461. #define PNG_sRGB_INTENT_RELATIVE 1
  176462. #define PNG_sRGB_INTENT_SATURATION 2
  176463. #define PNG_sRGB_INTENT_ABSOLUTE 3
  176464. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  176465. /* This is for text chunks */
  176466. #define PNG_KEYWORD_MAX_LENGTH 79
  176467. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  176468. #define PNG_MAX_PALETTE_LENGTH 256
  176469. /* These determine if an ancillary chunk's data has been successfully read
  176470. * from the PNG header, or if the application has filled in the corresponding
  176471. * data in the info_struct to be written into the output file. The values
  176472. * of the PNG_INFO_<chunk> defines should NOT be changed.
  176473. */
  176474. #define PNG_INFO_gAMA 0x0001
  176475. #define PNG_INFO_sBIT 0x0002
  176476. #define PNG_INFO_cHRM 0x0004
  176477. #define PNG_INFO_PLTE 0x0008
  176478. #define PNG_INFO_tRNS 0x0010
  176479. #define PNG_INFO_bKGD 0x0020
  176480. #define PNG_INFO_hIST 0x0040
  176481. #define PNG_INFO_pHYs 0x0080
  176482. #define PNG_INFO_oFFs 0x0100
  176483. #define PNG_INFO_tIME 0x0200
  176484. #define PNG_INFO_pCAL 0x0400
  176485. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  176486. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  176487. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  176488. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  176489. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  176490. /* This is used for the transformation routines, as some of them
  176491. * change these values for the row. It also should enable using
  176492. * the routines for other purposes.
  176493. */
  176494. typedef struct png_row_info_struct
  176495. {
  176496. png_uint_32 width; /* width of row */
  176497. png_uint_32 rowbytes; /* number of bytes in row */
  176498. png_byte color_type; /* color type of row */
  176499. png_byte bit_depth; /* bit depth of row */
  176500. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  176501. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  176502. } png_row_info;
  176503. typedef png_row_info FAR * png_row_infop;
  176504. typedef png_row_info FAR * FAR * png_row_infopp;
  176505. /* These are the function types for the I/O functions and for the functions
  176506. * that allow the user to override the default I/O functions with his or her
  176507. * own. The png_error_ptr type should match that of user-supplied warning
  176508. * and error functions, while the png_rw_ptr type should match that of the
  176509. * user read/write data functions.
  176510. */
  176511. typedef struct png_struct_def png_struct;
  176512. typedef png_struct FAR * png_structp;
  176513. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  176514. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  176515. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  176516. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  176517. int));
  176518. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  176519. int));
  176520. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  176521. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  176522. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  176523. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  176524. png_uint_32, int));
  176525. #endif
  176526. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  176527. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  176528. defined(PNG_LEGACY_SUPPORTED)
  176529. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  176530. png_row_infop, png_bytep));
  176531. #endif
  176532. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  176533. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  176534. #endif
  176535. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176536. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  176537. #endif
  176538. /* Transform masks for the high-level interface */
  176539. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  176540. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  176541. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  176542. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  176543. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  176544. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  176545. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  176546. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  176547. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  176548. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  176549. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  176550. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  176551. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  176552. /* Flags for MNG supported features */
  176553. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  176554. #define PNG_FLAG_MNG_FILTER_64 0x04
  176555. #define PNG_ALL_MNG_FEATURES 0x05
  176556. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  176557. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  176558. /* The structure that holds the information to read and write PNG files.
  176559. * The only people who need to care about what is inside of this are the
  176560. * people who will be modifying the library for their own special needs.
  176561. * It should NOT be accessed directly by an application, except to store
  176562. * the jmp_buf.
  176563. */
  176564. struct png_struct_def
  176565. {
  176566. #ifdef PNG_SETJMP_SUPPORTED
  176567. jmp_buf jmpbuf; /* used in png_error */
  176568. #endif
  176569. png_error_ptr error_fn; /* function for printing errors and aborting */
  176570. png_error_ptr warning_fn; /* function for printing warnings */
  176571. png_voidp error_ptr; /* user supplied struct for error functions */
  176572. png_rw_ptr write_data_fn; /* function for writing output data */
  176573. png_rw_ptr read_data_fn; /* function for reading input data */
  176574. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  176575. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  176576. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  176577. #endif
  176578. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  176579. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  176580. #endif
  176581. /* These were added in libpng-1.0.2 */
  176582. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  176583. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  176584. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  176585. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  176586. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  176587. png_byte user_transform_channels; /* channels in user transformed pixels */
  176588. #endif
  176589. #endif
  176590. png_uint_32 mode; /* tells us where we are in the PNG file */
  176591. png_uint_32 flags; /* flags indicating various things to libpng */
  176592. png_uint_32 transformations; /* which transformations to perform */
  176593. z_stream zstream; /* pointer to decompression structure (below) */
  176594. png_bytep zbuf; /* buffer for zlib */
  176595. png_size_t zbuf_size; /* size of zbuf */
  176596. int zlib_level; /* holds zlib compression level */
  176597. int zlib_method; /* holds zlib compression method */
  176598. int zlib_window_bits; /* holds zlib compression window bits */
  176599. int zlib_mem_level; /* holds zlib compression memory level */
  176600. int zlib_strategy; /* holds zlib compression strategy */
  176601. png_uint_32 width; /* width of image in pixels */
  176602. png_uint_32 height; /* height of image in pixels */
  176603. png_uint_32 num_rows; /* number of rows in current pass */
  176604. png_uint_32 usr_width; /* width of row at start of write */
  176605. png_uint_32 rowbytes; /* size of row in bytes */
  176606. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  176607. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  176608. png_uint_32 row_number; /* current row in interlace pass */
  176609. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  176610. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  176611. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  176612. png_bytep up_row; /* buffer to save "up" row when filtering */
  176613. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  176614. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  176615. png_row_info row_info; /* used for transformation routines */
  176616. png_uint_32 idat_size; /* current IDAT size for read */
  176617. png_uint_32 crc; /* current chunk CRC value */
  176618. png_colorp palette; /* palette from the input file */
  176619. png_uint_16 num_palette; /* number of color entries in palette */
  176620. png_uint_16 num_trans; /* number of transparency values */
  176621. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  176622. png_byte compression; /* file compression type (always 0) */
  176623. png_byte filter; /* file filter type (always 0) */
  176624. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  176625. png_byte pass; /* current interlace pass (0 - 6) */
  176626. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  176627. png_byte color_type; /* color type of file */
  176628. png_byte bit_depth; /* bit depth of file */
  176629. png_byte usr_bit_depth; /* bit depth of users row */
  176630. png_byte pixel_depth; /* number of bits per pixel */
  176631. png_byte channels; /* number of channels in file */
  176632. png_byte usr_channels; /* channels at start of write */
  176633. png_byte sig_bytes; /* magic bytes read/written from start of file */
  176634. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  176635. #ifdef PNG_LEGACY_SUPPORTED
  176636. png_byte filler; /* filler byte for pixel expansion */
  176637. #else
  176638. png_uint_16 filler; /* filler bytes for pixel expansion */
  176639. #endif
  176640. #endif
  176641. #if defined(PNG_bKGD_SUPPORTED)
  176642. png_byte background_gamma_type;
  176643. # ifdef PNG_FLOATING_POINT_SUPPORTED
  176644. float background_gamma;
  176645. # endif
  176646. png_color_16 background; /* background color in screen gamma space */
  176647. #if defined(PNG_READ_GAMMA_SUPPORTED)
  176648. png_color_16 background_1; /* background normalized to gamma 1.0 */
  176649. #endif
  176650. #endif /* PNG_bKGD_SUPPORTED */
  176651. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  176652. png_flush_ptr output_flush_fn;/* Function for flushing output */
  176653. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  176654. png_uint_32 flush_rows; /* number of rows written since last flush */
  176655. #endif
  176656. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  176657. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  176658. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176659. float gamma; /* file gamma value */
  176660. float screen_gamma; /* screen gamma value (display_exponent) */
  176661. #endif
  176662. #endif
  176663. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  176664. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  176665. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  176666. png_bytep gamma_to_1; /* converts from file to 1.0 */
  176667. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  176668. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  176669. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  176670. #endif
  176671. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  176672. png_color_8 sig_bit; /* significant bits in each available channel */
  176673. #endif
  176674. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  176675. png_color_8 shift; /* shift for significant bit tranformation */
  176676. #endif
  176677. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  176678. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  176679. png_bytep trans; /* transparency values for paletted files */
  176680. png_color_16 trans_values; /* transparency values for non-paletted files */
  176681. #endif
  176682. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  176683. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  176684. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  176685. png_progressive_info_ptr info_fn; /* called after header data fully read */
  176686. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  176687. png_progressive_end_ptr end_fn; /* called after image is complete */
  176688. png_bytep save_buffer_ptr; /* current location in save_buffer */
  176689. png_bytep save_buffer; /* buffer for previously read data */
  176690. png_bytep current_buffer_ptr; /* current location in current_buffer */
  176691. png_bytep current_buffer; /* buffer for recently used data */
  176692. png_uint_32 push_length; /* size of current input chunk */
  176693. png_uint_32 skip_length; /* bytes to skip in input data */
  176694. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  176695. png_size_t save_buffer_max; /* total size of save_buffer */
  176696. png_size_t buffer_size; /* total amount of available input data */
  176697. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  176698. int process_mode; /* what push library is currently doing */
  176699. int cur_palette; /* current push library palette index */
  176700. # if defined(PNG_TEXT_SUPPORTED)
  176701. png_size_t current_text_size; /* current size of text input data */
  176702. png_size_t current_text_left; /* how much text left to read in input */
  176703. png_charp current_text; /* current text chunk buffer */
  176704. png_charp current_text_ptr; /* current location in current_text */
  176705. # endif /* PNG_TEXT_SUPPORTED */
  176706. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  176707. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  176708. /* for the Borland special 64K segment handler */
  176709. png_bytepp offset_table_ptr;
  176710. png_bytep offset_table;
  176711. png_uint_16 offset_table_number;
  176712. png_uint_16 offset_table_count;
  176713. png_uint_16 offset_table_count_free;
  176714. #endif
  176715. #if defined(PNG_READ_DITHER_SUPPORTED)
  176716. png_bytep palette_lookup; /* lookup table for dithering */
  176717. png_bytep dither_index; /* index translation for palette files */
  176718. #endif
  176719. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  176720. png_uint_16p hist; /* histogram */
  176721. #endif
  176722. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  176723. png_byte heuristic_method; /* heuristic for row filter selection */
  176724. png_byte num_prev_filters; /* number of weights for previous rows */
  176725. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  176726. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  176727. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  176728. png_uint_16p filter_costs; /* relative filter calculation cost */
  176729. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  176730. #endif
  176731. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  176732. png_charp time_buffer; /* String to hold RFC 1123 time text */
  176733. #endif
  176734. /* New members added in libpng-1.0.6 */
  176735. #ifdef PNG_FREE_ME_SUPPORTED
  176736. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  176737. #endif
  176738. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  176739. png_voidp user_chunk_ptr;
  176740. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  176741. #endif
  176742. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176743. int num_chunk_list;
  176744. png_bytep chunk_list;
  176745. #endif
  176746. /* New members added in libpng-1.0.3 */
  176747. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  176748. png_byte rgb_to_gray_status;
  176749. /* These were changed from png_byte in libpng-1.0.6 */
  176750. png_uint_16 rgb_to_gray_red_coeff;
  176751. png_uint_16 rgb_to_gray_green_coeff;
  176752. png_uint_16 rgb_to_gray_blue_coeff;
  176753. #endif
  176754. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  176755. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  176756. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  176757. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  176758. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  176759. #ifdef PNG_1_0_X
  176760. png_byte mng_features_permitted;
  176761. #else
  176762. png_uint_32 mng_features_permitted;
  176763. #endif /* PNG_1_0_X */
  176764. #endif
  176765. /* New member added in libpng-1.0.7 */
  176766. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  176767. png_fixed_point int_gamma;
  176768. #endif
  176769. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  176770. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  176771. png_byte filter_type;
  176772. #endif
  176773. #if defined(PNG_1_0_X)
  176774. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  176775. png_uint_32 row_buf_size;
  176776. #endif
  176777. /* New members added in libpng-1.2.0 */
  176778. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  176779. # if !defined(PNG_1_0_X)
  176780. # if defined(PNG_MMX_CODE_SUPPORTED)
  176781. png_byte mmx_bitdepth_threshold;
  176782. png_uint_32 mmx_rowbytes_threshold;
  176783. # endif
  176784. png_uint_32 asm_flags;
  176785. # endif
  176786. #endif
  176787. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  176788. #ifdef PNG_USER_MEM_SUPPORTED
  176789. png_voidp mem_ptr; /* user supplied struct for mem functions */
  176790. png_malloc_ptr malloc_fn; /* function for allocating memory */
  176791. png_free_ptr free_fn; /* function for freeing memory */
  176792. #endif
  176793. /* New member added in libpng-1.0.13 and 1.2.0 */
  176794. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  176795. #if defined(PNG_READ_DITHER_SUPPORTED)
  176796. /* The following three members were added at version 1.0.14 and 1.2.4 */
  176797. png_bytep dither_sort; /* working sort array */
  176798. png_bytep index_to_palette; /* where the original index currently is */
  176799. /* in the palette */
  176800. png_bytep palette_to_index; /* which original index points to this */
  176801. /* palette color */
  176802. #endif
  176803. /* New members added in libpng-1.0.16 and 1.2.6 */
  176804. png_byte compression_type;
  176805. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  176806. png_uint_32 user_width_max;
  176807. png_uint_32 user_height_max;
  176808. #endif
  176809. /* New member added in libpng-1.0.25 and 1.2.17 */
  176810. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176811. /* storage for unknown chunk that the library doesn't recognize. */
  176812. png_unknown_chunk unknown_chunk;
  176813. #endif
  176814. };
  176815. /* This triggers a compiler error in png.c, if png.c and png.h
  176816. * do not agree upon the version number.
  176817. */
  176818. typedef png_structp version_1_2_21;
  176819. typedef png_struct FAR * FAR * png_structpp;
  176820. /* Here are the function definitions most commonly used. This is not
  176821. * the place to find out how to use libpng. See libpng.txt for the
  176822. * full explanation, see example.c for the summary. This just provides
  176823. * a simple one line description of the use of each function.
  176824. */
  176825. /* Returns the version number of the library */
  176826. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  176827. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  176828. * Handling more than 8 bytes from the beginning of the file is an error.
  176829. */
  176830. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  176831. int num_bytes));
  176832. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  176833. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  176834. * signature, and non-zero otherwise. Having num_to_check == 0 or
  176835. * start > 7 will always fail (ie return non-zero).
  176836. */
  176837. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  176838. png_size_t num_to_check));
  176839. /* Simple signature checking function. This is the same as calling
  176840. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  176841. */
  176842. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  176843. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  176844. extern PNG_EXPORT(png_structp,png_create_read_struct)
  176845. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176846. png_error_ptr error_fn, png_error_ptr warn_fn));
  176847. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  176848. extern PNG_EXPORT(png_structp,png_create_write_struct)
  176849. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176850. png_error_ptr error_fn, png_error_ptr warn_fn));
  176851. #ifdef PNG_WRITE_SUPPORTED
  176852. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  176853. PNGARG((png_structp png_ptr));
  176854. #endif
  176855. #ifdef PNG_WRITE_SUPPORTED
  176856. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  176857. PNGARG((png_structp png_ptr, png_uint_32 size));
  176858. #endif
  176859. /* Reset the compression stream */
  176860. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  176861. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  176862. #ifdef PNG_USER_MEM_SUPPORTED
  176863. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  176864. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176865. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  176866. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  176867. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  176868. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176869. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  176870. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  176871. #endif
  176872. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  176873. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  176874. png_bytep chunk_name, png_bytep data, png_size_t length));
  176875. /* Write the start of a PNG chunk - length and chunk name. */
  176876. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  176877. png_bytep chunk_name, png_uint_32 length));
  176878. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  176879. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  176880. png_bytep data, png_size_t length));
  176881. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  176882. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  176883. /* Allocate and initialize the info structure */
  176884. extern PNG_EXPORT(png_infop,png_create_info_struct)
  176885. PNGARG((png_structp png_ptr));
  176886. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176887. /* Initialize the info structure (old interface - DEPRECATED) */
  176888. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  176889. #undef png_info_init
  176890. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  176891. png_sizeof(png_info));
  176892. #endif
  176893. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  176894. png_size_t png_info_struct_size));
  176895. /* Writes all the PNG information before the image. */
  176896. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  176897. png_infop info_ptr));
  176898. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  176899. png_infop info_ptr));
  176900. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  176901. /* read the information before the actual image data. */
  176902. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  176903. png_infop info_ptr));
  176904. #endif
  176905. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  176906. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  176907. PNGARG((png_structp png_ptr, png_timep ptime));
  176908. #endif
  176909. #if !defined(_WIN32_WCE)
  176910. /* "time.h" functions are not supported on WindowsCE */
  176911. #if defined(PNG_WRITE_tIME_SUPPORTED)
  176912. /* convert from a struct tm to png_time */
  176913. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  176914. struct tm FAR * ttime));
  176915. /* convert from time_t to png_time. Uses gmtime() */
  176916. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  176917. time_t ttime));
  176918. #endif /* PNG_WRITE_tIME_SUPPORTED */
  176919. #endif /* _WIN32_WCE */
  176920. #if defined(PNG_READ_EXPAND_SUPPORTED)
  176921. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  176922. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  176923. #if !defined(PNG_1_0_X)
  176924. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  176925. png_ptr));
  176926. #endif
  176927. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  176928. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  176929. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176930. /* Deprecated */
  176931. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  176932. #endif
  176933. #endif
  176934. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  176935. /* Use blue, green, red order for pixels. */
  176936. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  176937. #endif
  176938. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  176939. /* Expand the grayscale to 24-bit RGB if necessary. */
  176940. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  176941. #endif
  176942. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  176943. /* Reduce RGB to grayscale. */
  176944. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176945. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  176946. int error_action, double red, double green ));
  176947. #endif
  176948. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  176949. int error_action, png_fixed_point red, png_fixed_point green ));
  176950. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  176951. png_ptr));
  176952. #endif
  176953. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  176954. png_colorp palette));
  176955. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  176956. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  176957. #endif
  176958. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  176959. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  176960. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  176961. #endif
  176962. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  176963. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  176964. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  176965. #endif
  176966. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  176967. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  176968. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  176969. png_uint_32 filler, int flags));
  176970. /* The values of the PNG_FILLER_ defines should NOT be changed */
  176971. #define PNG_FILLER_BEFORE 0
  176972. #define PNG_FILLER_AFTER 1
  176973. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  176974. #if !defined(PNG_1_0_X)
  176975. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  176976. png_uint_32 filler, int flags));
  176977. #endif
  176978. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  176979. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  176980. /* Swap bytes in 16-bit depth files. */
  176981. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  176982. #endif
  176983. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  176984. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  176985. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  176986. #endif
  176987. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  176988. /* Swap packing order of pixels in bytes. */
  176989. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  176990. #endif
  176991. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  176992. /* Converts files to legal bit depths. */
  176993. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  176994. png_color_8p true_bits));
  176995. #endif
  176996. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  176997. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  176998. /* Have the code handle the interlacing. Returns the number of passes. */
  176999. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  177000. #endif
  177001. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  177002. /* Invert monochrome files */
  177003. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  177004. #endif
  177005. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  177006. /* Handle alpha and tRNS by replacing with a background color. */
  177007. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177008. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  177009. png_color_16p background_color, int background_gamma_code,
  177010. int need_expand, double background_gamma));
  177011. #endif
  177012. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  177013. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  177014. #define PNG_BACKGROUND_GAMMA_FILE 2
  177015. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  177016. #endif
  177017. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  177018. /* strip the second byte of information from a 16-bit depth file. */
  177019. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  177020. #endif
  177021. #if defined(PNG_READ_DITHER_SUPPORTED)
  177022. /* Turn on dithering, and reduce the palette to the number of colors available. */
  177023. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  177024. png_colorp palette, int num_palette, int maximum_colors,
  177025. png_uint_16p histogram, int full_dither));
  177026. #endif
  177027. #if defined(PNG_READ_GAMMA_SUPPORTED)
  177028. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  177029. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177030. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  177031. double screen_gamma, double default_file_gamma));
  177032. #endif
  177033. #endif
  177034. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177035. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  177036. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  177037. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  177038. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  177039. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  177040. int empty_plte_permitted));
  177041. #endif
  177042. #endif
  177043. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  177044. /* Set how many lines between output flushes - 0 for no flushing */
  177045. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  177046. /* Flush the current PNG output buffer */
  177047. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  177048. #endif
  177049. /* optional update palette with requested transformations */
  177050. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  177051. /* optional call to update the users info structure */
  177052. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  177053. png_infop info_ptr));
  177054. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177055. /* read one or more rows of image data. */
  177056. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  177057. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  177058. #endif
  177059. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177060. /* read a row of data. */
  177061. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  177062. png_bytep row,
  177063. png_bytep display_row));
  177064. #endif
  177065. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177066. /* read the whole image into memory at once. */
  177067. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  177068. png_bytepp image));
  177069. #endif
  177070. /* write a row of image data */
  177071. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  177072. png_bytep row));
  177073. /* write a few rows of image data */
  177074. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  177075. png_bytepp row, png_uint_32 num_rows));
  177076. /* write the image data */
  177077. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  177078. png_bytepp image));
  177079. /* writes the end of the PNG file. */
  177080. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  177081. png_infop info_ptr));
  177082. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177083. /* read the end of the PNG file. */
  177084. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  177085. png_infop info_ptr));
  177086. #endif
  177087. /* free any memory associated with the png_info_struct */
  177088. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  177089. png_infopp info_ptr_ptr));
  177090. /* free any memory associated with the png_struct and the png_info_structs */
  177091. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  177092. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  177093. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  177094. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  177095. png_infop end_info_ptr));
  177096. /* free any memory associated with the png_struct and the png_info_structs */
  177097. extern PNG_EXPORT(void,png_destroy_write_struct)
  177098. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  177099. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  177100. extern void png_write_destroy PNGARG((png_structp png_ptr));
  177101. /* set the libpng method of handling chunk CRC errors */
  177102. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  177103. int crit_action, int ancil_action));
  177104. /* Values for png_set_crc_action() to say how to handle CRC errors in
  177105. * ancillary and critical chunks, and whether to use the data contained
  177106. * therein. Note that it is impossible to "discard" data in a critical
  177107. * chunk. For versions prior to 0.90, the action was always error/quit,
  177108. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  177109. * chunks is warn/discard. These values should NOT be changed.
  177110. *
  177111. * value action:critical action:ancillary
  177112. */
  177113. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  177114. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  177115. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  177116. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  177117. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  177118. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  177119. /* These functions give the user control over the scan-line filtering in
  177120. * libpng and the compression methods used by zlib. These functions are
  177121. * mainly useful for testing, as the defaults should work with most users.
  177122. * Those users who are tight on memory or want faster performance at the
  177123. * expense of compression can modify them. See the compression library
  177124. * header file (zlib.h) for an explination of the compression functions.
  177125. */
  177126. /* set the filtering method(s) used by libpng. Currently, the only valid
  177127. * value for "method" is 0.
  177128. */
  177129. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  177130. int filters));
  177131. /* Flags for png_set_filter() to say which filters to use. The flags
  177132. * are chosen so that they don't conflict with real filter types
  177133. * below, in case they are supplied instead of the #defined constants.
  177134. * These values should NOT be changed.
  177135. */
  177136. #define PNG_NO_FILTERS 0x00
  177137. #define PNG_FILTER_NONE 0x08
  177138. #define PNG_FILTER_SUB 0x10
  177139. #define PNG_FILTER_UP 0x20
  177140. #define PNG_FILTER_AVG 0x40
  177141. #define PNG_FILTER_PAETH 0x80
  177142. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  177143. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  177144. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  177145. * These defines should NOT be changed.
  177146. */
  177147. #define PNG_FILTER_VALUE_NONE 0
  177148. #define PNG_FILTER_VALUE_SUB 1
  177149. #define PNG_FILTER_VALUE_UP 2
  177150. #define PNG_FILTER_VALUE_AVG 3
  177151. #define PNG_FILTER_VALUE_PAETH 4
  177152. #define PNG_FILTER_VALUE_LAST 5
  177153. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  177154. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  177155. * defines, either the default (minimum-sum-of-absolute-differences), or
  177156. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  177157. *
  177158. * Weights are factors >= 1.0, indicating how important it is to keep the
  177159. * filter type consistent between rows. Larger numbers mean the current
  177160. * filter is that many times as likely to be the same as the "num_weights"
  177161. * previous filters. This is cumulative for each previous row with a weight.
  177162. * There needs to be "num_weights" values in "filter_weights", or it can be
  177163. * NULL if the weights aren't being specified. Weights have no influence on
  177164. * the selection of the first row filter. Well chosen weights can (in theory)
  177165. * improve the compression for a given image.
  177166. *
  177167. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  177168. * filter type. Higher costs indicate more decoding expense, and are
  177169. * therefore less likely to be selected over a filter with lower computational
  177170. * costs. There needs to be a value in "filter_costs" for each valid filter
  177171. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  177172. * setting the costs. Costs try to improve the speed of decompression without
  177173. * unduly increasing the compressed image size.
  177174. *
  177175. * A negative weight or cost indicates the default value is to be used, and
  177176. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  177177. * The default values for both weights and costs are currently 1.0, but may
  177178. * change if good general weighting/cost heuristics can be found. If both
  177179. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  177180. * to the UNWEIGHTED method, but with added encoding time/computation.
  177181. */
  177182. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177183. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  177184. int heuristic_method, int num_weights, png_doublep filter_weights,
  177185. png_doublep filter_costs));
  177186. #endif
  177187. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  177188. /* Heuristic used for row filter selection. These defines should NOT be
  177189. * changed.
  177190. */
  177191. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  177192. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  177193. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  177194. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  177195. /* Set the library compression level. Currently, valid values range from
  177196. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  177197. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  177198. * shown that zlib compression levels 3-6 usually perform as well as level 9
  177199. * for PNG images, and do considerably fewer caclulations. In the future,
  177200. * these values may not correspond directly to the zlib compression levels.
  177201. */
  177202. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  177203. int level));
  177204. extern PNG_EXPORT(void,png_set_compression_mem_level)
  177205. PNGARG((png_structp png_ptr, int mem_level));
  177206. extern PNG_EXPORT(void,png_set_compression_strategy)
  177207. PNGARG((png_structp png_ptr, int strategy));
  177208. extern PNG_EXPORT(void,png_set_compression_window_bits)
  177209. PNGARG((png_structp png_ptr, int window_bits));
  177210. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  177211. int method));
  177212. /* These next functions are called for input/output, memory, and error
  177213. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  177214. * and call standard C I/O routines such as fread(), fwrite(), and
  177215. * fprintf(). These functions can be made to use other I/O routines
  177216. * at run time for those applications that need to handle I/O in a
  177217. * different manner by calling png_set_???_fn(). See libpng.txt for
  177218. * more information.
  177219. */
  177220. #if !defined(PNG_NO_STDIO)
  177221. /* Initialize the input/output for the PNG file to the default functions. */
  177222. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  177223. #endif
  177224. /* Replace the (error and abort), and warning functions with user
  177225. * supplied functions. If no messages are to be printed you must still
  177226. * write and use replacement functions. The replacement error_fn should
  177227. * still do a longjmp to the last setjmp location if you are using this
  177228. * method of error handling. If error_fn or warning_fn is NULL, the
  177229. * default function will be used.
  177230. */
  177231. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  177232. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  177233. /* Return the user pointer associated with the error functions */
  177234. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  177235. /* Replace the default data output functions with a user supplied one(s).
  177236. * If buffered output is not used, then output_flush_fn can be set to NULL.
  177237. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  177238. * output_flush_fn will be ignored (and thus can be NULL).
  177239. */
  177240. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  177241. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  177242. /* Replace the default data input function with a user supplied one. */
  177243. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  177244. png_voidp io_ptr, png_rw_ptr read_data_fn));
  177245. /* Return the user pointer associated with the I/O functions */
  177246. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  177247. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  177248. png_read_status_ptr read_row_fn));
  177249. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  177250. png_write_status_ptr write_row_fn));
  177251. #ifdef PNG_USER_MEM_SUPPORTED
  177252. /* Replace the default memory allocation functions with user supplied one(s). */
  177253. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  177254. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  177255. /* Return the user pointer associated with the memory functions */
  177256. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  177257. #endif
  177258. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  177259. defined(PNG_LEGACY_SUPPORTED)
  177260. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  177261. png_ptr, png_user_transform_ptr read_user_transform_fn));
  177262. #endif
  177263. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  177264. defined(PNG_LEGACY_SUPPORTED)
  177265. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  177266. png_ptr, png_user_transform_ptr write_user_transform_fn));
  177267. #endif
  177268. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  177269. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  177270. defined(PNG_LEGACY_SUPPORTED)
  177271. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  177272. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  177273. int user_transform_channels));
  177274. /* Return the user pointer associated with the user transform functions */
  177275. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  177276. PNGARG((png_structp png_ptr));
  177277. #endif
  177278. #ifdef PNG_USER_CHUNKS_SUPPORTED
  177279. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  177280. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  177281. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  177282. png_ptr));
  177283. #endif
  177284. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  177285. /* Sets the function callbacks for the push reader, and a pointer to a
  177286. * user-defined structure available to the callback functions.
  177287. */
  177288. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  177289. png_voidp progressive_ptr,
  177290. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  177291. png_progressive_end_ptr end_fn));
  177292. /* returns the user pointer associated with the push read functions */
  177293. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  177294. PNGARG((png_structp png_ptr));
  177295. /* function to be called when data becomes available */
  177296. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  177297. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  177298. /* function that combines rows. Not very much different than the
  177299. * png_combine_row() call. Is this even used?????
  177300. */
  177301. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  177302. png_bytep old_row, png_bytep new_row));
  177303. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  177304. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  177305. png_uint_32 size));
  177306. #if defined(PNG_1_0_X)
  177307. # define png_malloc_warn png_malloc
  177308. #else
  177309. /* Added at libpng version 1.2.4 */
  177310. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  177311. png_uint_32 size));
  177312. #endif
  177313. /* frees a pointer allocated by png_malloc() */
  177314. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  177315. #if defined(PNG_1_0_X)
  177316. /* Function to allocate memory for zlib. */
  177317. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  177318. uInt size));
  177319. /* Function to free memory for zlib */
  177320. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  177321. #endif
  177322. /* Free data that was allocated internally */
  177323. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  177324. png_infop info_ptr, png_uint_32 free_me, int num));
  177325. #ifdef PNG_FREE_ME_SUPPORTED
  177326. /* Reassign responsibility for freeing existing data, whether allocated
  177327. * by libpng or by the application */
  177328. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  177329. png_infop info_ptr, int freer, png_uint_32 mask));
  177330. #endif
  177331. /* assignments for png_data_freer */
  177332. #define PNG_DESTROY_WILL_FREE_DATA 1
  177333. #define PNG_SET_WILL_FREE_DATA 1
  177334. #define PNG_USER_WILL_FREE_DATA 2
  177335. /* Flags for png_ptr->free_me and info_ptr->free_me */
  177336. #define PNG_FREE_HIST 0x0008
  177337. #define PNG_FREE_ICCP 0x0010
  177338. #define PNG_FREE_SPLT 0x0020
  177339. #define PNG_FREE_ROWS 0x0040
  177340. #define PNG_FREE_PCAL 0x0080
  177341. #define PNG_FREE_SCAL 0x0100
  177342. #define PNG_FREE_UNKN 0x0200
  177343. #define PNG_FREE_LIST 0x0400
  177344. #define PNG_FREE_PLTE 0x1000
  177345. #define PNG_FREE_TRNS 0x2000
  177346. #define PNG_FREE_TEXT 0x4000
  177347. #define PNG_FREE_ALL 0x7fff
  177348. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  177349. #ifdef PNG_USER_MEM_SUPPORTED
  177350. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  177351. png_uint_32 size));
  177352. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  177353. png_voidp ptr));
  177354. #endif
  177355. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  177356. png_voidp s1, png_voidp s2, png_uint_32 size));
  177357. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  177358. png_voidp s1, int value, png_uint_32 size));
  177359. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  177360. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  177361. int check));
  177362. #endif /* USE_FAR_KEYWORD */
  177363. #ifndef PNG_NO_ERROR_TEXT
  177364. /* Fatal error in PNG image of libpng - can't continue */
  177365. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  177366. png_const_charp error_message));
  177367. /* The same, but the chunk name is prepended to the error string. */
  177368. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  177369. png_const_charp error_message));
  177370. #else
  177371. /* Fatal error in PNG image of libpng - can't continue */
  177372. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  177373. #endif
  177374. #ifndef PNG_NO_WARNINGS
  177375. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  177376. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  177377. png_const_charp warning_message));
  177378. #ifdef PNG_READ_SUPPORTED
  177379. /* Non-fatal error in libpng, chunk name is prepended to message. */
  177380. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  177381. png_const_charp warning_message));
  177382. #endif /* PNG_READ_SUPPORTED */
  177383. #endif /* PNG_NO_WARNINGS */
  177384. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  177385. * Similarly, the png_get_<chunk> calls are used to read values from the
  177386. * png_info_struct, either storing the parameters in the passed variables, or
  177387. * setting pointers into the png_info_struct where the data is stored. The
  177388. * png_get_<chunk> functions return a non-zero value if the data was available
  177389. * in info_ptr, or return zero and do not change any of the parameters if the
  177390. * data was not available.
  177391. *
  177392. * These functions should be used instead of directly accessing png_info
  177393. * to avoid problems with future changes in the size and internal layout of
  177394. * png_info_struct.
  177395. */
  177396. /* Returns "flag" if chunk data is valid in info_ptr. */
  177397. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  177398. png_infop info_ptr, png_uint_32 flag));
  177399. /* Returns number of bytes needed to hold a transformed row. */
  177400. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  177401. png_infop info_ptr));
  177402. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  177403. /* Returns row_pointers, which is an array of pointers to scanlines that was
  177404. returned from png_read_png(). */
  177405. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  177406. png_infop info_ptr));
  177407. /* Set row_pointers, which is an array of pointers to scanlines for use
  177408. by png_write_png(). */
  177409. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  177410. png_infop info_ptr, png_bytepp row_pointers));
  177411. #endif
  177412. /* Returns number of color channels in image. */
  177413. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  177414. png_infop info_ptr));
  177415. #ifdef PNG_EASY_ACCESS_SUPPORTED
  177416. /* Returns image width in pixels. */
  177417. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  177418. png_ptr, png_infop info_ptr));
  177419. /* Returns image height in pixels. */
  177420. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  177421. png_ptr, png_infop info_ptr));
  177422. /* Returns image bit_depth. */
  177423. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  177424. png_ptr, png_infop info_ptr));
  177425. /* Returns image color_type. */
  177426. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  177427. png_ptr, png_infop info_ptr));
  177428. /* Returns image filter_type. */
  177429. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  177430. png_ptr, png_infop info_ptr));
  177431. /* Returns image interlace_type. */
  177432. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  177433. png_ptr, png_infop info_ptr));
  177434. /* Returns image compression_type. */
  177435. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  177436. png_ptr, png_infop info_ptr));
  177437. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  177438. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  177439. png_ptr, png_infop info_ptr));
  177440. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  177441. png_ptr, png_infop info_ptr));
  177442. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  177443. png_ptr, png_infop info_ptr));
  177444. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  177445. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177446. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  177447. png_ptr, png_infop info_ptr));
  177448. #endif
  177449. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  177450. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  177451. png_ptr, png_infop info_ptr));
  177452. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  177453. png_ptr, png_infop info_ptr));
  177454. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  177455. png_ptr, png_infop info_ptr));
  177456. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  177457. png_ptr, png_infop info_ptr));
  177458. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  177459. /* Returns pointer to signature string read from PNG header */
  177460. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  177461. png_infop info_ptr));
  177462. #if defined(PNG_bKGD_SUPPORTED)
  177463. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  177464. png_infop info_ptr, png_color_16p *background));
  177465. #endif
  177466. #if defined(PNG_bKGD_SUPPORTED)
  177467. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  177468. png_infop info_ptr, png_color_16p background));
  177469. #endif
  177470. #if defined(PNG_cHRM_SUPPORTED)
  177471. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177472. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  177473. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  177474. double *red_y, double *green_x, double *green_y, double *blue_x,
  177475. double *blue_y));
  177476. #endif
  177477. #ifdef PNG_FIXED_POINT_SUPPORTED
  177478. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  177479. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  177480. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  177481. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  177482. *int_blue_x, png_fixed_point *int_blue_y));
  177483. #endif
  177484. #endif
  177485. #if defined(PNG_cHRM_SUPPORTED)
  177486. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177487. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  177488. png_infop info_ptr, double white_x, double white_y, double red_x,
  177489. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  177490. #endif
  177491. #ifdef PNG_FIXED_POINT_SUPPORTED
  177492. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  177493. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  177494. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  177495. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  177496. png_fixed_point int_blue_y));
  177497. #endif
  177498. #endif
  177499. #if defined(PNG_gAMA_SUPPORTED)
  177500. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177501. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  177502. png_infop info_ptr, double *file_gamma));
  177503. #endif
  177504. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  177505. png_infop info_ptr, png_fixed_point *int_file_gamma));
  177506. #endif
  177507. #if defined(PNG_gAMA_SUPPORTED)
  177508. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177509. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  177510. png_infop info_ptr, double file_gamma));
  177511. #endif
  177512. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  177513. png_infop info_ptr, png_fixed_point int_file_gamma));
  177514. #endif
  177515. #if defined(PNG_hIST_SUPPORTED)
  177516. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  177517. png_infop info_ptr, png_uint_16p *hist));
  177518. #endif
  177519. #if defined(PNG_hIST_SUPPORTED)
  177520. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  177521. png_infop info_ptr, png_uint_16p hist));
  177522. #endif
  177523. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  177524. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  177525. int *bit_depth, int *color_type, int *interlace_method,
  177526. int *compression_method, int *filter_method));
  177527. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  177528. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  177529. int color_type, int interlace_method, int compression_method,
  177530. int filter_method));
  177531. #if defined(PNG_oFFs_SUPPORTED)
  177532. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  177533. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  177534. int *unit_type));
  177535. #endif
  177536. #if defined(PNG_oFFs_SUPPORTED)
  177537. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  177538. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  177539. int unit_type));
  177540. #endif
  177541. #if defined(PNG_pCAL_SUPPORTED)
  177542. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  177543. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  177544. int *type, int *nparams, png_charp *units, png_charpp *params));
  177545. #endif
  177546. #if defined(PNG_pCAL_SUPPORTED)
  177547. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  177548. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  177549. int type, int nparams, png_charp units, png_charpp params));
  177550. #endif
  177551. #if defined(PNG_pHYs_SUPPORTED)
  177552. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  177553. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  177554. #endif
  177555. #if defined(PNG_pHYs_SUPPORTED)
  177556. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  177557. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  177558. #endif
  177559. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  177560. png_infop info_ptr, png_colorp *palette, int *num_palette));
  177561. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  177562. png_infop info_ptr, png_colorp palette, int num_palette));
  177563. #if defined(PNG_sBIT_SUPPORTED)
  177564. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  177565. png_infop info_ptr, png_color_8p *sig_bit));
  177566. #endif
  177567. #if defined(PNG_sBIT_SUPPORTED)
  177568. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  177569. png_infop info_ptr, png_color_8p sig_bit));
  177570. #endif
  177571. #if defined(PNG_sRGB_SUPPORTED)
  177572. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  177573. png_infop info_ptr, int *intent));
  177574. #endif
  177575. #if defined(PNG_sRGB_SUPPORTED)
  177576. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  177577. png_infop info_ptr, int intent));
  177578. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  177579. png_infop info_ptr, int intent));
  177580. #endif
  177581. #if defined(PNG_iCCP_SUPPORTED)
  177582. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  177583. png_infop info_ptr, png_charpp name, int *compression_type,
  177584. png_charpp profile, png_uint_32 *proflen));
  177585. /* Note to maintainer: profile should be png_bytepp */
  177586. #endif
  177587. #if defined(PNG_iCCP_SUPPORTED)
  177588. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  177589. png_infop info_ptr, png_charp name, int compression_type,
  177590. png_charp profile, png_uint_32 proflen));
  177591. /* Note to maintainer: profile should be png_bytep */
  177592. #endif
  177593. #if defined(PNG_sPLT_SUPPORTED)
  177594. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  177595. png_infop info_ptr, png_sPLT_tpp entries));
  177596. #endif
  177597. #if defined(PNG_sPLT_SUPPORTED)
  177598. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  177599. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  177600. #endif
  177601. #if defined(PNG_TEXT_SUPPORTED)
  177602. /* png_get_text also returns the number of text chunks in *num_text */
  177603. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  177604. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  177605. #endif
  177606. /*
  177607. * Note while png_set_text() will accept a structure whose text,
  177608. * language, and translated keywords are NULL pointers, the structure
  177609. * returned by png_get_text will always contain regular
  177610. * zero-terminated C strings. They might be empty strings but
  177611. * they will never be NULL pointers.
  177612. */
  177613. #if defined(PNG_TEXT_SUPPORTED)
  177614. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  177615. png_infop info_ptr, png_textp text_ptr, int num_text));
  177616. #endif
  177617. #if defined(PNG_tIME_SUPPORTED)
  177618. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  177619. png_infop info_ptr, png_timep *mod_time));
  177620. #endif
  177621. #if defined(PNG_tIME_SUPPORTED)
  177622. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  177623. png_infop info_ptr, png_timep mod_time));
  177624. #endif
  177625. #if defined(PNG_tRNS_SUPPORTED)
  177626. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  177627. png_infop info_ptr, png_bytep *trans, int *num_trans,
  177628. png_color_16p *trans_values));
  177629. #endif
  177630. #if defined(PNG_tRNS_SUPPORTED)
  177631. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  177632. png_infop info_ptr, png_bytep trans, int num_trans,
  177633. png_color_16p trans_values));
  177634. #endif
  177635. #if defined(PNG_tRNS_SUPPORTED)
  177636. #endif
  177637. #if defined(PNG_sCAL_SUPPORTED)
  177638. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177639. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  177640. png_infop info_ptr, int *unit, double *width, double *height));
  177641. #else
  177642. #ifdef PNG_FIXED_POINT_SUPPORTED
  177643. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  177644. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  177645. #endif
  177646. #endif
  177647. #endif /* PNG_sCAL_SUPPORTED */
  177648. #if defined(PNG_sCAL_SUPPORTED)
  177649. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177650. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  177651. png_infop info_ptr, int unit, double width, double height));
  177652. #else
  177653. #ifdef PNG_FIXED_POINT_SUPPORTED
  177654. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  177655. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  177656. #endif
  177657. #endif
  177658. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  177659. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177660. /* provide a list of chunks and how they are to be handled, if the built-in
  177661. handling or default unknown chunk handling is not desired. Any chunks not
  177662. listed will be handled in the default manner. The IHDR and IEND chunks
  177663. must not be listed.
  177664. keep = 0: follow default behaviour
  177665. = 1: do not keep
  177666. = 2: keep only if safe-to-copy
  177667. = 3: keep even if unsafe-to-copy
  177668. */
  177669. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  177670. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  177671. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  177672. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  177673. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  177674. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  177675. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  177676. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  177677. #endif
  177678. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  177679. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  177680. chunk_name));
  177681. #endif
  177682. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  177683. If you need to turn it off for a chunk that your application has freed,
  177684. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  177685. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  177686. png_infop info_ptr, int mask));
  177687. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  177688. /* The "params" pointer is currently not used and is for future expansion. */
  177689. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  177690. png_infop info_ptr,
  177691. int transforms,
  177692. png_voidp params));
  177693. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  177694. png_infop info_ptr,
  177695. int transforms,
  177696. png_voidp params));
  177697. #endif
  177698. /* Define PNG_DEBUG at compile time for debugging information. Higher
  177699. * numbers for PNG_DEBUG mean more debugging information. This has
  177700. * only been added since version 0.95 so it is not implemented throughout
  177701. * libpng yet, but more support will be added as needed.
  177702. */
  177703. #ifdef PNG_DEBUG
  177704. #if (PNG_DEBUG > 0)
  177705. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  177706. #include <crtdbg.h>
  177707. #if (PNG_DEBUG > 1)
  177708. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  177709. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  177710. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  177711. #endif
  177712. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  177713. #ifndef PNG_DEBUG_FILE
  177714. #define PNG_DEBUG_FILE stderr
  177715. #endif /* PNG_DEBUG_FILE */
  177716. #if (PNG_DEBUG > 1)
  177717. #define png_debug(l,m) \
  177718. { \
  177719. int num_tabs=l; \
  177720. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  177721. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  177722. }
  177723. #define png_debug1(l,m,p1) \
  177724. { \
  177725. int num_tabs=l; \
  177726. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  177727. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  177728. }
  177729. #define png_debug2(l,m,p1,p2) \
  177730. { \
  177731. int num_tabs=l; \
  177732. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  177733. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  177734. }
  177735. #endif /* (PNG_DEBUG > 1) */
  177736. #endif /* _MSC_VER */
  177737. #endif /* (PNG_DEBUG > 0) */
  177738. #endif /* PNG_DEBUG */
  177739. #ifndef png_debug
  177740. #define png_debug(l, m)
  177741. #endif
  177742. #ifndef png_debug1
  177743. #define png_debug1(l, m, p1)
  177744. #endif
  177745. #ifndef png_debug2
  177746. #define png_debug2(l, m, p1, p2)
  177747. #endif
  177748. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  177749. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  177750. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  177751. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  177752. #ifdef PNG_MNG_FEATURES_SUPPORTED
  177753. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  177754. png_ptr, png_uint_32 mng_features_permitted));
  177755. #endif
  177756. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  177757. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  177758. #define PNG_HANDLE_CHUNK_NEVER 1
  177759. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  177760. #define PNG_HANDLE_CHUNK_ALWAYS 3
  177761. /* Added to version 1.2.0 */
  177762. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  177763. #if defined(PNG_MMX_CODE_SUPPORTED)
  177764. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  177765. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  177766. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  177767. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  177768. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  177769. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  177770. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  177771. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  177772. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  177773. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  177774. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  177775. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  177776. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  177777. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  177778. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  177779. #define PNG_MMX_WRITE_FLAGS ( 0 )
  177780. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  177781. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  177782. | PNG_MMX_READ_FLAGS \
  177783. | PNG_MMX_WRITE_FLAGS )
  177784. #define PNG_SELECT_READ 1
  177785. #define PNG_SELECT_WRITE 2
  177786. #endif /* PNG_MMX_CODE_SUPPORTED */
  177787. #if !defined(PNG_1_0_X)
  177788. /* pngget.c */
  177789. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  177790. PNGARG((int flag_select, int *compilerID));
  177791. /* pngget.c */
  177792. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  177793. PNGARG((int flag_select));
  177794. /* pngget.c */
  177795. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  177796. PNGARG((png_structp png_ptr));
  177797. /* pngget.c */
  177798. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  177799. PNGARG((png_structp png_ptr));
  177800. /* pngget.c */
  177801. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  177802. PNGARG((png_structp png_ptr));
  177803. /* pngset.c */
  177804. extern PNG_EXPORT(void,png_set_asm_flags)
  177805. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  177806. /* pngset.c */
  177807. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  177808. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  177809. png_uint_32 mmx_rowbytes_threshold));
  177810. #endif /* PNG_1_0_X */
  177811. #if !defined(PNG_1_0_X)
  177812. /* png.c, pnggccrd.c, or pngvcrd.c */
  177813. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  177814. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  177815. /* Strip the prepended error numbers ("#nnn ") from error and warning
  177816. * messages before passing them to the error or warning handler. */
  177817. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  177818. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  177819. png_ptr, png_uint_32 strip_mode));
  177820. #endif
  177821. #endif /* PNG_1_0_X */
  177822. /* Added at libpng-1.2.6 */
  177823. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  177824. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  177825. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  177826. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  177827. png_ptr));
  177828. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  177829. png_ptr));
  177830. #endif
  177831. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  177832. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  177833. /* With these routines we avoid an integer divide, which will be slower on
  177834. * most machines. However, it does take more operations than the corresponding
  177835. * divide method, so it may be slower on a few RISC systems. There are two
  177836. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  177837. *
  177838. * Note that the rounding factors are NOT supposed to be the same! 128 and
  177839. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  177840. * standard method.
  177841. *
  177842. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  177843. */
  177844. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  177845. # define png_composite(composite, fg, alpha, bg) \
  177846. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  177847. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  177848. (png_uint_16)(alpha)) + (png_uint_16)128); \
  177849. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  177850. # define png_composite_16(composite, fg, alpha, bg) \
  177851. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  177852. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  177853. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  177854. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  177855. #else /* standard method using integer division */
  177856. # define png_composite(composite, fg, alpha, bg) \
  177857. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  177858. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  177859. (png_uint_16)127) / 255)
  177860. # define png_composite_16(composite, fg, alpha, bg) \
  177861. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  177862. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  177863. (png_uint_32)32767) / (png_uint_32)65535L)
  177864. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  177865. /* Inline macros to do direct reads of bytes from the input buffer. These
  177866. * require that you are using an architecture that uses PNG byte ordering
  177867. * (MSB first) and supports unaligned data storage. I think that PowerPC
  177868. * in big-endian mode and 680x0 are the only ones that will support this.
  177869. * The x86 line of processors definitely do not. The png_get_int_32()
  177870. * routine also assumes we are using two's complement format for negative
  177871. * values, which is almost certainly true.
  177872. */
  177873. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  177874. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  177875. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  177876. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  177877. #else
  177878. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  177879. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  177880. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  177881. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  177882. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  177883. PNGARG((png_structp png_ptr, png_bytep buf));
  177884. /* No png_get_int_16 -- may be added if there's a real need for it. */
  177885. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  177886. */
  177887. extern PNG_EXPORT(void,png_save_uint_32)
  177888. PNGARG((png_bytep buf, png_uint_32 i));
  177889. extern PNG_EXPORT(void,png_save_int_32)
  177890. PNGARG((png_bytep buf, png_int_32 i));
  177891. /* Place a 16-bit number into a buffer in PNG byte order.
  177892. * The parameter is declared unsigned int, not png_uint_16,
  177893. * just to avoid potential problems on pre-ANSI C compilers.
  177894. */
  177895. extern PNG_EXPORT(void,png_save_uint_16)
  177896. PNGARG((png_bytep buf, unsigned int i));
  177897. /* No png_save_int_16 -- may be added if there's a real need for it. */
  177898. /* ************************************************************************* */
  177899. /* These next functions are used internally in the code. They generally
  177900. * shouldn't be used unless you are writing code to add or replace some
  177901. * functionality in libpng. More information about most functions can
  177902. * be found in the files where the functions are located.
  177903. */
  177904. /* Various modes of operation, that are visible to applications because
  177905. * they are used for unknown chunk location.
  177906. */
  177907. #define PNG_HAVE_IHDR 0x01
  177908. #define PNG_HAVE_PLTE 0x02
  177909. #define PNG_HAVE_IDAT 0x04
  177910. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  177911. #define PNG_HAVE_IEND 0x10
  177912. #if defined(PNG_INTERNAL)
  177913. /* More modes of operation. Note that after an init, mode is set to
  177914. * zero automatically when the structure is created.
  177915. */
  177916. #define PNG_HAVE_gAMA 0x20
  177917. #define PNG_HAVE_cHRM 0x40
  177918. #define PNG_HAVE_sRGB 0x80
  177919. #define PNG_HAVE_CHUNK_HEADER 0x100
  177920. #define PNG_WROTE_tIME 0x200
  177921. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  177922. #define PNG_BACKGROUND_IS_GRAY 0x800
  177923. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  177924. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  177925. /* flags for the transformations the PNG library does on the image data */
  177926. #define PNG_BGR 0x0001
  177927. #define PNG_INTERLACE 0x0002
  177928. #define PNG_PACK 0x0004
  177929. #define PNG_SHIFT 0x0008
  177930. #define PNG_SWAP_BYTES 0x0010
  177931. #define PNG_INVERT_MONO 0x0020
  177932. #define PNG_DITHER 0x0040
  177933. #define PNG_BACKGROUND 0x0080
  177934. #define PNG_BACKGROUND_EXPAND 0x0100
  177935. /* 0x0200 unused */
  177936. #define PNG_16_TO_8 0x0400
  177937. #define PNG_RGBA 0x0800
  177938. #define PNG_EXPAND 0x1000
  177939. #define PNG_GAMMA 0x2000
  177940. #define PNG_GRAY_TO_RGB 0x4000
  177941. #define PNG_FILLER 0x8000L
  177942. #define PNG_PACKSWAP 0x10000L
  177943. #define PNG_SWAP_ALPHA 0x20000L
  177944. #define PNG_STRIP_ALPHA 0x40000L
  177945. #define PNG_INVERT_ALPHA 0x80000L
  177946. #define PNG_USER_TRANSFORM 0x100000L
  177947. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  177948. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  177949. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  177950. /* 0x800000L Unused */
  177951. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  177952. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  177953. /* 0x4000000L unused */
  177954. /* 0x8000000L unused */
  177955. /* 0x10000000L unused */
  177956. /* 0x20000000L unused */
  177957. /* 0x40000000L unused */
  177958. /* flags for png_create_struct */
  177959. #define PNG_STRUCT_PNG 0x0001
  177960. #define PNG_STRUCT_INFO 0x0002
  177961. /* Scaling factor for filter heuristic weighting calculations */
  177962. #define PNG_WEIGHT_SHIFT 8
  177963. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  177964. #define PNG_COST_SHIFT 3
  177965. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  177966. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  177967. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  177968. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  177969. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  177970. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  177971. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  177972. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  177973. #define PNG_FLAG_ROW_INIT 0x0040
  177974. #define PNG_FLAG_FILLER_AFTER 0x0080
  177975. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  177976. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  177977. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  177978. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  177979. #define PNG_FLAG_FREE_PLTE 0x1000
  177980. #define PNG_FLAG_FREE_TRNS 0x2000
  177981. #define PNG_FLAG_FREE_HIST 0x4000
  177982. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  177983. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  177984. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  177985. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  177986. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  177987. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  177988. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  177989. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  177990. /* 0x800000L unused */
  177991. /* 0x1000000L unused */
  177992. /* 0x2000000L unused */
  177993. /* 0x4000000L unused */
  177994. /* 0x8000000L unused */
  177995. /* 0x10000000L unused */
  177996. /* 0x20000000L unused */
  177997. /* 0x40000000L unused */
  177998. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  177999. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  178000. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  178001. PNG_FLAG_CRC_CRITICAL_IGNORE)
  178002. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  178003. PNG_FLAG_CRC_CRITICAL_MASK)
  178004. /* save typing and make code easier to understand */
  178005. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  178006. abs((int)((c1).green) - (int)((c2).green)) + \
  178007. abs((int)((c1).blue) - (int)((c2).blue)))
  178008. /* Added to libpng-1.2.6 JB */
  178009. #define PNG_ROWBYTES(pixel_bits, width) \
  178010. ((pixel_bits) >= 8 ? \
  178011. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  178012. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  178013. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  178014. ideal-delta..ideal+delta. Each argument is evaluated twice.
  178015. "ideal" and "delta" should be constants, normally simple
  178016. integers, "value" a variable. Added to libpng-1.2.6 JB */
  178017. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  178018. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  178019. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  178020. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  178021. /* place to hold the signature string for a PNG file. */
  178022. #ifdef PNG_USE_GLOBAL_ARRAYS
  178023. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  178024. #else
  178025. #endif
  178026. #endif /* PNG_NO_EXTERN */
  178027. /* Constant strings for known chunk types. If you need to add a chunk,
  178028. * define the name here, and add an invocation of the macro in png.c and
  178029. * wherever it's needed.
  178030. */
  178031. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  178032. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  178033. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  178034. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  178035. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  178036. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  178037. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  178038. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  178039. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  178040. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  178041. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  178042. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  178043. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  178044. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  178045. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  178046. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  178047. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  178048. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  178049. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  178050. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  178051. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  178052. #ifdef PNG_USE_GLOBAL_ARRAYS
  178053. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  178054. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  178055. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  178056. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  178057. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  178058. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  178059. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  178060. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  178061. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  178062. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  178063. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  178064. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  178065. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  178066. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  178067. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  178068. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  178069. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  178070. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  178071. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  178072. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  178073. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  178074. #endif /* PNG_USE_GLOBAL_ARRAYS */
  178075. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178076. /* Initialize png_ptr struct for reading, and allocate any other memory.
  178077. * (old interface - DEPRECATED - use png_create_read_struct instead).
  178078. */
  178079. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  178080. #undef png_read_init
  178081. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  178082. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  178083. #endif
  178084. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  178085. png_const_charp user_png_ver, png_size_t png_struct_size));
  178086. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178087. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  178088. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  178089. png_info_size));
  178090. #endif
  178091. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178092. /* Initialize png_ptr struct for writing, and allocate any other memory.
  178093. * (old interface - DEPRECATED - use png_create_write_struct instead).
  178094. */
  178095. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  178096. #undef png_write_init
  178097. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  178098. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  178099. #endif
  178100. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  178101. png_const_charp user_png_ver, png_size_t png_struct_size));
  178102. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  178103. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  178104. png_info_size));
  178105. /* Allocate memory for an internal libpng struct */
  178106. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  178107. /* Free memory from internal libpng struct */
  178108. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  178109. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  178110. malloc_fn, png_voidp mem_ptr));
  178111. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  178112. png_free_ptr free_fn, png_voidp mem_ptr));
  178113. /* Free any memory that info_ptr points to and reset struct. */
  178114. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  178115. png_infop info_ptr));
  178116. #ifndef PNG_1_0_X
  178117. /* Function to allocate memory for zlib. */
  178118. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  178119. /* Function to free memory for zlib */
  178120. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  178121. #ifdef PNG_SIZE_T
  178122. /* Function to convert a sizeof an item to png_sizeof item */
  178123. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  178124. #endif
  178125. /* Next four functions are used internally as callbacks. PNGAPI is required
  178126. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  178127. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  178128. png_bytep data, png_size_t length));
  178129. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178130. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  178131. png_bytep buffer, png_size_t length));
  178132. #endif
  178133. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  178134. png_bytep data, png_size_t length));
  178135. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  178136. #if !defined(PNG_NO_STDIO)
  178137. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  178138. #endif
  178139. #endif
  178140. #else /* PNG_1_0_X */
  178141. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178142. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  178143. png_bytep buffer, png_size_t length));
  178144. #endif
  178145. #endif /* PNG_1_0_X */
  178146. /* Reset the CRC variable */
  178147. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  178148. /* Write the "data" buffer to whatever output you are using. */
  178149. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  178150. png_size_t length));
  178151. /* Read data from whatever input you are using into the "data" buffer */
  178152. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  178153. png_size_t length));
  178154. /* Read bytes into buf, and update png_ptr->crc */
  178155. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  178156. png_size_t length));
  178157. /* Decompress data in a chunk that uses compression */
  178158. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  178159. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  178160. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  178161. int comp_type, png_charp chunkdata, png_size_t chunklength,
  178162. png_size_t prefix_length, png_size_t *data_length));
  178163. #endif
  178164. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  178165. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  178166. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  178167. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  178168. /* Calculate the CRC over a section of data. Note that we are only
  178169. * passing a maximum of 64K on systems that have this as a memory limit,
  178170. * since this is the maximum buffer size we can specify.
  178171. */
  178172. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  178173. png_size_t length));
  178174. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  178175. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  178176. #endif
  178177. /* simple function to write the signature */
  178178. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  178179. /* write various chunks */
  178180. /* Write the IHDR chunk, and update the png_struct with the necessary
  178181. * information.
  178182. */
  178183. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  178184. png_uint_32 height,
  178185. int bit_depth, int color_type, int compression_method, int filter_method,
  178186. int interlace_method));
  178187. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  178188. png_uint_32 num_pal));
  178189. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  178190. png_size_t length));
  178191. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  178192. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  178193. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178194. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  178195. #endif
  178196. #ifdef PNG_FIXED_POINT_SUPPORTED
  178197. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  178198. file_gamma));
  178199. #endif
  178200. #endif
  178201. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  178202. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  178203. int color_type));
  178204. #endif
  178205. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  178206. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178207. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  178208. double white_x, double white_y,
  178209. double red_x, double red_y, double green_x, double green_y,
  178210. double blue_x, double blue_y));
  178211. #endif
  178212. #ifdef PNG_FIXED_POINT_SUPPORTED
  178213. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  178214. png_fixed_point int_white_x, png_fixed_point int_white_y,
  178215. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  178216. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  178217. png_fixed_point int_blue_y));
  178218. #endif
  178219. #endif
  178220. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  178221. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  178222. int intent));
  178223. #endif
  178224. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  178225. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  178226. png_charp name, int compression_type,
  178227. png_charp profile, int proflen));
  178228. /* Note to maintainer: profile should be png_bytep */
  178229. #endif
  178230. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  178231. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  178232. png_sPLT_tp palette));
  178233. #endif
  178234. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  178235. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  178236. png_color_16p values, int number, int color_type));
  178237. #endif
  178238. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  178239. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  178240. png_color_16p values, int color_type));
  178241. #endif
  178242. #if defined(PNG_WRITE_hIST_SUPPORTED)
  178243. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  178244. int num_hist));
  178245. #endif
  178246. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  178247. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  178248. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  178249. png_charp key, png_charpp new_key));
  178250. #endif
  178251. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  178252. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  178253. png_charp text, png_size_t text_len));
  178254. #endif
  178255. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  178256. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  178257. png_charp text, png_size_t text_len, int compression));
  178258. #endif
  178259. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  178260. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  178261. int compression, png_charp key, png_charp lang, png_charp lang_key,
  178262. png_charp text));
  178263. #endif
  178264. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  178265. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  178266. png_infop info_ptr, png_textp text_ptr, int num_text));
  178267. #endif
  178268. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  178269. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  178270. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  178271. #endif
  178272. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  178273. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  178274. png_int_32 X0, png_int_32 X1, int type, int nparams,
  178275. png_charp units, png_charpp params));
  178276. #endif
  178277. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  178278. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  178279. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  178280. int unit_type));
  178281. #endif
  178282. #if defined(PNG_WRITE_tIME_SUPPORTED)
  178283. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  178284. png_timep mod_time));
  178285. #endif
  178286. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  178287. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  178288. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  178289. int unit, double width, double height));
  178290. #else
  178291. #ifdef PNG_FIXED_POINT_SUPPORTED
  178292. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  178293. int unit, png_charp width, png_charp height));
  178294. #endif
  178295. #endif
  178296. #endif
  178297. /* Called when finished processing a row of data */
  178298. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  178299. /* Internal use only. Called before first row of data */
  178300. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  178301. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178302. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  178303. #endif
  178304. /* combine a row of data, dealing with alpha, etc. if requested */
  178305. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  178306. int mask));
  178307. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  178308. /* expand an interlaced row */
  178309. /* OLD pre-1.0.9 interface:
  178310. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  178311. png_bytep row, int pass, png_uint_32 transformations));
  178312. */
  178313. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  178314. #endif
  178315. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  178316. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  178317. /* grab pixels out of a row for an interlaced pass */
  178318. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  178319. png_bytep row, int pass));
  178320. #endif
  178321. /* unfilter a row */
  178322. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  178323. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  178324. /* Choose the best filter to use and filter the row data */
  178325. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  178326. png_row_infop row_info));
  178327. /* Write out the filtered row. */
  178328. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  178329. png_bytep filtered_row));
  178330. /* finish a row while reading, dealing with interlacing passes, etc. */
  178331. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  178332. /* initialize the row buffers, etc. */
  178333. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  178334. /* optional call to update the users info structure */
  178335. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  178336. png_infop info_ptr));
  178337. /* these are the functions that do the transformations */
  178338. #if defined(PNG_READ_FILLER_SUPPORTED)
  178339. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  178340. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  178341. #endif
  178342. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  178343. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  178344. png_bytep row));
  178345. #endif
  178346. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  178347. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  178348. png_bytep row));
  178349. #endif
  178350. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  178351. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  178352. png_bytep row));
  178353. #endif
  178354. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  178355. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  178356. png_bytep row));
  178357. #endif
  178358. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  178359. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  178360. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  178361. png_bytep row, png_uint_32 flags));
  178362. #endif
  178363. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  178364. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  178365. #endif
  178366. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  178367. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  178368. #endif
  178369. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  178370. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  178371. row_info, png_bytep row));
  178372. #endif
  178373. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  178374. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  178375. png_bytep row));
  178376. #endif
  178377. #if defined(PNG_READ_PACK_SUPPORTED)
  178378. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  178379. #endif
  178380. #if defined(PNG_READ_SHIFT_SUPPORTED)
  178381. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  178382. png_color_8p sig_bits));
  178383. #endif
  178384. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  178385. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  178386. #endif
  178387. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  178388. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  178389. #endif
  178390. #if defined(PNG_READ_DITHER_SUPPORTED)
  178391. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  178392. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  178393. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  178394. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  178395. png_colorp palette, int num_palette));
  178396. # endif
  178397. #endif
  178398. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  178399. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  178400. #endif
  178401. #if defined(PNG_WRITE_PACK_SUPPORTED)
  178402. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  178403. png_bytep row, png_uint_32 bit_depth));
  178404. #endif
  178405. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  178406. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  178407. png_color_8p bit_depth));
  178408. #endif
  178409. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  178410. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178411. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  178412. png_color_16p trans_values, png_color_16p background,
  178413. png_color_16p background_1,
  178414. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  178415. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  178416. png_uint_16pp gamma_16_to_1, int gamma_shift));
  178417. #else
  178418. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  178419. png_color_16p trans_values, png_color_16p background));
  178420. #endif
  178421. #endif
  178422. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178423. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  178424. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  178425. int gamma_shift));
  178426. #endif
  178427. #if defined(PNG_READ_EXPAND_SUPPORTED)
  178428. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  178429. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  178430. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  178431. png_bytep row, png_color_16p trans_value));
  178432. #endif
  178433. /* The following decodes the appropriate chunks, and does error correction,
  178434. * then calls the appropriate callback for the chunk if it is valid.
  178435. */
  178436. /* decode the IHDR chunk */
  178437. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  178438. png_uint_32 length));
  178439. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  178440. png_uint_32 length));
  178441. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  178442. png_uint_32 length));
  178443. #if defined(PNG_READ_bKGD_SUPPORTED)
  178444. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  178445. png_uint_32 length));
  178446. #endif
  178447. #if defined(PNG_READ_cHRM_SUPPORTED)
  178448. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  178449. png_uint_32 length));
  178450. #endif
  178451. #if defined(PNG_READ_gAMA_SUPPORTED)
  178452. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  178453. png_uint_32 length));
  178454. #endif
  178455. #if defined(PNG_READ_hIST_SUPPORTED)
  178456. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  178457. png_uint_32 length));
  178458. #endif
  178459. #if defined(PNG_READ_iCCP_SUPPORTED)
  178460. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  178461. png_uint_32 length));
  178462. #endif /* PNG_READ_iCCP_SUPPORTED */
  178463. #if defined(PNG_READ_iTXt_SUPPORTED)
  178464. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  178465. png_uint_32 length));
  178466. #endif
  178467. #if defined(PNG_READ_oFFs_SUPPORTED)
  178468. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  178469. png_uint_32 length));
  178470. #endif
  178471. #if defined(PNG_READ_pCAL_SUPPORTED)
  178472. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  178473. png_uint_32 length));
  178474. #endif
  178475. #if defined(PNG_READ_pHYs_SUPPORTED)
  178476. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  178477. png_uint_32 length));
  178478. #endif
  178479. #if defined(PNG_READ_sBIT_SUPPORTED)
  178480. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  178481. png_uint_32 length));
  178482. #endif
  178483. #if defined(PNG_READ_sCAL_SUPPORTED)
  178484. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  178485. png_uint_32 length));
  178486. #endif
  178487. #if defined(PNG_READ_sPLT_SUPPORTED)
  178488. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  178489. png_uint_32 length));
  178490. #endif /* PNG_READ_sPLT_SUPPORTED */
  178491. #if defined(PNG_READ_sRGB_SUPPORTED)
  178492. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  178493. png_uint_32 length));
  178494. #endif
  178495. #if defined(PNG_READ_tEXt_SUPPORTED)
  178496. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  178497. png_uint_32 length));
  178498. #endif
  178499. #if defined(PNG_READ_tIME_SUPPORTED)
  178500. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  178501. png_uint_32 length));
  178502. #endif
  178503. #if defined(PNG_READ_tRNS_SUPPORTED)
  178504. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  178505. png_uint_32 length));
  178506. #endif
  178507. #if defined(PNG_READ_zTXt_SUPPORTED)
  178508. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  178509. png_uint_32 length));
  178510. #endif
  178511. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  178512. png_infop info_ptr, png_uint_32 length));
  178513. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  178514. png_bytep chunk_name));
  178515. /* handle the transformations for reading and writing */
  178516. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  178517. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  178518. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  178519. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178520. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  178521. png_infop info_ptr));
  178522. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  178523. png_infop info_ptr));
  178524. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  178525. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  178526. png_uint_32 length));
  178527. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  178528. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  178529. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  178530. png_bytep buffer, png_size_t buffer_length));
  178531. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  178532. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  178533. png_bytep buffer, png_size_t buffer_length));
  178534. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  178535. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  178536. png_infop info_ptr, png_uint_32 length));
  178537. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  178538. png_infop info_ptr));
  178539. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  178540. png_infop info_ptr));
  178541. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  178542. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  178543. png_infop info_ptr));
  178544. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  178545. png_infop info_ptr));
  178546. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  178547. #if defined(PNG_READ_tEXt_SUPPORTED)
  178548. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  178549. png_infop info_ptr, png_uint_32 length));
  178550. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  178551. png_infop info_ptr));
  178552. #endif
  178553. #if defined(PNG_READ_zTXt_SUPPORTED)
  178554. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  178555. png_infop info_ptr, png_uint_32 length));
  178556. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  178557. png_infop info_ptr));
  178558. #endif
  178559. #if defined(PNG_READ_iTXt_SUPPORTED)
  178560. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  178561. png_infop info_ptr, png_uint_32 length));
  178562. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  178563. png_infop info_ptr));
  178564. #endif
  178565. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  178566. #ifdef PNG_MNG_FEATURES_SUPPORTED
  178567. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  178568. png_bytep row));
  178569. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  178570. png_bytep row));
  178571. #endif
  178572. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  178573. #if defined(PNG_MMX_CODE_SUPPORTED)
  178574. /* png.c */ /* PRIVATE */
  178575. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  178576. #endif
  178577. #endif
  178578. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  178579. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  178580. png_infop info_ptr));
  178581. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  178582. png_infop info_ptr));
  178583. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  178584. png_infop info_ptr));
  178585. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  178586. png_infop info_ptr));
  178587. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  178588. png_infop info_ptr));
  178589. #if defined(PNG_pHYs_SUPPORTED)
  178590. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  178591. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  178592. #endif /* PNG_pHYs_SUPPORTED */
  178593. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  178594. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  178595. #endif /* PNG_INTERNAL */
  178596. #ifdef __cplusplus
  178597. }
  178598. #endif
  178599. #endif /* PNG_VERSION_INFO_ONLY */
  178600. /* do not put anything past this line */
  178601. #endif /* PNG_H */
  178602. /********* End of inlined file: png.h *********/
  178603. #define PNG_NO_EXTERN
  178604. /********* Start of inlined file: png.c *********/
  178605. /* png.c - location for general purpose libpng functions
  178606. *
  178607. * Last changed in libpng 1.2.21 [October 4, 2007]
  178608. * For conditions of distribution and use, see copyright notice in png.h
  178609. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  178610. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  178611. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  178612. */
  178613. #define PNG_INTERNAL
  178614. #define PNG_NO_EXTERN
  178615. /* Generate a compiler error if there is an old png.h in the search path. */
  178616. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  178617. /* Version information for C files. This had better match the version
  178618. * string defined in png.h. */
  178619. #ifdef PNG_USE_GLOBAL_ARRAYS
  178620. /* png_libpng_ver was changed to a function in version 1.0.5c */
  178621. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  178622. #ifdef PNG_READ_SUPPORTED
  178623. /* png_sig was changed to a function in version 1.0.5c */
  178624. /* Place to hold the signature string for a PNG file. */
  178625. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  178626. #endif /* PNG_READ_SUPPORTED */
  178627. /* Invoke global declarations for constant strings for known chunk types */
  178628. PNG_IHDR;
  178629. PNG_IDAT;
  178630. PNG_IEND;
  178631. PNG_PLTE;
  178632. PNG_bKGD;
  178633. PNG_cHRM;
  178634. PNG_gAMA;
  178635. PNG_hIST;
  178636. PNG_iCCP;
  178637. PNG_iTXt;
  178638. PNG_oFFs;
  178639. PNG_pCAL;
  178640. PNG_sCAL;
  178641. PNG_pHYs;
  178642. PNG_sBIT;
  178643. PNG_sPLT;
  178644. PNG_sRGB;
  178645. PNG_tEXt;
  178646. PNG_tIME;
  178647. PNG_tRNS;
  178648. PNG_zTXt;
  178649. #ifdef PNG_READ_SUPPORTED
  178650. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  178651. /* start of interlace block */
  178652. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  178653. /* offset to next interlace block */
  178654. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  178655. /* start of interlace block in the y direction */
  178656. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  178657. /* offset to next interlace block in the y direction */
  178658. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  178659. /* Height of interlace block. This is not currently used - if you need
  178660. * it, uncomment it here and in png.h
  178661. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  178662. */
  178663. /* Mask to determine which pixels are valid in a pass */
  178664. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  178665. /* Mask to determine which pixels to overwrite while displaying */
  178666. PNG_CONST int FARDATA png_pass_dsp_mask[]
  178667. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  178668. #endif /* PNG_READ_SUPPORTED */
  178669. #endif /* PNG_USE_GLOBAL_ARRAYS */
  178670. /* Tells libpng that we have already handled the first "num_bytes" bytes
  178671. * of the PNG file signature. If the PNG data is embedded into another
  178672. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  178673. * or write any of the magic bytes before it starts on the IHDR.
  178674. */
  178675. #ifdef PNG_READ_SUPPORTED
  178676. void PNGAPI
  178677. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  178678. {
  178679. if(png_ptr == NULL) return;
  178680. png_debug(1, "in png_set_sig_bytes\n");
  178681. if (num_bytes > 8)
  178682. png_error(png_ptr, "Too many bytes for PNG signature.");
  178683. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  178684. }
  178685. /* Checks whether the supplied bytes match the PNG signature. We allow
  178686. * checking less than the full 8-byte signature so that those apps that
  178687. * already read the first few bytes of a file to determine the file type
  178688. * can simply check the remaining bytes for extra assurance. Returns
  178689. * an integer less than, equal to, or greater than zero if sig is found,
  178690. * respectively, to be less than, to match, or be greater than the correct
  178691. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  178692. */
  178693. int PNGAPI
  178694. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  178695. {
  178696. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  178697. if (num_to_check > 8)
  178698. num_to_check = 8;
  178699. else if (num_to_check < 1)
  178700. return (-1);
  178701. if (start > 7)
  178702. return (-1);
  178703. if (start + num_to_check > 8)
  178704. num_to_check = 8 - start;
  178705. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  178706. }
  178707. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  178708. /* (Obsolete) function to check signature bytes. It does not allow one
  178709. * to check a partial signature. This function might be removed in the
  178710. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  178711. */
  178712. int PNGAPI
  178713. png_check_sig(png_bytep sig, int num)
  178714. {
  178715. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  178716. }
  178717. #endif
  178718. #endif /* PNG_READ_SUPPORTED */
  178719. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  178720. /* Function to allocate memory for zlib and clear it to 0. */
  178721. #ifdef PNG_1_0_X
  178722. voidpf PNGAPI
  178723. #else
  178724. voidpf /* private */
  178725. #endif
  178726. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  178727. {
  178728. png_voidp ptr;
  178729. png_structp p=(png_structp)png_ptr;
  178730. png_uint_32 save_flags=p->flags;
  178731. png_uint_32 num_bytes;
  178732. if(png_ptr == NULL) return (NULL);
  178733. if (items > PNG_UINT_32_MAX/size)
  178734. {
  178735. png_warning (p, "Potential overflow in png_zalloc()");
  178736. return (NULL);
  178737. }
  178738. num_bytes = (png_uint_32)items * size;
  178739. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  178740. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  178741. p->flags=save_flags;
  178742. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  178743. if (ptr == NULL)
  178744. return ((voidpf)ptr);
  178745. if (num_bytes > (png_uint_32)0x8000L)
  178746. {
  178747. png_memset(ptr, 0, (png_size_t)0x8000L);
  178748. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  178749. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  178750. }
  178751. else
  178752. {
  178753. png_memset(ptr, 0, (png_size_t)num_bytes);
  178754. }
  178755. #endif
  178756. return ((voidpf)ptr);
  178757. }
  178758. /* function to free memory for zlib */
  178759. #ifdef PNG_1_0_X
  178760. void PNGAPI
  178761. #else
  178762. void /* private */
  178763. #endif
  178764. png_zfree(voidpf png_ptr, voidpf ptr)
  178765. {
  178766. png_free((png_structp)png_ptr, (png_voidp)ptr);
  178767. }
  178768. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  178769. * in case CRC is > 32 bits to leave the top bits 0.
  178770. */
  178771. void /* PRIVATE */
  178772. png_reset_crc(png_structp png_ptr)
  178773. {
  178774. png_ptr->crc = crc32(0, Z_NULL, 0);
  178775. }
  178776. /* Calculate the CRC over a section of data. We can only pass as
  178777. * much data to this routine as the largest single buffer size. We
  178778. * also check that this data will actually be used before going to the
  178779. * trouble of calculating it.
  178780. */
  178781. void /* PRIVATE */
  178782. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  178783. {
  178784. int need_crc = 1;
  178785. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  178786. {
  178787. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  178788. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  178789. need_crc = 0;
  178790. }
  178791. else /* critical */
  178792. {
  178793. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  178794. need_crc = 0;
  178795. }
  178796. if (need_crc)
  178797. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  178798. }
  178799. /* Allocate the memory for an info_struct for the application. We don't
  178800. * really need the png_ptr, but it could potentially be useful in the
  178801. * future. This should be used in favour of malloc(png_sizeof(png_info))
  178802. * and png_info_init() so that applications that want to use a shared
  178803. * libpng don't have to be recompiled if png_info changes size.
  178804. */
  178805. png_infop PNGAPI
  178806. png_create_info_struct(png_structp png_ptr)
  178807. {
  178808. png_infop info_ptr;
  178809. png_debug(1, "in png_create_info_struct\n");
  178810. if(png_ptr == NULL) return (NULL);
  178811. #ifdef PNG_USER_MEM_SUPPORTED
  178812. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  178813. png_ptr->malloc_fn, png_ptr->mem_ptr);
  178814. #else
  178815. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  178816. #endif
  178817. if (info_ptr != NULL)
  178818. png_info_init_3(&info_ptr, png_sizeof(png_info));
  178819. return (info_ptr);
  178820. }
  178821. /* This function frees the memory associated with a single info struct.
  178822. * Normally, one would use either png_destroy_read_struct() or
  178823. * png_destroy_write_struct() to free an info struct, but this may be
  178824. * useful for some applications.
  178825. */
  178826. void PNGAPI
  178827. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  178828. {
  178829. png_infop info_ptr = NULL;
  178830. if(png_ptr == NULL) return;
  178831. png_debug(1, "in png_destroy_info_struct\n");
  178832. if (info_ptr_ptr != NULL)
  178833. info_ptr = *info_ptr_ptr;
  178834. if (info_ptr != NULL)
  178835. {
  178836. png_info_destroy(png_ptr, info_ptr);
  178837. #ifdef PNG_USER_MEM_SUPPORTED
  178838. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  178839. png_ptr->mem_ptr);
  178840. #else
  178841. png_destroy_struct((png_voidp)info_ptr);
  178842. #endif
  178843. *info_ptr_ptr = NULL;
  178844. }
  178845. }
  178846. /* Initialize the info structure. This is now an internal function (0.89)
  178847. * and applications using it are urged to use png_create_info_struct()
  178848. * instead.
  178849. */
  178850. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  178851. #undef png_info_init
  178852. void PNGAPI
  178853. png_info_init(png_infop info_ptr)
  178854. {
  178855. /* We only come here via pre-1.0.12-compiled applications */
  178856. png_info_init_3(&info_ptr, 0);
  178857. }
  178858. #endif
  178859. void PNGAPI
  178860. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  178861. {
  178862. png_infop info_ptr = *ptr_ptr;
  178863. if(info_ptr == NULL) return;
  178864. png_debug(1, "in png_info_init_3\n");
  178865. if(png_sizeof(png_info) > png_info_struct_size)
  178866. {
  178867. png_destroy_struct(info_ptr);
  178868. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  178869. *ptr_ptr = info_ptr;
  178870. }
  178871. /* set everything to 0 */
  178872. png_memset(info_ptr, 0, png_sizeof (png_info));
  178873. }
  178874. #ifdef PNG_FREE_ME_SUPPORTED
  178875. void PNGAPI
  178876. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  178877. int freer, png_uint_32 mask)
  178878. {
  178879. png_debug(1, "in png_data_freer\n");
  178880. if (png_ptr == NULL || info_ptr == NULL)
  178881. return;
  178882. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  178883. info_ptr->free_me |= mask;
  178884. else if(freer == PNG_USER_WILL_FREE_DATA)
  178885. info_ptr->free_me &= ~mask;
  178886. else
  178887. png_warning(png_ptr,
  178888. "Unknown freer parameter in png_data_freer.");
  178889. }
  178890. #endif
  178891. void PNGAPI
  178892. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  178893. int num)
  178894. {
  178895. png_debug(1, "in png_free_data\n");
  178896. if (png_ptr == NULL || info_ptr == NULL)
  178897. return;
  178898. #if defined(PNG_TEXT_SUPPORTED)
  178899. /* free text item num or (if num == -1) all text items */
  178900. #ifdef PNG_FREE_ME_SUPPORTED
  178901. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  178902. #else
  178903. if (mask & PNG_FREE_TEXT)
  178904. #endif
  178905. {
  178906. if (num != -1)
  178907. {
  178908. if (info_ptr->text && info_ptr->text[num].key)
  178909. {
  178910. png_free(png_ptr, info_ptr->text[num].key);
  178911. info_ptr->text[num].key = NULL;
  178912. }
  178913. }
  178914. else
  178915. {
  178916. int i;
  178917. for (i = 0; i < info_ptr->num_text; i++)
  178918. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  178919. png_free(png_ptr, info_ptr->text);
  178920. info_ptr->text = NULL;
  178921. info_ptr->num_text=0;
  178922. }
  178923. }
  178924. #endif
  178925. #if defined(PNG_tRNS_SUPPORTED)
  178926. /* free any tRNS entry */
  178927. #ifdef PNG_FREE_ME_SUPPORTED
  178928. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  178929. #else
  178930. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  178931. #endif
  178932. {
  178933. png_free(png_ptr, info_ptr->trans);
  178934. info_ptr->valid &= ~PNG_INFO_tRNS;
  178935. #ifndef PNG_FREE_ME_SUPPORTED
  178936. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  178937. #endif
  178938. info_ptr->trans = NULL;
  178939. }
  178940. #endif
  178941. #if defined(PNG_sCAL_SUPPORTED)
  178942. /* free any sCAL entry */
  178943. #ifdef PNG_FREE_ME_SUPPORTED
  178944. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  178945. #else
  178946. if (mask & PNG_FREE_SCAL)
  178947. #endif
  178948. {
  178949. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  178950. png_free(png_ptr, info_ptr->scal_s_width);
  178951. png_free(png_ptr, info_ptr->scal_s_height);
  178952. info_ptr->scal_s_width = NULL;
  178953. info_ptr->scal_s_height = NULL;
  178954. #endif
  178955. info_ptr->valid &= ~PNG_INFO_sCAL;
  178956. }
  178957. #endif
  178958. #if defined(PNG_pCAL_SUPPORTED)
  178959. /* free any pCAL entry */
  178960. #ifdef PNG_FREE_ME_SUPPORTED
  178961. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  178962. #else
  178963. if (mask & PNG_FREE_PCAL)
  178964. #endif
  178965. {
  178966. png_free(png_ptr, info_ptr->pcal_purpose);
  178967. png_free(png_ptr, info_ptr->pcal_units);
  178968. info_ptr->pcal_purpose = NULL;
  178969. info_ptr->pcal_units = NULL;
  178970. if (info_ptr->pcal_params != NULL)
  178971. {
  178972. int i;
  178973. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  178974. {
  178975. png_free(png_ptr, info_ptr->pcal_params[i]);
  178976. info_ptr->pcal_params[i]=NULL;
  178977. }
  178978. png_free(png_ptr, info_ptr->pcal_params);
  178979. info_ptr->pcal_params = NULL;
  178980. }
  178981. info_ptr->valid &= ~PNG_INFO_pCAL;
  178982. }
  178983. #endif
  178984. #if defined(PNG_iCCP_SUPPORTED)
  178985. /* free any iCCP entry */
  178986. #ifdef PNG_FREE_ME_SUPPORTED
  178987. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  178988. #else
  178989. if (mask & PNG_FREE_ICCP)
  178990. #endif
  178991. {
  178992. png_free(png_ptr, info_ptr->iccp_name);
  178993. png_free(png_ptr, info_ptr->iccp_profile);
  178994. info_ptr->iccp_name = NULL;
  178995. info_ptr->iccp_profile = NULL;
  178996. info_ptr->valid &= ~PNG_INFO_iCCP;
  178997. }
  178998. #endif
  178999. #if defined(PNG_sPLT_SUPPORTED)
  179000. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  179001. #ifdef PNG_FREE_ME_SUPPORTED
  179002. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  179003. #else
  179004. if (mask & PNG_FREE_SPLT)
  179005. #endif
  179006. {
  179007. if (num != -1)
  179008. {
  179009. if(info_ptr->splt_palettes)
  179010. {
  179011. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  179012. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  179013. info_ptr->splt_palettes[num].name = NULL;
  179014. info_ptr->splt_palettes[num].entries = NULL;
  179015. }
  179016. }
  179017. else
  179018. {
  179019. if(info_ptr->splt_palettes_num)
  179020. {
  179021. int i;
  179022. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  179023. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  179024. png_free(png_ptr, info_ptr->splt_palettes);
  179025. info_ptr->splt_palettes = NULL;
  179026. info_ptr->splt_palettes_num = 0;
  179027. }
  179028. info_ptr->valid &= ~PNG_INFO_sPLT;
  179029. }
  179030. }
  179031. #endif
  179032. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179033. if(png_ptr->unknown_chunk.data)
  179034. {
  179035. png_free(png_ptr, png_ptr->unknown_chunk.data);
  179036. png_ptr->unknown_chunk.data = NULL;
  179037. }
  179038. #ifdef PNG_FREE_ME_SUPPORTED
  179039. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  179040. #else
  179041. if (mask & PNG_FREE_UNKN)
  179042. #endif
  179043. {
  179044. if (num != -1)
  179045. {
  179046. if(info_ptr->unknown_chunks)
  179047. {
  179048. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  179049. info_ptr->unknown_chunks[num].data = NULL;
  179050. }
  179051. }
  179052. else
  179053. {
  179054. int i;
  179055. if(info_ptr->unknown_chunks_num)
  179056. {
  179057. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  179058. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  179059. png_free(png_ptr, info_ptr->unknown_chunks);
  179060. info_ptr->unknown_chunks = NULL;
  179061. info_ptr->unknown_chunks_num = 0;
  179062. }
  179063. }
  179064. }
  179065. #endif
  179066. #if defined(PNG_hIST_SUPPORTED)
  179067. /* free any hIST entry */
  179068. #ifdef PNG_FREE_ME_SUPPORTED
  179069. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  179070. #else
  179071. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  179072. #endif
  179073. {
  179074. png_free(png_ptr, info_ptr->hist);
  179075. info_ptr->hist = NULL;
  179076. info_ptr->valid &= ~PNG_INFO_hIST;
  179077. #ifndef PNG_FREE_ME_SUPPORTED
  179078. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  179079. #endif
  179080. }
  179081. #endif
  179082. /* free any PLTE entry that was internally allocated */
  179083. #ifdef PNG_FREE_ME_SUPPORTED
  179084. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  179085. #else
  179086. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  179087. #endif
  179088. {
  179089. png_zfree(png_ptr, info_ptr->palette);
  179090. info_ptr->palette = NULL;
  179091. info_ptr->valid &= ~PNG_INFO_PLTE;
  179092. #ifndef PNG_FREE_ME_SUPPORTED
  179093. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  179094. #endif
  179095. info_ptr->num_palette = 0;
  179096. }
  179097. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  179098. /* free any image bits attached to the info structure */
  179099. #ifdef PNG_FREE_ME_SUPPORTED
  179100. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  179101. #else
  179102. if (mask & PNG_FREE_ROWS)
  179103. #endif
  179104. {
  179105. if(info_ptr->row_pointers)
  179106. {
  179107. int row;
  179108. for (row = 0; row < (int)info_ptr->height; row++)
  179109. {
  179110. png_free(png_ptr, info_ptr->row_pointers[row]);
  179111. info_ptr->row_pointers[row]=NULL;
  179112. }
  179113. png_free(png_ptr, info_ptr->row_pointers);
  179114. info_ptr->row_pointers=NULL;
  179115. }
  179116. info_ptr->valid &= ~PNG_INFO_IDAT;
  179117. }
  179118. #endif
  179119. #ifdef PNG_FREE_ME_SUPPORTED
  179120. if(num == -1)
  179121. info_ptr->free_me &= ~mask;
  179122. else
  179123. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  179124. #endif
  179125. }
  179126. /* This is an internal routine to free any memory that the info struct is
  179127. * pointing to before re-using it or freeing the struct itself. Recall
  179128. * that png_free() checks for NULL pointers for us.
  179129. */
  179130. void /* PRIVATE */
  179131. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  179132. {
  179133. png_debug(1, "in png_info_destroy\n");
  179134. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  179135. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179136. if (png_ptr->num_chunk_list)
  179137. {
  179138. png_free(png_ptr, png_ptr->chunk_list);
  179139. png_ptr->chunk_list=NULL;
  179140. png_ptr->num_chunk_list=0;
  179141. }
  179142. #endif
  179143. png_info_init_3(&info_ptr, png_sizeof(png_info));
  179144. }
  179145. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  179146. /* This function returns a pointer to the io_ptr associated with the user
  179147. * functions. The application should free any memory associated with this
  179148. * pointer before png_write_destroy() or png_read_destroy() are called.
  179149. */
  179150. png_voidp PNGAPI
  179151. png_get_io_ptr(png_structp png_ptr)
  179152. {
  179153. if(png_ptr == NULL) return (NULL);
  179154. return (png_ptr->io_ptr);
  179155. }
  179156. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179157. #if !defined(PNG_NO_STDIO)
  179158. /* Initialize the default input/output functions for the PNG file. If you
  179159. * use your own read or write routines, you can call either png_set_read_fn()
  179160. * or png_set_write_fn() instead of png_init_io(). If you have defined
  179161. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  179162. * necessarily available.
  179163. */
  179164. void PNGAPI
  179165. png_init_io(png_structp png_ptr, png_FILE_p fp)
  179166. {
  179167. png_debug(1, "in png_init_io\n");
  179168. if(png_ptr == NULL) return;
  179169. png_ptr->io_ptr = (png_voidp)fp;
  179170. }
  179171. #endif
  179172. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  179173. /* Convert the supplied time into an RFC 1123 string suitable for use in
  179174. * a "Creation Time" or other text-based time string.
  179175. */
  179176. png_charp PNGAPI
  179177. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  179178. {
  179179. static PNG_CONST char short_months[12][4] =
  179180. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  179181. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  179182. if(png_ptr == NULL) return (NULL);
  179183. if (png_ptr->time_buffer == NULL)
  179184. {
  179185. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  179186. png_sizeof(char)));
  179187. }
  179188. #if defined(_WIN32_WCE)
  179189. {
  179190. wchar_t time_buf[29];
  179191. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  179192. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  179193. ptime->year, ptime->hour % 24, ptime->minute % 60,
  179194. ptime->second % 61);
  179195. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  179196. NULL, NULL);
  179197. }
  179198. #else
  179199. #ifdef USE_FAR_KEYWORD
  179200. {
  179201. char near_time_buf[29];
  179202. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  179203. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  179204. ptime->year, ptime->hour % 24, ptime->minute % 60,
  179205. ptime->second % 61);
  179206. png_memcpy(png_ptr->time_buffer, near_time_buf,
  179207. 29*png_sizeof(char));
  179208. }
  179209. #else
  179210. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  179211. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  179212. ptime->year, ptime->hour % 24, ptime->minute % 60,
  179213. ptime->second % 61);
  179214. #endif
  179215. #endif /* _WIN32_WCE */
  179216. return ((png_charp)png_ptr->time_buffer);
  179217. }
  179218. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  179219. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  179220. png_charp PNGAPI
  179221. png_get_copyright(png_structp png_ptr)
  179222. {
  179223. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  179224. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  179225. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  179226. Copyright (c) 1996-1997 Andreas Dilger\n\
  179227. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  179228. }
  179229. /* The following return the library version as a short string in the
  179230. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  179231. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  179232. * is defined in png.h.
  179233. * Note: now there is no difference between png_get_libpng_ver() and
  179234. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  179235. * it is guaranteed that png.c uses the correct version of png.h.
  179236. */
  179237. png_charp PNGAPI
  179238. png_get_libpng_ver(png_structp png_ptr)
  179239. {
  179240. /* Version of *.c files used when building libpng */
  179241. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  179242. return ((png_charp) PNG_LIBPNG_VER_STRING);
  179243. }
  179244. png_charp PNGAPI
  179245. png_get_header_ver(png_structp png_ptr)
  179246. {
  179247. /* Version of *.h files used when building libpng */
  179248. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  179249. return ((png_charp) PNG_LIBPNG_VER_STRING);
  179250. }
  179251. png_charp PNGAPI
  179252. png_get_header_version(png_structp png_ptr)
  179253. {
  179254. /* Returns longer string containing both version and date */
  179255. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  179256. return ((png_charp) PNG_HEADER_VERSION_STRING
  179257. #ifndef PNG_READ_SUPPORTED
  179258. " (NO READ SUPPORT)"
  179259. #endif
  179260. "\n");
  179261. }
  179262. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179263. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  179264. int PNGAPI
  179265. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  179266. {
  179267. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  179268. int i;
  179269. png_bytep p;
  179270. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  179271. return 0;
  179272. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  179273. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  179274. if (!png_memcmp(chunk_name, p, 4))
  179275. return ((int)*(p+4));
  179276. return 0;
  179277. }
  179278. #endif
  179279. /* This function, added to libpng-1.0.6g, is untested. */
  179280. int PNGAPI
  179281. png_reset_zstream(png_structp png_ptr)
  179282. {
  179283. if (png_ptr == NULL) return Z_STREAM_ERROR;
  179284. return (inflateReset(&png_ptr->zstream));
  179285. }
  179286. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  179287. /* This function was added to libpng-1.0.7 */
  179288. png_uint_32 PNGAPI
  179289. png_access_version_number(void)
  179290. {
  179291. /* Version of *.c files used when building libpng */
  179292. return((png_uint_32) PNG_LIBPNG_VER);
  179293. }
  179294. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  179295. #if !defined(PNG_1_0_X)
  179296. /* this function was added to libpng 1.2.0 */
  179297. int PNGAPI
  179298. png_mmx_support(void)
  179299. {
  179300. /* obsolete, to be removed from libpng-1.4.0 */
  179301. return -1;
  179302. }
  179303. #endif /* PNG_1_0_X */
  179304. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  179305. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179306. #ifdef PNG_SIZE_T
  179307. /* Added at libpng version 1.2.6 */
  179308. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  179309. png_size_t PNGAPI
  179310. png_convert_size(size_t size)
  179311. {
  179312. if (size > (png_size_t)-1)
  179313. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  179314. return ((png_size_t)size);
  179315. }
  179316. #endif /* PNG_SIZE_T */
  179317. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  179318. /********* End of inlined file: png.c *********/
  179319. /********* Start of inlined file: pngerror.c *********/
  179320. /* pngerror.c - stub functions for i/o and memory allocation
  179321. *
  179322. * Last changed in libpng 1.2.20 October 4, 2007
  179323. * For conditions of distribution and use, see copyright notice in png.h
  179324. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179325. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179326. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179327. *
  179328. * This file provides a location for all error handling. Users who
  179329. * need special error handling are expected to write replacement functions
  179330. * and use png_set_error_fn() to use those functions. See the instructions
  179331. * at each function.
  179332. */
  179333. #define PNG_INTERNAL
  179334. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179335. static void /* PRIVATE */
  179336. png_default_error PNGARG((png_structp png_ptr,
  179337. png_const_charp error_message));
  179338. #ifndef PNG_NO_WARNINGS
  179339. static void /* PRIVATE */
  179340. png_default_warning PNGARG((png_structp png_ptr,
  179341. png_const_charp warning_message));
  179342. #endif /* PNG_NO_WARNINGS */
  179343. /* This function is called whenever there is a fatal error. This function
  179344. * should not be changed. If there is a need to handle errors differently,
  179345. * you should supply a replacement error function and use png_set_error_fn()
  179346. * to replace the error function at run-time.
  179347. */
  179348. #ifndef PNG_NO_ERROR_TEXT
  179349. void PNGAPI
  179350. png_error(png_structp png_ptr, png_const_charp error_message)
  179351. {
  179352. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179353. char msg[16];
  179354. if (png_ptr != NULL)
  179355. {
  179356. if (png_ptr->flags&
  179357. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  179358. {
  179359. if (*error_message == '#')
  179360. {
  179361. int offset;
  179362. for (offset=1; offset<15; offset++)
  179363. if (*(error_message+offset) == ' ')
  179364. break;
  179365. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  179366. {
  179367. int i;
  179368. for (i=0; i<offset-1; i++)
  179369. msg[i]=error_message[i+1];
  179370. msg[i]='\0';
  179371. error_message=msg;
  179372. }
  179373. else
  179374. error_message+=offset;
  179375. }
  179376. else
  179377. {
  179378. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  179379. {
  179380. msg[0]='0';
  179381. msg[1]='\0';
  179382. error_message=msg;
  179383. }
  179384. }
  179385. }
  179386. }
  179387. #endif
  179388. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  179389. (*(png_ptr->error_fn))(png_ptr, error_message);
  179390. /* If the custom handler doesn't exist, or if it returns,
  179391. use the default handler, which will not return. */
  179392. png_default_error(png_ptr, error_message);
  179393. }
  179394. #else
  179395. void PNGAPI
  179396. png_err(png_structp png_ptr)
  179397. {
  179398. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  179399. (*(png_ptr->error_fn))(png_ptr, '\0');
  179400. /* If the custom handler doesn't exist, or if it returns,
  179401. use the default handler, which will not return. */
  179402. png_default_error(png_ptr, '\0');
  179403. }
  179404. #endif /* PNG_NO_ERROR_TEXT */
  179405. #ifndef PNG_NO_WARNINGS
  179406. /* This function is called whenever there is a non-fatal error. This function
  179407. * should not be changed. If there is a need to handle warnings differently,
  179408. * you should supply a replacement warning function and use
  179409. * png_set_error_fn() to replace the warning function at run-time.
  179410. */
  179411. void PNGAPI
  179412. png_warning(png_structp png_ptr, png_const_charp warning_message)
  179413. {
  179414. int offset = 0;
  179415. if (png_ptr != NULL)
  179416. {
  179417. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179418. if (png_ptr->flags&
  179419. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  179420. #endif
  179421. {
  179422. if (*warning_message == '#')
  179423. {
  179424. for (offset=1; offset<15; offset++)
  179425. if (*(warning_message+offset) == ' ')
  179426. break;
  179427. }
  179428. }
  179429. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  179430. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  179431. }
  179432. else
  179433. png_default_warning(png_ptr, warning_message+offset);
  179434. }
  179435. #endif /* PNG_NO_WARNINGS */
  179436. /* These utilities are used internally to build an error message that relates
  179437. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  179438. * this is used to prefix the message. The message is limited in length
  179439. * to 63 bytes, the name characters are output as hex digits wrapped in []
  179440. * if the character is invalid.
  179441. */
  179442. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  179443. /*static PNG_CONST char png_digit[16] = {
  179444. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  179445. 'A', 'B', 'C', 'D', 'E', 'F'
  179446. };*/
  179447. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  179448. static void /* PRIVATE */
  179449. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  179450. error_message)
  179451. {
  179452. int iout = 0, iin = 0;
  179453. while (iin < 4)
  179454. {
  179455. int c = png_ptr->chunk_name[iin++];
  179456. if (isnonalpha(c))
  179457. {
  179458. buffer[iout++] = '[';
  179459. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  179460. buffer[iout++] = png_digit[c & 0x0f];
  179461. buffer[iout++] = ']';
  179462. }
  179463. else
  179464. {
  179465. buffer[iout++] = (png_byte)c;
  179466. }
  179467. }
  179468. if (error_message == NULL)
  179469. buffer[iout] = 0;
  179470. else
  179471. {
  179472. buffer[iout++] = ':';
  179473. buffer[iout++] = ' ';
  179474. png_strncpy(buffer+iout, error_message, 63);
  179475. buffer[iout+63] = 0;
  179476. }
  179477. }
  179478. #ifdef PNG_READ_SUPPORTED
  179479. void PNGAPI
  179480. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  179481. {
  179482. char msg[18+64];
  179483. if (png_ptr == NULL)
  179484. png_error(png_ptr, error_message);
  179485. else
  179486. {
  179487. png_format_buffer(png_ptr, msg, error_message);
  179488. png_error(png_ptr, msg);
  179489. }
  179490. }
  179491. #endif /* PNG_READ_SUPPORTED */
  179492. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  179493. #ifndef PNG_NO_WARNINGS
  179494. void PNGAPI
  179495. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  179496. {
  179497. char msg[18+64];
  179498. if (png_ptr == NULL)
  179499. png_warning(png_ptr, warning_message);
  179500. else
  179501. {
  179502. png_format_buffer(png_ptr, msg, warning_message);
  179503. png_warning(png_ptr, msg);
  179504. }
  179505. }
  179506. #endif /* PNG_NO_WARNINGS */
  179507. /* This is the default error handling function. Note that replacements for
  179508. * this function MUST NOT RETURN, or the program will likely crash. This
  179509. * function is used by default, or if the program supplies NULL for the
  179510. * error function pointer in png_set_error_fn().
  179511. */
  179512. static void /* PRIVATE */
  179513. png_default_error(png_structp png_ptr, png_const_charp error_message)
  179514. {
  179515. #ifndef PNG_NO_CONSOLE_IO
  179516. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179517. if (*error_message == '#')
  179518. {
  179519. int offset;
  179520. char error_number[16];
  179521. for (offset=0; offset<15; offset++)
  179522. {
  179523. error_number[offset] = *(error_message+offset+1);
  179524. if (*(error_message+offset) == ' ')
  179525. break;
  179526. }
  179527. if((offset > 1) && (offset < 15))
  179528. {
  179529. error_number[offset-1]='\0';
  179530. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  179531. error_message+offset);
  179532. }
  179533. else
  179534. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  179535. }
  179536. else
  179537. #endif
  179538. fprintf(stderr, "libpng error: %s\n", error_message);
  179539. #endif
  179540. #ifdef PNG_SETJMP_SUPPORTED
  179541. if (png_ptr)
  179542. {
  179543. # ifdef USE_FAR_KEYWORD
  179544. {
  179545. jmp_buf jmpbuf;
  179546. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  179547. longjmp(jmpbuf, 1);
  179548. }
  179549. # else
  179550. longjmp(png_ptr->jmpbuf, 1);
  179551. # endif
  179552. }
  179553. #else
  179554. PNG_ABORT();
  179555. #endif
  179556. #ifdef PNG_NO_CONSOLE_IO
  179557. error_message = error_message; /* make compiler happy */
  179558. #endif
  179559. }
  179560. #ifndef PNG_NO_WARNINGS
  179561. /* This function is called when there is a warning, but the library thinks
  179562. * it can continue anyway. Replacement functions don't have to do anything
  179563. * here if you don't want them to. In the default configuration, png_ptr is
  179564. * not used, but it is passed in case it may be useful.
  179565. */
  179566. static void /* PRIVATE */
  179567. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  179568. {
  179569. #ifndef PNG_NO_CONSOLE_IO
  179570. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179571. if (*warning_message == '#')
  179572. {
  179573. int offset;
  179574. char warning_number[16];
  179575. for (offset=0; offset<15; offset++)
  179576. {
  179577. warning_number[offset]=*(warning_message+offset+1);
  179578. if (*(warning_message+offset) == ' ')
  179579. break;
  179580. }
  179581. if((offset > 1) && (offset < 15))
  179582. {
  179583. warning_number[offset-1]='\0';
  179584. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  179585. warning_message+offset);
  179586. }
  179587. else
  179588. fprintf(stderr, "libpng warning: %s\n", warning_message);
  179589. }
  179590. else
  179591. # endif
  179592. fprintf(stderr, "libpng warning: %s\n", warning_message);
  179593. #else
  179594. warning_message = warning_message; /* make compiler happy */
  179595. #endif
  179596. png_ptr = png_ptr; /* make compiler happy */
  179597. }
  179598. #endif /* PNG_NO_WARNINGS */
  179599. /* This function is called when the application wants to use another method
  179600. * of handling errors and warnings. Note that the error function MUST NOT
  179601. * return to the calling routine or serious problems will occur. The return
  179602. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  179603. */
  179604. void PNGAPI
  179605. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  179606. png_error_ptr error_fn, png_error_ptr warning_fn)
  179607. {
  179608. if (png_ptr == NULL)
  179609. return;
  179610. png_ptr->error_ptr = error_ptr;
  179611. png_ptr->error_fn = error_fn;
  179612. png_ptr->warning_fn = warning_fn;
  179613. }
  179614. /* This function returns a pointer to the error_ptr associated with the user
  179615. * functions. The application should free any memory associated with this
  179616. * pointer before png_write_destroy and png_read_destroy are called.
  179617. */
  179618. png_voidp PNGAPI
  179619. png_get_error_ptr(png_structp png_ptr)
  179620. {
  179621. if (png_ptr == NULL)
  179622. return NULL;
  179623. return ((png_voidp)png_ptr->error_ptr);
  179624. }
  179625. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179626. void PNGAPI
  179627. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  179628. {
  179629. if(png_ptr != NULL)
  179630. {
  179631. png_ptr->flags &=
  179632. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  179633. }
  179634. }
  179635. #endif
  179636. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  179637. /********* End of inlined file: pngerror.c *********/
  179638. /********* Start of inlined file: pngget.c *********/
  179639. /* pngget.c - retrieval of values from info struct
  179640. *
  179641. * Last changed in libpng 1.2.15 January 5, 2007
  179642. * For conditions of distribution and use, see copyright notice in png.h
  179643. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179644. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179645. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179646. */
  179647. #define PNG_INTERNAL
  179648. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179649. png_uint_32 PNGAPI
  179650. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  179651. {
  179652. if (png_ptr != NULL && info_ptr != NULL)
  179653. return(info_ptr->valid & flag);
  179654. else
  179655. return(0);
  179656. }
  179657. png_uint_32 PNGAPI
  179658. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  179659. {
  179660. if (png_ptr != NULL && info_ptr != NULL)
  179661. return(info_ptr->rowbytes);
  179662. else
  179663. return(0);
  179664. }
  179665. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  179666. png_bytepp PNGAPI
  179667. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  179668. {
  179669. if (png_ptr != NULL && info_ptr != NULL)
  179670. return(info_ptr->row_pointers);
  179671. else
  179672. return(0);
  179673. }
  179674. #endif
  179675. #ifdef PNG_EASY_ACCESS_SUPPORTED
  179676. /* easy access to info, added in libpng-0.99 */
  179677. png_uint_32 PNGAPI
  179678. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  179679. {
  179680. if (png_ptr != NULL && info_ptr != NULL)
  179681. {
  179682. return info_ptr->width;
  179683. }
  179684. return (0);
  179685. }
  179686. png_uint_32 PNGAPI
  179687. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  179688. {
  179689. if (png_ptr != NULL && info_ptr != NULL)
  179690. {
  179691. return info_ptr->height;
  179692. }
  179693. return (0);
  179694. }
  179695. png_byte PNGAPI
  179696. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  179697. {
  179698. if (png_ptr != NULL && info_ptr != NULL)
  179699. {
  179700. return info_ptr->bit_depth;
  179701. }
  179702. return (0);
  179703. }
  179704. png_byte PNGAPI
  179705. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  179706. {
  179707. if (png_ptr != NULL && info_ptr != NULL)
  179708. {
  179709. return info_ptr->color_type;
  179710. }
  179711. return (0);
  179712. }
  179713. png_byte PNGAPI
  179714. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  179715. {
  179716. if (png_ptr != NULL && info_ptr != NULL)
  179717. {
  179718. return info_ptr->filter_type;
  179719. }
  179720. return (0);
  179721. }
  179722. png_byte PNGAPI
  179723. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  179724. {
  179725. if (png_ptr != NULL && info_ptr != NULL)
  179726. {
  179727. return info_ptr->interlace_type;
  179728. }
  179729. return (0);
  179730. }
  179731. png_byte PNGAPI
  179732. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  179733. {
  179734. if (png_ptr != NULL && info_ptr != NULL)
  179735. {
  179736. return info_ptr->compression_type;
  179737. }
  179738. return (0);
  179739. }
  179740. png_uint_32 PNGAPI
  179741. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  179742. {
  179743. if (png_ptr != NULL && info_ptr != NULL)
  179744. #if defined(PNG_pHYs_SUPPORTED)
  179745. if (info_ptr->valid & PNG_INFO_pHYs)
  179746. {
  179747. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  179748. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  179749. return (0);
  179750. else return (info_ptr->x_pixels_per_unit);
  179751. }
  179752. #else
  179753. return (0);
  179754. #endif
  179755. return (0);
  179756. }
  179757. png_uint_32 PNGAPI
  179758. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  179759. {
  179760. if (png_ptr != NULL && info_ptr != NULL)
  179761. #if defined(PNG_pHYs_SUPPORTED)
  179762. if (info_ptr->valid & PNG_INFO_pHYs)
  179763. {
  179764. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  179765. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  179766. return (0);
  179767. else return (info_ptr->y_pixels_per_unit);
  179768. }
  179769. #else
  179770. return (0);
  179771. #endif
  179772. return (0);
  179773. }
  179774. png_uint_32 PNGAPI
  179775. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  179776. {
  179777. if (png_ptr != NULL && info_ptr != NULL)
  179778. #if defined(PNG_pHYs_SUPPORTED)
  179779. if (info_ptr->valid & PNG_INFO_pHYs)
  179780. {
  179781. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  179782. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  179783. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  179784. return (0);
  179785. else return (info_ptr->x_pixels_per_unit);
  179786. }
  179787. #else
  179788. return (0);
  179789. #endif
  179790. return (0);
  179791. }
  179792. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179793. float PNGAPI
  179794. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  179795. {
  179796. if (png_ptr != NULL && info_ptr != NULL)
  179797. #if defined(PNG_pHYs_SUPPORTED)
  179798. if (info_ptr->valid & PNG_INFO_pHYs)
  179799. {
  179800. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  179801. if (info_ptr->x_pixels_per_unit == 0)
  179802. return ((float)0.0);
  179803. else
  179804. return ((float)((float)info_ptr->y_pixels_per_unit
  179805. /(float)info_ptr->x_pixels_per_unit));
  179806. }
  179807. #else
  179808. return (0.0);
  179809. #endif
  179810. return ((float)0.0);
  179811. }
  179812. #endif
  179813. png_int_32 PNGAPI
  179814. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  179815. {
  179816. if (png_ptr != NULL && info_ptr != NULL)
  179817. #if defined(PNG_oFFs_SUPPORTED)
  179818. if (info_ptr->valid & PNG_INFO_oFFs)
  179819. {
  179820. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  179821. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  179822. return (0);
  179823. else return (info_ptr->x_offset);
  179824. }
  179825. #else
  179826. return (0);
  179827. #endif
  179828. return (0);
  179829. }
  179830. png_int_32 PNGAPI
  179831. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  179832. {
  179833. if (png_ptr != NULL && info_ptr != NULL)
  179834. #if defined(PNG_oFFs_SUPPORTED)
  179835. if (info_ptr->valid & PNG_INFO_oFFs)
  179836. {
  179837. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  179838. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  179839. return (0);
  179840. else return (info_ptr->y_offset);
  179841. }
  179842. #else
  179843. return (0);
  179844. #endif
  179845. return (0);
  179846. }
  179847. png_int_32 PNGAPI
  179848. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  179849. {
  179850. if (png_ptr != NULL && info_ptr != NULL)
  179851. #if defined(PNG_oFFs_SUPPORTED)
  179852. if (info_ptr->valid & PNG_INFO_oFFs)
  179853. {
  179854. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  179855. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  179856. return (0);
  179857. else return (info_ptr->x_offset);
  179858. }
  179859. #else
  179860. return (0);
  179861. #endif
  179862. return (0);
  179863. }
  179864. png_int_32 PNGAPI
  179865. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  179866. {
  179867. if (png_ptr != NULL && info_ptr != NULL)
  179868. #if defined(PNG_oFFs_SUPPORTED)
  179869. if (info_ptr->valid & PNG_INFO_oFFs)
  179870. {
  179871. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  179872. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  179873. return (0);
  179874. else return (info_ptr->y_offset);
  179875. }
  179876. #else
  179877. return (0);
  179878. #endif
  179879. return (0);
  179880. }
  179881. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  179882. png_uint_32 PNGAPI
  179883. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  179884. {
  179885. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  179886. *.0254 +.5));
  179887. }
  179888. png_uint_32 PNGAPI
  179889. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  179890. {
  179891. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  179892. *.0254 +.5));
  179893. }
  179894. png_uint_32 PNGAPI
  179895. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  179896. {
  179897. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  179898. *.0254 +.5));
  179899. }
  179900. float PNGAPI
  179901. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  179902. {
  179903. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  179904. *.00003937);
  179905. }
  179906. float PNGAPI
  179907. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  179908. {
  179909. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  179910. *.00003937);
  179911. }
  179912. #if defined(PNG_pHYs_SUPPORTED)
  179913. png_uint_32 PNGAPI
  179914. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  179915. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  179916. {
  179917. png_uint_32 retval = 0;
  179918. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  179919. {
  179920. png_debug1(1, "in %s retrieval function\n", "pHYs");
  179921. if (res_x != NULL)
  179922. {
  179923. *res_x = info_ptr->x_pixels_per_unit;
  179924. retval |= PNG_INFO_pHYs;
  179925. }
  179926. if (res_y != NULL)
  179927. {
  179928. *res_y = info_ptr->y_pixels_per_unit;
  179929. retval |= PNG_INFO_pHYs;
  179930. }
  179931. if (unit_type != NULL)
  179932. {
  179933. *unit_type = (int)info_ptr->phys_unit_type;
  179934. retval |= PNG_INFO_pHYs;
  179935. if(*unit_type == 1)
  179936. {
  179937. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  179938. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  179939. }
  179940. }
  179941. }
  179942. return (retval);
  179943. }
  179944. #endif /* PNG_pHYs_SUPPORTED */
  179945. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  179946. /* png_get_channels really belongs in here, too, but it's been around longer */
  179947. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  179948. png_byte PNGAPI
  179949. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  179950. {
  179951. if (png_ptr != NULL && info_ptr != NULL)
  179952. return(info_ptr->channels);
  179953. else
  179954. return (0);
  179955. }
  179956. png_bytep PNGAPI
  179957. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  179958. {
  179959. if (png_ptr != NULL && info_ptr != NULL)
  179960. return(info_ptr->signature);
  179961. else
  179962. return (NULL);
  179963. }
  179964. #if defined(PNG_bKGD_SUPPORTED)
  179965. png_uint_32 PNGAPI
  179966. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  179967. png_color_16p *background)
  179968. {
  179969. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  179970. && background != NULL)
  179971. {
  179972. png_debug1(1, "in %s retrieval function\n", "bKGD");
  179973. *background = &(info_ptr->background);
  179974. return (PNG_INFO_bKGD);
  179975. }
  179976. return (0);
  179977. }
  179978. #endif
  179979. #if defined(PNG_cHRM_SUPPORTED)
  179980. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179981. png_uint_32 PNGAPI
  179982. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  179983. double *white_x, double *white_y, double *red_x, double *red_y,
  179984. double *green_x, double *green_y, double *blue_x, double *blue_y)
  179985. {
  179986. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  179987. {
  179988. png_debug1(1, "in %s retrieval function\n", "cHRM");
  179989. if (white_x != NULL)
  179990. *white_x = (double)info_ptr->x_white;
  179991. if (white_y != NULL)
  179992. *white_y = (double)info_ptr->y_white;
  179993. if (red_x != NULL)
  179994. *red_x = (double)info_ptr->x_red;
  179995. if (red_y != NULL)
  179996. *red_y = (double)info_ptr->y_red;
  179997. if (green_x != NULL)
  179998. *green_x = (double)info_ptr->x_green;
  179999. if (green_y != NULL)
  180000. *green_y = (double)info_ptr->y_green;
  180001. if (blue_x != NULL)
  180002. *blue_x = (double)info_ptr->x_blue;
  180003. if (blue_y != NULL)
  180004. *blue_y = (double)info_ptr->y_blue;
  180005. return (PNG_INFO_cHRM);
  180006. }
  180007. return (0);
  180008. }
  180009. #endif
  180010. #ifdef PNG_FIXED_POINT_SUPPORTED
  180011. png_uint_32 PNGAPI
  180012. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  180013. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  180014. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  180015. png_fixed_point *blue_x, png_fixed_point *blue_y)
  180016. {
  180017. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  180018. {
  180019. png_debug1(1, "in %s retrieval function\n", "cHRM");
  180020. if (white_x != NULL)
  180021. *white_x = info_ptr->int_x_white;
  180022. if (white_y != NULL)
  180023. *white_y = info_ptr->int_y_white;
  180024. if (red_x != NULL)
  180025. *red_x = info_ptr->int_x_red;
  180026. if (red_y != NULL)
  180027. *red_y = info_ptr->int_y_red;
  180028. if (green_x != NULL)
  180029. *green_x = info_ptr->int_x_green;
  180030. if (green_y != NULL)
  180031. *green_y = info_ptr->int_y_green;
  180032. if (blue_x != NULL)
  180033. *blue_x = info_ptr->int_x_blue;
  180034. if (blue_y != NULL)
  180035. *blue_y = info_ptr->int_y_blue;
  180036. return (PNG_INFO_cHRM);
  180037. }
  180038. return (0);
  180039. }
  180040. #endif
  180041. #endif
  180042. #if defined(PNG_gAMA_SUPPORTED)
  180043. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180044. png_uint_32 PNGAPI
  180045. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  180046. {
  180047. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  180048. && file_gamma != NULL)
  180049. {
  180050. png_debug1(1, "in %s retrieval function\n", "gAMA");
  180051. *file_gamma = (double)info_ptr->gamma;
  180052. return (PNG_INFO_gAMA);
  180053. }
  180054. return (0);
  180055. }
  180056. #endif
  180057. #ifdef PNG_FIXED_POINT_SUPPORTED
  180058. png_uint_32 PNGAPI
  180059. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  180060. png_fixed_point *int_file_gamma)
  180061. {
  180062. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  180063. && int_file_gamma != NULL)
  180064. {
  180065. png_debug1(1, "in %s retrieval function\n", "gAMA");
  180066. *int_file_gamma = info_ptr->int_gamma;
  180067. return (PNG_INFO_gAMA);
  180068. }
  180069. return (0);
  180070. }
  180071. #endif
  180072. #endif
  180073. #if defined(PNG_sRGB_SUPPORTED)
  180074. png_uint_32 PNGAPI
  180075. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  180076. {
  180077. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  180078. && file_srgb_intent != NULL)
  180079. {
  180080. png_debug1(1, "in %s retrieval function\n", "sRGB");
  180081. *file_srgb_intent = (int)info_ptr->srgb_intent;
  180082. return (PNG_INFO_sRGB);
  180083. }
  180084. return (0);
  180085. }
  180086. #endif
  180087. #if defined(PNG_iCCP_SUPPORTED)
  180088. png_uint_32 PNGAPI
  180089. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  180090. png_charpp name, int *compression_type,
  180091. png_charpp profile, png_uint_32 *proflen)
  180092. {
  180093. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  180094. && name != NULL && profile != NULL && proflen != NULL)
  180095. {
  180096. png_debug1(1, "in %s retrieval function\n", "iCCP");
  180097. *name = info_ptr->iccp_name;
  180098. *profile = info_ptr->iccp_profile;
  180099. /* compression_type is a dummy so the API won't have to change
  180100. if we introduce multiple compression types later. */
  180101. *proflen = (int)info_ptr->iccp_proflen;
  180102. *compression_type = (int)info_ptr->iccp_compression;
  180103. return (PNG_INFO_iCCP);
  180104. }
  180105. return (0);
  180106. }
  180107. #endif
  180108. #if defined(PNG_sPLT_SUPPORTED)
  180109. png_uint_32 PNGAPI
  180110. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  180111. png_sPLT_tpp spalettes)
  180112. {
  180113. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  180114. {
  180115. *spalettes = info_ptr->splt_palettes;
  180116. return ((png_uint_32)info_ptr->splt_palettes_num);
  180117. }
  180118. return (0);
  180119. }
  180120. #endif
  180121. #if defined(PNG_hIST_SUPPORTED)
  180122. png_uint_32 PNGAPI
  180123. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  180124. {
  180125. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  180126. && hist != NULL)
  180127. {
  180128. png_debug1(1, "in %s retrieval function\n", "hIST");
  180129. *hist = info_ptr->hist;
  180130. return (PNG_INFO_hIST);
  180131. }
  180132. return (0);
  180133. }
  180134. #endif
  180135. png_uint_32 PNGAPI
  180136. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  180137. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  180138. int *color_type, int *interlace_type, int *compression_type,
  180139. int *filter_type)
  180140. {
  180141. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  180142. bit_depth != NULL && color_type != NULL)
  180143. {
  180144. png_debug1(1, "in %s retrieval function\n", "IHDR");
  180145. *width = info_ptr->width;
  180146. *height = info_ptr->height;
  180147. *bit_depth = info_ptr->bit_depth;
  180148. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  180149. png_error(png_ptr, "Invalid bit depth");
  180150. *color_type = info_ptr->color_type;
  180151. if (info_ptr->color_type > 6)
  180152. png_error(png_ptr, "Invalid color type");
  180153. if (compression_type != NULL)
  180154. *compression_type = info_ptr->compression_type;
  180155. if (filter_type != NULL)
  180156. *filter_type = info_ptr->filter_type;
  180157. if (interlace_type != NULL)
  180158. *interlace_type = info_ptr->interlace_type;
  180159. /* check for potential overflow of rowbytes */
  180160. if (*width == 0 || *width > PNG_UINT_31_MAX)
  180161. png_error(png_ptr, "Invalid image width");
  180162. if (*height == 0 || *height > PNG_UINT_31_MAX)
  180163. png_error(png_ptr, "Invalid image height");
  180164. if (info_ptr->width > (PNG_UINT_32_MAX
  180165. >> 3) /* 8-byte RGBA pixels */
  180166. - 64 /* bigrowbuf hack */
  180167. - 1 /* filter byte */
  180168. - 7*8 /* rounding of width to multiple of 8 pixels */
  180169. - 8) /* extra max_pixel_depth pad */
  180170. {
  180171. png_warning(png_ptr,
  180172. "Width too large for libpng to process image data.");
  180173. }
  180174. return (1);
  180175. }
  180176. return (0);
  180177. }
  180178. #if defined(PNG_oFFs_SUPPORTED)
  180179. png_uint_32 PNGAPI
  180180. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  180181. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  180182. {
  180183. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  180184. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  180185. {
  180186. png_debug1(1, "in %s retrieval function\n", "oFFs");
  180187. *offset_x = info_ptr->x_offset;
  180188. *offset_y = info_ptr->y_offset;
  180189. *unit_type = (int)info_ptr->offset_unit_type;
  180190. return (PNG_INFO_oFFs);
  180191. }
  180192. return (0);
  180193. }
  180194. #endif
  180195. #if defined(PNG_pCAL_SUPPORTED)
  180196. png_uint_32 PNGAPI
  180197. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  180198. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  180199. png_charp *units, png_charpp *params)
  180200. {
  180201. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  180202. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  180203. nparams != NULL && units != NULL && params != NULL)
  180204. {
  180205. png_debug1(1, "in %s retrieval function\n", "pCAL");
  180206. *purpose = info_ptr->pcal_purpose;
  180207. *X0 = info_ptr->pcal_X0;
  180208. *X1 = info_ptr->pcal_X1;
  180209. *type = (int)info_ptr->pcal_type;
  180210. *nparams = (int)info_ptr->pcal_nparams;
  180211. *units = info_ptr->pcal_units;
  180212. *params = info_ptr->pcal_params;
  180213. return (PNG_INFO_pCAL);
  180214. }
  180215. return (0);
  180216. }
  180217. #endif
  180218. #if defined(PNG_sCAL_SUPPORTED)
  180219. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180220. png_uint_32 PNGAPI
  180221. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  180222. int *unit, double *width, double *height)
  180223. {
  180224. if (png_ptr != NULL && info_ptr != NULL &&
  180225. (info_ptr->valid & PNG_INFO_sCAL))
  180226. {
  180227. *unit = info_ptr->scal_unit;
  180228. *width = info_ptr->scal_pixel_width;
  180229. *height = info_ptr->scal_pixel_height;
  180230. return (PNG_INFO_sCAL);
  180231. }
  180232. return(0);
  180233. }
  180234. #else
  180235. #ifdef PNG_FIXED_POINT_SUPPORTED
  180236. png_uint_32 PNGAPI
  180237. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  180238. int *unit, png_charpp width, png_charpp height)
  180239. {
  180240. if (png_ptr != NULL && info_ptr != NULL &&
  180241. (info_ptr->valid & PNG_INFO_sCAL))
  180242. {
  180243. *unit = info_ptr->scal_unit;
  180244. *width = info_ptr->scal_s_width;
  180245. *height = info_ptr->scal_s_height;
  180246. return (PNG_INFO_sCAL);
  180247. }
  180248. return(0);
  180249. }
  180250. #endif
  180251. #endif
  180252. #endif
  180253. #if defined(PNG_pHYs_SUPPORTED)
  180254. png_uint_32 PNGAPI
  180255. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  180256. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  180257. {
  180258. png_uint_32 retval = 0;
  180259. if (png_ptr != NULL && info_ptr != NULL &&
  180260. (info_ptr->valid & PNG_INFO_pHYs))
  180261. {
  180262. png_debug1(1, "in %s retrieval function\n", "pHYs");
  180263. if (res_x != NULL)
  180264. {
  180265. *res_x = info_ptr->x_pixels_per_unit;
  180266. retval |= PNG_INFO_pHYs;
  180267. }
  180268. if (res_y != NULL)
  180269. {
  180270. *res_y = info_ptr->y_pixels_per_unit;
  180271. retval |= PNG_INFO_pHYs;
  180272. }
  180273. if (unit_type != NULL)
  180274. {
  180275. *unit_type = (int)info_ptr->phys_unit_type;
  180276. retval |= PNG_INFO_pHYs;
  180277. }
  180278. }
  180279. return (retval);
  180280. }
  180281. #endif
  180282. png_uint_32 PNGAPI
  180283. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  180284. int *num_palette)
  180285. {
  180286. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  180287. && palette != NULL)
  180288. {
  180289. png_debug1(1, "in %s retrieval function\n", "PLTE");
  180290. *palette = info_ptr->palette;
  180291. *num_palette = info_ptr->num_palette;
  180292. png_debug1(3, "num_palette = %d\n", *num_palette);
  180293. return (PNG_INFO_PLTE);
  180294. }
  180295. return (0);
  180296. }
  180297. #if defined(PNG_sBIT_SUPPORTED)
  180298. png_uint_32 PNGAPI
  180299. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  180300. {
  180301. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  180302. && sig_bit != NULL)
  180303. {
  180304. png_debug1(1, "in %s retrieval function\n", "sBIT");
  180305. *sig_bit = &(info_ptr->sig_bit);
  180306. return (PNG_INFO_sBIT);
  180307. }
  180308. return (0);
  180309. }
  180310. #endif
  180311. #if defined(PNG_TEXT_SUPPORTED)
  180312. png_uint_32 PNGAPI
  180313. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  180314. int *num_text)
  180315. {
  180316. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  180317. {
  180318. png_debug1(1, "in %s retrieval function\n",
  180319. (png_ptr->chunk_name[0] == '\0' ? "text"
  180320. : (png_const_charp)png_ptr->chunk_name));
  180321. if (text_ptr != NULL)
  180322. *text_ptr = info_ptr->text;
  180323. if (num_text != NULL)
  180324. *num_text = info_ptr->num_text;
  180325. return ((png_uint_32)info_ptr->num_text);
  180326. }
  180327. if (num_text != NULL)
  180328. *num_text = 0;
  180329. return(0);
  180330. }
  180331. #endif
  180332. #if defined(PNG_tIME_SUPPORTED)
  180333. png_uint_32 PNGAPI
  180334. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  180335. {
  180336. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  180337. && mod_time != NULL)
  180338. {
  180339. png_debug1(1, "in %s retrieval function\n", "tIME");
  180340. *mod_time = &(info_ptr->mod_time);
  180341. return (PNG_INFO_tIME);
  180342. }
  180343. return (0);
  180344. }
  180345. #endif
  180346. #if defined(PNG_tRNS_SUPPORTED)
  180347. png_uint_32 PNGAPI
  180348. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  180349. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  180350. {
  180351. png_uint_32 retval = 0;
  180352. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  180353. {
  180354. png_debug1(1, "in %s retrieval function\n", "tRNS");
  180355. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  180356. {
  180357. if (trans != NULL)
  180358. {
  180359. *trans = info_ptr->trans;
  180360. retval |= PNG_INFO_tRNS;
  180361. }
  180362. if (trans_values != NULL)
  180363. *trans_values = &(info_ptr->trans_values);
  180364. }
  180365. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  180366. {
  180367. if (trans_values != NULL)
  180368. {
  180369. *trans_values = &(info_ptr->trans_values);
  180370. retval |= PNG_INFO_tRNS;
  180371. }
  180372. if(trans != NULL)
  180373. *trans = NULL;
  180374. }
  180375. if(num_trans != NULL)
  180376. {
  180377. *num_trans = info_ptr->num_trans;
  180378. retval |= PNG_INFO_tRNS;
  180379. }
  180380. }
  180381. return (retval);
  180382. }
  180383. #endif
  180384. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180385. png_uint_32 PNGAPI
  180386. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  180387. png_unknown_chunkpp unknowns)
  180388. {
  180389. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  180390. {
  180391. *unknowns = info_ptr->unknown_chunks;
  180392. return ((png_uint_32)info_ptr->unknown_chunks_num);
  180393. }
  180394. return (0);
  180395. }
  180396. #endif
  180397. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  180398. png_byte PNGAPI
  180399. png_get_rgb_to_gray_status (png_structp png_ptr)
  180400. {
  180401. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  180402. }
  180403. #endif
  180404. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  180405. png_voidp PNGAPI
  180406. png_get_user_chunk_ptr(png_structp png_ptr)
  180407. {
  180408. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  180409. }
  180410. #endif
  180411. #ifdef PNG_WRITE_SUPPORTED
  180412. png_uint_32 PNGAPI
  180413. png_get_compression_buffer_size(png_structp png_ptr)
  180414. {
  180415. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  180416. }
  180417. #endif
  180418. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  180419. #ifndef PNG_1_0_X
  180420. /* this function was added to libpng 1.2.0 and should exist by default */
  180421. png_uint_32 PNGAPI
  180422. png_get_asm_flags (png_structp png_ptr)
  180423. {
  180424. /* obsolete, to be removed from libpng-1.4.0 */
  180425. return (png_ptr? 0L: 0L);
  180426. }
  180427. /* this function was added to libpng 1.2.0 and should exist by default */
  180428. png_uint_32 PNGAPI
  180429. png_get_asm_flagmask (int flag_select)
  180430. {
  180431. /* obsolete, to be removed from libpng-1.4.0 */
  180432. flag_select=flag_select;
  180433. return 0L;
  180434. }
  180435. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  180436. /* this function was added to libpng 1.2.0 */
  180437. png_uint_32 PNGAPI
  180438. png_get_mmx_flagmask (int flag_select, int *compilerID)
  180439. {
  180440. /* obsolete, to be removed from libpng-1.4.0 */
  180441. flag_select=flag_select;
  180442. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  180443. return 0L;
  180444. }
  180445. /* this function was added to libpng 1.2.0 */
  180446. png_byte PNGAPI
  180447. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  180448. {
  180449. /* obsolete, to be removed from libpng-1.4.0 */
  180450. return (png_ptr? 0: 0);
  180451. }
  180452. /* this function was added to libpng 1.2.0 */
  180453. png_uint_32 PNGAPI
  180454. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  180455. {
  180456. /* obsolete, to be removed from libpng-1.4.0 */
  180457. return (png_ptr? 0L: 0L);
  180458. }
  180459. #endif /* ?PNG_1_0_X */
  180460. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  180461. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  180462. /* these functions were added to libpng 1.2.6 */
  180463. png_uint_32 PNGAPI
  180464. png_get_user_width_max (png_structp png_ptr)
  180465. {
  180466. return (png_ptr? png_ptr->user_width_max : 0);
  180467. }
  180468. png_uint_32 PNGAPI
  180469. png_get_user_height_max (png_structp png_ptr)
  180470. {
  180471. return (png_ptr? png_ptr->user_height_max : 0);
  180472. }
  180473. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  180474. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  180475. /********* End of inlined file: pngget.c *********/
  180476. /********* Start of inlined file: pngmem.c *********/
  180477. /* pngmem.c - stub functions for memory allocation
  180478. *
  180479. * Last changed in libpng 1.2.13 November 13, 2006
  180480. * For conditions of distribution and use, see copyright notice in png.h
  180481. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  180482. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180483. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180484. *
  180485. * This file provides a location for all memory allocation. Users who
  180486. * need special memory handling are expected to supply replacement
  180487. * functions for png_malloc() and png_free(), and to use
  180488. * png_create_read_struct_2() and png_create_write_struct_2() to
  180489. * identify the replacement functions.
  180490. */
  180491. #define PNG_INTERNAL
  180492. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180493. /* Borland DOS special memory handler */
  180494. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  180495. /* if you change this, be sure to change the one in png.h also */
  180496. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  180497. by a single call to calloc() if this is thought to improve performance. */
  180498. png_voidp /* PRIVATE */
  180499. png_create_struct(int type)
  180500. {
  180501. #ifdef PNG_USER_MEM_SUPPORTED
  180502. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  180503. }
  180504. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  180505. png_voidp /* PRIVATE */
  180506. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  180507. {
  180508. #endif /* PNG_USER_MEM_SUPPORTED */
  180509. png_size_t size;
  180510. png_voidp struct_ptr;
  180511. if (type == PNG_STRUCT_INFO)
  180512. size = png_sizeof(png_info);
  180513. else if (type == PNG_STRUCT_PNG)
  180514. size = png_sizeof(png_struct);
  180515. else
  180516. return (png_get_copyright(NULL));
  180517. #ifdef PNG_USER_MEM_SUPPORTED
  180518. if(malloc_fn != NULL)
  180519. {
  180520. png_struct dummy_struct;
  180521. png_structp png_ptr = &dummy_struct;
  180522. png_ptr->mem_ptr=mem_ptr;
  180523. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  180524. }
  180525. else
  180526. #endif /* PNG_USER_MEM_SUPPORTED */
  180527. struct_ptr = (png_voidp)farmalloc(size);
  180528. if (struct_ptr != NULL)
  180529. png_memset(struct_ptr, 0, size);
  180530. return (struct_ptr);
  180531. }
  180532. /* Free memory allocated by a png_create_struct() call */
  180533. void /* PRIVATE */
  180534. png_destroy_struct(png_voidp struct_ptr)
  180535. {
  180536. #ifdef PNG_USER_MEM_SUPPORTED
  180537. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  180538. }
  180539. /* Free memory allocated by a png_create_struct() call */
  180540. void /* PRIVATE */
  180541. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  180542. png_voidp mem_ptr)
  180543. {
  180544. #endif
  180545. if (struct_ptr != NULL)
  180546. {
  180547. #ifdef PNG_USER_MEM_SUPPORTED
  180548. if(free_fn != NULL)
  180549. {
  180550. png_struct dummy_struct;
  180551. png_structp png_ptr = &dummy_struct;
  180552. png_ptr->mem_ptr=mem_ptr;
  180553. (*(free_fn))(png_ptr, struct_ptr);
  180554. return;
  180555. }
  180556. #endif /* PNG_USER_MEM_SUPPORTED */
  180557. farfree (struct_ptr);
  180558. }
  180559. }
  180560. /* Allocate memory. For reasonable files, size should never exceed
  180561. * 64K. However, zlib may allocate more then 64K if you don't tell
  180562. * it not to. See zconf.h and png.h for more information. zlib does
  180563. * need to allocate exactly 64K, so whatever you call here must
  180564. * have the ability to do that.
  180565. *
  180566. * Borland seems to have a problem in DOS mode for exactly 64K.
  180567. * It gives you a segment with an offset of 8 (perhaps to store its
  180568. * memory stuff). zlib doesn't like this at all, so we have to
  180569. * detect and deal with it. This code should not be needed in
  180570. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  180571. * been updated by Alexander Lehmann for version 0.89 to waste less
  180572. * memory.
  180573. *
  180574. * Note that we can't use png_size_t for the "size" declaration,
  180575. * since on some systems a png_size_t is a 16-bit quantity, and as a
  180576. * result, we would be truncating potentially larger memory requests
  180577. * (which should cause a fatal error) and introducing major problems.
  180578. */
  180579. png_voidp PNGAPI
  180580. png_malloc(png_structp png_ptr, png_uint_32 size)
  180581. {
  180582. png_voidp ret;
  180583. if (png_ptr == NULL || size == 0)
  180584. return (NULL);
  180585. #ifdef PNG_USER_MEM_SUPPORTED
  180586. if(png_ptr->malloc_fn != NULL)
  180587. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  180588. else
  180589. ret = (png_malloc_default(png_ptr, size));
  180590. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180591. png_error(png_ptr, "Out of memory!");
  180592. return (ret);
  180593. }
  180594. png_voidp PNGAPI
  180595. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  180596. {
  180597. png_voidp ret;
  180598. #endif /* PNG_USER_MEM_SUPPORTED */
  180599. if (png_ptr == NULL || size == 0)
  180600. return (NULL);
  180601. #ifdef PNG_MAX_MALLOC_64K
  180602. if (size > (png_uint_32)65536L)
  180603. {
  180604. png_warning(png_ptr, "Cannot Allocate > 64K");
  180605. ret = NULL;
  180606. }
  180607. else
  180608. #endif
  180609. if (size != (size_t)size)
  180610. ret = NULL;
  180611. else if (size == (png_uint_32)65536L)
  180612. {
  180613. if (png_ptr->offset_table == NULL)
  180614. {
  180615. /* try to see if we need to do any of this fancy stuff */
  180616. ret = farmalloc(size);
  180617. if (ret == NULL || ((png_size_t)ret & 0xffff))
  180618. {
  180619. int num_blocks;
  180620. png_uint_32 total_size;
  180621. png_bytep table;
  180622. int i;
  180623. png_byte huge * hptr;
  180624. if (ret != NULL)
  180625. {
  180626. farfree(ret);
  180627. ret = NULL;
  180628. }
  180629. if(png_ptr->zlib_window_bits > 14)
  180630. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  180631. else
  180632. num_blocks = 1;
  180633. if (png_ptr->zlib_mem_level >= 7)
  180634. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  180635. else
  180636. num_blocks++;
  180637. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  180638. table = farmalloc(total_size);
  180639. if (table == NULL)
  180640. {
  180641. #ifndef PNG_USER_MEM_SUPPORTED
  180642. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180643. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  180644. else
  180645. png_warning(png_ptr, "Out Of Memory.");
  180646. #endif
  180647. return (NULL);
  180648. }
  180649. if ((png_size_t)table & 0xfff0)
  180650. {
  180651. #ifndef PNG_USER_MEM_SUPPORTED
  180652. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180653. png_error(png_ptr,
  180654. "Farmalloc didn't return normalized pointer");
  180655. else
  180656. png_warning(png_ptr,
  180657. "Farmalloc didn't return normalized pointer");
  180658. #endif
  180659. return (NULL);
  180660. }
  180661. png_ptr->offset_table = table;
  180662. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  180663. png_sizeof (png_bytep));
  180664. if (png_ptr->offset_table_ptr == NULL)
  180665. {
  180666. #ifndef PNG_USER_MEM_SUPPORTED
  180667. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180668. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  180669. else
  180670. png_warning(png_ptr, "Out Of memory.");
  180671. #endif
  180672. return (NULL);
  180673. }
  180674. hptr = (png_byte huge *)table;
  180675. if ((png_size_t)hptr & 0xf)
  180676. {
  180677. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  180678. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  180679. }
  180680. for (i = 0; i < num_blocks; i++)
  180681. {
  180682. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  180683. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  180684. }
  180685. png_ptr->offset_table_number = num_blocks;
  180686. png_ptr->offset_table_count = 0;
  180687. png_ptr->offset_table_count_free = 0;
  180688. }
  180689. }
  180690. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  180691. {
  180692. #ifndef PNG_USER_MEM_SUPPORTED
  180693. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180694. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  180695. else
  180696. png_warning(png_ptr, "Out of Memory.");
  180697. #endif
  180698. return (NULL);
  180699. }
  180700. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  180701. }
  180702. else
  180703. ret = farmalloc(size);
  180704. #ifndef PNG_USER_MEM_SUPPORTED
  180705. if (ret == NULL)
  180706. {
  180707. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180708. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  180709. else
  180710. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  180711. }
  180712. #endif
  180713. return (ret);
  180714. }
  180715. /* free a pointer allocated by png_malloc(). In the default
  180716. configuration, png_ptr is not used, but is passed in case it
  180717. is needed. If ptr is NULL, return without taking any action. */
  180718. void PNGAPI
  180719. png_free(png_structp png_ptr, png_voidp ptr)
  180720. {
  180721. if (png_ptr == NULL || ptr == NULL)
  180722. return;
  180723. #ifdef PNG_USER_MEM_SUPPORTED
  180724. if (png_ptr->free_fn != NULL)
  180725. {
  180726. (*(png_ptr->free_fn))(png_ptr, ptr);
  180727. return;
  180728. }
  180729. else png_free_default(png_ptr, ptr);
  180730. }
  180731. void PNGAPI
  180732. png_free_default(png_structp png_ptr, png_voidp ptr)
  180733. {
  180734. #endif /* PNG_USER_MEM_SUPPORTED */
  180735. if(png_ptr == NULL) return;
  180736. if (png_ptr->offset_table != NULL)
  180737. {
  180738. int i;
  180739. for (i = 0; i < png_ptr->offset_table_count; i++)
  180740. {
  180741. if (ptr == png_ptr->offset_table_ptr[i])
  180742. {
  180743. ptr = NULL;
  180744. png_ptr->offset_table_count_free++;
  180745. break;
  180746. }
  180747. }
  180748. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  180749. {
  180750. farfree(png_ptr->offset_table);
  180751. farfree(png_ptr->offset_table_ptr);
  180752. png_ptr->offset_table = NULL;
  180753. png_ptr->offset_table_ptr = NULL;
  180754. }
  180755. }
  180756. if (ptr != NULL)
  180757. {
  180758. farfree(ptr);
  180759. }
  180760. }
  180761. #else /* Not the Borland DOS special memory handler */
  180762. /* Allocate memory for a png_struct or a png_info. The malloc and
  180763. memset can be replaced by a single call to calloc() if this is thought
  180764. to improve performance noticably. */
  180765. png_voidp /* PRIVATE */
  180766. png_create_struct(int type)
  180767. {
  180768. #ifdef PNG_USER_MEM_SUPPORTED
  180769. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  180770. }
  180771. /* Allocate memory for a png_struct or a png_info. The malloc and
  180772. memset can be replaced by a single call to calloc() if this is thought
  180773. to improve performance noticably. */
  180774. png_voidp /* PRIVATE */
  180775. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  180776. {
  180777. #endif /* PNG_USER_MEM_SUPPORTED */
  180778. png_size_t size;
  180779. png_voidp struct_ptr;
  180780. if (type == PNG_STRUCT_INFO)
  180781. size = png_sizeof(png_info);
  180782. else if (type == PNG_STRUCT_PNG)
  180783. size = png_sizeof(png_struct);
  180784. else
  180785. return (NULL);
  180786. #ifdef PNG_USER_MEM_SUPPORTED
  180787. if(malloc_fn != NULL)
  180788. {
  180789. png_struct dummy_struct;
  180790. png_structp png_ptr = &dummy_struct;
  180791. png_ptr->mem_ptr=mem_ptr;
  180792. struct_ptr = (*(malloc_fn))(png_ptr, size);
  180793. if (struct_ptr != NULL)
  180794. png_memset(struct_ptr, 0, size);
  180795. return (struct_ptr);
  180796. }
  180797. #endif /* PNG_USER_MEM_SUPPORTED */
  180798. #if defined(__TURBOC__) && !defined(__FLAT__)
  180799. struct_ptr = (png_voidp)farmalloc(size);
  180800. #else
  180801. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180802. struct_ptr = (png_voidp)halloc(size,1);
  180803. # else
  180804. struct_ptr = (png_voidp)malloc(size);
  180805. # endif
  180806. #endif
  180807. if (struct_ptr != NULL)
  180808. png_memset(struct_ptr, 0, size);
  180809. return (struct_ptr);
  180810. }
  180811. /* Free memory allocated by a png_create_struct() call */
  180812. void /* PRIVATE */
  180813. png_destroy_struct(png_voidp struct_ptr)
  180814. {
  180815. #ifdef PNG_USER_MEM_SUPPORTED
  180816. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  180817. }
  180818. /* Free memory allocated by a png_create_struct() call */
  180819. void /* PRIVATE */
  180820. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  180821. png_voidp mem_ptr)
  180822. {
  180823. #endif /* PNG_USER_MEM_SUPPORTED */
  180824. if (struct_ptr != NULL)
  180825. {
  180826. #ifdef PNG_USER_MEM_SUPPORTED
  180827. if(free_fn != NULL)
  180828. {
  180829. png_struct dummy_struct;
  180830. png_structp png_ptr = &dummy_struct;
  180831. png_ptr->mem_ptr=mem_ptr;
  180832. (*(free_fn))(png_ptr, struct_ptr);
  180833. return;
  180834. }
  180835. #endif /* PNG_USER_MEM_SUPPORTED */
  180836. #if defined(__TURBOC__) && !defined(__FLAT__)
  180837. farfree(struct_ptr);
  180838. #else
  180839. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180840. hfree(struct_ptr);
  180841. # else
  180842. free(struct_ptr);
  180843. # endif
  180844. #endif
  180845. }
  180846. }
  180847. /* Allocate memory. For reasonable files, size should never exceed
  180848. 64K. However, zlib may allocate more then 64K if you don't tell
  180849. it not to. See zconf.h and png.h for more information. zlib does
  180850. need to allocate exactly 64K, so whatever you call here must
  180851. have the ability to do that. */
  180852. png_voidp PNGAPI
  180853. png_malloc(png_structp png_ptr, png_uint_32 size)
  180854. {
  180855. png_voidp ret;
  180856. #ifdef PNG_USER_MEM_SUPPORTED
  180857. if (png_ptr == NULL || size == 0)
  180858. return (NULL);
  180859. if(png_ptr->malloc_fn != NULL)
  180860. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  180861. else
  180862. ret = (png_malloc_default(png_ptr, size));
  180863. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180864. png_error(png_ptr, "Out of Memory!");
  180865. return (ret);
  180866. }
  180867. png_voidp PNGAPI
  180868. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  180869. {
  180870. png_voidp ret;
  180871. #endif /* PNG_USER_MEM_SUPPORTED */
  180872. if (png_ptr == NULL || size == 0)
  180873. return (NULL);
  180874. #ifdef PNG_MAX_MALLOC_64K
  180875. if (size > (png_uint_32)65536L)
  180876. {
  180877. #ifndef PNG_USER_MEM_SUPPORTED
  180878. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180879. png_error(png_ptr, "Cannot Allocate > 64K");
  180880. else
  180881. #endif
  180882. return NULL;
  180883. }
  180884. #endif
  180885. /* Check for overflow */
  180886. #if defined(__TURBOC__) && !defined(__FLAT__)
  180887. if (size != (unsigned long)size)
  180888. ret = NULL;
  180889. else
  180890. ret = farmalloc(size);
  180891. #else
  180892. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180893. if (size != (unsigned long)size)
  180894. ret = NULL;
  180895. else
  180896. ret = halloc(size, 1);
  180897. # else
  180898. if (size != (size_t)size)
  180899. ret = NULL;
  180900. else
  180901. ret = malloc((size_t)size);
  180902. # endif
  180903. #endif
  180904. #ifndef PNG_USER_MEM_SUPPORTED
  180905. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180906. png_error(png_ptr, "Out of Memory");
  180907. #endif
  180908. return (ret);
  180909. }
  180910. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  180911. without taking any action. */
  180912. void PNGAPI
  180913. png_free(png_structp png_ptr, png_voidp ptr)
  180914. {
  180915. if (png_ptr == NULL || ptr == NULL)
  180916. return;
  180917. #ifdef PNG_USER_MEM_SUPPORTED
  180918. if (png_ptr->free_fn != NULL)
  180919. {
  180920. (*(png_ptr->free_fn))(png_ptr, ptr);
  180921. return;
  180922. }
  180923. else png_free_default(png_ptr, ptr);
  180924. }
  180925. void PNGAPI
  180926. png_free_default(png_structp png_ptr, png_voidp ptr)
  180927. {
  180928. if (png_ptr == NULL || ptr == NULL)
  180929. return;
  180930. #endif /* PNG_USER_MEM_SUPPORTED */
  180931. #if defined(__TURBOC__) && !defined(__FLAT__)
  180932. farfree(ptr);
  180933. #else
  180934. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180935. hfree(ptr);
  180936. # else
  180937. free(ptr);
  180938. # endif
  180939. #endif
  180940. }
  180941. #endif /* Not Borland DOS special memory handler */
  180942. #if defined(PNG_1_0_X)
  180943. # define png_malloc_warn png_malloc
  180944. #else
  180945. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  180946. * function will set up png_malloc() to issue a png_warning and return NULL
  180947. * instead of issuing a png_error, if it fails to allocate the requested
  180948. * memory.
  180949. */
  180950. png_voidp PNGAPI
  180951. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  180952. {
  180953. png_voidp ptr;
  180954. png_uint_32 save_flags;
  180955. if(png_ptr == NULL) return (NULL);
  180956. save_flags=png_ptr->flags;
  180957. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  180958. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  180959. png_ptr->flags=save_flags;
  180960. return(ptr);
  180961. }
  180962. #endif
  180963. png_voidp PNGAPI
  180964. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  180965. png_uint_32 length)
  180966. {
  180967. png_size_t size;
  180968. size = (png_size_t)length;
  180969. if ((png_uint_32)size != length)
  180970. png_error(png_ptr,"Overflow in png_memcpy_check.");
  180971. return(png_memcpy (s1, s2, size));
  180972. }
  180973. png_voidp PNGAPI
  180974. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  180975. png_uint_32 length)
  180976. {
  180977. png_size_t size;
  180978. size = (png_size_t)length;
  180979. if ((png_uint_32)size != length)
  180980. png_error(png_ptr,"Overflow in png_memset_check.");
  180981. return (png_memset (s1, value, size));
  180982. }
  180983. #ifdef PNG_USER_MEM_SUPPORTED
  180984. /* This function is called when the application wants to use another method
  180985. * of allocating and freeing memory.
  180986. */
  180987. void PNGAPI
  180988. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  180989. malloc_fn, png_free_ptr free_fn)
  180990. {
  180991. if(png_ptr != NULL) {
  180992. png_ptr->mem_ptr = mem_ptr;
  180993. png_ptr->malloc_fn = malloc_fn;
  180994. png_ptr->free_fn = free_fn;
  180995. }
  180996. }
  180997. /* This function returns a pointer to the mem_ptr associated with the user
  180998. * functions. The application should free any memory associated with this
  180999. * pointer before png_write_destroy and png_read_destroy are called.
  181000. */
  181001. png_voidp PNGAPI
  181002. png_get_mem_ptr(png_structp png_ptr)
  181003. {
  181004. if(png_ptr == NULL) return (NULL);
  181005. return ((png_voidp)png_ptr->mem_ptr);
  181006. }
  181007. #endif /* PNG_USER_MEM_SUPPORTED */
  181008. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  181009. /********* End of inlined file: pngmem.c *********/
  181010. /********* Start of inlined file: pngread.c *********/
  181011. /* pngread.c - read a PNG file
  181012. *
  181013. * Last changed in libpng 1.2.20 September 7, 2007
  181014. * For conditions of distribution and use, see copyright notice in png.h
  181015. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181016. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181017. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181018. *
  181019. * This file contains routines that an application calls directly to
  181020. * read a PNG file or stream.
  181021. */
  181022. #define PNG_INTERNAL
  181023. #if defined(PNG_READ_SUPPORTED)
  181024. /* Create a PNG structure for reading, and allocate any memory needed. */
  181025. png_structp PNGAPI
  181026. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  181027. png_error_ptr error_fn, png_error_ptr warn_fn)
  181028. {
  181029. #ifdef PNG_USER_MEM_SUPPORTED
  181030. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  181031. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  181032. }
  181033. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  181034. png_structp PNGAPI
  181035. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  181036. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  181037. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  181038. {
  181039. #endif /* PNG_USER_MEM_SUPPORTED */
  181040. png_structp png_ptr;
  181041. #ifdef PNG_SETJMP_SUPPORTED
  181042. #ifdef USE_FAR_KEYWORD
  181043. jmp_buf jmpbuf;
  181044. #endif
  181045. #endif
  181046. int i;
  181047. png_debug(1, "in png_create_read_struct\n");
  181048. #ifdef PNG_USER_MEM_SUPPORTED
  181049. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  181050. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  181051. #else
  181052. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  181053. #endif
  181054. if (png_ptr == NULL)
  181055. return (NULL);
  181056. /* added at libpng-1.2.6 */
  181057. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  181058. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  181059. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  181060. #endif
  181061. #ifdef PNG_SETJMP_SUPPORTED
  181062. #ifdef USE_FAR_KEYWORD
  181063. if (setjmp(jmpbuf))
  181064. #else
  181065. if (setjmp(png_ptr->jmpbuf))
  181066. #endif
  181067. {
  181068. png_free(png_ptr, png_ptr->zbuf);
  181069. png_ptr->zbuf=NULL;
  181070. #ifdef PNG_USER_MEM_SUPPORTED
  181071. png_destroy_struct_2((png_voidp)png_ptr,
  181072. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  181073. #else
  181074. png_destroy_struct((png_voidp)png_ptr);
  181075. #endif
  181076. return (NULL);
  181077. }
  181078. #ifdef USE_FAR_KEYWORD
  181079. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  181080. #endif
  181081. #endif
  181082. #ifdef PNG_USER_MEM_SUPPORTED
  181083. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  181084. #endif
  181085. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  181086. i=0;
  181087. do
  181088. {
  181089. if(user_png_ver[i] != png_libpng_ver[i])
  181090. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  181091. } while (png_libpng_ver[i++]);
  181092. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  181093. {
  181094. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  181095. * we must recompile any applications that use any older library version.
  181096. * For versions after libpng 1.0, we will be compatible, so we need
  181097. * only check the first digit.
  181098. */
  181099. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  181100. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  181101. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  181102. {
  181103. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  181104. char msg[80];
  181105. if (user_png_ver)
  181106. {
  181107. png_snprintf(msg, 80,
  181108. "Application was compiled with png.h from libpng-%.20s",
  181109. user_png_ver);
  181110. png_warning(png_ptr, msg);
  181111. }
  181112. png_snprintf(msg, 80,
  181113. "Application is running with png.c from libpng-%.20s",
  181114. png_libpng_ver);
  181115. png_warning(png_ptr, msg);
  181116. #endif
  181117. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181118. png_ptr->flags=0;
  181119. #endif
  181120. png_error(png_ptr,
  181121. "Incompatible libpng version in application and library");
  181122. }
  181123. }
  181124. /* initialize zbuf - compression buffer */
  181125. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  181126. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  181127. (png_uint_32)png_ptr->zbuf_size);
  181128. png_ptr->zstream.zalloc = png_zalloc;
  181129. png_ptr->zstream.zfree = png_zfree;
  181130. png_ptr->zstream.opaque = (voidpf)png_ptr;
  181131. switch (inflateInit(&png_ptr->zstream))
  181132. {
  181133. case Z_OK: /* Do nothing */ break;
  181134. case Z_MEM_ERROR:
  181135. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  181136. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  181137. default: png_error(png_ptr, "Unknown zlib error");
  181138. }
  181139. png_ptr->zstream.next_out = png_ptr->zbuf;
  181140. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  181141. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  181142. #ifdef PNG_SETJMP_SUPPORTED
  181143. /* Applications that neglect to set up their own setjmp() and then encounter
  181144. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  181145. abort instead of returning. */
  181146. #ifdef USE_FAR_KEYWORD
  181147. if (setjmp(jmpbuf))
  181148. PNG_ABORT();
  181149. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  181150. #else
  181151. if (setjmp(png_ptr->jmpbuf))
  181152. PNG_ABORT();
  181153. #endif
  181154. #endif
  181155. return (png_ptr);
  181156. }
  181157. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  181158. /* Initialize PNG structure for reading, and allocate any memory needed.
  181159. This interface is deprecated in favour of the png_create_read_struct(),
  181160. and it will disappear as of libpng-1.3.0. */
  181161. #undef png_read_init
  181162. void PNGAPI
  181163. png_read_init(png_structp png_ptr)
  181164. {
  181165. /* We only come here via pre-1.0.7-compiled applications */
  181166. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  181167. }
  181168. void PNGAPI
  181169. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  181170. png_size_t png_struct_size, png_size_t png_info_size)
  181171. {
  181172. /* We only come here via pre-1.0.12-compiled applications */
  181173. if(png_ptr == NULL) return;
  181174. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  181175. if(png_sizeof(png_struct) > png_struct_size ||
  181176. png_sizeof(png_info) > png_info_size)
  181177. {
  181178. char msg[80];
  181179. png_ptr->warning_fn=NULL;
  181180. if (user_png_ver)
  181181. {
  181182. png_snprintf(msg, 80,
  181183. "Application was compiled with png.h from libpng-%.20s",
  181184. user_png_ver);
  181185. png_warning(png_ptr, msg);
  181186. }
  181187. png_snprintf(msg, 80,
  181188. "Application is running with png.c from libpng-%.20s",
  181189. png_libpng_ver);
  181190. png_warning(png_ptr, msg);
  181191. }
  181192. #endif
  181193. if(png_sizeof(png_struct) > png_struct_size)
  181194. {
  181195. png_ptr->error_fn=NULL;
  181196. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181197. png_ptr->flags=0;
  181198. #endif
  181199. png_error(png_ptr,
  181200. "The png struct allocated by the application for reading is too small.");
  181201. }
  181202. if(png_sizeof(png_info) > png_info_size)
  181203. {
  181204. png_ptr->error_fn=NULL;
  181205. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181206. png_ptr->flags=0;
  181207. #endif
  181208. png_error(png_ptr,
  181209. "The info struct allocated by application for reading is too small.");
  181210. }
  181211. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  181212. }
  181213. #endif /* PNG_1_0_X || PNG_1_2_X */
  181214. void PNGAPI
  181215. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  181216. png_size_t png_struct_size)
  181217. {
  181218. #ifdef PNG_SETJMP_SUPPORTED
  181219. jmp_buf tmp_jmp; /* to save current jump buffer */
  181220. #endif
  181221. int i=0;
  181222. png_structp png_ptr=*ptr_ptr;
  181223. if(png_ptr == NULL) return;
  181224. do
  181225. {
  181226. if(user_png_ver[i] != png_libpng_ver[i])
  181227. {
  181228. #ifdef PNG_LEGACY_SUPPORTED
  181229. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  181230. #else
  181231. png_ptr->warning_fn=NULL;
  181232. png_warning(png_ptr,
  181233. "Application uses deprecated png_read_init() and should be recompiled.");
  181234. break;
  181235. #endif
  181236. }
  181237. } while (png_libpng_ver[i++]);
  181238. png_debug(1, "in png_read_init_3\n");
  181239. #ifdef PNG_SETJMP_SUPPORTED
  181240. /* save jump buffer and error functions */
  181241. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  181242. #endif
  181243. if(png_sizeof(png_struct) > png_struct_size)
  181244. {
  181245. png_destroy_struct(png_ptr);
  181246. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  181247. png_ptr = *ptr_ptr;
  181248. }
  181249. /* reset all variables to 0 */
  181250. png_memset(png_ptr, 0, png_sizeof (png_struct));
  181251. #ifdef PNG_SETJMP_SUPPORTED
  181252. /* restore jump buffer */
  181253. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  181254. #endif
  181255. /* added at libpng-1.2.6 */
  181256. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  181257. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  181258. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  181259. #endif
  181260. /* initialize zbuf - compression buffer */
  181261. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  181262. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  181263. (png_uint_32)png_ptr->zbuf_size);
  181264. png_ptr->zstream.zalloc = png_zalloc;
  181265. png_ptr->zstream.zfree = png_zfree;
  181266. png_ptr->zstream.opaque = (voidpf)png_ptr;
  181267. switch (inflateInit(&png_ptr->zstream))
  181268. {
  181269. case Z_OK: /* Do nothing */ break;
  181270. case Z_MEM_ERROR:
  181271. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  181272. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  181273. default: png_error(png_ptr, "Unknown zlib error");
  181274. }
  181275. png_ptr->zstream.next_out = png_ptr->zbuf;
  181276. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  181277. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  181278. }
  181279. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181280. /* Read the information before the actual image data. This has been
  181281. * changed in v0.90 to allow reading a file that already has the magic
  181282. * bytes read from the stream. You can tell libpng how many bytes have
  181283. * been read from the beginning of the stream (up to the maximum of 8)
  181284. * via png_set_sig_bytes(), and we will only check the remaining bytes
  181285. * here. The application can then have access to the signature bytes we
  181286. * read if it is determined that this isn't a valid PNG file.
  181287. */
  181288. void PNGAPI
  181289. png_read_info(png_structp png_ptr, png_infop info_ptr)
  181290. {
  181291. if(png_ptr == NULL) return;
  181292. png_debug(1, "in png_read_info\n");
  181293. /* If we haven't checked all of the PNG signature bytes, do so now. */
  181294. if (png_ptr->sig_bytes < 8)
  181295. {
  181296. png_size_t num_checked = png_ptr->sig_bytes,
  181297. num_to_check = 8 - num_checked;
  181298. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  181299. png_ptr->sig_bytes = 8;
  181300. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  181301. {
  181302. if (num_checked < 4 &&
  181303. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  181304. png_error(png_ptr, "Not a PNG file");
  181305. else
  181306. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  181307. }
  181308. if (num_checked < 3)
  181309. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  181310. }
  181311. for(;;)
  181312. {
  181313. #ifdef PNG_USE_LOCAL_ARRAYS
  181314. PNG_CONST PNG_IHDR;
  181315. PNG_CONST PNG_IDAT;
  181316. PNG_CONST PNG_IEND;
  181317. PNG_CONST PNG_PLTE;
  181318. #if defined(PNG_READ_bKGD_SUPPORTED)
  181319. PNG_CONST PNG_bKGD;
  181320. #endif
  181321. #if defined(PNG_READ_cHRM_SUPPORTED)
  181322. PNG_CONST PNG_cHRM;
  181323. #endif
  181324. #if defined(PNG_READ_gAMA_SUPPORTED)
  181325. PNG_CONST PNG_gAMA;
  181326. #endif
  181327. #if defined(PNG_READ_hIST_SUPPORTED)
  181328. PNG_CONST PNG_hIST;
  181329. #endif
  181330. #if defined(PNG_READ_iCCP_SUPPORTED)
  181331. PNG_CONST PNG_iCCP;
  181332. #endif
  181333. #if defined(PNG_READ_iTXt_SUPPORTED)
  181334. PNG_CONST PNG_iTXt;
  181335. #endif
  181336. #if defined(PNG_READ_oFFs_SUPPORTED)
  181337. PNG_CONST PNG_oFFs;
  181338. #endif
  181339. #if defined(PNG_READ_pCAL_SUPPORTED)
  181340. PNG_CONST PNG_pCAL;
  181341. #endif
  181342. #if defined(PNG_READ_pHYs_SUPPORTED)
  181343. PNG_CONST PNG_pHYs;
  181344. #endif
  181345. #if defined(PNG_READ_sBIT_SUPPORTED)
  181346. PNG_CONST PNG_sBIT;
  181347. #endif
  181348. #if defined(PNG_READ_sCAL_SUPPORTED)
  181349. PNG_CONST PNG_sCAL;
  181350. #endif
  181351. #if defined(PNG_READ_sPLT_SUPPORTED)
  181352. PNG_CONST PNG_sPLT;
  181353. #endif
  181354. #if defined(PNG_READ_sRGB_SUPPORTED)
  181355. PNG_CONST PNG_sRGB;
  181356. #endif
  181357. #if defined(PNG_READ_tEXt_SUPPORTED)
  181358. PNG_CONST PNG_tEXt;
  181359. #endif
  181360. #if defined(PNG_READ_tIME_SUPPORTED)
  181361. PNG_CONST PNG_tIME;
  181362. #endif
  181363. #if defined(PNG_READ_tRNS_SUPPORTED)
  181364. PNG_CONST PNG_tRNS;
  181365. #endif
  181366. #if defined(PNG_READ_zTXt_SUPPORTED)
  181367. PNG_CONST PNG_zTXt;
  181368. #endif
  181369. #endif /* PNG_USE_LOCAL_ARRAYS */
  181370. png_byte chunk_length[4];
  181371. png_uint_32 length;
  181372. png_read_data(png_ptr, chunk_length, 4);
  181373. length = png_get_uint_31(png_ptr,chunk_length);
  181374. png_reset_crc(png_ptr);
  181375. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  181376. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  181377. length);
  181378. /* This should be a binary subdivision search or a hash for
  181379. * matching the chunk name rather than a linear search.
  181380. */
  181381. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181382. if(png_ptr->mode & PNG_AFTER_IDAT)
  181383. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  181384. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  181385. png_handle_IHDR(png_ptr, info_ptr, length);
  181386. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  181387. png_handle_IEND(png_ptr, info_ptr, length);
  181388. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181389. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  181390. {
  181391. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181392. png_ptr->mode |= PNG_HAVE_IDAT;
  181393. png_handle_unknown(png_ptr, info_ptr, length);
  181394. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181395. png_ptr->mode |= PNG_HAVE_PLTE;
  181396. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181397. {
  181398. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  181399. png_error(png_ptr, "Missing IHDR before IDAT");
  181400. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  181401. !(png_ptr->mode & PNG_HAVE_PLTE))
  181402. png_error(png_ptr, "Missing PLTE before IDAT");
  181403. break;
  181404. }
  181405. }
  181406. #endif
  181407. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181408. png_handle_PLTE(png_ptr, info_ptr, length);
  181409. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181410. {
  181411. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  181412. png_error(png_ptr, "Missing IHDR before IDAT");
  181413. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  181414. !(png_ptr->mode & PNG_HAVE_PLTE))
  181415. png_error(png_ptr, "Missing PLTE before IDAT");
  181416. png_ptr->idat_size = length;
  181417. png_ptr->mode |= PNG_HAVE_IDAT;
  181418. break;
  181419. }
  181420. #if defined(PNG_READ_bKGD_SUPPORTED)
  181421. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  181422. png_handle_bKGD(png_ptr, info_ptr, length);
  181423. #endif
  181424. #if defined(PNG_READ_cHRM_SUPPORTED)
  181425. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  181426. png_handle_cHRM(png_ptr, info_ptr, length);
  181427. #endif
  181428. #if defined(PNG_READ_gAMA_SUPPORTED)
  181429. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  181430. png_handle_gAMA(png_ptr, info_ptr, length);
  181431. #endif
  181432. #if defined(PNG_READ_hIST_SUPPORTED)
  181433. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  181434. png_handle_hIST(png_ptr, info_ptr, length);
  181435. #endif
  181436. #if defined(PNG_READ_oFFs_SUPPORTED)
  181437. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  181438. png_handle_oFFs(png_ptr, info_ptr, length);
  181439. #endif
  181440. #if defined(PNG_READ_pCAL_SUPPORTED)
  181441. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  181442. png_handle_pCAL(png_ptr, info_ptr, length);
  181443. #endif
  181444. #if defined(PNG_READ_sCAL_SUPPORTED)
  181445. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  181446. png_handle_sCAL(png_ptr, info_ptr, length);
  181447. #endif
  181448. #if defined(PNG_READ_pHYs_SUPPORTED)
  181449. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  181450. png_handle_pHYs(png_ptr, info_ptr, length);
  181451. #endif
  181452. #if defined(PNG_READ_sBIT_SUPPORTED)
  181453. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  181454. png_handle_sBIT(png_ptr, info_ptr, length);
  181455. #endif
  181456. #if defined(PNG_READ_sRGB_SUPPORTED)
  181457. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  181458. png_handle_sRGB(png_ptr, info_ptr, length);
  181459. #endif
  181460. #if defined(PNG_READ_iCCP_SUPPORTED)
  181461. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  181462. png_handle_iCCP(png_ptr, info_ptr, length);
  181463. #endif
  181464. #if defined(PNG_READ_sPLT_SUPPORTED)
  181465. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  181466. png_handle_sPLT(png_ptr, info_ptr, length);
  181467. #endif
  181468. #if defined(PNG_READ_tEXt_SUPPORTED)
  181469. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  181470. png_handle_tEXt(png_ptr, info_ptr, length);
  181471. #endif
  181472. #if defined(PNG_READ_tIME_SUPPORTED)
  181473. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  181474. png_handle_tIME(png_ptr, info_ptr, length);
  181475. #endif
  181476. #if defined(PNG_READ_tRNS_SUPPORTED)
  181477. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  181478. png_handle_tRNS(png_ptr, info_ptr, length);
  181479. #endif
  181480. #if defined(PNG_READ_zTXt_SUPPORTED)
  181481. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  181482. png_handle_zTXt(png_ptr, info_ptr, length);
  181483. #endif
  181484. #if defined(PNG_READ_iTXt_SUPPORTED)
  181485. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  181486. png_handle_iTXt(png_ptr, info_ptr, length);
  181487. #endif
  181488. else
  181489. png_handle_unknown(png_ptr, info_ptr, length);
  181490. }
  181491. }
  181492. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181493. /* optional call to update the users info_ptr structure */
  181494. void PNGAPI
  181495. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  181496. {
  181497. png_debug(1, "in png_read_update_info\n");
  181498. if(png_ptr == NULL) return;
  181499. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  181500. png_read_start_row(png_ptr);
  181501. else
  181502. png_warning(png_ptr,
  181503. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  181504. png_read_transform_info(png_ptr, info_ptr);
  181505. }
  181506. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181507. /* Initialize palette, background, etc, after transformations
  181508. * are set, but before any reading takes place. This allows
  181509. * the user to obtain a gamma-corrected palette, for example.
  181510. * If the user doesn't call this, we will do it ourselves.
  181511. */
  181512. void PNGAPI
  181513. png_start_read_image(png_structp png_ptr)
  181514. {
  181515. png_debug(1, "in png_start_read_image\n");
  181516. if(png_ptr == NULL) return;
  181517. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  181518. png_read_start_row(png_ptr);
  181519. }
  181520. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181521. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181522. void PNGAPI
  181523. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  181524. {
  181525. #ifdef PNG_USE_LOCAL_ARRAYS
  181526. PNG_CONST PNG_IDAT;
  181527. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  181528. 0xff};
  181529. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  181530. #endif
  181531. int ret;
  181532. if(png_ptr == NULL) return;
  181533. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  181534. png_ptr->row_number, png_ptr->pass);
  181535. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  181536. png_read_start_row(png_ptr);
  181537. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  181538. {
  181539. /* check for transforms that have been set but were defined out */
  181540. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  181541. if (png_ptr->transformations & PNG_INVERT_MONO)
  181542. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  181543. #endif
  181544. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  181545. if (png_ptr->transformations & PNG_FILLER)
  181546. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  181547. #endif
  181548. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  181549. if (png_ptr->transformations & PNG_PACKSWAP)
  181550. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  181551. #endif
  181552. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  181553. if (png_ptr->transformations & PNG_PACK)
  181554. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  181555. #endif
  181556. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  181557. if (png_ptr->transformations & PNG_SHIFT)
  181558. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  181559. #endif
  181560. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  181561. if (png_ptr->transformations & PNG_BGR)
  181562. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  181563. #endif
  181564. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  181565. if (png_ptr->transformations & PNG_SWAP_BYTES)
  181566. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  181567. #endif
  181568. }
  181569. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  181570. /* if interlaced and we do not need a new row, combine row and return */
  181571. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  181572. {
  181573. switch (png_ptr->pass)
  181574. {
  181575. case 0:
  181576. if (png_ptr->row_number & 0x07)
  181577. {
  181578. if (dsp_row != NULL)
  181579. png_combine_row(png_ptr, dsp_row,
  181580. png_pass_dsp_mask[png_ptr->pass]);
  181581. png_read_finish_row(png_ptr);
  181582. return;
  181583. }
  181584. break;
  181585. case 1:
  181586. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  181587. {
  181588. if (dsp_row != NULL)
  181589. png_combine_row(png_ptr, dsp_row,
  181590. png_pass_dsp_mask[png_ptr->pass]);
  181591. png_read_finish_row(png_ptr);
  181592. return;
  181593. }
  181594. break;
  181595. case 2:
  181596. if ((png_ptr->row_number & 0x07) != 4)
  181597. {
  181598. if (dsp_row != NULL && (png_ptr->row_number & 4))
  181599. png_combine_row(png_ptr, dsp_row,
  181600. png_pass_dsp_mask[png_ptr->pass]);
  181601. png_read_finish_row(png_ptr);
  181602. return;
  181603. }
  181604. break;
  181605. case 3:
  181606. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  181607. {
  181608. if (dsp_row != NULL)
  181609. png_combine_row(png_ptr, dsp_row,
  181610. png_pass_dsp_mask[png_ptr->pass]);
  181611. png_read_finish_row(png_ptr);
  181612. return;
  181613. }
  181614. break;
  181615. case 4:
  181616. if ((png_ptr->row_number & 3) != 2)
  181617. {
  181618. if (dsp_row != NULL && (png_ptr->row_number & 2))
  181619. png_combine_row(png_ptr, dsp_row,
  181620. png_pass_dsp_mask[png_ptr->pass]);
  181621. png_read_finish_row(png_ptr);
  181622. return;
  181623. }
  181624. break;
  181625. case 5:
  181626. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  181627. {
  181628. if (dsp_row != NULL)
  181629. png_combine_row(png_ptr, dsp_row,
  181630. png_pass_dsp_mask[png_ptr->pass]);
  181631. png_read_finish_row(png_ptr);
  181632. return;
  181633. }
  181634. break;
  181635. case 6:
  181636. if (!(png_ptr->row_number & 1))
  181637. {
  181638. png_read_finish_row(png_ptr);
  181639. return;
  181640. }
  181641. break;
  181642. }
  181643. }
  181644. #endif
  181645. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  181646. png_error(png_ptr, "Invalid attempt to read row data");
  181647. png_ptr->zstream.next_out = png_ptr->row_buf;
  181648. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  181649. do
  181650. {
  181651. if (!(png_ptr->zstream.avail_in))
  181652. {
  181653. while (!png_ptr->idat_size)
  181654. {
  181655. png_byte chunk_length[4];
  181656. png_crc_finish(png_ptr, 0);
  181657. png_read_data(png_ptr, chunk_length, 4);
  181658. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  181659. png_reset_crc(png_ptr);
  181660. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  181661. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181662. png_error(png_ptr, "Not enough image data");
  181663. }
  181664. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  181665. png_ptr->zstream.next_in = png_ptr->zbuf;
  181666. if (png_ptr->zbuf_size > png_ptr->idat_size)
  181667. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  181668. png_crc_read(png_ptr, png_ptr->zbuf,
  181669. (png_size_t)png_ptr->zstream.avail_in);
  181670. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  181671. }
  181672. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  181673. if (ret == Z_STREAM_END)
  181674. {
  181675. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  181676. png_ptr->idat_size)
  181677. png_error(png_ptr, "Extra compressed data");
  181678. png_ptr->mode |= PNG_AFTER_IDAT;
  181679. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  181680. break;
  181681. }
  181682. if (ret != Z_OK)
  181683. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  181684. "Decompression error");
  181685. } while (png_ptr->zstream.avail_out);
  181686. png_ptr->row_info.color_type = png_ptr->color_type;
  181687. png_ptr->row_info.width = png_ptr->iwidth;
  181688. png_ptr->row_info.channels = png_ptr->channels;
  181689. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  181690. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  181691. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  181692. png_ptr->row_info.width);
  181693. if(png_ptr->row_buf[0])
  181694. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  181695. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  181696. (int)(png_ptr->row_buf[0]));
  181697. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  181698. png_ptr->rowbytes + 1);
  181699. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  181700. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  181701. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  181702. {
  181703. /* Intrapixel differencing */
  181704. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  181705. }
  181706. #endif
  181707. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  181708. png_do_read_transformations(png_ptr);
  181709. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  181710. /* blow up interlaced rows to full size */
  181711. if (png_ptr->interlaced &&
  181712. (png_ptr->transformations & PNG_INTERLACE))
  181713. {
  181714. if (png_ptr->pass < 6)
  181715. /* old interface (pre-1.0.9):
  181716. png_do_read_interlace(&(png_ptr->row_info),
  181717. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  181718. */
  181719. png_do_read_interlace(png_ptr);
  181720. if (dsp_row != NULL)
  181721. png_combine_row(png_ptr, dsp_row,
  181722. png_pass_dsp_mask[png_ptr->pass]);
  181723. if (row != NULL)
  181724. png_combine_row(png_ptr, row,
  181725. png_pass_mask[png_ptr->pass]);
  181726. }
  181727. else
  181728. #endif
  181729. {
  181730. if (row != NULL)
  181731. png_combine_row(png_ptr, row, 0xff);
  181732. if (dsp_row != NULL)
  181733. png_combine_row(png_ptr, dsp_row, 0xff);
  181734. }
  181735. png_read_finish_row(png_ptr);
  181736. if (png_ptr->read_row_fn != NULL)
  181737. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  181738. }
  181739. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181740. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181741. /* Read one or more rows of image data. If the image is interlaced,
  181742. * and png_set_interlace_handling() has been called, the rows need to
  181743. * contain the contents of the rows from the previous pass. If the
  181744. * image has alpha or transparency, and png_handle_alpha()[*] has been
  181745. * called, the rows contents must be initialized to the contents of the
  181746. * screen.
  181747. *
  181748. * "row" holds the actual image, and pixels are placed in it
  181749. * as they arrive. If the image is displayed after each pass, it will
  181750. * appear to "sparkle" in. "display_row" can be used to display a
  181751. * "chunky" progressive image, with finer detail added as it becomes
  181752. * available. If you do not want this "chunky" display, you may pass
  181753. * NULL for display_row. If you do not want the sparkle display, and
  181754. * you have not called png_handle_alpha(), you may pass NULL for rows.
  181755. * If you have called png_handle_alpha(), and the image has either an
  181756. * alpha channel or a transparency chunk, you must provide a buffer for
  181757. * rows. In this case, you do not have to provide a display_row buffer
  181758. * also, but you may. If the image is not interlaced, or if you have
  181759. * not called png_set_interlace_handling(), the display_row buffer will
  181760. * be ignored, so pass NULL to it.
  181761. *
  181762. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  181763. */
  181764. void PNGAPI
  181765. png_read_rows(png_structp png_ptr, png_bytepp row,
  181766. png_bytepp display_row, png_uint_32 num_rows)
  181767. {
  181768. png_uint_32 i;
  181769. png_bytepp rp;
  181770. png_bytepp dp;
  181771. png_debug(1, "in png_read_rows\n");
  181772. if(png_ptr == NULL) return;
  181773. rp = row;
  181774. dp = display_row;
  181775. if (rp != NULL && dp != NULL)
  181776. for (i = 0; i < num_rows; i++)
  181777. {
  181778. png_bytep rptr = *rp++;
  181779. png_bytep dptr = *dp++;
  181780. png_read_row(png_ptr, rptr, dptr);
  181781. }
  181782. else if(rp != NULL)
  181783. for (i = 0; i < num_rows; i++)
  181784. {
  181785. png_bytep rptr = *rp;
  181786. png_read_row(png_ptr, rptr, png_bytep_NULL);
  181787. rp++;
  181788. }
  181789. else if(dp != NULL)
  181790. for (i = 0; i < num_rows; i++)
  181791. {
  181792. png_bytep dptr = *dp;
  181793. png_read_row(png_ptr, png_bytep_NULL, dptr);
  181794. dp++;
  181795. }
  181796. }
  181797. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181798. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181799. /* Read the entire image. If the image has an alpha channel or a tRNS
  181800. * chunk, and you have called png_handle_alpha()[*], you will need to
  181801. * initialize the image to the current image that PNG will be overlaying.
  181802. * We set the num_rows again here, in case it was incorrectly set in
  181803. * png_read_start_row() by a call to png_read_update_info() or
  181804. * png_start_read_image() if png_set_interlace_handling() wasn't called
  181805. * prior to either of these functions like it should have been. You can
  181806. * only call this function once. If you desire to have an image for
  181807. * each pass of a interlaced image, use png_read_rows() instead.
  181808. *
  181809. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  181810. */
  181811. void PNGAPI
  181812. png_read_image(png_structp png_ptr, png_bytepp image)
  181813. {
  181814. png_uint_32 i,image_height;
  181815. int pass, j;
  181816. png_bytepp rp;
  181817. png_debug(1, "in png_read_image\n");
  181818. if(png_ptr == NULL) return;
  181819. #ifdef PNG_READ_INTERLACING_SUPPORTED
  181820. pass = png_set_interlace_handling(png_ptr);
  181821. #else
  181822. if (png_ptr->interlaced)
  181823. png_error(png_ptr,
  181824. "Cannot read interlaced image -- interlace handler disabled.");
  181825. pass = 1;
  181826. #endif
  181827. image_height=png_ptr->height;
  181828. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  181829. for (j = 0; j < pass; j++)
  181830. {
  181831. rp = image;
  181832. for (i = 0; i < image_height; i++)
  181833. {
  181834. png_read_row(png_ptr, *rp, png_bytep_NULL);
  181835. rp++;
  181836. }
  181837. }
  181838. }
  181839. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181840. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181841. /* Read the end of the PNG file. Will not read past the end of the
  181842. * file, will verify the end is accurate, and will read any comments
  181843. * or time information at the end of the file, if info is not NULL.
  181844. */
  181845. void PNGAPI
  181846. png_read_end(png_structp png_ptr, png_infop info_ptr)
  181847. {
  181848. png_byte chunk_length[4];
  181849. png_uint_32 length;
  181850. png_debug(1, "in png_read_end\n");
  181851. if(png_ptr == NULL) return;
  181852. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  181853. do
  181854. {
  181855. #ifdef PNG_USE_LOCAL_ARRAYS
  181856. PNG_CONST PNG_IHDR;
  181857. PNG_CONST PNG_IDAT;
  181858. PNG_CONST PNG_IEND;
  181859. PNG_CONST PNG_PLTE;
  181860. #if defined(PNG_READ_bKGD_SUPPORTED)
  181861. PNG_CONST PNG_bKGD;
  181862. #endif
  181863. #if defined(PNG_READ_cHRM_SUPPORTED)
  181864. PNG_CONST PNG_cHRM;
  181865. #endif
  181866. #if defined(PNG_READ_gAMA_SUPPORTED)
  181867. PNG_CONST PNG_gAMA;
  181868. #endif
  181869. #if defined(PNG_READ_hIST_SUPPORTED)
  181870. PNG_CONST PNG_hIST;
  181871. #endif
  181872. #if defined(PNG_READ_iCCP_SUPPORTED)
  181873. PNG_CONST PNG_iCCP;
  181874. #endif
  181875. #if defined(PNG_READ_iTXt_SUPPORTED)
  181876. PNG_CONST PNG_iTXt;
  181877. #endif
  181878. #if defined(PNG_READ_oFFs_SUPPORTED)
  181879. PNG_CONST PNG_oFFs;
  181880. #endif
  181881. #if defined(PNG_READ_pCAL_SUPPORTED)
  181882. PNG_CONST PNG_pCAL;
  181883. #endif
  181884. #if defined(PNG_READ_pHYs_SUPPORTED)
  181885. PNG_CONST PNG_pHYs;
  181886. #endif
  181887. #if defined(PNG_READ_sBIT_SUPPORTED)
  181888. PNG_CONST PNG_sBIT;
  181889. #endif
  181890. #if defined(PNG_READ_sCAL_SUPPORTED)
  181891. PNG_CONST PNG_sCAL;
  181892. #endif
  181893. #if defined(PNG_READ_sPLT_SUPPORTED)
  181894. PNG_CONST PNG_sPLT;
  181895. #endif
  181896. #if defined(PNG_READ_sRGB_SUPPORTED)
  181897. PNG_CONST PNG_sRGB;
  181898. #endif
  181899. #if defined(PNG_READ_tEXt_SUPPORTED)
  181900. PNG_CONST PNG_tEXt;
  181901. #endif
  181902. #if defined(PNG_READ_tIME_SUPPORTED)
  181903. PNG_CONST PNG_tIME;
  181904. #endif
  181905. #if defined(PNG_READ_tRNS_SUPPORTED)
  181906. PNG_CONST PNG_tRNS;
  181907. #endif
  181908. #if defined(PNG_READ_zTXt_SUPPORTED)
  181909. PNG_CONST PNG_zTXt;
  181910. #endif
  181911. #endif /* PNG_USE_LOCAL_ARRAYS */
  181912. png_read_data(png_ptr, chunk_length, 4);
  181913. length = png_get_uint_31(png_ptr,chunk_length);
  181914. png_reset_crc(png_ptr);
  181915. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  181916. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  181917. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  181918. png_handle_IHDR(png_ptr, info_ptr, length);
  181919. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  181920. png_handle_IEND(png_ptr, info_ptr, length);
  181921. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181922. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  181923. {
  181924. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181925. {
  181926. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  181927. png_error(png_ptr, "Too many IDAT's found");
  181928. }
  181929. png_handle_unknown(png_ptr, info_ptr, length);
  181930. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181931. png_ptr->mode |= PNG_HAVE_PLTE;
  181932. }
  181933. #endif
  181934. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181935. {
  181936. /* Zero length IDATs are legal after the last IDAT has been
  181937. * read, but not after other chunks have been read.
  181938. */
  181939. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  181940. png_error(png_ptr, "Too many IDAT's found");
  181941. png_crc_finish(png_ptr, length);
  181942. }
  181943. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181944. png_handle_PLTE(png_ptr, info_ptr, length);
  181945. #if defined(PNG_READ_bKGD_SUPPORTED)
  181946. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  181947. png_handle_bKGD(png_ptr, info_ptr, length);
  181948. #endif
  181949. #if defined(PNG_READ_cHRM_SUPPORTED)
  181950. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  181951. png_handle_cHRM(png_ptr, info_ptr, length);
  181952. #endif
  181953. #if defined(PNG_READ_gAMA_SUPPORTED)
  181954. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  181955. png_handle_gAMA(png_ptr, info_ptr, length);
  181956. #endif
  181957. #if defined(PNG_READ_hIST_SUPPORTED)
  181958. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  181959. png_handle_hIST(png_ptr, info_ptr, length);
  181960. #endif
  181961. #if defined(PNG_READ_oFFs_SUPPORTED)
  181962. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  181963. png_handle_oFFs(png_ptr, info_ptr, length);
  181964. #endif
  181965. #if defined(PNG_READ_pCAL_SUPPORTED)
  181966. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  181967. png_handle_pCAL(png_ptr, info_ptr, length);
  181968. #endif
  181969. #if defined(PNG_READ_sCAL_SUPPORTED)
  181970. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  181971. png_handle_sCAL(png_ptr, info_ptr, length);
  181972. #endif
  181973. #if defined(PNG_READ_pHYs_SUPPORTED)
  181974. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  181975. png_handle_pHYs(png_ptr, info_ptr, length);
  181976. #endif
  181977. #if defined(PNG_READ_sBIT_SUPPORTED)
  181978. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  181979. png_handle_sBIT(png_ptr, info_ptr, length);
  181980. #endif
  181981. #if defined(PNG_READ_sRGB_SUPPORTED)
  181982. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  181983. png_handle_sRGB(png_ptr, info_ptr, length);
  181984. #endif
  181985. #if defined(PNG_READ_iCCP_SUPPORTED)
  181986. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  181987. png_handle_iCCP(png_ptr, info_ptr, length);
  181988. #endif
  181989. #if defined(PNG_READ_sPLT_SUPPORTED)
  181990. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  181991. png_handle_sPLT(png_ptr, info_ptr, length);
  181992. #endif
  181993. #if defined(PNG_READ_tEXt_SUPPORTED)
  181994. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  181995. png_handle_tEXt(png_ptr, info_ptr, length);
  181996. #endif
  181997. #if defined(PNG_READ_tIME_SUPPORTED)
  181998. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  181999. png_handle_tIME(png_ptr, info_ptr, length);
  182000. #endif
  182001. #if defined(PNG_READ_tRNS_SUPPORTED)
  182002. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  182003. png_handle_tRNS(png_ptr, info_ptr, length);
  182004. #endif
  182005. #if defined(PNG_READ_zTXt_SUPPORTED)
  182006. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  182007. png_handle_zTXt(png_ptr, info_ptr, length);
  182008. #endif
  182009. #if defined(PNG_READ_iTXt_SUPPORTED)
  182010. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  182011. png_handle_iTXt(png_ptr, info_ptr, length);
  182012. #endif
  182013. else
  182014. png_handle_unknown(png_ptr, info_ptr, length);
  182015. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  182016. }
  182017. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  182018. /* free all memory used by the read */
  182019. void PNGAPI
  182020. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  182021. png_infopp end_info_ptr_ptr)
  182022. {
  182023. png_structp png_ptr = NULL;
  182024. png_infop info_ptr = NULL, end_info_ptr = NULL;
  182025. #ifdef PNG_USER_MEM_SUPPORTED
  182026. png_free_ptr free_fn;
  182027. png_voidp mem_ptr;
  182028. #endif
  182029. png_debug(1, "in png_destroy_read_struct\n");
  182030. if (png_ptr_ptr != NULL)
  182031. png_ptr = *png_ptr_ptr;
  182032. if (info_ptr_ptr != NULL)
  182033. info_ptr = *info_ptr_ptr;
  182034. if (end_info_ptr_ptr != NULL)
  182035. end_info_ptr = *end_info_ptr_ptr;
  182036. #ifdef PNG_USER_MEM_SUPPORTED
  182037. free_fn = png_ptr->free_fn;
  182038. mem_ptr = png_ptr->mem_ptr;
  182039. #endif
  182040. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  182041. if (info_ptr != NULL)
  182042. {
  182043. #if defined(PNG_TEXT_SUPPORTED)
  182044. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  182045. #endif
  182046. #ifdef PNG_USER_MEM_SUPPORTED
  182047. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  182048. (png_voidp)mem_ptr);
  182049. #else
  182050. png_destroy_struct((png_voidp)info_ptr);
  182051. #endif
  182052. *info_ptr_ptr = NULL;
  182053. }
  182054. if (end_info_ptr != NULL)
  182055. {
  182056. #if defined(PNG_READ_TEXT_SUPPORTED)
  182057. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  182058. #endif
  182059. #ifdef PNG_USER_MEM_SUPPORTED
  182060. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  182061. (png_voidp)mem_ptr);
  182062. #else
  182063. png_destroy_struct((png_voidp)end_info_ptr);
  182064. #endif
  182065. *end_info_ptr_ptr = NULL;
  182066. }
  182067. if (png_ptr != NULL)
  182068. {
  182069. #ifdef PNG_USER_MEM_SUPPORTED
  182070. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  182071. (png_voidp)mem_ptr);
  182072. #else
  182073. png_destroy_struct((png_voidp)png_ptr);
  182074. #endif
  182075. *png_ptr_ptr = NULL;
  182076. }
  182077. }
  182078. /* free all memory used by the read (old method) */
  182079. void /* PRIVATE */
  182080. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  182081. {
  182082. #ifdef PNG_SETJMP_SUPPORTED
  182083. jmp_buf tmp_jmp;
  182084. #endif
  182085. png_error_ptr error_fn;
  182086. png_error_ptr warning_fn;
  182087. png_voidp error_ptr;
  182088. #ifdef PNG_USER_MEM_SUPPORTED
  182089. png_free_ptr free_fn;
  182090. #endif
  182091. png_debug(1, "in png_read_destroy\n");
  182092. if (info_ptr != NULL)
  182093. png_info_destroy(png_ptr, info_ptr);
  182094. if (end_info_ptr != NULL)
  182095. png_info_destroy(png_ptr, end_info_ptr);
  182096. png_free(png_ptr, png_ptr->zbuf);
  182097. png_free(png_ptr, png_ptr->big_row_buf);
  182098. png_free(png_ptr, png_ptr->prev_row);
  182099. #if defined(PNG_READ_DITHER_SUPPORTED)
  182100. png_free(png_ptr, png_ptr->palette_lookup);
  182101. png_free(png_ptr, png_ptr->dither_index);
  182102. #endif
  182103. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182104. png_free(png_ptr, png_ptr->gamma_table);
  182105. #endif
  182106. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182107. png_free(png_ptr, png_ptr->gamma_from_1);
  182108. png_free(png_ptr, png_ptr->gamma_to_1);
  182109. #endif
  182110. #ifdef PNG_FREE_ME_SUPPORTED
  182111. if (png_ptr->free_me & PNG_FREE_PLTE)
  182112. png_zfree(png_ptr, png_ptr->palette);
  182113. png_ptr->free_me &= ~PNG_FREE_PLTE;
  182114. #else
  182115. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  182116. png_zfree(png_ptr, png_ptr->palette);
  182117. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  182118. #endif
  182119. #if defined(PNG_tRNS_SUPPORTED) || \
  182120. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182121. #ifdef PNG_FREE_ME_SUPPORTED
  182122. if (png_ptr->free_me & PNG_FREE_TRNS)
  182123. png_free(png_ptr, png_ptr->trans);
  182124. png_ptr->free_me &= ~PNG_FREE_TRNS;
  182125. #else
  182126. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  182127. png_free(png_ptr, png_ptr->trans);
  182128. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  182129. #endif
  182130. #endif
  182131. #if defined(PNG_READ_hIST_SUPPORTED)
  182132. #ifdef PNG_FREE_ME_SUPPORTED
  182133. if (png_ptr->free_me & PNG_FREE_HIST)
  182134. png_free(png_ptr, png_ptr->hist);
  182135. png_ptr->free_me &= ~PNG_FREE_HIST;
  182136. #else
  182137. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  182138. png_free(png_ptr, png_ptr->hist);
  182139. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  182140. #endif
  182141. #endif
  182142. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182143. if (png_ptr->gamma_16_table != NULL)
  182144. {
  182145. int i;
  182146. int istop = (1 << (8 - png_ptr->gamma_shift));
  182147. for (i = 0; i < istop; i++)
  182148. {
  182149. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  182150. }
  182151. png_free(png_ptr, png_ptr->gamma_16_table);
  182152. }
  182153. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182154. if (png_ptr->gamma_16_from_1 != NULL)
  182155. {
  182156. int i;
  182157. int istop = (1 << (8 - png_ptr->gamma_shift));
  182158. for (i = 0; i < istop; i++)
  182159. {
  182160. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  182161. }
  182162. png_free(png_ptr, png_ptr->gamma_16_from_1);
  182163. }
  182164. if (png_ptr->gamma_16_to_1 != NULL)
  182165. {
  182166. int i;
  182167. int istop = (1 << (8 - png_ptr->gamma_shift));
  182168. for (i = 0; i < istop; i++)
  182169. {
  182170. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  182171. }
  182172. png_free(png_ptr, png_ptr->gamma_16_to_1);
  182173. }
  182174. #endif
  182175. #endif
  182176. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182177. png_free(png_ptr, png_ptr->time_buffer);
  182178. #endif
  182179. inflateEnd(&png_ptr->zstream);
  182180. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182181. png_free(png_ptr, png_ptr->save_buffer);
  182182. #endif
  182183. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182184. #ifdef PNG_TEXT_SUPPORTED
  182185. png_free(png_ptr, png_ptr->current_text);
  182186. #endif /* PNG_TEXT_SUPPORTED */
  182187. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182188. /* Save the important info out of the png_struct, in case it is
  182189. * being used again.
  182190. */
  182191. #ifdef PNG_SETJMP_SUPPORTED
  182192. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  182193. #endif
  182194. error_fn = png_ptr->error_fn;
  182195. warning_fn = png_ptr->warning_fn;
  182196. error_ptr = png_ptr->error_ptr;
  182197. #ifdef PNG_USER_MEM_SUPPORTED
  182198. free_fn = png_ptr->free_fn;
  182199. #endif
  182200. png_memset(png_ptr, 0, png_sizeof (png_struct));
  182201. png_ptr->error_fn = error_fn;
  182202. png_ptr->warning_fn = warning_fn;
  182203. png_ptr->error_ptr = error_ptr;
  182204. #ifdef PNG_USER_MEM_SUPPORTED
  182205. png_ptr->free_fn = free_fn;
  182206. #endif
  182207. #ifdef PNG_SETJMP_SUPPORTED
  182208. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  182209. #endif
  182210. }
  182211. void PNGAPI
  182212. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  182213. {
  182214. if(png_ptr == NULL) return;
  182215. png_ptr->read_row_fn = read_row_fn;
  182216. }
  182217. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182218. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182219. void PNGAPI
  182220. png_read_png(png_structp png_ptr, png_infop info_ptr,
  182221. int transforms,
  182222. voidp params)
  182223. {
  182224. int row;
  182225. if(png_ptr == NULL) return;
  182226. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  182227. /* invert the alpha channel from opacity to transparency
  182228. */
  182229. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  182230. png_set_invert_alpha(png_ptr);
  182231. #endif
  182232. /* png_read_info() gives us all of the information from the
  182233. * PNG file before the first IDAT (image data chunk).
  182234. */
  182235. png_read_info(png_ptr, info_ptr);
  182236. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  182237. png_error(png_ptr,"Image is too high to process with png_read_png()");
  182238. /* -------------- image transformations start here ------------------- */
  182239. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182240. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  182241. */
  182242. if (transforms & PNG_TRANSFORM_STRIP_16)
  182243. png_set_strip_16(png_ptr);
  182244. #endif
  182245. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182246. /* Strip alpha bytes from the input data without combining with
  182247. * the background (not recommended).
  182248. */
  182249. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  182250. png_set_strip_alpha(png_ptr);
  182251. #endif
  182252. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  182253. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  182254. * byte into separate bytes (useful for paletted and grayscale images).
  182255. */
  182256. if (transforms & PNG_TRANSFORM_PACKING)
  182257. png_set_packing(png_ptr);
  182258. #endif
  182259. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  182260. /* Change the order of packed pixels to least significant bit first
  182261. * (not useful if you are using png_set_packing).
  182262. */
  182263. if (transforms & PNG_TRANSFORM_PACKSWAP)
  182264. png_set_packswap(png_ptr);
  182265. #endif
  182266. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182267. /* Expand paletted colors into true RGB triplets
  182268. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  182269. * Expand paletted or RGB images with transparency to full alpha
  182270. * channels so the data will be available as RGBA quartets.
  182271. */
  182272. if (transforms & PNG_TRANSFORM_EXPAND)
  182273. if ((png_ptr->bit_depth < 8) ||
  182274. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  182275. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  182276. png_set_expand(png_ptr);
  182277. #endif
  182278. /* We don't handle background color or gamma transformation or dithering.
  182279. */
  182280. #if defined(PNG_READ_INVERT_SUPPORTED)
  182281. /* invert monochrome files to have 0 as white and 1 as black
  182282. */
  182283. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  182284. png_set_invert_mono(png_ptr);
  182285. #endif
  182286. #if defined(PNG_READ_SHIFT_SUPPORTED)
  182287. /* If you want to shift the pixel values from the range [0,255] or
  182288. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  182289. * colors were originally in:
  182290. */
  182291. if ((transforms & PNG_TRANSFORM_SHIFT)
  182292. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  182293. {
  182294. png_color_8p sig_bit;
  182295. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  182296. png_set_shift(png_ptr, sig_bit);
  182297. }
  182298. #endif
  182299. #if defined(PNG_READ_BGR_SUPPORTED)
  182300. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  182301. */
  182302. if (transforms & PNG_TRANSFORM_BGR)
  182303. png_set_bgr(png_ptr);
  182304. #endif
  182305. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  182306. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  182307. */
  182308. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  182309. png_set_swap_alpha(png_ptr);
  182310. #endif
  182311. #if defined(PNG_READ_SWAP_SUPPORTED)
  182312. /* swap bytes of 16 bit files to least significant byte first
  182313. */
  182314. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  182315. png_set_swap(png_ptr);
  182316. #endif
  182317. /* We don't handle adding filler bytes */
  182318. /* Optional call to gamma correct and add the background to the palette
  182319. * and update info structure. REQUIRED if you are expecting libpng to
  182320. * update the palette for you (i.e., you selected such a transform above).
  182321. */
  182322. png_read_update_info(png_ptr, info_ptr);
  182323. /* -------------- image transformations end here ------------------- */
  182324. #ifdef PNG_FREE_ME_SUPPORTED
  182325. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  182326. #endif
  182327. if(info_ptr->row_pointers == NULL)
  182328. {
  182329. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  182330. info_ptr->height * png_sizeof(png_bytep));
  182331. #ifdef PNG_FREE_ME_SUPPORTED
  182332. info_ptr->free_me |= PNG_FREE_ROWS;
  182333. #endif
  182334. for (row = 0; row < (int)info_ptr->height; row++)
  182335. {
  182336. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  182337. png_get_rowbytes(png_ptr, info_ptr));
  182338. }
  182339. }
  182340. png_read_image(png_ptr, info_ptr->row_pointers);
  182341. info_ptr->valid |= PNG_INFO_IDAT;
  182342. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  182343. png_read_end(png_ptr, info_ptr);
  182344. transforms = transforms; /* quiet compiler warnings */
  182345. params = params;
  182346. }
  182347. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  182348. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  182349. #endif /* PNG_READ_SUPPORTED */
  182350. /********* End of inlined file: pngread.c *********/
  182351. /********* Start of inlined file: pngpread.c *********/
  182352. /* pngpread.c - read a png file in push mode
  182353. *
  182354. * Last changed in libpng 1.2.21 October 4, 2007
  182355. * For conditions of distribution and use, see copyright notice in png.h
  182356. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  182357. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182358. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182359. */
  182360. #define PNG_INTERNAL
  182361. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182362. /* push model modes */
  182363. #define PNG_READ_SIG_MODE 0
  182364. #define PNG_READ_CHUNK_MODE 1
  182365. #define PNG_READ_IDAT_MODE 2
  182366. #define PNG_SKIP_MODE 3
  182367. #define PNG_READ_tEXt_MODE 4
  182368. #define PNG_READ_zTXt_MODE 5
  182369. #define PNG_READ_DONE_MODE 6
  182370. #define PNG_READ_iTXt_MODE 7
  182371. #define PNG_ERROR_MODE 8
  182372. void PNGAPI
  182373. png_process_data(png_structp png_ptr, png_infop info_ptr,
  182374. png_bytep buffer, png_size_t buffer_size)
  182375. {
  182376. if(png_ptr == NULL) return;
  182377. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  182378. while (png_ptr->buffer_size)
  182379. {
  182380. png_process_some_data(png_ptr, info_ptr);
  182381. }
  182382. }
  182383. /* What we do with the incoming data depends on what we were previously
  182384. * doing before we ran out of data...
  182385. */
  182386. void /* PRIVATE */
  182387. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  182388. {
  182389. if(png_ptr == NULL) return;
  182390. switch (png_ptr->process_mode)
  182391. {
  182392. case PNG_READ_SIG_MODE:
  182393. {
  182394. png_push_read_sig(png_ptr, info_ptr);
  182395. break;
  182396. }
  182397. case PNG_READ_CHUNK_MODE:
  182398. {
  182399. png_push_read_chunk(png_ptr, info_ptr);
  182400. break;
  182401. }
  182402. case PNG_READ_IDAT_MODE:
  182403. {
  182404. png_push_read_IDAT(png_ptr);
  182405. break;
  182406. }
  182407. #if defined(PNG_READ_tEXt_SUPPORTED)
  182408. case PNG_READ_tEXt_MODE:
  182409. {
  182410. png_push_read_tEXt(png_ptr, info_ptr);
  182411. break;
  182412. }
  182413. #endif
  182414. #if defined(PNG_READ_zTXt_SUPPORTED)
  182415. case PNG_READ_zTXt_MODE:
  182416. {
  182417. png_push_read_zTXt(png_ptr, info_ptr);
  182418. break;
  182419. }
  182420. #endif
  182421. #if defined(PNG_READ_iTXt_SUPPORTED)
  182422. case PNG_READ_iTXt_MODE:
  182423. {
  182424. png_push_read_iTXt(png_ptr, info_ptr);
  182425. break;
  182426. }
  182427. #endif
  182428. case PNG_SKIP_MODE:
  182429. {
  182430. png_push_crc_finish(png_ptr);
  182431. break;
  182432. }
  182433. default:
  182434. {
  182435. png_ptr->buffer_size = 0;
  182436. break;
  182437. }
  182438. }
  182439. }
  182440. /* Read any remaining signature bytes from the stream and compare them with
  182441. * the correct PNG signature. It is possible that this routine is called
  182442. * with bytes already read from the signature, either because they have been
  182443. * checked by the calling application, or because of multiple calls to this
  182444. * routine.
  182445. */
  182446. void /* PRIVATE */
  182447. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  182448. {
  182449. png_size_t num_checked = png_ptr->sig_bytes,
  182450. num_to_check = 8 - num_checked;
  182451. if (png_ptr->buffer_size < num_to_check)
  182452. {
  182453. num_to_check = png_ptr->buffer_size;
  182454. }
  182455. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  182456. num_to_check);
  182457. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  182458. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  182459. {
  182460. if (num_checked < 4 &&
  182461. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  182462. png_error(png_ptr, "Not a PNG file");
  182463. else
  182464. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  182465. }
  182466. else
  182467. {
  182468. if (png_ptr->sig_bytes >= 8)
  182469. {
  182470. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  182471. }
  182472. }
  182473. }
  182474. void /* PRIVATE */
  182475. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  182476. {
  182477. #ifdef PNG_USE_LOCAL_ARRAYS
  182478. PNG_CONST PNG_IHDR;
  182479. PNG_CONST PNG_IDAT;
  182480. PNG_CONST PNG_IEND;
  182481. PNG_CONST PNG_PLTE;
  182482. #if defined(PNG_READ_bKGD_SUPPORTED)
  182483. PNG_CONST PNG_bKGD;
  182484. #endif
  182485. #if defined(PNG_READ_cHRM_SUPPORTED)
  182486. PNG_CONST PNG_cHRM;
  182487. #endif
  182488. #if defined(PNG_READ_gAMA_SUPPORTED)
  182489. PNG_CONST PNG_gAMA;
  182490. #endif
  182491. #if defined(PNG_READ_hIST_SUPPORTED)
  182492. PNG_CONST PNG_hIST;
  182493. #endif
  182494. #if defined(PNG_READ_iCCP_SUPPORTED)
  182495. PNG_CONST PNG_iCCP;
  182496. #endif
  182497. #if defined(PNG_READ_iTXt_SUPPORTED)
  182498. PNG_CONST PNG_iTXt;
  182499. #endif
  182500. #if defined(PNG_READ_oFFs_SUPPORTED)
  182501. PNG_CONST PNG_oFFs;
  182502. #endif
  182503. #if defined(PNG_READ_pCAL_SUPPORTED)
  182504. PNG_CONST PNG_pCAL;
  182505. #endif
  182506. #if defined(PNG_READ_pHYs_SUPPORTED)
  182507. PNG_CONST PNG_pHYs;
  182508. #endif
  182509. #if defined(PNG_READ_sBIT_SUPPORTED)
  182510. PNG_CONST PNG_sBIT;
  182511. #endif
  182512. #if defined(PNG_READ_sCAL_SUPPORTED)
  182513. PNG_CONST PNG_sCAL;
  182514. #endif
  182515. #if defined(PNG_READ_sRGB_SUPPORTED)
  182516. PNG_CONST PNG_sRGB;
  182517. #endif
  182518. #if defined(PNG_READ_sPLT_SUPPORTED)
  182519. PNG_CONST PNG_sPLT;
  182520. #endif
  182521. #if defined(PNG_READ_tEXt_SUPPORTED)
  182522. PNG_CONST PNG_tEXt;
  182523. #endif
  182524. #if defined(PNG_READ_tIME_SUPPORTED)
  182525. PNG_CONST PNG_tIME;
  182526. #endif
  182527. #if defined(PNG_READ_tRNS_SUPPORTED)
  182528. PNG_CONST PNG_tRNS;
  182529. #endif
  182530. #if defined(PNG_READ_zTXt_SUPPORTED)
  182531. PNG_CONST PNG_zTXt;
  182532. #endif
  182533. #endif /* PNG_USE_LOCAL_ARRAYS */
  182534. /* First we make sure we have enough data for the 4 byte chunk name
  182535. * and the 4 byte chunk length before proceeding with decoding the
  182536. * chunk data. To fully decode each of these chunks, we also make
  182537. * sure we have enough data in the buffer for the 4 byte CRC at the
  182538. * end of every chunk (except IDAT, which is handled separately).
  182539. */
  182540. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  182541. {
  182542. png_byte chunk_length[4];
  182543. if (png_ptr->buffer_size < 8)
  182544. {
  182545. png_push_save_buffer(png_ptr);
  182546. return;
  182547. }
  182548. png_push_fill_buffer(png_ptr, chunk_length, 4);
  182549. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  182550. png_reset_crc(png_ptr);
  182551. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  182552. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  182553. }
  182554. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182555. if(png_ptr->mode & PNG_AFTER_IDAT)
  182556. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  182557. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  182558. {
  182559. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182560. {
  182561. png_push_save_buffer(png_ptr);
  182562. return;
  182563. }
  182564. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  182565. }
  182566. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  182567. {
  182568. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182569. {
  182570. png_push_save_buffer(png_ptr);
  182571. return;
  182572. }
  182573. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  182574. png_ptr->process_mode = PNG_READ_DONE_MODE;
  182575. png_push_have_end(png_ptr, info_ptr);
  182576. }
  182577. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182578. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  182579. {
  182580. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182581. {
  182582. png_push_save_buffer(png_ptr);
  182583. return;
  182584. }
  182585. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182586. png_ptr->mode |= PNG_HAVE_IDAT;
  182587. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  182588. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182589. png_ptr->mode |= PNG_HAVE_PLTE;
  182590. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182591. {
  182592. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  182593. png_error(png_ptr, "Missing IHDR before IDAT");
  182594. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  182595. !(png_ptr->mode & PNG_HAVE_PLTE))
  182596. png_error(png_ptr, "Missing PLTE before IDAT");
  182597. }
  182598. }
  182599. #endif
  182600. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182601. {
  182602. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182603. {
  182604. png_push_save_buffer(png_ptr);
  182605. return;
  182606. }
  182607. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  182608. }
  182609. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182610. {
  182611. /* If we reach an IDAT chunk, this means we have read all of the
  182612. * header chunks, and we can start reading the image (or if this
  182613. * is called after the image has been read - we have an error).
  182614. */
  182615. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  182616. png_error(png_ptr, "Missing IHDR before IDAT");
  182617. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  182618. !(png_ptr->mode & PNG_HAVE_PLTE))
  182619. png_error(png_ptr, "Missing PLTE before IDAT");
  182620. if (png_ptr->mode & PNG_HAVE_IDAT)
  182621. {
  182622. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  182623. if (png_ptr->push_length == 0)
  182624. return;
  182625. if (png_ptr->mode & PNG_AFTER_IDAT)
  182626. png_error(png_ptr, "Too many IDAT's found");
  182627. }
  182628. png_ptr->idat_size = png_ptr->push_length;
  182629. png_ptr->mode |= PNG_HAVE_IDAT;
  182630. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  182631. png_push_have_info(png_ptr, info_ptr);
  182632. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  182633. png_ptr->zstream.next_out = png_ptr->row_buf;
  182634. return;
  182635. }
  182636. #if defined(PNG_READ_gAMA_SUPPORTED)
  182637. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  182638. {
  182639. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182640. {
  182641. png_push_save_buffer(png_ptr);
  182642. return;
  182643. }
  182644. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  182645. }
  182646. #endif
  182647. #if defined(PNG_READ_sBIT_SUPPORTED)
  182648. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  182649. {
  182650. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182651. {
  182652. png_push_save_buffer(png_ptr);
  182653. return;
  182654. }
  182655. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  182656. }
  182657. #endif
  182658. #if defined(PNG_READ_cHRM_SUPPORTED)
  182659. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  182660. {
  182661. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182662. {
  182663. png_push_save_buffer(png_ptr);
  182664. return;
  182665. }
  182666. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  182667. }
  182668. #endif
  182669. #if defined(PNG_READ_sRGB_SUPPORTED)
  182670. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  182671. {
  182672. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182673. {
  182674. png_push_save_buffer(png_ptr);
  182675. return;
  182676. }
  182677. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  182678. }
  182679. #endif
  182680. #if defined(PNG_READ_iCCP_SUPPORTED)
  182681. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  182682. {
  182683. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182684. {
  182685. png_push_save_buffer(png_ptr);
  182686. return;
  182687. }
  182688. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  182689. }
  182690. #endif
  182691. #if defined(PNG_READ_sPLT_SUPPORTED)
  182692. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  182693. {
  182694. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182695. {
  182696. png_push_save_buffer(png_ptr);
  182697. return;
  182698. }
  182699. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  182700. }
  182701. #endif
  182702. #if defined(PNG_READ_tRNS_SUPPORTED)
  182703. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  182704. {
  182705. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182706. {
  182707. png_push_save_buffer(png_ptr);
  182708. return;
  182709. }
  182710. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  182711. }
  182712. #endif
  182713. #if defined(PNG_READ_bKGD_SUPPORTED)
  182714. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  182715. {
  182716. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182717. {
  182718. png_push_save_buffer(png_ptr);
  182719. return;
  182720. }
  182721. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  182722. }
  182723. #endif
  182724. #if defined(PNG_READ_hIST_SUPPORTED)
  182725. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  182726. {
  182727. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182728. {
  182729. png_push_save_buffer(png_ptr);
  182730. return;
  182731. }
  182732. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  182733. }
  182734. #endif
  182735. #if defined(PNG_READ_pHYs_SUPPORTED)
  182736. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  182737. {
  182738. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182739. {
  182740. png_push_save_buffer(png_ptr);
  182741. return;
  182742. }
  182743. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  182744. }
  182745. #endif
  182746. #if defined(PNG_READ_oFFs_SUPPORTED)
  182747. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  182748. {
  182749. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182750. {
  182751. png_push_save_buffer(png_ptr);
  182752. return;
  182753. }
  182754. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  182755. }
  182756. #endif
  182757. #if defined(PNG_READ_pCAL_SUPPORTED)
  182758. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  182759. {
  182760. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182761. {
  182762. png_push_save_buffer(png_ptr);
  182763. return;
  182764. }
  182765. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  182766. }
  182767. #endif
  182768. #if defined(PNG_READ_sCAL_SUPPORTED)
  182769. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  182770. {
  182771. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182772. {
  182773. png_push_save_buffer(png_ptr);
  182774. return;
  182775. }
  182776. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  182777. }
  182778. #endif
  182779. #if defined(PNG_READ_tIME_SUPPORTED)
  182780. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  182781. {
  182782. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182783. {
  182784. png_push_save_buffer(png_ptr);
  182785. return;
  182786. }
  182787. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  182788. }
  182789. #endif
  182790. #if defined(PNG_READ_tEXt_SUPPORTED)
  182791. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  182792. {
  182793. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182794. {
  182795. png_push_save_buffer(png_ptr);
  182796. return;
  182797. }
  182798. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  182799. }
  182800. #endif
  182801. #if defined(PNG_READ_zTXt_SUPPORTED)
  182802. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  182803. {
  182804. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182805. {
  182806. png_push_save_buffer(png_ptr);
  182807. return;
  182808. }
  182809. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  182810. }
  182811. #endif
  182812. #if defined(PNG_READ_iTXt_SUPPORTED)
  182813. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  182814. {
  182815. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182816. {
  182817. png_push_save_buffer(png_ptr);
  182818. return;
  182819. }
  182820. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  182821. }
  182822. #endif
  182823. else
  182824. {
  182825. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182826. {
  182827. png_push_save_buffer(png_ptr);
  182828. return;
  182829. }
  182830. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  182831. }
  182832. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  182833. }
  182834. void /* PRIVATE */
  182835. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  182836. {
  182837. png_ptr->process_mode = PNG_SKIP_MODE;
  182838. png_ptr->skip_length = skip;
  182839. }
  182840. void /* PRIVATE */
  182841. png_push_crc_finish(png_structp png_ptr)
  182842. {
  182843. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  182844. {
  182845. png_size_t save_size;
  182846. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  182847. save_size = (png_size_t)png_ptr->skip_length;
  182848. else
  182849. save_size = png_ptr->save_buffer_size;
  182850. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  182851. png_ptr->skip_length -= save_size;
  182852. png_ptr->buffer_size -= save_size;
  182853. png_ptr->save_buffer_size -= save_size;
  182854. png_ptr->save_buffer_ptr += save_size;
  182855. }
  182856. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  182857. {
  182858. png_size_t save_size;
  182859. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  182860. save_size = (png_size_t)png_ptr->skip_length;
  182861. else
  182862. save_size = png_ptr->current_buffer_size;
  182863. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  182864. png_ptr->skip_length -= save_size;
  182865. png_ptr->buffer_size -= save_size;
  182866. png_ptr->current_buffer_size -= save_size;
  182867. png_ptr->current_buffer_ptr += save_size;
  182868. }
  182869. if (!png_ptr->skip_length)
  182870. {
  182871. if (png_ptr->buffer_size < 4)
  182872. {
  182873. png_push_save_buffer(png_ptr);
  182874. return;
  182875. }
  182876. png_crc_finish(png_ptr, 0);
  182877. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  182878. }
  182879. }
  182880. void PNGAPI
  182881. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  182882. {
  182883. png_bytep ptr;
  182884. if(png_ptr == NULL) return;
  182885. ptr = buffer;
  182886. if (png_ptr->save_buffer_size)
  182887. {
  182888. png_size_t save_size;
  182889. if (length < png_ptr->save_buffer_size)
  182890. save_size = length;
  182891. else
  182892. save_size = png_ptr->save_buffer_size;
  182893. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  182894. length -= save_size;
  182895. ptr += save_size;
  182896. png_ptr->buffer_size -= save_size;
  182897. png_ptr->save_buffer_size -= save_size;
  182898. png_ptr->save_buffer_ptr += save_size;
  182899. }
  182900. if (length && png_ptr->current_buffer_size)
  182901. {
  182902. png_size_t save_size;
  182903. if (length < png_ptr->current_buffer_size)
  182904. save_size = length;
  182905. else
  182906. save_size = png_ptr->current_buffer_size;
  182907. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  182908. png_ptr->buffer_size -= save_size;
  182909. png_ptr->current_buffer_size -= save_size;
  182910. png_ptr->current_buffer_ptr += save_size;
  182911. }
  182912. }
  182913. void /* PRIVATE */
  182914. png_push_save_buffer(png_structp png_ptr)
  182915. {
  182916. if (png_ptr->save_buffer_size)
  182917. {
  182918. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  182919. {
  182920. png_size_t i,istop;
  182921. png_bytep sp;
  182922. png_bytep dp;
  182923. istop = png_ptr->save_buffer_size;
  182924. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  182925. i < istop; i++, sp++, dp++)
  182926. {
  182927. *dp = *sp;
  182928. }
  182929. }
  182930. }
  182931. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  182932. png_ptr->save_buffer_max)
  182933. {
  182934. png_size_t new_max;
  182935. png_bytep old_buffer;
  182936. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  182937. (png_ptr->current_buffer_size + 256))
  182938. {
  182939. png_error(png_ptr, "Potential overflow of save_buffer");
  182940. }
  182941. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  182942. old_buffer = png_ptr->save_buffer;
  182943. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  182944. (png_uint_32)new_max);
  182945. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  182946. png_free(png_ptr, old_buffer);
  182947. png_ptr->save_buffer_max = new_max;
  182948. }
  182949. if (png_ptr->current_buffer_size)
  182950. {
  182951. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  182952. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  182953. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  182954. png_ptr->current_buffer_size = 0;
  182955. }
  182956. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  182957. png_ptr->buffer_size = 0;
  182958. }
  182959. void /* PRIVATE */
  182960. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  182961. png_size_t buffer_length)
  182962. {
  182963. png_ptr->current_buffer = buffer;
  182964. png_ptr->current_buffer_size = buffer_length;
  182965. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  182966. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  182967. }
  182968. void /* PRIVATE */
  182969. png_push_read_IDAT(png_structp png_ptr)
  182970. {
  182971. #ifdef PNG_USE_LOCAL_ARRAYS
  182972. PNG_CONST PNG_IDAT;
  182973. #endif
  182974. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  182975. {
  182976. png_byte chunk_length[4];
  182977. if (png_ptr->buffer_size < 8)
  182978. {
  182979. png_push_save_buffer(png_ptr);
  182980. return;
  182981. }
  182982. png_push_fill_buffer(png_ptr, chunk_length, 4);
  182983. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  182984. png_reset_crc(png_ptr);
  182985. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  182986. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  182987. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182988. {
  182989. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  182990. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  182991. png_error(png_ptr, "Not enough compressed data");
  182992. return;
  182993. }
  182994. png_ptr->idat_size = png_ptr->push_length;
  182995. }
  182996. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  182997. {
  182998. png_size_t save_size;
  182999. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  183000. {
  183001. save_size = (png_size_t)png_ptr->idat_size;
  183002. /* check for overflow */
  183003. if((png_uint_32)save_size != png_ptr->idat_size)
  183004. png_error(png_ptr, "save_size overflowed in pngpread");
  183005. }
  183006. else
  183007. save_size = png_ptr->save_buffer_size;
  183008. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  183009. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  183010. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  183011. png_ptr->idat_size -= save_size;
  183012. png_ptr->buffer_size -= save_size;
  183013. png_ptr->save_buffer_size -= save_size;
  183014. png_ptr->save_buffer_ptr += save_size;
  183015. }
  183016. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  183017. {
  183018. png_size_t save_size;
  183019. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  183020. {
  183021. save_size = (png_size_t)png_ptr->idat_size;
  183022. /* check for overflow */
  183023. if((png_uint_32)save_size != png_ptr->idat_size)
  183024. png_error(png_ptr, "save_size overflowed in pngpread");
  183025. }
  183026. else
  183027. save_size = png_ptr->current_buffer_size;
  183028. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  183029. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  183030. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  183031. png_ptr->idat_size -= save_size;
  183032. png_ptr->buffer_size -= save_size;
  183033. png_ptr->current_buffer_size -= save_size;
  183034. png_ptr->current_buffer_ptr += save_size;
  183035. }
  183036. if (!png_ptr->idat_size)
  183037. {
  183038. if (png_ptr->buffer_size < 4)
  183039. {
  183040. png_push_save_buffer(png_ptr);
  183041. return;
  183042. }
  183043. png_crc_finish(png_ptr, 0);
  183044. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  183045. png_ptr->mode |= PNG_AFTER_IDAT;
  183046. }
  183047. }
  183048. void /* PRIVATE */
  183049. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  183050. png_size_t buffer_length)
  183051. {
  183052. int ret;
  183053. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  183054. png_error(png_ptr, "Extra compression data");
  183055. png_ptr->zstream.next_in = buffer;
  183056. png_ptr->zstream.avail_in = (uInt)buffer_length;
  183057. for(;;)
  183058. {
  183059. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  183060. if (ret != Z_OK)
  183061. {
  183062. if (ret == Z_STREAM_END)
  183063. {
  183064. if (png_ptr->zstream.avail_in)
  183065. png_error(png_ptr, "Extra compressed data");
  183066. if (!(png_ptr->zstream.avail_out))
  183067. {
  183068. png_push_process_row(png_ptr);
  183069. }
  183070. png_ptr->mode |= PNG_AFTER_IDAT;
  183071. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  183072. break;
  183073. }
  183074. else if (ret == Z_BUF_ERROR)
  183075. break;
  183076. else
  183077. png_error(png_ptr, "Decompression Error");
  183078. }
  183079. if (!(png_ptr->zstream.avail_out))
  183080. {
  183081. if ((
  183082. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183083. png_ptr->interlaced && png_ptr->pass > 6) ||
  183084. (!png_ptr->interlaced &&
  183085. #endif
  183086. png_ptr->row_number == png_ptr->num_rows))
  183087. {
  183088. if (png_ptr->zstream.avail_in)
  183089. {
  183090. png_warning(png_ptr, "Too much data in IDAT chunks");
  183091. }
  183092. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  183093. break;
  183094. }
  183095. png_push_process_row(png_ptr);
  183096. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  183097. png_ptr->zstream.next_out = png_ptr->row_buf;
  183098. }
  183099. else
  183100. break;
  183101. }
  183102. }
  183103. void /* PRIVATE */
  183104. png_push_process_row(png_structp png_ptr)
  183105. {
  183106. png_ptr->row_info.color_type = png_ptr->color_type;
  183107. png_ptr->row_info.width = png_ptr->iwidth;
  183108. png_ptr->row_info.channels = png_ptr->channels;
  183109. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  183110. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  183111. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  183112. png_ptr->row_info.width);
  183113. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  183114. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  183115. (int)(png_ptr->row_buf[0]));
  183116. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  183117. png_ptr->rowbytes + 1);
  183118. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  183119. png_do_read_transformations(png_ptr);
  183120. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183121. /* blow up interlaced rows to full size */
  183122. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  183123. {
  183124. if (png_ptr->pass < 6)
  183125. /* old interface (pre-1.0.9):
  183126. png_do_read_interlace(&(png_ptr->row_info),
  183127. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  183128. */
  183129. png_do_read_interlace(png_ptr);
  183130. switch (png_ptr->pass)
  183131. {
  183132. case 0:
  183133. {
  183134. int i;
  183135. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  183136. {
  183137. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183138. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  183139. }
  183140. if (png_ptr->pass == 2) /* pass 1 might be empty */
  183141. {
  183142. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  183143. {
  183144. png_push_have_row(png_ptr, png_bytep_NULL);
  183145. png_read_push_finish_row(png_ptr);
  183146. }
  183147. }
  183148. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  183149. {
  183150. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  183151. {
  183152. png_push_have_row(png_ptr, png_bytep_NULL);
  183153. png_read_push_finish_row(png_ptr);
  183154. }
  183155. }
  183156. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  183157. {
  183158. png_push_have_row(png_ptr, png_bytep_NULL);
  183159. png_read_push_finish_row(png_ptr);
  183160. }
  183161. break;
  183162. }
  183163. case 1:
  183164. {
  183165. int i;
  183166. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  183167. {
  183168. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183169. png_read_push_finish_row(png_ptr);
  183170. }
  183171. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  183172. {
  183173. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  183174. {
  183175. png_push_have_row(png_ptr, png_bytep_NULL);
  183176. png_read_push_finish_row(png_ptr);
  183177. }
  183178. }
  183179. break;
  183180. }
  183181. case 2:
  183182. {
  183183. int i;
  183184. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  183185. {
  183186. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183187. png_read_push_finish_row(png_ptr);
  183188. }
  183189. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  183190. {
  183191. png_push_have_row(png_ptr, png_bytep_NULL);
  183192. png_read_push_finish_row(png_ptr);
  183193. }
  183194. if (png_ptr->pass == 4) /* pass 3 might be empty */
  183195. {
  183196. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  183197. {
  183198. png_push_have_row(png_ptr, png_bytep_NULL);
  183199. png_read_push_finish_row(png_ptr);
  183200. }
  183201. }
  183202. break;
  183203. }
  183204. case 3:
  183205. {
  183206. int i;
  183207. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  183208. {
  183209. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183210. png_read_push_finish_row(png_ptr);
  183211. }
  183212. if (png_ptr->pass == 4) /* skip top two generated rows */
  183213. {
  183214. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  183215. {
  183216. png_push_have_row(png_ptr, png_bytep_NULL);
  183217. png_read_push_finish_row(png_ptr);
  183218. }
  183219. }
  183220. break;
  183221. }
  183222. case 4:
  183223. {
  183224. int i;
  183225. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  183226. {
  183227. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183228. png_read_push_finish_row(png_ptr);
  183229. }
  183230. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  183231. {
  183232. png_push_have_row(png_ptr, png_bytep_NULL);
  183233. png_read_push_finish_row(png_ptr);
  183234. }
  183235. if (png_ptr->pass == 6) /* pass 5 might be empty */
  183236. {
  183237. png_push_have_row(png_ptr, png_bytep_NULL);
  183238. png_read_push_finish_row(png_ptr);
  183239. }
  183240. break;
  183241. }
  183242. case 5:
  183243. {
  183244. int i;
  183245. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  183246. {
  183247. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183248. png_read_push_finish_row(png_ptr);
  183249. }
  183250. if (png_ptr->pass == 6) /* skip top generated row */
  183251. {
  183252. png_push_have_row(png_ptr, png_bytep_NULL);
  183253. png_read_push_finish_row(png_ptr);
  183254. }
  183255. break;
  183256. }
  183257. case 6:
  183258. {
  183259. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183260. png_read_push_finish_row(png_ptr);
  183261. if (png_ptr->pass != 6)
  183262. break;
  183263. png_push_have_row(png_ptr, png_bytep_NULL);
  183264. png_read_push_finish_row(png_ptr);
  183265. }
  183266. }
  183267. }
  183268. else
  183269. #endif
  183270. {
  183271. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183272. png_read_push_finish_row(png_ptr);
  183273. }
  183274. }
  183275. void /* PRIVATE */
  183276. png_read_push_finish_row(png_structp png_ptr)
  183277. {
  183278. #ifdef PNG_USE_LOCAL_ARRAYS
  183279. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  183280. /* start of interlace block */
  183281. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  183282. /* offset to next interlace block */
  183283. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  183284. /* start of interlace block in the y direction */
  183285. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  183286. /* offset to next interlace block in the y direction */
  183287. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  183288. /* Height of interlace block. This is not currently used - if you need
  183289. * it, uncomment it here and in png.h
  183290. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  183291. */
  183292. #endif
  183293. png_ptr->row_number++;
  183294. if (png_ptr->row_number < png_ptr->num_rows)
  183295. return;
  183296. if (png_ptr->interlaced)
  183297. {
  183298. png_ptr->row_number = 0;
  183299. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  183300. png_ptr->rowbytes + 1);
  183301. do
  183302. {
  183303. png_ptr->pass++;
  183304. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  183305. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  183306. (png_ptr->pass == 5 && png_ptr->width < 2))
  183307. png_ptr->pass++;
  183308. if (png_ptr->pass > 7)
  183309. png_ptr->pass--;
  183310. if (png_ptr->pass >= 7)
  183311. break;
  183312. png_ptr->iwidth = (png_ptr->width +
  183313. png_pass_inc[png_ptr->pass] - 1 -
  183314. png_pass_start[png_ptr->pass]) /
  183315. png_pass_inc[png_ptr->pass];
  183316. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  183317. png_ptr->iwidth) + 1;
  183318. if (png_ptr->transformations & PNG_INTERLACE)
  183319. break;
  183320. png_ptr->num_rows = (png_ptr->height +
  183321. png_pass_yinc[png_ptr->pass] - 1 -
  183322. png_pass_ystart[png_ptr->pass]) /
  183323. png_pass_yinc[png_ptr->pass];
  183324. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  183325. }
  183326. }
  183327. #if defined(PNG_READ_tEXt_SUPPORTED)
  183328. void /* PRIVATE */
  183329. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  183330. length)
  183331. {
  183332. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  183333. {
  183334. png_error(png_ptr, "Out of place tEXt");
  183335. info_ptr = info_ptr; /* to quiet some compiler warnings */
  183336. }
  183337. #ifdef PNG_MAX_MALLOC_64K
  183338. png_ptr->skip_length = 0; /* This may not be necessary */
  183339. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  183340. {
  183341. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  183342. png_ptr->skip_length = length - (png_uint_32)65535L;
  183343. length = (png_uint_32)65535L;
  183344. }
  183345. #endif
  183346. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  183347. (png_uint_32)(length+1));
  183348. png_ptr->current_text[length] = '\0';
  183349. png_ptr->current_text_ptr = png_ptr->current_text;
  183350. png_ptr->current_text_size = (png_size_t)length;
  183351. png_ptr->current_text_left = (png_size_t)length;
  183352. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  183353. }
  183354. void /* PRIVATE */
  183355. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  183356. {
  183357. if (png_ptr->buffer_size && png_ptr->current_text_left)
  183358. {
  183359. png_size_t text_size;
  183360. if (png_ptr->buffer_size < png_ptr->current_text_left)
  183361. text_size = png_ptr->buffer_size;
  183362. else
  183363. text_size = png_ptr->current_text_left;
  183364. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  183365. png_ptr->current_text_left -= text_size;
  183366. png_ptr->current_text_ptr += text_size;
  183367. }
  183368. if (!(png_ptr->current_text_left))
  183369. {
  183370. png_textp text_ptr;
  183371. png_charp text;
  183372. png_charp key;
  183373. int ret;
  183374. if (png_ptr->buffer_size < 4)
  183375. {
  183376. png_push_save_buffer(png_ptr);
  183377. return;
  183378. }
  183379. png_push_crc_finish(png_ptr);
  183380. #if defined(PNG_MAX_MALLOC_64K)
  183381. if (png_ptr->skip_length)
  183382. return;
  183383. #endif
  183384. key = png_ptr->current_text;
  183385. for (text = key; *text; text++)
  183386. /* empty loop */ ;
  183387. if (text < key + png_ptr->current_text_size)
  183388. text++;
  183389. text_ptr = (png_textp)png_malloc(png_ptr,
  183390. (png_uint_32)png_sizeof(png_text));
  183391. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  183392. text_ptr->key = key;
  183393. #ifdef PNG_iTXt_SUPPORTED
  183394. text_ptr->lang = NULL;
  183395. text_ptr->lang_key = NULL;
  183396. #endif
  183397. text_ptr->text = text;
  183398. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  183399. png_free(png_ptr, key);
  183400. png_free(png_ptr, text_ptr);
  183401. png_ptr->current_text = NULL;
  183402. if (ret)
  183403. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  183404. }
  183405. }
  183406. #endif
  183407. #if defined(PNG_READ_zTXt_SUPPORTED)
  183408. void /* PRIVATE */
  183409. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  183410. length)
  183411. {
  183412. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  183413. {
  183414. png_error(png_ptr, "Out of place zTXt");
  183415. info_ptr = info_ptr; /* to quiet some compiler warnings */
  183416. }
  183417. #ifdef PNG_MAX_MALLOC_64K
  183418. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  183419. * to be able to store the uncompressed data. Actually, the threshold
  183420. * is probably around 32K, but it isn't as definite as 64K is.
  183421. */
  183422. if (length > (png_uint_32)65535L)
  183423. {
  183424. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  183425. png_push_crc_skip(png_ptr, length);
  183426. return;
  183427. }
  183428. #endif
  183429. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  183430. (png_uint_32)(length+1));
  183431. png_ptr->current_text[length] = '\0';
  183432. png_ptr->current_text_ptr = png_ptr->current_text;
  183433. png_ptr->current_text_size = (png_size_t)length;
  183434. png_ptr->current_text_left = (png_size_t)length;
  183435. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  183436. }
  183437. void /* PRIVATE */
  183438. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  183439. {
  183440. if (png_ptr->buffer_size && png_ptr->current_text_left)
  183441. {
  183442. png_size_t text_size;
  183443. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  183444. text_size = png_ptr->buffer_size;
  183445. else
  183446. text_size = png_ptr->current_text_left;
  183447. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  183448. png_ptr->current_text_left -= text_size;
  183449. png_ptr->current_text_ptr += text_size;
  183450. }
  183451. if (!(png_ptr->current_text_left))
  183452. {
  183453. png_textp text_ptr;
  183454. png_charp text;
  183455. png_charp key;
  183456. int ret;
  183457. png_size_t text_size, key_size;
  183458. if (png_ptr->buffer_size < 4)
  183459. {
  183460. png_push_save_buffer(png_ptr);
  183461. return;
  183462. }
  183463. png_push_crc_finish(png_ptr);
  183464. key = png_ptr->current_text;
  183465. for (text = key; *text; text++)
  183466. /* empty loop */ ;
  183467. /* zTXt can't have zero text */
  183468. if (text >= key + png_ptr->current_text_size)
  183469. {
  183470. png_ptr->current_text = NULL;
  183471. png_free(png_ptr, key);
  183472. return;
  183473. }
  183474. text++;
  183475. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  183476. {
  183477. png_ptr->current_text = NULL;
  183478. png_free(png_ptr, key);
  183479. return;
  183480. }
  183481. text++;
  183482. png_ptr->zstream.next_in = (png_bytep )text;
  183483. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  183484. (text - key));
  183485. png_ptr->zstream.next_out = png_ptr->zbuf;
  183486. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  183487. key_size = text - key;
  183488. text_size = 0;
  183489. text = NULL;
  183490. ret = Z_STREAM_END;
  183491. while (png_ptr->zstream.avail_in)
  183492. {
  183493. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  183494. if (ret != Z_OK && ret != Z_STREAM_END)
  183495. {
  183496. inflateReset(&png_ptr->zstream);
  183497. png_ptr->zstream.avail_in = 0;
  183498. png_ptr->current_text = NULL;
  183499. png_free(png_ptr, key);
  183500. png_free(png_ptr, text);
  183501. return;
  183502. }
  183503. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  183504. {
  183505. if (text == NULL)
  183506. {
  183507. text = (png_charp)png_malloc(png_ptr,
  183508. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  183509. + key_size + 1));
  183510. png_memcpy(text + key_size, png_ptr->zbuf,
  183511. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  183512. png_memcpy(text, key, key_size);
  183513. text_size = key_size + png_ptr->zbuf_size -
  183514. png_ptr->zstream.avail_out;
  183515. *(text + text_size) = '\0';
  183516. }
  183517. else
  183518. {
  183519. png_charp tmp;
  183520. tmp = text;
  183521. text = (png_charp)png_malloc(png_ptr, text_size +
  183522. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  183523. + 1));
  183524. png_memcpy(text, tmp, text_size);
  183525. png_free(png_ptr, tmp);
  183526. png_memcpy(text + text_size, png_ptr->zbuf,
  183527. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  183528. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  183529. *(text + text_size) = '\0';
  183530. }
  183531. if (ret != Z_STREAM_END)
  183532. {
  183533. png_ptr->zstream.next_out = png_ptr->zbuf;
  183534. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  183535. }
  183536. }
  183537. else
  183538. {
  183539. break;
  183540. }
  183541. if (ret == Z_STREAM_END)
  183542. break;
  183543. }
  183544. inflateReset(&png_ptr->zstream);
  183545. png_ptr->zstream.avail_in = 0;
  183546. if (ret != Z_STREAM_END)
  183547. {
  183548. png_ptr->current_text = NULL;
  183549. png_free(png_ptr, key);
  183550. png_free(png_ptr, text);
  183551. return;
  183552. }
  183553. png_ptr->current_text = NULL;
  183554. png_free(png_ptr, key);
  183555. key = text;
  183556. text += key_size;
  183557. text_ptr = (png_textp)png_malloc(png_ptr,
  183558. (png_uint_32)png_sizeof(png_text));
  183559. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  183560. text_ptr->key = key;
  183561. #ifdef PNG_iTXt_SUPPORTED
  183562. text_ptr->lang = NULL;
  183563. text_ptr->lang_key = NULL;
  183564. #endif
  183565. text_ptr->text = text;
  183566. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  183567. png_free(png_ptr, key);
  183568. png_free(png_ptr, text_ptr);
  183569. if (ret)
  183570. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  183571. }
  183572. }
  183573. #endif
  183574. #if defined(PNG_READ_iTXt_SUPPORTED)
  183575. void /* PRIVATE */
  183576. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  183577. length)
  183578. {
  183579. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  183580. {
  183581. png_error(png_ptr, "Out of place iTXt");
  183582. info_ptr = info_ptr; /* to quiet some compiler warnings */
  183583. }
  183584. #ifdef PNG_MAX_MALLOC_64K
  183585. png_ptr->skip_length = 0; /* This may not be necessary */
  183586. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  183587. {
  183588. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  183589. png_ptr->skip_length = length - (png_uint_32)65535L;
  183590. length = (png_uint_32)65535L;
  183591. }
  183592. #endif
  183593. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  183594. (png_uint_32)(length+1));
  183595. png_ptr->current_text[length] = '\0';
  183596. png_ptr->current_text_ptr = png_ptr->current_text;
  183597. png_ptr->current_text_size = (png_size_t)length;
  183598. png_ptr->current_text_left = (png_size_t)length;
  183599. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  183600. }
  183601. void /* PRIVATE */
  183602. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  183603. {
  183604. if (png_ptr->buffer_size && png_ptr->current_text_left)
  183605. {
  183606. png_size_t text_size;
  183607. if (png_ptr->buffer_size < png_ptr->current_text_left)
  183608. text_size = png_ptr->buffer_size;
  183609. else
  183610. text_size = png_ptr->current_text_left;
  183611. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  183612. png_ptr->current_text_left -= text_size;
  183613. png_ptr->current_text_ptr += text_size;
  183614. }
  183615. if (!(png_ptr->current_text_left))
  183616. {
  183617. png_textp text_ptr;
  183618. png_charp key;
  183619. int comp_flag;
  183620. png_charp lang;
  183621. png_charp lang_key;
  183622. png_charp text;
  183623. int ret;
  183624. if (png_ptr->buffer_size < 4)
  183625. {
  183626. png_push_save_buffer(png_ptr);
  183627. return;
  183628. }
  183629. png_push_crc_finish(png_ptr);
  183630. #if defined(PNG_MAX_MALLOC_64K)
  183631. if (png_ptr->skip_length)
  183632. return;
  183633. #endif
  183634. key = png_ptr->current_text;
  183635. for (lang = key; *lang; lang++)
  183636. /* empty loop */ ;
  183637. if (lang < key + png_ptr->current_text_size - 3)
  183638. lang++;
  183639. comp_flag = *lang++;
  183640. lang++; /* skip comp_type, always zero */
  183641. for (lang_key = lang; *lang_key; lang_key++)
  183642. /* empty loop */ ;
  183643. lang_key++; /* skip NUL separator */
  183644. text=lang_key;
  183645. if (lang_key < key + png_ptr->current_text_size - 1)
  183646. {
  183647. for (; *text; text++)
  183648. /* empty loop */ ;
  183649. }
  183650. if (text < key + png_ptr->current_text_size)
  183651. text++;
  183652. text_ptr = (png_textp)png_malloc(png_ptr,
  183653. (png_uint_32)png_sizeof(png_text));
  183654. text_ptr->compression = comp_flag + 2;
  183655. text_ptr->key = key;
  183656. text_ptr->lang = lang;
  183657. text_ptr->lang_key = lang_key;
  183658. text_ptr->text = text;
  183659. text_ptr->text_length = 0;
  183660. text_ptr->itxt_length = png_strlen(text);
  183661. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  183662. png_ptr->current_text = NULL;
  183663. png_free(png_ptr, text_ptr);
  183664. if (ret)
  183665. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  183666. }
  183667. }
  183668. #endif
  183669. /* This function is called when we haven't found a handler for this
  183670. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  183671. * name or a critical chunk), the chunk is (currently) silently ignored.
  183672. */
  183673. void /* PRIVATE */
  183674. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  183675. length)
  183676. {
  183677. png_uint_32 skip=0;
  183678. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  183679. if (!(png_ptr->chunk_name[0] & 0x20))
  183680. {
  183681. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  183682. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  183683. PNG_HANDLE_CHUNK_ALWAYS
  183684. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  183685. && png_ptr->read_user_chunk_fn == NULL
  183686. #endif
  183687. )
  183688. #endif
  183689. png_chunk_error(png_ptr, "unknown critical chunk");
  183690. info_ptr = info_ptr; /* to quiet some compiler warnings */
  183691. }
  183692. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  183693. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  183694. {
  183695. #ifdef PNG_MAX_MALLOC_64K
  183696. if (length > (png_uint_32)65535L)
  183697. {
  183698. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  183699. skip = length - (png_uint_32)65535L;
  183700. length = (png_uint_32)65535L;
  183701. }
  183702. #endif
  183703. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  183704. (png_charp)png_ptr->chunk_name, 5);
  183705. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  183706. png_ptr->unknown_chunk.size = (png_size_t)length;
  183707. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  183708. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  183709. if(png_ptr->read_user_chunk_fn != NULL)
  183710. {
  183711. /* callback to user unknown chunk handler */
  183712. int ret;
  183713. ret = (*(png_ptr->read_user_chunk_fn))
  183714. (png_ptr, &png_ptr->unknown_chunk);
  183715. if (ret < 0)
  183716. png_chunk_error(png_ptr, "error in user chunk");
  183717. if (ret == 0)
  183718. {
  183719. if (!(png_ptr->chunk_name[0] & 0x20))
  183720. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  183721. PNG_HANDLE_CHUNK_ALWAYS)
  183722. png_chunk_error(png_ptr, "unknown critical chunk");
  183723. png_set_unknown_chunks(png_ptr, info_ptr,
  183724. &png_ptr->unknown_chunk, 1);
  183725. }
  183726. }
  183727. #else
  183728. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  183729. #endif
  183730. png_free(png_ptr, png_ptr->unknown_chunk.data);
  183731. png_ptr->unknown_chunk.data = NULL;
  183732. }
  183733. else
  183734. #endif
  183735. skip=length;
  183736. png_push_crc_skip(png_ptr, skip);
  183737. }
  183738. void /* PRIVATE */
  183739. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  183740. {
  183741. if (png_ptr->info_fn != NULL)
  183742. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  183743. }
  183744. void /* PRIVATE */
  183745. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  183746. {
  183747. if (png_ptr->end_fn != NULL)
  183748. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  183749. }
  183750. void /* PRIVATE */
  183751. png_push_have_row(png_structp png_ptr, png_bytep row)
  183752. {
  183753. if (png_ptr->row_fn != NULL)
  183754. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  183755. (int)png_ptr->pass);
  183756. }
  183757. void PNGAPI
  183758. png_progressive_combine_row (png_structp png_ptr,
  183759. png_bytep old_row, png_bytep new_row)
  183760. {
  183761. #ifdef PNG_USE_LOCAL_ARRAYS
  183762. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  183763. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  183764. #endif
  183765. if(png_ptr == NULL) return;
  183766. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  183767. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  183768. }
  183769. void PNGAPI
  183770. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  183771. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183772. png_progressive_end_ptr end_fn)
  183773. {
  183774. if(png_ptr == NULL) return;
  183775. png_ptr->info_fn = info_fn;
  183776. png_ptr->row_fn = row_fn;
  183777. png_ptr->end_fn = end_fn;
  183778. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  183779. }
  183780. png_voidp PNGAPI
  183781. png_get_progressive_ptr(png_structp png_ptr)
  183782. {
  183783. if(png_ptr == NULL) return (NULL);
  183784. return png_ptr->io_ptr;
  183785. }
  183786. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183787. /********* End of inlined file: pngpread.c *********/
  183788. /********* Start of inlined file: pngrio.c *********/
  183789. /* pngrio.c - functions for data input
  183790. *
  183791. * Last changed in libpng 1.2.13 November 13, 2006
  183792. * For conditions of distribution and use, see copyright notice in png.h
  183793. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  183794. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183795. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183796. *
  183797. * This file provides a location for all input. Users who need
  183798. * special handling are expected to write a function that has the same
  183799. * arguments as this and performs a similar function, but that possibly
  183800. * has a different input method. Note that you shouldn't change this
  183801. * function, but rather write a replacement function and then make
  183802. * libpng use it at run time with png_set_read_fn(...).
  183803. */
  183804. #define PNG_INTERNAL
  183805. #if defined(PNG_READ_SUPPORTED)
  183806. /* Read the data from whatever input you are using. The default routine
  183807. reads from a file pointer. Note that this routine sometimes gets called
  183808. with very small lengths, so you should implement some kind of simple
  183809. buffering if you are using unbuffered reads. This should never be asked
  183810. to read more then 64K on a 16 bit machine. */
  183811. void /* PRIVATE */
  183812. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  183813. {
  183814. png_debug1(4,"reading %d bytes\n", (int)length);
  183815. if (png_ptr->read_data_fn != NULL)
  183816. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  183817. else
  183818. png_error(png_ptr, "Call to NULL read function");
  183819. }
  183820. #if !defined(PNG_NO_STDIO)
  183821. /* This is the function that does the actual reading of data. If you are
  183822. not reading from a standard C stream, you should create a replacement
  183823. read_data function and use it at run time with png_set_read_fn(), rather
  183824. than changing the library. */
  183825. #ifndef USE_FAR_KEYWORD
  183826. void PNGAPI
  183827. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  183828. {
  183829. png_size_t check;
  183830. if(png_ptr == NULL) return;
  183831. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  183832. * instead of an int, which is what fread() actually returns.
  183833. */
  183834. #if defined(_WIN32_WCE)
  183835. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  183836. check = 0;
  183837. #else
  183838. check = (png_size_t)fread(data, (png_size_t)1, length,
  183839. (png_FILE_p)png_ptr->io_ptr);
  183840. #endif
  183841. if (check != length)
  183842. png_error(png_ptr, "Read Error");
  183843. }
  183844. #else
  183845. /* this is the model-independent version. Since the standard I/O library
  183846. can't handle far buffers in the medium and small models, we have to copy
  183847. the data.
  183848. */
  183849. #define NEAR_BUF_SIZE 1024
  183850. #define MIN(a,b) (a <= b ? a : b)
  183851. static void PNGAPI
  183852. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  183853. {
  183854. int check;
  183855. png_byte *n_data;
  183856. png_FILE_p io_ptr;
  183857. if(png_ptr == NULL) return;
  183858. /* Check if data really is near. If so, use usual code. */
  183859. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  183860. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  183861. if ((png_bytep)n_data == data)
  183862. {
  183863. #if defined(_WIN32_WCE)
  183864. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  183865. check = 0;
  183866. #else
  183867. check = fread(n_data, 1, length, io_ptr);
  183868. #endif
  183869. }
  183870. else
  183871. {
  183872. png_byte buf[NEAR_BUF_SIZE];
  183873. png_size_t read, remaining, err;
  183874. check = 0;
  183875. remaining = length;
  183876. do
  183877. {
  183878. read = MIN(NEAR_BUF_SIZE, remaining);
  183879. #if defined(_WIN32_WCE)
  183880. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  183881. err = 0;
  183882. #else
  183883. err = fread(buf, (png_size_t)1, read, io_ptr);
  183884. #endif
  183885. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  183886. if(err != read)
  183887. break;
  183888. else
  183889. check += err;
  183890. data += read;
  183891. remaining -= read;
  183892. }
  183893. while (remaining != 0);
  183894. }
  183895. if ((png_uint_32)check != (png_uint_32)length)
  183896. png_error(png_ptr, "read Error");
  183897. }
  183898. #endif
  183899. #endif
  183900. /* This function allows the application to supply a new input function
  183901. for libpng if standard C streams aren't being used.
  183902. This function takes as its arguments:
  183903. png_ptr - pointer to a png input data structure
  183904. io_ptr - pointer to user supplied structure containing info about
  183905. the input functions. May be NULL.
  183906. read_data_fn - pointer to a new input function that takes as its
  183907. arguments a pointer to a png_struct, a pointer to
  183908. a location where input data can be stored, and a 32-bit
  183909. unsigned int that is the number of bytes to be read.
  183910. To exit and output any fatal error messages the new write
  183911. function should call png_error(png_ptr, "Error msg"). */
  183912. void PNGAPI
  183913. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  183914. png_rw_ptr read_data_fn)
  183915. {
  183916. if(png_ptr == NULL) return;
  183917. png_ptr->io_ptr = io_ptr;
  183918. #if !defined(PNG_NO_STDIO)
  183919. if (read_data_fn != NULL)
  183920. png_ptr->read_data_fn = read_data_fn;
  183921. else
  183922. png_ptr->read_data_fn = png_default_read_data;
  183923. #else
  183924. png_ptr->read_data_fn = read_data_fn;
  183925. #endif
  183926. /* It is an error to write to a read device */
  183927. if (png_ptr->write_data_fn != NULL)
  183928. {
  183929. png_ptr->write_data_fn = NULL;
  183930. png_warning(png_ptr,
  183931. "It's an error to set both read_data_fn and write_data_fn in the ");
  183932. png_warning(png_ptr,
  183933. "same structure. Resetting write_data_fn to NULL.");
  183934. }
  183935. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183936. png_ptr->output_flush_fn = NULL;
  183937. #endif
  183938. }
  183939. #endif /* PNG_READ_SUPPORTED */
  183940. /********* End of inlined file: pngrio.c *********/
  183941. /********* Start of inlined file: pngrtran.c *********/
  183942. /* pngrtran.c - transforms the data in a row for PNG readers
  183943. *
  183944. * Last changed in libpng 1.2.21 [October 4, 2007]
  183945. * For conditions of distribution and use, see copyright notice in png.h
  183946. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  183947. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183948. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183949. *
  183950. * This file contains functions optionally called by an application
  183951. * in order to tell libpng how to handle data when reading a PNG.
  183952. * Transformations that are used in both reading and writing are
  183953. * in pngtrans.c.
  183954. */
  183955. #define PNG_INTERNAL
  183956. #if defined(PNG_READ_SUPPORTED)
  183957. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  183958. void PNGAPI
  183959. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  183960. {
  183961. png_debug(1, "in png_set_crc_action\n");
  183962. /* Tell libpng how we react to CRC errors in critical chunks */
  183963. if(png_ptr == NULL) return;
  183964. switch (crit_action)
  183965. {
  183966. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  183967. break;
  183968. case PNG_CRC_WARN_USE: /* warn/use data */
  183969. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  183970. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  183971. break;
  183972. case PNG_CRC_QUIET_USE: /* quiet/use data */
  183973. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  183974. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  183975. PNG_FLAG_CRC_CRITICAL_IGNORE;
  183976. break;
  183977. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  183978. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  183979. case PNG_CRC_ERROR_QUIT: /* error/quit */
  183980. case PNG_CRC_DEFAULT:
  183981. default:
  183982. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  183983. break;
  183984. }
  183985. switch (ancil_action)
  183986. {
  183987. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  183988. break;
  183989. case PNG_CRC_WARN_USE: /* warn/use data */
  183990. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  183991. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  183992. break;
  183993. case PNG_CRC_QUIET_USE: /* quiet/use data */
  183994. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  183995. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  183996. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  183997. break;
  183998. case PNG_CRC_ERROR_QUIT: /* error/quit */
  183999. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  184000. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  184001. break;
  184002. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  184003. case PNG_CRC_DEFAULT:
  184004. default:
  184005. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  184006. break;
  184007. }
  184008. }
  184009. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  184010. defined(PNG_FLOATING_POINT_SUPPORTED)
  184011. /* handle alpha and tRNS via a background color */
  184012. void PNGAPI
  184013. png_set_background(png_structp png_ptr,
  184014. png_color_16p background_color, int background_gamma_code,
  184015. int need_expand, double background_gamma)
  184016. {
  184017. png_debug(1, "in png_set_background\n");
  184018. if(png_ptr == NULL) return;
  184019. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  184020. {
  184021. png_warning(png_ptr, "Application must supply a known background gamma");
  184022. return;
  184023. }
  184024. png_ptr->transformations |= PNG_BACKGROUND;
  184025. png_memcpy(&(png_ptr->background), background_color,
  184026. png_sizeof(png_color_16));
  184027. png_ptr->background_gamma = (float)background_gamma;
  184028. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  184029. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  184030. }
  184031. #endif
  184032. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184033. /* strip 16 bit depth files to 8 bit depth */
  184034. void PNGAPI
  184035. png_set_strip_16(png_structp png_ptr)
  184036. {
  184037. png_debug(1, "in png_set_strip_16\n");
  184038. if(png_ptr == NULL) return;
  184039. png_ptr->transformations |= PNG_16_TO_8;
  184040. }
  184041. #endif
  184042. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184043. void PNGAPI
  184044. png_set_strip_alpha(png_structp png_ptr)
  184045. {
  184046. png_debug(1, "in png_set_strip_alpha\n");
  184047. if(png_ptr == NULL) return;
  184048. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  184049. }
  184050. #endif
  184051. #if defined(PNG_READ_DITHER_SUPPORTED)
  184052. /* Dither file to 8 bit. Supply a palette, the current number
  184053. * of elements in the palette, the maximum number of elements
  184054. * allowed, and a histogram if possible. If the current number
  184055. * of colors is greater then the maximum number, the palette will be
  184056. * modified to fit in the maximum number. "full_dither" indicates
  184057. * whether we need a dithering cube set up for RGB images, or if we
  184058. * simply are reducing the number of colors in a paletted image.
  184059. */
  184060. typedef struct png_dsort_struct
  184061. {
  184062. struct png_dsort_struct FAR * next;
  184063. png_byte left;
  184064. png_byte right;
  184065. } png_dsort;
  184066. typedef png_dsort FAR * png_dsortp;
  184067. typedef png_dsort FAR * FAR * png_dsortpp;
  184068. void PNGAPI
  184069. png_set_dither(png_structp png_ptr, png_colorp palette,
  184070. int num_palette, int maximum_colors, png_uint_16p histogram,
  184071. int full_dither)
  184072. {
  184073. png_debug(1, "in png_set_dither\n");
  184074. if(png_ptr == NULL) return;
  184075. png_ptr->transformations |= PNG_DITHER;
  184076. if (!full_dither)
  184077. {
  184078. int i;
  184079. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  184080. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  184081. for (i = 0; i < num_palette; i++)
  184082. png_ptr->dither_index[i] = (png_byte)i;
  184083. }
  184084. if (num_palette > maximum_colors)
  184085. {
  184086. if (histogram != NULL)
  184087. {
  184088. /* This is easy enough, just throw out the least used colors.
  184089. Perhaps not the best solution, but good enough. */
  184090. int i;
  184091. /* initialize an array to sort colors */
  184092. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  184093. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  184094. /* initialize the dither_sort array */
  184095. for (i = 0; i < num_palette; i++)
  184096. png_ptr->dither_sort[i] = (png_byte)i;
  184097. /* Find the least used palette entries by starting a
  184098. bubble sort, and running it until we have sorted
  184099. out enough colors. Note that we don't care about
  184100. sorting all the colors, just finding which are
  184101. least used. */
  184102. for (i = num_palette - 1; i >= maximum_colors; i--)
  184103. {
  184104. int done; /* to stop early if the list is pre-sorted */
  184105. int j;
  184106. done = 1;
  184107. for (j = 0; j < i; j++)
  184108. {
  184109. if (histogram[png_ptr->dither_sort[j]]
  184110. < histogram[png_ptr->dither_sort[j + 1]])
  184111. {
  184112. png_byte t;
  184113. t = png_ptr->dither_sort[j];
  184114. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  184115. png_ptr->dither_sort[j + 1] = t;
  184116. done = 0;
  184117. }
  184118. }
  184119. if (done)
  184120. break;
  184121. }
  184122. /* swap the palette around, and set up a table, if necessary */
  184123. if (full_dither)
  184124. {
  184125. int j = num_palette;
  184126. /* put all the useful colors within the max, but don't
  184127. move the others */
  184128. for (i = 0; i < maximum_colors; i++)
  184129. {
  184130. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  184131. {
  184132. do
  184133. j--;
  184134. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  184135. palette[i] = palette[j];
  184136. }
  184137. }
  184138. }
  184139. else
  184140. {
  184141. int j = num_palette;
  184142. /* move all the used colors inside the max limit, and
  184143. develop a translation table */
  184144. for (i = 0; i < maximum_colors; i++)
  184145. {
  184146. /* only move the colors we need to */
  184147. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  184148. {
  184149. png_color tmp_color;
  184150. do
  184151. j--;
  184152. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  184153. tmp_color = palette[j];
  184154. palette[j] = palette[i];
  184155. palette[i] = tmp_color;
  184156. /* indicate where the color went */
  184157. png_ptr->dither_index[j] = (png_byte)i;
  184158. png_ptr->dither_index[i] = (png_byte)j;
  184159. }
  184160. }
  184161. /* find closest color for those colors we are not using */
  184162. for (i = 0; i < num_palette; i++)
  184163. {
  184164. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  184165. {
  184166. int min_d, k, min_k, d_index;
  184167. /* find the closest color to one we threw out */
  184168. d_index = png_ptr->dither_index[i];
  184169. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  184170. for (k = 1, min_k = 0; k < maximum_colors; k++)
  184171. {
  184172. int d;
  184173. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  184174. if (d < min_d)
  184175. {
  184176. min_d = d;
  184177. min_k = k;
  184178. }
  184179. }
  184180. /* point to closest color */
  184181. png_ptr->dither_index[i] = (png_byte)min_k;
  184182. }
  184183. }
  184184. }
  184185. png_free(png_ptr, png_ptr->dither_sort);
  184186. png_ptr->dither_sort=NULL;
  184187. }
  184188. else
  184189. {
  184190. /* This is much harder to do simply (and quickly). Perhaps
  184191. we need to go through a median cut routine, but those
  184192. don't always behave themselves with only a few colors
  184193. as input. So we will just find the closest two colors,
  184194. and throw out one of them (chosen somewhat randomly).
  184195. [We don't understand this at all, so if someone wants to
  184196. work on improving it, be our guest - AED, GRP]
  184197. */
  184198. int i;
  184199. int max_d;
  184200. int num_new_palette;
  184201. png_dsortp t;
  184202. png_dsortpp hash;
  184203. t=NULL;
  184204. /* initialize palette index arrays */
  184205. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  184206. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  184207. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  184208. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  184209. /* initialize the sort array */
  184210. for (i = 0; i < num_palette; i++)
  184211. {
  184212. png_ptr->index_to_palette[i] = (png_byte)i;
  184213. png_ptr->palette_to_index[i] = (png_byte)i;
  184214. }
  184215. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  184216. png_sizeof (png_dsortp)));
  184217. for (i = 0; i < 769; i++)
  184218. hash[i] = NULL;
  184219. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  184220. num_new_palette = num_palette;
  184221. /* initial wild guess at how far apart the farthest pixel
  184222. pair we will be eliminating will be. Larger
  184223. numbers mean more areas will be allocated, Smaller
  184224. numbers run the risk of not saving enough data, and
  184225. having to do this all over again.
  184226. I have not done extensive checking on this number.
  184227. */
  184228. max_d = 96;
  184229. while (num_new_palette > maximum_colors)
  184230. {
  184231. for (i = 0; i < num_new_palette - 1; i++)
  184232. {
  184233. int j;
  184234. for (j = i + 1; j < num_new_palette; j++)
  184235. {
  184236. int d;
  184237. d = PNG_COLOR_DIST(palette[i], palette[j]);
  184238. if (d <= max_d)
  184239. {
  184240. t = (png_dsortp)png_malloc_warn(png_ptr,
  184241. (png_uint_32)(png_sizeof(png_dsort)));
  184242. if (t == NULL)
  184243. break;
  184244. t->next = hash[d];
  184245. t->left = (png_byte)i;
  184246. t->right = (png_byte)j;
  184247. hash[d] = t;
  184248. }
  184249. }
  184250. if (t == NULL)
  184251. break;
  184252. }
  184253. if (t != NULL)
  184254. for (i = 0; i <= max_d; i++)
  184255. {
  184256. if (hash[i] != NULL)
  184257. {
  184258. png_dsortp p;
  184259. for (p = hash[i]; p; p = p->next)
  184260. {
  184261. if ((int)png_ptr->index_to_palette[p->left]
  184262. < num_new_palette &&
  184263. (int)png_ptr->index_to_palette[p->right]
  184264. < num_new_palette)
  184265. {
  184266. int j, next_j;
  184267. if (num_new_palette & 0x01)
  184268. {
  184269. j = p->left;
  184270. next_j = p->right;
  184271. }
  184272. else
  184273. {
  184274. j = p->right;
  184275. next_j = p->left;
  184276. }
  184277. num_new_palette--;
  184278. palette[png_ptr->index_to_palette[j]]
  184279. = palette[num_new_palette];
  184280. if (!full_dither)
  184281. {
  184282. int k;
  184283. for (k = 0; k < num_palette; k++)
  184284. {
  184285. if (png_ptr->dither_index[k] ==
  184286. png_ptr->index_to_palette[j])
  184287. png_ptr->dither_index[k] =
  184288. png_ptr->index_to_palette[next_j];
  184289. if ((int)png_ptr->dither_index[k] ==
  184290. num_new_palette)
  184291. png_ptr->dither_index[k] =
  184292. png_ptr->index_to_palette[j];
  184293. }
  184294. }
  184295. png_ptr->index_to_palette[png_ptr->palette_to_index
  184296. [num_new_palette]] = png_ptr->index_to_palette[j];
  184297. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  184298. = png_ptr->palette_to_index[num_new_palette];
  184299. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  184300. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  184301. }
  184302. if (num_new_palette <= maximum_colors)
  184303. break;
  184304. }
  184305. if (num_new_palette <= maximum_colors)
  184306. break;
  184307. }
  184308. }
  184309. for (i = 0; i < 769; i++)
  184310. {
  184311. if (hash[i] != NULL)
  184312. {
  184313. png_dsortp p = hash[i];
  184314. while (p)
  184315. {
  184316. t = p->next;
  184317. png_free(png_ptr, p);
  184318. p = t;
  184319. }
  184320. }
  184321. hash[i] = 0;
  184322. }
  184323. max_d += 96;
  184324. }
  184325. png_free(png_ptr, hash);
  184326. png_free(png_ptr, png_ptr->palette_to_index);
  184327. png_free(png_ptr, png_ptr->index_to_palette);
  184328. png_ptr->palette_to_index=NULL;
  184329. png_ptr->index_to_palette=NULL;
  184330. }
  184331. num_palette = maximum_colors;
  184332. }
  184333. if (png_ptr->palette == NULL)
  184334. {
  184335. png_ptr->palette = palette;
  184336. }
  184337. png_ptr->num_palette = (png_uint_16)num_palette;
  184338. if (full_dither)
  184339. {
  184340. int i;
  184341. png_bytep distance;
  184342. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  184343. PNG_DITHER_BLUE_BITS;
  184344. int num_red = (1 << PNG_DITHER_RED_BITS);
  184345. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  184346. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  184347. png_size_t num_entries = ((png_size_t)1 << total_bits);
  184348. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  184349. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  184350. png_memset(png_ptr->palette_lookup, 0, num_entries *
  184351. png_sizeof (png_byte));
  184352. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  184353. png_sizeof(png_byte)));
  184354. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  184355. for (i = 0; i < num_palette; i++)
  184356. {
  184357. int ir, ig, ib;
  184358. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  184359. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  184360. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  184361. for (ir = 0; ir < num_red; ir++)
  184362. {
  184363. /* int dr = abs(ir - r); */
  184364. int dr = ((ir > r) ? ir - r : r - ir);
  184365. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  184366. for (ig = 0; ig < num_green; ig++)
  184367. {
  184368. /* int dg = abs(ig - g); */
  184369. int dg = ((ig > g) ? ig - g : g - ig);
  184370. int dt = dr + dg;
  184371. int dm = ((dr > dg) ? dr : dg);
  184372. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  184373. for (ib = 0; ib < num_blue; ib++)
  184374. {
  184375. int d_index = index_g | ib;
  184376. /* int db = abs(ib - b); */
  184377. int db = ((ib > b) ? ib - b : b - ib);
  184378. int dmax = ((dm > db) ? dm : db);
  184379. int d = dmax + dt + db;
  184380. if (d < (int)distance[d_index])
  184381. {
  184382. distance[d_index] = (png_byte)d;
  184383. png_ptr->palette_lookup[d_index] = (png_byte)i;
  184384. }
  184385. }
  184386. }
  184387. }
  184388. }
  184389. png_free(png_ptr, distance);
  184390. }
  184391. }
  184392. #endif
  184393. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184394. /* Transform the image from the file_gamma to the screen_gamma. We
  184395. * only do transformations on images where the file_gamma and screen_gamma
  184396. * are not close reciprocals, otherwise it slows things down slightly, and
  184397. * also needlessly introduces small errors.
  184398. *
  184399. * We will turn off gamma transformation later if no semitransparent entries
  184400. * are present in the tRNS array for palette images. We can't do it here
  184401. * because we don't necessarily have the tRNS chunk yet.
  184402. */
  184403. void PNGAPI
  184404. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  184405. {
  184406. png_debug(1, "in png_set_gamma\n");
  184407. if(png_ptr == NULL) return;
  184408. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  184409. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  184410. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  184411. png_ptr->transformations |= PNG_GAMMA;
  184412. png_ptr->gamma = (float)file_gamma;
  184413. png_ptr->screen_gamma = (float)scrn_gamma;
  184414. }
  184415. #endif
  184416. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184417. /* Expand paletted images to RGB, expand grayscale images of
  184418. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  184419. * to alpha channels.
  184420. */
  184421. void PNGAPI
  184422. png_set_expand(png_structp png_ptr)
  184423. {
  184424. png_debug(1, "in png_set_expand\n");
  184425. if(png_ptr == NULL) return;
  184426. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  184427. #ifdef PNG_WARN_UNINITIALIZED_ROW
  184428. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  184429. #endif
  184430. }
  184431. /* GRR 19990627: the following three functions currently are identical
  184432. * to png_set_expand(). However, it is entirely reasonable that someone
  184433. * might wish to expand an indexed image to RGB but *not* expand a single,
  184434. * fully transparent palette entry to a full alpha channel--perhaps instead
  184435. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  184436. * the transparent color with a particular RGB value, or drop tRNS entirely.
  184437. * IOW, a future version of the library may make the transformations flag
  184438. * a bit more fine-grained, with separate bits for each of these three
  184439. * functions.
  184440. *
  184441. * More to the point, these functions make it obvious what libpng will be
  184442. * doing, whereas "expand" can (and does) mean any number of things.
  184443. *
  184444. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  184445. * to expand only the sample depth but not to expand the tRNS to alpha.
  184446. */
  184447. /* Expand paletted images to RGB. */
  184448. void PNGAPI
  184449. png_set_palette_to_rgb(png_structp png_ptr)
  184450. {
  184451. png_debug(1, "in png_set_palette_to_rgb\n");
  184452. if(png_ptr == NULL) return;
  184453. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  184454. #ifdef PNG_WARN_UNINITIALIZED_ROW
  184455. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  184456. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  184457. #endif
  184458. }
  184459. #if !defined(PNG_1_0_X)
  184460. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  184461. void PNGAPI
  184462. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  184463. {
  184464. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  184465. if(png_ptr == NULL) return;
  184466. png_ptr->transformations |= PNG_EXPAND;
  184467. #ifdef PNG_WARN_UNINITIALIZED_ROW
  184468. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  184469. #endif
  184470. }
  184471. #endif
  184472. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184473. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  184474. /* Deprecated as of libpng-1.2.9 */
  184475. void PNGAPI
  184476. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  184477. {
  184478. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  184479. if(png_ptr == NULL) return;
  184480. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  184481. }
  184482. #endif
  184483. /* Expand tRNS chunks to alpha channels. */
  184484. void PNGAPI
  184485. png_set_tRNS_to_alpha(png_structp png_ptr)
  184486. {
  184487. png_debug(1, "in png_set_tRNS_to_alpha\n");
  184488. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  184489. #ifdef PNG_WARN_UNINITIALIZED_ROW
  184490. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  184491. #endif
  184492. }
  184493. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  184494. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184495. void PNGAPI
  184496. png_set_gray_to_rgb(png_structp png_ptr)
  184497. {
  184498. png_debug(1, "in png_set_gray_to_rgb\n");
  184499. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  184500. #ifdef PNG_WARN_UNINITIALIZED_ROW
  184501. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  184502. #endif
  184503. }
  184504. #endif
  184505. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184506. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  184507. /* Convert a RGB image to a grayscale of the same width. This allows us,
  184508. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  184509. */
  184510. void PNGAPI
  184511. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  184512. double green)
  184513. {
  184514. int red_fixed = (int)((float)red*100000.0 + 0.5);
  184515. int green_fixed = (int)((float)green*100000.0 + 0.5);
  184516. if(png_ptr == NULL) return;
  184517. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  184518. }
  184519. #endif
  184520. void PNGAPI
  184521. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  184522. png_fixed_point red, png_fixed_point green)
  184523. {
  184524. png_debug(1, "in png_set_rgb_to_gray\n");
  184525. if(png_ptr == NULL) return;
  184526. switch(error_action)
  184527. {
  184528. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  184529. break;
  184530. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  184531. break;
  184532. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  184533. }
  184534. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  184535. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184536. png_ptr->transformations |= PNG_EXPAND;
  184537. #else
  184538. {
  184539. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  184540. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  184541. }
  184542. #endif
  184543. {
  184544. png_uint_16 red_int, green_int;
  184545. if(red < 0 || green < 0)
  184546. {
  184547. red_int = 6968; /* .212671 * 32768 + .5 */
  184548. green_int = 23434; /* .715160 * 32768 + .5 */
  184549. }
  184550. else if(red + green < 100000L)
  184551. {
  184552. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  184553. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  184554. }
  184555. else
  184556. {
  184557. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  184558. red_int = 6968;
  184559. green_int = 23434;
  184560. }
  184561. png_ptr->rgb_to_gray_red_coeff = red_int;
  184562. png_ptr->rgb_to_gray_green_coeff = green_int;
  184563. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  184564. }
  184565. }
  184566. #endif
  184567. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  184568. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  184569. defined(PNG_LEGACY_SUPPORTED)
  184570. void PNGAPI
  184571. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  184572. read_user_transform_fn)
  184573. {
  184574. png_debug(1, "in png_set_read_user_transform_fn\n");
  184575. if(png_ptr == NULL) return;
  184576. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  184577. png_ptr->transformations |= PNG_USER_TRANSFORM;
  184578. png_ptr->read_user_transform_fn = read_user_transform_fn;
  184579. #endif
  184580. #ifdef PNG_LEGACY_SUPPORTED
  184581. if(read_user_transform_fn)
  184582. png_warning(png_ptr,
  184583. "This version of libpng does not support user transforms");
  184584. #endif
  184585. }
  184586. #endif
  184587. /* Initialize everything needed for the read. This includes modifying
  184588. * the palette.
  184589. */
  184590. void /* PRIVATE */
  184591. png_init_read_transformations(png_structp png_ptr)
  184592. {
  184593. png_debug(1, "in png_init_read_transformations\n");
  184594. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  184595. if(png_ptr != NULL)
  184596. #endif
  184597. {
  184598. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  184599. || defined(PNG_READ_GAMMA_SUPPORTED)
  184600. int color_type = png_ptr->color_type;
  184601. #endif
  184602. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  184603. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184604. /* Detect gray background and attempt to enable optimization
  184605. * for gray --> RGB case */
  184606. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  184607. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  184608. * background color might actually be gray yet not be flagged as such.
  184609. * This is not a problem for the current code, which uses
  184610. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  184611. * png_do_gray_to_rgb() transformation.
  184612. */
  184613. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  184614. !(color_type & PNG_COLOR_MASK_COLOR))
  184615. {
  184616. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  184617. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  184618. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  184619. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  184620. png_ptr->background.red == png_ptr->background.green &&
  184621. png_ptr->background.red == png_ptr->background.blue)
  184622. {
  184623. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  184624. png_ptr->background.gray = png_ptr->background.red;
  184625. }
  184626. #endif
  184627. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  184628. (png_ptr->transformations & PNG_EXPAND))
  184629. {
  184630. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  184631. {
  184632. /* expand background and tRNS chunks */
  184633. switch (png_ptr->bit_depth)
  184634. {
  184635. case 1:
  184636. png_ptr->background.gray *= (png_uint_16)0xff;
  184637. png_ptr->background.red = png_ptr->background.green
  184638. = png_ptr->background.blue = png_ptr->background.gray;
  184639. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  184640. {
  184641. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  184642. png_ptr->trans_values.red = png_ptr->trans_values.green
  184643. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  184644. }
  184645. break;
  184646. case 2:
  184647. png_ptr->background.gray *= (png_uint_16)0x55;
  184648. png_ptr->background.red = png_ptr->background.green
  184649. = png_ptr->background.blue = png_ptr->background.gray;
  184650. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  184651. {
  184652. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  184653. png_ptr->trans_values.red = png_ptr->trans_values.green
  184654. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  184655. }
  184656. break;
  184657. case 4:
  184658. png_ptr->background.gray *= (png_uint_16)0x11;
  184659. png_ptr->background.red = png_ptr->background.green
  184660. = png_ptr->background.blue = png_ptr->background.gray;
  184661. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  184662. {
  184663. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  184664. png_ptr->trans_values.red = png_ptr->trans_values.green
  184665. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  184666. }
  184667. break;
  184668. case 8:
  184669. case 16:
  184670. png_ptr->background.red = png_ptr->background.green
  184671. = png_ptr->background.blue = png_ptr->background.gray;
  184672. break;
  184673. }
  184674. }
  184675. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  184676. {
  184677. png_ptr->background.red =
  184678. png_ptr->palette[png_ptr->background.index].red;
  184679. png_ptr->background.green =
  184680. png_ptr->palette[png_ptr->background.index].green;
  184681. png_ptr->background.blue =
  184682. png_ptr->palette[png_ptr->background.index].blue;
  184683. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184684. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  184685. {
  184686. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184687. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  184688. #endif
  184689. {
  184690. /* invert the alpha channel (in tRNS) unless the pixels are
  184691. going to be expanded, in which case leave it for later */
  184692. int i,istop;
  184693. istop=(int)png_ptr->num_trans;
  184694. for (i=0; i<istop; i++)
  184695. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  184696. }
  184697. }
  184698. #endif
  184699. }
  184700. }
  184701. #endif
  184702. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  184703. png_ptr->background_1 = png_ptr->background;
  184704. #endif
  184705. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184706. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  184707. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  184708. < PNG_GAMMA_THRESHOLD))
  184709. {
  184710. int i,k;
  184711. k=0;
  184712. for (i=0; i<png_ptr->num_trans; i++)
  184713. {
  184714. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  184715. k=1; /* partial transparency is present */
  184716. }
  184717. if (k == 0)
  184718. png_ptr->transformations &= (~PNG_GAMMA);
  184719. }
  184720. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  184721. png_ptr->gamma != 0.0)
  184722. {
  184723. png_build_gamma_table(png_ptr);
  184724. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184725. if (png_ptr->transformations & PNG_BACKGROUND)
  184726. {
  184727. if (color_type == PNG_COLOR_TYPE_PALETTE)
  184728. {
  184729. /* could skip if no transparency and
  184730. */
  184731. png_color back, back_1;
  184732. png_colorp palette = png_ptr->palette;
  184733. int num_palette = png_ptr->num_palette;
  184734. int i;
  184735. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  184736. {
  184737. back.red = png_ptr->gamma_table[png_ptr->background.red];
  184738. back.green = png_ptr->gamma_table[png_ptr->background.green];
  184739. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  184740. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  184741. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  184742. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  184743. }
  184744. else
  184745. {
  184746. double g, gs;
  184747. switch (png_ptr->background_gamma_type)
  184748. {
  184749. case PNG_BACKGROUND_GAMMA_SCREEN:
  184750. g = (png_ptr->screen_gamma);
  184751. gs = 1.0;
  184752. break;
  184753. case PNG_BACKGROUND_GAMMA_FILE:
  184754. g = 1.0 / (png_ptr->gamma);
  184755. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  184756. break;
  184757. case PNG_BACKGROUND_GAMMA_UNIQUE:
  184758. g = 1.0 / (png_ptr->background_gamma);
  184759. gs = 1.0 / (png_ptr->background_gamma *
  184760. png_ptr->screen_gamma);
  184761. break;
  184762. default:
  184763. g = 1.0; /* back_1 */
  184764. gs = 1.0; /* back */
  184765. }
  184766. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  184767. {
  184768. back.red = (png_byte)png_ptr->background.red;
  184769. back.green = (png_byte)png_ptr->background.green;
  184770. back.blue = (png_byte)png_ptr->background.blue;
  184771. }
  184772. else
  184773. {
  184774. back.red = (png_byte)(pow(
  184775. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  184776. back.green = (png_byte)(pow(
  184777. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  184778. back.blue = (png_byte)(pow(
  184779. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  184780. }
  184781. back_1.red = (png_byte)(pow(
  184782. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  184783. back_1.green = (png_byte)(pow(
  184784. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  184785. back_1.blue = (png_byte)(pow(
  184786. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  184787. }
  184788. for (i = 0; i < num_palette; i++)
  184789. {
  184790. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  184791. {
  184792. if (png_ptr->trans[i] == 0)
  184793. {
  184794. palette[i] = back;
  184795. }
  184796. else /* if (png_ptr->trans[i] != 0xff) */
  184797. {
  184798. png_byte v, w;
  184799. v = png_ptr->gamma_to_1[palette[i].red];
  184800. png_composite(w, v, png_ptr->trans[i], back_1.red);
  184801. palette[i].red = png_ptr->gamma_from_1[w];
  184802. v = png_ptr->gamma_to_1[palette[i].green];
  184803. png_composite(w, v, png_ptr->trans[i], back_1.green);
  184804. palette[i].green = png_ptr->gamma_from_1[w];
  184805. v = png_ptr->gamma_to_1[palette[i].blue];
  184806. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  184807. palette[i].blue = png_ptr->gamma_from_1[w];
  184808. }
  184809. }
  184810. else
  184811. {
  184812. palette[i].red = png_ptr->gamma_table[palette[i].red];
  184813. palette[i].green = png_ptr->gamma_table[palette[i].green];
  184814. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  184815. }
  184816. }
  184817. }
  184818. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  184819. else
  184820. /* color_type != PNG_COLOR_TYPE_PALETTE */
  184821. {
  184822. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  184823. double g = 1.0;
  184824. double gs = 1.0;
  184825. switch (png_ptr->background_gamma_type)
  184826. {
  184827. case PNG_BACKGROUND_GAMMA_SCREEN:
  184828. g = (png_ptr->screen_gamma);
  184829. gs = 1.0;
  184830. break;
  184831. case PNG_BACKGROUND_GAMMA_FILE:
  184832. g = 1.0 / (png_ptr->gamma);
  184833. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  184834. break;
  184835. case PNG_BACKGROUND_GAMMA_UNIQUE:
  184836. g = 1.0 / (png_ptr->background_gamma);
  184837. gs = 1.0 / (png_ptr->background_gamma *
  184838. png_ptr->screen_gamma);
  184839. break;
  184840. }
  184841. png_ptr->background_1.gray = (png_uint_16)(pow(
  184842. (double)png_ptr->background.gray / m, g) * m + .5);
  184843. png_ptr->background.gray = (png_uint_16)(pow(
  184844. (double)png_ptr->background.gray / m, gs) * m + .5);
  184845. if ((png_ptr->background.red != png_ptr->background.green) ||
  184846. (png_ptr->background.red != png_ptr->background.blue) ||
  184847. (png_ptr->background.red != png_ptr->background.gray))
  184848. {
  184849. /* RGB or RGBA with color background */
  184850. png_ptr->background_1.red = (png_uint_16)(pow(
  184851. (double)png_ptr->background.red / m, g) * m + .5);
  184852. png_ptr->background_1.green = (png_uint_16)(pow(
  184853. (double)png_ptr->background.green / m, g) * m + .5);
  184854. png_ptr->background_1.blue = (png_uint_16)(pow(
  184855. (double)png_ptr->background.blue / m, g) * m + .5);
  184856. png_ptr->background.red = (png_uint_16)(pow(
  184857. (double)png_ptr->background.red / m, gs) * m + .5);
  184858. png_ptr->background.green = (png_uint_16)(pow(
  184859. (double)png_ptr->background.green / m, gs) * m + .5);
  184860. png_ptr->background.blue = (png_uint_16)(pow(
  184861. (double)png_ptr->background.blue / m, gs) * m + .5);
  184862. }
  184863. else
  184864. {
  184865. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  184866. png_ptr->background_1.red = png_ptr->background_1.green
  184867. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  184868. png_ptr->background.red = png_ptr->background.green
  184869. = png_ptr->background.blue = png_ptr->background.gray;
  184870. }
  184871. }
  184872. }
  184873. else
  184874. /* transformation does not include PNG_BACKGROUND */
  184875. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  184876. if (color_type == PNG_COLOR_TYPE_PALETTE)
  184877. {
  184878. png_colorp palette = png_ptr->palette;
  184879. int num_palette = png_ptr->num_palette;
  184880. int i;
  184881. for (i = 0; i < num_palette; i++)
  184882. {
  184883. palette[i].red = png_ptr->gamma_table[palette[i].red];
  184884. palette[i].green = png_ptr->gamma_table[palette[i].green];
  184885. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  184886. }
  184887. }
  184888. }
  184889. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184890. else
  184891. #endif
  184892. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  184893. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184894. /* No GAMMA transformation */
  184895. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  184896. (color_type == PNG_COLOR_TYPE_PALETTE))
  184897. {
  184898. int i;
  184899. int istop = (int)png_ptr->num_trans;
  184900. png_color back;
  184901. png_colorp palette = png_ptr->palette;
  184902. back.red = (png_byte)png_ptr->background.red;
  184903. back.green = (png_byte)png_ptr->background.green;
  184904. back.blue = (png_byte)png_ptr->background.blue;
  184905. for (i = 0; i < istop; i++)
  184906. {
  184907. if (png_ptr->trans[i] == 0)
  184908. {
  184909. palette[i] = back;
  184910. }
  184911. else if (png_ptr->trans[i] != 0xff)
  184912. {
  184913. /* The png_composite() macro is defined in png.h */
  184914. png_composite(palette[i].red, palette[i].red,
  184915. png_ptr->trans[i], back.red);
  184916. png_composite(palette[i].green, palette[i].green,
  184917. png_ptr->trans[i], back.green);
  184918. png_composite(palette[i].blue, palette[i].blue,
  184919. png_ptr->trans[i], back.blue);
  184920. }
  184921. }
  184922. }
  184923. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  184924. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184925. if ((png_ptr->transformations & PNG_SHIFT) &&
  184926. (color_type == PNG_COLOR_TYPE_PALETTE))
  184927. {
  184928. png_uint_16 i;
  184929. png_uint_16 istop = png_ptr->num_palette;
  184930. int sr = 8 - png_ptr->sig_bit.red;
  184931. int sg = 8 - png_ptr->sig_bit.green;
  184932. int sb = 8 - png_ptr->sig_bit.blue;
  184933. if (sr < 0 || sr > 8)
  184934. sr = 0;
  184935. if (sg < 0 || sg > 8)
  184936. sg = 0;
  184937. if (sb < 0 || sb > 8)
  184938. sb = 0;
  184939. for (i = 0; i < istop; i++)
  184940. {
  184941. png_ptr->palette[i].red >>= sr;
  184942. png_ptr->palette[i].green >>= sg;
  184943. png_ptr->palette[i].blue >>= sb;
  184944. }
  184945. }
  184946. #endif /* PNG_READ_SHIFT_SUPPORTED */
  184947. }
  184948. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  184949. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  184950. if(png_ptr)
  184951. return;
  184952. #endif
  184953. }
  184954. /* Modify the info structure to reflect the transformations. The
  184955. * info should be updated so a PNG file could be written with it,
  184956. * assuming the transformations result in valid PNG data.
  184957. */
  184958. void /* PRIVATE */
  184959. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  184960. {
  184961. png_debug(1, "in png_read_transform_info\n");
  184962. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184963. if (png_ptr->transformations & PNG_EXPAND)
  184964. {
  184965. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  184966. {
  184967. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  184968. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  184969. else
  184970. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  184971. info_ptr->bit_depth = 8;
  184972. info_ptr->num_trans = 0;
  184973. }
  184974. else
  184975. {
  184976. if (png_ptr->num_trans)
  184977. {
  184978. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  184979. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  184980. else
  184981. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  184982. }
  184983. if (info_ptr->bit_depth < 8)
  184984. info_ptr->bit_depth = 8;
  184985. info_ptr->num_trans = 0;
  184986. }
  184987. }
  184988. #endif
  184989. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184990. if (png_ptr->transformations & PNG_BACKGROUND)
  184991. {
  184992. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  184993. info_ptr->num_trans = 0;
  184994. info_ptr->background = png_ptr->background;
  184995. }
  184996. #endif
  184997. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184998. if (png_ptr->transformations & PNG_GAMMA)
  184999. {
  185000. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185001. info_ptr->gamma = png_ptr->gamma;
  185002. #endif
  185003. #ifdef PNG_FIXED_POINT_SUPPORTED
  185004. info_ptr->int_gamma = png_ptr->int_gamma;
  185005. #endif
  185006. }
  185007. #endif
  185008. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185009. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  185010. info_ptr->bit_depth = 8;
  185011. #endif
  185012. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185013. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  185014. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  185015. #endif
  185016. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185017. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  185018. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  185019. #endif
  185020. #if defined(PNG_READ_DITHER_SUPPORTED)
  185021. if (png_ptr->transformations & PNG_DITHER)
  185022. {
  185023. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  185024. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  185025. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  185026. {
  185027. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  185028. }
  185029. }
  185030. #endif
  185031. #if defined(PNG_READ_PACK_SUPPORTED)
  185032. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  185033. info_ptr->bit_depth = 8;
  185034. #endif
  185035. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185036. info_ptr->channels = 1;
  185037. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  185038. info_ptr->channels = 3;
  185039. else
  185040. info_ptr->channels = 1;
  185041. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  185042. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  185043. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  185044. #endif
  185045. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  185046. info_ptr->channels++;
  185047. #if defined(PNG_READ_FILLER_SUPPORTED)
  185048. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  185049. if ((png_ptr->transformations & PNG_FILLER) &&
  185050. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  185051. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  185052. {
  185053. info_ptr->channels++;
  185054. /* if adding a true alpha channel not just filler */
  185055. #if !defined(PNG_1_0_X)
  185056. if (png_ptr->transformations & PNG_ADD_ALPHA)
  185057. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  185058. #endif
  185059. }
  185060. #endif
  185061. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  185062. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  185063. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  185064. {
  185065. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  185066. info_ptr->bit_depth = png_ptr->user_transform_depth;
  185067. if(info_ptr->channels < png_ptr->user_transform_channels)
  185068. info_ptr->channels = png_ptr->user_transform_channels;
  185069. }
  185070. #endif
  185071. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  185072. info_ptr->bit_depth);
  185073. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  185074. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  185075. if(png_ptr)
  185076. return;
  185077. #endif
  185078. }
  185079. /* Transform the row. The order of transformations is significant,
  185080. * and is very touchy. If you add a transformation, take care to
  185081. * decide how it fits in with the other transformations here.
  185082. */
  185083. void /* PRIVATE */
  185084. png_do_read_transformations(png_structp png_ptr)
  185085. {
  185086. png_debug(1, "in png_do_read_transformations\n");
  185087. if (png_ptr->row_buf == NULL)
  185088. {
  185089. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  185090. char msg[50];
  185091. png_snprintf2(msg, 50,
  185092. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  185093. png_ptr->pass);
  185094. png_error(png_ptr, msg);
  185095. #else
  185096. png_error(png_ptr, "NULL row buffer");
  185097. #endif
  185098. }
  185099. #ifdef PNG_WARN_UNINITIALIZED_ROW
  185100. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  185101. /* Application has failed to call either png_read_start_image()
  185102. * or png_read_update_info() after setting transforms that expand
  185103. * pixels. This check added to libpng-1.2.19 */
  185104. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  185105. png_error(png_ptr, "Uninitialized row");
  185106. #else
  185107. png_warning(png_ptr, "Uninitialized row");
  185108. #endif
  185109. #endif
  185110. #if defined(PNG_READ_EXPAND_SUPPORTED)
  185111. if (png_ptr->transformations & PNG_EXPAND)
  185112. {
  185113. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  185114. {
  185115. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185116. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  185117. }
  185118. else
  185119. {
  185120. if (png_ptr->num_trans &&
  185121. (png_ptr->transformations & PNG_EXPAND_tRNS))
  185122. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185123. &(png_ptr->trans_values));
  185124. else
  185125. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185126. NULL);
  185127. }
  185128. }
  185129. #endif
  185130. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  185131. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  185132. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185133. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  185134. #endif
  185135. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185136. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  185137. {
  185138. int rgb_error =
  185139. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  185140. if(rgb_error)
  185141. {
  185142. png_ptr->rgb_to_gray_status=1;
  185143. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  185144. PNG_RGB_TO_GRAY_WARN)
  185145. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  185146. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  185147. PNG_RGB_TO_GRAY_ERR)
  185148. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  185149. }
  185150. }
  185151. #endif
  185152. /*
  185153. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  185154. In most cases, the "simple transparency" should be done prior to doing
  185155. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  185156. pixel is transparent. You would also need to make sure that the
  185157. transparency information is upgraded to RGB.
  185158. To summarize, the current flow is:
  185159. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  185160. with background "in place" if transparent,
  185161. convert to RGB if necessary
  185162. - Gray + alpha -> composite with gray background and remove alpha bytes,
  185163. convert to RGB if necessary
  185164. To support RGB backgrounds for gray images we need:
  185165. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  185166. 3 or 6 bytes and composite with background
  185167. "in place" if transparent (3x compare/pixel
  185168. compared to doing composite with gray bkgrnd)
  185169. - Gray + alpha -> convert to RGB + alpha, composite with background and
  185170. remove alpha bytes (3x float operations/pixel
  185171. compared with composite on gray background)
  185172. Greg's change will do this. The reason it wasn't done before is for
  185173. performance, as this increases the per-pixel operations. If we would check
  185174. in advance if the background was gray or RGB, and position the gray-to-RGB
  185175. transform appropriately, then it would save a lot of work/time.
  185176. */
  185177. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185178. /* if gray -> RGB, do so now only if background is non-gray; else do later
  185179. * for performance reasons */
  185180. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  185181. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  185182. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185183. #endif
  185184. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185185. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  185186. ((png_ptr->num_trans != 0 ) ||
  185187. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  185188. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185189. &(png_ptr->trans_values), &(png_ptr->background)
  185190. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185191. , &(png_ptr->background_1),
  185192. png_ptr->gamma_table, png_ptr->gamma_from_1,
  185193. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  185194. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  185195. png_ptr->gamma_shift
  185196. #endif
  185197. );
  185198. #endif
  185199. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185200. if ((png_ptr->transformations & PNG_GAMMA) &&
  185201. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185202. !((png_ptr->transformations & PNG_BACKGROUND) &&
  185203. ((png_ptr->num_trans != 0) ||
  185204. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  185205. #endif
  185206. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  185207. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185208. png_ptr->gamma_table, png_ptr->gamma_16_table,
  185209. png_ptr->gamma_shift);
  185210. #endif
  185211. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185212. if (png_ptr->transformations & PNG_16_TO_8)
  185213. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185214. #endif
  185215. #if defined(PNG_READ_DITHER_SUPPORTED)
  185216. if (png_ptr->transformations & PNG_DITHER)
  185217. {
  185218. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  185219. png_ptr->palette_lookup, png_ptr->dither_index);
  185220. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  185221. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  185222. }
  185223. #endif
  185224. #if defined(PNG_READ_INVERT_SUPPORTED)
  185225. if (png_ptr->transformations & PNG_INVERT_MONO)
  185226. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185227. #endif
  185228. #if defined(PNG_READ_SHIFT_SUPPORTED)
  185229. if (png_ptr->transformations & PNG_SHIFT)
  185230. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185231. &(png_ptr->shift));
  185232. #endif
  185233. #if defined(PNG_READ_PACK_SUPPORTED)
  185234. if (png_ptr->transformations & PNG_PACK)
  185235. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185236. #endif
  185237. #if defined(PNG_READ_BGR_SUPPORTED)
  185238. if (png_ptr->transformations & PNG_BGR)
  185239. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185240. #endif
  185241. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  185242. if (png_ptr->transformations & PNG_PACKSWAP)
  185243. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185244. #endif
  185245. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185246. /* if gray -> RGB, do so now only if we did not do so above */
  185247. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  185248. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  185249. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185250. #endif
  185251. #if defined(PNG_READ_FILLER_SUPPORTED)
  185252. if (png_ptr->transformations & PNG_FILLER)
  185253. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185254. (png_uint_32)png_ptr->filler, png_ptr->flags);
  185255. #endif
  185256. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  185257. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  185258. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185259. #endif
  185260. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  185261. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  185262. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185263. #endif
  185264. #if defined(PNG_READ_SWAP_SUPPORTED)
  185265. if (png_ptr->transformations & PNG_SWAP_BYTES)
  185266. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185267. #endif
  185268. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  185269. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  185270. {
  185271. if(png_ptr->read_user_transform_fn != NULL)
  185272. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  185273. (png_ptr, /* png_ptr */
  185274. &(png_ptr->row_info), /* row_info: */
  185275. /* png_uint_32 width; width of row */
  185276. /* png_uint_32 rowbytes; number of bytes in row */
  185277. /* png_byte color_type; color type of pixels */
  185278. /* png_byte bit_depth; bit depth of samples */
  185279. /* png_byte channels; number of channels (1-4) */
  185280. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  185281. png_ptr->row_buf + 1); /* start of pixel data for row */
  185282. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  185283. if(png_ptr->user_transform_depth)
  185284. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  185285. if(png_ptr->user_transform_channels)
  185286. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  185287. #endif
  185288. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  185289. png_ptr->row_info.channels);
  185290. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  185291. png_ptr->row_info.width);
  185292. }
  185293. #endif
  185294. }
  185295. #if defined(PNG_READ_PACK_SUPPORTED)
  185296. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  185297. * without changing the actual values. Thus, if you had a row with
  185298. * a bit depth of 1, you would end up with bytes that only contained
  185299. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  185300. * png_do_shift() after this.
  185301. */
  185302. void /* PRIVATE */
  185303. png_do_unpack(png_row_infop row_info, png_bytep row)
  185304. {
  185305. png_debug(1, "in png_do_unpack\n");
  185306. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185307. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  185308. #else
  185309. if (row_info->bit_depth < 8)
  185310. #endif
  185311. {
  185312. png_uint_32 i;
  185313. png_uint_32 row_width=row_info->width;
  185314. switch (row_info->bit_depth)
  185315. {
  185316. case 1:
  185317. {
  185318. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  185319. png_bytep dp = row + (png_size_t)row_width - 1;
  185320. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  185321. for (i = 0; i < row_width; i++)
  185322. {
  185323. *dp = (png_byte)((*sp >> shift) & 0x01);
  185324. if (shift == 7)
  185325. {
  185326. shift = 0;
  185327. sp--;
  185328. }
  185329. else
  185330. shift++;
  185331. dp--;
  185332. }
  185333. break;
  185334. }
  185335. case 2:
  185336. {
  185337. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  185338. png_bytep dp = row + (png_size_t)row_width - 1;
  185339. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  185340. for (i = 0; i < row_width; i++)
  185341. {
  185342. *dp = (png_byte)((*sp >> shift) & 0x03);
  185343. if (shift == 6)
  185344. {
  185345. shift = 0;
  185346. sp--;
  185347. }
  185348. else
  185349. shift += 2;
  185350. dp--;
  185351. }
  185352. break;
  185353. }
  185354. case 4:
  185355. {
  185356. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  185357. png_bytep dp = row + (png_size_t)row_width - 1;
  185358. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  185359. for (i = 0; i < row_width; i++)
  185360. {
  185361. *dp = (png_byte)((*sp >> shift) & 0x0f);
  185362. if (shift == 4)
  185363. {
  185364. shift = 0;
  185365. sp--;
  185366. }
  185367. else
  185368. shift = 4;
  185369. dp--;
  185370. }
  185371. break;
  185372. }
  185373. }
  185374. row_info->bit_depth = 8;
  185375. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  185376. row_info->rowbytes = row_width * row_info->channels;
  185377. }
  185378. }
  185379. #endif
  185380. #if defined(PNG_READ_SHIFT_SUPPORTED)
  185381. /* Reverse the effects of png_do_shift. This routine merely shifts the
  185382. * pixels back to their significant bits values. Thus, if you have
  185383. * a row of bit depth 8, but only 5 are significant, this will shift
  185384. * the values back to 0 through 31.
  185385. */
  185386. void /* PRIVATE */
  185387. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  185388. {
  185389. png_debug(1, "in png_do_unshift\n");
  185390. if (
  185391. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185392. row != NULL && row_info != NULL && sig_bits != NULL &&
  185393. #endif
  185394. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  185395. {
  185396. int shift[4];
  185397. int channels = 0;
  185398. int c;
  185399. png_uint_16 value = 0;
  185400. png_uint_32 row_width = row_info->width;
  185401. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  185402. {
  185403. shift[channels++] = row_info->bit_depth - sig_bits->red;
  185404. shift[channels++] = row_info->bit_depth - sig_bits->green;
  185405. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  185406. }
  185407. else
  185408. {
  185409. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  185410. }
  185411. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  185412. {
  185413. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  185414. }
  185415. for (c = 0; c < channels; c++)
  185416. {
  185417. if (shift[c] <= 0)
  185418. shift[c] = 0;
  185419. else
  185420. value = 1;
  185421. }
  185422. if (!value)
  185423. return;
  185424. switch (row_info->bit_depth)
  185425. {
  185426. case 2:
  185427. {
  185428. png_bytep bp;
  185429. png_uint_32 i;
  185430. png_uint_32 istop = row_info->rowbytes;
  185431. for (bp = row, i = 0; i < istop; i++)
  185432. {
  185433. *bp >>= 1;
  185434. *bp++ &= 0x55;
  185435. }
  185436. break;
  185437. }
  185438. case 4:
  185439. {
  185440. png_bytep bp = row;
  185441. png_uint_32 i;
  185442. png_uint_32 istop = row_info->rowbytes;
  185443. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  185444. (png_byte)((int)0xf >> shift[0]));
  185445. for (i = 0; i < istop; i++)
  185446. {
  185447. *bp >>= shift[0];
  185448. *bp++ &= mask;
  185449. }
  185450. break;
  185451. }
  185452. case 8:
  185453. {
  185454. png_bytep bp = row;
  185455. png_uint_32 i;
  185456. png_uint_32 istop = row_width * channels;
  185457. for (i = 0; i < istop; i++)
  185458. {
  185459. *bp++ >>= shift[i%channels];
  185460. }
  185461. break;
  185462. }
  185463. case 16:
  185464. {
  185465. png_bytep bp = row;
  185466. png_uint_32 i;
  185467. png_uint_32 istop = channels * row_width;
  185468. for (i = 0; i < istop; i++)
  185469. {
  185470. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  185471. value >>= shift[i%channels];
  185472. *bp++ = (png_byte)(value >> 8);
  185473. *bp++ = (png_byte)(value & 0xff);
  185474. }
  185475. break;
  185476. }
  185477. }
  185478. }
  185479. }
  185480. #endif
  185481. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185482. /* chop rows of bit depth 16 down to 8 */
  185483. void /* PRIVATE */
  185484. png_do_chop(png_row_infop row_info, png_bytep row)
  185485. {
  185486. png_debug(1, "in png_do_chop\n");
  185487. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185488. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  185489. #else
  185490. if (row_info->bit_depth == 16)
  185491. #endif
  185492. {
  185493. png_bytep sp = row;
  185494. png_bytep dp = row;
  185495. png_uint_32 i;
  185496. png_uint_32 istop = row_info->width * row_info->channels;
  185497. for (i = 0; i<istop; i++, sp += 2, dp++)
  185498. {
  185499. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  185500. /* This does a more accurate scaling of the 16-bit color
  185501. * value, rather than a simple low-byte truncation.
  185502. *
  185503. * What the ideal calculation should be:
  185504. * *dp = (((((png_uint_32)(*sp) << 8) |
  185505. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  185506. *
  185507. * GRR: no, I think this is what it really should be:
  185508. * *dp = (((((png_uint_32)(*sp) << 8) |
  185509. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  185510. *
  185511. * GRR: here's the exact calculation with shifts:
  185512. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  185513. * *dp = (temp - (temp >> 8)) >> 8;
  185514. *
  185515. * Approximate calculation with shift/add instead of multiply/divide:
  185516. * *dp = ((((png_uint_32)(*sp) << 8) |
  185517. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  185518. *
  185519. * What we actually do to avoid extra shifting and conversion:
  185520. */
  185521. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  185522. #else
  185523. /* Simply discard the low order byte */
  185524. *dp = *sp;
  185525. #endif
  185526. }
  185527. row_info->bit_depth = 8;
  185528. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  185529. row_info->rowbytes = row_info->width * row_info->channels;
  185530. }
  185531. }
  185532. #endif
  185533. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  185534. void /* PRIVATE */
  185535. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  185536. {
  185537. png_debug(1, "in png_do_read_swap_alpha\n");
  185538. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185539. if (row != NULL && row_info != NULL)
  185540. #endif
  185541. {
  185542. png_uint_32 row_width = row_info->width;
  185543. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  185544. {
  185545. /* This converts from RGBA to ARGB */
  185546. if (row_info->bit_depth == 8)
  185547. {
  185548. png_bytep sp = row + row_info->rowbytes;
  185549. png_bytep dp = sp;
  185550. png_byte save;
  185551. png_uint_32 i;
  185552. for (i = 0; i < row_width; i++)
  185553. {
  185554. save = *(--sp);
  185555. *(--dp) = *(--sp);
  185556. *(--dp) = *(--sp);
  185557. *(--dp) = *(--sp);
  185558. *(--dp) = save;
  185559. }
  185560. }
  185561. /* This converts from RRGGBBAA to AARRGGBB */
  185562. else
  185563. {
  185564. png_bytep sp = row + row_info->rowbytes;
  185565. png_bytep dp = sp;
  185566. png_byte save[2];
  185567. png_uint_32 i;
  185568. for (i = 0; i < row_width; i++)
  185569. {
  185570. save[0] = *(--sp);
  185571. save[1] = *(--sp);
  185572. *(--dp) = *(--sp);
  185573. *(--dp) = *(--sp);
  185574. *(--dp) = *(--sp);
  185575. *(--dp) = *(--sp);
  185576. *(--dp) = *(--sp);
  185577. *(--dp) = *(--sp);
  185578. *(--dp) = save[0];
  185579. *(--dp) = save[1];
  185580. }
  185581. }
  185582. }
  185583. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  185584. {
  185585. /* This converts from GA to AG */
  185586. if (row_info->bit_depth == 8)
  185587. {
  185588. png_bytep sp = row + row_info->rowbytes;
  185589. png_bytep dp = sp;
  185590. png_byte save;
  185591. png_uint_32 i;
  185592. for (i = 0; i < row_width; i++)
  185593. {
  185594. save = *(--sp);
  185595. *(--dp) = *(--sp);
  185596. *(--dp) = save;
  185597. }
  185598. }
  185599. /* This converts from GGAA to AAGG */
  185600. else
  185601. {
  185602. png_bytep sp = row + row_info->rowbytes;
  185603. png_bytep dp = sp;
  185604. png_byte save[2];
  185605. png_uint_32 i;
  185606. for (i = 0; i < row_width; i++)
  185607. {
  185608. save[0] = *(--sp);
  185609. save[1] = *(--sp);
  185610. *(--dp) = *(--sp);
  185611. *(--dp) = *(--sp);
  185612. *(--dp) = save[0];
  185613. *(--dp) = save[1];
  185614. }
  185615. }
  185616. }
  185617. }
  185618. }
  185619. #endif
  185620. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  185621. void /* PRIVATE */
  185622. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  185623. {
  185624. png_debug(1, "in png_do_read_invert_alpha\n");
  185625. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185626. if (row != NULL && row_info != NULL)
  185627. #endif
  185628. {
  185629. png_uint_32 row_width = row_info->width;
  185630. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  185631. {
  185632. /* This inverts the alpha channel in RGBA */
  185633. if (row_info->bit_depth == 8)
  185634. {
  185635. png_bytep sp = row + row_info->rowbytes;
  185636. png_bytep dp = sp;
  185637. png_uint_32 i;
  185638. for (i = 0; i < row_width; i++)
  185639. {
  185640. *(--dp) = (png_byte)(255 - *(--sp));
  185641. /* This does nothing:
  185642. *(--dp) = *(--sp);
  185643. *(--dp) = *(--sp);
  185644. *(--dp) = *(--sp);
  185645. We can replace it with:
  185646. */
  185647. sp-=3;
  185648. dp=sp;
  185649. }
  185650. }
  185651. /* This inverts the alpha channel in RRGGBBAA */
  185652. else
  185653. {
  185654. png_bytep sp = row + row_info->rowbytes;
  185655. png_bytep dp = sp;
  185656. png_uint_32 i;
  185657. for (i = 0; i < row_width; i++)
  185658. {
  185659. *(--dp) = (png_byte)(255 - *(--sp));
  185660. *(--dp) = (png_byte)(255 - *(--sp));
  185661. /* This does nothing:
  185662. *(--dp) = *(--sp);
  185663. *(--dp) = *(--sp);
  185664. *(--dp) = *(--sp);
  185665. *(--dp) = *(--sp);
  185666. *(--dp) = *(--sp);
  185667. *(--dp) = *(--sp);
  185668. We can replace it with:
  185669. */
  185670. sp-=6;
  185671. dp=sp;
  185672. }
  185673. }
  185674. }
  185675. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  185676. {
  185677. /* This inverts the alpha channel in GA */
  185678. if (row_info->bit_depth == 8)
  185679. {
  185680. png_bytep sp = row + row_info->rowbytes;
  185681. png_bytep dp = sp;
  185682. png_uint_32 i;
  185683. for (i = 0; i < row_width; i++)
  185684. {
  185685. *(--dp) = (png_byte)(255 - *(--sp));
  185686. *(--dp) = *(--sp);
  185687. }
  185688. }
  185689. /* This inverts the alpha channel in GGAA */
  185690. else
  185691. {
  185692. png_bytep sp = row + row_info->rowbytes;
  185693. png_bytep dp = sp;
  185694. png_uint_32 i;
  185695. for (i = 0; i < row_width; i++)
  185696. {
  185697. *(--dp) = (png_byte)(255 - *(--sp));
  185698. *(--dp) = (png_byte)(255 - *(--sp));
  185699. /*
  185700. *(--dp) = *(--sp);
  185701. *(--dp) = *(--sp);
  185702. */
  185703. sp-=2;
  185704. dp=sp;
  185705. }
  185706. }
  185707. }
  185708. }
  185709. }
  185710. #endif
  185711. #if defined(PNG_READ_FILLER_SUPPORTED)
  185712. /* Add filler channel if we have RGB color */
  185713. void /* PRIVATE */
  185714. png_do_read_filler(png_row_infop row_info, png_bytep row,
  185715. png_uint_32 filler, png_uint_32 flags)
  185716. {
  185717. png_uint_32 i;
  185718. png_uint_32 row_width = row_info->width;
  185719. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  185720. png_byte lo_filler = (png_byte)(filler & 0xff);
  185721. png_debug(1, "in png_do_read_filler\n");
  185722. if (
  185723. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185724. row != NULL && row_info != NULL &&
  185725. #endif
  185726. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  185727. {
  185728. if(row_info->bit_depth == 8)
  185729. {
  185730. /* This changes the data from G to GX */
  185731. if (flags & PNG_FLAG_FILLER_AFTER)
  185732. {
  185733. png_bytep sp = row + (png_size_t)row_width;
  185734. png_bytep dp = sp + (png_size_t)row_width;
  185735. for (i = 1; i < row_width; i++)
  185736. {
  185737. *(--dp) = lo_filler;
  185738. *(--dp) = *(--sp);
  185739. }
  185740. *(--dp) = lo_filler;
  185741. row_info->channels = 2;
  185742. row_info->pixel_depth = 16;
  185743. row_info->rowbytes = row_width * 2;
  185744. }
  185745. /* This changes the data from G to XG */
  185746. else
  185747. {
  185748. png_bytep sp = row + (png_size_t)row_width;
  185749. png_bytep dp = sp + (png_size_t)row_width;
  185750. for (i = 0; i < row_width; i++)
  185751. {
  185752. *(--dp) = *(--sp);
  185753. *(--dp) = lo_filler;
  185754. }
  185755. row_info->channels = 2;
  185756. row_info->pixel_depth = 16;
  185757. row_info->rowbytes = row_width * 2;
  185758. }
  185759. }
  185760. else if(row_info->bit_depth == 16)
  185761. {
  185762. /* This changes the data from GG to GGXX */
  185763. if (flags & PNG_FLAG_FILLER_AFTER)
  185764. {
  185765. png_bytep sp = row + (png_size_t)row_width * 2;
  185766. png_bytep dp = sp + (png_size_t)row_width * 2;
  185767. for (i = 1; i < row_width; i++)
  185768. {
  185769. *(--dp) = hi_filler;
  185770. *(--dp) = lo_filler;
  185771. *(--dp) = *(--sp);
  185772. *(--dp) = *(--sp);
  185773. }
  185774. *(--dp) = hi_filler;
  185775. *(--dp) = lo_filler;
  185776. row_info->channels = 2;
  185777. row_info->pixel_depth = 32;
  185778. row_info->rowbytes = row_width * 4;
  185779. }
  185780. /* This changes the data from GG to XXGG */
  185781. else
  185782. {
  185783. png_bytep sp = row + (png_size_t)row_width * 2;
  185784. png_bytep dp = sp + (png_size_t)row_width * 2;
  185785. for (i = 0; i < row_width; i++)
  185786. {
  185787. *(--dp) = *(--sp);
  185788. *(--dp) = *(--sp);
  185789. *(--dp) = hi_filler;
  185790. *(--dp) = lo_filler;
  185791. }
  185792. row_info->channels = 2;
  185793. row_info->pixel_depth = 32;
  185794. row_info->rowbytes = row_width * 4;
  185795. }
  185796. }
  185797. } /* COLOR_TYPE == GRAY */
  185798. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  185799. {
  185800. if(row_info->bit_depth == 8)
  185801. {
  185802. /* This changes the data from RGB to RGBX */
  185803. if (flags & PNG_FLAG_FILLER_AFTER)
  185804. {
  185805. png_bytep sp = row + (png_size_t)row_width * 3;
  185806. png_bytep dp = sp + (png_size_t)row_width;
  185807. for (i = 1; i < row_width; i++)
  185808. {
  185809. *(--dp) = lo_filler;
  185810. *(--dp) = *(--sp);
  185811. *(--dp) = *(--sp);
  185812. *(--dp) = *(--sp);
  185813. }
  185814. *(--dp) = lo_filler;
  185815. row_info->channels = 4;
  185816. row_info->pixel_depth = 32;
  185817. row_info->rowbytes = row_width * 4;
  185818. }
  185819. /* This changes the data from RGB to XRGB */
  185820. else
  185821. {
  185822. png_bytep sp = row + (png_size_t)row_width * 3;
  185823. png_bytep dp = sp + (png_size_t)row_width;
  185824. for (i = 0; i < row_width; i++)
  185825. {
  185826. *(--dp) = *(--sp);
  185827. *(--dp) = *(--sp);
  185828. *(--dp) = *(--sp);
  185829. *(--dp) = lo_filler;
  185830. }
  185831. row_info->channels = 4;
  185832. row_info->pixel_depth = 32;
  185833. row_info->rowbytes = row_width * 4;
  185834. }
  185835. }
  185836. else if(row_info->bit_depth == 16)
  185837. {
  185838. /* This changes the data from RRGGBB to RRGGBBXX */
  185839. if (flags & PNG_FLAG_FILLER_AFTER)
  185840. {
  185841. png_bytep sp = row + (png_size_t)row_width * 6;
  185842. png_bytep dp = sp + (png_size_t)row_width * 2;
  185843. for (i = 1; i < row_width; i++)
  185844. {
  185845. *(--dp) = hi_filler;
  185846. *(--dp) = lo_filler;
  185847. *(--dp) = *(--sp);
  185848. *(--dp) = *(--sp);
  185849. *(--dp) = *(--sp);
  185850. *(--dp) = *(--sp);
  185851. *(--dp) = *(--sp);
  185852. *(--dp) = *(--sp);
  185853. }
  185854. *(--dp) = hi_filler;
  185855. *(--dp) = lo_filler;
  185856. row_info->channels = 4;
  185857. row_info->pixel_depth = 64;
  185858. row_info->rowbytes = row_width * 8;
  185859. }
  185860. /* This changes the data from RRGGBB to XXRRGGBB */
  185861. else
  185862. {
  185863. png_bytep sp = row + (png_size_t)row_width * 6;
  185864. png_bytep dp = sp + (png_size_t)row_width * 2;
  185865. for (i = 0; i < row_width; i++)
  185866. {
  185867. *(--dp) = *(--sp);
  185868. *(--dp) = *(--sp);
  185869. *(--dp) = *(--sp);
  185870. *(--dp) = *(--sp);
  185871. *(--dp) = *(--sp);
  185872. *(--dp) = *(--sp);
  185873. *(--dp) = hi_filler;
  185874. *(--dp) = lo_filler;
  185875. }
  185876. row_info->channels = 4;
  185877. row_info->pixel_depth = 64;
  185878. row_info->rowbytes = row_width * 8;
  185879. }
  185880. }
  185881. } /* COLOR_TYPE == RGB */
  185882. }
  185883. #endif
  185884. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185885. /* expand grayscale files to RGB, with or without alpha */
  185886. void /* PRIVATE */
  185887. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  185888. {
  185889. png_uint_32 i;
  185890. png_uint_32 row_width = row_info->width;
  185891. png_debug(1, "in png_do_gray_to_rgb\n");
  185892. if (row_info->bit_depth >= 8 &&
  185893. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185894. row != NULL && row_info != NULL &&
  185895. #endif
  185896. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  185897. {
  185898. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  185899. {
  185900. if (row_info->bit_depth == 8)
  185901. {
  185902. png_bytep sp = row + (png_size_t)row_width - 1;
  185903. png_bytep dp = sp + (png_size_t)row_width * 2;
  185904. for (i = 0; i < row_width; i++)
  185905. {
  185906. *(dp--) = *sp;
  185907. *(dp--) = *sp;
  185908. *(dp--) = *(sp--);
  185909. }
  185910. }
  185911. else
  185912. {
  185913. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  185914. png_bytep dp = sp + (png_size_t)row_width * 4;
  185915. for (i = 0; i < row_width; i++)
  185916. {
  185917. *(dp--) = *sp;
  185918. *(dp--) = *(sp - 1);
  185919. *(dp--) = *sp;
  185920. *(dp--) = *(sp - 1);
  185921. *(dp--) = *(sp--);
  185922. *(dp--) = *(sp--);
  185923. }
  185924. }
  185925. }
  185926. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  185927. {
  185928. if (row_info->bit_depth == 8)
  185929. {
  185930. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  185931. png_bytep dp = sp + (png_size_t)row_width * 2;
  185932. for (i = 0; i < row_width; i++)
  185933. {
  185934. *(dp--) = *(sp--);
  185935. *(dp--) = *sp;
  185936. *(dp--) = *sp;
  185937. *(dp--) = *(sp--);
  185938. }
  185939. }
  185940. else
  185941. {
  185942. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  185943. png_bytep dp = sp + (png_size_t)row_width * 4;
  185944. for (i = 0; i < row_width; i++)
  185945. {
  185946. *(dp--) = *(sp--);
  185947. *(dp--) = *(sp--);
  185948. *(dp--) = *sp;
  185949. *(dp--) = *(sp - 1);
  185950. *(dp--) = *sp;
  185951. *(dp--) = *(sp - 1);
  185952. *(dp--) = *(sp--);
  185953. *(dp--) = *(sp--);
  185954. }
  185955. }
  185956. }
  185957. row_info->channels += (png_byte)2;
  185958. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  185959. row_info->pixel_depth = (png_byte)(row_info->channels *
  185960. row_info->bit_depth);
  185961. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  185962. }
  185963. }
  185964. #endif
  185965. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185966. /* reduce RGB files to grayscale, with or without alpha
  185967. * using the equation given in Poynton's ColorFAQ at
  185968. * <http://www.inforamp.net/~poynton/>
  185969. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  185970. *
  185971. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  185972. *
  185973. * We approximate this with
  185974. *
  185975. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  185976. *
  185977. * which can be expressed with integers as
  185978. *
  185979. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  185980. *
  185981. * The calculation is to be done in a linear colorspace.
  185982. *
  185983. * Other integer coefficents can be used via png_set_rgb_to_gray().
  185984. */
  185985. int /* PRIVATE */
  185986. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  185987. {
  185988. png_uint_32 i;
  185989. png_uint_32 row_width = row_info->width;
  185990. int rgb_error = 0;
  185991. png_debug(1, "in png_do_rgb_to_gray\n");
  185992. if (
  185993. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185994. row != NULL && row_info != NULL &&
  185995. #endif
  185996. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  185997. {
  185998. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  185999. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  186000. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  186001. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  186002. {
  186003. if (row_info->bit_depth == 8)
  186004. {
  186005. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  186006. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  186007. {
  186008. png_bytep sp = row;
  186009. png_bytep dp = row;
  186010. for (i = 0; i < row_width; i++)
  186011. {
  186012. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  186013. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  186014. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  186015. if(red != green || red != blue)
  186016. {
  186017. rgb_error |= 1;
  186018. *(dp++) = png_ptr->gamma_from_1[
  186019. (rc*red+gc*green+bc*blue)>>15];
  186020. }
  186021. else
  186022. *(dp++) = *(sp-1);
  186023. }
  186024. }
  186025. else
  186026. #endif
  186027. {
  186028. png_bytep sp = row;
  186029. png_bytep dp = row;
  186030. for (i = 0; i < row_width; i++)
  186031. {
  186032. png_byte red = *(sp++);
  186033. png_byte green = *(sp++);
  186034. png_byte blue = *(sp++);
  186035. if(red != green || red != blue)
  186036. {
  186037. rgb_error |= 1;
  186038. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  186039. }
  186040. else
  186041. *(dp++) = *(sp-1);
  186042. }
  186043. }
  186044. }
  186045. else /* RGB bit_depth == 16 */
  186046. {
  186047. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  186048. if (png_ptr->gamma_16_to_1 != NULL &&
  186049. png_ptr->gamma_16_from_1 != NULL)
  186050. {
  186051. png_bytep sp = row;
  186052. png_bytep dp = row;
  186053. for (i = 0; i < row_width; i++)
  186054. {
  186055. png_uint_16 red, green, blue, w;
  186056. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186057. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186058. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186059. if(red == green && red == blue)
  186060. w = red;
  186061. else
  186062. {
  186063. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  186064. png_ptr->gamma_shift][red>>8];
  186065. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  186066. png_ptr->gamma_shift][green>>8];
  186067. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  186068. png_ptr->gamma_shift][blue>>8];
  186069. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  186070. + bc*blue_1)>>15);
  186071. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  186072. png_ptr->gamma_shift][gray16 >> 8];
  186073. rgb_error |= 1;
  186074. }
  186075. *(dp++) = (png_byte)((w>>8) & 0xff);
  186076. *(dp++) = (png_byte)(w & 0xff);
  186077. }
  186078. }
  186079. else
  186080. #endif
  186081. {
  186082. png_bytep sp = row;
  186083. png_bytep dp = row;
  186084. for (i = 0; i < row_width; i++)
  186085. {
  186086. png_uint_16 red, green, blue, gray16;
  186087. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186088. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186089. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186090. if(red != green || red != blue)
  186091. rgb_error |= 1;
  186092. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  186093. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  186094. *(dp++) = (png_byte)(gray16 & 0xff);
  186095. }
  186096. }
  186097. }
  186098. }
  186099. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  186100. {
  186101. if (row_info->bit_depth == 8)
  186102. {
  186103. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  186104. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  186105. {
  186106. png_bytep sp = row;
  186107. png_bytep dp = row;
  186108. for (i = 0; i < row_width; i++)
  186109. {
  186110. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  186111. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  186112. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  186113. if(red != green || red != blue)
  186114. rgb_error |= 1;
  186115. *(dp++) = png_ptr->gamma_from_1
  186116. [(rc*red + gc*green + bc*blue)>>15];
  186117. *(dp++) = *(sp++); /* alpha */
  186118. }
  186119. }
  186120. else
  186121. #endif
  186122. {
  186123. png_bytep sp = row;
  186124. png_bytep dp = row;
  186125. for (i = 0; i < row_width; i++)
  186126. {
  186127. png_byte red = *(sp++);
  186128. png_byte green = *(sp++);
  186129. png_byte blue = *(sp++);
  186130. if(red != green || red != blue)
  186131. rgb_error |= 1;
  186132. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  186133. *(dp++) = *(sp++); /* alpha */
  186134. }
  186135. }
  186136. }
  186137. else /* RGBA bit_depth == 16 */
  186138. {
  186139. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  186140. if (png_ptr->gamma_16_to_1 != NULL &&
  186141. png_ptr->gamma_16_from_1 != NULL)
  186142. {
  186143. png_bytep sp = row;
  186144. png_bytep dp = row;
  186145. for (i = 0; i < row_width; i++)
  186146. {
  186147. png_uint_16 red, green, blue, w;
  186148. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186149. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186150. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186151. if(red == green && red == blue)
  186152. w = red;
  186153. else
  186154. {
  186155. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  186156. png_ptr->gamma_shift][red>>8];
  186157. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  186158. png_ptr->gamma_shift][green>>8];
  186159. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  186160. png_ptr->gamma_shift][blue>>8];
  186161. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  186162. + gc * green_1 + bc * blue_1)>>15);
  186163. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  186164. png_ptr->gamma_shift][gray16 >> 8];
  186165. rgb_error |= 1;
  186166. }
  186167. *(dp++) = (png_byte)((w>>8) & 0xff);
  186168. *(dp++) = (png_byte)(w & 0xff);
  186169. *(dp++) = *(sp++); /* alpha */
  186170. *(dp++) = *(sp++);
  186171. }
  186172. }
  186173. else
  186174. #endif
  186175. {
  186176. png_bytep sp = row;
  186177. png_bytep dp = row;
  186178. for (i = 0; i < row_width; i++)
  186179. {
  186180. png_uint_16 red, green, blue, gray16;
  186181. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  186182. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  186183. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  186184. if(red != green || red != blue)
  186185. rgb_error |= 1;
  186186. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  186187. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  186188. *(dp++) = (png_byte)(gray16 & 0xff);
  186189. *(dp++) = *(sp++); /* alpha */
  186190. *(dp++) = *(sp++);
  186191. }
  186192. }
  186193. }
  186194. }
  186195. row_info->channels -= (png_byte)2;
  186196. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  186197. row_info->pixel_depth = (png_byte)(row_info->channels *
  186198. row_info->bit_depth);
  186199. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  186200. }
  186201. return rgb_error;
  186202. }
  186203. #endif
  186204. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  186205. * large of png_color. This lets grayscale images be treated as
  186206. * paletted. Most useful for gamma correction and simplification
  186207. * of code.
  186208. */
  186209. void PNGAPI
  186210. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  186211. {
  186212. int num_palette;
  186213. int color_inc;
  186214. int i;
  186215. int v;
  186216. png_debug(1, "in png_do_build_grayscale_palette\n");
  186217. if (palette == NULL)
  186218. return;
  186219. switch (bit_depth)
  186220. {
  186221. case 1:
  186222. num_palette = 2;
  186223. color_inc = 0xff;
  186224. break;
  186225. case 2:
  186226. num_palette = 4;
  186227. color_inc = 0x55;
  186228. break;
  186229. case 4:
  186230. num_palette = 16;
  186231. color_inc = 0x11;
  186232. break;
  186233. case 8:
  186234. num_palette = 256;
  186235. color_inc = 1;
  186236. break;
  186237. default:
  186238. num_palette = 0;
  186239. color_inc = 0;
  186240. break;
  186241. }
  186242. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  186243. {
  186244. palette[i].red = (png_byte)v;
  186245. palette[i].green = (png_byte)v;
  186246. palette[i].blue = (png_byte)v;
  186247. }
  186248. }
  186249. /* This function is currently unused. Do we really need it? */
  186250. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  186251. void /* PRIVATE */
  186252. png_correct_palette(png_structp png_ptr, png_colorp palette,
  186253. int num_palette)
  186254. {
  186255. png_debug(1, "in png_correct_palette\n");
  186256. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  186257. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186258. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  186259. {
  186260. png_color back, back_1;
  186261. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  186262. {
  186263. back.red = png_ptr->gamma_table[png_ptr->background.red];
  186264. back.green = png_ptr->gamma_table[png_ptr->background.green];
  186265. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  186266. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  186267. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  186268. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  186269. }
  186270. else
  186271. {
  186272. double g;
  186273. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  186274. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  186275. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  186276. {
  186277. back.red = png_ptr->background.red;
  186278. back.green = png_ptr->background.green;
  186279. back.blue = png_ptr->background.blue;
  186280. }
  186281. else
  186282. {
  186283. back.red =
  186284. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  186285. 255.0 + 0.5);
  186286. back.green =
  186287. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  186288. 255.0 + 0.5);
  186289. back.blue =
  186290. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  186291. 255.0 + 0.5);
  186292. }
  186293. g = 1.0 / png_ptr->background_gamma;
  186294. back_1.red =
  186295. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  186296. 255.0 + 0.5);
  186297. back_1.green =
  186298. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  186299. 255.0 + 0.5);
  186300. back_1.blue =
  186301. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  186302. 255.0 + 0.5);
  186303. }
  186304. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186305. {
  186306. png_uint_32 i;
  186307. for (i = 0; i < (png_uint_32)num_palette; i++)
  186308. {
  186309. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  186310. {
  186311. palette[i] = back;
  186312. }
  186313. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  186314. {
  186315. png_byte v, w;
  186316. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  186317. png_composite(w, v, png_ptr->trans[i], back_1.red);
  186318. palette[i].red = png_ptr->gamma_from_1[w];
  186319. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  186320. png_composite(w, v, png_ptr->trans[i], back_1.green);
  186321. palette[i].green = png_ptr->gamma_from_1[w];
  186322. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  186323. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  186324. palette[i].blue = png_ptr->gamma_from_1[w];
  186325. }
  186326. else
  186327. {
  186328. palette[i].red = png_ptr->gamma_table[palette[i].red];
  186329. palette[i].green = png_ptr->gamma_table[palette[i].green];
  186330. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  186331. }
  186332. }
  186333. }
  186334. else
  186335. {
  186336. int i;
  186337. for (i = 0; i < num_palette; i++)
  186338. {
  186339. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  186340. {
  186341. palette[i] = back;
  186342. }
  186343. else
  186344. {
  186345. palette[i].red = png_ptr->gamma_table[palette[i].red];
  186346. palette[i].green = png_ptr->gamma_table[palette[i].green];
  186347. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  186348. }
  186349. }
  186350. }
  186351. }
  186352. else
  186353. #endif
  186354. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186355. if (png_ptr->transformations & PNG_GAMMA)
  186356. {
  186357. int i;
  186358. for (i = 0; i < num_palette; i++)
  186359. {
  186360. palette[i].red = png_ptr->gamma_table[palette[i].red];
  186361. palette[i].green = png_ptr->gamma_table[palette[i].green];
  186362. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  186363. }
  186364. }
  186365. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186366. else
  186367. #endif
  186368. #endif
  186369. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186370. if (png_ptr->transformations & PNG_BACKGROUND)
  186371. {
  186372. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186373. {
  186374. png_color back;
  186375. back.red = (png_byte)png_ptr->background.red;
  186376. back.green = (png_byte)png_ptr->background.green;
  186377. back.blue = (png_byte)png_ptr->background.blue;
  186378. for (i = 0; i < (int)png_ptr->num_trans; i++)
  186379. {
  186380. if (png_ptr->trans[i] == 0)
  186381. {
  186382. palette[i].red = back.red;
  186383. palette[i].green = back.green;
  186384. palette[i].blue = back.blue;
  186385. }
  186386. else if (png_ptr->trans[i] != 0xff)
  186387. {
  186388. png_composite(palette[i].red, png_ptr->palette[i].red,
  186389. png_ptr->trans[i], back.red);
  186390. png_composite(palette[i].green, png_ptr->palette[i].green,
  186391. png_ptr->trans[i], back.green);
  186392. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  186393. png_ptr->trans[i], back.blue);
  186394. }
  186395. }
  186396. }
  186397. else /* assume grayscale palette (what else could it be?) */
  186398. {
  186399. int i;
  186400. for (i = 0; i < num_palette; i++)
  186401. {
  186402. if (i == (png_byte)png_ptr->trans_values.gray)
  186403. {
  186404. palette[i].red = (png_byte)png_ptr->background.red;
  186405. palette[i].green = (png_byte)png_ptr->background.green;
  186406. palette[i].blue = (png_byte)png_ptr->background.blue;
  186407. }
  186408. }
  186409. }
  186410. }
  186411. #endif
  186412. }
  186413. #endif
  186414. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186415. /* Replace any alpha or transparency with the supplied background color.
  186416. * "background" is already in the screen gamma, while "background_1" is
  186417. * at a gamma of 1.0. Paletted files have already been taken care of.
  186418. */
  186419. void /* PRIVATE */
  186420. png_do_background(png_row_infop row_info, png_bytep row,
  186421. png_color_16p trans_values, png_color_16p background
  186422. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186423. , png_color_16p background_1,
  186424. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  186425. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  186426. png_uint_16pp gamma_16_to_1, int gamma_shift
  186427. #endif
  186428. )
  186429. {
  186430. png_bytep sp, dp;
  186431. png_uint_32 i;
  186432. png_uint_32 row_width=row_info->width;
  186433. int shift;
  186434. png_debug(1, "in png_do_background\n");
  186435. if (background != NULL &&
  186436. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186437. row != NULL && row_info != NULL &&
  186438. #endif
  186439. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  186440. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  186441. {
  186442. switch (row_info->color_type)
  186443. {
  186444. case PNG_COLOR_TYPE_GRAY:
  186445. {
  186446. switch (row_info->bit_depth)
  186447. {
  186448. case 1:
  186449. {
  186450. sp = row;
  186451. shift = 7;
  186452. for (i = 0; i < row_width; i++)
  186453. {
  186454. if ((png_uint_16)((*sp >> shift) & 0x01)
  186455. == trans_values->gray)
  186456. {
  186457. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  186458. *sp |= (png_byte)(background->gray << shift);
  186459. }
  186460. if (!shift)
  186461. {
  186462. shift = 7;
  186463. sp++;
  186464. }
  186465. else
  186466. shift--;
  186467. }
  186468. break;
  186469. }
  186470. case 2:
  186471. {
  186472. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186473. if (gamma_table != NULL)
  186474. {
  186475. sp = row;
  186476. shift = 6;
  186477. for (i = 0; i < row_width; i++)
  186478. {
  186479. if ((png_uint_16)((*sp >> shift) & 0x03)
  186480. == trans_values->gray)
  186481. {
  186482. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  186483. *sp |= (png_byte)(background->gray << shift);
  186484. }
  186485. else
  186486. {
  186487. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  186488. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  186489. (p << 4) | (p << 6)] >> 6) & 0x03);
  186490. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  186491. *sp |= (png_byte)(g << shift);
  186492. }
  186493. if (!shift)
  186494. {
  186495. shift = 6;
  186496. sp++;
  186497. }
  186498. else
  186499. shift -= 2;
  186500. }
  186501. }
  186502. else
  186503. #endif
  186504. {
  186505. sp = row;
  186506. shift = 6;
  186507. for (i = 0; i < row_width; i++)
  186508. {
  186509. if ((png_uint_16)((*sp >> shift) & 0x03)
  186510. == trans_values->gray)
  186511. {
  186512. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  186513. *sp |= (png_byte)(background->gray << shift);
  186514. }
  186515. if (!shift)
  186516. {
  186517. shift = 6;
  186518. sp++;
  186519. }
  186520. else
  186521. shift -= 2;
  186522. }
  186523. }
  186524. break;
  186525. }
  186526. case 4:
  186527. {
  186528. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186529. if (gamma_table != NULL)
  186530. {
  186531. sp = row;
  186532. shift = 4;
  186533. for (i = 0; i < row_width; i++)
  186534. {
  186535. if ((png_uint_16)((*sp >> shift) & 0x0f)
  186536. == trans_values->gray)
  186537. {
  186538. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  186539. *sp |= (png_byte)(background->gray << shift);
  186540. }
  186541. else
  186542. {
  186543. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  186544. png_byte g = (png_byte)((gamma_table[p |
  186545. (p << 4)] >> 4) & 0x0f);
  186546. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  186547. *sp |= (png_byte)(g << shift);
  186548. }
  186549. if (!shift)
  186550. {
  186551. shift = 4;
  186552. sp++;
  186553. }
  186554. else
  186555. shift -= 4;
  186556. }
  186557. }
  186558. else
  186559. #endif
  186560. {
  186561. sp = row;
  186562. shift = 4;
  186563. for (i = 0; i < row_width; i++)
  186564. {
  186565. if ((png_uint_16)((*sp >> shift) & 0x0f)
  186566. == trans_values->gray)
  186567. {
  186568. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  186569. *sp |= (png_byte)(background->gray << shift);
  186570. }
  186571. if (!shift)
  186572. {
  186573. shift = 4;
  186574. sp++;
  186575. }
  186576. else
  186577. shift -= 4;
  186578. }
  186579. }
  186580. break;
  186581. }
  186582. case 8:
  186583. {
  186584. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186585. if (gamma_table != NULL)
  186586. {
  186587. sp = row;
  186588. for (i = 0; i < row_width; i++, sp++)
  186589. {
  186590. if (*sp == trans_values->gray)
  186591. {
  186592. *sp = (png_byte)background->gray;
  186593. }
  186594. else
  186595. {
  186596. *sp = gamma_table[*sp];
  186597. }
  186598. }
  186599. }
  186600. else
  186601. #endif
  186602. {
  186603. sp = row;
  186604. for (i = 0; i < row_width; i++, sp++)
  186605. {
  186606. if (*sp == trans_values->gray)
  186607. {
  186608. *sp = (png_byte)background->gray;
  186609. }
  186610. }
  186611. }
  186612. break;
  186613. }
  186614. case 16:
  186615. {
  186616. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186617. if (gamma_16 != NULL)
  186618. {
  186619. sp = row;
  186620. for (i = 0; i < row_width; i++, sp += 2)
  186621. {
  186622. png_uint_16 v;
  186623. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186624. if (v == trans_values->gray)
  186625. {
  186626. /* background is already in screen gamma */
  186627. *sp = (png_byte)((background->gray >> 8) & 0xff);
  186628. *(sp + 1) = (png_byte)(background->gray & 0xff);
  186629. }
  186630. else
  186631. {
  186632. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  186633. *sp = (png_byte)((v >> 8) & 0xff);
  186634. *(sp + 1) = (png_byte)(v & 0xff);
  186635. }
  186636. }
  186637. }
  186638. else
  186639. #endif
  186640. {
  186641. sp = row;
  186642. for (i = 0; i < row_width; i++, sp += 2)
  186643. {
  186644. png_uint_16 v;
  186645. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186646. if (v == trans_values->gray)
  186647. {
  186648. *sp = (png_byte)((background->gray >> 8) & 0xff);
  186649. *(sp + 1) = (png_byte)(background->gray & 0xff);
  186650. }
  186651. }
  186652. }
  186653. break;
  186654. }
  186655. }
  186656. break;
  186657. }
  186658. case PNG_COLOR_TYPE_RGB:
  186659. {
  186660. if (row_info->bit_depth == 8)
  186661. {
  186662. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186663. if (gamma_table != NULL)
  186664. {
  186665. sp = row;
  186666. for (i = 0; i < row_width; i++, sp += 3)
  186667. {
  186668. if (*sp == trans_values->red &&
  186669. *(sp + 1) == trans_values->green &&
  186670. *(sp + 2) == trans_values->blue)
  186671. {
  186672. *sp = (png_byte)background->red;
  186673. *(sp + 1) = (png_byte)background->green;
  186674. *(sp + 2) = (png_byte)background->blue;
  186675. }
  186676. else
  186677. {
  186678. *sp = gamma_table[*sp];
  186679. *(sp + 1) = gamma_table[*(sp + 1)];
  186680. *(sp + 2) = gamma_table[*(sp + 2)];
  186681. }
  186682. }
  186683. }
  186684. else
  186685. #endif
  186686. {
  186687. sp = row;
  186688. for (i = 0; i < row_width; i++, sp += 3)
  186689. {
  186690. if (*sp == trans_values->red &&
  186691. *(sp + 1) == trans_values->green &&
  186692. *(sp + 2) == trans_values->blue)
  186693. {
  186694. *sp = (png_byte)background->red;
  186695. *(sp + 1) = (png_byte)background->green;
  186696. *(sp + 2) = (png_byte)background->blue;
  186697. }
  186698. }
  186699. }
  186700. }
  186701. else /* if (row_info->bit_depth == 16) */
  186702. {
  186703. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186704. if (gamma_16 != NULL)
  186705. {
  186706. sp = row;
  186707. for (i = 0; i < row_width; i++, sp += 6)
  186708. {
  186709. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186710. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186711. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  186712. if (r == trans_values->red && g == trans_values->green &&
  186713. b == trans_values->blue)
  186714. {
  186715. /* background is already in screen gamma */
  186716. *sp = (png_byte)((background->red >> 8) & 0xff);
  186717. *(sp + 1) = (png_byte)(background->red & 0xff);
  186718. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  186719. *(sp + 3) = (png_byte)(background->green & 0xff);
  186720. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  186721. *(sp + 5) = (png_byte)(background->blue & 0xff);
  186722. }
  186723. else
  186724. {
  186725. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  186726. *sp = (png_byte)((v >> 8) & 0xff);
  186727. *(sp + 1) = (png_byte)(v & 0xff);
  186728. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  186729. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  186730. *(sp + 3) = (png_byte)(v & 0xff);
  186731. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  186732. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  186733. *(sp + 5) = (png_byte)(v & 0xff);
  186734. }
  186735. }
  186736. }
  186737. else
  186738. #endif
  186739. {
  186740. sp = row;
  186741. for (i = 0; i < row_width; i++, sp += 6)
  186742. {
  186743. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  186744. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186745. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  186746. if (r == trans_values->red && g == trans_values->green &&
  186747. b == trans_values->blue)
  186748. {
  186749. *sp = (png_byte)((background->red >> 8) & 0xff);
  186750. *(sp + 1) = (png_byte)(background->red & 0xff);
  186751. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  186752. *(sp + 3) = (png_byte)(background->green & 0xff);
  186753. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  186754. *(sp + 5) = (png_byte)(background->blue & 0xff);
  186755. }
  186756. }
  186757. }
  186758. }
  186759. break;
  186760. }
  186761. case PNG_COLOR_TYPE_GRAY_ALPHA:
  186762. {
  186763. if (row_info->bit_depth == 8)
  186764. {
  186765. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186766. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  186767. gamma_table != NULL)
  186768. {
  186769. sp = row;
  186770. dp = row;
  186771. for (i = 0; i < row_width; i++, sp += 2, dp++)
  186772. {
  186773. png_uint_16 a = *(sp + 1);
  186774. if (a == 0xff)
  186775. {
  186776. *dp = gamma_table[*sp];
  186777. }
  186778. else if (a == 0)
  186779. {
  186780. /* background is already in screen gamma */
  186781. *dp = (png_byte)background->gray;
  186782. }
  186783. else
  186784. {
  186785. png_byte v, w;
  186786. v = gamma_to_1[*sp];
  186787. png_composite(w, v, a, background_1->gray);
  186788. *dp = gamma_from_1[w];
  186789. }
  186790. }
  186791. }
  186792. else
  186793. #endif
  186794. {
  186795. sp = row;
  186796. dp = row;
  186797. for (i = 0; i < row_width; i++, sp += 2, dp++)
  186798. {
  186799. png_byte a = *(sp + 1);
  186800. if (a == 0xff)
  186801. {
  186802. *dp = *sp;
  186803. }
  186804. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186805. else if (a == 0)
  186806. {
  186807. *dp = (png_byte)background->gray;
  186808. }
  186809. else
  186810. {
  186811. png_composite(*dp, *sp, a, background_1->gray);
  186812. }
  186813. #else
  186814. *dp = (png_byte)background->gray;
  186815. #endif
  186816. }
  186817. }
  186818. }
  186819. else /* if (png_ptr->bit_depth == 16) */
  186820. {
  186821. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186822. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  186823. gamma_16_to_1 != NULL)
  186824. {
  186825. sp = row;
  186826. dp = row;
  186827. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  186828. {
  186829. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186830. if (a == (png_uint_16)0xffff)
  186831. {
  186832. png_uint_16 v;
  186833. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  186834. *dp = (png_byte)((v >> 8) & 0xff);
  186835. *(dp + 1) = (png_byte)(v & 0xff);
  186836. }
  186837. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186838. else if (a == 0)
  186839. #else
  186840. else
  186841. #endif
  186842. {
  186843. /* background is already in screen gamma */
  186844. *dp = (png_byte)((background->gray >> 8) & 0xff);
  186845. *(dp + 1) = (png_byte)(background->gray & 0xff);
  186846. }
  186847. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186848. else
  186849. {
  186850. png_uint_16 g, v, w;
  186851. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  186852. png_composite_16(v, g, a, background_1->gray);
  186853. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  186854. *dp = (png_byte)((w >> 8) & 0xff);
  186855. *(dp + 1) = (png_byte)(w & 0xff);
  186856. }
  186857. #endif
  186858. }
  186859. }
  186860. else
  186861. #endif
  186862. {
  186863. sp = row;
  186864. dp = row;
  186865. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  186866. {
  186867. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186868. if (a == (png_uint_16)0xffff)
  186869. {
  186870. png_memcpy(dp, sp, 2);
  186871. }
  186872. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186873. else if (a == 0)
  186874. #else
  186875. else
  186876. #endif
  186877. {
  186878. *dp = (png_byte)((background->gray >> 8) & 0xff);
  186879. *(dp + 1) = (png_byte)(background->gray & 0xff);
  186880. }
  186881. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186882. else
  186883. {
  186884. png_uint_16 g, v;
  186885. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186886. png_composite_16(v, g, a, background_1->gray);
  186887. *dp = (png_byte)((v >> 8) & 0xff);
  186888. *(dp + 1) = (png_byte)(v & 0xff);
  186889. }
  186890. #endif
  186891. }
  186892. }
  186893. }
  186894. break;
  186895. }
  186896. case PNG_COLOR_TYPE_RGB_ALPHA:
  186897. {
  186898. if (row_info->bit_depth == 8)
  186899. {
  186900. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186901. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  186902. gamma_table != NULL)
  186903. {
  186904. sp = row;
  186905. dp = row;
  186906. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  186907. {
  186908. png_byte a = *(sp + 3);
  186909. if (a == 0xff)
  186910. {
  186911. *dp = gamma_table[*sp];
  186912. *(dp + 1) = gamma_table[*(sp + 1)];
  186913. *(dp + 2) = gamma_table[*(sp + 2)];
  186914. }
  186915. else if (a == 0)
  186916. {
  186917. /* background is already in screen gamma */
  186918. *dp = (png_byte)background->red;
  186919. *(dp + 1) = (png_byte)background->green;
  186920. *(dp + 2) = (png_byte)background->blue;
  186921. }
  186922. else
  186923. {
  186924. png_byte v, w;
  186925. v = gamma_to_1[*sp];
  186926. png_composite(w, v, a, background_1->red);
  186927. *dp = gamma_from_1[w];
  186928. v = gamma_to_1[*(sp + 1)];
  186929. png_composite(w, v, a, background_1->green);
  186930. *(dp + 1) = gamma_from_1[w];
  186931. v = gamma_to_1[*(sp + 2)];
  186932. png_composite(w, v, a, background_1->blue);
  186933. *(dp + 2) = gamma_from_1[w];
  186934. }
  186935. }
  186936. }
  186937. else
  186938. #endif
  186939. {
  186940. sp = row;
  186941. dp = row;
  186942. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  186943. {
  186944. png_byte a = *(sp + 3);
  186945. if (a == 0xff)
  186946. {
  186947. *dp = *sp;
  186948. *(dp + 1) = *(sp + 1);
  186949. *(dp + 2) = *(sp + 2);
  186950. }
  186951. else if (a == 0)
  186952. {
  186953. *dp = (png_byte)background->red;
  186954. *(dp + 1) = (png_byte)background->green;
  186955. *(dp + 2) = (png_byte)background->blue;
  186956. }
  186957. else
  186958. {
  186959. png_composite(*dp, *sp, a, background->red);
  186960. png_composite(*(dp + 1), *(sp + 1), a,
  186961. background->green);
  186962. png_composite(*(dp + 2), *(sp + 2), a,
  186963. background->blue);
  186964. }
  186965. }
  186966. }
  186967. }
  186968. else /* if (row_info->bit_depth == 16) */
  186969. {
  186970. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186971. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  186972. gamma_16_to_1 != NULL)
  186973. {
  186974. sp = row;
  186975. dp = row;
  186976. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  186977. {
  186978. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  186979. << 8) + (png_uint_16)(*(sp + 7)));
  186980. if (a == (png_uint_16)0xffff)
  186981. {
  186982. png_uint_16 v;
  186983. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  186984. *dp = (png_byte)((v >> 8) & 0xff);
  186985. *(dp + 1) = (png_byte)(v & 0xff);
  186986. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  186987. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  186988. *(dp + 3) = (png_byte)(v & 0xff);
  186989. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  186990. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  186991. *(dp + 5) = (png_byte)(v & 0xff);
  186992. }
  186993. else if (a == 0)
  186994. {
  186995. /* background is already in screen gamma */
  186996. *dp = (png_byte)((background->red >> 8) & 0xff);
  186997. *(dp + 1) = (png_byte)(background->red & 0xff);
  186998. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  186999. *(dp + 3) = (png_byte)(background->green & 0xff);
  187000. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  187001. *(dp + 5) = (png_byte)(background->blue & 0xff);
  187002. }
  187003. else
  187004. {
  187005. png_uint_16 v, w, x;
  187006. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  187007. png_composite_16(w, v, a, background_1->red);
  187008. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  187009. *dp = (png_byte)((x >> 8) & 0xff);
  187010. *(dp + 1) = (png_byte)(x & 0xff);
  187011. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  187012. png_composite_16(w, v, a, background_1->green);
  187013. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  187014. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  187015. *(dp + 3) = (png_byte)(x & 0xff);
  187016. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  187017. png_composite_16(w, v, a, background_1->blue);
  187018. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  187019. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  187020. *(dp + 5) = (png_byte)(x & 0xff);
  187021. }
  187022. }
  187023. }
  187024. else
  187025. #endif
  187026. {
  187027. sp = row;
  187028. dp = row;
  187029. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  187030. {
  187031. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  187032. << 8) + (png_uint_16)(*(sp + 7)));
  187033. if (a == (png_uint_16)0xffff)
  187034. {
  187035. png_memcpy(dp, sp, 6);
  187036. }
  187037. else if (a == 0)
  187038. {
  187039. *dp = (png_byte)((background->red >> 8) & 0xff);
  187040. *(dp + 1) = (png_byte)(background->red & 0xff);
  187041. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  187042. *(dp + 3) = (png_byte)(background->green & 0xff);
  187043. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  187044. *(dp + 5) = (png_byte)(background->blue & 0xff);
  187045. }
  187046. else
  187047. {
  187048. png_uint_16 v;
  187049. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  187050. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  187051. + *(sp + 3));
  187052. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  187053. + *(sp + 5));
  187054. png_composite_16(v, r, a, background->red);
  187055. *dp = (png_byte)((v >> 8) & 0xff);
  187056. *(dp + 1) = (png_byte)(v & 0xff);
  187057. png_composite_16(v, g, a, background->green);
  187058. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  187059. *(dp + 3) = (png_byte)(v & 0xff);
  187060. png_composite_16(v, b, a, background->blue);
  187061. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  187062. *(dp + 5) = (png_byte)(v & 0xff);
  187063. }
  187064. }
  187065. }
  187066. }
  187067. break;
  187068. }
  187069. }
  187070. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  187071. {
  187072. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  187073. row_info->channels--;
  187074. row_info->pixel_depth = (png_byte)(row_info->channels *
  187075. row_info->bit_depth);
  187076. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187077. }
  187078. }
  187079. }
  187080. #endif
  187081. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187082. /* Gamma correct the image, avoiding the alpha channel. Make sure
  187083. * you do this after you deal with the transparency issue on grayscale
  187084. * or RGB images. If your bit depth is 8, use gamma_table, if it
  187085. * is 16, use gamma_16_table and gamma_shift. Build these with
  187086. * build_gamma_table().
  187087. */
  187088. void /* PRIVATE */
  187089. png_do_gamma(png_row_infop row_info, png_bytep row,
  187090. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  187091. int gamma_shift)
  187092. {
  187093. png_bytep sp;
  187094. png_uint_32 i;
  187095. png_uint_32 row_width=row_info->width;
  187096. png_debug(1, "in png_do_gamma\n");
  187097. if (
  187098. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187099. row != NULL && row_info != NULL &&
  187100. #endif
  187101. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  187102. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  187103. {
  187104. switch (row_info->color_type)
  187105. {
  187106. case PNG_COLOR_TYPE_RGB:
  187107. {
  187108. if (row_info->bit_depth == 8)
  187109. {
  187110. sp = row;
  187111. for (i = 0; i < row_width; i++)
  187112. {
  187113. *sp = gamma_table[*sp];
  187114. sp++;
  187115. *sp = gamma_table[*sp];
  187116. sp++;
  187117. *sp = gamma_table[*sp];
  187118. sp++;
  187119. }
  187120. }
  187121. else /* if (row_info->bit_depth == 16) */
  187122. {
  187123. sp = row;
  187124. for (i = 0; i < row_width; i++)
  187125. {
  187126. png_uint_16 v;
  187127. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187128. *sp = (png_byte)((v >> 8) & 0xff);
  187129. *(sp + 1) = (png_byte)(v & 0xff);
  187130. sp += 2;
  187131. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187132. *sp = (png_byte)((v >> 8) & 0xff);
  187133. *(sp + 1) = (png_byte)(v & 0xff);
  187134. sp += 2;
  187135. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187136. *sp = (png_byte)((v >> 8) & 0xff);
  187137. *(sp + 1) = (png_byte)(v & 0xff);
  187138. sp += 2;
  187139. }
  187140. }
  187141. break;
  187142. }
  187143. case PNG_COLOR_TYPE_RGB_ALPHA:
  187144. {
  187145. if (row_info->bit_depth == 8)
  187146. {
  187147. sp = row;
  187148. for (i = 0; i < row_width; i++)
  187149. {
  187150. *sp = gamma_table[*sp];
  187151. sp++;
  187152. *sp = gamma_table[*sp];
  187153. sp++;
  187154. *sp = gamma_table[*sp];
  187155. sp++;
  187156. sp++;
  187157. }
  187158. }
  187159. else /* if (row_info->bit_depth == 16) */
  187160. {
  187161. sp = row;
  187162. for (i = 0; i < row_width; i++)
  187163. {
  187164. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187165. *sp = (png_byte)((v >> 8) & 0xff);
  187166. *(sp + 1) = (png_byte)(v & 0xff);
  187167. sp += 2;
  187168. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187169. *sp = (png_byte)((v >> 8) & 0xff);
  187170. *(sp + 1) = (png_byte)(v & 0xff);
  187171. sp += 2;
  187172. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187173. *sp = (png_byte)((v >> 8) & 0xff);
  187174. *(sp + 1) = (png_byte)(v & 0xff);
  187175. sp += 4;
  187176. }
  187177. }
  187178. break;
  187179. }
  187180. case PNG_COLOR_TYPE_GRAY_ALPHA:
  187181. {
  187182. if (row_info->bit_depth == 8)
  187183. {
  187184. sp = row;
  187185. for (i = 0; i < row_width; i++)
  187186. {
  187187. *sp = gamma_table[*sp];
  187188. sp += 2;
  187189. }
  187190. }
  187191. else /* if (row_info->bit_depth == 16) */
  187192. {
  187193. sp = row;
  187194. for (i = 0; i < row_width; i++)
  187195. {
  187196. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187197. *sp = (png_byte)((v >> 8) & 0xff);
  187198. *(sp + 1) = (png_byte)(v & 0xff);
  187199. sp += 4;
  187200. }
  187201. }
  187202. break;
  187203. }
  187204. case PNG_COLOR_TYPE_GRAY:
  187205. {
  187206. if (row_info->bit_depth == 2)
  187207. {
  187208. sp = row;
  187209. for (i = 0; i < row_width; i += 4)
  187210. {
  187211. int a = *sp & 0xc0;
  187212. int b = *sp & 0x30;
  187213. int c = *sp & 0x0c;
  187214. int d = *sp & 0x03;
  187215. *sp = (png_byte)(
  187216. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  187217. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  187218. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  187219. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  187220. sp++;
  187221. }
  187222. }
  187223. if (row_info->bit_depth == 4)
  187224. {
  187225. sp = row;
  187226. for (i = 0; i < row_width; i += 2)
  187227. {
  187228. int msb = *sp & 0xf0;
  187229. int lsb = *sp & 0x0f;
  187230. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  187231. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  187232. sp++;
  187233. }
  187234. }
  187235. else if (row_info->bit_depth == 8)
  187236. {
  187237. sp = row;
  187238. for (i = 0; i < row_width; i++)
  187239. {
  187240. *sp = gamma_table[*sp];
  187241. sp++;
  187242. }
  187243. }
  187244. else if (row_info->bit_depth == 16)
  187245. {
  187246. sp = row;
  187247. for (i = 0; i < row_width; i++)
  187248. {
  187249. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187250. *sp = (png_byte)((v >> 8) & 0xff);
  187251. *(sp + 1) = (png_byte)(v & 0xff);
  187252. sp += 2;
  187253. }
  187254. }
  187255. break;
  187256. }
  187257. }
  187258. }
  187259. }
  187260. #endif
  187261. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187262. /* Expands a palette row to an RGB or RGBA row depending
  187263. * upon whether you supply trans and num_trans.
  187264. */
  187265. void /* PRIVATE */
  187266. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  187267. png_colorp palette, png_bytep trans, int num_trans)
  187268. {
  187269. int shift, value;
  187270. png_bytep sp, dp;
  187271. png_uint_32 i;
  187272. png_uint_32 row_width=row_info->width;
  187273. png_debug(1, "in png_do_expand_palette\n");
  187274. if (
  187275. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187276. row != NULL && row_info != NULL &&
  187277. #endif
  187278. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  187279. {
  187280. if (row_info->bit_depth < 8)
  187281. {
  187282. switch (row_info->bit_depth)
  187283. {
  187284. case 1:
  187285. {
  187286. sp = row + (png_size_t)((row_width - 1) >> 3);
  187287. dp = row + (png_size_t)row_width - 1;
  187288. shift = 7 - (int)((row_width + 7) & 0x07);
  187289. for (i = 0; i < row_width; i++)
  187290. {
  187291. if ((*sp >> shift) & 0x01)
  187292. *dp = 1;
  187293. else
  187294. *dp = 0;
  187295. if (shift == 7)
  187296. {
  187297. shift = 0;
  187298. sp--;
  187299. }
  187300. else
  187301. shift++;
  187302. dp--;
  187303. }
  187304. break;
  187305. }
  187306. case 2:
  187307. {
  187308. sp = row + (png_size_t)((row_width - 1) >> 2);
  187309. dp = row + (png_size_t)row_width - 1;
  187310. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  187311. for (i = 0; i < row_width; i++)
  187312. {
  187313. value = (*sp >> shift) & 0x03;
  187314. *dp = (png_byte)value;
  187315. if (shift == 6)
  187316. {
  187317. shift = 0;
  187318. sp--;
  187319. }
  187320. else
  187321. shift += 2;
  187322. dp--;
  187323. }
  187324. break;
  187325. }
  187326. case 4:
  187327. {
  187328. sp = row + (png_size_t)((row_width - 1) >> 1);
  187329. dp = row + (png_size_t)row_width - 1;
  187330. shift = (int)((row_width & 0x01) << 2);
  187331. for (i = 0; i < row_width; i++)
  187332. {
  187333. value = (*sp >> shift) & 0x0f;
  187334. *dp = (png_byte)value;
  187335. if (shift == 4)
  187336. {
  187337. shift = 0;
  187338. sp--;
  187339. }
  187340. else
  187341. shift += 4;
  187342. dp--;
  187343. }
  187344. break;
  187345. }
  187346. }
  187347. row_info->bit_depth = 8;
  187348. row_info->pixel_depth = 8;
  187349. row_info->rowbytes = row_width;
  187350. }
  187351. switch (row_info->bit_depth)
  187352. {
  187353. case 8:
  187354. {
  187355. if (trans != NULL)
  187356. {
  187357. sp = row + (png_size_t)row_width - 1;
  187358. dp = row + (png_size_t)(row_width << 2) - 1;
  187359. for (i = 0; i < row_width; i++)
  187360. {
  187361. if ((int)(*sp) >= num_trans)
  187362. *dp-- = 0xff;
  187363. else
  187364. *dp-- = trans[*sp];
  187365. *dp-- = palette[*sp].blue;
  187366. *dp-- = palette[*sp].green;
  187367. *dp-- = palette[*sp].red;
  187368. sp--;
  187369. }
  187370. row_info->bit_depth = 8;
  187371. row_info->pixel_depth = 32;
  187372. row_info->rowbytes = row_width * 4;
  187373. row_info->color_type = 6;
  187374. row_info->channels = 4;
  187375. }
  187376. else
  187377. {
  187378. sp = row + (png_size_t)row_width - 1;
  187379. dp = row + (png_size_t)(row_width * 3) - 1;
  187380. for (i = 0; i < row_width; i++)
  187381. {
  187382. *dp-- = palette[*sp].blue;
  187383. *dp-- = palette[*sp].green;
  187384. *dp-- = palette[*sp].red;
  187385. sp--;
  187386. }
  187387. row_info->bit_depth = 8;
  187388. row_info->pixel_depth = 24;
  187389. row_info->rowbytes = row_width * 3;
  187390. row_info->color_type = 2;
  187391. row_info->channels = 3;
  187392. }
  187393. break;
  187394. }
  187395. }
  187396. }
  187397. }
  187398. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  187399. * expanded transparency value is supplied, an alpha channel is built.
  187400. */
  187401. void /* PRIVATE */
  187402. png_do_expand(png_row_infop row_info, png_bytep row,
  187403. png_color_16p trans_value)
  187404. {
  187405. int shift, value;
  187406. png_bytep sp, dp;
  187407. png_uint_32 i;
  187408. png_uint_32 row_width=row_info->width;
  187409. png_debug(1, "in png_do_expand\n");
  187410. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187411. if (row != NULL && row_info != NULL)
  187412. #endif
  187413. {
  187414. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  187415. {
  187416. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  187417. if (row_info->bit_depth < 8)
  187418. {
  187419. switch (row_info->bit_depth)
  187420. {
  187421. case 1:
  187422. {
  187423. gray = (png_uint_16)((gray&0x01)*0xff);
  187424. sp = row + (png_size_t)((row_width - 1) >> 3);
  187425. dp = row + (png_size_t)row_width - 1;
  187426. shift = 7 - (int)((row_width + 7) & 0x07);
  187427. for (i = 0; i < row_width; i++)
  187428. {
  187429. if ((*sp >> shift) & 0x01)
  187430. *dp = 0xff;
  187431. else
  187432. *dp = 0;
  187433. if (shift == 7)
  187434. {
  187435. shift = 0;
  187436. sp--;
  187437. }
  187438. else
  187439. shift++;
  187440. dp--;
  187441. }
  187442. break;
  187443. }
  187444. case 2:
  187445. {
  187446. gray = (png_uint_16)((gray&0x03)*0x55);
  187447. sp = row + (png_size_t)((row_width - 1) >> 2);
  187448. dp = row + (png_size_t)row_width - 1;
  187449. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  187450. for (i = 0; i < row_width; i++)
  187451. {
  187452. value = (*sp >> shift) & 0x03;
  187453. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  187454. (value << 6));
  187455. if (shift == 6)
  187456. {
  187457. shift = 0;
  187458. sp--;
  187459. }
  187460. else
  187461. shift += 2;
  187462. dp--;
  187463. }
  187464. break;
  187465. }
  187466. case 4:
  187467. {
  187468. gray = (png_uint_16)((gray&0x0f)*0x11);
  187469. sp = row + (png_size_t)((row_width - 1) >> 1);
  187470. dp = row + (png_size_t)row_width - 1;
  187471. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  187472. for (i = 0; i < row_width; i++)
  187473. {
  187474. value = (*sp >> shift) & 0x0f;
  187475. *dp = (png_byte)(value | (value << 4));
  187476. if (shift == 4)
  187477. {
  187478. shift = 0;
  187479. sp--;
  187480. }
  187481. else
  187482. shift = 4;
  187483. dp--;
  187484. }
  187485. break;
  187486. }
  187487. }
  187488. row_info->bit_depth = 8;
  187489. row_info->pixel_depth = 8;
  187490. row_info->rowbytes = row_width;
  187491. }
  187492. if (trans_value != NULL)
  187493. {
  187494. if (row_info->bit_depth == 8)
  187495. {
  187496. gray = gray & 0xff;
  187497. sp = row + (png_size_t)row_width - 1;
  187498. dp = row + (png_size_t)(row_width << 1) - 1;
  187499. for (i = 0; i < row_width; i++)
  187500. {
  187501. if (*sp == gray)
  187502. *dp-- = 0;
  187503. else
  187504. *dp-- = 0xff;
  187505. *dp-- = *sp--;
  187506. }
  187507. }
  187508. else if (row_info->bit_depth == 16)
  187509. {
  187510. png_byte gray_high = (gray >> 8) & 0xff;
  187511. png_byte gray_low = gray & 0xff;
  187512. sp = row + row_info->rowbytes - 1;
  187513. dp = row + (row_info->rowbytes << 1) - 1;
  187514. for (i = 0; i < row_width; i++)
  187515. {
  187516. if (*(sp-1) == gray_high && *(sp) == gray_low)
  187517. {
  187518. *dp-- = 0;
  187519. *dp-- = 0;
  187520. }
  187521. else
  187522. {
  187523. *dp-- = 0xff;
  187524. *dp-- = 0xff;
  187525. }
  187526. *dp-- = *sp--;
  187527. *dp-- = *sp--;
  187528. }
  187529. }
  187530. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  187531. row_info->channels = 2;
  187532. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  187533. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  187534. row_width);
  187535. }
  187536. }
  187537. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  187538. {
  187539. if (row_info->bit_depth == 8)
  187540. {
  187541. png_byte red = trans_value->red & 0xff;
  187542. png_byte green = trans_value->green & 0xff;
  187543. png_byte blue = trans_value->blue & 0xff;
  187544. sp = row + (png_size_t)row_info->rowbytes - 1;
  187545. dp = row + (png_size_t)(row_width << 2) - 1;
  187546. for (i = 0; i < row_width; i++)
  187547. {
  187548. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  187549. *dp-- = 0;
  187550. else
  187551. *dp-- = 0xff;
  187552. *dp-- = *sp--;
  187553. *dp-- = *sp--;
  187554. *dp-- = *sp--;
  187555. }
  187556. }
  187557. else if (row_info->bit_depth == 16)
  187558. {
  187559. png_byte red_high = (trans_value->red >> 8) & 0xff;
  187560. png_byte green_high = (trans_value->green >> 8) & 0xff;
  187561. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  187562. png_byte red_low = trans_value->red & 0xff;
  187563. png_byte green_low = trans_value->green & 0xff;
  187564. png_byte blue_low = trans_value->blue & 0xff;
  187565. sp = row + row_info->rowbytes - 1;
  187566. dp = row + (png_size_t)(row_width << 3) - 1;
  187567. for (i = 0; i < row_width; i++)
  187568. {
  187569. if (*(sp - 5) == red_high &&
  187570. *(sp - 4) == red_low &&
  187571. *(sp - 3) == green_high &&
  187572. *(sp - 2) == green_low &&
  187573. *(sp - 1) == blue_high &&
  187574. *(sp ) == blue_low)
  187575. {
  187576. *dp-- = 0;
  187577. *dp-- = 0;
  187578. }
  187579. else
  187580. {
  187581. *dp-- = 0xff;
  187582. *dp-- = 0xff;
  187583. }
  187584. *dp-- = *sp--;
  187585. *dp-- = *sp--;
  187586. *dp-- = *sp--;
  187587. *dp-- = *sp--;
  187588. *dp-- = *sp--;
  187589. *dp-- = *sp--;
  187590. }
  187591. }
  187592. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  187593. row_info->channels = 4;
  187594. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  187595. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187596. }
  187597. }
  187598. }
  187599. #endif
  187600. #if defined(PNG_READ_DITHER_SUPPORTED)
  187601. void /* PRIVATE */
  187602. png_do_dither(png_row_infop row_info, png_bytep row,
  187603. png_bytep palette_lookup, png_bytep dither_lookup)
  187604. {
  187605. png_bytep sp, dp;
  187606. png_uint_32 i;
  187607. png_uint_32 row_width=row_info->width;
  187608. png_debug(1, "in png_do_dither\n");
  187609. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187610. if (row != NULL && row_info != NULL)
  187611. #endif
  187612. {
  187613. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  187614. palette_lookup && row_info->bit_depth == 8)
  187615. {
  187616. int r, g, b, p;
  187617. sp = row;
  187618. dp = row;
  187619. for (i = 0; i < row_width; i++)
  187620. {
  187621. r = *sp++;
  187622. g = *sp++;
  187623. b = *sp++;
  187624. /* this looks real messy, but the compiler will reduce
  187625. it down to a reasonable formula. For example, with
  187626. 5 bits per color, we get:
  187627. p = (((r >> 3) & 0x1f) << 10) |
  187628. (((g >> 3) & 0x1f) << 5) |
  187629. ((b >> 3) & 0x1f);
  187630. */
  187631. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  187632. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  187633. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  187634. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  187635. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  187636. (PNG_DITHER_BLUE_BITS)) |
  187637. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  187638. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  187639. *dp++ = palette_lookup[p];
  187640. }
  187641. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  187642. row_info->channels = 1;
  187643. row_info->pixel_depth = row_info->bit_depth;
  187644. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187645. }
  187646. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  187647. palette_lookup != NULL && row_info->bit_depth == 8)
  187648. {
  187649. int r, g, b, p;
  187650. sp = row;
  187651. dp = row;
  187652. for (i = 0; i < row_width; i++)
  187653. {
  187654. r = *sp++;
  187655. g = *sp++;
  187656. b = *sp++;
  187657. sp++;
  187658. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  187659. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  187660. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  187661. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  187662. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  187663. (PNG_DITHER_BLUE_BITS)) |
  187664. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  187665. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  187666. *dp++ = palette_lookup[p];
  187667. }
  187668. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  187669. row_info->channels = 1;
  187670. row_info->pixel_depth = row_info->bit_depth;
  187671. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187672. }
  187673. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  187674. dither_lookup && row_info->bit_depth == 8)
  187675. {
  187676. sp = row;
  187677. for (i = 0; i < row_width; i++, sp++)
  187678. {
  187679. *sp = dither_lookup[*sp];
  187680. }
  187681. }
  187682. }
  187683. }
  187684. #endif
  187685. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187686. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187687. static PNG_CONST int png_gamma_shift[] =
  187688. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  187689. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  187690. * tables, we don't make a full table if we are reducing to 8-bit in
  187691. * the future. Note also how the gamma_16 tables are segmented so that
  187692. * we don't need to allocate > 64K chunks for a full 16-bit table.
  187693. */
  187694. void /* PRIVATE */
  187695. png_build_gamma_table(png_structp png_ptr)
  187696. {
  187697. png_debug(1, "in png_build_gamma_table\n");
  187698. if (png_ptr->bit_depth <= 8)
  187699. {
  187700. int i;
  187701. double g;
  187702. if (png_ptr->screen_gamma > .000001)
  187703. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  187704. else
  187705. g = 1.0;
  187706. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  187707. (png_uint_32)256);
  187708. for (i = 0; i < 256; i++)
  187709. {
  187710. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  187711. g) * 255.0 + .5);
  187712. }
  187713. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  187714. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187715. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  187716. {
  187717. g = 1.0 / (png_ptr->gamma);
  187718. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  187719. (png_uint_32)256);
  187720. for (i = 0; i < 256; i++)
  187721. {
  187722. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  187723. g) * 255.0 + .5);
  187724. }
  187725. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  187726. (png_uint_32)256);
  187727. if(png_ptr->screen_gamma > 0.000001)
  187728. g = 1.0 / png_ptr->screen_gamma;
  187729. else
  187730. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  187731. for (i = 0; i < 256; i++)
  187732. {
  187733. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  187734. g) * 255.0 + .5);
  187735. }
  187736. }
  187737. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  187738. }
  187739. else
  187740. {
  187741. double g;
  187742. int i, j, shift, num;
  187743. int sig_bit;
  187744. png_uint_32 ig;
  187745. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  187746. {
  187747. sig_bit = (int)png_ptr->sig_bit.red;
  187748. if ((int)png_ptr->sig_bit.green > sig_bit)
  187749. sig_bit = png_ptr->sig_bit.green;
  187750. if ((int)png_ptr->sig_bit.blue > sig_bit)
  187751. sig_bit = png_ptr->sig_bit.blue;
  187752. }
  187753. else
  187754. {
  187755. sig_bit = (int)png_ptr->sig_bit.gray;
  187756. }
  187757. if (sig_bit > 0)
  187758. shift = 16 - sig_bit;
  187759. else
  187760. shift = 0;
  187761. if (png_ptr->transformations & PNG_16_TO_8)
  187762. {
  187763. if (shift < (16 - PNG_MAX_GAMMA_8))
  187764. shift = (16 - PNG_MAX_GAMMA_8);
  187765. }
  187766. if (shift > 8)
  187767. shift = 8;
  187768. if (shift < 0)
  187769. shift = 0;
  187770. png_ptr->gamma_shift = (png_byte)shift;
  187771. num = (1 << (8 - shift));
  187772. if (png_ptr->screen_gamma > .000001)
  187773. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  187774. else
  187775. g = 1.0;
  187776. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  187777. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  187778. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  187779. {
  187780. double fin, fout;
  187781. png_uint_32 last, max;
  187782. for (i = 0; i < num; i++)
  187783. {
  187784. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  187785. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187786. }
  187787. g = 1.0 / g;
  187788. last = 0;
  187789. for (i = 0; i < 256; i++)
  187790. {
  187791. fout = ((double)i + 0.5) / 256.0;
  187792. fin = pow(fout, g);
  187793. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  187794. while (last <= max)
  187795. {
  187796. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  187797. [(int)(last >> (8 - shift))] = (png_uint_16)(
  187798. (png_uint_16)i | ((png_uint_16)i << 8));
  187799. last++;
  187800. }
  187801. }
  187802. while (last < ((png_uint_32)num << 8))
  187803. {
  187804. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  187805. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  187806. last++;
  187807. }
  187808. }
  187809. else
  187810. {
  187811. for (i = 0; i < num; i++)
  187812. {
  187813. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  187814. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187815. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  187816. for (j = 0; j < 256; j++)
  187817. {
  187818. png_ptr->gamma_16_table[i][j] =
  187819. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  187820. 65535.0, g) * 65535.0 + .5);
  187821. }
  187822. }
  187823. }
  187824. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  187825. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187826. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  187827. {
  187828. g = 1.0 / (png_ptr->gamma);
  187829. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  187830. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  187831. for (i = 0; i < num; i++)
  187832. {
  187833. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  187834. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187835. ig = (((png_uint_32)i *
  187836. (png_uint_32)png_gamma_shift[shift]) >> 4);
  187837. for (j = 0; j < 256; j++)
  187838. {
  187839. png_ptr->gamma_16_to_1[i][j] =
  187840. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  187841. 65535.0, g) * 65535.0 + .5);
  187842. }
  187843. }
  187844. if(png_ptr->screen_gamma > 0.000001)
  187845. g = 1.0 / png_ptr->screen_gamma;
  187846. else
  187847. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  187848. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  187849. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  187850. for (i = 0; i < num; i++)
  187851. {
  187852. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  187853. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187854. ig = (((png_uint_32)i *
  187855. (png_uint_32)png_gamma_shift[shift]) >> 4);
  187856. for (j = 0; j < 256; j++)
  187857. {
  187858. png_ptr->gamma_16_from_1[i][j] =
  187859. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  187860. 65535.0, g) * 65535.0 + .5);
  187861. }
  187862. }
  187863. }
  187864. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  187865. }
  187866. }
  187867. #endif
  187868. /* To do: install integer version of png_build_gamma_table here */
  187869. #endif
  187870. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187871. /* undoes intrapixel differencing */
  187872. void /* PRIVATE */
  187873. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  187874. {
  187875. png_debug(1, "in png_do_read_intrapixel\n");
  187876. if (
  187877. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187878. row != NULL && row_info != NULL &&
  187879. #endif
  187880. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  187881. {
  187882. int bytes_per_pixel;
  187883. png_uint_32 row_width = row_info->width;
  187884. if (row_info->bit_depth == 8)
  187885. {
  187886. png_bytep rp;
  187887. png_uint_32 i;
  187888. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187889. bytes_per_pixel = 3;
  187890. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187891. bytes_per_pixel = 4;
  187892. else
  187893. return;
  187894. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  187895. {
  187896. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  187897. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  187898. }
  187899. }
  187900. else if (row_info->bit_depth == 16)
  187901. {
  187902. png_bytep rp;
  187903. png_uint_32 i;
  187904. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187905. bytes_per_pixel = 6;
  187906. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187907. bytes_per_pixel = 8;
  187908. else
  187909. return;
  187910. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  187911. {
  187912. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  187913. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  187914. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  187915. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  187916. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  187917. *(rp ) = (png_byte)((red >> 8) & 0xff);
  187918. *(rp+1) = (png_byte)(red & 0xff);
  187919. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  187920. *(rp+5) = (png_byte)(blue & 0xff);
  187921. }
  187922. }
  187923. }
  187924. }
  187925. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  187926. #endif /* PNG_READ_SUPPORTED */
  187927. /********* End of inlined file: pngrtran.c *********/
  187928. /********* Start of inlined file: pngrutil.c *********/
  187929. /* pngrutil.c - utilities to read a PNG file
  187930. *
  187931. * Last changed in libpng 1.2.21 [October 4, 2007]
  187932. * For conditions of distribution and use, see copyright notice in png.h
  187933. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187934. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187935. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187936. *
  187937. * This file contains routines that are only called from within
  187938. * libpng itself during the course of reading an image.
  187939. */
  187940. #define PNG_INTERNAL
  187941. #if defined(PNG_READ_SUPPORTED)
  187942. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  187943. # define WIN32_WCE_OLD
  187944. #endif
  187945. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187946. # if defined(WIN32_WCE_OLD)
  187947. /* strtod() function is not supported on WindowsCE */
  187948. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  187949. {
  187950. double result = 0;
  187951. int len;
  187952. wchar_t *str, *end;
  187953. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  187954. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  187955. if ( NULL != str )
  187956. {
  187957. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  187958. result = wcstod(str, &end);
  187959. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  187960. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  187961. png_free(png_ptr, str);
  187962. }
  187963. return result;
  187964. }
  187965. # else
  187966. # define png_strtod(p,a,b) strtod(a,b)
  187967. # endif
  187968. #endif
  187969. png_uint_32 PNGAPI
  187970. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  187971. {
  187972. png_uint_32 i = png_get_uint_32(buf);
  187973. if (i > PNG_UINT_31_MAX)
  187974. png_error(png_ptr, "PNG unsigned integer out of range.");
  187975. return (i);
  187976. }
  187977. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  187978. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  187979. png_uint_32 PNGAPI
  187980. png_get_uint_32(png_bytep buf)
  187981. {
  187982. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  187983. ((png_uint_32)(*(buf + 1)) << 16) +
  187984. ((png_uint_32)(*(buf + 2)) << 8) +
  187985. (png_uint_32)(*(buf + 3));
  187986. return (i);
  187987. }
  187988. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  187989. * data is stored in the PNG file in two's complement format, and it is
  187990. * assumed that the machine format for signed integers is the same. */
  187991. png_int_32 PNGAPI
  187992. png_get_int_32(png_bytep buf)
  187993. {
  187994. png_int_32 i = ((png_int_32)(*buf) << 24) +
  187995. ((png_int_32)(*(buf + 1)) << 16) +
  187996. ((png_int_32)(*(buf + 2)) << 8) +
  187997. (png_int_32)(*(buf + 3));
  187998. return (i);
  187999. }
  188000. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  188001. png_uint_16 PNGAPI
  188002. png_get_uint_16(png_bytep buf)
  188003. {
  188004. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  188005. (png_uint_16)(*(buf + 1)));
  188006. return (i);
  188007. }
  188008. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  188009. /* Read data, and (optionally) run it through the CRC. */
  188010. void /* PRIVATE */
  188011. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  188012. {
  188013. if(png_ptr == NULL) return;
  188014. png_read_data(png_ptr, buf, length);
  188015. png_calculate_crc(png_ptr, buf, length);
  188016. }
  188017. /* Optionally skip data and then check the CRC. Depending on whether we
  188018. are reading a ancillary or critical chunk, and how the program has set
  188019. things up, we may calculate the CRC on the data and print a message.
  188020. Returns '1' if there was a CRC error, '0' otherwise. */
  188021. int /* PRIVATE */
  188022. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  188023. {
  188024. png_size_t i;
  188025. png_size_t istop = png_ptr->zbuf_size;
  188026. for (i = (png_size_t)skip; i > istop; i -= istop)
  188027. {
  188028. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  188029. }
  188030. if (i)
  188031. {
  188032. png_crc_read(png_ptr, png_ptr->zbuf, i);
  188033. }
  188034. if (png_crc_error(png_ptr))
  188035. {
  188036. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  188037. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  188038. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  188039. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  188040. {
  188041. png_chunk_warning(png_ptr, "CRC error");
  188042. }
  188043. else
  188044. {
  188045. png_chunk_error(png_ptr, "CRC error");
  188046. }
  188047. return (1);
  188048. }
  188049. return (0);
  188050. }
  188051. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  188052. the data it has read thus far. */
  188053. int /* PRIVATE */
  188054. png_crc_error(png_structp png_ptr)
  188055. {
  188056. png_byte crc_bytes[4];
  188057. png_uint_32 crc;
  188058. int need_crc = 1;
  188059. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  188060. {
  188061. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  188062. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  188063. need_crc = 0;
  188064. }
  188065. else /* critical */
  188066. {
  188067. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  188068. need_crc = 0;
  188069. }
  188070. png_read_data(png_ptr, crc_bytes, 4);
  188071. if (need_crc)
  188072. {
  188073. crc = png_get_uint_32(crc_bytes);
  188074. return ((int)(crc != png_ptr->crc));
  188075. }
  188076. else
  188077. return (0);
  188078. }
  188079. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  188080. defined(PNG_READ_iCCP_SUPPORTED)
  188081. /*
  188082. * Decompress trailing data in a chunk. The assumption is that chunkdata
  188083. * points at an allocated area holding the contents of a chunk with a
  188084. * trailing compressed part. What we get back is an allocated area
  188085. * holding the original prefix part and an uncompressed version of the
  188086. * trailing part (the malloc area passed in is freed).
  188087. */
  188088. png_charp /* PRIVATE */
  188089. png_decompress_chunk(png_structp png_ptr, int comp_type,
  188090. png_charp chunkdata, png_size_t chunklength,
  188091. png_size_t prefix_size, png_size_t *newlength)
  188092. {
  188093. static PNG_CONST char msg[] = "Error decoding compressed text";
  188094. png_charp text;
  188095. png_size_t text_size;
  188096. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  188097. {
  188098. int ret = Z_OK;
  188099. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  188100. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  188101. png_ptr->zstream.next_out = png_ptr->zbuf;
  188102. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188103. text_size = 0;
  188104. text = NULL;
  188105. while (png_ptr->zstream.avail_in)
  188106. {
  188107. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188108. if (ret != Z_OK && ret != Z_STREAM_END)
  188109. {
  188110. if (png_ptr->zstream.msg != NULL)
  188111. png_warning(png_ptr, png_ptr->zstream.msg);
  188112. else
  188113. png_warning(png_ptr, msg);
  188114. inflateReset(&png_ptr->zstream);
  188115. png_ptr->zstream.avail_in = 0;
  188116. if (text == NULL)
  188117. {
  188118. text_size = prefix_size + png_sizeof(msg) + 1;
  188119. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  188120. if (text == NULL)
  188121. {
  188122. png_free(png_ptr,chunkdata);
  188123. png_error(png_ptr,"Not enough memory to decompress chunk");
  188124. }
  188125. png_memcpy(text, chunkdata, prefix_size);
  188126. }
  188127. text[text_size - 1] = 0x00;
  188128. /* Copy what we can of the error message into the text chunk */
  188129. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  188130. text_size = png_sizeof(msg) > text_size ? text_size :
  188131. png_sizeof(msg);
  188132. png_memcpy(text + prefix_size, msg, text_size + 1);
  188133. break;
  188134. }
  188135. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  188136. {
  188137. if (text == NULL)
  188138. {
  188139. text_size = prefix_size +
  188140. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  188141. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  188142. if (text == NULL)
  188143. {
  188144. png_free(png_ptr,chunkdata);
  188145. png_error(png_ptr,"Not enough memory to decompress chunk.");
  188146. }
  188147. png_memcpy(text + prefix_size, png_ptr->zbuf,
  188148. text_size - prefix_size);
  188149. png_memcpy(text, chunkdata, prefix_size);
  188150. *(text + text_size) = 0x00;
  188151. }
  188152. else
  188153. {
  188154. png_charp tmp;
  188155. tmp = text;
  188156. text = (png_charp)png_malloc_warn(png_ptr,
  188157. (png_uint_32)(text_size +
  188158. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  188159. if (text == NULL)
  188160. {
  188161. png_free(png_ptr, tmp);
  188162. png_free(png_ptr, chunkdata);
  188163. png_error(png_ptr,"Not enough memory to decompress chunk..");
  188164. }
  188165. png_memcpy(text, tmp, text_size);
  188166. png_free(png_ptr, tmp);
  188167. png_memcpy(text + text_size, png_ptr->zbuf,
  188168. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  188169. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  188170. *(text + text_size) = 0x00;
  188171. }
  188172. if (ret == Z_STREAM_END)
  188173. break;
  188174. else
  188175. {
  188176. png_ptr->zstream.next_out = png_ptr->zbuf;
  188177. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188178. }
  188179. }
  188180. }
  188181. if (ret != Z_STREAM_END)
  188182. {
  188183. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  188184. char umsg[52];
  188185. if (ret == Z_BUF_ERROR)
  188186. png_snprintf(umsg, 52,
  188187. "Buffer error in compressed datastream in %s chunk",
  188188. png_ptr->chunk_name);
  188189. else if (ret == Z_DATA_ERROR)
  188190. png_snprintf(umsg, 52,
  188191. "Data error in compressed datastream in %s chunk",
  188192. png_ptr->chunk_name);
  188193. else
  188194. png_snprintf(umsg, 52,
  188195. "Incomplete compressed datastream in %s chunk",
  188196. png_ptr->chunk_name);
  188197. png_warning(png_ptr, umsg);
  188198. #else
  188199. png_warning(png_ptr,
  188200. "Incomplete compressed datastream in chunk other than IDAT");
  188201. #endif
  188202. text_size=prefix_size;
  188203. if (text == NULL)
  188204. {
  188205. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  188206. if (text == NULL)
  188207. {
  188208. png_free(png_ptr, chunkdata);
  188209. png_error(png_ptr,"Not enough memory for text.");
  188210. }
  188211. png_memcpy(text, chunkdata, prefix_size);
  188212. }
  188213. *(text + text_size) = 0x00;
  188214. }
  188215. inflateReset(&png_ptr->zstream);
  188216. png_ptr->zstream.avail_in = 0;
  188217. png_free(png_ptr, chunkdata);
  188218. chunkdata = text;
  188219. *newlength=text_size;
  188220. }
  188221. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  188222. {
  188223. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  188224. char umsg[50];
  188225. png_snprintf(umsg, 50,
  188226. "Unknown zTXt compression type %d", comp_type);
  188227. png_warning(png_ptr, umsg);
  188228. #else
  188229. png_warning(png_ptr, "Unknown zTXt compression type");
  188230. #endif
  188231. *(chunkdata + prefix_size) = 0x00;
  188232. *newlength=prefix_size;
  188233. }
  188234. return chunkdata;
  188235. }
  188236. #endif
  188237. /* read and check the IDHR chunk */
  188238. void /* PRIVATE */
  188239. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188240. {
  188241. png_byte buf[13];
  188242. png_uint_32 width, height;
  188243. int bit_depth, color_type, compression_type, filter_type;
  188244. int interlace_type;
  188245. png_debug(1, "in png_handle_IHDR\n");
  188246. if (png_ptr->mode & PNG_HAVE_IHDR)
  188247. png_error(png_ptr, "Out of place IHDR");
  188248. /* check the length */
  188249. if (length != 13)
  188250. png_error(png_ptr, "Invalid IHDR chunk");
  188251. png_ptr->mode |= PNG_HAVE_IHDR;
  188252. png_crc_read(png_ptr, buf, 13);
  188253. png_crc_finish(png_ptr, 0);
  188254. width = png_get_uint_31(png_ptr, buf);
  188255. height = png_get_uint_31(png_ptr, buf + 4);
  188256. bit_depth = buf[8];
  188257. color_type = buf[9];
  188258. compression_type = buf[10];
  188259. filter_type = buf[11];
  188260. interlace_type = buf[12];
  188261. /* set internal variables */
  188262. png_ptr->width = width;
  188263. png_ptr->height = height;
  188264. png_ptr->bit_depth = (png_byte)bit_depth;
  188265. png_ptr->interlaced = (png_byte)interlace_type;
  188266. png_ptr->color_type = (png_byte)color_type;
  188267. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  188268. png_ptr->filter_type = (png_byte)filter_type;
  188269. #endif
  188270. png_ptr->compression_type = (png_byte)compression_type;
  188271. /* find number of channels */
  188272. switch (png_ptr->color_type)
  188273. {
  188274. case PNG_COLOR_TYPE_GRAY:
  188275. case PNG_COLOR_TYPE_PALETTE:
  188276. png_ptr->channels = 1;
  188277. break;
  188278. case PNG_COLOR_TYPE_RGB:
  188279. png_ptr->channels = 3;
  188280. break;
  188281. case PNG_COLOR_TYPE_GRAY_ALPHA:
  188282. png_ptr->channels = 2;
  188283. break;
  188284. case PNG_COLOR_TYPE_RGB_ALPHA:
  188285. png_ptr->channels = 4;
  188286. break;
  188287. }
  188288. /* set up other useful info */
  188289. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  188290. png_ptr->channels);
  188291. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  188292. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  188293. png_debug1(3,"channels = %d\n", png_ptr->channels);
  188294. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  188295. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  188296. color_type, interlace_type, compression_type, filter_type);
  188297. }
  188298. /* read and check the palette */
  188299. void /* PRIVATE */
  188300. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188301. {
  188302. png_color palette[PNG_MAX_PALETTE_LENGTH];
  188303. int num, i;
  188304. #ifndef PNG_NO_POINTER_INDEXING
  188305. png_colorp pal_ptr;
  188306. #endif
  188307. png_debug(1, "in png_handle_PLTE\n");
  188308. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188309. png_error(png_ptr, "Missing IHDR before PLTE");
  188310. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188311. {
  188312. png_warning(png_ptr, "Invalid PLTE after IDAT");
  188313. png_crc_finish(png_ptr, length);
  188314. return;
  188315. }
  188316. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188317. png_error(png_ptr, "Duplicate PLTE chunk");
  188318. png_ptr->mode |= PNG_HAVE_PLTE;
  188319. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  188320. {
  188321. png_warning(png_ptr,
  188322. "Ignoring PLTE chunk in grayscale PNG");
  188323. png_crc_finish(png_ptr, length);
  188324. return;
  188325. }
  188326. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  188327. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  188328. {
  188329. png_crc_finish(png_ptr, length);
  188330. return;
  188331. }
  188332. #endif
  188333. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  188334. {
  188335. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  188336. {
  188337. png_warning(png_ptr, "Invalid palette chunk");
  188338. png_crc_finish(png_ptr, length);
  188339. return;
  188340. }
  188341. else
  188342. {
  188343. png_error(png_ptr, "Invalid palette chunk");
  188344. }
  188345. }
  188346. num = (int)length / 3;
  188347. #ifndef PNG_NO_POINTER_INDEXING
  188348. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  188349. {
  188350. png_byte buf[3];
  188351. png_crc_read(png_ptr, buf, 3);
  188352. pal_ptr->red = buf[0];
  188353. pal_ptr->green = buf[1];
  188354. pal_ptr->blue = buf[2];
  188355. }
  188356. #else
  188357. for (i = 0; i < num; i++)
  188358. {
  188359. png_byte buf[3];
  188360. png_crc_read(png_ptr, buf, 3);
  188361. /* don't depend upon png_color being any order */
  188362. palette[i].red = buf[0];
  188363. palette[i].green = buf[1];
  188364. palette[i].blue = buf[2];
  188365. }
  188366. #endif
  188367. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  188368. whatever the normal CRC configuration tells us. However, if we
  188369. have an RGB image, the PLTE can be considered ancillary, so
  188370. we will act as though it is. */
  188371. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  188372. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188373. #endif
  188374. {
  188375. png_crc_finish(png_ptr, 0);
  188376. }
  188377. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  188378. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  188379. {
  188380. /* If we don't want to use the data from an ancillary chunk,
  188381. we have two options: an error abort, or a warning and we
  188382. ignore the data in this chunk (which should be OK, since
  188383. it's considered ancillary for a RGB or RGBA image). */
  188384. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  188385. {
  188386. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  188387. {
  188388. png_chunk_error(png_ptr, "CRC error");
  188389. }
  188390. else
  188391. {
  188392. png_chunk_warning(png_ptr, "CRC error");
  188393. return;
  188394. }
  188395. }
  188396. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  188397. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  188398. {
  188399. png_chunk_warning(png_ptr, "CRC error");
  188400. }
  188401. }
  188402. #endif
  188403. png_set_PLTE(png_ptr, info_ptr, palette, num);
  188404. #if defined(PNG_READ_tRNS_SUPPORTED)
  188405. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188406. {
  188407. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  188408. {
  188409. if (png_ptr->num_trans > (png_uint_16)num)
  188410. {
  188411. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  188412. png_ptr->num_trans = (png_uint_16)num;
  188413. }
  188414. if (info_ptr->num_trans > (png_uint_16)num)
  188415. {
  188416. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  188417. info_ptr->num_trans = (png_uint_16)num;
  188418. }
  188419. }
  188420. }
  188421. #endif
  188422. }
  188423. void /* PRIVATE */
  188424. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188425. {
  188426. png_debug(1, "in png_handle_IEND\n");
  188427. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  188428. {
  188429. png_error(png_ptr, "No image in file");
  188430. }
  188431. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  188432. if (length != 0)
  188433. {
  188434. png_warning(png_ptr, "Incorrect IEND chunk length");
  188435. }
  188436. png_crc_finish(png_ptr, length);
  188437. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  188438. }
  188439. #if defined(PNG_READ_gAMA_SUPPORTED)
  188440. void /* PRIVATE */
  188441. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188442. {
  188443. png_fixed_point igamma;
  188444. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188445. float file_gamma;
  188446. #endif
  188447. png_byte buf[4];
  188448. png_debug(1, "in png_handle_gAMA\n");
  188449. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188450. png_error(png_ptr, "Missing IHDR before gAMA");
  188451. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188452. {
  188453. png_warning(png_ptr, "Invalid gAMA after IDAT");
  188454. png_crc_finish(png_ptr, length);
  188455. return;
  188456. }
  188457. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188458. /* Should be an error, but we can cope with it */
  188459. png_warning(png_ptr, "Out of place gAMA chunk");
  188460. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  188461. #if defined(PNG_READ_sRGB_SUPPORTED)
  188462. && !(info_ptr->valid & PNG_INFO_sRGB)
  188463. #endif
  188464. )
  188465. {
  188466. png_warning(png_ptr, "Duplicate gAMA chunk");
  188467. png_crc_finish(png_ptr, length);
  188468. return;
  188469. }
  188470. if (length != 4)
  188471. {
  188472. png_warning(png_ptr, "Incorrect gAMA chunk length");
  188473. png_crc_finish(png_ptr, length);
  188474. return;
  188475. }
  188476. png_crc_read(png_ptr, buf, 4);
  188477. if (png_crc_finish(png_ptr, 0))
  188478. return;
  188479. igamma = (png_fixed_point)png_get_uint_32(buf);
  188480. /* check for zero gamma */
  188481. if (igamma == 0)
  188482. {
  188483. png_warning(png_ptr,
  188484. "Ignoring gAMA chunk with gamma=0");
  188485. return;
  188486. }
  188487. #if defined(PNG_READ_sRGB_SUPPORTED)
  188488. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  188489. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  188490. {
  188491. png_warning(png_ptr,
  188492. "Ignoring incorrect gAMA value when sRGB is also present");
  188493. #ifndef PNG_NO_CONSOLE_IO
  188494. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  188495. #endif
  188496. return;
  188497. }
  188498. #endif /* PNG_READ_sRGB_SUPPORTED */
  188499. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188500. file_gamma = (float)igamma / (float)100000.0;
  188501. # ifdef PNG_READ_GAMMA_SUPPORTED
  188502. png_ptr->gamma = file_gamma;
  188503. # endif
  188504. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  188505. #endif
  188506. #ifdef PNG_FIXED_POINT_SUPPORTED
  188507. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  188508. #endif
  188509. }
  188510. #endif
  188511. #if defined(PNG_READ_sBIT_SUPPORTED)
  188512. void /* PRIVATE */
  188513. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188514. {
  188515. png_size_t truelen;
  188516. png_byte buf[4];
  188517. png_debug(1, "in png_handle_sBIT\n");
  188518. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  188519. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188520. png_error(png_ptr, "Missing IHDR before sBIT");
  188521. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188522. {
  188523. png_warning(png_ptr, "Invalid sBIT after IDAT");
  188524. png_crc_finish(png_ptr, length);
  188525. return;
  188526. }
  188527. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188528. {
  188529. /* Should be an error, but we can cope with it */
  188530. png_warning(png_ptr, "Out of place sBIT chunk");
  188531. }
  188532. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  188533. {
  188534. png_warning(png_ptr, "Duplicate sBIT chunk");
  188535. png_crc_finish(png_ptr, length);
  188536. return;
  188537. }
  188538. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188539. truelen = 3;
  188540. else
  188541. truelen = (png_size_t)png_ptr->channels;
  188542. if (length != truelen || length > 4)
  188543. {
  188544. png_warning(png_ptr, "Incorrect sBIT chunk length");
  188545. png_crc_finish(png_ptr, length);
  188546. return;
  188547. }
  188548. png_crc_read(png_ptr, buf, truelen);
  188549. if (png_crc_finish(png_ptr, 0))
  188550. return;
  188551. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  188552. {
  188553. png_ptr->sig_bit.red = buf[0];
  188554. png_ptr->sig_bit.green = buf[1];
  188555. png_ptr->sig_bit.blue = buf[2];
  188556. png_ptr->sig_bit.alpha = buf[3];
  188557. }
  188558. else
  188559. {
  188560. png_ptr->sig_bit.gray = buf[0];
  188561. png_ptr->sig_bit.red = buf[0];
  188562. png_ptr->sig_bit.green = buf[0];
  188563. png_ptr->sig_bit.blue = buf[0];
  188564. png_ptr->sig_bit.alpha = buf[1];
  188565. }
  188566. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  188567. }
  188568. #endif
  188569. #if defined(PNG_READ_cHRM_SUPPORTED)
  188570. void /* PRIVATE */
  188571. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188572. {
  188573. png_byte buf[4];
  188574. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188575. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  188576. #endif
  188577. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  188578. int_y_green, int_x_blue, int_y_blue;
  188579. png_uint_32 uint_x, uint_y;
  188580. png_debug(1, "in png_handle_cHRM\n");
  188581. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188582. png_error(png_ptr, "Missing IHDR before cHRM");
  188583. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188584. {
  188585. png_warning(png_ptr, "Invalid cHRM after IDAT");
  188586. png_crc_finish(png_ptr, length);
  188587. return;
  188588. }
  188589. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188590. /* Should be an error, but we can cope with it */
  188591. png_warning(png_ptr, "Missing PLTE before cHRM");
  188592. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  188593. #if defined(PNG_READ_sRGB_SUPPORTED)
  188594. && !(info_ptr->valid & PNG_INFO_sRGB)
  188595. #endif
  188596. )
  188597. {
  188598. png_warning(png_ptr, "Duplicate cHRM chunk");
  188599. png_crc_finish(png_ptr, length);
  188600. return;
  188601. }
  188602. if (length != 32)
  188603. {
  188604. png_warning(png_ptr, "Incorrect cHRM chunk length");
  188605. png_crc_finish(png_ptr, length);
  188606. return;
  188607. }
  188608. png_crc_read(png_ptr, buf, 4);
  188609. uint_x = png_get_uint_32(buf);
  188610. png_crc_read(png_ptr, buf, 4);
  188611. uint_y = png_get_uint_32(buf);
  188612. if (uint_x > 80000L || uint_y > 80000L ||
  188613. uint_x + uint_y > 100000L)
  188614. {
  188615. png_warning(png_ptr, "Invalid cHRM white point");
  188616. png_crc_finish(png_ptr, 24);
  188617. return;
  188618. }
  188619. int_x_white = (png_fixed_point)uint_x;
  188620. int_y_white = (png_fixed_point)uint_y;
  188621. png_crc_read(png_ptr, buf, 4);
  188622. uint_x = png_get_uint_32(buf);
  188623. png_crc_read(png_ptr, buf, 4);
  188624. uint_y = png_get_uint_32(buf);
  188625. if (uint_x + uint_y > 100000L)
  188626. {
  188627. png_warning(png_ptr, "Invalid cHRM red point");
  188628. png_crc_finish(png_ptr, 16);
  188629. return;
  188630. }
  188631. int_x_red = (png_fixed_point)uint_x;
  188632. int_y_red = (png_fixed_point)uint_y;
  188633. png_crc_read(png_ptr, buf, 4);
  188634. uint_x = png_get_uint_32(buf);
  188635. png_crc_read(png_ptr, buf, 4);
  188636. uint_y = png_get_uint_32(buf);
  188637. if (uint_x + uint_y > 100000L)
  188638. {
  188639. png_warning(png_ptr, "Invalid cHRM green point");
  188640. png_crc_finish(png_ptr, 8);
  188641. return;
  188642. }
  188643. int_x_green = (png_fixed_point)uint_x;
  188644. int_y_green = (png_fixed_point)uint_y;
  188645. png_crc_read(png_ptr, buf, 4);
  188646. uint_x = png_get_uint_32(buf);
  188647. png_crc_read(png_ptr, buf, 4);
  188648. uint_y = png_get_uint_32(buf);
  188649. if (uint_x + uint_y > 100000L)
  188650. {
  188651. png_warning(png_ptr, "Invalid cHRM blue point");
  188652. png_crc_finish(png_ptr, 0);
  188653. return;
  188654. }
  188655. int_x_blue = (png_fixed_point)uint_x;
  188656. int_y_blue = (png_fixed_point)uint_y;
  188657. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188658. white_x = (float)int_x_white / (float)100000.0;
  188659. white_y = (float)int_y_white / (float)100000.0;
  188660. red_x = (float)int_x_red / (float)100000.0;
  188661. red_y = (float)int_y_red / (float)100000.0;
  188662. green_x = (float)int_x_green / (float)100000.0;
  188663. green_y = (float)int_y_green / (float)100000.0;
  188664. blue_x = (float)int_x_blue / (float)100000.0;
  188665. blue_y = (float)int_y_blue / (float)100000.0;
  188666. #endif
  188667. #if defined(PNG_READ_sRGB_SUPPORTED)
  188668. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  188669. {
  188670. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  188671. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  188672. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  188673. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  188674. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  188675. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  188676. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  188677. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  188678. {
  188679. png_warning(png_ptr,
  188680. "Ignoring incorrect cHRM value when sRGB is also present");
  188681. #ifndef PNG_NO_CONSOLE_IO
  188682. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188683. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  188684. white_x, white_y, red_x, red_y);
  188685. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  188686. green_x, green_y, blue_x, blue_y);
  188687. #else
  188688. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  188689. int_x_white, int_y_white, int_x_red, int_y_red);
  188690. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  188691. int_x_green, int_y_green, int_x_blue, int_y_blue);
  188692. #endif
  188693. #endif /* PNG_NO_CONSOLE_IO */
  188694. }
  188695. png_crc_finish(png_ptr, 0);
  188696. return;
  188697. }
  188698. #endif /* PNG_READ_sRGB_SUPPORTED */
  188699. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188700. png_set_cHRM(png_ptr, info_ptr,
  188701. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  188702. #endif
  188703. #ifdef PNG_FIXED_POINT_SUPPORTED
  188704. png_set_cHRM_fixed(png_ptr, info_ptr,
  188705. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  188706. int_y_green, int_x_blue, int_y_blue);
  188707. #endif
  188708. if (png_crc_finish(png_ptr, 0))
  188709. return;
  188710. }
  188711. #endif
  188712. #if defined(PNG_READ_sRGB_SUPPORTED)
  188713. void /* PRIVATE */
  188714. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188715. {
  188716. int intent;
  188717. png_byte buf[1];
  188718. png_debug(1, "in png_handle_sRGB\n");
  188719. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188720. png_error(png_ptr, "Missing IHDR before sRGB");
  188721. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188722. {
  188723. png_warning(png_ptr, "Invalid sRGB after IDAT");
  188724. png_crc_finish(png_ptr, length);
  188725. return;
  188726. }
  188727. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188728. /* Should be an error, but we can cope with it */
  188729. png_warning(png_ptr, "Out of place sRGB chunk");
  188730. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  188731. {
  188732. png_warning(png_ptr, "Duplicate sRGB chunk");
  188733. png_crc_finish(png_ptr, length);
  188734. return;
  188735. }
  188736. if (length != 1)
  188737. {
  188738. png_warning(png_ptr, "Incorrect sRGB chunk length");
  188739. png_crc_finish(png_ptr, length);
  188740. return;
  188741. }
  188742. png_crc_read(png_ptr, buf, 1);
  188743. if (png_crc_finish(png_ptr, 0))
  188744. return;
  188745. intent = buf[0];
  188746. /* check for bad intent */
  188747. if (intent >= PNG_sRGB_INTENT_LAST)
  188748. {
  188749. png_warning(png_ptr, "Unknown sRGB intent");
  188750. return;
  188751. }
  188752. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  188753. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  188754. {
  188755. png_fixed_point igamma;
  188756. #ifdef PNG_FIXED_POINT_SUPPORTED
  188757. igamma=info_ptr->int_gamma;
  188758. #else
  188759. # ifdef PNG_FLOATING_POINT_SUPPORTED
  188760. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  188761. # endif
  188762. #endif
  188763. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  188764. {
  188765. png_warning(png_ptr,
  188766. "Ignoring incorrect gAMA value when sRGB is also present");
  188767. #ifndef PNG_NO_CONSOLE_IO
  188768. # ifdef PNG_FIXED_POINT_SUPPORTED
  188769. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  188770. # else
  188771. # ifdef PNG_FLOATING_POINT_SUPPORTED
  188772. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  188773. # endif
  188774. # endif
  188775. #endif
  188776. }
  188777. }
  188778. #endif /* PNG_READ_gAMA_SUPPORTED */
  188779. #ifdef PNG_READ_cHRM_SUPPORTED
  188780. #ifdef PNG_FIXED_POINT_SUPPORTED
  188781. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  188782. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  188783. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  188784. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  188785. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  188786. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  188787. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  188788. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  188789. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  188790. {
  188791. png_warning(png_ptr,
  188792. "Ignoring incorrect cHRM value when sRGB is also present");
  188793. }
  188794. #endif /* PNG_FIXED_POINT_SUPPORTED */
  188795. #endif /* PNG_READ_cHRM_SUPPORTED */
  188796. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  188797. }
  188798. #endif /* PNG_READ_sRGB_SUPPORTED */
  188799. #if defined(PNG_READ_iCCP_SUPPORTED)
  188800. void /* PRIVATE */
  188801. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188802. /* Note: this does not properly handle chunks that are > 64K under DOS */
  188803. {
  188804. png_charp chunkdata;
  188805. png_byte compression_type;
  188806. png_bytep pC;
  188807. png_charp profile;
  188808. png_uint_32 skip = 0;
  188809. png_uint_32 profile_size, profile_length;
  188810. png_size_t slength, prefix_length, data_length;
  188811. png_debug(1, "in png_handle_iCCP\n");
  188812. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188813. png_error(png_ptr, "Missing IHDR before iCCP");
  188814. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188815. {
  188816. png_warning(png_ptr, "Invalid iCCP after IDAT");
  188817. png_crc_finish(png_ptr, length);
  188818. return;
  188819. }
  188820. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188821. /* Should be an error, but we can cope with it */
  188822. png_warning(png_ptr, "Out of place iCCP chunk");
  188823. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  188824. {
  188825. png_warning(png_ptr, "Duplicate iCCP chunk");
  188826. png_crc_finish(png_ptr, length);
  188827. return;
  188828. }
  188829. #ifdef PNG_MAX_MALLOC_64K
  188830. if (length > (png_uint_32)65535L)
  188831. {
  188832. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  188833. skip = length - (png_uint_32)65535L;
  188834. length = (png_uint_32)65535L;
  188835. }
  188836. #endif
  188837. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  188838. slength = (png_size_t)length;
  188839. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  188840. if (png_crc_finish(png_ptr, skip))
  188841. {
  188842. png_free(png_ptr, chunkdata);
  188843. return;
  188844. }
  188845. chunkdata[slength] = 0x00;
  188846. for (profile = chunkdata; *profile; profile++)
  188847. /* empty loop to find end of name */ ;
  188848. ++profile;
  188849. /* there should be at least one zero (the compression type byte)
  188850. following the separator, and we should be on it */
  188851. if ( profile >= chunkdata + slength - 1)
  188852. {
  188853. png_free(png_ptr, chunkdata);
  188854. png_warning(png_ptr, "Malformed iCCP chunk");
  188855. return;
  188856. }
  188857. /* compression_type should always be zero */
  188858. compression_type = *profile++;
  188859. if (compression_type)
  188860. {
  188861. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  188862. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  188863. wrote nonzero) */
  188864. }
  188865. prefix_length = profile - chunkdata;
  188866. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  188867. slength, prefix_length, &data_length);
  188868. profile_length = data_length - prefix_length;
  188869. if ( prefix_length > data_length || profile_length < 4)
  188870. {
  188871. png_free(png_ptr, chunkdata);
  188872. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  188873. return;
  188874. }
  188875. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  188876. pC = (png_bytep)(chunkdata+prefix_length);
  188877. profile_size = ((*(pC ))<<24) |
  188878. ((*(pC+1))<<16) |
  188879. ((*(pC+2))<< 8) |
  188880. ((*(pC+3)) );
  188881. if(profile_size < profile_length)
  188882. profile_length = profile_size;
  188883. if(profile_size > profile_length)
  188884. {
  188885. png_free(png_ptr, chunkdata);
  188886. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  188887. return;
  188888. }
  188889. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  188890. chunkdata + prefix_length, profile_length);
  188891. png_free(png_ptr, chunkdata);
  188892. }
  188893. #endif /* PNG_READ_iCCP_SUPPORTED */
  188894. #if defined(PNG_READ_sPLT_SUPPORTED)
  188895. void /* PRIVATE */
  188896. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188897. /* Note: this does not properly handle chunks that are > 64K under DOS */
  188898. {
  188899. png_bytep chunkdata;
  188900. png_bytep entry_start;
  188901. png_sPLT_t new_palette;
  188902. #ifdef PNG_NO_POINTER_INDEXING
  188903. png_sPLT_entryp pp;
  188904. #endif
  188905. int data_length, entry_size, i;
  188906. png_uint_32 skip = 0;
  188907. png_size_t slength;
  188908. png_debug(1, "in png_handle_sPLT\n");
  188909. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188910. png_error(png_ptr, "Missing IHDR before sPLT");
  188911. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188912. {
  188913. png_warning(png_ptr, "Invalid sPLT after IDAT");
  188914. png_crc_finish(png_ptr, length);
  188915. return;
  188916. }
  188917. #ifdef PNG_MAX_MALLOC_64K
  188918. if (length > (png_uint_32)65535L)
  188919. {
  188920. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  188921. skip = length - (png_uint_32)65535L;
  188922. length = (png_uint_32)65535L;
  188923. }
  188924. #endif
  188925. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  188926. slength = (png_size_t)length;
  188927. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  188928. if (png_crc_finish(png_ptr, skip))
  188929. {
  188930. png_free(png_ptr, chunkdata);
  188931. return;
  188932. }
  188933. chunkdata[slength] = 0x00;
  188934. for (entry_start = chunkdata; *entry_start; entry_start++)
  188935. /* empty loop to find end of name */ ;
  188936. ++entry_start;
  188937. /* a sample depth should follow the separator, and we should be on it */
  188938. if (entry_start > chunkdata + slength - 2)
  188939. {
  188940. png_free(png_ptr, chunkdata);
  188941. png_warning(png_ptr, "malformed sPLT chunk");
  188942. return;
  188943. }
  188944. new_palette.depth = *entry_start++;
  188945. entry_size = (new_palette.depth == 8 ? 6 : 10);
  188946. data_length = (slength - (entry_start - chunkdata));
  188947. /* integrity-check the data length */
  188948. if (data_length % entry_size)
  188949. {
  188950. png_free(png_ptr, chunkdata);
  188951. png_warning(png_ptr, "sPLT chunk has bad length");
  188952. return;
  188953. }
  188954. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  188955. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  188956. png_sizeof(png_sPLT_entry)))
  188957. {
  188958. png_warning(png_ptr, "sPLT chunk too long");
  188959. return;
  188960. }
  188961. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  188962. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  188963. if (new_palette.entries == NULL)
  188964. {
  188965. png_warning(png_ptr, "sPLT chunk requires too much memory");
  188966. return;
  188967. }
  188968. #ifndef PNG_NO_POINTER_INDEXING
  188969. for (i = 0; i < new_palette.nentries; i++)
  188970. {
  188971. png_sPLT_entryp pp = new_palette.entries + i;
  188972. if (new_palette.depth == 8)
  188973. {
  188974. pp->red = *entry_start++;
  188975. pp->green = *entry_start++;
  188976. pp->blue = *entry_start++;
  188977. pp->alpha = *entry_start++;
  188978. }
  188979. else
  188980. {
  188981. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  188982. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  188983. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  188984. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  188985. }
  188986. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  188987. }
  188988. #else
  188989. pp = new_palette.entries;
  188990. for (i = 0; i < new_palette.nentries; i++)
  188991. {
  188992. if (new_palette.depth == 8)
  188993. {
  188994. pp[i].red = *entry_start++;
  188995. pp[i].green = *entry_start++;
  188996. pp[i].blue = *entry_start++;
  188997. pp[i].alpha = *entry_start++;
  188998. }
  188999. else
  189000. {
  189001. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  189002. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  189003. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  189004. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  189005. }
  189006. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  189007. }
  189008. #endif
  189009. /* discard all chunk data except the name and stash that */
  189010. new_palette.name = (png_charp)chunkdata;
  189011. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  189012. png_free(png_ptr, chunkdata);
  189013. png_free(png_ptr, new_palette.entries);
  189014. }
  189015. #endif /* PNG_READ_sPLT_SUPPORTED */
  189016. #if defined(PNG_READ_tRNS_SUPPORTED)
  189017. void /* PRIVATE */
  189018. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189019. {
  189020. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  189021. int bit_mask;
  189022. png_debug(1, "in png_handle_tRNS\n");
  189023. /* For non-indexed color, mask off any bits in the tRNS value that
  189024. * exceed the bit depth. Some creators were writing extra bits there.
  189025. * This is not needed for indexed color. */
  189026. bit_mask = (1 << png_ptr->bit_depth) - 1;
  189027. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189028. png_error(png_ptr, "Missing IHDR before tRNS");
  189029. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189030. {
  189031. png_warning(png_ptr, "Invalid tRNS after IDAT");
  189032. png_crc_finish(png_ptr, length);
  189033. return;
  189034. }
  189035. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  189036. {
  189037. png_warning(png_ptr, "Duplicate tRNS chunk");
  189038. png_crc_finish(png_ptr, length);
  189039. return;
  189040. }
  189041. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  189042. {
  189043. png_byte buf[2];
  189044. if (length != 2)
  189045. {
  189046. png_warning(png_ptr, "Incorrect tRNS chunk length");
  189047. png_crc_finish(png_ptr, length);
  189048. return;
  189049. }
  189050. png_crc_read(png_ptr, buf, 2);
  189051. png_ptr->num_trans = 1;
  189052. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  189053. }
  189054. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  189055. {
  189056. png_byte buf[6];
  189057. if (length != 6)
  189058. {
  189059. png_warning(png_ptr, "Incorrect tRNS chunk length");
  189060. png_crc_finish(png_ptr, length);
  189061. return;
  189062. }
  189063. png_crc_read(png_ptr, buf, (png_size_t)length);
  189064. png_ptr->num_trans = 1;
  189065. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  189066. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  189067. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  189068. }
  189069. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189070. {
  189071. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  189072. {
  189073. /* Should be an error, but we can cope with it. */
  189074. png_warning(png_ptr, "Missing PLTE before tRNS");
  189075. }
  189076. if (length > (png_uint_32)png_ptr->num_palette ||
  189077. length > PNG_MAX_PALETTE_LENGTH)
  189078. {
  189079. png_warning(png_ptr, "Incorrect tRNS chunk length");
  189080. png_crc_finish(png_ptr, length);
  189081. return;
  189082. }
  189083. if (length == 0)
  189084. {
  189085. png_warning(png_ptr, "Zero length tRNS chunk");
  189086. png_crc_finish(png_ptr, length);
  189087. return;
  189088. }
  189089. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  189090. png_ptr->num_trans = (png_uint_16)length;
  189091. }
  189092. else
  189093. {
  189094. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  189095. png_crc_finish(png_ptr, length);
  189096. return;
  189097. }
  189098. if (png_crc_finish(png_ptr, 0))
  189099. {
  189100. png_ptr->num_trans = 0;
  189101. return;
  189102. }
  189103. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  189104. &(png_ptr->trans_values));
  189105. }
  189106. #endif
  189107. #if defined(PNG_READ_bKGD_SUPPORTED)
  189108. void /* PRIVATE */
  189109. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189110. {
  189111. png_size_t truelen;
  189112. png_byte buf[6];
  189113. png_debug(1, "in png_handle_bKGD\n");
  189114. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189115. png_error(png_ptr, "Missing IHDR before bKGD");
  189116. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189117. {
  189118. png_warning(png_ptr, "Invalid bKGD after IDAT");
  189119. png_crc_finish(png_ptr, length);
  189120. return;
  189121. }
  189122. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  189123. !(png_ptr->mode & PNG_HAVE_PLTE))
  189124. {
  189125. png_warning(png_ptr, "Missing PLTE before bKGD");
  189126. png_crc_finish(png_ptr, length);
  189127. return;
  189128. }
  189129. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  189130. {
  189131. png_warning(png_ptr, "Duplicate bKGD chunk");
  189132. png_crc_finish(png_ptr, length);
  189133. return;
  189134. }
  189135. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189136. truelen = 1;
  189137. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  189138. truelen = 6;
  189139. else
  189140. truelen = 2;
  189141. if (length != truelen)
  189142. {
  189143. png_warning(png_ptr, "Incorrect bKGD chunk length");
  189144. png_crc_finish(png_ptr, length);
  189145. return;
  189146. }
  189147. png_crc_read(png_ptr, buf, truelen);
  189148. if (png_crc_finish(png_ptr, 0))
  189149. return;
  189150. /* We convert the index value into RGB components so that we can allow
  189151. * arbitrary RGB values for background when we have transparency, and
  189152. * so it is easy to determine the RGB values of the background color
  189153. * from the info_ptr struct. */
  189154. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189155. {
  189156. png_ptr->background.index = buf[0];
  189157. if(info_ptr->num_palette)
  189158. {
  189159. if(buf[0] > info_ptr->num_palette)
  189160. {
  189161. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  189162. return;
  189163. }
  189164. png_ptr->background.red =
  189165. (png_uint_16)png_ptr->palette[buf[0]].red;
  189166. png_ptr->background.green =
  189167. (png_uint_16)png_ptr->palette[buf[0]].green;
  189168. png_ptr->background.blue =
  189169. (png_uint_16)png_ptr->palette[buf[0]].blue;
  189170. }
  189171. }
  189172. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  189173. {
  189174. png_ptr->background.red =
  189175. png_ptr->background.green =
  189176. png_ptr->background.blue =
  189177. png_ptr->background.gray = png_get_uint_16(buf);
  189178. }
  189179. else
  189180. {
  189181. png_ptr->background.red = png_get_uint_16(buf);
  189182. png_ptr->background.green = png_get_uint_16(buf + 2);
  189183. png_ptr->background.blue = png_get_uint_16(buf + 4);
  189184. }
  189185. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  189186. }
  189187. #endif
  189188. #if defined(PNG_READ_hIST_SUPPORTED)
  189189. void /* PRIVATE */
  189190. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189191. {
  189192. unsigned int num, i;
  189193. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  189194. png_debug(1, "in png_handle_hIST\n");
  189195. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189196. png_error(png_ptr, "Missing IHDR before hIST");
  189197. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189198. {
  189199. png_warning(png_ptr, "Invalid hIST after IDAT");
  189200. png_crc_finish(png_ptr, length);
  189201. return;
  189202. }
  189203. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  189204. {
  189205. png_warning(png_ptr, "Missing PLTE before hIST");
  189206. png_crc_finish(png_ptr, length);
  189207. return;
  189208. }
  189209. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  189210. {
  189211. png_warning(png_ptr, "Duplicate hIST chunk");
  189212. png_crc_finish(png_ptr, length);
  189213. return;
  189214. }
  189215. num = length / 2 ;
  189216. if (num != (unsigned int) png_ptr->num_palette || num >
  189217. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  189218. {
  189219. png_warning(png_ptr, "Incorrect hIST chunk length");
  189220. png_crc_finish(png_ptr, length);
  189221. return;
  189222. }
  189223. for (i = 0; i < num; i++)
  189224. {
  189225. png_byte buf[2];
  189226. png_crc_read(png_ptr, buf, 2);
  189227. readbuf[i] = png_get_uint_16(buf);
  189228. }
  189229. if (png_crc_finish(png_ptr, 0))
  189230. return;
  189231. png_set_hIST(png_ptr, info_ptr, readbuf);
  189232. }
  189233. #endif
  189234. #if defined(PNG_READ_pHYs_SUPPORTED)
  189235. void /* PRIVATE */
  189236. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189237. {
  189238. png_byte buf[9];
  189239. png_uint_32 res_x, res_y;
  189240. int unit_type;
  189241. png_debug(1, "in png_handle_pHYs\n");
  189242. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189243. png_error(png_ptr, "Missing IHDR before pHYs");
  189244. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189245. {
  189246. png_warning(png_ptr, "Invalid pHYs after IDAT");
  189247. png_crc_finish(png_ptr, length);
  189248. return;
  189249. }
  189250. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  189251. {
  189252. png_warning(png_ptr, "Duplicate pHYs chunk");
  189253. png_crc_finish(png_ptr, length);
  189254. return;
  189255. }
  189256. if (length != 9)
  189257. {
  189258. png_warning(png_ptr, "Incorrect pHYs chunk length");
  189259. png_crc_finish(png_ptr, length);
  189260. return;
  189261. }
  189262. png_crc_read(png_ptr, buf, 9);
  189263. if (png_crc_finish(png_ptr, 0))
  189264. return;
  189265. res_x = png_get_uint_32(buf);
  189266. res_y = png_get_uint_32(buf + 4);
  189267. unit_type = buf[8];
  189268. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  189269. }
  189270. #endif
  189271. #if defined(PNG_READ_oFFs_SUPPORTED)
  189272. void /* PRIVATE */
  189273. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189274. {
  189275. png_byte buf[9];
  189276. png_int_32 offset_x, offset_y;
  189277. int unit_type;
  189278. png_debug(1, "in png_handle_oFFs\n");
  189279. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189280. png_error(png_ptr, "Missing IHDR before oFFs");
  189281. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189282. {
  189283. png_warning(png_ptr, "Invalid oFFs after IDAT");
  189284. png_crc_finish(png_ptr, length);
  189285. return;
  189286. }
  189287. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  189288. {
  189289. png_warning(png_ptr, "Duplicate oFFs chunk");
  189290. png_crc_finish(png_ptr, length);
  189291. return;
  189292. }
  189293. if (length != 9)
  189294. {
  189295. png_warning(png_ptr, "Incorrect oFFs chunk length");
  189296. png_crc_finish(png_ptr, length);
  189297. return;
  189298. }
  189299. png_crc_read(png_ptr, buf, 9);
  189300. if (png_crc_finish(png_ptr, 0))
  189301. return;
  189302. offset_x = png_get_int_32(buf);
  189303. offset_y = png_get_int_32(buf + 4);
  189304. unit_type = buf[8];
  189305. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  189306. }
  189307. #endif
  189308. #if defined(PNG_READ_pCAL_SUPPORTED)
  189309. /* read the pCAL chunk (described in the PNG Extensions document) */
  189310. void /* PRIVATE */
  189311. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189312. {
  189313. png_charp purpose;
  189314. png_int_32 X0, X1;
  189315. png_byte type, nparams;
  189316. png_charp buf, units, endptr;
  189317. png_charpp params;
  189318. png_size_t slength;
  189319. int i;
  189320. png_debug(1, "in png_handle_pCAL\n");
  189321. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189322. png_error(png_ptr, "Missing IHDR before pCAL");
  189323. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189324. {
  189325. png_warning(png_ptr, "Invalid pCAL after IDAT");
  189326. png_crc_finish(png_ptr, length);
  189327. return;
  189328. }
  189329. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  189330. {
  189331. png_warning(png_ptr, "Duplicate pCAL chunk");
  189332. png_crc_finish(png_ptr, length);
  189333. return;
  189334. }
  189335. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  189336. length + 1);
  189337. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  189338. if (purpose == NULL)
  189339. {
  189340. png_warning(png_ptr, "No memory for pCAL purpose.");
  189341. return;
  189342. }
  189343. slength = (png_size_t)length;
  189344. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  189345. if (png_crc_finish(png_ptr, 0))
  189346. {
  189347. png_free(png_ptr, purpose);
  189348. return;
  189349. }
  189350. purpose[slength] = 0x00; /* null terminate the last string */
  189351. png_debug(3, "Finding end of pCAL purpose string\n");
  189352. for (buf = purpose; *buf; buf++)
  189353. /* empty loop */ ;
  189354. endptr = purpose + slength;
  189355. /* We need to have at least 12 bytes after the purpose string
  189356. in order to get the parameter information. */
  189357. if (endptr <= buf + 12)
  189358. {
  189359. png_warning(png_ptr, "Invalid pCAL data");
  189360. png_free(png_ptr, purpose);
  189361. return;
  189362. }
  189363. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  189364. X0 = png_get_int_32((png_bytep)buf+1);
  189365. X1 = png_get_int_32((png_bytep)buf+5);
  189366. type = buf[9];
  189367. nparams = buf[10];
  189368. units = buf + 11;
  189369. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  189370. /* Check that we have the right number of parameters for known
  189371. equation types. */
  189372. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  189373. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  189374. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  189375. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  189376. {
  189377. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  189378. png_free(png_ptr, purpose);
  189379. return;
  189380. }
  189381. else if (type >= PNG_EQUATION_LAST)
  189382. {
  189383. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  189384. }
  189385. for (buf = units; *buf; buf++)
  189386. /* Empty loop to move past the units string. */ ;
  189387. png_debug(3, "Allocating pCAL parameters array\n");
  189388. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  189389. *png_sizeof(png_charp))) ;
  189390. if (params == NULL)
  189391. {
  189392. png_free(png_ptr, purpose);
  189393. png_warning(png_ptr, "No memory for pCAL params.");
  189394. return;
  189395. }
  189396. /* Get pointers to the start of each parameter string. */
  189397. for (i = 0; i < (int)nparams; i++)
  189398. {
  189399. buf++; /* Skip the null string terminator from previous parameter. */
  189400. png_debug1(3, "Reading pCAL parameter %d\n", i);
  189401. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  189402. /* Empty loop to move past each parameter string */ ;
  189403. /* Make sure we haven't run out of data yet */
  189404. if (buf > endptr)
  189405. {
  189406. png_warning(png_ptr, "Invalid pCAL data");
  189407. png_free(png_ptr, purpose);
  189408. png_free(png_ptr, params);
  189409. return;
  189410. }
  189411. }
  189412. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  189413. units, params);
  189414. png_free(png_ptr, purpose);
  189415. png_free(png_ptr, params);
  189416. }
  189417. #endif
  189418. #if defined(PNG_READ_sCAL_SUPPORTED)
  189419. /* read the sCAL chunk */
  189420. void /* PRIVATE */
  189421. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189422. {
  189423. png_charp buffer, ep;
  189424. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189425. double width, height;
  189426. png_charp vp;
  189427. #else
  189428. #ifdef PNG_FIXED_POINT_SUPPORTED
  189429. png_charp swidth, sheight;
  189430. #endif
  189431. #endif
  189432. png_size_t slength;
  189433. png_debug(1, "in png_handle_sCAL\n");
  189434. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189435. png_error(png_ptr, "Missing IHDR before sCAL");
  189436. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189437. {
  189438. png_warning(png_ptr, "Invalid sCAL after IDAT");
  189439. png_crc_finish(png_ptr, length);
  189440. return;
  189441. }
  189442. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  189443. {
  189444. png_warning(png_ptr, "Duplicate sCAL chunk");
  189445. png_crc_finish(png_ptr, length);
  189446. return;
  189447. }
  189448. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  189449. length + 1);
  189450. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  189451. if (buffer == NULL)
  189452. {
  189453. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  189454. return;
  189455. }
  189456. slength = (png_size_t)length;
  189457. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  189458. if (png_crc_finish(png_ptr, 0))
  189459. {
  189460. png_free(png_ptr, buffer);
  189461. return;
  189462. }
  189463. buffer[slength] = 0x00; /* null terminate the last string */
  189464. ep = buffer + 1; /* skip unit byte */
  189465. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189466. width = png_strtod(png_ptr, ep, &vp);
  189467. if (*vp)
  189468. {
  189469. png_warning(png_ptr, "malformed width string in sCAL chunk");
  189470. return;
  189471. }
  189472. #else
  189473. #ifdef PNG_FIXED_POINT_SUPPORTED
  189474. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  189475. if (swidth == NULL)
  189476. {
  189477. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  189478. return;
  189479. }
  189480. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  189481. #endif
  189482. #endif
  189483. for (ep = buffer; *ep; ep++)
  189484. /* empty loop */ ;
  189485. ep++;
  189486. if (buffer + slength < ep)
  189487. {
  189488. png_warning(png_ptr, "Truncated sCAL chunk");
  189489. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  189490. !defined(PNG_FLOATING_POINT_SUPPORTED)
  189491. png_free(png_ptr, swidth);
  189492. #endif
  189493. png_free(png_ptr, buffer);
  189494. return;
  189495. }
  189496. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189497. height = png_strtod(png_ptr, ep, &vp);
  189498. if (*vp)
  189499. {
  189500. png_warning(png_ptr, "malformed height string in sCAL chunk");
  189501. return;
  189502. }
  189503. #else
  189504. #ifdef PNG_FIXED_POINT_SUPPORTED
  189505. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  189506. if (swidth == NULL)
  189507. {
  189508. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  189509. return;
  189510. }
  189511. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  189512. #endif
  189513. #endif
  189514. if (buffer + slength < ep
  189515. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189516. || width <= 0. || height <= 0.
  189517. #endif
  189518. )
  189519. {
  189520. png_warning(png_ptr, "Invalid sCAL data");
  189521. png_free(png_ptr, buffer);
  189522. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  189523. png_free(png_ptr, swidth);
  189524. png_free(png_ptr, sheight);
  189525. #endif
  189526. return;
  189527. }
  189528. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189529. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  189530. #else
  189531. #ifdef PNG_FIXED_POINT_SUPPORTED
  189532. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  189533. #endif
  189534. #endif
  189535. png_free(png_ptr, buffer);
  189536. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  189537. png_free(png_ptr, swidth);
  189538. png_free(png_ptr, sheight);
  189539. #endif
  189540. }
  189541. #endif
  189542. #if defined(PNG_READ_tIME_SUPPORTED)
  189543. void /* PRIVATE */
  189544. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189545. {
  189546. png_byte buf[7];
  189547. png_time mod_time;
  189548. png_debug(1, "in png_handle_tIME\n");
  189549. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189550. png_error(png_ptr, "Out of place tIME chunk");
  189551. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  189552. {
  189553. png_warning(png_ptr, "Duplicate tIME chunk");
  189554. png_crc_finish(png_ptr, length);
  189555. return;
  189556. }
  189557. if (png_ptr->mode & PNG_HAVE_IDAT)
  189558. png_ptr->mode |= PNG_AFTER_IDAT;
  189559. if (length != 7)
  189560. {
  189561. png_warning(png_ptr, "Incorrect tIME chunk length");
  189562. png_crc_finish(png_ptr, length);
  189563. return;
  189564. }
  189565. png_crc_read(png_ptr, buf, 7);
  189566. if (png_crc_finish(png_ptr, 0))
  189567. return;
  189568. mod_time.second = buf[6];
  189569. mod_time.minute = buf[5];
  189570. mod_time.hour = buf[4];
  189571. mod_time.day = buf[3];
  189572. mod_time.month = buf[2];
  189573. mod_time.year = png_get_uint_16(buf);
  189574. png_set_tIME(png_ptr, info_ptr, &mod_time);
  189575. }
  189576. #endif
  189577. #if defined(PNG_READ_tEXt_SUPPORTED)
  189578. /* Note: this does not properly handle chunks that are > 64K under DOS */
  189579. void /* PRIVATE */
  189580. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189581. {
  189582. png_textp text_ptr;
  189583. png_charp key;
  189584. png_charp text;
  189585. png_uint_32 skip = 0;
  189586. png_size_t slength;
  189587. int ret;
  189588. png_debug(1, "in png_handle_tEXt\n");
  189589. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189590. png_error(png_ptr, "Missing IHDR before tEXt");
  189591. if (png_ptr->mode & PNG_HAVE_IDAT)
  189592. png_ptr->mode |= PNG_AFTER_IDAT;
  189593. #ifdef PNG_MAX_MALLOC_64K
  189594. if (length > (png_uint_32)65535L)
  189595. {
  189596. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189597. skip = length - (png_uint_32)65535L;
  189598. length = (png_uint_32)65535L;
  189599. }
  189600. #endif
  189601. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  189602. if (key == NULL)
  189603. {
  189604. png_warning(png_ptr, "No memory to process text chunk.");
  189605. return;
  189606. }
  189607. slength = (png_size_t)length;
  189608. png_crc_read(png_ptr, (png_bytep)key, slength);
  189609. if (png_crc_finish(png_ptr, skip))
  189610. {
  189611. png_free(png_ptr, key);
  189612. return;
  189613. }
  189614. key[slength] = 0x00;
  189615. for (text = key; *text; text++)
  189616. /* empty loop to find end of key */ ;
  189617. if (text != key + slength)
  189618. text++;
  189619. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  189620. (png_uint_32)png_sizeof(png_text));
  189621. if (text_ptr == NULL)
  189622. {
  189623. png_warning(png_ptr, "Not enough memory to process text chunk.");
  189624. png_free(png_ptr, key);
  189625. return;
  189626. }
  189627. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189628. text_ptr->key = key;
  189629. #ifdef PNG_iTXt_SUPPORTED
  189630. text_ptr->lang = NULL;
  189631. text_ptr->lang_key = NULL;
  189632. text_ptr->itxt_length = 0;
  189633. #endif
  189634. text_ptr->text = text;
  189635. text_ptr->text_length = png_strlen(text);
  189636. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189637. png_free(png_ptr, key);
  189638. png_free(png_ptr, text_ptr);
  189639. if (ret)
  189640. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  189641. }
  189642. #endif
  189643. #if defined(PNG_READ_zTXt_SUPPORTED)
  189644. /* note: this does not correctly handle chunks that are > 64K under DOS */
  189645. void /* PRIVATE */
  189646. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189647. {
  189648. png_textp text_ptr;
  189649. png_charp chunkdata;
  189650. png_charp text;
  189651. int comp_type;
  189652. int ret;
  189653. png_size_t slength, prefix_len, data_len;
  189654. png_debug(1, "in png_handle_zTXt\n");
  189655. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189656. png_error(png_ptr, "Missing IHDR before zTXt");
  189657. if (png_ptr->mode & PNG_HAVE_IDAT)
  189658. png_ptr->mode |= PNG_AFTER_IDAT;
  189659. #ifdef PNG_MAX_MALLOC_64K
  189660. /* We will no doubt have problems with chunks even half this size, but
  189661. there is no hard and fast rule to tell us where to stop. */
  189662. if (length > (png_uint_32)65535L)
  189663. {
  189664. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  189665. png_crc_finish(png_ptr, length);
  189666. return;
  189667. }
  189668. #endif
  189669. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  189670. if (chunkdata == NULL)
  189671. {
  189672. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  189673. return;
  189674. }
  189675. slength = (png_size_t)length;
  189676. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  189677. if (png_crc_finish(png_ptr, 0))
  189678. {
  189679. png_free(png_ptr, chunkdata);
  189680. return;
  189681. }
  189682. chunkdata[slength] = 0x00;
  189683. for (text = chunkdata; *text; text++)
  189684. /* empty loop */ ;
  189685. /* zTXt must have some text after the chunkdataword */
  189686. if (text >= chunkdata + slength - 2)
  189687. {
  189688. png_warning(png_ptr, "Truncated zTXt chunk");
  189689. png_free(png_ptr, chunkdata);
  189690. return;
  189691. }
  189692. else
  189693. {
  189694. comp_type = *(++text);
  189695. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  189696. {
  189697. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  189698. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  189699. }
  189700. text++; /* skip the compression_method byte */
  189701. }
  189702. prefix_len = text - chunkdata;
  189703. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  189704. (png_size_t)length, prefix_len, &data_len);
  189705. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  189706. (png_uint_32)png_sizeof(png_text));
  189707. if (text_ptr == NULL)
  189708. {
  189709. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  189710. png_free(png_ptr, chunkdata);
  189711. return;
  189712. }
  189713. text_ptr->compression = comp_type;
  189714. text_ptr->key = chunkdata;
  189715. #ifdef PNG_iTXt_SUPPORTED
  189716. text_ptr->lang = NULL;
  189717. text_ptr->lang_key = NULL;
  189718. text_ptr->itxt_length = 0;
  189719. #endif
  189720. text_ptr->text = chunkdata + prefix_len;
  189721. text_ptr->text_length = data_len;
  189722. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189723. png_free(png_ptr, text_ptr);
  189724. png_free(png_ptr, chunkdata);
  189725. if (ret)
  189726. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  189727. }
  189728. #endif
  189729. #if defined(PNG_READ_iTXt_SUPPORTED)
  189730. /* note: this does not correctly handle chunks that are > 64K under DOS */
  189731. void /* PRIVATE */
  189732. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189733. {
  189734. png_textp text_ptr;
  189735. png_charp chunkdata;
  189736. png_charp key, lang, text, lang_key;
  189737. int comp_flag;
  189738. int comp_type = 0;
  189739. int ret;
  189740. png_size_t slength, prefix_len, data_len;
  189741. png_debug(1, "in png_handle_iTXt\n");
  189742. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189743. png_error(png_ptr, "Missing IHDR before iTXt");
  189744. if (png_ptr->mode & PNG_HAVE_IDAT)
  189745. png_ptr->mode |= PNG_AFTER_IDAT;
  189746. #ifdef PNG_MAX_MALLOC_64K
  189747. /* We will no doubt have problems with chunks even half this size, but
  189748. there is no hard and fast rule to tell us where to stop. */
  189749. if (length > (png_uint_32)65535L)
  189750. {
  189751. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  189752. png_crc_finish(png_ptr, length);
  189753. return;
  189754. }
  189755. #endif
  189756. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  189757. if (chunkdata == NULL)
  189758. {
  189759. png_warning(png_ptr, "No memory to process iTXt chunk.");
  189760. return;
  189761. }
  189762. slength = (png_size_t)length;
  189763. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  189764. if (png_crc_finish(png_ptr, 0))
  189765. {
  189766. png_free(png_ptr, chunkdata);
  189767. return;
  189768. }
  189769. chunkdata[slength] = 0x00;
  189770. for (lang = chunkdata; *lang; lang++)
  189771. /* empty loop */ ;
  189772. lang++; /* skip NUL separator */
  189773. /* iTXt must have a language tag (possibly empty), two compression bytes,
  189774. translated keyword (possibly empty), and possibly some text after the
  189775. keyword */
  189776. if (lang >= chunkdata + slength - 3)
  189777. {
  189778. png_warning(png_ptr, "Truncated iTXt chunk");
  189779. png_free(png_ptr, chunkdata);
  189780. return;
  189781. }
  189782. else
  189783. {
  189784. comp_flag = *lang++;
  189785. comp_type = *lang++;
  189786. }
  189787. for (lang_key = lang; *lang_key; lang_key++)
  189788. /* empty loop */ ;
  189789. lang_key++; /* skip NUL separator */
  189790. if (lang_key >= chunkdata + slength)
  189791. {
  189792. png_warning(png_ptr, "Truncated iTXt chunk");
  189793. png_free(png_ptr, chunkdata);
  189794. return;
  189795. }
  189796. for (text = lang_key; *text; text++)
  189797. /* empty loop */ ;
  189798. text++; /* skip NUL separator */
  189799. if (text >= chunkdata + slength)
  189800. {
  189801. png_warning(png_ptr, "Malformed iTXt chunk");
  189802. png_free(png_ptr, chunkdata);
  189803. return;
  189804. }
  189805. prefix_len = text - chunkdata;
  189806. key=chunkdata;
  189807. if (comp_flag)
  189808. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  189809. (size_t)length, prefix_len, &data_len);
  189810. else
  189811. data_len=png_strlen(chunkdata + prefix_len);
  189812. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  189813. (png_uint_32)png_sizeof(png_text));
  189814. if (text_ptr == NULL)
  189815. {
  189816. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  189817. png_free(png_ptr, chunkdata);
  189818. return;
  189819. }
  189820. text_ptr->compression = (int)comp_flag + 1;
  189821. text_ptr->lang_key = chunkdata+(lang_key-key);
  189822. text_ptr->lang = chunkdata+(lang-key);
  189823. text_ptr->itxt_length = data_len;
  189824. text_ptr->text_length = 0;
  189825. text_ptr->key = chunkdata;
  189826. text_ptr->text = chunkdata + prefix_len;
  189827. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189828. png_free(png_ptr, text_ptr);
  189829. png_free(png_ptr, chunkdata);
  189830. if (ret)
  189831. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  189832. }
  189833. #endif
  189834. /* This function is called when we haven't found a handler for a
  189835. chunk. If there isn't a problem with the chunk itself (ie bad
  189836. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  189837. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  189838. case it will be saved away to be written out later. */
  189839. void /* PRIVATE */
  189840. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189841. {
  189842. png_uint_32 skip = 0;
  189843. png_debug(1, "in png_handle_unknown\n");
  189844. if (png_ptr->mode & PNG_HAVE_IDAT)
  189845. {
  189846. #ifdef PNG_USE_LOCAL_ARRAYS
  189847. PNG_CONST PNG_IDAT;
  189848. #endif
  189849. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  189850. png_ptr->mode |= PNG_AFTER_IDAT;
  189851. }
  189852. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189853. if (!(png_ptr->chunk_name[0] & 0x20))
  189854. {
  189855. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189856. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189857. PNG_HANDLE_CHUNK_ALWAYS
  189858. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189859. && png_ptr->read_user_chunk_fn == NULL
  189860. #endif
  189861. )
  189862. #endif
  189863. png_chunk_error(png_ptr, "unknown critical chunk");
  189864. }
  189865. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189866. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  189867. (png_ptr->read_user_chunk_fn != NULL))
  189868. {
  189869. #ifdef PNG_MAX_MALLOC_64K
  189870. if (length > (png_uint_32)65535L)
  189871. {
  189872. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189873. skip = length - (png_uint_32)65535L;
  189874. length = (png_uint_32)65535L;
  189875. }
  189876. #endif
  189877. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189878. (png_charp)png_ptr->chunk_name, 5);
  189879. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189880. png_ptr->unknown_chunk.size = (png_size_t)length;
  189881. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189882. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189883. if(png_ptr->read_user_chunk_fn != NULL)
  189884. {
  189885. /* callback to user unknown chunk handler */
  189886. int ret;
  189887. ret = (*(png_ptr->read_user_chunk_fn))
  189888. (png_ptr, &png_ptr->unknown_chunk);
  189889. if (ret < 0)
  189890. png_chunk_error(png_ptr, "error in user chunk");
  189891. if (ret == 0)
  189892. {
  189893. if (!(png_ptr->chunk_name[0] & 0x20))
  189894. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189895. PNG_HANDLE_CHUNK_ALWAYS)
  189896. png_chunk_error(png_ptr, "unknown critical chunk");
  189897. png_set_unknown_chunks(png_ptr, info_ptr,
  189898. &png_ptr->unknown_chunk, 1);
  189899. }
  189900. }
  189901. #else
  189902. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189903. #endif
  189904. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189905. png_ptr->unknown_chunk.data = NULL;
  189906. }
  189907. else
  189908. #endif
  189909. skip = length;
  189910. png_crc_finish(png_ptr, skip);
  189911. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189912. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  189913. #endif
  189914. }
  189915. /* This function is called to verify that a chunk name is valid.
  189916. This function can't have the "critical chunk check" incorporated
  189917. into it, since in the future we will need to be able to call user
  189918. functions to handle unknown critical chunks after we check that
  189919. the chunk name itself is valid. */
  189920. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  189921. void /* PRIVATE */
  189922. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  189923. {
  189924. png_debug(1, "in png_check_chunk_name\n");
  189925. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  189926. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  189927. {
  189928. png_chunk_error(png_ptr, "invalid chunk type");
  189929. }
  189930. }
  189931. /* Combines the row recently read in with the existing pixels in the
  189932. row. This routine takes care of alpha and transparency if requested.
  189933. This routine also handles the two methods of progressive display
  189934. of interlaced images, depending on the mask value.
  189935. The mask value describes which pixels are to be combined with
  189936. the row. The pattern always repeats every 8 pixels, so just 8
  189937. bits are needed. A one indicates the pixel is to be combined,
  189938. a zero indicates the pixel is to be skipped. This is in addition
  189939. to any alpha or transparency value associated with the pixel. If
  189940. you want all pixels to be combined, pass 0xff (255) in mask. */
  189941. void /* PRIVATE */
  189942. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  189943. {
  189944. png_debug(1,"in png_combine_row\n");
  189945. if (mask == 0xff)
  189946. {
  189947. png_memcpy(row, png_ptr->row_buf + 1,
  189948. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  189949. }
  189950. else
  189951. {
  189952. switch (png_ptr->row_info.pixel_depth)
  189953. {
  189954. case 1:
  189955. {
  189956. png_bytep sp = png_ptr->row_buf + 1;
  189957. png_bytep dp = row;
  189958. int s_inc, s_start, s_end;
  189959. int m = 0x80;
  189960. int shift;
  189961. png_uint_32 i;
  189962. png_uint_32 row_width = png_ptr->width;
  189963. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  189964. if (png_ptr->transformations & PNG_PACKSWAP)
  189965. {
  189966. s_start = 0;
  189967. s_end = 7;
  189968. s_inc = 1;
  189969. }
  189970. else
  189971. #endif
  189972. {
  189973. s_start = 7;
  189974. s_end = 0;
  189975. s_inc = -1;
  189976. }
  189977. shift = s_start;
  189978. for (i = 0; i < row_width; i++)
  189979. {
  189980. if (m & mask)
  189981. {
  189982. int value;
  189983. value = (*sp >> shift) & 0x01;
  189984. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  189985. *dp |= (png_byte)(value << shift);
  189986. }
  189987. if (shift == s_end)
  189988. {
  189989. shift = s_start;
  189990. sp++;
  189991. dp++;
  189992. }
  189993. else
  189994. shift += s_inc;
  189995. if (m == 1)
  189996. m = 0x80;
  189997. else
  189998. m >>= 1;
  189999. }
  190000. break;
  190001. }
  190002. case 2:
  190003. {
  190004. png_bytep sp = png_ptr->row_buf + 1;
  190005. png_bytep dp = row;
  190006. int s_start, s_end, s_inc;
  190007. int m = 0x80;
  190008. int shift;
  190009. png_uint_32 i;
  190010. png_uint_32 row_width = png_ptr->width;
  190011. int value;
  190012. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190013. if (png_ptr->transformations & PNG_PACKSWAP)
  190014. {
  190015. s_start = 0;
  190016. s_end = 6;
  190017. s_inc = 2;
  190018. }
  190019. else
  190020. #endif
  190021. {
  190022. s_start = 6;
  190023. s_end = 0;
  190024. s_inc = -2;
  190025. }
  190026. shift = s_start;
  190027. for (i = 0; i < row_width; i++)
  190028. {
  190029. if (m & mask)
  190030. {
  190031. value = (*sp >> shift) & 0x03;
  190032. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  190033. *dp |= (png_byte)(value << shift);
  190034. }
  190035. if (shift == s_end)
  190036. {
  190037. shift = s_start;
  190038. sp++;
  190039. dp++;
  190040. }
  190041. else
  190042. shift += s_inc;
  190043. if (m == 1)
  190044. m = 0x80;
  190045. else
  190046. m >>= 1;
  190047. }
  190048. break;
  190049. }
  190050. case 4:
  190051. {
  190052. png_bytep sp = png_ptr->row_buf + 1;
  190053. png_bytep dp = row;
  190054. int s_start, s_end, s_inc;
  190055. int m = 0x80;
  190056. int shift;
  190057. png_uint_32 i;
  190058. png_uint_32 row_width = png_ptr->width;
  190059. int value;
  190060. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190061. if (png_ptr->transformations & PNG_PACKSWAP)
  190062. {
  190063. s_start = 0;
  190064. s_end = 4;
  190065. s_inc = 4;
  190066. }
  190067. else
  190068. #endif
  190069. {
  190070. s_start = 4;
  190071. s_end = 0;
  190072. s_inc = -4;
  190073. }
  190074. shift = s_start;
  190075. for (i = 0; i < row_width; i++)
  190076. {
  190077. if (m & mask)
  190078. {
  190079. value = (*sp >> shift) & 0xf;
  190080. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  190081. *dp |= (png_byte)(value << shift);
  190082. }
  190083. if (shift == s_end)
  190084. {
  190085. shift = s_start;
  190086. sp++;
  190087. dp++;
  190088. }
  190089. else
  190090. shift += s_inc;
  190091. if (m == 1)
  190092. m = 0x80;
  190093. else
  190094. m >>= 1;
  190095. }
  190096. break;
  190097. }
  190098. default:
  190099. {
  190100. png_bytep sp = png_ptr->row_buf + 1;
  190101. png_bytep dp = row;
  190102. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  190103. png_uint_32 i;
  190104. png_uint_32 row_width = png_ptr->width;
  190105. png_byte m = 0x80;
  190106. for (i = 0; i < row_width; i++)
  190107. {
  190108. if (m & mask)
  190109. {
  190110. png_memcpy(dp, sp, pixel_bytes);
  190111. }
  190112. sp += pixel_bytes;
  190113. dp += pixel_bytes;
  190114. if (m == 1)
  190115. m = 0x80;
  190116. else
  190117. m >>= 1;
  190118. }
  190119. break;
  190120. }
  190121. }
  190122. }
  190123. }
  190124. #ifdef PNG_READ_INTERLACING_SUPPORTED
  190125. /* OLD pre-1.0.9 interface:
  190126. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  190127. png_uint_32 transformations)
  190128. */
  190129. void /* PRIVATE */
  190130. png_do_read_interlace(png_structp png_ptr)
  190131. {
  190132. png_row_infop row_info = &(png_ptr->row_info);
  190133. png_bytep row = png_ptr->row_buf + 1;
  190134. int pass = png_ptr->pass;
  190135. png_uint_32 transformations = png_ptr->transformations;
  190136. #ifdef PNG_USE_LOCAL_ARRAYS
  190137. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  190138. /* offset to next interlace block */
  190139. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  190140. #endif
  190141. png_debug(1,"in png_do_read_interlace\n");
  190142. if (row != NULL && row_info != NULL)
  190143. {
  190144. png_uint_32 final_width;
  190145. final_width = row_info->width * png_pass_inc[pass];
  190146. switch (row_info->pixel_depth)
  190147. {
  190148. case 1:
  190149. {
  190150. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  190151. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  190152. int sshift, dshift;
  190153. int s_start, s_end, s_inc;
  190154. int jstop = png_pass_inc[pass];
  190155. png_byte v;
  190156. png_uint_32 i;
  190157. int j;
  190158. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190159. if (transformations & PNG_PACKSWAP)
  190160. {
  190161. sshift = (int)((row_info->width + 7) & 0x07);
  190162. dshift = (int)((final_width + 7) & 0x07);
  190163. s_start = 7;
  190164. s_end = 0;
  190165. s_inc = -1;
  190166. }
  190167. else
  190168. #endif
  190169. {
  190170. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  190171. dshift = 7 - (int)((final_width + 7) & 0x07);
  190172. s_start = 0;
  190173. s_end = 7;
  190174. s_inc = 1;
  190175. }
  190176. for (i = 0; i < row_info->width; i++)
  190177. {
  190178. v = (png_byte)((*sp >> sshift) & 0x01);
  190179. for (j = 0; j < jstop; j++)
  190180. {
  190181. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  190182. *dp |= (png_byte)(v << dshift);
  190183. if (dshift == s_end)
  190184. {
  190185. dshift = s_start;
  190186. dp--;
  190187. }
  190188. else
  190189. dshift += s_inc;
  190190. }
  190191. if (sshift == s_end)
  190192. {
  190193. sshift = s_start;
  190194. sp--;
  190195. }
  190196. else
  190197. sshift += s_inc;
  190198. }
  190199. break;
  190200. }
  190201. case 2:
  190202. {
  190203. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  190204. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  190205. int sshift, dshift;
  190206. int s_start, s_end, s_inc;
  190207. int jstop = png_pass_inc[pass];
  190208. png_uint_32 i;
  190209. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190210. if (transformations & PNG_PACKSWAP)
  190211. {
  190212. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  190213. dshift = (int)(((final_width + 3) & 0x03) << 1);
  190214. s_start = 6;
  190215. s_end = 0;
  190216. s_inc = -2;
  190217. }
  190218. else
  190219. #endif
  190220. {
  190221. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  190222. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  190223. s_start = 0;
  190224. s_end = 6;
  190225. s_inc = 2;
  190226. }
  190227. for (i = 0; i < row_info->width; i++)
  190228. {
  190229. png_byte v;
  190230. int j;
  190231. v = (png_byte)((*sp >> sshift) & 0x03);
  190232. for (j = 0; j < jstop; j++)
  190233. {
  190234. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  190235. *dp |= (png_byte)(v << dshift);
  190236. if (dshift == s_end)
  190237. {
  190238. dshift = s_start;
  190239. dp--;
  190240. }
  190241. else
  190242. dshift += s_inc;
  190243. }
  190244. if (sshift == s_end)
  190245. {
  190246. sshift = s_start;
  190247. sp--;
  190248. }
  190249. else
  190250. sshift += s_inc;
  190251. }
  190252. break;
  190253. }
  190254. case 4:
  190255. {
  190256. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  190257. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  190258. int sshift, dshift;
  190259. int s_start, s_end, s_inc;
  190260. png_uint_32 i;
  190261. int jstop = png_pass_inc[pass];
  190262. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190263. if (transformations & PNG_PACKSWAP)
  190264. {
  190265. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  190266. dshift = (int)(((final_width + 1) & 0x01) << 2);
  190267. s_start = 4;
  190268. s_end = 0;
  190269. s_inc = -4;
  190270. }
  190271. else
  190272. #endif
  190273. {
  190274. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  190275. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  190276. s_start = 0;
  190277. s_end = 4;
  190278. s_inc = 4;
  190279. }
  190280. for (i = 0; i < row_info->width; i++)
  190281. {
  190282. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  190283. int j;
  190284. for (j = 0; j < jstop; j++)
  190285. {
  190286. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  190287. *dp |= (png_byte)(v << dshift);
  190288. if (dshift == s_end)
  190289. {
  190290. dshift = s_start;
  190291. dp--;
  190292. }
  190293. else
  190294. dshift += s_inc;
  190295. }
  190296. if (sshift == s_end)
  190297. {
  190298. sshift = s_start;
  190299. sp--;
  190300. }
  190301. else
  190302. sshift += s_inc;
  190303. }
  190304. break;
  190305. }
  190306. default:
  190307. {
  190308. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  190309. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  190310. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  190311. int jstop = png_pass_inc[pass];
  190312. png_uint_32 i;
  190313. for (i = 0; i < row_info->width; i++)
  190314. {
  190315. png_byte v[8];
  190316. int j;
  190317. png_memcpy(v, sp, pixel_bytes);
  190318. for (j = 0; j < jstop; j++)
  190319. {
  190320. png_memcpy(dp, v, pixel_bytes);
  190321. dp -= pixel_bytes;
  190322. }
  190323. sp -= pixel_bytes;
  190324. }
  190325. break;
  190326. }
  190327. }
  190328. row_info->width = final_width;
  190329. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  190330. }
  190331. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  190332. transformations = transformations; /* silence compiler warning */
  190333. #endif
  190334. }
  190335. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  190336. void /* PRIVATE */
  190337. png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row,
  190338. png_bytep prev_row, int filter)
  190339. {
  190340. png_debug(1, "in png_read_filter_row\n");
  190341. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  190342. switch (filter)
  190343. {
  190344. case PNG_FILTER_VALUE_NONE:
  190345. break;
  190346. case PNG_FILTER_VALUE_SUB:
  190347. {
  190348. png_uint_32 i;
  190349. png_uint_32 istop = row_info->rowbytes;
  190350. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  190351. png_bytep rp = row + bpp;
  190352. png_bytep lp = row;
  190353. for (i = bpp; i < istop; i++)
  190354. {
  190355. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  190356. rp++;
  190357. }
  190358. break;
  190359. }
  190360. case PNG_FILTER_VALUE_UP:
  190361. {
  190362. png_uint_32 i;
  190363. png_uint_32 istop = row_info->rowbytes;
  190364. png_bytep rp = row;
  190365. png_bytep pp = prev_row;
  190366. for (i = 0; i < istop; i++)
  190367. {
  190368. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  190369. rp++;
  190370. }
  190371. break;
  190372. }
  190373. case PNG_FILTER_VALUE_AVG:
  190374. {
  190375. png_uint_32 i;
  190376. png_bytep rp = row;
  190377. png_bytep pp = prev_row;
  190378. png_bytep lp = row;
  190379. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  190380. png_uint_32 istop = row_info->rowbytes - bpp;
  190381. for (i = 0; i < bpp; i++)
  190382. {
  190383. *rp = (png_byte)(((int)(*rp) +
  190384. ((int)(*pp++) / 2 )) & 0xff);
  190385. rp++;
  190386. }
  190387. for (i = 0; i < istop; i++)
  190388. {
  190389. *rp = (png_byte)(((int)(*rp) +
  190390. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  190391. rp++;
  190392. }
  190393. break;
  190394. }
  190395. case PNG_FILTER_VALUE_PAETH:
  190396. {
  190397. png_uint_32 i;
  190398. png_bytep rp = row;
  190399. png_bytep pp = prev_row;
  190400. png_bytep lp = row;
  190401. png_bytep cp = prev_row;
  190402. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  190403. png_uint_32 istop=row_info->rowbytes - bpp;
  190404. for (i = 0; i < bpp; i++)
  190405. {
  190406. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  190407. rp++;
  190408. }
  190409. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  190410. {
  190411. int a, b, c, pa, pb, pc, p;
  190412. a = *lp++;
  190413. b = *pp++;
  190414. c = *cp++;
  190415. p = b - c;
  190416. pc = a - c;
  190417. #ifdef PNG_USE_ABS
  190418. pa = abs(p);
  190419. pb = abs(pc);
  190420. pc = abs(p + pc);
  190421. #else
  190422. pa = p < 0 ? -p : p;
  190423. pb = pc < 0 ? -pc : pc;
  190424. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  190425. #endif
  190426. /*
  190427. if (pa <= pb && pa <= pc)
  190428. p = a;
  190429. else if (pb <= pc)
  190430. p = b;
  190431. else
  190432. p = c;
  190433. */
  190434. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  190435. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  190436. rp++;
  190437. }
  190438. break;
  190439. }
  190440. default:
  190441. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  190442. *row=0;
  190443. break;
  190444. }
  190445. }
  190446. void /* PRIVATE */
  190447. png_read_finish_row(png_structp png_ptr)
  190448. {
  190449. #ifdef PNG_USE_LOCAL_ARRAYS
  190450. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  190451. /* start of interlace block */
  190452. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  190453. /* offset to next interlace block */
  190454. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  190455. /* start of interlace block in the y direction */
  190456. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  190457. /* offset to next interlace block in the y direction */
  190458. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  190459. #endif
  190460. png_debug(1, "in png_read_finish_row\n");
  190461. png_ptr->row_number++;
  190462. if (png_ptr->row_number < png_ptr->num_rows)
  190463. return;
  190464. if (png_ptr->interlaced)
  190465. {
  190466. png_ptr->row_number = 0;
  190467. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  190468. png_ptr->rowbytes + 1);
  190469. do
  190470. {
  190471. png_ptr->pass++;
  190472. if (png_ptr->pass >= 7)
  190473. break;
  190474. png_ptr->iwidth = (png_ptr->width +
  190475. png_pass_inc[png_ptr->pass] - 1 -
  190476. png_pass_start[png_ptr->pass]) /
  190477. png_pass_inc[png_ptr->pass];
  190478. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  190479. png_ptr->iwidth) + 1;
  190480. if (!(png_ptr->transformations & PNG_INTERLACE))
  190481. {
  190482. png_ptr->num_rows = (png_ptr->height +
  190483. png_pass_yinc[png_ptr->pass] - 1 -
  190484. png_pass_ystart[png_ptr->pass]) /
  190485. png_pass_yinc[png_ptr->pass];
  190486. if (!(png_ptr->num_rows))
  190487. continue;
  190488. }
  190489. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  190490. break;
  190491. } while (png_ptr->iwidth == 0);
  190492. if (png_ptr->pass < 7)
  190493. return;
  190494. }
  190495. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  190496. {
  190497. #ifdef PNG_USE_LOCAL_ARRAYS
  190498. PNG_CONST PNG_IDAT;
  190499. #endif
  190500. char extra;
  190501. int ret;
  190502. png_ptr->zstream.next_out = (Byte *)&extra;
  190503. png_ptr->zstream.avail_out = (uInt)1;
  190504. for(;;)
  190505. {
  190506. if (!(png_ptr->zstream.avail_in))
  190507. {
  190508. while (!png_ptr->idat_size)
  190509. {
  190510. png_byte chunk_length[4];
  190511. png_crc_finish(png_ptr, 0);
  190512. png_read_data(png_ptr, chunk_length, 4);
  190513. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  190514. png_reset_crc(png_ptr);
  190515. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  190516. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  190517. png_error(png_ptr, "Not enough image data");
  190518. }
  190519. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  190520. png_ptr->zstream.next_in = png_ptr->zbuf;
  190521. if (png_ptr->zbuf_size > png_ptr->idat_size)
  190522. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  190523. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  190524. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  190525. }
  190526. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  190527. if (ret == Z_STREAM_END)
  190528. {
  190529. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  190530. png_ptr->idat_size)
  190531. png_warning(png_ptr, "Extra compressed data");
  190532. png_ptr->mode |= PNG_AFTER_IDAT;
  190533. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  190534. break;
  190535. }
  190536. if (ret != Z_OK)
  190537. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  190538. "Decompression Error");
  190539. if (!(png_ptr->zstream.avail_out))
  190540. {
  190541. png_warning(png_ptr, "Extra compressed data.");
  190542. png_ptr->mode |= PNG_AFTER_IDAT;
  190543. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  190544. break;
  190545. }
  190546. }
  190547. png_ptr->zstream.avail_out = 0;
  190548. }
  190549. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  190550. png_warning(png_ptr, "Extra compression data");
  190551. inflateReset(&png_ptr->zstream);
  190552. png_ptr->mode |= PNG_AFTER_IDAT;
  190553. }
  190554. void /* PRIVATE */
  190555. png_read_start_row(png_structp png_ptr)
  190556. {
  190557. #ifdef PNG_USE_LOCAL_ARRAYS
  190558. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  190559. /* start of interlace block */
  190560. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  190561. /* offset to next interlace block */
  190562. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  190563. /* start of interlace block in the y direction */
  190564. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  190565. /* offset to next interlace block in the y direction */
  190566. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  190567. #endif
  190568. int max_pixel_depth;
  190569. png_uint_32 row_bytes;
  190570. png_debug(1, "in png_read_start_row\n");
  190571. png_ptr->zstream.avail_in = 0;
  190572. png_init_read_transformations(png_ptr);
  190573. if (png_ptr->interlaced)
  190574. {
  190575. if (!(png_ptr->transformations & PNG_INTERLACE))
  190576. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  190577. png_pass_ystart[0]) / png_pass_yinc[0];
  190578. else
  190579. png_ptr->num_rows = png_ptr->height;
  190580. png_ptr->iwidth = (png_ptr->width +
  190581. png_pass_inc[png_ptr->pass] - 1 -
  190582. png_pass_start[png_ptr->pass]) /
  190583. png_pass_inc[png_ptr->pass];
  190584. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  190585. png_ptr->irowbytes = (png_size_t)row_bytes;
  190586. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  190587. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  190588. }
  190589. else
  190590. {
  190591. png_ptr->num_rows = png_ptr->height;
  190592. png_ptr->iwidth = png_ptr->width;
  190593. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  190594. }
  190595. max_pixel_depth = png_ptr->pixel_depth;
  190596. #if defined(PNG_READ_PACK_SUPPORTED)
  190597. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  190598. max_pixel_depth = 8;
  190599. #endif
  190600. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190601. if (png_ptr->transformations & PNG_EXPAND)
  190602. {
  190603. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190604. {
  190605. if (png_ptr->num_trans)
  190606. max_pixel_depth = 32;
  190607. else
  190608. max_pixel_depth = 24;
  190609. }
  190610. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  190611. {
  190612. if (max_pixel_depth < 8)
  190613. max_pixel_depth = 8;
  190614. if (png_ptr->num_trans)
  190615. max_pixel_depth *= 2;
  190616. }
  190617. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  190618. {
  190619. if (png_ptr->num_trans)
  190620. {
  190621. max_pixel_depth *= 4;
  190622. max_pixel_depth /= 3;
  190623. }
  190624. }
  190625. }
  190626. #endif
  190627. #if defined(PNG_READ_FILLER_SUPPORTED)
  190628. if (png_ptr->transformations & (PNG_FILLER))
  190629. {
  190630. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190631. max_pixel_depth = 32;
  190632. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  190633. {
  190634. if (max_pixel_depth <= 8)
  190635. max_pixel_depth = 16;
  190636. else
  190637. max_pixel_depth = 32;
  190638. }
  190639. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  190640. {
  190641. if (max_pixel_depth <= 32)
  190642. max_pixel_depth = 32;
  190643. else
  190644. max_pixel_depth = 64;
  190645. }
  190646. }
  190647. #endif
  190648. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190649. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190650. {
  190651. if (
  190652. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190653. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  190654. #endif
  190655. #if defined(PNG_READ_FILLER_SUPPORTED)
  190656. (png_ptr->transformations & (PNG_FILLER)) ||
  190657. #endif
  190658. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  190659. {
  190660. if (max_pixel_depth <= 16)
  190661. max_pixel_depth = 32;
  190662. else
  190663. max_pixel_depth = 64;
  190664. }
  190665. else
  190666. {
  190667. if (max_pixel_depth <= 8)
  190668. {
  190669. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190670. max_pixel_depth = 32;
  190671. else
  190672. max_pixel_depth = 24;
  190673. }
  190674. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190675. max_pixel_depth = 64;
  190676. else
  190677. max_pixel_depth = 48;
  190678. }
  190679. }
  190680. #endif
  190681. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  190682. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  190683. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  190684. {
  190685. int user_pixel_depth=png_ptr->user_transform_depth*
  190686. png_ptr->user_transform_channels;
  190687. if(user_pixel_depth > max_pixel_depth)
  190688. max_pixel_depth=user_pixel_depth;
  190689. }
  190690. #endif
  190691. /* align the width on the next larger 8 pixels. Mainly used
  190692. for interlacing */
  190693. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  190694. /* calculate the maximum bytes needed, adding a byte and a pixel
  190695. for safety's sake */
  190696. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  190697. 1 + ((max_pixel_depth + 7) >> 3);
  190698. #ifdef PNG_MAX_MALLOC_64K
  190699. if (row_bytes > (png_uint_32)65536L)
  190700. png_error(png_ptr, "This image requires a row greater than 64KB");
  190701. #endif
  190702. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  190703. png_ptr->row_buf = png_ptr->big_row_buf+32;
  190704. #ifdef PNG_MAX_MALLOC_64K
  190705. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  190706. png_error(png_ptr, "This image requires a row greater than 64KB");
  190707. #endif
  190708. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  190709. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  190710. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  190711. png_ptr->rowbytes + 1));
  190712. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  190713. png_debug1(3, "width = %lu,\n", png_ptr->width);
  190714. png_debug1(3, "height = %lu,\n", png_ptr->height);
  190715. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  190716. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  190717. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  190718. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  190719. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  190720. }
  190721. #endif /* PNG_READ_SUPPORTED */
  190722. /********* End of inlined file: pngrutil.c *********/
  190723. /********* Start of inlined file: pngset.c *********/
  190724. /* pngset.c - storage of image information into info struct
  190725. *
  190726. * Last changed in libpng 1.2.21 [October 4, 2007]
  190727. * For conditions of distribution and use, see copyright notice in png.h
  190728. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190729. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190730. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190731. *
  190732. * The functions here are used during reads to store data from the file
  190733. * into the info struct, and during writes to store application data
  190734. * into the info struct for writing into the file. This abstracts the
  190735. * info struct and allows us to change the structure in the future.
  190736. */
  190737. #define PNG_INTERNAL
  190738. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  190739. #if defined(PNG_bKGD_SUPPORTED)
  190740. void PNGAPI
  190741. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  190742. {
  190743. png_debug1(1, "in %s storage function\n", "bKGD");
  190744. if (png_ptr == NULL || info_ptr == NULL)
  190745. return;
  190746. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  190747. info_ptr->valid |= PNG_INFO_bKGD;
  190748. }
  190749. #endif
  190750. #if defined(PNG_cHRM_SUPPORTED)
  190751. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190752. void PNGAPI
  190753. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  190754. double white_x, double white_y, double red_x, double red_y,
  190755. double green_x, double green_y, double blue_x, double blue_y)
  190756. {
  190757. png_debug1(1, "in %s storage function\n", "cHRM");
  190758. if (png_ptr == NULL || info_ptr == NULL)
  190759. return;
  190760. if (white_x < 0.0 || white_y < 0.0 ||
  190761. red_x < 0.0 || red_y < 0.0 ||
  190762. green_x < 0.0 || green_y < 0.0 ||
  190763. blue_x < 0.0 || blue_y < 0.0)
  190764. {
  190765. png_warning(png_ptr,
  190766. "Ignoring attempt to set negative chromaticity value");
  190767. return;
  190768. }
  190769. if (white_x > 21474.83 || white_y > 21474.83 ||
  190770. red_x > 21474.83 || red_y > 21474.83 ||
  190771. green_x > 21474.83 || green_y > 21474.83 ||
  190772. blue_x > 21474.83 || blue_y > 21474.83)
  190773. {
  190774. png_warning(png_ptr,
  190775. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  190776. return;
  190777. }
  190778. info_ptr->x_white = (float)white_x;
  190779. info_ptr->y_white = (float)white_y;
  190780. info_ptr->x_red = (float)red_x;
  190781. info_ptr->y_red = (float)red_y;
  190782. info_ptr->x_green = (float)green_x;
  190783. info_ptr->y_green = (float)green_y;
  190784. info_ptr->x_blue = (float)blue_x;
  190785. info_ptr->y_blue = (float)blue_y;
  190786. #ifdef PNG_FIXED_POINT_SUPPORTED
  190787. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  190788. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  190789. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  190790. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  190791. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  190792. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  190793. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  190794. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  190795. #endif
  190796. info_ptr->valid |= PNG_INFO_cHRM;
  190797. }
  190798. #endif
  190799. #ifdef PNG_FIXED_POINT_SUPPORTED
  190800. void PNGAPI
  190801. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  190802. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  190803. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  190804. png_fixed_point blue_x, png_fixed_point blue_y)
  190805. {
  190806. png_debug1(1, "in %s storage function\n", "cHRM");
  190807. if (png_ptr == NULL || info_ptr == NULL)
  190808. return;
  190809. if (white_x < 0 || white_y < 0 ||
  190810. red_x < 0 || red_y < 0 ||
  190811. green_x < 0 || green_y < 0 ||
  190812. blue_x < 0 || blue_y < 0)
  190813. {
  190814. png_warning(png_ptr,
  190815. "Ignoring attempt to set negative chromaticity value");
  190816. return;
  190817. }
  190818. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190819. if (white_x > (double) PNG_UINT_31_MAX ||
  190820. white_y > (double) PNG_UINT_31_MAX ||
  190821. red_x > (double) PNG_UINT_31_MAX ||
  190822. red_y > (double) PNG_UINT_31_MAX ||
  190823. green_x > (double) PNG_UINT_31_MAX ||
  190824. green_y > (double) PNG_UINT_31_MAX ||
  190825. blue_x > (double) PNG_UINT_31_MAX ||
  190826. blue_y > (double) PNG_UINT_31_MAX)
  190827. #else
  190828. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190829. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190830. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190831. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190832. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190833. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190834. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190835. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  190836. #endif
  190837. {
  190838. png_warning(png_ptr,
  190839. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  190840. return;
  190841. }
  190842. info_ptr->int_x_white = white_x;
  190843. info_ptr->int_y_white = white_y;
  190844. info_ptr->int_x_red = red_x;
  190845. info_ptr->int_y_red = red_y;
  190846. info_ptr->int_x_green = green_x;
  190847. info_ptr->int_y_green = green_y;
  190848. info_ptr->int_x_blue = blue_x;
  190849. info_ptr->int_y_blue = blue_y;
  190850. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190851. info_ptr->x_white = (float)(white_x/100000.);
  190852. info_ptr->y_white = (float)(white_y/100000.);
  190853. info_ptr->x_red = (float)( red_x/100000.);
  190854. info_ptr->y_red = (float)( red_y/100000.);
  190855. info_ptr->x_green = (float)(green_x/100000.);
  190856. info_ptr->y_green = (float)(green_y/100000.);
  190857. info_ptr->x_blue = (float)( blue_x/100000.);
  190858. info_ptr->y_blue = (float)( blue_y/100000.);
  190859. #endif
  190860. info_ptr->valid |= PNG_INFO_cHRM;
  190861. }
  190862. #endif
  190863. #endif
  190864. #if defined(PNG_gAMA_SUPPORTED)
  190865. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190866. void PNGAPI
  190867. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  190868. {
  190869. double gamma;
  190870. png_debug1(1, "in %s storage function\n", "gAMA");
  190871. if (png_ptr == NULL || info_ptr == NULL)
  190872. return;
  190873. /* Check for overflow */
  190874. if (file_gamma > 21474.83)
  190875. {
  190876. png_warning(png_ptr, "Limiting gamma to 21474.83");
  190877. gamma=21474.83;
  190878. }
  190879. else
  190880. gamma=file_gamma;
  190881. info_ptr->gamma = (float)gamma;
  190882. #ifdef PNG_FIXED_POINT_SUPPORTED
  190883. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  190884. #endif
  190885. info_ptr->valid |= PNG_INFO_gAMA;
  190886. if(gamma == 0.0)
  190887. png_warning(png_ptr, "Setting gamma=0");
  190888. }
  190889. #endif
  190890. void PNGAPI
  190891. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  190892. int_gamma)
  190893. {
  190894. png_fixed_point gamma;
  190895. png_debug1(1, "in %s storage function\n", "gAMA");
  190896. if (png_ptr == NULL || info_ptr == NULL)
  190897. return;
  190898. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  190899. {
  190900. png_warning(png_ptr, "Limiting gamma to 21474.83");
  190901. gamma=PNG_UINT_31_MAX;
  190902. }
  190903. else
  190904. {
  190905. if (int_gamma < 0)
  190906. {
  190907. png_warning(png_ptr, "Setting negative gamma to zero");
  190908. gamma=0;
  190909. }
  190910. else
  190911. gamma=int_gamma;
  190912. }
  190913. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190914. info_ptr->gamma = (float)(gamma/100000.);
  190915. #endif
  190916. #ifdef PNG_FIXED_POINT_SUPPORTED
  190917. info_ptr->int_gamma = gamma;
  190918. #endif
  190919. info_ptr->valid |= PNG_INFO_gAMA;
  190920. if(gamma == 0)
  190921. png_warning(png_ptr, "Setting gamma=0");
  190922. }
  190923. #endif
  190924. #if defined(PNG_hIST_SUPPORTED)
  190925. void PNGAPI
  190926. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  190927. {
  190928. int i;
  190929. png_debug1(1, "in %s storage function\n", "hIST");
  190930. if (png_ptr == NULL || info_ptr == NULL)
  190931. return;
  190932. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  190933. > PNG_MAX_PALETTE_LENGTH)
  190934. {
  190935. png_warning(png_ptr,
  190936. "Invalid palette size, hIST allocation skipped.");
  190937. return;
  190938. }
  190939. #ifdef PNG_FREE_ME_SUPPORTED
  190940. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  190941. #endif
  190942. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  190943. 1.2.1 */
  190944. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  190945. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  190946. if (png_ptr->hist == NULL)
  190947. {
  190948. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  190949. return;
  190950. }
  190951. for (i = 0; i < info_ptr->num_palette; i++)
  190952. png_ptr->hist[i] = hist[i];
  190953. info_ptr->hist = png_ptr->hist;
  190954. info_ptr->valid |= PNG_INFO_hIST;
  190955. #ifdef PNG_FREE_ME_SUPPORTED
  190956. info_ptr->free_me |= PNG_FREE_HIST;
  190957. #else
  190958. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  190959. #endif
  190960. }
  190961. #endif
  190962. void PNGAPI
  190963. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  190964. png_uint_32 width, png_uint_32 height, int bit_depth,
  190965. int color_type, int interlace_type, int compression_type,
  190966. int filter_type)
  190967. {
  190968. png_debug1(1, "in %s storage function\n", "IHDR");
  190969. if (png_ptr == NULL || info_ptr == NULL)
  190970. return;
  190971. /* check for width and height valid values */
  190972. if (width == 0 || height == 0)
  190973. png_error(png_ptr, "Image width or height is zero in IHDR");
  190974. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  190975. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  190976. png_error(png_ptr, "image size exceeds user limits in IHDR");
  190977. #else
  190978. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  190979. png_error(png_ptr, "image size exceeds user limits in IHDR");
  190980. #endif
  190981. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  190982. png_error(png_ptr, "Invalid image size in IHDR");
  190983. if ( width > (PNG_UINT_32_MAX
  190984. >> 3) /* 8-byte RGBA pixels */
  190985. - 64 /* bigrowbuf hack */
  190986. - 1 /* filter byte */
  190987. - 7*8 /* rounding of width to multiple of 8 pixels */
  190988. - 8) /* extra max_pixel_depth pad */
  190989. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  190990. /* check other values */
  190991. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  190992. bit_depth != 8 && bit_depth != 16)
  190993. png_error(png_ptr, "Invalid bit depth in IHDR");
  190994. if (color_type < 0 || color_type == 1 ||
  190995. color_type == 5 || color_type > 6)
  190996. png_error(png_ptr, "Invalid color type in IHDR");
  190997. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  190998. ((color_type == PNG_COLOR_TYPE_RGB ||
  190999. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  191000. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  191001. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  191002. if (interlace_type >= PNG_INTERLACE_LAST)
  191003. png_error(png_ptr, "Unknown interlace method in IHDR");
  191004. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  191005. png_error(png_ptr, "Unknown compression method in IHDR");
  191006. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  191007. /* Accept filter_method 64 (intrapixel differencing) only if
  191008. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  191009. * 2. Libpng did not read a PNG signature (this filter_method is only
  191010. * used in PNG datastreams that are embedded in MNG datastreams) and
  191011. * 3. The application called png_permit_mng_features with a mask that
  191012. * included PNG_FLAG_MNG_FILTER_64 and
  191013. * 4. The filter_method is 64 and
  191014. * 5. The color_type is RGB or RGBA
  191015. */
  191016. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  191017. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  191018. if(filter_type != PNG_FILTER_TYPE_BASE)
  191019. {
  191020. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  191021. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  191022. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  191023. (color_type == PNG_COLOR_TYPE_RGB ||
  191024. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  191025. png_error(png_ptr, "Unknown filter method in IHDR");
  191026. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  191027. png_warning(png_ptr, "Invalid filter method in IHDR");
  191028. }
  191029. #else
  191030. if(filter_type != PNG_FILTER_TYPE_BASE)
  191031. png_error(png_ptr, "Unknown filter method in IHDR");
  191032. #endif
  191033. info_ptr->width = width;
  191034. info_ptr->height = height;
  191035. info_ptr->bit_depth = (png_byte)bit_depth;
  191036. info_ptr->color_type =(png_byte) color_type;
  191037. info_ptr->compression_type = (png_byte)compression_type;
  191038. info_ptr->filter_type = (png_byte)filter_type;
  191039. info_ptr->interlace_type = (png_byte)interlace_type;
  191040. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191041. info_ptr->channels = 1;
  191042. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191043. info_ptr->channels = 3;
  191044. else
  191045. info_ptr->channels = 1;
  191046. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191047. info_ptr->channels++;
  191048. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  191049. /* check for potential overflow */
  191050. if (width > (PNG_UINT_32_MAX
  191051. >> 3) /* 8-byte RGBA pixels */
  191052. - 64 /* bigrowbuf hack */
  191053. - 1 /* filter byte */
  191054. - 7*8 /* rounding of width to multiple of 8 pixels */
  191055. - 8) /* extra max_pixel_depth pad */
  191056. info_ptr->rowbytes = (png_size_t)0;
  191057. else
  191058. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  191059. }
  191060. #if defined(PNG_oFFs_SUPPORTED)
  191061. void PNGAPI
  191062. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  191063. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  191064. {
  191065. png_debug1(1, "in %s storage function\n", "oFFs");
  191066. if (png_ptr == NULL || info_ptr == NULL)
  191067. return;
  191068. info_ptr->x_offset = offset_x;
  191069. info_ptr->y_offset = offset_y;
  191070. info_ptr->offset_unit_type = (png_byte)unit_type;
  191071. info_ptr->valid |= PNG_INFO_oFFs;
  191072. }
  191073. #endif
  191074. #if defined(PNG_pCAL_SUPPORTED)
  191075. void PNGAPI
  191076. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  191077. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  191078. png_charp units, png_charpp params)
  191079. {
  191080. png_uint_32 length;
  191081. int i;
  191082. png_debug1(1, "in %s storage function\n", "pCAL");
  191083. if (png_ptr == NULL || info_ptr == NULL)
  191084. return;
  191085. length = png_strlen(purpose) + 1;
  191086. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  191087. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  191088. if (info_ptr->pcal_purpose == NULL)
  191089. {
  191090. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  191091. return;
  191092. }
  191093. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  191094. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  191095. info_ptr->pcal_X0 = X0;
  191096. info_ptr->pcal_X1 = X1;
  191097. info_ptr->pcal_type = (png_byte)type;
  191098. info_ptr->pcal_nparams = (png_byte)nparams;
  191099. length = png_strlen(units) + 1;
  191100. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  191101. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  191102. if (info_ptr->pcal_units == NULL)
  191103. {
  191104. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  191105. return;
  191106. }
  191107. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  191108. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  191109. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  191110. if (info_ptr->pcal_params == NULL)
  191111. {
  191112. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  191113. return;
  191114. }
  191115. info_ptr->pcal_params[nparams] = NULL;
  191116. for (i = 0; i < nparams; i++)
  191117. {
  191118. length = png_strlen(params[i]) + 1;
  191119. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  191120. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  191121. if (info_ptr->pcal_params[i] == NULL)
  191122. {
  191123. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  191124. return;
  191125. }
  191126. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  191127. }
  191128. info_ptr->valid |= PNG_INFO_pCAL;
  191129. #ifdef PNG_FREE_ME_SUPPORTED
  191130. info_ptr->free_me |= PNG_FREE_PCAL;
  191131. #endif
  191132. }
  191133. #endif
  191134. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  191135. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191136. void PNGAPI
  191137. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  191138. int unit, double width, double height)
  191139. {
  191140. png_debug1(1, "in %s storage function\n", "sCAL");
  191141. if (png_ptr == NULL || info_ptr == NULL)
  191142. return;
  191143. info_ptr->scal_unit = (png_byte)unit;
  191144. info_ptr->scal_pixel_width = width;
  191145. info_ptr->scal_pixel_height = height;
  191146. info_ptr->valid |= PNG_INFO_sCAL;
  191147. }
  191148. #else
  191149. #ifdef PNG_FIXED_POINT_SUPPORTED
  191150. void PNGAPI
  191151. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  191152. int unit, png_charp swidth, png_charp sheight)
  191153. {
  191154. png_uint_32 length;
  191155. png_debug1(1, "in %s storage function\n", "sCAL");
  191156. if (png_ptr == NULL || info_ptr == NULL)
  191157. return;
  191158. info_ptr->scal_unit = (png_byte)unit;
  191159. length = png_strlen(swidth) + 1;
  191160. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  191161. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  191162. if (info_ptr->scal_s_width == NULL)
  191163. {
  191164. png_warning(png_ptr,
  191165. "Memory allocation failed while processing sCAL.");
  191166. }
  191167. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  191168. length = png_strlen(sheight) + 1;
  191169. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  191170. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  191171. if (info_ptr->scal_s_height == NULL)
  191172. {
  191173. png_free (png_ptr, info_ptr->scal_s_width);
  191174. png_warning(png_ptr,
  191175. "Memory allocation failed while processing sCAL.");
  191176. }
  191177. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  191178. info_ptr->valid |= PNG_INFO_sCAL;
  191179. #ifdef PNG_FREE_ME_SUPPORTED
  191180. info_ptr->free_me |= PNG_FREE_SCAL;
  191181. #endif
  191182. }
  191183. #endif
  191184. #endif
  191185. #endif
  191186. #if defined(PNG_pHYs_SUPPORTED)
  191187. void PNGAPI
  191188. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  191189. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  191190. {
  191191. png_debug1(1, "in %s storage function\n", "pHYs");
  191192. if (png_ptr == NULL || info_ptr == NULL)
  191193. return;
  191194. info_ptr->x_pixels_per_unit = res_x;
  191195. info_ptr->y_pixels_per_unit = res_y;
  191196. info_ptr->phys_unit_type = (png_byte)unit_type;
  191197. info_ptr->valid |= PNG_INFO_pHYs;
  191198. }
  191199. #endif
  191200. void PNGAPI
  191201. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  191202. png_colorp palette, int num_palette)
  191203. {
  191204. png_debug1(1, "in %s storage function\n", "PLTE");
  191205. if (png_ptr == NULL || info_ptr == NULL)
  191206. return;
  191207. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  191208. {
  191209. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191210. png_error(png_ptr, "Invalid palette length");
  191211. else
  191212. {
  191213. png_warning(png_ptr, "Invalid palette length");
  191214. return;
  191215. }
  191216. }
  191217. /*
  191218. * It may not actually be necessary to set png_ptr->palette here;
  191219. * we do it for backward compatibility with the way the png_handle_tRNS
  191220. * function used to do the allocation.
  191221. */
  191222. #ifdef PNG_FREE_ME_SUPPORTED
  191223. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  191224. #endif
  191225. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  191226. of num_palette entries,
  191227. in case of an invalid PNG file that has too-large sample values. */
  191228. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  191229. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  191230. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  191231. png_sizeof(png_color));
  191232. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  191233. info_ptr->palette = png_ptr->palette;
  191234. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  191235. #ifdef PNG_FREE_ME_SUPPORTED
  191236. info_ptr->free_me |= PNG_FREE_PLTE;
  191237. #else
  191238. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  191239. #endif
  191240. info_ptr->valid |= PNG_INFO_PLTE;
  191241. }
  191242. #if defined(PNG_sBIT_SUPPORTED)
  191243. void PNGAPI
  191244. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  191245. png_color_8p sig_bit)
  191246. {
  191247. png_debug1(1, "in %s storage function\n", "sBIT");
  191248. if (png_ptr == NULL || info_ptr == NULL)
  191249. return;
  191250. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  191251. info_ptr->valid |= PNG_INFO_sBIT;
  191252. }
  191253. #endif
  191254. #if defined(PNG_sRGB_SUPPORTED)
  191255. void PNGAPI
  191256. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  191257. {
  191258. png_debug1(1, "in %s storage function\n", "sRGB");
  191259. if (png_ptr == NULL || info_ptr == NULL)
  191260. return;
  191261. info_ptr->srgb_intent = (png_byte)intent;
  191262. info_ptr->valid |= PNG_INFO_sRGB;
  191263. }
  191264. void PNGAPI
  191265. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  191266. int intent)
  191267. {
  191268. #if defined(PNG_gAMA_SUPPORTED)
  191269. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191270. float file_gamma;
  191271. #endif
  191272. #ifdef PNG_FIXED_POINT_SUPPORTED
  191273. png_fixed_point int_file_gamma;
  191274. #endif
  191275. #endif
  191276. #if defined(PNG_cHRM_SUPPORTED)
  191277. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191278. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  191279. #endif
  191280. #ifdef PNG_FIXED_POINT_SUPPORTED
  191281. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  191282. int_green_y, int_blue_x, int_blue_y;
  191283. #endif
  191284. #endif
  191285. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  191286. if (png_ptr == NULL || info_ptr == NULL)
  191287. return;
  191288. png_set_sRGB(png_ptr, info_ptr, intent);
  191289. #if defined(PNG_gAMA_SUPPORTED)
  191290. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191291. file_gamma = (float).45455;
  191292. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  191293. #endif
  191294. #ifdef PNG_FIXED_POINT_SUPPORTED
  191295. int_file_gamma = 45455L;
  191296. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  191297. #endif
  191298. #endif
  191299. #if defined(PNG_cHRM_SUPPORTED)
  191300. #ifdef PNG_FIXED_POINT_SUPPORTED
  191301. int_white_x = 31270L;
  191302. int_white_y = 32900L;
  191303. int_red_x = 64000L;
  191304. int_red_y = 33000L;
  191305. int_green_x = 30000L;
  191306. int_green_y = 60000L;
  191307. int_blue_x = 15000L;
  191308. int_blue_y = 6000L;
  191309. png_set_cHRM_fixed(png_ptr, info_ptr,
  191310. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  191311. int_blue_x, int_blue_y);
  191312. #endif
  191313. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191314. white_x = (float).3127;
  191315. white_y = (float).3290;
  191316. red_x = (float).64;
  191317. red_y = (float).33;
  191318. green_x = (float).30;
  191319. green_y = (float).60;
  191320. blue_x = (float).15;
  191321. blue_y = (float).06;
  191322. png_set_cHRM(png_ptr, info_ptr,
  191323. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  191324. #endif
  191325. #endif
  191326. }
  191327. #endif
  191328. #if defined(PNG_iCCP_SUPPORTED)
  191329. void PNGAPI
  191330. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  191331. png_charp name, int compression_type,
  191332. png_charp profile, png_uint_32 proflen)
  191333. {
  191334. png_charp new_iccp_name;
  191335. png_charp new_iccp_profile;
  191336. png_debug1(1, "in %s storage function\n", "iCCP");
  191337. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  191338. return;
  191339. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  191340. if (new_iccp_name == NULL)
  191341. {
  191342. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  191343. return;
  191344. }
  191345. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  191346. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  191347. if (new_iccp_profile == NULL)
  191348. {
  191349. png_free (png_ptr, new_iccp_name);
  191350. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  191351. return;
  191352. }
  191353. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  191354. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  191355. info_ptr->iccp_proflen = proflen;
  191356. info_ptr->iccp_name = new_iccp_name;
  191357. info_ptr->iccp_profile = new_iccp_profile;
  191358. /* Compression is always zero but is here so the API and info structure
  191359. * does not have to change if we introduce multiple compression types */
  191360. info_ptr->iccp_compression = (png_byte)compression_type;
  191361. #ifdef PNG_FREE_ME_SUPPORTED
  191362. info_ptr->free_me |= PNG_FREE_ICCP;
  191363. #endif
  191364. info_ptr->valid |= PNG_INFO_iCCP;
  191365. }
  191366. #endif
  191367. #if defined(PNG_TEXT_SUPPORTED)
  191368. void PNGAPI
  191369. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  191370. int num_text)
  191371. {
  191372. int ret;
  191373. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  191374. if (ret)
  191375. png_error(png_ptr, "Insufficient memory to store text");
  191376. }
  191377. int /* PRIVATE */
  191378. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  191379. int num_text)
  191380. {
  191381. int i;
  191382. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  191383. "text" : (png_const_charp)png_ptr->chunk_name));
  191384. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  191385. return(0);
  191386. /* Make sure we have enough space in the "text" array in info_struct
  191387. * to hold all of the incoming text_ptr objects.
  191388. */
  191389. if (info_ptr->num_text + num_text > info_ptr->max_text)
  191390. {
  191391. if (info_ptr->text != NULL)
  191392. {
  191393. png_textp old_text;
  191394. int old_max;
  191395. old_max = info_ptr->max_text;
  191396. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  191397. old_text = info_ptr->text;
  191398. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  191399. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  191400. if (info_ptr->text == NULL)
  191401. {
  191402. png_free(png_ptr, old_text);
  191403. return(1);
  191404. }
  191405. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  191406. png_sizeof(png_text)));
  191407. png_free(png_ptr, old_text);
  191408. }
  191409. else
  191410. {
  191411. info_ptr->max_text = num_text + 8;
  191412. info_ptr->num_text = 0;
  191413. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  191414. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  191415. if (info_ptr->text == NULL)
  191416. return(1);
  191417. #ifdef PNG_FREE_ME_SUPPORTED
  191418. info_ptr->free_me |= PNG_FREE_TEXT;
  191419. #endif
  191420. }
  191421. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  191422. info_ptr->max_text);
  191423. }
  191424. for (i = 0; i < num_text; i++)
  191425. {
  191426. png_size_t text_length,key_len;
  191427. png_size_t lang_len,lang_key_len;
  191428. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  191429. if (text_ptr[i].key == NULL)
  191430. continue;
  191431. key_len = png_strlen(text_ptr[i].key);
  191432. if(text_ptr[i].compression <= 0)
  191433. {
  191434. lang_len = 0;
  191435. lang_key_len = 0;
  191436. }
  191437. else
  191438. #ifdef PNG_iTXt_SUPPORTED
  191439. {
  191440. /* set iTXt data */
  191441. if (text_ptr[i].lang != NULL)
  191442. lang_len = png_strlen(text_ptr[i].lang);
  191443. else
  191444. lang_len = 0;
  191445. if (text_ptr[i].lang_key != NULL)
  191446. lang_key_len = png_strlen(text_ptr[i].lang_key);
  191447. else
  191448. lang_key_len = 0;
  191449. }
  191450. #else
  191451. {
  191452. png_warning(png_ptr, "iTXt chunk not supported.");
  191453. continue;
  191454. }
  191455. #endif
  191456. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  191457. {
  191458. text_length = 0;
  191459. #ifdef PNG_iTXt_SUPPORTED
  191460. if(text_ptr[i].compression > 0)
  191461. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  191462. else
  191463. #endif
  191464. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  191465. }
  191466. else
  191467. {
  191468. text_length = png_strlen(text_ptr[i].text);
  191469. textp->compression = text_ptr[i].compression;
  191470. }
  191471. textp->key = (png_charp)png_malloc_warn(png_ptr,
  191472. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  191473. if (textp->key == NULL)
  191474. return(1);
  191475. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  191476. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  191477. (int)textp->key);
  191478. png_memcpy(textp->key, text_ptr[i].key,
  191479. (png_size_t)(key_len));
  191480. *(textp->key+key_len) = '\0';
  191481. #ifdef PNG_iTXt_SUPPORTED
  191482. if (text_ptr[i].compression > 0)
  191483. {
  191484. textp->lang=textp->key + key_len + 1;
  191485. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  191486. *(textp->lang+lang_len) = '\0';
  191487. textp->lang_key=textp->lang + lang_len + 1;
  191488. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  191489. *(textp->lang_key+lang_key_len) = '\0';
  191490. textp->text=textp->lang_key + lang_key_len + 1;
  191491. }
  191492. else
  191493. #endif
  191494. {
  191495. #ifdef PNG_iTXt_SUPPORTED
  191496. textp->lang=NULL;
  191497. textp->lang_key=NULL;
  191498. #endif
  191499. textp->text=textp->key + key_len + 1;
  191500. }
  191501. if(text_length)
  191502. png_memcpy(textp->text, text_ptr[i].text,
  191503. (png_size_t)(text_length));
  191504. *(textp->text+text_length) = '\0';
  191505. #ifdef PNG_iTXt_SUPPORTED
  191506. if(textp->compression > 0)
  191507. {
  191508. textp->text_length = 0;
  191509. textp->itxt_length = text_length;
  191510. }
  191511. else
  191512. #endif
  191513. {
  191514. textp->text_length = text_length;
  191515. #ifdef PNG_iTXt_SUPPORTED
  191516. textp->itxt_length = 0;
  191517. #endif
  191518. }
  191519. info_ptr->num_text++;
  191520. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  191521. }
  191522. return(0);
  191523. }
  191524. #endif
  191525. #if defined(PNG_tIME_SUPPORTED)
  191526. void PNGAPI
  191527. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  191528. {
  191529. png_debug1(1, "in %s storage function\n", "tIME");
  191530. if (png_ptr == NULL || info_ptr == NULL ||
  191531. (png_ptr->mode & PNG_WROTE_tIME))
  191532. return;
  191533. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  191534. info_ptr->valid |= PNG_INFO_tIME;
  191535. }
  191536. #endif
  191537. #if defined(PNG_tRNS_SUPPORTED)
  191538. void PNGAPI
  191539. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  191540. png_bytep trans, int num_trans, png_color_16p trans_values)
  191541. {
  191542. png_debug1(1, "in %s storage function\n", "tRNS");
  191543. if (png_ptr == NULL || info_ptr == NULL)
  191544. return;
  191545. if (trans != NULL)
  191546. {
  191547. /*
  191548. * It may not actually be necessary to set png_ptr->trans here;
  191549. * we do it for backward compatibility with the way the png_handle_tRNS
  191550. * function used to do the allocation.
  191551. */
  191552. #ifdef PNG_FREE_ME_SUPPORTED
  191553. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  191554. #endif
  191555. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  191556. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  191557. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  191558. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  191559. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  191560. #ifdef PNG_FREE_ME_SUPPORTED
  191561. info_ptr->free_me |= PNG_FREE_TRNS;
  191562. #else
  191563. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  191564. #endif
  191565. }
  191566. if (trans_values != NULL)
  191567. {
  191568. png_memcpy(&(info_ptr->trans_values), trans_values,
  191569. png_sizeof(png_color_16));
  191570. if (num_trans == 0)
  191571. num_trans = 1;
  191572. }
  191573. info_ptr->num_trans = (png_uint_16)num_trans;
  191574. info_ptr->valid |= PNG_INFO_tRNS;
  191575. }
  191576. #endif
  191577. #if defined(PNG_sPLT_SUPPORTED)
  191578. void PNGAPI
  191579. png_set_sPLT(png_structp png_ptr,
  191580. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  191581. {
  191582. png_sPLT_tp np;
  191583. int i;
  191584. if (png_ptr == NULL || info_ptr == NULL)
  191585. return;
  191586. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  191587. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  191588. if (np == NULL)
  191589. {
  191590. png_warning(png_ptr, "No memory for sPLT palettes.");
  191591. return;
  191592. }
  191593. png_memcpy(np, info_ptr->splt_palettes,
  191594. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  191595. png_free(png_ptr, info_ptr->splt_palettes);
  191596. info_ptr->splt_palettes=NULL;
  191597. for (i = 0; i < nentries; i++)
  191598. {
  191599. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  191600. png_sPLT_tp from = entries + i;
  191601. to->name = (png_charp)png_malloc_warn(png_ptr,
  191602. png_strlen(from->name) + 1);
  191603. if (to->name == NULL)
  191604. {
  191605. png_warning(png_ptr,
  191606. "Out of memory while processing sPLT chunk");
  191607. }
  191608. /* TODO: use png_malloc_warn */
  191609. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  191610. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  191611. from->nentries * png_sizeof(png_sPLT_entry));
  191612. /* TODO: use png_malloc_warn */
  191613. png_memcpy(to->entries, from->entries,
  191614. from->nentries * png_sizeof(png_sPLT_entry));
  191615. if (to->entries == NULL)
  191616. {
  191617. png_warning(png_ptr,
  191618. "Out of memory while processing sPLT chunk");
  191619. png_free(png_ptr,to->name);
  191620. to->name = NULL;
  191621. }
  191622. to->nentries = from->nentries;
  191623. to->depth = from->depth;
  191624. }
  191625. info_ptr->splt_palettes = np;
  191626. info_ptr->splt_palettes_num += nentries;
  191627. info_ptr->valid |= PNG_INFO_sPLT;
  191628. #ifdef PNG_FREE_ME_SUPPORTED
  191629. info_ptr->free_me |= PNG_FREE_SPLT;
  191630. #endif
  191631. }
  191632. #endif /* PNG_sPLT_SUPPORTED */
  191633. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  191634. void PNGAPI
  191635. png_set_unknown_chunks(png_structp png_ptr,
  191636. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  191637. {
  191638. png_unknown_chunkp np;
  191639. int i;
  191640. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  191641. return;
  191642. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  191643. (info_ptr->unknown_chunks_num + num_unknowns) *
  191644. png_sizeof(png_unknown_chunk));
  191645. if (np == NULL)
  191646. {
  191647. png_warning(png_ptr,
  191648. "Out of memory while processing unknown chunk.");
  191649. return;
  191650. }
  191651. png_memcpy(np, info_ptr->unknown_chunks,
  191652. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  191653. png_free(png_ptr, info_ptr->unknown_chunks);
  191654. info_ptr->unknown_chunks=NULL;
  191655. for (i = 0; i < num_unknowns; i++)
  191656. {
  191657. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  191658. png_unknown_chunkp from = unknowns + i;
  191659. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  191660. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  191661. if (to->data == NULL)
  191662. {
  191663. png_warning(png_ptr,
  191664. "Out of memory while processing unknown chunk.");
  191665. }
  191666. else
  191667. {
  191668. png_memcpy(to->data, from->data, from->size);
  191669. to->size = from->size;
  191670. /* note our location in the read or write sequence */
  191671. to->location = (png_byte)(png_ptr->mode & 0xff);
  191672. }
  191673. }
  191674. info_ptr->unknown_chunks = np;
  191675. info_ptr->unknown_chunks_num += num_unknowns;
  191676. #ifdef PNG_FREE_ME_SUPPORTED
  191677. info_ptr->free_me |= PNG_FREE_UNKN;
  191678. #endif
  191679. }
  191680. void PNGAPI
  191681. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  191682. int chunk, int location)
  191683. {
  191684. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  191685. (int)info_ptr->unknown_chunks_num)
  191686. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  191687. }
  191688. #endif
  191689. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  191690. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  191691. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  191692. void PNGAPI
  191693. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  191694. {
  191695. /* This function is deprecated in favor of png_permit_mng_features()
  191696. and will be removed from libpng-1.3.0 */
  191697. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  191698. if (png_ptr == NULL)
  191699. return;
  191700. png_ptr->mng_features_permitted = (png_byte)
  191701. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  191702. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  191703. }
  191704. #endif
  191705. #endif
  191706. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  191707. png_uint_32 PNGAPI
  191708. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  191709. {
  191710. png_debug(1, "in png_permit_mng_features\n");
  191711. if (png_ptr == NULL)
  191712. return (png_uint_32)0;
  191713. png_ptr->mng_features_permitted =
  191714. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  191715. return (png_uint_32)png_ptr->mng_features_permitted;
  191716. }
  191717. #endif
  191718. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  191719. void PNGAPI
  191720. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  191721. chunk_list, int num_chunks)
  191722. {
  191723. png_bytep new_list, p;
  191724. int i, old_num_chunks;
  191725. if (png_ptr == NULL)
  191726. return;
  191727. if (num_chunks == 0)
  191728. {
  191729. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  191730. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  191731. else
  191732. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  191733. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  191734. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  191735. else
  191736. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  191737. return;
  191738. }
  191739. if (chunk_list == NULL)
  191740. return;
  191741. old_num_chunks=png_ptr->num_chunk_list;
  191742. new_list=(png_bytep)png_malloc(png_ptr,
  191743. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  191744. if(png_ptr->chunk_list != NULL)
  191745. {
  191746. png_memcpy(new_list, png_ptr->chunk_list,
  191747. (png_size_t)(5*old_num_chunks));
  191748. png_free(png_ptr, png_ptr->chunk_list);
  191749. png_ptr->chunk_list=NULL;
  191750. }
  191751. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  191752. (png_size_t)(5*num_chunks));
  191753. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  191754. *p=(png_byte)keep;
  191755. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  191756. png_ptr->chunk_list=new_list;
  191757. #ifdef PNG_FREE_ME_SUPPORTED
  191758. png_ptr->free_me |= PNG_FREE_LIST;
  191759. #endif
  191760. }
  191761. #endif
  191762. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  191763. void PNGAPI
  191764. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  191765. png_user_chunk_ptr read_user_chunk_fn)
  191766. {
  191767. png_debug(1, "in png_set_read_user_chunk_fn\n");
  191768. if (png_ptr == NULL)
  191769. return;
  191770. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  191771. png_ptr->user_chunk_ptr = user_chunk_ptr;
  191772. }
  191773. #endif
  191774. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  191775. void PNGAPI
  191776. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  191777. {
  191778. png_debug1(1, "in %s storage function\n", "rows");
  191779. if (png_ptr == NULL || info_ptr == NULL)
  191780. return;
  191781. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  191782. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  191783. info_ptr->row_pointers = row_pointers;
  191784. if(row_pointers)
  191785. info_ptr->valid |= PNG_INFO_IDAT;
  191786. }
  191787. #endif
  191788. #ifdef PNG_WRITE_SUPPORTED
  191789. void PNGAPI
  191790. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  191791. {
  191792. if (png_ptr == NULL)
  191793. return;
  191794. if(png_ptr->zbuf)
  191795. png_free(png_ptr, png_ptr->zbuf);
  191796. png_ptr->zbuf_size = (png_size_t)size;
  191797. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  191798. png_ptr->zstream.next_out = png_ptr->zbuf;
  191799. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  191800. }
  191801. #endif
  191802. void PNGAPI
  191803. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  191804. {
  191805. if (png_ptr && info_ptr)
  191806. info_ptr->valid &= ~(mask);
  191807. }
  191808. #ifndef PNG_1_0_X
  191809. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  191810. /* function was added to libpng 1.2.0 and should always exist by default */
  191811. void PNGAPI
  191812. png_set_asm_flags (png_structp png_ptr, png_uint_32 asm_flags)
  191813. {
  191814. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  191815. if (png_ptr != NULL)
  191816. png_ptr->asm_flags = 0;
  191817. }
  191818. /* this function was added to libpng 1.2.0 */
  191819. void PNGAPI
  191820. png_set_mmx_thresholds (png_structp png_ptr,
  191821. png_byte mmx_bitdepth_threshold,
  191822. png_uint_32 mmx_rowbytes_threshold)
  191823. {
  191824. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  191825. if (png_ptr == NULL)
  191826. return;
  191827. }
  191828. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  191829. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  191830. /* this function was added to libpng 1.2.6 */
  191831. void PNGAPI
  191832. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  191833. png_uint_32 user_height_max)
  191834. {
  191835. /* Images with dimensions larger than these limits will be
  191836. * rejected by png_set_IHDR(). To accept any PNG datastream
  191837. * regardless of dimensions, set both limits to 0x7ffffffL.
  191838. */
  191839. if(png_ptr == NULL) return;
  191840. png_ptr->user_width_max = user_width_max;
  191841. png_ptr->user_height_max = user_height_max;
  191842. }
  191843. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  191844. #endif /* ?PNG_1_0_X */
  191845. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  191846. /********* End of inlined file: pngset.c *********/
  191847. /********* Start of inlined file: pngtrans.c *********/
  191848. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  191849. *
  191850. * Last changed in libpng 1.2.17 May 15, 2007
  191851. * For conditions of distribution and use, see copyright notice in png.h
  191852. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  191853. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  191854. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  191855. */
  191856. #define PNG_INTERNAL
  191857. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  191858. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  191859. /* turn on BGR-to-RGB mapping */
  191860. void PNGAPI
  191861. png_set_bgr(png_structp png_ptr)
  191862. {
  191863. png_debug(1, "in png_set_bgr\n");
  191864. if(png_ptr == NULL) return;
  191865. png_ptr->transformations |= PNG_BGR;
  191866. }
  191867. #endif
  191868. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  191869. /* turn on 16 bit byte swapping */
  191870. void PNGAPI
  191871. png_set_swap(png_structp png_ptr)
  191872. {
  191873. png_debug(1, "in png_set_swap\n");
  191874. if(png_ptr == NULL) return;
  191875. if (png_ptr->bit_depth == 16)
  191876. png_ptr->transformations |= PNG_SWAP_BYTES;
  191877. }
  191878. #endif
  191879. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  191880. /* turn on pixel packing */
  191881. void PNGAPI
  191882. png_set_packing(png_structp png_ptr)
  191883. {
  191884. png_debug(1, "in png_set_packing\n");
  191885. if(png_ptr == NULL) return;
  191886. if (png_ptr->bit_depth < 8)
  191887. {
  191888. png_ptr->transformations |= PNG_PACK;
  191889. png_ptr->usr_bit_depth = 8;
  191890. }
  191891. }
  191892. #endif
  191893. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  191894. /* turn on packed pixel swapping */
  191895. void PNGAPI
  191896. png_set_packswap(png_structp png_ptr)
  191897. {
  191898. png_debug(1, "in png_set_packswap\n");
  191899. if(png_ptr == NULL) return;
  191900. if (png_ptr->bit_depth < 8)
  191901. png_ptr->transformations |= PNG_PACKSWAP;
  191902. }
  191903. #endif
  191904. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  191905. void PNGAPI
  191906. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  191907. {
  191908. png_debug(1, "in png_set_shift\n");
  191909. if(png_ptr == NULL) return;
  191910. png_ptr->transformations |= PNG_SHIFT;
  191911. png_ptr->shift = *true_bits;
  191912. }
  191913. #endif
  191914. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  191915. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  191916. int PNGAPI
  191917. png_set_interlace_handling(png_structp png_ptr)
  191918. {
  191919. png_debug(1, "in png_set_interlace handling\n");
  191920. if (png_ptr && png_ptr->interlaced)
  191921. {
  191922. png_ptr->transformations |= PNG_INTERLACE;
  191923. return (7);
  191924. }
  191925. return (1);
  191926. }
  191927. #endif
  191928. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  191929. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  191930. * The filler type has changed in v0.95 to allow future 2-byte fillers
  191931. * for 48-bit input data, as well as to avoid problems with some compilers
  191932. * that don't like bytes as parameters.
  191933. */
  191934. void PNGAPI
  191935. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  191936. {
  191937. png_debug(1, "in png_set_filler\n");
  191938. if(png_ptr == NULL) return;
  191939. png_ptr->transformations |= PNG_FILLER;
  191940. png_ptr->filler = (png_byte)filler;
  191941. if (filler_loc == PNG_FILLER_AFTER)
  191942. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  191943. else
  191944. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  191945. /* This should probably go in the "do_read_filler" routine.
  191946. * I attempted to do that in libpng-1.0.1a but that caused problems
  191947. * so I restored it in libpng-1.0.2a
  191948. */
  191949. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  191950. {
  191951. png_ptr->usr_channels = 4;
  191952. }
  191953. /* Also I added this in libpng-1.0.2a (what happens when we expand
  191954. * a less-than-8-bit grayscale to GA? */
  191955. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  191956. {
  191957. png_ptr->usr_channels = 2;
  191958. }
  191959. }
  191960. #if !defined(PNG_1_0_X)
  191961. /* Added to libpng-1.2.7 */
  191962. void PNGAPI
  191963. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  191964. {
  191965. png_debug(1, "in png_set_add_alpha\n");
  191966. if(png_ptr == NULL) return;
  191967. png_set_filler(png_ptr, filler, filler_loc);
  191968. png_ptr->transformations |= PNG_ADD_ALPHA;
  191969. }
  191970. #endif
  191971. #endif
  191972. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  191973. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  191974. void PNGAPI
  191975. png_set_swap_alpha(png_structp png_ptr)
  191976. {
  191977. png_debug(1, "in png_set_swap_alpha\n");
  191978. if(png_ptr == NULL) return;
  191979. png_ptr->transformations |= PNG_SWAP_ALPHA;
  191980. }
  191981. #endif
  191982. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  191983. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  191984. void PNGAPI
  191985. png_set_invert_alpha(png_structp png_ptr)
  191986. {
  191987. png_debug(1, "in png_set_invert_alpha\n");
  191988. if(png_ptr == NULL) return;
  191989. png_ptr->transformations |= PNG_INVERT_ALPHA;
  191990. }
  191991. #endif
  191992. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  191993. void PNGAPI
  191994. png_set_invert_mono(png_structp png_ptr)
  191995. {
  191996. png_debug(1, "in png_set_invert_mono\n");
  191997. if(png_ptr == NULL) return;
  191998. png_ptr->transformations |= PNG_INVERT_MONO;
  191999. }
  192000. /* invert monochrome grayscale data */
  192001. void /* PRIVATE */
  192002. png_do_invert(png_row_infop row_info, png_bytep row)
  192003. {
  192004. png_debug(1, "in png_do_invert\n");
  192005. /* This test removed from libpng version 1.0.13 and 1.2.0:
  192006. * if (row_info->bit_depth == 1 &&
  192007. */
  192008. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192009. if (row == NULL || row_info == NULL)
  192010. return;
  192011. #endif
  192012. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192013. {
  192014. png_bytep rp = row;
  192015. png_uint_32 i;
  192016. png_uint_32 istop = row_info->rowbytes;
  192017. for (i = 0; i < istop; i++)
  192018. {
  192019. *rp = (png_byte)(~(*rp));
  192020. rp++;
  192021. }
  192022. }
  192023. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  192024. row_info->bit_depth == 8)
  192025. {
  192026. png_bytep rp = row;
  192027. png_uint_32 i;
  192028. png_uint_32 istop = row_info->rowbytes;
  192029. for (i = 0; i < istop; i+=2)
  192030. {
  192031. *rp = (png_byte)(~(*rp));
  192032. rp+=2;
  192033. }
  192034. }
  192035. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  192036. row_info->bit_depth == 16)
  192037. {
  192038. png_bytep rp = row;
  192039. png_uint_32 i;
  192040. png_uint_32 istop = row_info->rowbytes;
  192041. for (i = 0; i < istop; i+=4)
  192042. {
  192043. *rp = (png_byte)(~(*rp));
  192044. *(rp+1) = (png_byte)(~(*(rp+1)));
  192045. rp+=4;
  192046. }
  192047. }
  192048. }
  192049. #endif
  192050. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  192051. /* swaps byte order on 16 bit depth images */
  192052. void /* PRIVATE */
  192053. png_do_swap(png_row_infop row_info, png_bytep row)
  192054. {
  192055. png_debug(1, "in png_do_swap\n");
  192056. if (
  192057. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192058. row != NULL && row_info != NULL &&
  192059. #endif
  192060. row_info->bit_depth == 16)
  192061. {
  192062. png_bytep rp = row;
  192063. png_uint_32 i;
  192064. png_uint_32 istop= row_info->width * row_info->channels;
  192065. for (i = 0; i < istop; i++, rp += 2)
  192066. {
  192067. png_byte t = *rp;
  192068. *rp = *(rp + 1);
  192069. *(rp + 1) = t;
  192070. }
  192071. }
  192072. }
  192073. #endif
  192074. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  192075. static PNG_CONST png_byte onebppswaptable[256] = {
  192076. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  192077. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  192078. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  192079. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  192080. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  192081. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  192082. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  192083. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  192084. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  192085. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  192086. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  192087. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  192088. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  192089. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  192090. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  192091. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  192092. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  192093. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  192094. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  192095. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  192096. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  192097. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  192098. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  192099. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  192100. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  192101. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  192102. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  192103. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  192104. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  192105. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  192106. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  192107. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  192108. };
  192109. static PNG_CONST png_byte twobppswaptable[256] = {
  192110. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  192111. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  192112. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  192113. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  192114. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  192115. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  192116. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  192117. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  192118. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  192119. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  192120. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  192121. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  192122. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  192123. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  192124. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  192125. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  192126. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  192127. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  192128. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  192129. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  192130. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  192131. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  192132. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  192133. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  192134. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  192135. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  192136. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  192137. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  192138. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  192139. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  192140. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  192141. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  192142. };
  192143. static PNG_CONST png_byte fourbppswaptable[256] = {
  192144. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  192145. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  192146. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  192147. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  192148. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  192149. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  192150. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  192151. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  192152. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  192153. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  192154. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  192155. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  192156. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  192157. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  192158. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  192159. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  192160. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  192161. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  192162. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  192163. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  192164. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  192165. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  192166. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  192167. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  192168. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  192169. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  192170. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  192171. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  192172. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  192173. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  192174. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  192175. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  192176. };
  192177. /* swaps pixel packing order within bytes */
  192178. void /* PRIVATE */
  192179. png_do_packswap(png_row_infop row_info, png_bytep row)
  192180. {
  192181. png_debug(1, "in png_do_packswap\n");
  192182. if (
  192183. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192184. row != NULL && row_info != NULL &&
  192185. #endif
  192186. row_info->bit_depth < 8)
  192187. {
  192188. png_bytep rp, end, table;
  192189. end = row + row_info->rowbytes;
  192190. if (row_info->bit_depth == 1)
  192191. table = (png_bytep)onebppswaptable;
  192192. else if (row_info->bit_depth == 2)
  192193. table = (png_bytep)twobppswaptable;
  192194. else if (row_info->bit_depth == 4)
  192195. table = (png_bytep)fourbppswaptable;
  192196. else
  192197. return;
  192198. for (rp = row; rp < end; rp++)
  192199. *rp = table[*rp];
  192200. }
  192201. }
  192202. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  192203. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  192204. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  192205. /* remove filler or alpha byte(s) */
  192206. void /* PRIVATE */
  192207. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  192208. {
  192209. png_debug(1, "in png_do_strip_filler\n");
  192210. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192211. if (row != NULL && row_info != NULL)
  192212. #endif
  192213. {
  192214. png_bytep sp=row;
  192215. png_bytep dp=row;
  192216. png_uint_32 row_width=row_info->width;
  192217. png_uint_32 i;
  192218. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  192219. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  192220. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  192221. row_info->channels == 4)
  192222. {
  192223. if (row_info->bit_depth == 8)
  192224. {
  192225. /* This converts from RGBX or RGBA to RGB */
  192226. if (flags & PNG_FLAG_FILLER_AFTER)
  192227. {
  192228. dp+=3; sp+=4;
  192229. for (i = 1; i < row_width; i++)
  192230. {
  192231. *dp++ = *sp++;
  192232. *dp++ = *sp++;
  192233. *dp++ = *sp++;
  192234. sp++;
  192235. }
  192236. }
  192237. /* This converts from XRGB or ARGB to RGB */
  192238. else
  192239. {
  192240. for (i = 0; i < row_width; i++)
  192241. {
  192242. sp++;
  192243. *dp++ = *sp++;
  192244. *dp++ = *sp++;
  192245. *dp++ = *sp++;
  192246. }
  192247. }
  192248. row_info->pixel_depth = 24;
  192249. row_info->rowbytes = row_width * 3;
  192250. }
  192251. else /* if (row_info->bit_depth == 16) */
  192252. {
  192253. if (flags & PNG_FLAG_FILLER_AFTER)
  192254. {
  192255. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  192256. sp += 8; dp += 6;
  192257. for (i = 1; i < row_width; i++)
  192258. {
  192259. /* This could be (although png_memcpy is probably slower):
  192260. png_memcpy(dp, sp, 6);
  192261. sp += 8;
  192262. dp += 6;
  192263. */
  192264. *dp++ = *sp++;
  192265. *dp++ = *sp++;
  192266. *dp++ = *sp++;
  192267. *dp++ = *sp++;
  192268. *dp++ = *sp++;
  192269. *dp++ = *sp++;
  192270. sp += 2;
  192271. }
  192272. }
  192273. else
  192274. {
  192275. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  192276. for (i = 0; i < row_width; i++)
  192277. {
  192278. /* This could be (although png_memcpy is probably slower):
  192279. png_memcpy(dp, sp, 6);
  192280. sp += 8;
  192281. dp += 6;
  192282. */
  192283. sp+=2;
  192284. *dp++ = *sp++;
  192285. *dp++ = *sp++;
  192286. *dp++ = *sp++;
  192287. *dp++ = *sp++;
  192288. *dp++ = *sp++;
  192289. *dp++ = *sp++;
  192290. }
  192291. }
  192292. row_info->pixel_depth = 48;
  192293. row_info->rowbytes = row_width * 6;
  192294. }
  192295. row_info->channels = 3;
  192296. }
  192297. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  192298. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  192299. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  192300. row_info->channels == 2)
  192301. {
  192302. if (row_info->bit_depth == 8)
  192303. {
  192304. /* This converts from GX or GA to G */
  192305. if (flags & PNG_FLAG_FILLER_AFTER)
  192306. {
  192307. for (i = 0; i < row_width; i++)
  192308. {
  192309. *dp++ = *sp++;
  192310. sp++;
  192311. }
  192312. }
  192313. /* This converts from XG or AG to G */
  192314. else
  192315. {
  192316. for (i = 0; i < row_width; i++)
  192317. {
  192318. sp++;
  192319. *dp++ = *sp++;
  192320. }
  192321. }
  192322. row_info->pixel_depth = 8;
  192323. row_info->rowbytes = row_width;
  192324. }
  192325. else /* if (row_info->bit_depth == 16) */
  192326. {
  192327. if (flags & PNG_FLAG_FILLER_AFTER)
  192328. {
  192329. /* This converts from GGXX or GGAA to GG */
  192330. sp += 4; dp += 2;
  192331. for (i = 1; i < row_width; i++)
  192332. {
  192333. *dp++ = *sp++;
  192334. *dp++ = *sp++;
  192335. sp += 2;
  192336. }
  192337. }
  192338. else
  192339. {
  192340. /* This converts from XXGG or AAGG to GG */
  192341. for (i = 0; i < row_width; i++)
  192342. {
  192343. sp += 2;
  192344. *dp++ = *sp++;
  192345. *dp++ = *sp++;
  192346. }
  192347. }
  192348. row_info->pixel_depth = 16;
  192349. row_info->rowbytes = row_width * 2;
  192350. }
  192351. row_info->channels = 1;
  192352. }
  192353. if (flags & PNG_FLAG_STRIP_ALPHA)
  192354. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  192355. }
  192356. }
  192357. #endif
  192358. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  192359. /* swaps red and blue bytes within a pixel */
  192360. void /* PRIVATE */
  192361. png_do_bgr(png_row_infop row_info, png_bytep row)
  192362. {
  192363. png_debug(1, "in png_do_bgr\n");
  192364. if (
  192365. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192366. row != NULL && row_info != NULL &&
  192367. #endif
  192368. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192369. {
  192370. png_uint_32 row_width = row_info->width;
  192371. if (row_info->bit_depth == 8)
  192372. {
  192373. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192374. {
  192375. png_bytep rp;
  192376. png_uint_32 i;
  192377. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  192378. {
  192379. png_byte save = *rp;
  192380. *rp = *(rp + 2);
  192381. *(rp + 2) = save;
  192382. }
  192383. }
  192384. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192385. {
  192386. png_bytep rp;
  192387. png_uint_32 i;
  192388. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  192389. {
  192390. png_byte save = *rp;
  192391. *rp = *(rp + 2);
  192392. *(rp + 2) = save;
  192393. }
  192394. }
  192395. }
  192396. else if (row_info->bit_depth == 16)
  192397. {
  192398. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192399. {
  192400. png_bytep rp;
  192401. png_uint_32 i;
  192402. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  192403. {
  192404. png_byte save = *rp;
  192405. *rp = *(rp + 4);
  192406. *(rp + 4) = save;
  192407. save = *(rp + 1);
  192408. *(rp + 1) = *(rp + 5);
  192409. *(rp + 5) = save;
  192410. }
  192411. }
  192412. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192413. {
  192414. png_bytep rp;
  192415. png_uint_32 i;
  192416. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  192417. {
  192418. png_byte save = *rp;
  192419. *rp = *(rp + 4);
  192420. *(rp + 4) = save;
  192421. save = *(rp + 1);
  192422. *(rp + 1) = *(rp + 5);
  192423. *(rp + 5) = save;
  192424. }
  192425. }
  192426. }
  192427. }
  192428. }
  192429. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  192430. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  192431. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  192432. defined(PNG_LEGACY_SUPPORTED)
  192433. void PNGAPI
  192434. png_set_user_transform_info(png_structp png_ptr, png_voidp
  192435. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  192436. {
  192437. png_debug(1, "in png_set_user_transform_info\n");
  192438. if(png_ptr == NULL) return;
  192439. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  192440. png_ptr->user_transform_ptr = user_transform_ptr;
  192441. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  192442. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  192443. #else
  192444. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  192445. png_warning(png_ptr,
  192446. "This version of libpng does not support user transform info");
  192447. #endif
  192448. }
  192449. #endif
  192450. /* This function returns a pointer to the user_transform_ptr associated with
  192451. * the user transform functions. The application should free any memory
  192452. * associated with this pointer before png_write_destroy and png_read_destroy
  192453. * are called.
  192454. */
  192455. png_voidp PNGAPI
  192456. png_get_user_transform_ptr(png_structp png_ptr)
  192457. {
  192458. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  192459. if (png_ptr == NULL) return (NULL);
  192460. return ((png_voidp)png_ptr->user_transform_ptr);
  192461. #else
  192462. return (NULL);
  192463. #endif
  192464. }
  192465. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  192466. /********* End of inlined file: pngtrans.c *********/
  192467. /********* Start of inlined file: pngwio.c *********/
  192468. /* pngwio.c - functions for data output
  192469. *
  192470. * Last changed in libpng 1.2.13 November 13, 2006
  192471. * For conditions of distribution and use, see copyright notice in png.h
  192472. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  192473. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  192474. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  192475. *
  192476. * This file provides a location for all output. Users who need
  192477. * special handling are expected to write functions that have the same
  192478. * arguments as these and perform similar functions, but that possibly
  192479. * use different output methods. Note that you shouldn't change these
  192480. * functions, but rather write replacement functions and then change
  192481. * them at run time with png_set_write_fn(...).
  192482. */
  192483. #define PNG_INTERNAL
  192484. #ifdef PNG_WRITE_SUPPORTED
  192485. /* Write the data to whatever output you are using. The default routine
  192486. writes to a file pointer. Note that this routine sometimes gets called
  192487. with very small lengths, so you should implement some kind of simple
  192488. buffering if you are using unbuffered writes. This should never be asked
  192489. to write more than 64K on a 16 bit machine. */
  192490. void /* PRIVATE */
  192491. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  192492. {
  192493. if (png_ptr->write_data_fn != NULL )
  192494. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  192495. else
  192496. png_error(png_ptr, "Call to NULL write function");
  192497. }
  192498. #if !defined(PNG_NO_STDIO)
  192499. /* This is the function that does the actual writing of data. If you are
  192500. not writing to a standard C stream, you should create a replacement
  192501. write_data function and use it at run time with png_set_write_fn(), rather
  192502. than changing the library. */
  192503. #ifndef USE_FAR_KEYWORD
  192504. void PNGAPI
  192505. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  192506. {
  192507. png_uint_32 check;
  192508. if(png_ptr == NULL) return;
  192509. #if defined(_WIN32_WCE)
  192510. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  192511. check = 0;
  192512. #else
  192513. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  192514. #endif
  192515. if (check != length)
  192516. png_error(png_ptr, "Write Error");
  192517. }
  192518. #else
  192519. /* this is the model-independent version. Since the standard I/O library
  192520. can't handle far buffers in the medium and small models, we have to copy
  192521. the data.
  192522. */
  192523. #define NEAR_BUF_SIZE 1024
  192524. #define MIN(a,b) (a <= b ? a : b)
  192525. void PNGAPI
  192526. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  192527. {
  192528. png_uint_32 check;
  192529. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  192530. png_FILE_p io_ptr;
  192531. if(png_ptr == NULL) return;
  192532. /* Check if data really is near. If so, use usual code. */
  192533. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  192534. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  192535. if ((png_bytep)near_data == data)
  192536. {
  192537. #if defined(_WIN32_WCE)
  192538. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  192539. check = 0;
  192540. #else
  192541. check = fwrite(near_data, 1, length, io_ptr);
  192542. #endif
  192543. }
  192544. else
  192545. {
  192546. png_byte buf[NEAR_BUF_SIZE];
  192547. png_size_t written, remaining, err;
  192548. check = 0;
  192549. remaining = length;
  192550. do
  192551. {
  192552. written = MIN(NEAR_BUF_SIZE, remaining);
  192553. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  192554. #if defined(_WIN32_WCE)
  192555. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  192556. err = 0;
  192557. #else
  192558. err = fwrite(buf, 1, written, io_ptr);
  192559. #endif
  192560. if (err != written)
  192561. break;
  192562. else
  192563. check += err;
  192564. data += written;
  192565. remaining -= written;
  192566. }
  192567. while (remaining != 0);
  192568. }
  192569. if (check != length)
  192570. png_error(png_ptr, "Write Error");
  192571. }
  192572. #endif
  192573. #endif
  192574. /* This function is called to output any data pending writing (normally
  192575. to disk). After png_flush is called, there should be no data pending
  192576. writing in any buffers. */
  192577. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  192578. void /* PRIVATE */
  192579. png_flush(png_structp png_ptr)
  192580. {
  192581. if (png_ptr->output_flush_fn != NULL)
  192582. (*(png_ptr->output_flush_fn))(png_ptr);
  192583. }
  192584. #if !defined(PNG_NO_STDIO)
  192585. void PNGAPI
  192586. png_default_flush(png_structp png_ptr)
  192587. {
  192588. #if !defined(_WIN32_WCE)
  192589. png_FILE_p io_ptr;
  192590. #endif
  192591. if(png_ptr == NULL) return;
  192592. #if !defined(_WIN32_WCE)
  192593. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  192594. if (io_ptr != NULL)
  192595. fflush(io_ptr);
  192596. #endif
  192597. }
  192598. #endif
  192599. #endif
  192600. /* This function allows the application to supply new output functions for
  192601. libpng if standard C streams aren't being used.
  192602. This function takes as its arguments:
  192603. png_ptr - pointer to a png output data structure
  192604. io_ptr - pointer to user supplied structure containing info about
  192605. the output functions. May be NULL.
  192606. write_data_fn - pointer to a new output function that takes as its
  192607. arguments a pointer to a png_struct, a pointer to
  192608. data to be written, and a 32-bit unsigned int that is
  192609. the number of bytes to be written. The new write
  192610. function should call png_error(png_ptr, "Error msg")
  192611. to exit and output any fatal error messages.
  192612. flush_data_fn - pointer to a new flush function that takes as its
  192613. arguments a pointer to a png_struct. After a call to
  192614. the flush function, there should be no data in any buffers
  192615. or pending transmission. If the output method doesn't do
  192616. any buffering of ouput, a function prototype must still be
  192617. supplied although it doesn't have to do anything. If
  192618. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  192619. time, output_flush_fn will be ignored, although it must be
  192620. supplied for compatibility. */
  192621. void PNGAPI
  192622. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  192623. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  192624. {
  192625. if(png_ptr == NULL) return;
  192626. png_ptr->io_ptr = io_ptr;
  192627. #if !defined(PNG_NO_STDIO)
  192628. if (write_data_fn != NULL)
  192629. png_ptr->write_data_fn = write_data_fn;
  192630. else
  192631. png_ptr->write_data_fn = png_default_write_data;
  192632. #else
  192633. png_ptr->write_data_fn = write_data_fn;
  192634. #endif
  192635. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  192636. #if !defined(PNG_NO_STDIO)
  192637. if (output_flush_fn != NULL)
  192638. png_ptr->output_flush_fn = output_flush_fn;
  192639. else
  192640. png_ptr->output_flush_fn = png_default_flush;
  192641. #else
  192642. png_ptr->output_flush_fn = output_flush_fn;
  192643. #endif
  192644. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  192645. /* It is an error to read while writing a png file */
  192646. if (png_ptr->read_data_fn != NULL)
  192647. {
  192648. png_ptr->read_data_fn = NULL;
  192649. png_warning(png_ptr,
  192650. "Attempted to set both read_data_fn and write_data_fn in");
  192651. png_warning(png_ptr,
  192652. "the same structure. Resetting read_data_fn to NULL.");
  192653. }
  192654. }
  192655. #if defined(USE_FAR_KEYWORD)
  192656. #if defined(_MSC_VER)
  192657. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  192658. {
  192659. void *near_ptr;
  192660. void FAR *far_ptr;
  192661. FP_OFF(near_ptr) = FP_OFF(ptr);
  192662. far_ptr = (void FAR *)near_ptr;
  192663. if(check != 0)
  192664. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  192665. png_error(png_ptr,"segment lost in conversion");
  192666. return(near_ptr);
  192667. }
  192668. # else
  192669. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  192670. {
  192671. void *near_ptr;
  192672. void FAR *far_ptr;
  192673. near_ptr = (void FAR *)ptr;
  192674. far_ptr = (void FAR *)near_ptr;
  192675. if(check != 0)
  192676. if(far_ptr != ptr)
  192677. png_error(png_ptr,"segment lost in conversion");
  192678. return(near_ptr);
  192679. }
  192680. # endif
  192681. # endif
  192682. #endif /* PNG_WRITE_SUPPORTED */
  192683. /********* End of inlined file: pngwio.c *********/
  192684. /********* Start of inlined file: pngwrite.c *********/
  192685. /* pngwrite.c - general routines to write a PNG file
  192686. *
  192687. * Last changed in libpng 1.2.15 January 5, 2007
  192688. * For conditions of distribution and use, see copyright notice in png.h
  192689. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  192690. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  192691. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  192692. */
  192693. /* get internal access to png.h */
  192694. #define PNG_INTERNAL
  192695. #ifdef PNG_WRITE_SUPPORTED
  192696. /* Writes all the PNG information. This is the suggested way to use the
  192697. * library. If you have a new chunk to add, make a function to write it,
  192698. * and put it in the correct location here. If you want the chunk written
  192699. * after the image data, put it in png_write_end(). I strongly encourage
  192700. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  192701. * the chunk, as that will keep the code from breaking if you want to just
  192702. * write a plain PNG file. If you have long comments, I suggest writing
  192703. * them in png_write_end(), and compressing them.
  192704. */
  192705. void PNGAPI
  192706. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  192707. {
  192708. png_debug(1, "in png_write_info_before_PLTE\n");
  192709. if (png_ptr == NULL || info_ptr == NULL)
  192710. return;
  192711. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  192712. {
  192713. png_write_sig(png_ptr); /* write PNG signature */
  192714. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  192715. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  192716. {
  192717. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  192718. png_ptr->mng_features_permitted=0;
  192719. }
  192720. #endif
  192721. /* write IHDR information. */
  192722. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  192723. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  192724. info_ptr->filter_type,
  192725. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  192726. info_ptr->interlace_type);
  192727. #else
  192728. 0);
  192729. #endif
  192730. /* the rest of these check to see if the valid field has the appropriate
  192731. flag set, and if it does, writes the chunk. */
  192732. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  192733. if (info_ptr->valid & PNG_INFO_gAMA)
  192734. {
  192735. # ifdef PNG_FLOATING_POINT_SUPPORTED
  192736. png_write_gAMA(png_ptr, info_ptr->gamma);
  192737. #else
  192738. #ifdef PNG_FIXED_POINT_SUPPORTED
  192739. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  192740. # endif
  192741. #endif
  192742. }
  192743. #endif
  192744. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  192745. if (info_ptr->valid & PNG_INFO_sRGB)
  192746. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  192747. #endif
  192748. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  192749. if (info_ptr->valid & PNG_INFO_iCCP)
  192750. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  192751. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  192752. #endif
  192753. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  192754. if (info_ptr->valid & PNG_INFO_sBIT)
  192755. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  192756. #endif
  192757. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  192758. if (info_ptr->valid & PNG_INFO_cHRM)
  192759. {
  192760. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192761. png_write_cHRM(png_ptr,
  192762. info_ptr->x_white, info_ptr->y_white,
  192763. info_ptr->x_red, info_ptr->y_red,
  192764. info_ptr->x_green, info_ptr->y_green,
  192765. info_ptr->x_blue, info_ptr->y_blue);
  192766. #else
  192767. # ifdef PNG_FIXED_POINT_SUPPORTED
  192768. png_write_cHRM_fixed(png_ptr,
  192769. info_ptr->int_x_white, info_ptr->int_y_white,
  192770. info_ptr->int_x_red, info_ptr->int_y_red,
  192771. info_ptr->int_x_green, info_ptr->int_y_green,
  192772. info_ptr->int_x_blue, info_ptr->int_y_blue);
  192773. # endif
  192774. #endif
  192775. }
  192776. #endif
  192777. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  192778. if (info_ptr->unknown_chunks_num)
  192779. {
  192780. png_unknown_chunk *up;
  192781. png_debug(5, "writing extra chunks\n");
  192782. for (up = info_ptr->unknown_chunks;
  192783. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  192784. up++)
  192785. {
  192786. int keep=png_handle_as_unknown(png_ptr, up->name);
  192787. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  192788. up->location && !(up->location & PNG_HAVE_PLTE) &&
  192789. !(up->location & PNG_HAVE_IDAT) &&
  192790. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  192791. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  192792. {
  192793. png_write_chunk(png_ptr, up->name, up->data, up->size);
  192794. }
  192795. }
  192796. }
  192797. #endif
  192798. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  192799. }
  192800. }
  192801. void PNGAPI
  192802. png_write_info(png_structp png_ptr, png_infop info_ptr)
  192803. {
  192804. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  192805. int i;
  192806. #endif
  192807. png_debug(1, "in png_write_info\n");
  192808. if (png_ptr == NULL || info_ptr == NULL)
  192809. return;
  192810. png_write_info_before_PLTE(png_ptr, info_ptr);
  192811. if (info_ptr->valid & PNG_INFO_PLTE)
  192812. png_write_PLTE(png_ptr, info_ptr->palette,
  192813. (png_uint_32)info_ptr->num_palette);
  192814. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192815. png_error(png_ptr, "Valid palette required for paletted images");
  192816. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  192817. if (info_ptr->valid & PNG_INFO_tRNS)
  192818. {
  192819. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  192820. /* invert the alpha channel (in tRNS) */
  192821. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  192822. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192823. {
  192824. int j;
  192825. for (j=0; j<(int)info_ptr->num_trans; j++)
  192826. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  192827. }
  192828. #endif
  192829. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  192830. info_ptr->num_trans, info_ptr->color_type);
  192831. }
  192832. #endif
  192833. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  192834. if (info_ptr->valid & PNG_INFO_bKGD)
  192835. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  192836. #endif
  192837. #if defined(PNG_WRITE_hIST_SUPPORTED)
  192838. if (info_ptr->valid & PNG_INFO_hIST)
  192839. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  192840. #endif
  192841. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  192842. if (info_ptr->valid & PNG_INFO_oFFs)
  192843. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  192844. info_ptr->offset_unit_type);
  192845. #endif
  192846. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  192847. if (info_ptr->valid & PNG_INFO_pCAL)
  192848. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  192849. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  192850. info_ptr->pcal_units, info_ptr->pcal_params);
  192851. #endif
  192852. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  192853. if (info_ptr->valid & PNG_INFO_sCAL)
  192854. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  192855. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  192856. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  192857. #else
  192858. #ifdef PNG_FIXED_POINT_SUPPORTED
  192859. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  192860. info_ptr->scal_s_width, info_ptr->scal_s_height);
  192861. #else
  192862. png_warning(png_ptr,
  192863. "png_write_sCAL not supported; sCAL chunk not written.");
  192864. #endif
  192865. #endif
  192866. #endif
  192867. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  192868. if (info_ptr->valid & PNG_INFO_pHYs)
  192869. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  192870. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  192871. #endif
  192872. #if defined(PNG_WRITE_tIME_SUPPORTED)
  192873. if (info_ptr->valid & PNG_INFO_tIME)
  192874. {
  192875. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  192876. png_ptr->mode |= PNG_WROTE_tIME;
  192877. }
  192878. #endif
  192879. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  192880. if (info_ptr->valid & PNG_INFO_sPLT)
  192881. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  192882. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  192883. #endif
  192884. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  192885. /* Check to see if we need to write text chunks */
  192886. for (i = 0; i < info_ptr->num_text; i++)
  192887. {
  192888. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  192889. info_ptr->text[i].compression);
  192890. /* an internationalized chunk? */
  192891. if (info_ptr->text[i].compression > 0)
  192892. {
  192893. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  192894. /* write international chunk */
  192895. png_write_iTXt(png_ptr,
  192896. info_ptr->text[i].compression,
  192897. info_ptr->text[i].key,
  192898. info_ptr->text[i].lang,
  192899. info_ptr->text[i].lang_key,
  192900. info_ptr->text[i].text);
  192901. #else
  192902. png_warning(png_ptr, "Unable to write international text");
  192903. #endif
  192904. /* Mark this chunk as written */
  192905. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  192906. }
  192907. /* If we want a compressed text chunk */
  192908. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  192909. {
  192910. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  192911. /* write compressed chunk */
  192912. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  192913. info_ptr->text[i].text, 0,
  192914. info_ptr->text[i].compression);
  192915. #else
  192916. png_warning(png_ptr, "Unable to write compressed text");
  192917. #endif
  192918. /* Mark this chunk as written */
  192919. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  192920. }
  192921. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  192922. {
  192923. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  192924. /* write uncompressed chunk */
  192925. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  192926. info_ptr->text[i].text,
  192927. 0);
  192928. #else
  192929. png_warning(png_ptr, "Unable to write uncompressed text");
  192930. #endif
  192931. /* Mark this chunk as written */
  192932. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  192933. }
  192934. }
  192935. #endif
  192936. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  192937. if (info_ptr->unknown_chunks_num)
  192938. {
  192939. png_unknown_chunk *up;
  192940. png_debug(5, "writing extra chunks\n");
  192941. for (up = info_ptr->unknown_chunks;
  192942. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  192943. up++)
  192944. {
  192945. int keep=png_handle_as_unknown(png_ptr, up->name);
  192946. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  192947. up->location && (up->location & PNG_HAVE_PLTE) &&
  192948. !(up->location & PNG_HAVE_IDAT) &&
  192949. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  192950. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  192951. {
  192952. png_write_chunk(png_ptr, up->name, up->data, up->size);
  192953. }
  192954. }
  192955. }
  192956. #endif
  192957. }
  192958. /* Writes the end of the PNG file. If you don't want to write comments or
  192959. * time information, you can pass NULL for info. If you already wrote these
  192960. * in png_write_info(), do not write them again here. If you have long
  192961. * comments, I suggest writing them here, and compressing them.
  192962. */
  192963. void PNGAPI
  192964. png_write_end(png_structp png_ptr, png_infop info_ptr)
  192965. {
  192966. png_debug(1, "in png_write_end\n");
  192967. if (png_ptr == NULL)
  192968. return;
  192969. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  192970. png_error(png_ptr, "No IDATs written into file");
  192971. /* see if user wants us to write information chunks */
  192972. if (info_ptr != NULL)
  192973. {
  192974. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  192975. int i; /* local index variable */
  192976. #endif
  192977. #if defined(PNG_WRITE_tIME_SUPPORTED)
  192978. /* check to see if user has supplied a time chunk */
  192979. if ((info_ptr->valid & PNG_INFO_tIME) &&
  192980. !(png_ptr->mode & PNG_WROTE_tIME))
  192981. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  192982. #endif
  192983. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  192984. /* loop through comment chunks */
  192985. for (i = 0; i < info_ptr->num_text; i++)
  192986. {
  192987. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  192988. info_ptr->text[i].compression);
  192989. /* an internationalized chunk? */
  192990. if (info_ptr->text[i].compression > 0)
  192991. {
  192992. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  192993. /* write international chunk */
  192994. png_write_iTXt(png_ptr,
  192995. info_ptr->text[i].compression,
  192996. info_ptr->text[i].key,
  192997. info_ptr->text[i].lang,
  192998. info_ptr->text[i].lang_key,
  192999. info_ptr->text[i].text);
  193000. #else
  193001. png_warning(png_ptr, "Unable to write international text");
  193002. #endif
  193003. /* Mark this chunk as written */
  193004. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  193005. }
  193006. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  193007. {
  193008. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  193009. /* write compressed chunk */
  193010. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  193011. info_ptr->text[i].text, 0,
  193012. info_ptr->text[i].compression);
  193013. #else
  193014. png_warning(png_ptr, "Unable to write compressed text");
  193015. #endif
  193016. /* Mark this chunk as written */
  193017. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  193018. }
  193019. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  193020. {
  193021. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  193022. /* write uncompressed chunk */
  193023. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  193024. info_ptr->text[i].text, 0);
  193025. #else
  193026. png_warning(png_ptr, "Unable to write uncompressed text");
  193027. #endif
  193028. /* Mark this chunk as written */
  193029. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  193030. }
  193031. }
  193032. #endif
  193033. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  193034. if (info_ptr->unknown_chunks_num)
  193035. {
  193036. png_unknown_chunk *up;
  193037. png_debug(5, "writing extra chunks\n");
  193038. for (up = info_ptr->unknown_chunks;
  193039. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  193040. up++)
  193041. {
  193042. int keep=png_handle_as_unknown(png_ptr, up->name);
  193043. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  193044. up->location && (up->location & PNG_AFTER_IDAT) &&
  193045. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  193046. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  193047. {
  193048. png_write_chunk(png_ptr, up->name, up->data, up->size);
  193049. }
  193050. }
  193051. }
  193052. #endif
  193053. }
  193054. png_ptr->mode |= PNG_AFTER_IDAT;
  193055. /* write end of PNG file */
  193056. png_write_IEND(png_ptr);
  193057. }
  193058. #if defined(PNG_WRITE_tIME_SUPPORTED)
  193059. #if !defined(_WIN32_WCE)
  193060. /* "time.h" functions are not supported on WindowsCE */
  193061. void PNGAPI
  193062. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  193063. {
  193064. png_debug(1, "in png_convert_from_struct_tm\n");
  193065. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  193066. ptime->month = (png_byte)(ttime->tm_mon + 1);
  193067. ptime->day = (png_byte)ttime->tm_mday;
  193068. ptime->hour = (png_byte)ttime->tm_hour;
  193069. ptime->minute = (png_byte)ttime->tm_min;
  193070. ptime->second = (png_byte)ttime->tm_sec;
  193071. }
  193072. void PNGAPI
  193073. png_convert_from_time_t(png_timep ptime, time_t ttime)
  193074. {
  193075. struct tm *tbuf;
  193076. png_debug(1, "in png_convert_from_time_t\n");
  193077. tbuf = gmtime(&ttime);
  193078. png_convert_from_struct_tm(ptime, tbuf);
  193079. }
  193080. #endif
  193081. #endif
  193082. /* Initialize png_ptr structure, and allocate any memory needed */
  193083. png_structp PNGAPI
  193084. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  193085. png_error_ptr error_fn, png_error_ptr warn_fn)
  193086. {
  193087. #ifdef PNG_USER_MEM_SUPPORTED
  193088. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  193089. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  193090. }
  193091. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  193092. png_structp PNGAPI
  193093. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  193094. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  193095. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  193096. {
  193097. #endif /* PNG_USER_MEM_SUPPORTED */
  193098. png_structp png_ptr;
  193099. #ifdef PNG_SETJMP_SUPPORTED
  193100. #ifdef USE_FAR_KEYWORD
  193101. jmp_buf jmpbuf;
  193102. #endif
  193103. #endif
  193104. int i;
  193105. png_debug(1, "in png_create_write_struct\n");
  193106. #ifdef PNG_USER_MEM_SUPPORTED
  193107. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  193108. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  193109. #else
  193110. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  193111. #endif /* PNG_USER_MEM_SUPPORTED */
  193112. if (png_ptr == NULL)
  193113. return (NULL);
  193114. /* added at libpng-1.2.6 */
  193115. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  193116. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  193117. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  193118. #endif
  193119. #ifdef PNG_SETJMP_SUPPORTED
  193120. #ifdef USE_FAR_KEYWORD
  193121. if (setjmp(jmpbuf))
  193122. #else
  193123. if (setjmp(png_ptr->jmpbuf))
  193124. #endif
  193125. {
  193126. png_free(png_ptr, png_ptr->zbuf);
  193127. png_ptr->zbuf=NULL;
  193128. png_destroy_struct(png_ptr);
  193129. return (NULL);
  193130. }
  193131. #ifdef USE_FAR_KEYWORD
  193132. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  193133. #endif
  193134. #endif
  193135. #ifdef PNG_USER_MEM_SUPPORTED
  193136. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  193137. #endif /* PNG_USER_MEM_SUPPORTED */
  193138. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  193139. i=0;
  193140. do
  193141. {
  193142. if(user_png_ver[i] != png_libpng_ver[i])
  193143. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  193144. } while (png_libpng_ver[i++]);
  193145. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  193146. {
  193147. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  193148. * we must recompile any applications that use any older library version.
  193149. * For versions after libpng 1.0, we will be compatible, so we need
  193150. * only check the first digit.
  193151. */
  193152. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  193153. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  193154. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  193155. {
  193156. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193157. char msg[80];
  193158. if (user_png_ver)
  193159. {
  193160. png_snprintf(msg, 80,
  193161. "Application was compiled with png.h from libpng-%.20s",
  193162. user_png_ver);
  193163. png_warning(png_ptr, msg);
  193164. }
  193165. png_snprintf(msg, 80,
  193166. "Application is running with png.c from libpng-%.20s",
  193167. png_libpng_ver);
  193168. png_warning(png_ptr, msg);
  193169. #endif
  193170. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  193171. png_ptr->flags=0;
  193172. #endif
  193173. png_error(png_ptr,
  193174. "Incompatible libpng version in application and library");
  193175. }
  193176. }
  193177. /* initialize zbuf - compression buffer */
  193178. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  193179. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  193180. (png_uint_32)png_ptr->zbuf_size);
  193181. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  193182. png_flush_ptr_NULL);
  193183. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  193184. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  193185. 1, png_doublep_NULL, png_doublep_NULL);
  193186. #endif
  193187. #ifdef PNG_SETJMP_SUPPORTED
  193188. /* Applications that neglect to set up their own setjmp() and then encounter
  193189. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  193190. abort instead of returning. */
  193191. #ifdef USE_FAR_KEYWORD
  193192. if (setjmp(jmpbuf))
  193193. PNG_ABORT();
  193194. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  193195. #else
  193196. if (setjmp(png_ptr->jmpbuf))
  193197. PNG_ABORT();
  193198. #endif
  193199. #endif
  193200. return (png_ptr);
  193201. }
  193202. /* Initialize png_ptr structure, and allocate any memory needed */
  193203. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  193204. /* Deprecated. */
  193205. #undef png_write_init
  193206. void PNGAPI
  193207. png_write_init(png_structp png_ptr)
  193208. {
  193209. /* We only come here via pre-1.0.7-compiled applications */
  193210. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  193211. }
  193212. void PNGAPI
  193213. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  193214. png_size_t png_struct_size, png_size_t png_info_size)
  193215. {
  193216. /* We only come here via pre-1.0.12-compiled applications */
  193217. if(png_ptr == NULL) return;
  193218. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193219. if(png_sizeof(png_struct) > png_struct_size ||
  193220. png_sizeof(png_info) > png_info_size)
  193221. {
  193222. char msg[80];
  193223. png_ptr->warning_fn=NULL;
  193224. if (user_png_ver)
  193225. {
  193226. png_snprintf(msg, 80,
  193227. "Application was compiled with png.h from libpng-%.20s",
  193228. user_png_ver);
  193229. png_warning(png_ptr, msg);
  193230. }
  193231. png_snprintf(msg, 80,
  193232. "Application is running with png.c from libpng-%.20s",
  193233. png_libpng_ver);
  193234. png_warning(png_ptr, msg);
  193235. }
  193236. #endif
  193237. if(png_sizeof(png_struct) > png_struct_size)
  193238. {
  193239. png_ptr->error_fn=NULL;
  193240. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  193241. png_ptr->flags=0;
  193242. #endif
  193243. png_error(png_ptr,
  193244. "The png struct allocated by the application for writing is too small.");
  193245. }
  193246. if(png_sizeof(png_info) > png_info_size)
  193247. {
  193248. png_ptr->error_fn=NULL;
  193249. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  193250. png_ptr->flags=0;
  193251. #endif
  193252. png_error(png_ptr,
  193253. "The info struct allocated by the application for writing is too small.");
  193254. }
  193255. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  193256. }
  193257. #endif /* PNG_1_0_X || PNG_1_2_X */
  193258. void PNGAPI
  193259. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  193260. png_size_t png_struct_size)
  193261. {
  193262. png_structp png_ptr=*ptr_ptr;
  193263. #ifdef PNG_SETJMP_SUPPORTED
  193264. jmp_buf tmp_jmp; /* to save current jump buffer */
  193265. #endif
  193266. int i = 0;
  193267. if (png_ptr == NULL)
  193268. return;
  193269. do
  193270. {
  193271. if (user_png_ver[i] != png_libpng_ver[i])
  193272. {
  193273. #ifdef PNG_LEGACY_SUPPORTED
  193274. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  193275. #else
  193276. png_ptr->warning_fn=NULL;
  193277. png_warning(png_ptr,
  193278. "Application uses deprecated png_write_init() and should be recompiled.");
  193279. break;
  193280. #endif
  193281. }
  193282. } while (png_libpng_ver[i++]);
  193283. png_debug(1, "in png_write_init_3\n");
  193284. #ifdef PNG_SETJMP_SUPPORTED
  193285. /* save jump buffer and error functions */
  193286. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  193287. #endif
  193288. if (png_sizeof(png_struct) > png_struct_size)
  193289. {
  193290. png_destroy_struct(png_ptr);
  193291. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  193292. *ptr_ptr = png_ptr;
  193293. }
  193294. /* reset all variables to 0 */
  193295. png_memset(png_ptr, 0, png_sizeof (png_struct));
  193296. /* added at libpng-1.2.6 */
  193297. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  193298. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  193299. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  193300. #endif
  193301. #ifdef PNG_SETJMP_SUPPORTED
  193302. /* restore jump buffer */
  193303. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  193304. #endif
  193305. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  193306. png_flush_ptr_NULL);
  193307. /* initialize zbuf - compression buffer */
  193308. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  193309. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  193310. (png_uint_32)png_ptr->zbuf_size);
  193311. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  193312. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  193313. 1, png_doublep_NULL, png_doublep_NULL);
  193314. #endif
  193315. }
  193316. /* Write a few rows of image data. If the image is interlaced,
  193317. * either you will have to write the 7 sub images, or, if you
  193318. * have called png_set_interlace_handling(), you will have to
  193319. * "write" the image seven times.
  193320. */
  193321. void PNGAPI
  193322. png_write_rows(png_structp png_ptr, png_bytepp row,
  193323. png_uint_32 num_rows)
  193324. {
  193325. png_uint_32 i; /* row counter */
  193326. png_bytepp rp; /* row pointer */
  193327. png_debug(1, "in png_write_rows\n");
  193328. if (png_ptr == NULL)
  193329. return;
  193330. /* loop through the rows */
  193331. for (i = 0, rp = row; i < num_rows; i++, rp++)
  193332. {
  193333. png_write_row(png_ptr, *rp);
  193334. }
  193335. }
  193336. /* Write the image. You only need to call this function once, even
  193337. * if you are writing an interlaced image.
  193338. */
  193339. void PNGAPI
  193340. png_write_image(png_structp png_ptr, png_bytepp image)
  193341. {
  193342. png_uint_32 i; /* row index */
  193343. int pass, num_pass; /* pass variables */
  193344. png_bytepp rp; /* points to current row */
  193345. if (png_ptr == NULL)
  193346. return;
  193347. png_debug(1, "in png_write_image\n");
  193348. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  193349. /* intialize interlace handling. If image is not interlaced,
  193350. this will set pass to 1 */
  193351. num_pass = png_set_interlace_handling(png_ptr);
  193352. #else
  193353. num_pass = 1;
  193354. #endif
  193355. /* loop through passes */
  193356. for (pass = 0; pass < num_pass; pass++)
  193357. {
  193358. /* loop through image */
  193359. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  193360. {
  193361. png_write_row(png_ptr, *rp);
  193362. }
  193363. }
  193364. }
  193365. /* called by user to write a row of image data */
  193366. void PNGAPI
  193367. png_write_row(png_structp png_ptr, png_bytep row)
  193368. {
  193369. if (png_ptr == NULL)
  193370. return;
  193371. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  193372. png_ptr->row_number, png_ptr->pass);
  193373. /* initialize transformations and other stuff if first time */
  193374. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  193375. {
  193376. /* make sure we wrote the header info */
  193377. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  193378. png_error(png_ptr,
  193379. "png_write_info was never called before png_write_row.");
  193380. /* check for transforms that have been set but were defined out */
  193381. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  193382. if (png_ptr->transformations & PNG_INVERT_MONO)
  193383. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  193384. #endif
  193385. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  193386. if (png_ptr->transformations & PNG_FILLER)
  193387. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  193388. #endif
  193389. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  193390. if (png_ptr->transformations & PNG_PACKSWAP)
  193391. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  193392. #endif
  193393. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  193394. if (png_ptr->transformations & PNG_PACK)
  193395. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  193396. #endif
  193397. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  193398. if (png_ptr->transformations & PNG_SHIFT)
  193399. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  193400. #endif
  193401. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  193402. if (png_ptr->transformations & PNG_BGR)
  193403. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  193404. #endif
  193405. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  193406. if (png_ptr->transformations & PNG_SWAP_BYTES)
  193407. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  193408. #endif
  193409. png_write_start_row(png_ptr);
  193410. }
  193411. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  193412. /* if interlaced and not interested in row, return */
  193413. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  193414. {
  193415. switch (png_ptr->pass)
  193416. {
  193417. case 0:
  193418. if (png_ptr->row_number & 0x07)
  193419. {
  193420. png_write_finish_row(png_ptr);
  193421. return;
  193422. }
  193423. break;
  193424. case 1:
  193425. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  193426. {
  193427. png_write_finish_row(png_ptr);
  193428. return;
  193429. }
  193430. break;
  193431. case 2:
  193432. if ((png_ptr->row_number & 0x07) != 4)
  193433. {
  193434. png_write_finish_row(png_ptr);
  193435. return;
  193436. }
  193437. break;
  193438. case 3:
  193439. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  193440. {
  193441. png_write_finish_row(png_ptr);
  193442. return;
  193443. }
  193444. break;
  193445. case 4:
  193446. if ((png_ptr->row_number & 0x03) != 2)
  193447. {
  193448. png_write_finish_row(png_ptr);
  193449. return;
  193450. }
  193451. break;
  193452. case 5:
  193453. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  193454. {
  193455. png_write_finish_row(png_ptr);
  193456. return;
  193457. }
  193458. break;
  193459. case 6:
  193460. if (!(png_ptr->row_number & 0x01))
  193461. {
  193462. png_write_finish_row(png_ptr);
  193463. return;
  193464. }
  193465. break;
  193466. }
  193467. }
  193468. #endif
  193469. /* set up row info for transformations */
  193470. png_ptr->row_info.color_type = png_ptr->color_type;
  193471. png_ptr->row_info.width = png_ptr->usr_width;
  193472. png_ptr->row_info.channels = png_ptr->usr_channels;
  193473. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  193474. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  193475. png_ptr->row_info.channels);
  193476. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  193477. png_ptr->row_info.width);
  193478. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  193479. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  193480. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  193481. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  193482. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  193483. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  193484. /* Copy user's row into buffer, leaving room for filter byte. */
  193485. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  193486. png_ptr->row_info.rowbytes);
  193487. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  193488. /* handle interlacing */
  193489. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  193490. (png_ptr->transformations & PNG_INTERLACE))
  193491. {
  193492. png_do_write_interlace(&(png_ptr->row_info),
  193493. png_ptr->row_buf + 1, png_ptr->pass);
  193494. /* this should always get caught above, but still ... */
  193495. if (!(png_ptr->row_info.width))
  193496. {
  193497. png_write_finish_row(png_ptr);
  193498. return;
  193499. }
  193500. }
  193501. #endif
  193502. /* handle other transformations */
  193503. if (png_ptr->transformations)
  193504. png_do_write_transformations(png_ptr);
  193505. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193506. /* Write filter_method 64 (intrapixel differencing) only if
  193507. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  193508. * 2. Libpng did not write a PNG signature (this filter_method is only
  193509. * used in PNG datastreams that are embedded in MNG datastreams) and
  193510. * 3. The application called png_permit_mng_features with a mask that
  193511. * included PNG_FLAG_MNG_FILTER_64 and
  193512. * 4. The filter_method is 64 and
  193513. * 5. The color_type is RGB or RGBA
  193514. */
  193515. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  193516. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  193517. {
  193518. /* Intrapixel differencing */
  193519. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  193520. }
  193521. #endif
  193522. /* Find a filter if necessary, filter the row and write it out. */
  193523. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  193524. if (png_ptr->write_row_fn != NULL)
  193525. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  193526. }
  193527. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  193528. /* Set the automatic flush interval or 0 to turn flushing off */
  193529. void PNGAPI
  193530. png_set_flush(png_structp png_ptr, int nrows)
  193531. {
  193532. png_debug(1, "in png_set_flush\n");
  193533. if (png_ptr == NULL)
  193534. return;
  193535. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  193536. }
  193537. /* flush the current output buffers now */
  193538. void PNGAPI
  193539. png_write_flush(png_structp png_ptr)
  193540. {
  193541. int wrote_IDAT;
  193542. png_debug(1, "in png_write_flush\n");
  193543. if (png_ptr == NULL)
  193544. return;
  193545. /* We have already written out all of the data */
  193546. if (png_ptr->row_number >= png_ptr->num_rows)
  193547. return;
  193548. do
  193549. {
  193550. int ret;
  193551. /* compress the data */
  193552. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  193553. wrote_IDAT = 0;
  193554. /* check for compression errors */
  193555. if (ret != Z_OK)
  193556. {
  193557. if (png_ptr->zstream.msg != NULL)
  193558. png_error(png_ptr, png_ptr->zstream.msg);
  193559. else
  193560. png_error(png_ptr, "zlib error");
  193561. }
  193562. if (!(png_ptr->zstream.avail_out))
  193563. {
  193564. /* write the IDAT and reset the zlib output buffer */
  193565. png_write_IDAT(png_ptr, png_ptr->zbuf,
  193566. png_ptr->zbuf_size);
  193567. png_ptr->zstream.next_out = png_ptr->zbuf;
  193568. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193569. wrote_IDAT = 1;
  193570. }
  193571. } while(wrote_IDAT == 1);
  193572. /* If there is any data left to be output, write it into a new IDAT */
  193573. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  193574. {
  193575. /* write the IDAT and reset the zlib output buffer */
  193576. png_write_IDAT(png_ptr, png_ptr->zbuf,
  193577. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  193578. png_ptr->zstream.next_out = png_ptr->zbuf;
  193579. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193580. }
  193581. png_ptr->flush_rows = 0;
  193582. png_flush(png_ptr);
  193583. }
  193584. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  193585. /* free all memory used by the write */
  193586. void PNGAPI
  193587. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  193588. {
  193589. png_structp png_ptr = NULL;
  193590. png_infop info_ptr = NULL;
  193591. #ifdef PNG_USER_MEM_SUPPORTED
  193592. png_free_ptr free_fn = NULL;
  193593. png_voidp mem_ptr = NULL;
  193594. #endif
  193595. png_debug(1, "in png_destroy_write_struct\n");
  193596. if (png_ptr_ptr != NULL)
  193597. {
  193598. png_ptr = *png_ptr_ptr;
  193599. #ifdef PNG_USER_MEM_SUPPORTED
  193600. free_fn = png_ptr->free_fn;
  193601. mem_ptr = png_ptr->mem_ptr;
  193602. #endif
  193603. }
  193604. if (info_ptr_ptr != NULL)
  193605. info_ptr = *info_ptr_ptr;
  193606. if (info_ptr != NULL)
  193607. {
  193608. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  193609. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  193610. if (png_ptr->num_chunk_list)
  193611. {
  193612. png_free(png_ptr, png_ptr->chunk_list);
  193613. png_ptr->chunk_list=NULL;
  193614. png_ptr->num_chunk_list=0;
  193615. }
  193616. #endif
  193617. #ifdef PNG_USER_MEM_SUPPORTED
  193618. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  193619. (png_voidp)mem_ptr);
  193620. #else
  193621. png_destroy_struct((png_voidp)info_ptr);
  193622. #endif
  193623. *info_ptr_ptr = NULL;
  193624. }
  193625. if (png_ptr != NULL)
  193626. {
  193627. png_write_destroy(png_ptr);
  193628. #ifdef PNG_USER_MEM_SUPPORTED
  193629. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  193630. (png_voidp)mem_ptr);
  193631. #else
  193632. png_destroy_struct((png_voidp)png_ptr);
  193633. #endif
  193634. *png_ptr_ptr = NULL;
  193635. }
  193636. }
  193637. /* Free any memory used in png_ptr struct (old method) */
  193638. void /* PRIVATE */
  193639. png_write_destroy(png_structp png_ptr)
  193640. {
  193641. #ifdef PNG_SETJMP_SUPPORTED
  193642. jmp_buf tmp_jmp; /* save jump buffer */
  193643. #endif
  193644. png_error_ptr error_fn;
  193645. png_error_ptr warning_fn;
  193646. png_voidp error_ptr;
  193647. #ifdef PNG_USER_MEM_SUPPORTED
  193648. png_free_ptr free_fn;
  193649. #endif
  193650. png_debug(1, "in png_write_destroy\n");
  193651. /* free any memory zlib uses */
  193652. deflateEnd(&png_ptr->zstream);
  193653. /* free our memory. png_free checks NULL for us. */
  193654. png_free(png_ptr, png_ptr->zbuf);
  193655. png_free(png_ptr, png_ptr->row_buf);
  193656. png_free(png_ptr, png_ptr->prev_row);
  193657. png_free(png_ptr, png_ptr->sub_row);
  193658. png_free(png_ptr, png_ptr->up_row);
  193659. png_free(png_ptr, png_ptr->avg_row);
  193660. png_free(png_ptr, png_ptr->paeth_row);
  193661. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  193662. png_free(png_ptr, png_ptr->time_buffer);
  193663. #endif
  193664. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  193665. png_free(png_ptr, png_ptr->prev_filters);
  193666. png_free(png_ptr, png_ptr->filter_weights);
  193667. png_free(png_ptr, png_ptr->inv_filter_weights);
  193668. png_free(png_ptr, png_ptr->filter_costs);
  193669. png_free(png_ptr, png_ptr->inv_filter_costs);
  193670. #endif
  193671. #ifdef PNG_SETJMP_SUPPORTED
  193672. /* reset structure */
  193673. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  193674. #endif
  193675. error_fn = png_ptr->error_fn;
  193676. warning_fn = png_ptr->warning_fn;
  193677. error_ptr = png_ptr->error_ptr;
  193678. #ifdef PNG_USER_MEM_SUPPORTED
  193679. free_fn = png_ptr->free_fn;
  193680. #endif
  193681. png_memset(png_ptr, 0, png_sizeof (png_struct));
  193682. png_ptr->error_fn = error_fn;
  193683. png_ptr->warning_fn = warning_fn;
  193684. png_ptr->error_ptr = error_ptr;
  193685. #ifdef PNG_USER_MEM_SUPPORTED
  193686. png_ptr->free_fn = free_fn;
  193687. #endif
  193688. #ifdef PNG_SETJMP_SUPPORTED
  193689. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  193690. #endif
  193691. }
  193692. /* Allow the application to select one or more row filters to use. */
  193693. void PNGAPI
  193694. png_set_filter(png_structp png_ptr, int method, int filters)
  193695. {
  193696. png_debug(1, "in png_set_filter\n");
  193697. if (png_ptr == NULL)
  193698. return;
  193699. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193700. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  193701. (method == PNG_INTRAPIXEL_DIFFERENCING))
  193702. method = PNG_FILTER_TYPE_BASE;
  193703. #endif
  193704. if (method == PNG_FILTER_TYPE_BASE)
  193705. {
  193706. switch (filters & (PNG_ALL_FILTERS | 0x07))
  193707. {
  193708. #ifndef PNG_NO_WRITE_FILTER
  193709. case 5:
  193710. case 6:
  193711. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  193712. #endif /* PNG_NO_WRITE_FILTER */
  193713. case PNG_FILTER_VALUE_NONE:
  193714. png_ptr->do_filter=PNG_FILTER_NONE; break;
  193715. #ifndef PNG_NO_WRITE_FILTER
  193716. case PNG_FILTER_VALUE_SUB:
  193717. png_ptr->do_filter=PNG_FILTER_SUB; break;
  193718. case PNG_FILTER_VALUE_UP:
  193719. png_ptr->do_filter=PNG_FILTER_UP; break;
  193720. case PNG_FILTER_VALUE_AVG:
  193721. png_ptr->do_filter=PNG_FILTER_AVG; break;
  193722. case PNG_FILTER_VALUE_PAETH:
  193723. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  193724. default: png_ptr->do_filter = (png_byte)filters; break;
  193725. #else
  193726. default: png_warning(png_ptr, "Unknown row filter for method 0");
  193727. #endif /* PNG_NO_WRITE_FILTER */
  193728. }
  193729. /* If we have allocated the row_buf, this means we have already started
  193730. * with the image and we should have allocated all of the filter buffers
  193731. * that have been selected. If prev_row isn't already allocated, then
  193732. * it is too late to start using the filters that need it, since we
  193733. * will be missing the data in the previous row. If an application
  193734. * wants to start and stop using particular filters during compression,
  193735. * it should start out with all of the filters, and then add and
  193736. * remove them after the start of compression.
  193737. */
  193738. if (png_ptr->row_buf != NULL)
  193739. {
  193740. #ifndef PNG_NO_WRITE_FILTER
  193741. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  193742. {
  193743. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  193744. (png_ptr->rowbytes + 1));
  193745. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  193746. }
  193747. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  193748. {
  193749. if (png_ptr->prev_row == NULL)
  193750. {
  193751. png_warning(png_ptr, "Can't add Up filter after starting");
  193752. png_ptr->do_filter &= ~PNG_FILTER_UP;
  193753. }
  193754. else
  193755. {
  193756. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  193757. (png_ptr->rowbytes + 1));
  193758. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  193759. }
  193760. }
  193761. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  193762. {
  193763. if (png_ptr->prev_row == NULL)
  193764. {
  193765. png_warning(png_ptr, "Can't add Average filter after starting");
  193766. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  193767. }
  193768. else
  193769. {
  193770. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  193771. (png_ptr->rowbytes + 1));
  193772. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  193773. }
  193774. }
  193775. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  193776. png_ptr->paeth_row == NULL)
  193777. {
  193778. if (png_ptr->prev_row == NULL)
  193779. {
  193780. png_warning(png_ptr, "Can't add Paeth filter after starting");
  193781. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  193782. }
  193783. else
  193784. {
  193785. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  193786. (png_ptr->rowbytes + 1));
  193787. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  193788. }
  193789. }
  193790. if (png_ptr->do_filter == PNG_NO_FILTERS)
  193791. #endif /* PNG_NO_WRITE_FILTER */
  193792. png_ptr->do_filter = PNG_FILTER_NONE;
  193793. }
  193794. }
  193795. else
  193796. png_error(png_ptr, "Unknown custom filter method");
  193797. }
  193798. /* This allows us to influence the way in which libpng chooses the "best"
  193799. * filter for the current scanline. While the "minimum-sum-of-absolute-
  193800. * differences metric is relatively fast and effective, there is some
  193801. * question as to whether it can be improved upon by trying to keep the
  193802. * filtered data going to zlib more consistent, hopefully resulting in
  193803. * better compression.
  193804. */
  193805. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  193806. void PNGAPI
  193807. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  193808. int num_weights, png_doublep filter_weights,
  193809. png_doublep filter_costs)
  193810. {
  193811. int i;
  193812. png_debug(1, "in png_set_filter_heuristics\n");
  193813. if (png_ptr == NULL)
  193814. return;
  193815. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  193816. {
  193817. png_warning(png_ptr, "Unknown filter heuristic method");
  193818. return;
  193819. }
  193820. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  193821. {
  193822. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  193823. }
  193824. if (num_weights < 0 || filter_weights == NULL ||
  193825. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  193826. {
  193827. num_weights = 0;
  193828. }
  193829. png_ptr->num_prev_filters = (png_byte)num_weights;
  193830. png_ptr->heuristic_method = (png_byte)heuristic_method;
  193831. if (num_weights > 0)
  193832. {
  193833. if (png_ptr->prev_filters == NULL)
  193834. {
  193835. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  193836. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  193837. /* To make sure that the weighting starts out fairly */
  193838. for (i = 0; i < num_weights; i++)
  193839. {
  193840. png_ptr->prev_filters[i] = 255;
  193841. }
  193842. }
  193843. if (png_ptr->filter_weights == NULL)
  193844. {
  193845. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  193846. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  193847. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  193848. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  193849. for (i = 0; i < num_weights; i++)
  193850. {
  193851. png_ptr->inv_filter_weights[i] =
  193852. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  193853. }
  193854. }
  193855. for (i = 0; i < num_weights; i++)
  193856. {
  193857. if (filter_weights[i] < 0.0)
  193858. {
  193859. png_ptr->inv_filter_weights[i] =
  193860. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  193861. }
  193862. else
  193863. {
  193864. png_ptr->inv_filter_weights[i] =
  193865. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  193866. png_ptr->filter_weights[i] =
  193867. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  193868. }
  193869. }
  193870. }
  193871. /* If, in the future, there are other filter methods, this would
  193872. * need to be based on png_ptr->filter.
  193873. */
  193874. if (png_ptr->filter_costs == NULL)
  193875. {
  193876. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  193877. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  193878. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  193879. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  193880. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  193881. {
  193882. png_ptr->inv_filter_costs[i] =
  193883. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  193884. }
  193885. }
  193886. /* Here is where we set the relative costs of the different filters. We
  193887. * should take the desired compression level into account when setting
  193888. * the costs, so that Paeth, for instance, has a high relative cost at low
  193889. * compression levels, while it has a lower relative cost at higher
  193890. * compression settings. The filter types are in order of increasing
  193891. * relative cost, so it would be possible to do this with an algorithm.
  193892. */
  193893. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  193894. {
  193895. if (filter_costs == NULL || filter_costs[i] < 0.0)
  193896. {
  193897. png_ptr->inv_filter_costs[i] =
  193898. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  193899. }
  193900. else if (filter_costs[i] >= 1.0)
  193901. {
  193902. png_ptr->inv_filter_costs[i] =
  193903. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  193904. png_ptr->filter_costs[i] =
  193905. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  193906. }
  193907. }
  193908. }
  193909. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  193910. void PNGAPI
  193911. png_set_compression_level(png_structp png_ptr, int level)
  193912. {
  193913. png_debug(1, "in png_set_compression_level\n");
  193914. if (png_ptr == NULL)
  193915. return;
  193916. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  193917. png_ptr->zlib_level = level;
  193918. }
  193919. void PNGAPI
  193920. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  193921. {
  193922. png_debug(1, "in png_set_compression_mem_level\n");
  193923. if (png_ptr == NULL)
  193924. return;
  193925. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  193926. png_ptr->zlib_mem_level = mem_level;
  193927. }
  193928. void PNGAPI
  193929. png_set_compression_strategy(png_structp png_ptr, int strategy)
  193930. {
  193931. png_debug(1, "in png_set_compression_strategy\n");
  193932. if (png_ptr == NULL)
  193933. return;
  193934. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  193935. png_ptr->zlib_strategy = strategy;
  193936. }
  193937. void PNGAPI
  193938. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  193939. {
  193940. if (png_ptr == NULL)
  193941. return;
  193942. if (window_bits > 15)
  193943. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  193944. else if (window_bits < 8)
  193945. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  193946. #ifndef WBITS_8_OK
  193947. /* avoid libpng bug with 256-byte windows */
  193948. if (window_bits == 8)
  193949. {
  193950. png_warning(png_ptr, "Compression window is being reset to 512");
  193951. window_bits=9;
  193952. }
  193953. #endif
  193954. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  193955. png_ptr->zlib_window_bits = window_bits;
  193956. }
  193957. void PNGAPI
  193958. png_set_compression_method(png_structp png_ptr, int method)
  193959. {
  193960. png_debug(1, "in png_set_compression_method\n");
  193961. if (png_ptr == NULL)
  193962. return;
  193963. if (method != 8)
  193964. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  193965. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  193966. png_ptr->zlib_method = method;
  193967. }
  193968. void PNGAPI
  193969. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  193970. {
  193971. if (png_ptr == NULL)
  193972. return;
  193973. png_ptr->write_row_fn = write_row_fn;
  193974. }
  193975. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  193976. void PNGAPI
  193977. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  193978. write_user_transform_fn)
  193979. {
  193980. png_debug(1, "in png_set_write_user_transform_fn\n");
  193981. if (png_ptr == NULL)
  193982. return;
  193983. png_ptr->transformations |= PNG_USER_TRANSFORM;
  193984. png_ptr->write_user_transform_fn = write_user_transform_fn;
  193985. }
  193986. #endif
  193987. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  193988. void PNGAPI
  193989. png_write_png(png_structp png_ptr, png_infop info_ptr,
  193990. int transforms, voidp params)
  193991. {
  193992. if (png_ptr == NULL || info_ptr == NULL)
  193993. return;
  193994. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  193995. /* invert the alpha channel from opacity to transparency */
  193996. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  193997. png_set_invert_alpha(png_ptr);
  193998. #endif
  193999. /* Write the file header information. */
  194000. png_write_info(png_ptr, info_ptr);
  194001. /* ------ these transformations don't touch the info structure ------- */
  194002. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  194003. /* invert monochrome pixels */
  194004. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  194005. png_set_invert_mono(png_ptr);
  194006. #endif
  194007. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  194008. /* Shift the pixels up to a legal bit depth and fill in
  194009. * as appropriate to correctly scale the image.
  194010. */
  194011. if ((transforms & PNG_TRANSFORM_SHIFT)
  194012. && (info_ptr->valid & PNG_INFO_sBIT))
  194013. png_set_shift(png_ptr, &info_ptr->sig_bit);
  194014. #endif
  194015. #if defined(PNG_WRITE_PACK_SUPPORTED)
  194016. /* pack pixels into bytes */
  194017. if (transforms & PNG_TRANSFORM_PACKING)
  194018. png_set_packing(png_ptr);
  194019. #endif
  194020. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  194021. /* swap location of alpha bytes from ARGB to RGBA */
  194022. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  194023. png_set_swap_alpha(png_ptr);
  194024. #endif
  194025. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  194026. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  194027. * RGB (4 channels -> 3 channels). The second parameter is not used.
  194028. */
  194029. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  194030. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  194031. #endif
  194032. #if defined(PNG_WRITE_BGR_SUPPORTED)
  194033. /* flip BGR pixels to RGB */
  194034. if (transforms & PNG_TRANSFORM_BGR)
  194035. png_set_bgr(png_ptr);
  194036. #endif
  194037. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  194038. /* swap bytes of 16-bit files to most significant byte first */
  194039. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  194040. png_set_swap(png_ptr);
  194041. #endif
  194042. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  194043. /* swap bits of 1, 2, 4 bit packed pixel formats */
  194044. if (transforms & PNG_TRANSFORM_PACKSWAP)
  194045. png_set_packswap(png_ptr);
  194046. #endif
  194047. /* ----------------------- end of transformations ------------------- */
  194048. /* write the bits */
  194049. if (info_ptr->valid & PNG_INFO_IDAT)
  194050. png_write_image(png_ptr, info_ptr->row_pointers);
  194051. /* It is REQUIRED to call this to finish writing the rest of the file */
  194052. png_write_end(png_ptr, info_ptr);
  194053. transforms = transforms; /* quiet compiler warnings */
  194054. params = params;
  194055. }
  194056. #endif
  194057. #endif /* PNG_WRITE_SUPPORTED */
  194058. /********* End of inlined file: pngwrite.c *********/
  194059. /********* Start of inlined file: pngwtran.c *********/
  194060. /* pngwtran.c - transforms the data in a row for PNG writers
  194061. *
  194062. * Last changed in libpng 1.2.9 April 14, 2006
  194063. * For conditions of distribution and use, see copyright notice in png.h
  194064. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  194065. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194066. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194067. */
  194068. #define PNG_INTERNAL
  194069. #ifdef PNG_WRITE_SUPPORTED
  194070. /* Transform the data according to the user's wishes. The order of
  194071. * transformations is significant.
  194072. */
  194073. void /* PRIVATE */
  194074. png_do_write_transformations(png_structp png_ptr)
  194075. {
  194076. png_debug(1, "in png_do_write_transformations\n");
  194077. if (png_ptr == NULL)
  194078. return;
  194079. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  194080. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  194081. if(png_ptr->write_user_transform_fn != NULL)
  194082. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  194083. (png_ptr, /* png_ptr */
  194084. &(png_ptr->row_info), /* row_info: */
  194085. /* png_uint_32 width; width of row */
  194086. /* png_uint_32 rowbytes; number of bytes in row */
  194087. /* png_byte color_type; color type of pixels */
  194088. /* png_byte bit_depth; bit depth of samples */
  194089. /* png_byte channels; number of channels (1-4) */
  194090. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  194091. png_ptr->row_buf + 1); /* start of pixel data for row */
  194092. #endif
  194093. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  194094. if (png_ptr->transformations & PNG_FILLER)
  194095. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  194096. png_ptr->flags);
  194097. #endif
  194098. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  194099. if (png_ptr->transformations & PNG_PACKSWAP)
  194100. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194101. #endif
  194102. #if defined(PNG_WRITE_PACK_SUPPORTED)
  194103. if (png_ptr->transformations & PNG_PACK)
  194104. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  194105. (png_uint_32)png_ptr->bit_depth);
  194106. #endif
  194107. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  194108. if (png_ptr->transformations & PNG_SWAP_BYTES)
  194109. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194110. #endif
  194111. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  194112. if (png_ptr->transformations & PNG_SHIFT)
  194113. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  194114. &(png_ptr->shift));
  194115. #endif
  194116. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  194117. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  194118. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194119. #endif
  194120. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  194121. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  194122. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194123. #endif
  194124. #if defined(PNG_WRITE_BGR_SUPPORTED)
  194125. if (png_ptr->transformations & PNG_BGR)
  194126. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194127. #endif
  194128. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  194129. if (png_ptr->transformations & PNG_INVERT_MONO)
  194130. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194131. #endif
  194132. }
  194133. #if defined(PNG_WRITE_PACK_SUPPORTED)
  194134. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  194135. * row_info bit depth should be 8 (one pixel per byte). The channels
  194136. * should be 1 (this only happens on grayscale and paletted images).
  194137. */
  194138. void /* PRIVATE */
  194139. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  194140. {
  194141. png_debug(1, "in png_do_pack\n");
  194142. if (row_info->bit_depth == 8 &&
  194143. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194144. row != NULL && row_info != NULL &&
  194145. #endif
  194146. row_info->channels == 1)
  194147. {
  194148. switch ((int)bit_depth)
  194149. {
  194150. case 1:
  194151. {
  194152. png_bytep sp, dp;
  194153. int mask, v;
  194154. png_uint_32 i;
  194155. png_uint_32 row_width = row_info->width;
  194156. sp = row;
  194157. dp = row;
  194158. mask = 0x80;
  194159. v = 0;
  194160. for (i = 0; i < row_width; i++)
  194161. {
  194162. if (*sp != 0)
  194163. v |= mask;
  194164. sp++;
  194165. if (mask > 1)
  194166. mask >>= 1;
  194167. else
  194168. {
  194169. mask = 0x80;
  194170. *dp = (png_byte)v;
  194171. dp++;
  194172. v = 0;
  194173. }
  194174. }
  194175. if (mask != 0x80)
  194176. *dp = (png_byte)v;
  194177. break;
  194178. }
  194179. case 2:
  194180. {
  194181. png_bytep sp, dp;
  194182. int shift, v;
  194183. png_uint_32 i;
  194184. png_uint_32 row_width = row_info->width;
  194185. sp = row;
  194186. dp = row;
  194187. shift = 6;
  194188. v = 0;
  194189. for (i = 0; i < row_width; i++)
  194190. {
  194191. png_byte value;
  194192. value = (png_byte)(*sp & 0x03);
  194193. v |= (value << shift);
  194194. if (shift == 0)
  194195. {
  194196. shift = 6;
  194197. *dp = (png_byte)v;
  194198. dp++;
  194199. v = 0;
  194200. }
  194201. else
  194202. shift -= 2;
  194203. sp++;
  194204. }
  194205. if (shift != 6)
  194206. *dp = (png_byte)v;
  194207. break;
  194208. }
  194209. case 4:
  194210. {
  194211. png_bytep sp, dp;
  194212. int shift, v;
  194213. png_uint_32 i;
  194214. png_uint_32 row_width = row_info->width;
  194215. sp = row;
  194216. dp = row;
  194217. shift = 4;
  194218. v = 0;
  194219. for (i = 0; i < row_width; i++)
  194220. {
  194221. png_byte value;
  194222. value = (png_byte)(*sp & 0x0f);
  194223. v |= (value << shift);
  194224. if (shift == 0)
  194225. {
  194226. shift = 4;
  194227. *dp = (png_byte)v;
  194228. dp++;
  194229. v = 0;
  194230. }
  194231. else
  194232. shift -= 4;
  194233. sp++;
  194234. }
  194235. if (shift != 4)
  194236. *dp = (png_byte)v;
  194237. break;
  194238. }
  194239. }
  194240. row_info->bit_depth = (png_byte)bit_depth;
  194241. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  194242. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  194243. row_info->width);
  194244. }
  194245. }
  194246. #endif
  194247. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  194248. /* Shift pixel values to take advantage of whole range. Pass the
  194249. * true number of bits in bit_depth. The row should be packed
  194250. * according to row_info->bit_depth. Thus, if you had a row of
  194251. * bit depth 4, but the pixels only had values from 0 to 7, you
  194252. * would pass 3 as bit_depth, and this routine would translate the
  194253. * data to 0 to 15.
  194254. */
  194255. void /* PRIVATE */
  194256. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  194257. {
  194258. png_debug(1, "in png_do_shift\n");
  194259. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194260. if (row != NULL && row_info != NULL &&
  194261. #else
  194262. if (
  194263. #endif
  194264. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  194265. {
  194266. int shift_start[4], shift_dec[4];
  194267. int channels = 0;
  194268. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  194269. {
  194270. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  194271. shift_dec[channels] = bit_depth->red;
  194272. channels++;
  194273. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  194274. shift_dec[channels] = bit_depth->green;
  194275. channels++;
  194276. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  194277. shift_dec[channels] = bit_depth->blue;
  194278. channels++;
  194279. }
  194280. else
  194281. {
  194282. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  194283. shift_dec[channels] = bit_depth->gray;
  194284. channels++;
  194285. }
  194286. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  194287. {
  194288. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  194289. shift_dec[channels] = bit_depth->alpha;
  194290. channels++;
  194291. }
  194292. /* with low row depths, could only be grayscale, so one channel */
  194293. if (row_info->bit_depth < 8)
  194294. {
  194295. png_bytep bp = row;
  194296. png_uint_32 i;
  194297. png_byte mask;
  194298. png_uint_32 row_bytes = row_info->rowbytes;
  194299. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  194300. mask = 0x55;
  194301. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  194302. mask = 0x11;
  194303. else
  194304. mask = 0xff;
  194305. for (i = 0; i < row_bytes; i++, bp++)
  194306. {
  194307. png_uint_16 v;
  194308. int j;
  194309. v = *bp;
  194310. *bp = 0;
  194311. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  194312. {
  194313. if (j > 0)
  194314. *bp |= (png_byte)((v << j) & 0xff);
  194315. else
  194316. *bp |= (png_byte)((v >> (-j)) & mask);
  194317. }
  194318. }
  194319. }
  194320. else if (row_info->bit_depth == 8)
  194321. {
  194322. png_bytep bp = row;
  194323. png_uint_32 i;
  194324. png_uint_32 istop = channels * row_info->width;
  194325. for (i = 0; i < istop; i++, bp++)
  194326. {
  194327. png_uint_16 v;
  194328. int j;
  194329. int c = (int)(i%channels);
  194330. v = *bp;
  194331. *bp = 0;
  194332. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  194333. {
  194334. if (j > 0)
  194335. *bp |= (png_byte)((v << j) & 0xff);
  194336. else
  194337. *bp |= (png_byte)((v >> (-j)) & 0xff);
  194338. }
  194339. }
  194340. }
  194341. else
  194342. {
  194343. png_bytep bp;
  194344. png_uint_32 i;
  194345. png_uint_32 istop = channels * row_info->width;
  194346. for (bp = row, i = 0; i < istop; i++)
  194347. {
  194348. int c = (int)(i%channels);
  194349. png_uint_16 value, v;
  194350. int j;
  194351. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  194352. value = 0;
  194353. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  194354. {
  194355. if (j > 0)
  194356. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  194357. else
  194358. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  194359. }
  194360. *bp++ = (png_byte)(value >> 8);
  194361. *bp++ = (png_byte)(value & 0xff);
  194362. }
  194363. }
  194364. }
  194365. }
  194366. #endif
  194367. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  194368. void /* PRIVATE */
  194369. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  194370. {
  194371. png_debug(1, "in png_do_write_swap_alpha\n");
  194372. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194373. if (row != NULL && row_info != NULL)
  194374. #endif
  194375. {
  194376. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194377. {
  194378. /* This converts from ARGB to RGBA */
  194379. if (row_info->bit_depth == 8)
  194380. {
  194381. png_bytep sp, dp;
  194382. png_uint_32 i;
  194383. png_uint_32 row_width = row_info->width;
  194384. for (i = 0, sp = dp = row; i < row_width; i++)
  194385. {
  194386. png_byte save = *(sp++);
  194387. *(dp++) = *(sp++);
  194388. *(dp++) = *(sp++);
  194389. *(dp++) = *(sp++);
  194390. *(dp++) = save;
  194391. }
  194392. }
  194393. /* This converts from AARRGGBB to RRGGBBAA */
  194394. else
  194395. {
  194396. png_bytep sp, dp;
  194397. png_uint_32 i;
  194398. png_uint_32 row_width = row_info->width;
  194399. for (i = 0, sp = dp = row; i < row_width; i++)
  194400. {
  194401. png_byte save[2];
  194402. save[0] = *(sp++);
  194403. save[1] = *(sp++);
  194404. *(dp++) = *(sp++);
  194405. *(dp++) = *(sp++);
  194406. *(dp++) = *(sp++);
  194407. *(dp++) = *(sp++);
  194408. *(dp++) = *(sp++);
  194409. *(dp++) = *(sp++);
  194410. *(dp++) = save[0];
  194411. *(dp++) = save[1];
  194412. }
  194413. }
  194414. }
  194415. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  194416. {
  194417. /* This converts from AG to GA */
  194418. if (row_info->bit_depth == 8)
  194419. {
  194420. png_bytep sp, dp;
  194421. png_uint_32 i;
  194422. png_uint_32 row_width = row_info->width;
  194423. for (i = 0, sp = dp = row; i < row_width; i++)
  194424. {
  194425. png_byte save = *(sp++);
  194426. *(dp++) = *(sp++);
  194427. *(dp++) = save;
  194428. }
  194429. }
  194430. /* This converts from AAGG to GGAA */
  194431. else
  194432. {
  194433. png_bytep sp, dp;
  194434. png_uint_32 i;
  194435. png_uint_32 row_width = row_info->width;
  194436. for (i = 0, sp = dp = row; i < row_width; i++)
  194437. {
  194438. png_byte save[2];
  194439. save[0] = *(sp++);
  194440. save[1] = *(sp++);
  194441. *(dp++) = *(sp++);
  194442. *(dp++) = *(sp++);
  194443. *(dp++) = save[0];
  194444. *(dp++) = save[1];
  194445. }
  194446. }
  194447. }
  194448. }
  194449. }
  194450. #endif
  194451. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  194452. void /* PRIVATE */
  194453. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  194454. {
  194455. png_debug(1, "in png_do_write_invert_alpha\n");
  194456. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194457. if (row != NULL && row_info != NULL)
  194458. #endif
  194459. {
  194460. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194461. {
  194462. /* This inverts the alpha channel in RGBA */
  194463. if (row_info->bit_depth == 8)
  194464. {
  194465. png_bytep sp, dp;
  194466. png_uint_32 i;
  194467. png_uint_32 row_width = row_info->width;
  194468. for (i = 0, sp = dp = row; i < row_width; i++)
  194469. {
  194470. /* does nothing
  194471. *(dp++) = *(sp++);
  194472. *(dp++) = *(sp++);
  194473. *(dp++) = *(sp++);
  194474. */
  194475. sp+=3; dp = sp;
  194476. *(dp++) = (png_byte)(255 - *(sp++));
  194477. }
  194478. }
  194479. /* This inverts the alpha channel in RRGGBBAA */
  194480. else
  194481. {
  194482. png_bytep sp, dp;
  194483. png_uint_32 i;
  194484. png_uint_32 row_width = row_info->width;
  194485. for (i = 0, sp = dp = row; i < row_width; i++)
  194486. {
  194487. /* does nothing
  194488. *(dp++) = *(sp++);
  194489. *(dp++) = *(sp++);
  194490. *(dp++) = *(sp++);
  194491. *(dp++) = *(sp++);
  194492. *(dp++) = *(sp++);
  194493. *(dp++) = *(sp++);
  194494. */
  194495. sp+=6; dp = sp;
  194496. *(dp++) = (png_byte)(255 - *(sp++));
  194497. *(dp++) = (png_byte)(255 - *(sp++));
  194498. }
  194499. }
  194500. }
  194501. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  194502. {
  194503. /* This inverts the alpha channel in GA */
  194504. if (row_info->bit_depth == 8)
  194505. {
  194506. png_bytep sp, dp;
  194507. png_uint_32 i;
  194508. png_uint_32 row_width = row_info->width;
  194509. for (i = 0, sp = dp = row; i < row_width; i++)
  194510. {
  194511. *(dp++) = *(sp++);
  194512. *(dp++) = (png_byte)(255 - *(sp++));
  194513. }
  194514. }
  194515. /* This inverts the alpha channel in GGAA */
  194516. else
  194517. {
  194518. png_bytep sp, dp;
  194519. png_uint_32 i;
  194520. png_uint_32 row_width = row_info->width;
  194521. for (i = 0, sp = dp = row; i < row_width; i++)
  194522. {
  194523. /* does nothing
  194524. *(dp++) = *(sp++);
  194525. *(dp++) = *(sp++);
  194526. */
  194527. sp+=2; dp = sp;
  194528. *(dp++) = (png_byte)(255 - *(sp++));
  194529. *(dp++) = (png_byte)(255 - *(sp++));
  194530. }
  194531. }
  194532. }
  194533. }
  194534. }
  194535. #endif
  194536. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194537. /* undoes intrapixel differencing */
  194538. void /* PRIVATE */
  194539. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  194540. {
  194541. png_debug(1, "in png_do_write_intrapixel\n");
  194542. if (
  194543. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194544. row != NULL && row_info != NULL &&
  194545. #endif
  194546. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  194547. {
  194548. int bytes_per_pixel;
  194549. png_uint_32 row_width = row_info->width;
  194550. if (row_info->bit_depth == 8)
  194551. {
  194552. png_bytep rp;
  194553. png_uint_32 i;
  194554. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194555. bytes_per_pixel = 3;
  194556. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194557. bytes_per_pixel = 4;
  194558. else
  194559. return;
  194560. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194561. {
  194562. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  194563. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  194564. }
  194565. }
  194566. else if (row_info->bit_depth == 16)
  194567. {
  194568. png_bytep rp;
  194569. png_uint_32 i;
  194570. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194571. bytes_per_pixel = 6;
  194572. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194573. bytes_per_pixel = 8;
  194574. else
  194575. return;
  194576. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194577. {
  194578. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  194579. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  194580. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  194581. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  194582. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  194583. *(rp ) = (png_byte)((red >> 8) & 0xff);
  194584. *(rp+1) = (png_byte)(red & 0xff);
  194585. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  194586. *(rp+5) = (png_byte)(blue & 0xff);
  194587. }
  194588. }
  194589. }
  194590. }
  194591. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  194592. #endif /* PNG_WRITE_SUPPORTED */
  194593. /********* End of inlined file: pngwtran.c *********/
  194594. /********* Start of inlined file: pngwutil.c *********/
  194595. /* pngwutil.c - utilities to write a PNG file
  194596. *
  194597. * Last changed in libpng 1.2.20 Septhember 3, 2007
  194598. * For conditions of distribution and use, see copyright notice in png.h
  194599. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194600. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194601. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194602. */
  194603. #define PNG_INTERNAL
  194604. #ifdef PNG_WRITE_SUPPORTED
  194605. /* Place a 32-bit number into a buffer in PNG byte order. We work
  194606. * with unsigned numbers for convenience, although one supported
  194607. * ancillary chunk uses signed (two's complement) numbers.
  194608. */
  194609. void PNGAPI
  194610. png_save_uint_32(png_bytep buf, png_uint_32 i)
  194611. {
  194612. buf[0] = (png_byte)((i >> 24) & 0xff);
  194613. buf[1] = (png_byte)((i >> 16) & 0xff);
  194614. buf[2] = (png_byte)((i >> 8) & 0xff);
  194615. buf[3] = (png_byte)(i & 0xff);
  194616. }
  194617. /* The png_save_int_32 function assumes integers are stored in two's
  194618. * complement format. If this isn't the case, then this routine needs to
  194619. * be modified to write data in two's complement format.
  194620. */
  194621. void PNGAPI
  194622. png_save_int_32(png_bytep buf, png_int_32 i)
  194623. {
  194624. buf[0] = (png_byte)((i >> 24) & 0xff);
  194625. buf[1] = (png_byte)((i >> 16) & 0xff);
  194626. buf[2] = (png_byte)((i >> 8) & 0xff);
  194627. buf[3] = (png_byte)(i & 0xff);
  194628. }
  194629. /* Place a 16-bit number into a buffer in PNG byte order.
  194630. * The parameter is declared unsigned int, not png_uint_16,
  194631. * just to avoid potential problems on pre-ANSI C compilers.
  194632. */
  194633. void PNGAPI
  194634. png_save_uint_16(png_bytep buf, unsigned int i)
  194635. {
  194636. buf[0] = (png_byte)((i >> 8) & 0xff);
  194637. buf[1] = (png_byte)(i & 0xff);
  194638. }
  194639. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  194640. * representing the chunk name. The array must be at least 4 bytes in
  194641. * length, and does not need to be null terminated. To be safe, pass the
  194642. * pre-defined chunk names here, and if you need a new one, define it
  194643. * where the others are defined. The length is the length of the data.
  194644. * All the data must be present. If that is not possible, use the
  194645. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  194646. * functions instead.
  194647. */
  194648. void PNGAPI
  194649. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  194650. png_bytep data, png_size_t length)
  194651. {
  194652. if(png_ptr == NULL) return;
  194653. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  194654. png_write_chunk_data(png_ptr, data, length);
  194655. png_write_chunk_end(png_ptr);
  194656. }
  194657. /* Write the start of a PNG chunk. The type is the chunk type.
  194658. * The total_length is the sum of the lengths of all the data you will be
  194659. * passing in png_write_chunk_data().
  194660. */
  194661. void PNGAPI
  194662. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  194663. png_uint_32 length)
  194664. {
  194665. png_byte buf[4];
  194666. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  194667. if(png_ptr == NULL) return;
  194668. /* write the length */
  194669. png_save_uint_32(buf, length);
  194670. png_write_data(png_ptr, buf, (png_size_t)4);
  194671. /* write the chunk name */
  194672. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  194673. /* reset the crc and run it over the chunk name */
  194674. png_reset_crc(png_ptr);
  194675. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  194676. }
  194677. /* Write the data of a PNG chunk started with png_write_chunk_start().
  194678. * Note that multiple calls to this function are allowed, and that the
  194679. * sum of the lengths from these calls *must* add up to the total_length
  194680. * given to png_write_chunk_start().
  194681. */
  194682. void PNGAPI
  194683. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  194684. {
  194685. /* write the data, and run the CRC over it */
  194686. if(png_ptr == NULL) return;
  194687. if (data != NULL && length > 0)
  194688. {
  194689. png_calculate_crc(png_ptr, data, length);
  194690. png_write_data(png_ptr, data, length);
  194691. }
  194692. }
  194693. /* Finish a chunk started with png_write_chunk_start(). */
  194694. void PNGAPI
  194695. png_write_chunk_end(png_structp png_ptr)
  194696. {
  194697. png_byte buf[4];
  194698. if(png_ptr == NULL) return;
  194699. /* write the crc */
  194700. png_save_uint_32(buf, png_ptr->crc);
  194701. png_write_data(png_ptr, buf, (png_size_t)4);
  194702. }
  194703. /* Simple function to write the signature. If we have already written
  194704. * the magic bytes of the signature, or more likely, the PNG stream is
  194705. * being embedded into another stream and doesn't need its own signature,
  194706. * we should call png_set_sig_bytes() to tell libpng how many of the
  194707. * bytes have already been written.
  194708. */
  194709. void /* PRIVATE */
  194710. png_write_sig(png_structp png_ptr)
  194711. {
  194712. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  194713. /* write the rest of the 8 byte signature */
  194714. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  194715. (png_size_t)8 - png_ptr->sig_bytes);
  194716. if(png_ptr->sig_bytes < 3)
  194717. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  194718. }
  194719. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  194720. /*
  194721. * This pair of functions encapsulates the operation of (a) compressing a
  194722. * text string, and (b) issuing it later as a series of chunk data writes.
  194723. * The compression_state structure is shared context for these functions
  194724. * set up by the caller in order to make the whole mess thread-safe.
  194725. */
  194726. typedef struct
  194727. {
  194728. char *input; /* the uncompressed input data */
  194729. int input_len; /* its length */
  194730. int num_output_ptr; /* number of output pointers used */
  194731. int max_output_ptr; /* size of output_ptr */
  194732. png_charpp output_ptr; /* array of pointers to output */
  194733. } compression_state;
  194734. /* compress given text into storage in the png_ptr structure */
  194735. static int /* PRIVATE */
  194736. png_text_compress(png_structp png_ptr,
  194737. png_charp text, png_size_t text_len, int compression,
  194738. compression_state *comp)
  194739. {
  194740. int ret;
  194741. comp->num_output_ptr = 0;
  194742. comp->max_output_ptr = 0;
  194743. comp->output_ptr = NULL;
  194744. comp->input = NULL;
  194745. comp->input_len = 0;
  194746. /* we may just want to pass the text right through */
  194747. if (compression == PNG_TEXT_COMPRESSION_NONE)
  194748. {
  194749. comp->input = text;
  194750. comp->input_len = text_len;
  194751. return((int)text_len);
  194752. }
  194753. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  194754. {
  194755. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194756. char msg[50];
  194757. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  194758. png_warning(png_ptr, msg);
  194759. #else
  194760. png_warning(png_ptr, "Unknown compression type");
  194761. #endif
  194762. }
  194763. /* We can't write the chunk until we find out how much data we have,
  194764. * which means we need to run the compressor first and save the
  194765. * output. This shouldn't be a problem, as the vast majority of
  194766. * comments should be reasonable, but we will set up an array of
  194767. * malloc'd pointers to be sure.
  194768. *
  194769. * If we knew the application was well behaved, we could simplify this
  194770. * greatly by assuming we can always malloc an output buffer large
  194771. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  194772. * and malloc this directly. The only time this would be a bad idea is
  194773. * if we can't malloc more than 64K and we have 64K of random input
  194774. * data, or if the input string is incredibly large (although this
  194775. * wouldn't cause a failure, just a slowdown due to swapping).
  194776. */
  194777. /* set up the compression buffers */
  194778. png_ptr->zstream.avail_in = (uInt)text_len;
  194779. png_ptr->zstream.next_in = (Bytef *)text;
  194780. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194781. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  194782. /* this is the same compression loop as in png_write_row() */
  194783. do
  194784. {
  194785. /* compress the data */
  194786. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  194787. if (ret != Z_OK)
  194788. {
  194789. /* error */
  194790. if (png_ptr->zstream.msg != NULL)
  194791. png_error(png_ptr, png_ptr->zstream.msg);
  194792. else
  194793. png_error(png_ptr, "zlib error");
  194794. }
  194795. /* check to see if we need more room */
  194796. if (!(png_ptr->zstream.avail_out))
  194797. {
  194798. /* make sure the output array has room */
  194799. if (comp->num_output_ptr >= comp->max_output_ptr)
  194800. {
  194801. int old_max;
  194802. old_max = comp->max_output_ptr;
  194803. comp->max_output_ptr = comp->num_output_ptr + 4;
  194804. if (comp->output_ptr != NULL)
  194805. {
  194806. png_charpp old_ptr;
  194807. old_ptr = comp->output_ptr;
  194808. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194809. (png_uint_32)(comp->max_output_ptr *
  194810. png_sizeof (png_charpp)));
  194811. png_memcpy(comp->output_ptr, old_ptr, old_max
  194812. * png_sizeof (png_charp));
  194813. png_free(png_ptr, old_ptr);
  194814. }
  194815. else
  194816. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194817. (png_uint_32)(comp->max_output_ptr *
  194818. png_sizeof (png_charp)));
  194819. }
  194820. /* save the data */
  194821. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  194822. (png_uint_32)png_ptr->zbuf_size);
  194823. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  194824. png_ptr->zbuf_size);
  194825. comp->num_output_ptr++;
  194826. /* and reset the buffer */
  194827. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194828. png_ptr->zstream.next_out = png_ptr->zbuf;
  194829. }
  194830. /* continue until we don't have any more to compress */
  194831. } while (png_ptr->zstream.avail_in);
  194832. /* finish the compression */
  194833. do
  194834. {
  194835. /* tell zlib we are finished */
  194836. ret = deflate(&png_ptr->zstream, Z_FINISH);
  194837. if (ret == Z_OK)
  194838. {
  194839. /* check to see if we need more room */
  194840. if (!(png_ptr->zstream.avail_out))
  194841. {
  194842. /* check to make sure our output array has room */
  194843. if (comp->num_output_ptr >= comp->max_output_ptr)
  194844. {
  194845. int old_max;
  194846. old_max = comp->max_output_ptr;
  194847. comp->max_output_ptr = comp->num_output_ptr + 4;
  194848. if (comp->output_ptr != NULL)
  194849. {
  194850. png_charpp old_ptr;
  194851. old_ptr = comp->output_ptr;
  194852. /* This could be optimized to realloc() */
  194853. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194854. (png_uint_32)(comp->max_output_ptr *
  194855. png_sizeof (png_charpp)));
  194856. png_memcpy(comp->output_ptr, old_ptr,
  194857. old_max * png_sizeof (png_charp));
  194858. png_free(png_ptr, old_ptr);
  194859. }
  194860. else
  194861. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194862. (png_uint_32)(comp->max_output_ptr *
  194863. png_sizeof (png_charp)));
  194864. }
  194865. /* save off the data */
  194866. comp->output_ptr[comp->num_output_ptr] =
  194867. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  194868. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  194869. png_ptr->zbuf_size);
  194870. comp->num_output_ptr++;
  194871. /* and reset the buffer pointers */
  194872. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194873. png_ptr->zstream.next_out = png_ptr->zbuf;
  194874. }
  194875. }
  194876. else if (ret != Z_STREAM_END)
  194877. {
  194878. /* we got an error */
  194879. if (png_ptr->zstream.msg != NULL)
  194880. png_error(png_ptr, png_ptr->zstream.msg);
  194881. else
  194882. png_error(png_ptr, "zlib error");
  194883. }
  194884. } while (ret != Z_STREAM_END);
  194885. /* text length is number of buffers plus last buffer */
  194886. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  194887. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  194888. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  194889. return((int)text_len);
  194890. }
  194891. /* ship the compressed text out via chunk writes */
  194892. static void /* PRIVATE */
  194893. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  194894. {
  194895. int i;
  194896. /* handle the no-compression case */
  194897. if (comp->input)
  194898. {
  194899. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  194900. (png_size_t)comp->input_len);
  194901. return;
  194902. }
  194903. /* write saved output buffers, if any */
  194904. for (i = 0; i < comp->num_output_ptr; i++)
  194905. {
  194906. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  194907. png_ptr->zbuf_size);
  194908. png_free(png_ptr, comp->output_ptr[i]);
  194909. comp->output_ptr[i]=NULL;
  194910. }
  194911. if (comp->max_output_ptr != 0)
  194912. png_free(png_ptr, comp->output_ptr);
  194913. comp->output_ptr=NULL;
  194914. /* write anything left in zbuf */
  194915. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  194916. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  194917. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  194918. /* reset zlib for another zTXt/iTXt or image data */
  194919. deflateReset(&png_ptr->zstream);
  194920. png_ptr->zstream.data_type = Z_BINARY;
  194921. }
  194922. #endif
  194923. /* Write the IHDR chunk, and update the png_struct with the necessary
  194924. * information. Note that the rest of this code depends upon this
  194925. * information being correct.
  194926. */
  194927. void /* PRIVATE */
  194928. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  194929. int bit_depth, int color_type, int compression_type, int filter_type,
  194930. int interlace_type)
  194931. {
  194932. #ifdef PNG_USE_LOCAL_ARRAYS
  194933. PNG_IHDR;
  194934. #endif
  194935. png_byte buf[13]; /* buffer to store the IHDR info */
  194936. png_debug(1, "in png_write_IHDR\n");
  194937. /* Check that we have valid input data from the application info */
  194938. switch (color_type)
  194939. {
  194940. case PNG_COLOR_TYPE_GRAY:
  194941. switch (bit_depth)
  194942. {
  194943. case 1:
  194944. case 2:
  194945. case 4:
  194946. case 8:
  194947. case 16: png_ptr->channels = 1; break;
  194948. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  194949. }
  194950. break;
  194951. case PNG_COLOR_TYPE_RGB:
  194952. if (bit_depth != 8 && bit_depth != 16)
  194953. png_error(png_ptr, "Invalid bit depth for RGB image");
  194954. png_ptr->channels = 3;
  194955. break;
  194956. case PNG_COLOR_TYPE_PALETTE:
  194957. switch (bit_depth)
  194958. {
  194959. case 1:
  194960. case 2:
  194961. case 4:
  194962. case 8: png_ptr->channels = 1; break;
  194963. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  194964. }
  194965. break;
  194966. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194967. if (bit_depth != 8 && bit_depth != 16)
  194968. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  194969. png_ptr->channels = 2;
  194970. break;
  194971. case PNG_COLOR_TYPE_RGB_ALPHA:
  194972. if (bit_depth != 8 && bit_depth != 16)
  194973. png_error(png_ptr, "Invalid bit depth for RGBA image");
  194974. png_ptr->channels = 4;
  194975. break;
  194976. default:
  194977. png_error(png_ptr, "Invalid image color type specified");
  194978. }
  194979. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  194980. {
  194981. png_warning(png_ptr, "Invalid compression type specified");
  194982. compression_type = PNG_COMPRESSION_TYPE_BASE;
  194983. }
  194984. /* Write filter_method 64 (intrapixel differencing) only if
  194985. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  194986. * 2. Libpng did not write a PNG signature (this filter_method is only
  194987. * used in PNG datastreams that are embedded in MNG datastreams) and
  194988. * 3. The application called png_permit_mng_features with a mask that
  194989. * included PNG_FLAG_MNG_FILTER_64 and
  194990. * 4. The filter_method is 64 and
  194991. * 5. The color_type is RGB or RGBA
  194992. */
  194993. if (
  194994. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194995. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  194996. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  194997. (color_type == PNG_COLOR_TYPE_RGB ||
  194998. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  194999. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  195000. #endif
  195001. filter_type != PNG_FILTER_TYPE_BASE)
  195002. {
  195003. png_warning(png_ptr, "Invalid filter type specified");
  195004. filter_type = PNG_FILTER_TYPE_BASE;
  195005. }
  195006. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  195007. if (interlace_type != PNG_INTERLACE_NONE &&
  195008. interlace_type != PNG_INTERLACE_ADAM7)
  195009. {
  195010. png_warning(png_ptr, "Invalid interlace type specified");
  195011. interlace_type = PNG_INTERLACE_ADAM7;
  195012. }
  195013. #else
  195014. interlace_type=PNG_INTERLACE_NONE;
  195015. #endif
  195016. /* save off the relevent information */
  195017. png_ptr->bit_depth = (png_byte)bit_depth;
  195018. png_ptr->color_type = (png_byte)color_type;
  195019. png_ptr->interlaced = (png_byte)interlace_type;
  195020. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195021. png_ptr->filter_type = (png_byte)filter_type;
  195022. #endif
  195023. png_ptr->compression_type = (png_byte)compression_type;
  195024. png_ptr->width = width;
  195025. png_ptr->height = height;
  195026. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  195027. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  195028. /* set the usr info, so any transformations can modify it */
  195029. png_ptr->usr_width = png_ptr->width;
  195030. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  195031. png_ptr->usr_channels = png_ptr->channels;
  195032. /* pack the header information into the buffer */
  195033. png_save_uint_32(buf, width);
  195034. png_save_uint_32(buf + 4, height);
  195035. buf[8] = (png_byte)bit_depth;
  195036. buf[9] = (png_byte)color_type;
  195037. buf[10] = (png_byte)compression_type;
  195038. buf[11] = (png_byte)filter_type;
  195039. buf[12] = (png_byte)interlace_type;
  195040. /* write the chunk */
  195041. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  195042. /* initialize zlib with PNG info */
  195043. png_ptr->zstream.zalloc = png_zalloc;
  195044. png_ptr->zstream.zfree = png_zfree;
  195045. png_ptr->zstream.opaque = (voidpf)png_ptr;
  195046. if (!(png_ptr->do_filter))
  195047. {
  195048. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  195049. png_ptr->bit_depth < 8)
  195050. png_ptr->do_filter = PNG_FILTER_NONE;
  195051. else
  195052. png_ptr->do_filter = PNG_ALL_FILTERS;
  195053. }
  195054. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  195055. {
  195056. if (png_ptr->do_filter != PNG_FILTER_NONE)
  195057. png_ptr->zlib_strategy = Z_FILTERED;
  195058. else
  195059. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  195060. }
  195061. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  195062. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  195063. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  195064. png_ptr->zlib_mem_level = 8;
  195065. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  195066. png_ptr->zlib_window_bits = 15;
  195067. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  195068. png_ptr->zlib_method = 8;
  195069. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  195070. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  195071. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  195072. png_error(png_ptr, "zlib failed to initialize compressor");
  195073. png_ptr->zstream.next_out = png_ptr->zbuf;
  195074. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195075. /* libpng is not interested in zstream.data_type */
  195076. /* set it to a predefined value, to avoid its evaluation inside zlib */
  195077. png_ptr->zstream.data_type = Z_BINARY;
  195078. png_ptr->mode = PNG_HAVE_IHDR;
  195079. }
  195080. /* write the palette. We are careful not to trust png_color to be in the
  195081. * correct order for PNG, so people can redefine it to any convenient
  195082. * structure.
  195083. */
  195084. void /* PRIVATE */
  195085. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  195086. {
  195087. #ifdef PNG_USE_LOCAL_ARRAYS
  195088. PNG_PLTE;
  195089. #endif
  195090. png_uint_32 i;
  195091. png_colorp pal_ptr;
  195092. png_byte buf[3];
  195093. png_debug(1, "in png_write_PLTE\n");
  195094. if ((
  195095. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195096. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  195097. #endif
  195098. num_pal == 0) || num_pal > 256)
  195099. {
  195100. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195101. {
  195102. png_error(png_ptr, "Invalid number of colors in palette");
  195103. }
  195104. else
  195105. {
  195106. png_warning(png_ptr, "Invalid number of colors in palette");
  195107. return;
  195108. }
  195109. }
  195110. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  195111. {
  195112. png_warning(png_ptr,
  195113. "Ignoring request to write a PLTE chunk in grayscale PNG");
  195114. return;
  195115. }
  195116. png_ptr->num_palette = (png_uint_16)num_pal;
  195117. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  195118. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  195119. #ifndef PNG_NO_POINTER_INDEXING
  195120. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  195121. {
  195122. buf[0] = pal_ptr->red;
  195123. buf[1] = pal_ptr->green;
  195124. buf[2] = pal_ptr->blue;
  195125. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  195126. }
  195127. #else
  195128. /* This is a little slower but some buggy compilers need to do this instead */
  195129. pal_ptr=palette;
  195130. for (i = 0; i < num_pal; i++)
  195131. {
  195132. buf[0] = pal_ptr[i].red;
  195133. buf[1] = pal_ptr[i].green;
  195134. buf[2] = pal_ptr[i].blue;
  195135. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  195136. }
  195137. #endif
  195138. png_write_chunk_end(png_ptr);
  195139. png_ptr->mode |= PNG_HAVE_PLTE;
  195140. }
  195141. /* write an IDAT chunk */
  195142. void /* PRIVATE */
  195143. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  195144. {
  195145. #ifdef PNG_USE_LOCAL_ARRAYS
  195146. PNG_IDAT;
  195147. #endif
  195148. png_debug(1, "in png_write_IDAT\n");
  195149. /* Optimize the CMF field in the zlib stream. */
  195150. /* This hack of the zlib stream is compliant to the stream specification. */
  195151. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  195152. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  195153. {
  195154. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  195155. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  195156. {
  195157. /* Avoid memory underflows and multiplication overflows. */
  195158. /* The conditions below are practically always satisfied;
  195159. however, they still must be checked. */
  195160. if (length >= 2 &&
  195161. png_ptr->height < 16384 && png_ptr->width < 16384)
  195162. {
  195163. png_uint_32 uncompressed_idat_size = png_ptr->height *
  195164. ((png_ptr->width *
  195165. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  195166. unsigned int z_cinfo = z_cmf >> 4;
  195167. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  195168. while (uncompressed_idat_size <= half_z_window_size &&
  195169. half_z_window_size >= 256)
  195170. {
  195171. z_cinfo--;
  195172. half_z_window_size >>= 1;
  195173. }
  195174. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  195175. if (data[0] != (png_byte)z_cmf)
  195176. {
  195177. data[0] = (png_byte)z_cmf;
  195178. data[1] &= 0xe0;
  195179. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  195180. }
  195181. }
  195182. }
  195183. else
  195184. png_error(png_ptr,
  195185. "Invalid zlib compression method or flags in IDAT");
  195186. }
  195187. png_write_chunk(png_ptr, png_IDAT, data, length);
  195188. png_ptr->mode |= PNG_HAVE_IDAT;
  195189. }
  195190. /* write an IEND chunk */
  195191. void /* PRIVATE */
  195192. png_write_IEND(png_structp png_ptr)
  195193. {
  195194. #ifdef PNG_USE_LOCAL_ARRAYS
  195195. PNG_IEND;
  195196. #endif
  195197. png_debug(1, "in png_write_IEND\n");
  195198. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  195199. (png_size_t)0);
  195200. png_ptr->mode |= PNG_HAVE_IEND;
  195201. }
  195202. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  195203. /* write a gAMA chunk */
  195204. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195205. void /* PRIVATE */
  195206. png_write_gAMA(png_structp png_ptr, double file_gamma)
  195207. {
  195208. #ifdef PNG_USE_LOCAL_ARRAYS
  195209. PNG_gAMA;
  195210. #endif
  195211. png_uint_32 igamma;
  195212. png_byte buf[4];
  195213. png_debug(1, "in png_write_gAMA\n");
  195214. /* file_gamma is saved in 1/100,000ths */
  195215. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  195216. png_save_uint_32(buf, igamma);
  195217. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  195218. }
  195219. #endif
  195220. #ifdef PNG_FIXED_POINT_SUPPORTED
  195221. void /* PRIVATE */
  195222. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  195223. {
  195224. #ifdef PNG_USE_LOCAL_ARRAYS
  195225. PNG_gAMA;
  195226. #endif
  195227. png_byte buf[4];
  195228. png_debug(1, "in png_write_gAMA\n");
  195229. /* file_gamma is saved in 1/100,000ths */
  195230. png_save_uint_32(buf, (png_uint_32)file_gamma);
  195231. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  195232. }
  195233. #endif
  195234. #endif
  195235. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  195236. /* write a sRGB chunk */
  195237. void /* PRIVATE */
  195238. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  195239. {
  195240. #ifdef PNG_USE_LOCAL_ARRAYS
  195241. PNG_sRGB;
  195242. #endif
  195243. png_byte buf[1];
  195244. png_debug(1, "in png_write_sRGB\n");
  195245. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  195246. png_warning(png_ptr,
  195247. "Invalid sRGB rendering intent specified");
  195248. buf[0]=(png_byte)srgb_intent;
  195249. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  195250. }
  195251. #endif
  195252. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  195253. /* write an iCCP chunk */
  195254. void /* PRIVATE */
  195255. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  195256. png_charp profile, int profile_len)
  195257. {
  195258. #ifdef PNG_USE_LOCAL_ARRAYS
  195259. PNG_iCCP;
  195260. #endif
  195261. png_size_t name_len;
  195262. png_charp new_name;
  195263. compression_state comp;
  195264. int embedded_profile_len = 0;
  195265. png_debug(1, "in png_write_iCCP\n");
  195266. comp.num_output_ptr = 0;
  195267. comp.max_output_ptr = 0;
  195268. comp.output_ptr = NULL;
  195269. comp.input = NULL;
  195270. comp.input_len = 0;
  195271. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  195272. &new_name)) == 0)
  195273. {
  195274. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  195275. return;
  195276. }
  195277. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  195278. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  195279. if (profile == NULL)
  195280. profile_len = 0;
  195281. if (profile_len > 3)
  195282. embedded_profile_len =
  195283. ((*( (png_bytep)profile ))<<24) |
  195284. ((*( (png_bytep)profile+1))<<16) |
  195285. ((*( (png_bytep)profile+2))<< 8) |
  195286. ((*( (png_bytep)profile+3)) );
  195287. if (profile_len < embedded_profile_len)
  195288. {
  195289. png_warning(png_ptr,
  195290. "Embedded profile length too large in iCCP chunk");
  195291. return;
  195292. }
  195293. if (profile_len > embedded_profile_len)
  195294. {
  195295. png_warning(png_ptr,
  195296. "Truncating profile to actual length in iCCP chunk");
  195297. profile_len = embedded_profile_len;
  195298. }
  195299. if (profile_len)
  195300. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  195301. PNG_COMPRESSION_TYPE_BASE, &comp);
  195302. /* make sure we include the NULL after the name and the compression type */
  195303. png_write_chunk_start(png_ptr, png_iCCP,
  195304. (png_uint_32)name_len+profile_len+2);
  195305. new_name[name_len+1]=0x00;
  195306. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  195307. if (profile_len)
  195308. png_write_compressed_data_out(png_ptr, &comp);
  195309. png_write_chunk_end(png_ptr);
  195310. png_free(png_ptr, new_name);
  195311. }
  195312. #endif
  195313. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  195314. /* write a sPLT chunk */
  195315. void /* PRIVATE */
  195316. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  195317. {
  195318. #ifdef PNG_USE_LOCAL_ARRAYS
  195319. PNG_sPLT;
  195320. #endif
  195321. png_size_t name_len;
  195322. png_charp new_name;
  195323. png_byte entrybuf[10];
  195324. int entry_size = (spalette->depth == 8 ? 6 : 10);
  195325. int palette_size = entry_size * spalette->nentries;
  195326. png_sPLT_entryp ep;
  195327. #ifdef PNG_NO_POINTER_INDEXING
  195328. int i;
  195329. #endif
  195330. png_debug(1, "in png_write_sPLT\n");
  195331. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  195332. spalette->name, &new_name))==0)
  195333. {
  195334. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  195335. return;
  195336. }
  195337. /* make sure we include the NULL after the name */
  195338. png_write_chunk_start(png_ptr, png_sPLT,
  195339. (png_uint_32)(name_len + 2 + palette_size));
  195340. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  195341. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  195342. /* loop through each palette entry, writing appropriately */
  195343. #ifndef PNG_NO_POINTER_INDEXING
  195344. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  195345. {
  195346. if (spalette->depth == 8)
  195347. {
  195348. entrybuf[0] = (png_byte)ep->red;
  195349. entrybuf[1] = (png_byte)ep->green;
  195350. entrybuf[2] = (png_byte)ep->blue;
  195351. entrybuf[3] = (png_byte)ep->alpha;
  195352. png_save_uint_16(entrybuf + 4, ep->frequency);
  195353. }
  195354. else
  195355. {
  195356. png_save_uint_16(entrybuf + 0, ep->red);
  195357. png_save_uint_16(entrybuf + 2, ep->green);
  195358. png_save_uint_16(entrybuf + 4, ep->blue);
  195359. png_save_uint_16(entrybuf + 6, ep->alpha);
  195360. png_save_uint_16(entrybuf + 8, ep->frequency);
  195361. }
  195362. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  195363. }
  195364. #else
  195365. ep=spalette->entries;
  195366. for (i=0; i>spalette->nentries; i++)
  195367. {
  195368. if (spalette->depth == 8)
  195369. {
  195370. entrybuf[0] = (png_byte)ep[i].red;
  195371. entrybuf[1] = (png_byte)ep[i].green;
  195372. entrybuf[2] = (png_byte)ep[i].blue;
  195373. entrybuf[3] = (png_byte)ep[i].alpha;
  195374. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  195375. }
  195376. else
  195377. {
  195378. png_save_uint_16(entrybuf + 0, ep[i].red);
  195379. png_save_uint_16(entrybuf + 2, ep[i].green);
  195380. png_save_uint_16(entrybuf + 4, ep[i].blue);
  195381. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  195382. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  195383. }
  195384. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  195385. }
  195386. #endif
  195387. png_write_chunk_end(png_ptr);
  195388. png_free(png_ptr, new_name);
  195389. }
  195390. #endif
  195391. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  195392. /* write the sBIT chunk */
  195393. void /* PRIVATE */
  195394. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  195395. {
  195396. #ifdef PNG_USE_LOCAL_ARRAYS
  195397. PNG_sBIT;
  195398. #endif
  195399. png_byte buf[4];
  195400. png_size_t size;
  195401. png_debug(1, "in png_write_sBIT\n");
  195402. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  195403. if (color_type & PNG_COLOR_MASK_COLOR)
  195404. {
  195405. png_byte maxbits;
  195406. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  195407. png_ptr->usr_bit_depth);
  195408. if (sbit->red == 0 || sbit->red > maxbits ||
  195409. sbit->green == 0 || sbit->green > maxbits ||
  195410. sbit->blue == 0 || sbit->blue > maxbits)
  195411. {
  195412. png_warning(png_ptr, "Invalid sBIT depth specified");
  195413. return;
  195414. }
  195415. buf[0] = sbit->red;
  195416. buf[1] = sbit->green;
  195417. buf[2] = sbit->blue;
  195418. size = 3;
  195419. }
  195420. else
  195421. {
  195422. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  195423. {
  195424. png_warning(png_ptr, "Invalid sBIT depth specified");
  195425. return;
  195426. }
  195427. buf[0] = sbit->gray;
  195428. size = 1;
  195429. }
  195430. if (color_type & PNG_COLOR_MASK_ALPHA)
  195431. {
  195432. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  195433. {
  195434. png_warning(png_ptr, "Invalid sBIT depth specified");
  195435. return;
  195436. }
  195437. buf[size++] = sbit->alpha;
  195438. }
  195439. png_write_chunk(png_ptr, png_sBIT, buf, size);
  195440. }
  195441. #endif
  195442. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  195443. /* write the cHRM chunk */
  195444. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195445. void /* PRIVATE */
  195446. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  195447. double red_x, double red_y, double green_x, double green_y,
  195448. double blue_x, double blue_y)
  195449. {
  195450. #ifdef PNG_USE_LOCAL_ARRAYS
  195451. PNG_cHRM;
  195452. #endif
  195453. png_byte buf[32];
  195454. png_uint_32 itemp;
  195455. png_debug(1, "in png_write_cHRM\n");
  195456. /* each value is saved in 1/100,000ths */
  195457. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  195458. white_x + white_y > 1.0)
  195459. {
  195460. png_warning(png_ptr, "Invalid cHRM white point specified");
  195461. #if !defined(PNG_NO_CONSOLE_IO)
  195462. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  195463. #endif
  195464. return;
  195465. }
  195466. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  195467. png_save_uint_32(buf, itemp);
  195468. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  195469. png_save_uint_32(buf + 4, itemp);
  195470. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  195471. {
  195472. png_warning(png_ptr, "Invalid cHRM red point specified");
  195473. return;
  195474. }
  195475. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  195476. png_save_uint_32(buf + 8, itemp);
  195477. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  195478. png_save_uint_32(buf + 12, itemp);
  195479. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  195480. {
  195481. png_warning(png_ptr, "Invalid cHRM green point specified");
  195482. return;
  195483. }
  195484. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  195485. png_save_uint_32(buf + 16, itemp);
  195486. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  195487. png_save_uint_32(buf + 20, itemp);
  195488. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  195489. {
  195490. png_warning(png_ptr, "Invalid cHRM blue point specified");
  195491. return;
  195492. }
  195493. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  195494. png_save_uint_32(buf + 24, itemp);
  195495. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  195496. png_save_uint_32(buf + 28, itemp);
  195497. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  195498. }
  195499. #endif
  195500. #ifdef PNG_FIXED_POINT_SUPPORTED
  195501. void /* PRIVATE */
  195502. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  195503. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  195504. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  195505. png_fixed_point blue_y)
  195506. {
  195507. #ifdef PNG_USE_LOCAL_ARRAYS
  195508. PNG_cHRM;
  195509. #endif
  195510. png_byte buf[32];
  195511. png_debug(1, "in png_write_cHRM\n");
  195512. /* each value is saved in 1/100,000ths */
  195513. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  195514. {
  195515. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  195516. #if !defined(PNG_NO_CONSOLE_IO)
  195517. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  195518. #endif
  195519. return;
  195520. }
  195521. png_save_uint_32(buf, (png_uint_32)white_x);
  195522. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  195523. if (red_x + red_y > 100000L)
  195524. {
  195525. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  195526. return;
  195527. }
  195528. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  195529. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  195530. if (green_x + green_y > 100000L)
  195531. {
  195532. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  195533. return;
  195534. }
  195535. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  195536. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  195537. if (blue_x + blue_y > 100000L)
  195538. {
  195539. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  195540. return;
  195541. }
  195542. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  195543. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  195544. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  195545. }
  195546. #endif
  195547. #endif
  195548. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  195549. /* write the tRNS chunk */
  195550. void /* PRIVATE */
  195551. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  195552. int num_trans, int color_type)
  195553. {
  195554. #ifdef PNG_USE_LOCAL_ARRAYS
  195555. PNG_tRNS;
  195556. #endif
  195557. png_byte buf[6];
  195558. png_debug(1, "in png_write_tRNS\n");
  195559. if (color_type == PNG_COLOR_TYPE_PALETTE)
  195560. {
  195561. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  195562. {
  195563. png_warning(png_ptr,"Invalid number of transparent colors specified");
  195564. return;
  195565. }
  195566. /* write the chunk out as it is */
  195567. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  195568. }
  195569. else if (color_type == PNG_COLOR_TYPE_GRAY)
  195570. {
  195571. /* one 16 bit value */
  195572. if(tran->gray >= (1 << png_ptr->bit_depth))
  195573. {
  195574. png_warning(png_ptr,
  195575. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  195576. return;
  195577. }
  195578. png_save_uint_16(buf, tran->gray);
  195579. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  195580. }
  195581. else if (color_type == PNG_COLOR_TYPE_RGB)
  195582. {
  195583. /* three 16 bit values */
  195584. png_save_uint_16(buf, tran->red);
  195585. png_save_uint_16(buf + 2, tran->green);
  195586. png_save_uint_16(buf + 4, tran->blue);
  195587. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  195588. {
  195589. png_warning(png_ptr,
  195590. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  195591. return;
  195592. }
  195593. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  195594. }
  195595. else
  195596. {
  195597. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  195598. }
  195599. }
  195600. #endif
  195601. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  195602. /* write the background chunk */
  195603. void /* PRIVATE */
  195604. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  195605. {
  195606. #ifdef PNG_USE_LOCAL_ARRAYS
  195607. PNG_bKGD;
  195608. #endif
  195609. png_byte buf[6];
  195610. png_debug(1, "in png_write_bKGD\n");
  195611. if (color_type == PNG_COLOR_TYPE_PALETTE)
  195612. {
  195613. if (
  195614. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195615. (png_ptr->num_palette ||
  195616. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  195617. #endif
  195618. back->index > png_ptr->num_palette)
  195619. {
  195620. png_warning(png_ptr, "Invalid background palette index");
  195621. return;
  195622. }
  195623. buf[0] = back->index;
  195624. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  195625. }
  195626. else if (color_type & PNG_COLOR_MASK_COLOR)
  195627. {
  195628. png_save_uint_16(buf, back->red);
  195629. png_save_uint_16(buf + 2, back->green);
  195630. png_save_uint_16(buf + 4, back->blue);
  195631. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  195632. {
  195633. png_warning(png_ptr,
  195634. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  195635. return;
  195636. }
  195637. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  195638. }
  195639. else
  195640. {
  195641. if(back->gray >= (1 << png_ptr->bit_depth))
  195642. {
  195643. png_warning(png_ptr,
  195644. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  195645. return;
  195646. }
  195647. png_save_uint_16(buf, back->gray);
  195648. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  195649. }
  195650. }
  195651. #endif
  195652. #if defined(PNG_WRITE_hIST_SUPPORTED)
  195653. /* write the histogram */
  195654. void /* PRIVATE */
  195655. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  195656. {
  195657. #ifdef PNG_USE_LOCAL_ARRAYS
  195658. PNG_hIST;
  195659. #endif
  195660. int i;
  195661. png_byte buf[3];
  195662. png_debug(1, "in png_write_hIST\n");
  195663. if (num_hist > (int)png_ptr->num_palette)
  195664. {
  195665. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  195666. png_ptr->num_palette);
  195667. png_warning(png_ptr, "Invalid number of histogram entries specified");
  195668. return;
  195669. }
  195670. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  195671. for (i = 0; i < num_hist; i++)
  195672. {
  195673. png_save_uint_16(buf, hist[i]);
  195674. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  195675. }
  195676. png_write_chunk_end(png_ptr);
  195677. }
  195678. #endif
  195679. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  195680. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  195681. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  195682. * and if invalid, correct the keyword rather than discarding the entire
  195683. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  195684. * length, forbids leading or trailing whitespace, multiple internal spaces,
  195685. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  195686. *
  195687. * The new_key is allocated to hold the corrected keyword and must be freed
  195688. * by the calling routine. This avoids problems with trying to write to
  195689. * static keywords without having to have duplicate copies of the strings.
  195690. */
  195691. png_size_t /* PRIVATE */
  195692. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  195693. {
  195694. png_size_t key_len;
  195695. png_charp kp, dp;
  195696. int kflag;
  195697. int kwarn=0;
  195698. png_debug(1, "in png_check_keyword\n");
  195699. *new_key = NULL;
  195700. if (key == NULL || (key_len = png_strlen(key)) == 0)
  195701. {
  195702. png_warning(png_ptr, "zero length keyword");
  195703. return ((png_size_t)0);
  195704. }
  195705. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  195706. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  195707. if (*new_key == NULL)
  195708. {
  195709. png_warning(png_ptr, "Out of memory while procesing keyword");
  195710. return ((png_size_t)0);
  195711. }
  195712. /* Replace non-printing characters with a blank and print a warning */
  195713. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  195714. {
  195715. if ((png_byte)*kp < 0x20 ||
  195716. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  195717. {
  195718. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  195719. char msg[40];
  195720. png_snprintf(msg, 40,
  195721. "invalid keyword character 0x%02X", (png_byte)*kp);
  195722. png_warning(png_ptr, msg);
  195723. #else
  195724. png_warning(png_ptr, "invalid character in keyword");
  195725. #endif
  195726. *dp = ' ';
  195727. }
  195728. else
  195729. {
  195730. *dp = *kp;
  195731. }
  195732. }
  195733. *dp = '\0';
  195734. /* Remove any trailing white space. */
  195735. kp = *new_key + key_len - 1;
  195736. if (*kp == ' ')
  195737. {
  195738. png_warning(png_ptr, "trailing spaces removed from keyword");
  195739. while (*kp == ' ')
  195740. {
  195741. *(kp--) = '\0';
  195742. key_len--;
  195743. }
  195744. }
  195745. /* Remove any leading white space. */
  195746. kp = *new_key;
  195747. if (*kp == ' ')
  195748. {
  195749. png_warning(png_ptr, "leading spaces removed from keyword");
  195750. while (*kp == ' ')
  195751. {
  195752. kp++;
  195753. key_len--;
  195754. }
  195755. }
  195756. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  195757. /* Remove multiple internal spaces. */
  195758. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  195759. {
  195760. if (*kp == ' ' && kflag == 0)
  195761. {
  195762. *(dp++) = *kp;
  195763. kflag = 1;
  195764. }
  195765. else if (*kp == ' ')
  195766. {
  195767. key_len--;
  195768. kwarn=1;
  195769. }
  195770. else
  195771. {
  195772. *(dp++) = *kp;
  195773. kflag = 0;
  195774. }
  195775. }
  195776. *dp = '\0';
  195777. if(kwarn)
  195778. png_warning(png_ptr, "extra interior spaces removed from keyword");
  195779. if (key_len == 0)
  195780. {
  195781. png_free(png_ptr, *new_key);
  195782. *new_key=NULL;
  195783. png_warning(png_ptr, "Zero length keyword");
  195784. }
  195785. if (key_len > 79)
  195786. {
  195787. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  195788. new_key[79] = '\0';
  195789. key_len = 79;
  195790. }
  195791. return (key_len);
  195792. }
  195793. #endif
  195794. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  195795. /* write a tEXt chunk */
  195796. void /* PRIVATE */
  195797. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  195798. png_size_t text_len)
  195799. {
  195800. #ifdef PNG_USE_LOCAL_ARRAYS
  195801. PNG_tEXt;
  195802. #endif
  195803. png_size_t key_len;
  195804. png_charp new_key;
  195805. png_debug(1, "in png_write_tEXt\n");
  195806. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  195807. {
  195808. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  195809. return;
  195810. }
  195811. if (text == NULL || *text == '\0')
  195812. text_len = 0;
  195813. else
  195814. text_len = png_strlen(text);
  195815. /* make sure we include the 0 after the key */
  195816. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  195817. /*
  195818. * We leave it to the application to meet PNG-1.0 requirements on the
  195819. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  195820. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  195821. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  195822. */
  195823. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  195824. if (text_len)
  195825. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  195826. png_write_chunk_end(png_ptr);
  195827. png_free(png_ptr, new_key);
  195828. }
  195829. #endif
  195830. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  195831. /* write a compressed text chunk */
  195832. void /* PRIVATE */
  195833. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  195834. png_size_t text_len, int compression)
  195835. {
  195836. #ifdef PNG_USE_LOCAL_ARRAYS
  195837. PNG_zTXt;
  195838. #endif
  195839. png_size_t key_len;
  195840. char buf[1];
  195841. png_charp new_key;
  195842. compression_state comp;
  195843. png_debug(1, "in png_write_zTXt\n");
  195844. comp.num_output_ptr = 0;
  195845. comp.max_output_ptr = 0;
  195846. comp.output_ptr = NULL;
  195847. comp.input = NULL;
  195848. comp.input_len = 0;
  195849. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  195850. {
  195851. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  195852. return;
  195853. }
  195854. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  195855. {
  195856. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  195857. png_free(png_ptr, new_key);
  195858. return;
  195859. }
  195860. text_len = png_strlen(text);
  195861. /* compute the compressed data; do it now for the length */
  195862. text_len = png_text_compress(png_ptr, text, text_len, compression,
  195863. &comp);
  195864. /* write start of chunk */
  195865. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  195866. (key_len+text_len+2));
  195867. /* write key */
  195868. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  195869. png_free(png_ptr, new_key);
  195870. buf[0] = (png_byte)compression;
  195871. /* write compression */
  195872. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  195873. /* write the compressed data */
  195874. png_write_compressed_data_out(png_ptr, &comp);
  195875. /* close the chunk */
  195876. png_write_chunk_end(png_ptr);
  195877. }
  195878. #endif
  195879. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  195880. /* write an iTXt chunk */
  195881. void /* PRIVATE */
  195882. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  195883. png_charp lang, png_charp lang_key, png_charp text)
  195884. {
  195885. #ifdef PNG_USE_LOCAL_ARRAYS
  195886. PNG_iTXt;
  195887. #endif
  195888. png_size_t lang_len, key_len, lang_key_len, text_len;
  195889. png_charp new_lang, new_key;
  195890. png_byte cbuf[2];
  195891. compression_state comp;
  195892. png_debug(1, "in png_write_iTXt\n");
  195893. comp.num_output_ptr = 0;
  195894. comp.max_output_ptr = 0;
  195895. comp.output_ptr = NULL;
  195896. comp.input = NULL;
  195897. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  195898. {
  195899. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  195900. return;
  195901. }
  195902. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  195903. {
  195904. png_warning(png_ptr, "Empty language field in iTXt chunk");
  195905. new_lang = NULL;
  195906. lang_len = 0;
  195907. }
  195908. if (lang_key == NULL)
  195909. lang_key_len = 0;
  195910. else
  195911. lang_key_len = png_strlen(lang_key);
  195912. if (text == NULL)
  195913. text_len = 0;
  195914. else
  195915. text_len = png_strlen(text);
  195916. /* compute the compressed data; do it now for the length */
  195917. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  195918. &comp);
  195919. /* make sure we include the compression flag, the compression byte,
  195920. * and the NULs after the key, lang, and lang_key parts */
  195921. png_write_chunk_start(png_ptr, png_iTXt,
  195922. (png_uint_32)(
  195923. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  195924. + key_len
  195925. + lang_len
  195926. + lang_key_len
  195927. + text_len));
  195928. /*
  195929. * We leave it to the application to meet PNG-1.0 requirements on the
  195930. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  195931. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  195932. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  195933. */
  195934. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  195935. /* set the compression flag */
  195936. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  195937. compression == PNG_TEXT_COMPRESSION_NONE)
  195938. cbuf[0] = 0;
  195939. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  195940. cbuf[0] = 1;
  195941. /* set the compression method */
  195942. cbuf[1] = 0;
  195943. png_write_chunk_data(png_ptr, cbuf, 2);
  195944. cbuf[0] = 0;
  195945. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  195946. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  195947. png_write_compressed_data_out(png_ptr, &comp);
  195948. png_write_chunk_end(png_ptr);
  195949. png_free(png_ptr, new_key);
  195950. if (new_lang)
  195951. png_free(png_ptr, new_lang);
  195952. }
  195953. #endif
  195954. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  195955. /* write the oFFs chunk */
  195956. void /* PRIVATE */
  195957. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  195958. int unit_type)
  195959. {
  195960. #ifdef PNG_USE_LOCAL_ARRAYS
  195961. PNG_oFFs;
  195962. #endif
  195963. png_byte buf[9];
  195964. png_debug(1, "in png_write_oFFs\n");
  195965. if (unit_type >= PNG_OFFSET_LAST)
  195966. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  195967. png_save_int_32(buf, x_offset);
  195968. png_save_int_32(buf + 4, y_offset);
  195969. buf[8] = (png_byte)unit_type;
  195970. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  195971. }
  195972. #endif
  195973. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  195974. /* write the pCAL chunk (described in the PNG extensions document) */
  195975. void /* PRIVATE */
  195976. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  195977. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  195978. {
  195979. #ifdef PNG_USE_LOCAL_ARRAYS
  195980. PNG_pCAL;
  195981. #endif
  195982. png_size_t purpose_len, units_len, total_len;
  195983. png_uint_32p params_len;
  195984. png_byte buf[10];
  195985. png_charp new_purpose;
  195986. int i;
  195987. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  195988. if (type >= PNG_EQUATION_LAST)
  195989. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195990. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  195991. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  195992. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  195993. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  195994. total_len = purpose_len + units_len + 10;
  195995. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  195996. *png_sizeof(png_uint_32)));
  195997. /* Find the length of each parameter, making sure we don't count the
  195998. null terminator for the last parameter. */
  195999. for (i = 0; i < nparams; i++)
  196000. {
  196001. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  196002. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  196003. total_len += (png_size_t)params_len[i];
  196004. }
  196005. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  196006. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  196007. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  196008. png_save_int_32(buf, X0);
  196009. png_save_int_32(buf + 4, X1);
  196010. buf[8] = (png_byte)type;
  196011. buf[9] = (png_byte)nparams;
  196012. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  196013. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  196014. png_free(png_ptr, new_purpose);
  196015. for (i = 0; i < nparams; i++)
  196016. {
  196017. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  196018. (png_size_t)params_len[i]);
  196019. }
  196020. png_free(png_ptr, params_len);
  196021. png_write_chunk_end(png_ptr);
  196022. }
  196023. #endif
  196024. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  196025. /* write the sCAL chunk */
  196026. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  196027. void /* PRIVATE */
  196028. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  196029. {
  196030. #ifdef PNG_USE_LOCAL_ARRAYS
  196031. PNG_sCAL;
  196032. #endif
  196033. char buf[64];
  196034. png_size_t total_len;
  196035. png_debug(1, "in png_write_sCAL\n");
  196036. buf[0] = (char)unit;
  196037. #if defined(_WIN32_WCE)
  196038. /* sprintf() function is not supported on WindowsCE */
  196039. {
  196040. wchar_t wc_buf[32];
  196041. size_t wc_len;
  196042. swprintf(wc_buf, TEXT("%12.12e"), width);
  196043. wc_len = wcslen(wc_buf);
  196044. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  196045. total_len = wc_len + 2;
  196046. swprintf(wc_buf, TEXT("%12.12e"), height);
  196047. wc_len = wcslen(wc_buf);
  196048. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  196049. NULL, NULL);
  196050. total_len += wc_len;
  196051. }
  196052. #else
  196053. png_snprintf(buf + 1, 63, "%12.12e", width);
  196054. total_len = 1 + png_strlen(buf + 1) + 1;
  196055. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  196056. total_len += png_strlen(buf + total_len);
  196057. #endif
  196058. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  196059. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  196060. }
  196061. #else
  196062. #ifdef PNG_FIXED_POINT_SUPPORTED
  196063. void /* PRIVATE */
  196064. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  196065. png_charp height)
  196066. {
  196067. #ifdef PNG_USE_LOCAL_ARRAYS
  196068. PNG_sCAL;
  196069. #endif
  196070. png_byte buf[64];
  196071. png_size_t wlen, hlen, total_len;
  196072. png_debug(1, "in png_write_sCAL_s\n");
  196073. wlen = png_strlen(width);
  196074. hlen = png_strlen(height);
  196075. total_len = wlen + hlen + 2;
  196076. if (total_len > 64)
  196077. {
  196078. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  196079. return;
  196080. }
  196081. buf[0] = (png_byte)unit;
  196082. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  196083. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  196084. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  196085. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  196086. }
  196087. #endif
  196088. #endif
  196089. #endif
  196090. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  196091. /* write the pHYs chunk */
  196092. void /* PRIVATE */
  196093. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  196094. png_uint_32 y_pixels_per_unit,
  196095. int unit_type)
  196096. {
  196097. #ifdef PNG_USE_LOCAL_ARRAYS
  196098. PNG_pHYs;
  196099. #endif
  196100. png_byte buf[9];
  196101. png_debug(1, "in png_write_pHYs\n");
  196102. if (unit_type >= PNG_RESOLUTION_LAST)
  196103. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  196104. png_save_uint_32(buf, x_pixels_per_unit);
  196105. png_save_uint_32(buf + 4, y_pixels_per_unit);
  196106. buf[8] = (png_byte)unit_type;
  196107. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  196108. }
  196109. #endif
  196110. #if defined(PNG_WRITE_tIME_SUPPORTED)
  196111. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  196112. * or png_convert_from_time_t(), or fill in the structure yourself.
  196113. */
  196114. void /* PRIVATE */
  196115. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  196116. {
  196117. #ifdef PNG_USE_LOCAL_ARRAYS
  196118. PNG_tIME;
  196119. #endif
  196120. png_byte buf[7];
  196121. png_debug(1, "in png_write_tIME\n");
  196122. if (mod_time->month > 12 || mod_time->month < 1 ||
  196123. mod_time->day > 31 || mod_time->day < 1 ||
  196124. mod_time->hour > 23 || mod_time->second > 60)
  196125. {
  196126. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  196127. return;
  196128. }
  196129. png_save_uint_16(buf, mod_time->year);
  196130. buf[2] = mod_time->month;
  196131. buf[3] = mod_time->day;
  196132. buf[4] = mod_time->hour;
  196133. buf[5] = mod_time->minute;
  196134. buf[6] = mod_time->second;
  196135. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  196136. }
  196137. #endif
  196138. /* initializes the row writing capability of libpng */
  196139. void /* PRIVATE */
  196140. png_write_start_row(png_structp png_ptr)
  196141. {
  196142. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  196143. #ifdef PNG_USE_LOCAL_ARRAYS
  196144. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196145. /* start of interlace block */
  196146. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196147. /* offset to next interlace block */
  196148. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196149. /* start of interlace block in the y direction */
  196150. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196151. /* offset to next interlace block in the y direction */
  196152. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196153. #endif
  196154. #endif
  196155. png_size_t buf_size;
  196156. png_debug(1, "in png_write_start_row\n");
  196157. buf_size = (png_size_t)(PNG_ROWBYTES(
  196158. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  196159. /* set up row buffer */
  196160. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  196161. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  196162. #ifndef PNG_NO_WRITE_FILTERING
  196163. /* set up filtering buffer, if using this filter */
  196164. if (png_ptr->do_filter & PNG_FILTER_SUB)
  196165. {
  196166. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  196167. (png_ptr->rowbytes + 1));
  196168. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  196169. }
  196170. /* We only need to keep the previous row if we are using one of these. */
  196171. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  196172. {
  196173. /* set up previous row buffer */
  196174. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  196175. png_memset(png_ptr->prev_row, 0, buf_size);
  196176. if (png_ptr->do_filter & PNG_FILTER_UP)
  196177. {
  196178. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  196179. (png_ptr->rowbytes + 1));
  196180. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  196181. }
  196182. if (png_ptr->do_filter & PNG_FILTER_AVG)
  196183. {
  196184. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  196185. (png_ptr->rowbytes + 1));
  196186. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  196187. }
  196188. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  196189. {
  196190. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  196191. (png_ptr->rowbytes + 1));
  196192. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  196193. }
  196194. #endif /* PNG_NO_WRITE_FILTERING */
  196195. }
  196196. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  196197. /* if interlaced, we need to set up width and height of pass */
  196198. if (png_ptr->interlaced)
  196199. {
  196200. if (!(png_ptr->transformations & PNG_INTERLACE))
  196201. {
  196202. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196203. png_pass_ystart[0]) / png_pass_yinc[0];
  196204. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  196205. png_pass_start[0]) / png_pass_inc[0];
  196206. }
  196207. else
  196208. {
  196209. png_ptr->num_rows = png_ptr->height;
  196210. png_ptr->usr_width = png_ptr->width;
  196211. }
  196212. }
  196213. else
  196214. #endif
  196215. {
  196216. png_ptr->num_rows = png_ptr->height;
  196217. png_ptr->usr_width = png_ptr->width;
  196218. }
  196219. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196220. png_ptr->zstream.next_out = png_ptr->zbuf;
  196221. }
  196222. /* Internal use only. Called when finished processing a row of data. */
  196223. void /* PRIVATE */
  196224. png_write_finish_row(png_structp png_ptr)
  196225. {
  196226. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  196227. #ifdef PNG_USE_LOCAL_ARRAYS
  196228. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196229. /* start of interlace block */
  196230. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196231. /* offset to next interlace block */
  196232. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196233. /* start of interlace block in the y direction */
  196234. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196235. /* offset to next interlace block in the y direction */
  196236. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196237. #endif
  196238. #endif
  196239. int ret;
  196240. png_debug(1, "in png_write_finish_row\n");
  196241. /* next row */
  196242. png_ptr->row_number++;
  196243. /* see if we are done */
  196244. if (png_ptr->row_number < png_ptr->num_rows)
  196245. return;
  196246. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  196247. /* if interlaced, go to next pass */
  196248. if (png_ptr->interlaced)
  196249. {
  196250. png_ptr->row_number = 0;
  196251. if (png_ptr->transformations & PNG_INTERLACE)
  196252. {
  196253. png_ptr->pass++;
  196254. }
  196255. else
  196256. {
  196257. /* loop until we find a non-zero width or height pass */
  196258. do
  196259. {
  196260. png_ptr->pass++;
  196261. if (png_ptr->pass >= 7)
  196262. break;
  196263. png_ptr->usr_width = (png_ptr->width +
  196264. png_pass_inc[png_ptr->pass] - 1 -
  196265. png_pass_start[png_ptr->pass]) /
  196266. png_pass_inc[png_ptr->pass];
  196267. png_ptr->num_rows = (png_ptr->height +
  196268. png_pass_yinc[png_ptr->pass] - 1 -
  196269. png_pass_ystart[png_ptr->pass]) /
  196270. png_pass_yinc[png_ptr->pass];
  196271. if (png_ptr->transformations & PNG_INTERLACE)
  196272. break;
  196273. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  196274. }
  196275. /* reset the row above the image for the next pass */
  196276. if (png_ptr->pass < 7)
  196277. {
  196278. if (png_ptr->prev_row != NULL)
  196279. png_memset(png_ptr->prev_row, 0,
  196280. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  196281. png_ptr->usr_bit_depth,png_ptr->width))+1);
  196282. return;
  196283. }
  196284. }
  196285. #endif
  196286. /* if we get here, we've just written the last row, so we need
  196287. to flush the compressor */
  196288. do
  196289. {
  196290. /* tell the compressor we are done */
  196291. ret = deflate(&png_ptr->zstream, Z_FINISH);
  196292. /* check for an error */
  196293. if (ret == Z_OK)
  196294. {
  196295. /* check to see if we need more room */
  196296. if (!(png_ptr->zstream.avail_out))
  196297. {
  196298. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  196299. png_ptr->zstream.next_out = png_ptr->zbuf;
  196300. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196301. }
  196302. }
  196303. else if (ret != Z_STREAM_END)
  196304. {
  196305. if (png_ptr->zstream.msg != NULL)
  196306. png_error(png_ptr, png_ptr->zstream.msg);
  196307. else
  196308. png_error(png_ptr, "zlib error");
  196309. }
  196310. } while (ret != Z_STREAM_END);
  196311. /* write any extra space */
  196312. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  196313. {
  196314. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  196315. png_ptr->zstream.avail_out);
  196316. }
  196317. deflateReset(&png_ptr->zstream);
  196318. png_ptr->zstream.data_type = Z_BINARY;
  196319. }
  196320. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  196321. /* Pick out the correct pixels for the interlace pass.
  196322. * The basic idea here is to go through the row with a source
  196323. * pointer and a destination pointer (sp and dp), and copy the
  196324. * correct pixels for the pass. As the row gets compacted,
  196325. * sp will always be >= dp, so we should never overwrite anything.
  196326. * See the default: case for the easiest code to understand.
  196327. */
  196328. void /* PRIVATE */
  196329. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  196330. {
  196331. #ifdef PNG_USE_LOCAL_ARRAYS
  196332. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196333. /* start of interlace block */
  196334. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196335. /* offset to next interlace block */
  196336. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196337. #endif
  196338. png_debug(1, "in png_do_write_interlace\n");
  196339. /* we don't have to do anything on the last pass (6) */
  196340. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196341. if (row != NULL && row_info != NULL && pass < 6)
  196342. #else
  196343. if (pass < 6)
  196344. #endif
  196345. {
  196346. /* each pixel depth is handled separately */
  196347. switch (row_info->pixel_depth)
  196348. {
  196349. case 1:
  196350. {
  196351. png_bytep sp;
  196352. png_bytep dp;
  196353. int shift;
  196354. int d;
  196355. int value;
  196356. png_uint_32 i;
  196357. png_uint_32 row_width = row_info->width;
  196358. dp = row;
  196359. d = 0;
  196360. shift = 7;
  196361. for (i = png_pass_start[pass]; i < row_width;
  196362. i += png_pass_inc[pass])
  196363. {
  196364. sp = row + (png_size_t)(i >> 3);
  196365. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  196366. d |= (value << shift);
  196367. if (shift == 0)
  196368. {
  196369. shift = 7;
  196370. *dp++ = (png_byte)d;
  196371. d = 0;
  196372. }
  196373. else
  196374. shift--;
  196375. }
  196376. if (shift != 7)
  196377. *dp = (png_byte)d;
  196378. break;
  196379. }
  196380. case 2:
  196381. {
  196382. png_bytep sp;
  196383. png_bytep dp;
  196384. int shift;
  196385. int d;
  196386. int value;
  196387. png_uint_32 i;
  196388. png_uint_32 row_width = row_info->width;
  196389. dp = row;
  196390. shift = 6;
  196391. d = 0;
  196392. for (i = png_pass_start[pass]; i < row_width;
  196393. i += png_pass_inc[pass])
  196394. {
  196395. sp = row + (png_size_t)(i >> 2);
  196396. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  196397. d |= (value << shift);
  196398. if (shift == 0)
  196399. {
  196400. shift = 6;
  196401. *dp++ = (png_byte)d;
  196402. d = 0;
  196403. }
  196404. else
  196405. shift -= 2;
  196406. }
  196407. if (shift != 6)
  196408. *dp = (png_byte)d;
  196409. break;
  196410. }
  196411. case 4:
  196412. {
  196413. png_bytep sp;
  196414. png_bytep dp;
  196415. int shift;
  196416. int d;
  196417. int value;
  196418. png_uint_32 i;
  196419. png_uint_32 row_width = row_info->width;
  196420. dp = row;
  196421. shift = 4;
  196422. d = 0;
  196423. for (i = png_pass_start[pass]; i < row_width;
  196424. i += png_pass_inc[pass])
  196425. {
  196426. sp = row + (png_size_t)(i >> 1);
  196427. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  196428. d |= (value << shift);
  196429. if (shift == 0)
  196430. {
  196431. shift = 4;
  196432. *dp++ = (png_byte)d;
  196433. d = 0;
  196434. }
  196435. else
  196436. shift -= 4;
  196437. }
  196438. if (shift != 4)
  196439. *dp = (png_byte)d;
  196440. break;
  196441. }
  196442. default:
  196443. {
  196444. png_bytep sp;
  196445. png_bytep dp;
  196446. png_uint_32 i;
  196447. png_uint_32 row_width = row_info->width;
  196448. png_size_t pixel_bytes;
  196449. /* start at the beginning */
  196450. dp = row;
  196451. /* find out how many bytes each pixel takes up */
  196452. pixel_bytes = (row_info->pixel_depth >> 3);
  196453. /* loop through the row, only looking at the pixels that
  196454. matter */
  196455. for (i = png_pass_start[pass]; i < row_width;
  196456. i += png_pass_inc[pass])
  196457. {
  196458. /* find out where the original pixel is */
  196459. sp = row + (png_size_t)i * pixel_bytes;
  196460. /* move the pixel */
  196461. if (dp != sp)
  196462. png_memcpy(dp, sp, pixel_bytes);
  196463. /* next pixel */
  196464. dp += pixel_bytes;
  196465. }
  196466. break;
  196467. }
  196468. }
  196469. /* set new row width */
  196470. row_info->width = (row_info->width +
  196471. png_pass_inc[pass] - 1 -
  196472. png_pass_start[pass]) /
  196473. png_pass_inc[pass];
  196474. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  196475. row_info->width);
  196476. }
  196477. }
  196478. #endif
  196479. /* This filters the row, chooses which filter to use, if it has not already
  196480. * been specified by the application, and then writes the row out with the
  196481. * chosen filter.
  196482. */
  196483. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  196484. #define PNG_HISHIFT 10
  196485. #define PNG_LOMASK ((png_uint_32)0xffffL)
  196486. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  196487. void /* PRIVATE */
  196488. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  196489. {
  196490. png_bytep best_row;
  196491. #ifndef PNG_NO_WRITE_FILTER
  196492. png_bytep prev_row, row_buf;
  196493. png_uint_32 mins, bpp;
  196494. png_byte filter_to_do = png_ptr->do_filter;
  196495. png_uint_32 row_bytes = row_info->rowbytes;
  196496. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196497. int num_p_filters = (int)png_ptr->num_prev_filters;
  196498. #endif
  196499. png_debug(1, "in png_write_find_filter\n");
  196500. /* find out how many bytes offset each pixel is */
  196501. bpp = (row_info->pixel_depth + 7) >> 3;
  196502. prev_row = png_ptr->prev_row;
  196503. #endif
  196504. best_row = png_ptr->row_buf;
  196505. #ifndef PNG_NO_WRITE_FILTER
  196506. row_buf = best_row;
  196507. mins = PNG_MAXSUM;
  196508. /* The prediction method we use is to find which method provides the
  196509. * smallest value when summing the absolute values of the distances
  196510. * from zero, using anything >= 128 as negative numbers. This is known
  196511. * as the "minimum sum of absolute differences" heuristic. Other
  196512. * heuristics are the "weighted minimum sum of absolute differences"
  196513. * (experimental and can in theory improve compression), and the "zlib
  196514. * predictive" method (not implemented yet), which does test compressions
  196515. * of lines using different filter methods, and then chooses the
  196516. * (series of) filter(s) that give minimum compressed data size (VERY
  196517. * computationally expensive).
  196518. *
  196519. * GRR 980525: consider also
  196520. * (1) minimum sum of absolute differences from running average (i.e.,
  196521. * keep running sum of non-absolute differences & count of bytes)
  196522. * [track dispersion, too? restart average if dispersion too large?]
  196523. * (1b) minimum sum of absolute differences from sliding average, probably
  196524. * with window size <= deflate window (usually 32K)
  196525. * (2) minimum sum of squared differences from zero or running average
  196526. * (i.e., ~ root-mean-square approach)
  196527. */
  196528. /* We don't need to test the 'no filter' case if this is the only filter
  196529. * that has been chosen, as it doesn't actually do anything to the data.
  196530. */
  196531. if ((filter_to_do & PNG_FILTER_NONE) &&
  196532. filter_to_do != PNG_FILTER_NONE)
  196533. {
  196534. png_bytep rp;
  196535. png_uint_32 sum = 0;
  196536. png_uint_32 i;
  196537. int v;
  196538. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  196539. {
  196540. v = *rp;
  196541. sum += (v < 128) ? v : 256 - v;
  196542. }
  196543. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196544. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196545. {
  196546. png_uint_32 sumhi, sumlo;
  196547. int j;
  196548. sumlo = sum & PNG_LOMASK;
  196549. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  196550. /* Reduce the sum if we match any of the previous rows */
  196551. for (j = 0; j < num_p_filters; j++)
  196552. {
  196553. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  196554. {
  196555. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  196556. PNG_WEIGHT_SHIFT;
  196557. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  196558. PNG_WEIGHT_SHIFT;
  196559. }
  196560. }
  196561. /* Factor in the cost of this filter (this is here for completeness,
  196562. * but it makes no sense to have a "cost" for the NONE filter, as
  196563. * it has the minimum possible computational cost - none).
  196564. */
  196565. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  196566. PNG_COST_SHIFT;
  196567. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  196568. PNG_COST_SHIFT;
  196569. if (sumhi > PNG_HIMASK)
  196570. sum = PNG_MAXSUM;
  196571. else
  196572. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196573. }
  196574. #endif
  196575. mins = sum;
  196576. }
  196577. /* sub filter */
  196578. if (filter_to_do == PNG_FILTER_SUB)
  196579. /* it's the only filter so no testing is needed */
  196580. {
  196581. png_bytep rp, lp, dp;
  196582. png_uint_32 i;
  196583. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  196584. i++, rp++, dp++)
  196585. {
  196586. *dp = *rp;
  196587. }
  196588. for (lp = row_buf + 1; i < row_bytes;
  196589. i++, rp++, lp++, dp++)
  196590. {
  196591. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  196592. }
  196593. best_row = png_ptr->sub_row;
  196594. }
  196595. else if (filter_to_do & PNG_FILTER_SUB)
  196596. {
  196597. png_bytep rp, dp, lp;
  196598. png_uint_32 sum = 0, lmins = mins;
  196599. png_uint_32 i;
  196600. int v;
  196601. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196602. /* We temporarily increase the "minimum sum" by the factor we
  196603. * would reduce the sum of this filter, so that we can do the
  196604. * early exit comparison without scaling the sum each time.
  196605. */
  196606. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196607. {
  196608. int j;
  196609. png_uint_32 lmhi, lmlo;
  196610. lmlo = lmins & PNG_LOMASK;
  196611. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  196612. for (j = 0; j < num_p_filters; j++)
  196613. {
  196614. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  196615. {
  196616. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  196617. PNG_WEIGHT_SHIFT;
  196618. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  196619. PNG_WEIGHT_SHIFT;
  196620. }
  196621. }
  196622. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  196623. PNG_COST_SHIFT;
  196624. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  196625. PNG_COST_SHIFT;
  196626. if (lmhi > PNG_HIMASK)
  196627. lmins = PNG_MAXSUM;
  196628. else
  196629. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  196630. }
  196631. #endif
  196632. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  196633. i++, rp++, dp++)
  196634. {
  196635. v = *dp = *rp;
  196636. sum += (v < 128) ? v : 256 - v;
  196637. }
  196638. for (lp = row_buf + 1; i < row_bytes;
  196639. i++, rp++, lp++, dp++)
  196640. {
  196641. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  196642. sum += (v < 128) ? v : 256 - v;
  196643. if (sum > lmins) /* We are already worse, don't continue. */
  196644. break;
  196645. }
  196646. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196647. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196648. {
  196649. int j;
  196650. png_uint_32 sumhi, sumlo;
  196651. sumlo = sum & PNG_LOMASK;
  196652. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  196653. for (j = 0; j < num_p_filters; j++)
  196654. {
  196655. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  196656. {
  196657. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  196658. PNG_WEIGHT_SHIFT;
  196659. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  196660. PNG_WEIGHT_SHIFT;
  196661. }
  196662. }
  196663. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  196664. PNG_COST_SHIFT;
  196665. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  196666. PNG_COST_SHIFT;
  196667. if (sumhi > PNG_HIMASK)
  196668. sum = PNG_MAXSUM;
  196669. else
  196670. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196671. }
  196672. #endif
  196673. if (sum < mins)
  196674. {
  196675. mins = sum;
  196676. best_row = png_ptr->sub_row;
  196677. }
  196678. }
  196679. /* up filter */
  196680. if (filter_to_do == PNG_FILTER_UP)
  196681. {
  196682. png_bytep rp, dp, pp;
  196683. png_uint_32 i;
  196684. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  196685. pp = prev_row + 1; i < row_bytes;
  196686. i++, rp++, pp++, dp++)
  196687. {
  196688. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  196689. }
  196690. best_row = png_ptr->up_row;
  196691. }
  196692. else if (filter_to_do & PNG_FILTER_UP)
  196693. {
  196694. png_bytep rp, dp, pp;
  196695. png_uint_32 sum = 0, lmins = mins;
  196696. png_uint_32 i;
  196697. int v;
  196698. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196699. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196700. {
  196701. int j;
  196702. png_uint_32 lmhi, lmlo;
  196703. lmlo = lmins & PNG_LOMASK;
  196704. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  196705. for (j = 0; j < num_p_filters; j++)
  196706. {
  196707. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  196708. {
  196709. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  196710. PNG_WEIGHT_SHIFT;
  196711. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  196712. PNG_WEIGHT_SHIFT;
  196713. }
  196714. }
  196715. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  196716. PNG_COST_SHIFT;
  196717. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  196718. PNG_COST_SHIFT;
  196719. if (lmhi > PNG_HIMASK)
  196720. lmins = PNG_MAXSUM;
  196721. else
  196722. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  196723. }
  196724. #endif
  196725. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  196726. pp = prev_row + 1; i < row_bytes; i++)
  196727. {
  196728. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  196729. sum += (v < 128) ? v : 256 - v;
  196730. if (sum > lmins) /* We are already worse, don't continue. */
  196731. break;
  196732. }
  196733. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196734. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196735. {
  196736. int j;
  196737. png_uint_32 sumhi, sumlo;
  196738. sumlo = sum & PNG_LOMASK;
  196739. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  196740. for (j = 0; j < num_p_filters; j++)
  196741. {
  196742. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  196743. {
  196744. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  196745. PNG_WEIGHT_SHIFT;
  196746. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  196747. PNG_WEIGHT_SHIFT;
  196748. }
  196749. }
  196750. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  196751. PNG_COST_SHIFT;
  196752. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  196753. PNG_COST_SHIFT;
  196754. if (sumhi > PNG_HIMASK)
  196755. sum = PNG_MAXSUM;
  196756. else
  196757. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196758. }
  196759. #endif
  196760. if (sum < mins)
  196761. {
  196762. mins = sum;
  196763. best_row = png_ptr->up_row;
  196764. }
  196765. }
  196766. /* avg filter */
  196767. if (filter_to_do == PNG_FILTER_AVG)
  196768. {
  196769. png_bytep rp, dp, pp, lp;
  196770. png_uint_32 i;
  196771. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  196772. pp = prev_row + 1; i < bpp; i++)
  196773. {
  196774. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  196775. }
  196776. for (lp = row_buf + 1; i < row_bytes; i++)
  196777. {
  196778. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  196779. & 0xff);
  196780. }
  196781. best_row = png_ptr->avg_row;
  196782. }
  196783. else if (filter_to_do & PNG_FILTER_AVG)
  196784. {
  196785. png_bytep rp, dp, pp, lp;
  196786. png_uint_32 sum = 0, lmins = mins;
  196787. png_uint_32 i;
  196788. int v;
  196789. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196790. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196791. {
  196792. int j;
  196793. png_uint_32 lmhi, lmlo;
  196794. lmlo = lmins & PNG_LOMASK;
  196795. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  196796. for (j = 0; j < num_p_filters; j++)
  196797. {
  196798. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  196799. {
  196800. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  196801. PNG_WEIGHT_SHIFT;
  196802. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  196803. PNG_WEIGHT_SHIFT;
  196804. }
  196805. }
  196806. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196807. PNG_COST_SHIFT;
  196808. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196809. PNG_COST_SHIFT;
  196810. if (lmhi > PNG_HIMASK)
  196811. lmins = PNG_MAXSUM;
  196812. else
  196813. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  196814. }
  196815. #endif
  196816. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  196817. pp = prev_row + 1; i < bpp; i++)
  196818. {
  196819. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  196820. sum += (v < 128) ? v : 256 - v;
  196821. }
  196822. for (lp = row_buf + 1; i < row_bytes; i++)
  196823. {
  196824. v = *dp++ =
  196825. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  196826. sum += (v < 128) ? v : 256 - v;
  196827. if (sum > lmins) /* We are already worse, don't continue. */
  196828. break;
  196829. }
  196830. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196831. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196832. {
  196833. int j;
  196834. png_uint_32 sumhi, sumlo;
  196835. sumlo = sum & PNG_LOMASK;
  196836. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  196837. for (j = 0; j < num_p_filters; j++)
  196838. {
  196839. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  196840. {
  196841. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  196842. PNG_WEIGHT_SHIFT;
  196843. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  196844. PNG_WEIGHT_SHIFT;
  196845. }
  196846. }
  196847. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196848. PNG_COST_SHIFT;
  196849. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196850. PNG_COST_SHIFT;
  196851. if (sumhi > PNG_HIMASK)
  196852. sum = PNG_MAXSUM;
  196853. else
  196854. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196855. }
  196856. #endif
  196857. if (sum < mins)
  196858. {
  196859. mins = sum;
  196860. best_row = png_ptr->avg_row;
  196861. }
  196862. }
  196863. /* Paeth filter */
  196864. if (filter_to_do == PNG_FILTER_PAETH)
  196865. {
  196866. png_bytep rp, dp, pp, cp, lp;
  196867. png_uint_32 i;
  196868. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  196869. pp = prev_row + 1; i < bpp; i++)
  196870. {
  196871. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  196872. }
  196873. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  196874. {
  196875. int a, b, c, pa, pb, pc, p;
  196876. b = *pp++;
  196877. c = *cp++;
  196878. a = *lp++;
  196879. p = b - c;
  196880. pc = a - c;
  196881. #ifdef PNG_USE_ABS
  196882. pa = abs(p);
  196883. pb = abs(pc);
  196884. pc = abs(p + pc);
  196885. #else
  196886. pa = p < 0 ? -p : p;
  196887. pb = pc < 0 ? -pc : pc;
  196888. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196889. #endif
  196890. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196891. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  196892. }
  196893. best_row = png_ptr->paeth_row;
  196894. }
  196895. else if (filter_to_do & PNG_FILTER_PAETH)
  196896. {
  196897. png_bytep rp, dp, pp, cp, lp;
  196898. png_uint_32 sum = 0, lmins = mins;
  196899. png_uint_32 i;
  196900. int v;
  196901. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196902. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196903. {
  196904. int j;
  196905. png_uint_32 lmhi, lmlo;
  196906. lmlo = lmins & PNG_LOMASK;
  196907. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  196908. for (j = 0; j < num_p_filters; j++)
  196909. {
  196910. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  196911. {
  196912. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  196913. PNG_WEIGHT_SHIFT;
  196914. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  196915. PNG_WEIGHT_SHIFT;
  196916. }
  196917. }
  196918. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  196919. PNG_COST_SHIFT;
  196920. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  196921. PNG_COST_SHIFT;
  196922. if (lmhi > PNG_HIMASK)
  196923. lmins = PNG_MAXSUM;
  196924. else
  196925. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  196926. }
  196927. #endif
  196928. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  196929. pp = prev_row + 1; i < bpp; i++)
  196930. {
  196931. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  196932. sum += (v < 128) ? v : 256 - v;
  196933. }
  196934. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  196935. {
  196936. int a, b, c, pa, pb, pc, p;
  196937. b = *pp++;
  196938. c = *cp++;
  196939. a = *lp++;
  196940. #ifndef PNG_SLOW_PAETH
  196941. p = b - c;
  196942. pc = a - c;
  196943. #ifdef PNG_USE_ABS
  196944. pa = abs(p);
  196945. pb = abs(pc);
  196946. pc = abs(p + pc);
  196947. #else
  196948. pa = p < 0 ? -p : p;
  196949. pb = pc < 0 ? -pc : pc;
  196950. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196951. #endif
  196952. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196953. #else /* PNG_SLOW_PAETH */
  196954. p = a + b - c;
  196955. pa = abs(p - a);
  196956. pb = abs(p - b);
  196957. pc = abs(p - c);
  196958. if (pa <= pb && pa <= pc)
  196959. p = a;
  196960. else if (pb <= pc)
  196961. p = b;
  196962. else
  196963. p = c;
  196964. #endif /* PNG_SLOW_PAETH */
  196965. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  196966. sum += (v < 128) ? v : 256 - v;
  196967. if (sum > lmins) /* We are already worse, don't continue. */
  196968. break;
  196969. }
  196970. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196971. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196972. {
  196973. int j;
  196974. png_uint_32 sumhi, sumlo;
  196975. sumlo = sum & PNG_LOMASK;
  196976. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  196977. for (j = 0; j < num_p_filters; j++)
  196978. {
  196979. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  196980. {
  196981. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  196982. PNG_WEIGHT_SHIFT;
  196983. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  196984. PNG_WEIGHT_SHIFT;
  196985. }
  196986. }
  196987. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  196988. PNG_COST_SHIFT;
  196989. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  196990. PNG_COST_SHIFT;
  196991. if (sumhi > PNG_HIMASK)
  196992. sum = PNG_MAXSUM;
  196993. else
  196994. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196995. }
  196996. #endif
  196997. if (sum < mins)
  196998. {
  196999. best_row = png_ptr->paeth_row;
  197000. }
  197001. }
  197002. #endif /* PNG_NO_WRITE_FILTER */
  197003. /* Do the actual writing of the filtered row data from the chosen filter. */
  197004. png_write_filtered_row(png_ptr, best_row);
  197005. #ifndef PNG_NO_WRITE_FILTER
  197006. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197007. /* Save the type of filter we picked this time for future calculations */
  197008. if (png_ptr->num_prev_filters > 0)
  197009. {
  197010. int j;
  197011. for (j = 1; j < num_p_filters; j++)
  197012. {
  197013. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  197014. }
  197015. png_ptr->prev_filters[j] = best_row[0];
  197016. }
  197017. #endif
  197018. #endif /* PNG_NO_WRITE_FILTER */
  197019. }
  197020. /* Do the actual writing of a previously filtered row. */
  197021. void /* PRIVATE */
  197022. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  197023. {
  197024. png_debug(1, "in png_write_filtered_row\n");
  197025. png_debug1(2, "filter = %d\n", filtered_row[0]);
  197026. /* set up the zlib input buffer */
  197027. png_ptr->zstream.next_in = filtered_row;
  197028. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  197029. /* repeat until we have compressed all the data */
  197030. do
  197031. {
  197032. int ret; /* return of zlib */
  197033. /* compress the data */
  197034. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  197035. /* check for compression errors */
  197036. if (ret != Z_OK)
  197037. {
  197038. if (png_ptr->zstream.msg != NULL)
  197039. png_error(png_ptr, png_ptr->zstream.msg);
  197040. else
  197041. png_error(png_ptr, "zlib error");
  197042. }
  197043. /* see if it is time to write another IDAT */
  197044. if (!(png_ptr->zstream.avail_out))
  197045. {
  197046. /* write the IDAT and reset the zlib output buffer */
  197047. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  197048. png_ptr->zstream.next_out = png_ptr->zbuf;
  197049. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197050. }
  197051. /* repeat until all data has been compressed */
  197052. } while (png_ptr->zstream.avail_in);
  197053. /* swap the current and previous rows */
  197054. if (png_ptr->prev_row != NULL)
  197055. {
  197056. png_bytep tptr;
  197057. tptr = png_ptr->prev_row;
  197058. png_ptr->prev_row = png_ptr->row_buf;
  197059. png_ptr->row_buf = tptr;
  197060. }
  197061. /* finish row - updates counters and flushes zlib if last row */
  197062. png_write_finish_row(png_ptr);
  197063. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  197064. png_ptr->flush_rows++;
  197065. if (png_ptr->flush_dist > 0 &&
  197066. png_ptr->flush_rows >= png_ptr->flush_dist)
  197067. {
  197068. png_write_flush(png_ptr);
  197069. }
  197070. #endif
  197071. }
  197072. #endif /* PNG_WRITE_SUPPORTED */
  197073. /********* End of inlined file: pngwutil.c *********/
  197074. }
  197075. }
  197076. #ifdef _MSC_VER
  197077. #pragma warning (pop)
  197078. #endif
  197079. BEGIN_JUCE_NAMESPACE
  197080. using namespace pnglibNamespace;
  197081. using ::malloc;
  197082. using ::free;
  197083. static void pngReadCallback (png_structp pngReadStruct, png_bytep data, png_size_t length) throw()
  197084. {
  197085. InputStream* const in = (InputStream*) png_get_io_ptr (pngReadStruct);
  197086. in->read (data, (int) length);
  197087. }
  197088. struct PNGErrorStruct {};
  197089. static void pngErrorCallback (png_structp, png_const_charp)
  197090. {
  197091. throw PNGErrorStruct();
  197092. }
  197093. Image* juce_loadPNGImageFromStream (InputStream& in) throw()
  197094. {
  197095. Image* image = 0;
  197096. png_structp pngReadStruct;
  197097. png_infop pngInfoStruct;
  197098. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  197099. if (pngReadStruct != 0)
  197100. {
  197101. pngInfoStruct = png_create_info_struct (pngReadStruct);
  197102. if (pngInfoStruct == 0)
  197103. {
  197104. png_destroy_read_struct (&pngReadStruct, 0, 0);
  197105. return 0;
  197106. }
  197107. png_set_error_fn (pngReadStruct, 0, pngErrorCallback, pngErrorCallback);
  197108. // read the header..
  197109. png_set_read_fn (pngReadStruct, &in, pngReadCallback);
  197110. png_uint_32 width, height;
  197111. int bitDepth, colorType, interlaceType;
  197112. try
  197113. {
  197114. png_read_info (pngReadStruct, pngInfoStruct);
  197115. png_get_IHDR (pngReadStruct, pngInfoStruct,
  197116. &width, &height,
  197117. &bitDepth, &colorType,
  197118. &interlaceType, 0, 0);
  197119. }
  197120. catch (...)
  197121. {
  197122. png_destroy_read_struct (&pngReadStruct, 0, 0);
  197123. return 0;
  197124. }
  197125. if (bitDepth == 16)
  197126. png_set_strip_16 (pngReadStruct);
  197127. if (colorType == PNG_COLOR_TYPE_PALETTE)
  197128. png_set_expand (pngReadStruct);
  197129. if (bitDepth < 8)
  197130. png_set_expand (pngReadStruct);
  197131. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  197132. png_set_expand (pngReadStruct);
  197133. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  197134. png_set_gray_to_rgb (pngReadStruct);
  197135. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  197136. const bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  197137. || pngInfoStruct->num_trans > 0;
  197138. // Load the image into a temp buffer in the pnglib format..
  197139. uint8* const tempBuffer = (uint8*) juce_malloc (height * (width << 2));
  197140. png_bytepp rows = (png_bytepp) juce_malloc (sizeof (png_bytep) * height);
  197141. int y;
  197142. for (y = (int) height; --y >= 0;)
  197143. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  197144. bool crashed = false;
  197145. try
  197146. {
  197147. png_read_image (pngReadStruct, rows);
  197148. png_read_end (pngReadStruct, pngInfoStruct);
  197149. }
  197150. catch (...)
  197151. {
  197152. crashed = true;
  197153. }
  197154. juce_free (rows);
  197155. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  197156. if (crashed)
  197157. return 0;
  197158. // now convert the data to a juce image format..
  197159. image = new Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  197160. width, height, hasAlphaChan);
  197161. int stride, pixelStride;
  197162. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  197163. uint8* srcRow = tempBuffer;
  197164. uint8* destRow = pixels;
  197165. for (y = 0; y < (int) height; ++y)
  197166. {
  197167. const uint8* src = srcRow;
  197168. srcRow += (width << 2);
  197169. uint8* dest = destRow;
  197170. destRow += stride;
  197171. if (hasAlphaChan)
  197172. {
  197173. for (int i = width; --i >= 0;)
  197174. {
  197175. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  197176. ((PixelARGB*) dest)->premultiply();
  197177. dest += pixelStride;
  197178. src += 4;
  197179. }
  197180. }
  197181. else
  197182. {
  197183. for (int i = width; --i >= 0;)
  197184. {
  197185. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  197186. dest += pixelStride;
  197187. src += 4;
  197188. }
  197189. }
  197190. }
  197191. image->releasePixelDataReadWrite (pixels);
  197192. juce_free (tempBuffer);
  197193. }
  197194. return image;
  197195. }
  197196. static void pngWriteDataCallback (png_structp png_ptr, png_bytep data, png_size_t length) throw()
  197197. {
  197198. OutputStream* const out = (OutputStream*) png_ptr->io_ptr;
  197199. const bool ok = out->write (data, length);
  197200. (void) ok;
  197201. jassert (ok);
  197202. }
  197203. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw()
  197204. {
  197205. const int width = image.getWidth();
  197206. const int height = image.getHeight();
  197207. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  197208. if (pngWriteStruct == 0)
  197209. return false;
  197210. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  197211. if (pngInfoStruct == 0)
  197212. {
  197213. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  197214. return false;
  197215. }
  197216. png_set_write_fn (pngWriteStruct, &out, pngWriteDataCallback, 0);
  197217. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  197218. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  197219. : PNG_COLOR_TYPE_RGB,
  197220. PNG_INTERLACE_NONE,
  197221. PNG_COMPRESSION_TYPE_BASE,
  197222. PNG_FILTER_TYPE_BASE);
  197223. png_bytep rowData = (png_bytep) juce_malloc (width * 4 * sizeof (png_byte));
  197224. png_color_8 sig_bit;
  197225. sig_bit.red = 8;
  197226. sig_bit.green = 8;
  197227. sig_bit.blue = 8;
  197228. sig_bit.alpha = 8;
  197229. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  197230. png_write_info (pngWriteStruct, pngInfoStruct);
  197231. png_set_shift (pngWriteStruct, &sig_bit);
  197232. png_set_packing (pngWriteStruct);
  197233. for (int y = 0; y < height; ++y)
  197234. {
  197235. uint8* dst = (uint8*) rowData;
  197236. int stride, pixelStride;
  197237. const uint8* pixels = image.lockPixelDataReadOnly (0, y, width, 1, stride, pixelStride);
  197238. const uint8* src = pixels;
  197239. if (image.hasAlphaChannel())
  197240. {
  197241. for (int i = width; --i >= 0;)
  197242. {
  197243. PixelARGB p (*(const PixelARGB*) src);
  197244. p.unpremultiply();
  197245. *dst++ = p.getRed();
  197246. *dst++ = p.getGreen();
  197247. *dst++ = p.getBlue();
  197248. *dst++ = p.getAlpha();
  197249. src += pixelStride;
  197250. }
  197251. }
  197252. else
  197253. {
  197254. for (int i = width; --i >= 0;)
  197255. {
  197256. *dst++ = ((const PixelRGB*) src)->getRed();
  197257. *dst++ = ((const PixelRGB*) src)->getGreen();
  197258. *dst++ = ((const PixelRGB*) src)->getBlue();
  197259. src += pixelStride;
  197260. }
  197261. }
  197262. png_write_rows (pngWriteStruct, &rowData, 1);
  197263. image.releasePixelDataReadOnly (pixels);
  197264. }
  197265. juce_free (rowData);
  197266. png_write_end (pngWriteStruct, pngInfoStruct);
  197267. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  197268. out.flush();
  197269. return true;
  197270. }
  197271. END_JUCE_NAMESPACE
  197272. /********* End of inlined file: juce_PNGLoader.cpp *********/
  197273. #endif
  197274. //==============================================================================
  197275. #if JUCE_WIN32
  197276. /********* Start of inlined file: juce_win32_Files.cpp *********/
  197277. #ifdef _MSC_VER
  197278. #pragma warning (disable: 4514)
  197279. #pragma warning (push)
  197280. #endif
  197281. #include <ctime>
  197282. #ifndef _WIN32_IE
  197283. #define _WIN32_IE 0x0400
  197284. #endif
  197285. #include <shlobj.h>
  197286. #ifndef CSIDL_MYMUSIC
  197287. #define CSIDL_MYMUSIC 0x000d
  197288. #endif
  197289. #ifndef CSIDL_MYVIDEO
  197290. #define CSIDL_MYVIDEO 0x000e
  197291. #endif
  197292. BEGIN_JUCE_NAMESPACE
  197293. #ifdef _MSC_VER
  197294. #pragma warning (pop)
  197295. #endif
  197296. const tchar File::separator = T('\\');
  197297. const tchar* File::separatorString = T("\\");
  197298. bool juce_fileExists (const String& fileName,
  197299. const bool dontCountDirectories) throw()
  197300. {
  197301. if (fileName.isEmpty())
  197302. return false;
  197303. const DWORD attr = GetFileAttributes (fileName);
  197304. return dontCountDirectories ? ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
  197305. : (attr != 0xffffffff);
  197306. }
  197307. bool juce_isDirectory (const String& fileName) throw()
  197308. {
  197309. const DWORD attr = GetFileAttributes (fileName);
  197310. return (attr != 0xffffffff)
  197311. && ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0);
  197312. }
  197313. bool juce_canWriteToFile (const String& fileName) throw()
  197314. {
  197315. const DWORD attr = GetFileAttributes (fileName);
  197316. return ((attr & FILE_ATTRIBUTE_READONLY) == 0);
  197317. }
  197318. bool juce_setFileReadOnly (const String& fileName,
  197319. bool isReadOnly)
  197320. {
  197321. DWORD attr = GetFileAttributes (fileName);
  197322. if (attr == 0xffffffff)
  197323. return false;
  197324. if (isReadOnly != juce_canWriteToFile (fileName))
  197325. return true;
  197326. if (isReadOnly)
  197327. attr |= FILE_ATTRIBUTE_READONLY;
  197328. else
  197329. attr &= ~FILE_ATTRIBUTE_READONLY;
  197330. return SetFileAttributes (fileName, attr) != FALSE;
  197331. }
  197332. bool File::isHidden() const throw()
  197333. {
  197334. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  197335. }
  197336. bool juce_deleteFile (const String& fileName) throw()
  197337. {
  197338. if (juce_isDirectory (fileName))
  197339. return RemoveDirectory (fileName) != 0;
  197340. return DeleteFile (fileName) != 0;
  197341. }
  197342. bool juce_moveFile (const String& source, const String& dest) throw()
  197343. {
  197344. return MoveFile (source, dest) != 0;
  197345. }
  197346. bool juce_copyFile (const String& source, const String& dest) throw()
  197347. {
  197348. return CopyFile (source, dest, false) != 0;
  197349. }
  197350. void juce_createDirectory (const String& fileName) throw()
  197351. {
  197352. if (! juce_fileExists (fileName, true))
  197353. {
  197354. CreateDirectory (fileName, 0);
  197355. }
  197356. }
  197357. // return 0 if not possible
  197358. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  197359. {
  197360. HANDLE h;
  197361. if (forWriting)
  197362. {
  197363. h = CreateFile (fileName, GENERIC_WRITE, FILE_SHARE_READ, 0,
  197364. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  197365. if (h != INVALID_HANDLE_VALUE)
  197366. SetFilePointer (h, 0, 0, FILE_END);
  197367. else
  197368. h = 0;
  197369. }
  197370. else
  197371. {
  197372. h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  197373. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  197374. if (h == INVALID_HANDLE_VALUE)
  197375. h = 0;
  197376. }
  197377. return (void*) h;
  197378. }
  197379. void juce_fileClose (void* handle) throw()
  197380. {
  197381. CloseHandle (handle);
  197382. }
  197383. int juce_fileRead (void* handle, void* buffer, int size) throw()
  197384. {
  197385. DWORD num = 0;
  197386. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  197387. return num;
  197388. }
  197389. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  197390. {
  197391. DWORD num;
  197392. WriteFile ((HANDLE) handle,
  197393. buffer, size,
  197394. &num, 0);
  197395. return num;
  197396. }
  197397. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  197398. {
  197399. LARGE_INTEGER li;
  197400. li.QuadPart = pos;
  197401. li.LowPart = SetFilePointer ((HANDLE) handle,
  197402. li.LowPart,
  197403. &li.HighPart,
  197404. FILE_BEGIN); // (returns -1 if it fails)
  197405. return li.QuadPart;
  197406. }
  197407. int64 juce_fileGetPosition (void* handle) throw()
  197408. {
  197409. LARGE_INTEGER li;
  197410. li.QuadPart = 0;
  197411. li.LowPart = SetFilePointer ((HANDLE) handle,
  197412. 0, &li.HighPart,
  197413. FILE_CURRENT); // (returns -1 if it fails)
  197414. return jmax ((int64) 0, li.QuadPart);
  197415. }
  197416. void juce_fileFlush (void* handle) throw()
  197417. {
  197418. FlushFileBuffers ((HANDLE) handle);
  197419. }
  197420. int64 juce_getFileSize (const String& fileName) throw()
  197421. {
  197422. WIN32_FILE_ATTRIBUTE_DATA attributes;
  197423. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  197424. {
  197425. return (((int64) attributes.nFileSizeHigh) << 32)
  197426. | attributes.nFileSizeLow;
  197427. }
  197428. return 0;
  197429. }
  197430. static int64 fileTimeToTime (const FILETIME* const ft) throw()
  197431. {
  197432. // tell me if this fails!
  197433. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME));
  197434. #if JUCE_GCC
  197435. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000LL) / 10000;
  197436. #else
  197437. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000) / 10000;
  197438. #endif
  197439. }
  197440. static void timeToFileTime (const int64 time, FILETIME* const ft) throw()
  197441. {
  197442. #if JUCE_GCC
  197443. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000LL;
  197444. #else
  197445. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000;
  197446. #endif
  197447. }
  197448. void juce_getFileTimes (const String& fileName,
  197449. int64& modificationTime,
  197450. int64& accessTime,
  197451. int64& creationTime) throw()
  197452. {
  197453. WIN32_FILE_ATTRIBUTE_DATA attributes;
  197454. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  197455. {
  197456. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  197457. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  197458. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  197459. }
  197460. else
  197461. {
  197462. creationTime = accessTime = modificationTime = 0;
  197463. }
  197464. }
  197465. bool juce_setFileTimes (const String& fileName,
  197466. int64 modificationTime,
  197467. int64 accessTime,
  197468. int64 creationTime) throw()
  197469. {
  197470. FILETIME m, a, c;
  197471. if (modificationTime > 0)
  197472. timeToFileTime (modificationTime, &m);
  197473. if (accessTime > 0)
  197474. timeToFileTime (accessTime, &a);
  197475. if (creationTime > 0)
  197476. timeToFileTime (creationTime, &c);
  197477. void* const h = juce_fileOpen (fileName, true);
  197478. bool ok = false;
  197479. if (h != 0)
  197480. {
  197481. ok = SetFileTime ((HANDLE) h,
  197482. (creationTime > 0) ? &c : 0,
  197483. (accessTime > 0) ? &a : 0,
  197484. (modificationTime > 0) ? &m : 0) != 0;
  197485. juce_fileClose (h);
  197486. }
  197487. return ok;
  197488. }
  197489. // return '\0' separated list of strings
  197490. const StringArray juce_getFileSystemRoots() throw()
  197491. {
  197492. TCHAR buffer [2048];
  197493. buffer[0] = 0;
  197494. buffer[1] = 0;
  197495. GetLogicalDriveStrings (2048, buffer);
  197496. TCHAR* n = buffer;
  197497. StringArray roots;
  197498. while (*n != 0)
  197499. {
  197500. roots.add (String (n));
  197501. while (*n++ != 0)
  197502. {
  197503. }
  197504. }
  197505. roots.sort (true);
  197506. return roots;
  197507. }
  197508. const String juce_getVolumeLabel (const String& filenameOnVolume,
  197509. int& volumeSerialNumber) throw()
  197510. {
  197511. TCHAR n [4];
  197512. n[0] = *(const TCHAR*) filenameOnVolume;
  197513. n[1] = L':';
  197514. n[2] = L'\\';
  197515. n[3] = 0;
  197516. TCHAR dest [64];
  197517. DWORD serialNum;
  197518. if (! GetVolumeInformation (n, dest, 64, (DWORD*) &serialNum, 0, 0, 0, 0))
  197519. {
  197520. dest[0] = 0;
  197521. serialNum = 0;
  197522. }
  197523. volumeSerialNumber = serialNum;
  197524. return String (dest);
  197525. }
  197526. int64 File::getBytesFreeOnVolume() const throw()
  197527. {
  197528. String fn (getFullPathName());
  197529. if (fn[1] == T(':'))
  197530. fn = fn.substring (0, 2) + T("\\");
  197531. ULARGE_INTEGER spc;
  197532. ULARGE_INTEGER tot;
  197533. ULARGE_INTEGER totFree;
  197534. if (GetDiskFreeSpaceEx (fn, &spc, &tot, &totFree))
  197535. return (int64)(spc.QuadPart);
  197536. return 0;
  197537. }
  197538. static unsigned int getWindowsDriveType (const String& fileName) throw()
  197539. {
  197540. TCHAR n[4];
  197541. n[0] = *(const TCHAR*) fileName;
  197542. n[1] = L':';
  197543. n[2] = L'\\';
  197544. n[3] = 0;
  197545. return GetDriveType (n);
  197546. }
  197547. bool File::isOnCDRomDrive() const throw()
  197548. {
  197549. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  197550. }
  197551. bool File::isOnHardDisk() const throw()
  197552. {
  197553. if (fullPath.isEmpty())
  197554. return false;
  197555. const unsigned int n = getWindowsDriveType (getFullPathName());
  197556. if (fullPath.toLowerCase()[0] <= 'b'
  197557. && fullPath[1] == T(':'))
  197558. {
  197559. return n != DRIVE_REMOVABLE;
  197560. }
  197561. else
  197562. {
  197563. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  197564. }
  197565. }
  197566. bool File::isOnRemovableDrive() const throw()
  197567. {
  197568. if (fullPath.isEmpty())
  197569. return false;
  197570. const unsigned int n = getWindowsDriveType (getFullPathName());
  197571. return n == DRIVE_CDROM
  197572. || n == DRIVE_REMOTE
  197573. || n == DRIVE_REMOVABLE
  197574. || n == DRIVE_RAMDISK;
  197575. }
  197576. #define MAX_PATH_CHARS (MAX_PATH + 256)
  197577. static const File juce_getSpecialFolderPath (int type) throw()
  197578. {
  197579. WCHAR path [MAX_PATH_CHARS];
  197580. if (SHGetSpecialFolderPath (0, path, type, 0))
  197581. return File (String (path));
  197582. return File::nonexistent;
  197583. }
  197584. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  197585. {
  197586. int csidlType = 0;
  197587. switch (type)
  197588. {
  197589. case userHomeDirectory:
  197590. case userDocumentsDirectory:
  197591. csidlType = CSIDL_PERSONAL;
  197592. break;
  197593. case userDesktopDirectory:
  197594. csidlType = CSIDL_DESKTOP;
  197595. break;
  197596. case userApplicationDataDirectory:
  197597. csidlType = CSIDL_APPDATA;
  197598. break;
  197599. case commonApplicationDataDirectory:
  197600. csidlType = CSIDL_COMMON_APPDATA;
  197601. break;
  197602. case globalApplicationsDirectory:
  197603. csidlType = CSIDL_PROGRAM_FILES;
  197604. break;
  197605. case userMusicDirectory:
  197606. csidlType = CSIDL_MYMUSIC;
  197607. break;
  197608. case userMoviesDirectory:
  197609. csidlType = CSIDL_MYVIDEO;
  197610. break;
  197611. case tempDirectory:
  197612. {
  197613. WCHAR dest [2048];
  197614. dest[0] = 0;
  197615. GetTempPath (2048, dest);
  197616. return File (String (dest));
  197617. }
  197618. case currentExecutableFile:
  197619. case currentApplicationFile:
  197620. {
  197621. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  197622. WCHAR dest [MAX_PATH_CHARS];
  197623. dest[0] = 0;
  197624. GetModuleFileName (moduleHandle, dest, MAX_PATH_CHARS);
  197625. return File (String (dest));
  197626. }
  197627. break;
  197628. default:
  197629. jassertfalse // unknown type?
  197630. return File::nonexistent;
  197631. }
  197632. return juce_getSpecialFolderPath (csidlType);
  197633. }
  197634. void juce_setCurrentExecutableFileName (const String&) throw()
  197635. {
  197636. // n/a on windows
  197637. }
  197638. const File File::getCurrentWorkingDirectory() throw()
  197639. {
  197640. WCHAR dest [MAX_PATH_CHARS];
  197641. dest[0] = 0;
  197642. GetCurrentDirectory (MAX_PATH_CHARS, dest);
  197643. return File (String (dest));
  197644. }
  197645. bool File::setAsCurrentWorkingDirectory() const throw()
  197646. {
  197647. return SetCurrentDirectory (getFullPathName()) != FALSE;
  197648. }
  197649. template <class FindDataType>
  197650. static void getFindFileInfo (FindDataType& findData,
  197651. String& filename, bool* const isDir, bool* const isHidden,
  197652. int64* const fileSize, Time* const modTime, Time* const creationTime,
  197653. bool* const isReadOnly) throw()
  197654. {
  197655. filename = findData.cFileName;
  197656. if (isDir != 0)
  197657. *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  197658. if (isHidden != 0)
  197659. *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  197660. if (fileSize != 0)
  197661. *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  197662. if (modTime != 0)
  197663. *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  197664. if (creationTime != 0)
  197665. *creationTime = fileTimeToTime (&findData.ftCreationTime);
  197666. if (isReadOnly != 0)
  197667. *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  197668. }
  197669. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResult,
  197670. bool* isDir, bool* isHidden, int64* fileSize,
  197671. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  197672. {
  197673. String wc (directory);
  197674. if (! wc.endsWithChar (File::separator))
  197675. wc += File::separator;
  197676. wc += wildCard;
  197677. WIN32_FIND_DATA findData;
  197678. HANDLE h = FindFirstFile (wc, &findData);
  197679. if (h != INVALID_HANDLE_VALUE)
  197680. {
  197681. getFindFileInfo (findData, firstResult, isDir, isHidden, fileSize,
  197682. modTime, creationTime, isReadOnly);
  197683. return h;
  197684. }
  197685. firstResult = String::empty;
  197686. return 0;
  197687. }
  197688. bool juce_findFileNext (void* handle, String& resultFile,
  197689. bool* isDir, bool* isHidden, int64* fileSize,
  197690. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  197691. {
  197692. WIN32_FIND_DATA findData;
  197693. if (handle != 0 && FindNextFile ((HANDLE) handle, &findData) != 0)
  197694. {
  197695. getFindFileInfo (findData, resultFile, isDir, isHidden, fileSize,
  197696. modTime, creationTime, isReadOnly);
  197697. return true;
  197698. }
  197699. resultFile = String::empty;
  197700. return false;
  197701. }
  197702. void juce_findFileClose (void* handle) throw()
  197703. {
  197704. FindClose (handle);
  197705. }
  197706. bool juce_launchFile (const String& fileName,
  197707. const String& parameters) throw()
  197708. {
  197709. HINSTANCE hInstance = 0;
  197710. JUCE_TRY
  197711. {
  197712. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  197713. }
  197714. JUCE_CATCH_ALL
  197715. return hInstance > (HINSTANCE) 32;
  197716. }
  197717. struct NamedPipeInternal
  197718. {
  197719. HANDLE pipeH;
  197720. HANDLE cancelEvent;
  197721. bool connected, createdPipe;
  197722. NamedPipeInternal()
  197723. : pipeH (0),
  197724. cancelEvent (0),
  197725. connected (false),
  197726. createdPipe (false)
  197727. {
  197728. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  197729. }
  197730. ~NamedPipeInternal()
  197731. {
  197732. disconnect();
  197733. if (pipeH != 0)
  197734. CloseHandle (pipeH);
  197735. CloseHandle (cancelEvent);
  197736. }
  197737. bool connect (const int timeOutMs)
  197738. {
  197739. if (! createdPipe)
  197740. return true;
  197741. if (! connected)
  197742. {
  197743. OVERLAPPED over;
  197744. zerostruct (over);
  197745. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  197746. if (ConnectNamedPipe (pipeH, &over))
  197747. {
  197748. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  197749. }
  197750. else
  197751. {
  197752. const int err = GetLastError();
  197753. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  197754. {
  197755. HANDLE handles[] = { over.hEvent, cancelEvent };
  197756. if (WaitForMultipleObjects (2, handles, FALSE,
  197757. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  197758. connected = true;
  197759. }
  197760. else if (err == ERROR_PIPE_CONNECTED)
  197761. {
  197762. connected = true;
  197763. }
  197764. }
  197765. CloseHandle (over.hEvent);
  197766. }
  197767. return connected;
  197768. }
  197769. void disconnect()
  197770. {
  197771. if (connected)
  197772. {
  197773. DisconnectNamedPipe (pipeH);
  197774. connected = false;
  197775. }
  197776. }
  197777. };
  197778. void NamedPipe::close()
  197779. {
  197780. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197781. delete intern;
  197782. internal = 0;
  197783. }
  197784. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  197785. {
  197786. close();
  197787. NamedPipeInternal* const intern = new NamedPipeInternal();
  197788. String file ("\\\\.\\pipe\\");
  197789. file += pipeName;
  197790. intern->createdPipe = createPipe;
  197791. if (createPipe)
  197792. {
  197793. intern->pipeH = CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  197794. 1, 64, 64, 0, NULL);
  197795. }
  197796. else
  197797. {
  197798. intern->pipeH = CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING,
  197799. FILE_FLAG_OVERLAPPED, 0);
  197800. }
  197801. if (intern->pipeH != INVALID_HANDLE_VALUE)
  197802. {
  197803. internal = intern;
  197804. return true;
  197805. }
  197806. delete intern;
  197807. return false;
  197808. }
  197809. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  197810. {
  197811. int bytesRead = -1;
  197812. bool waitAgain = true;
  197813. while (waitAgain && internal != 0)
  197814. {
  197815. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197816. waitAgain = false;
  197817. if (! intern->connect (timeOutMilliseconds))
  197818. break;
  197819. if (maxBytesToRead <= 0)
  197820. return 0;
  197821. OVERLAPPED over;
  197822. zerostruct (over);
  197823. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  197824. unsigned long numRead;
  197825. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  197826. {
  197827. bytesRead = (int) numRead;
  197828. }
  197829. else if (GetLastError() == ERROR_IO_PENDING)
  197830. {
  197831. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  197832. if (WaitForMultipleObjects (2, handles, FALSE,
  197833. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  197834. : INFINITE) == WAIT_OBJECT_0)
  197835. {
  197836. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  197837. {
  197838. bytesRead = (int) numRead;
  197839. }
  197840. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  197841. {
  197842. intern->disconnect();
  197843. waitAgain = true;
  197844. }
  197845. }
  197846. }
  197847. else
  197848. {
  197849. waitAgain = internal != 0;
  197850. Sleep (5);
  197851. }
  197852. CloseHandle (over.hEvent);
  197853. }
  197854. return bytesRead;
  197855. }
  197856. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  197857. {
  197858. int bytesWritten = -1;
  197859. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197860. if (intern != 0 && intern->connect (timeOutMilliseconds))
  197861. {
  197862. if (numBytesToWrite <= 0)
  197863. return 0;
  197864. OVERLAPPED over;
  197865. zerostruct (over);
  197866. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  197867. unsigned long numWritten;
  197868. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  197869. {
  197870. bytesWritten = (int) numWritten;
  197871. }
  197872. else if (GetLastError() == ERROR_IO_PENDING)
  197873. {
  197874. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  197875. if (WaitForMultipleObjects (2, handles, FALSE, timeOutMilliseconds >= 0 ? timeOutMilliseconds
  197876. : INFINITE) == WAIT_OBJECT_0)
  197877. {
  197878. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  197879. {
  197880. bytesWritten = (int) numWritten;
  197881. }
  197882. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  197883. {
  197884. intern->disconnect();
  197885. }
  197886. }
  197887. }
  197888. CloseHandle (over.hEvent);
  197889. }
  197890. return bytesWritten;
  197891. }
  197892. void NamedPipe::cancelPendingReads()
  197893. {
  197894. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197895. if (intern != 0)
  197896. SetEvent (intern->cancelEvent);
  197897. }
  197898. END_JUCE_NAMESPACE
  197899. /********* End of inlined file: juce_win32_Files.cpp *********/
  197900. /********* Start of inlined file: juce_win32_Network.cpp *********/
  197901. #ifdef _MSC_VER
  197902. #pragma warning (disable: 4514)
  197903. #pragma warning (push)
  197904. #endif
  197905. #include <wininet.h>
  197906. #include <nb30.h>
  197907. #include <iphlpapi.h>
  197908. #include <mapi.h>
  197909. BEGIN_JUCE_NAMESPACE
  197910. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  197911. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  197912. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  197913. #ifndef DOXYGEN
  197914. // use with DynamicLibraryLoader to simplify importing functions
  197915. //
  197916. // functionName: function to import
  197917. // localFunctionName: name you want to use to actually call it (must be different)
  197918. // returnType: the return type
  197919. // object: the DynamicLibraryLoader to use
  197920. // params: list of params (bracketed)
  197921. //
  197922. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  197923. typedef returnType (WINAPI *type##localFunctionName) params; \
  197924. type##localFunctionName localFunctionName \
  197925. = (type##localFunctionName)object.findProcAddress (#functionName);
  197926. // loads and unloads a DLL automatically
  197927. class JUCE_API DynamicLibraryLoader
  197928. {
  197929. public:
  197930. DynamicLibraryLoader (const String& name);
  197931. ~DynamicLibraryLoader();
  197932. void* findProcAddress (const String& functionName);
  197933. private:
  197934. void* libHandle;
  197935. };
  197936. #endif
  197937. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  197938. /********* End of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  197939. #ifndef INTERNET_FLAG_NEED_FILE
  197940. #define INTERNET_FLAG_NEED_FILE 0x00000010
  197941. #endif
  197942. #ifdef _MSC_VER
  197943. #pragma warning (pop)
  197944. #endif
  197945. bool juce_isOnLine()
  197946. {
  197947. DWORD connectionType;
  197948. return InternetGetConnectedState (&connectionType, 0) != 0
  197949. || (connectionType & (INTERNET_CONNECTION_LAN | INTERNET_CONNECTION_PROXY)) != 0;
  197950. }
  197951. struct ConnectionAndRequestStruct
  197952. {
  197953. HINTERNET connection, request;
  197954. };
  197955. static HINTERNET sessionHandle = 0;
  197956. void* juce_openInternetFile (const String& url,
  197957. const String& headers,
  197958. const MemoryBlock& postData,
  197959. const bool isPost,
  197960. URL::OpenStreamProgressCallback* callback,
  197961. void* callbackContext,
  197962. int timeOutMs)
  197963. {
  197964. if (sessionHandle == 0)
  197965. sessionHandle = InternetOpen (_T("juce"),
  197966. INTERNET_OPEN_TYPE_PRECONFIG,
  197967. 0, 0, 0);
  197968. if (sessionHandle != 0)
  197969. {
  197970. // break up the url..
  197971. TCHAR file[1024], server[1024];
  197972. URL_COMPONENTS uc;
  197973. zerostruct (uc);
  197974. uc.dwStructSize = sizeof (uc);
  197975. uc.dwUrlPathLength = sizeof (file);
  197976. uc.dwHostNameLength = sizeof (server);
  197977. uc.lpszUrlPath = file;
  197978. uc.lpszHostName = server;
  197979. if (InternetCrackUrl (url, 0, 0, &uc))
  197980. {
  197981. if (timeOutMs == 0)
  197982. timeOutMs = 30000;
  197983. else if (timeOutMs < 0)
  197984. timeOutMs = -1;
  197985. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  197986. const bool isFtp = url.startsWithIgnoreCase (T("ftp:"));
  197987. HINTERNET connection = InternetConnect (sessionHandle,
  197988. uc.lpszHostName,
  197989. uc.nPort,
  197990. _T(""), _T(""),
  197991. isFtp ? INTERNET_SERVICE_FTP
  197992. : INTERNET_SERVICE_HTTP,
  197993. 0, 0);
  197994. if (connection != 0)
  197995. {
  197996. if (isFtp)
  197997. {
  197998. HINTERNET request = FtpOpenFile (connection,
  197999. uc.lpszUrlPath,
  198000. GENERIC_READ,
  198001. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  198002. 0);
  198003. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  198004. result->connection = connection;
  198005. result->request = request;
  198006. return result;
  198007. }
  198008. else
  198009. {
  198010. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  198011. HINTERNET request = HttpOpenRequest (connection,
  198012. isPost ? _T("POST")
  198013. : _T("GET"),
  198014. uc.lpszUrlPath,
  198015. 0, 0, mimeTypes,
  198016. INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE,
  198017. 0);
  198018. if (request != 0)
  198019. {
  198020. INTERNET_BUFFERS buffers;
  198021. zerostruct (buffers);
  198022. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  198023. buffers.lpcszHeader = (LPCTSTR) headers;
  198024. buffers.dwHeadersLength = headers.length();
  198025. buffers.dwBufferTotal = (DWORD) postData.getSize();
  198026. ConnectionAndRequestStruct* result = 0;
  198027. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  198028. {
  198029. int bytesSent = 0;
  198030. for (;;)
  198031. {
  198032. const int bytesToDo = jmin (1024, postData.getSize() - bytesSent);
  198033. DWORD bytesDone = 0;
  198034. if (bytesToDo > 0
  198035. && ! InternetWriteFile (request,
  198036. ((const char*) postData.getData()) + bytesSent,
  198037. bytesToDo, &bytesDone))
  198038. {
  198039. break;
  198040. }
  198041. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  198042. {
  198043. result = new ConnectionAndRequestStruct();
  198044. result->connection = connection;
  198045. result->request = request;
  198046. HttpEndRequest (request, 0, 0, 0);
  198047. return result;
  198048. }
  198049. bytesSent += bytesDone;
  198050. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  198051. break;
  198052. }
  198053. }
  198054. InternetCloseHandle (request);
  198055. }
  198056. InternetCloseHandle (connection);
  198057. }
  198058. }
  198059. }
  198060. }
  198061. return 0;
  198062. }
  198063. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  198064. {
  198065. DWORD bytesRead = 0;
  198066. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  198067. if (crs != 0)
  198068. InternetReadFile (crs->request,
  198069. buffer, bytesToRead,
  198070. &bytesRead);
  198071. return bytesRead;
  198072. }
  198073. int juce_seekInInternetFile (void* handle, int newPosition)
  198074. {
  198075. if (handle != 0)
  198076. {
  198077. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  198078. return InternetSetFilePointer (crs->request,
  198079. newPosition, 0,
  198080. FILE_BEGIN, 0);
  198081. }
  198082. else
  198083. {
  198084. return -1;
  198085. }
  198086. }
  198087. void juce_closeInternetFile (void* handle)
  198088. {
  198089. if (handle != 0)
  198090. {
  198091. ConnectionAndRequestStruct* const crs = (ConnectionAndRequestStruct*) handle;
  198092. InternetCloseHandle (crs->request);
  198093. InternetCloseHandle (crs->connection);
  198094. delete crs;
  198095. }
  198096. }
  198097. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  198098. {
  198099. int numFound = 0;
  198100. DynamicLibraryLoader dll ("iphlpapi.dll");
  198101. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  198102. if (getAdaptersInfo != 0)
  198103. {
  198104. ULONG len = sizeof (IP_ADAPTER_INFO);
  198105. MemoryBlock mb;
  198106. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  198107. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  198108. {
  198109. mb.setSize (len);
  198110. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  198111. }
  198112. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  198113. {
  198114. PIP_ADAPTER_INFO adapter = adapterInfo;
  198115. while (adapter != 0)
  198116. {
  198117. int64 mac = 0;
  198118. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  198119. mac = (mac << 8) | adapter->Address[i];
  198120. if (littleEndian)
  198121. mac = (int64) swapByteOrder ((uint64) mac);
  198122. if (numFound < maxNum && mac != 0)
  198123. addresses [numFound++] = mac;
  198124. adapter = adapter->Next;
  198125. }
  198126. }
  198127. }
  198128. return numFound;
  198129. }
  198130. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  198131. {
  198132. int numFound = 0;
  198133. DynamicLibraryLoader dll ("netapi32.dll");
  198134. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  198135. if (NetbiosCall != 0)
  198136. {
  198137. NCB ncb;
  198138. zerostruct (ncb);
  198139. typedef struct _ASTAT_
  198140. {
  198141. ADAPTER_STATUS adapt;
  198142. NAME_BUFFER NameBuff [30];
  198143. } ASTAT;
  198144. ASTAT astat;
  198145. zerostruct (astat);
  198146. LANA_ENUM enums;
  198147. zerostruct (enums);
  198148. ncb.ncb_command = NCBENUM;
  198149. ncb.ncb_buffer = (unsigned char*) &enums;
  198150. ncb.ncb_length = sizeof (LANA_ENUM);
  198151. NetbiosCall (&ncb);
  198152. for (int i = 0; i < enums.length; ++i)
  198153. {
  198154. zerostruct (ncb);
  198155. ncb.ncb_command = NCBRESET;
  198156. ncb.ncb_lana_num = enums.lana[i];
  198157. if (NetbiosCall (&ncb) == 0)
  198158. {
  198159. zerostruct (ncb);
  198160. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  198161. ncb.ncb_command = NCBASTAT;
  198162. ncb.ncb_lana_num = enums.lana[i];
  198163. ncb.ncb_buffer = (unsigned char*) &astat;
  198164. ncb.ncb_length = sizeof (ASTAT);
  198165. if (NetbiosCall (&ncb) == 0)
  198166. {
  198167. if (astat.adapt.adapter_type == 0xfe)
  198168. {
  198169. int64 mac = 0;
  198170. for (unsigned int i = 0; i < 6; ++i)
  198171. mac = (mac << 8) | astat.adapt.adapter_address[i];
  198172. if (littleEndian)
  198173. mac = (int64) swapByteOrder ((uint64) mac);
  198174. if (numFound < maxNum && mac != 0)
  198175. addresses [numFound++] = mac;
  198176. }
  198177. }
  198178. }
  198179. }
  198180. }
  198181. return numFound;
  198182. }
  198183. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  198184. {
  198185. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  198186. if (numFound == 0)
  198187. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  198188. return numFound;
  198189. }
  198190. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  198191. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  198192. const String& emailSubject,
  198193. const String& bodyText,
  198194. const StringArray& filesToAttach)
  198195. {
  198196. HMODULE h = LoadLibraryA ("MAPI32.dll");
  198197. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  198198. bool ok = false;
  198199. if (mapiSendMail != 0)
  198200. {
  198201. MapiMessage message;
  198202. zerostruct (message);
  198203. message.lpszSubject = (LPSTR) (LPCSTR) emailSubject;
  198204. message.lpszNoteText = (LPSTR) (LPCSTR) bodyText;
  198205. MapiRecipDesc recip;
  198206. zerostruct (recip);
  198207. recip.ulRecipClass = MAPI_TO;
  198208. recip.lpszName = (LPSTR) (LPCSTR) targetEmailAddress;
  198209. message.nRecipCount = 1;
  198210. message.lpRecips = &recip;
  198211. MemoryBlock mb (sizeof (MapiFileDesc) * filesToAttach.size());
  198212. mb.fillWith (0);
  198213. MapiFileDesc* files = (MapiFileDesc*) mb.getData();
  198214. message.nFileCount = filesToAttach.size();
  198215. message.lpFiles = files;
  198216. for (int i = 0; i < filesToAttach.size(); ++i)
  198217. {
  198218. files[i].nPosition = (ULONG) -1;
  198219. files[i].lpszPathName = (LPSTR) (LPCSTR) filesToAttach [i];
  198220. }
  198221. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  198222. }
  198223. FreeLibrary (h);
  198224. return ok;
  198225. }
  198226. END_JUCE_NAMESPACE
  198227. /********* End of inlined file: juce_win32_Network.cpp *********/
  198228. /********* Start of inlined file: juce_win32_Misc.cpp *********/
  198229. BEGIN_JUCE_NAMESPACE
  198230. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198231. bool AlertWindow::showNativeDialogBox (const String& title,
  198232. const String& bodyText,
  198233. bool isOkCancel)
  198234. {
  198235. return MessageBox (0, bodyText, title,
  198236. (isOkCancel) ? MB_OKCANCEL
  198237. : MB_OK) == IDOK;
  198238. }
  198239. #endif
  198240. void PlatformUtilities::beep()
  198241. {
  198242. MessageBeep (MB_OK);
  198243. }
  198244. #if JUCE_MSVC
  198245. #pragma warning (disable : 4127) // "Conditional expression is constant" warning
  198246. #endif
  198247. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198248. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  198249. {
  198250. if (OpenClipboard (0) != 0)
  198251. {
  198252. if (EmptyClipboard() != 0)
  198253. {
  198254. const int len = text.length();
  198255. if (len > 0)
  198256. {
  198257. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  198258. (len + 1) * sizeof (wchar_t));
  198259. if (bufH != 0)
  198260. {
  198261. wchar_t* const data = (wchar_t*) GlobalLock (bufH);
  198262. text.copyToBuffer (data, len);
  198263. GlobalUnlock (bufH);
  198264. SetClipboardData (CF_UNICODETEXT, bufH);
  198265. }
  198266. }
  198267. }
  198268. CloseClipboard();
  198269. }
  198270. }
  198271. const String SystemClipboard::getTextFromClipboard() throw()
  198272. {
  198273. String result;
  198274. if (OpenClipboard (0) != 0)
  198275. {
  198276. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  198277. if (bufH != 0)
  198278. {
  198279. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  198280. if (data != 0)
  198281. {
  198282. result = String (data, (int) (GlobalSize (bufH) / sizeof (tchar)));
  198283. GlobalUnlock (bufH);
  198284. }
  198285. }
  198286. CloseClipboard();
  198287. }
  198288. return result;
  198289. }
  198290. #endif
  198291. END_JUCE_NAMESPACE
  198292. /********* End of inlined file: juce_win32_Misc.cpp *********/
  198293. /********* Start of inlined file: juce_win32_PlatformUtils.cpp *********/
  198294. #ifdef _MSC_VER
  198295. #pragma warning (disable: 4514)
  198296. #pragma warning (push)
  198297. #endif
  198298. #include <float.h>
  198299. BEGIN_JUCE_NAMESPACE
  198300. #ifdef _MSC_VER
  198301. #pragma warning (pop)
  198302. #endif
  198303. static HKEY findKeyForPath (String name,
  198304. const bool createForWriting,
  198305. String& valueName) throw()
  198306. {
  198307. HKEY rootKey = 0;
  198308. if (name.startsWithIgnoreCase (T("HKEY_CURRENT_USER\\")))
  198309. rootKey = HKEY_CURRENT_USER;
  198310. else if (name.startsWithIgnoreCase (T("HKEY_LOCAL_MACHINE\\")))
  198311. rootKey = HKEY_LOCAL_MACHINE;
  198312. else if (name.startsWithIgnoreCase (T("HKEY_CLASSES_ROOT\\")))
  198313. rootKey = HKEY_CLASSES_ROOT;
  198314. if (rootKey != 0)
  198315. {
  198316. name = name.substring (name.indexOfChar (T('\\')) + 1);
  198317. const int lastSlash = name.lastIndexOfChar (T('\\'));
  198318. valueName = name.substring (lastSlash + 1);
  198319. name = name.substring (0, lastSlash);
  198320. HKEY key;
  198321. DWORD result;
  198322. if (createForWriting)
  198323. {
  198324. if (RegCreateKeyEx (rootKey, name, 0, L"", REG_OPTION_NON_VOLATILE,
  198325. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  198326. return key;
  198327. }
  198328. else
  198329. {
  198330. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  198331. return key;
  198332. }
  198333. }
  198334. return 0;
  198335. }
  198336. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  198337. const String& defaultValue)
  198338. {
  198339. String valueName, s;
  198340. HKEY k = findKeyForPath (regValuePath, false, valueName);
  198341. if (k != 0)
  198342. {
  198343. WCHAR buffer [2048];
  198344. unsigned long bufferSize = sizeof (buffer);
  198345. DWORD type = REG_SZ;
  198346. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  198347. s = buffer;
  198348. else
  198349. s = defaultValue;
  198350. RegCloseKey (k);
  198351. }
  198352. return s;
  198353. }
  198354. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  198355. const String& value)
  198356. {
  198357. String valueName;
  198358. HKEY k = findKeyForPath (regValuePath, true, valueName);
  198359. if (k != 0)
  198360. {
  198361. RegSetValueEx (k, valueName, 0, REG_SZ,
  198362. (const BYTE*) (const WCHAR*) value,
  198363. sizeof (WCHAR) * (value.length() + 1));
  198364. RegCloseKey (k);
  198365. }
  198366. }
  198367. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  198368. {
  198369. bool exists = false;
  198370. String valueName;
  198371. HKEY k = findKeyForPath (regValuePath, false, valueName);
  198372. if (k != 0)
  198373. {
  198374. unsigned char buffer [2048];
  198375. unsigned long bufferSize = sizeof (buffer);
  198376. DWORD type = 0;
  198377. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  198378. exists = true;
  198379. RegCloseKey (k);
  198380. }
  198381. return exists;
  198382. }
  198383. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  198384. {
  198385. String valueName;
  198386. HKEY k = findKeyForPath (regValuePath, true, valueName);
  198387. if (k != 0)
  198388. {
  198389. RegDeleteValue (k, valueName);
  198390. RegCloseKey (k);
  198391. }
  198392. }
  198393. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  198394. {
  198395. String valueName;
  198396. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  198397. if (k != 0)
  198398. {
  198399. RegDeleteKey (k, valueName);
  198400. RegCloseKey (k);
  198401. }
  198402. }
  198403. bool juce_IsRunningInWine() throw()
  198404. {
  198405. HKEY key;
  198406. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  198407. {
  198408. RegCloseKey (key);
  198409. return true;
  198410. }
  198411. return false;
  198412. }
  198413. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams() throw()
  198414. {
  198415. String s (::GetCommandLineW());
  198416. StringArray tokens;
  198417. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  198418. return tokens.joinIntoString (T(" "), 1);
  198419. }
  198420. static void* currentModuleHandle = 0;
  198421. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  198422. {
  198423. if (currentModuleHandle == 0)
  198424. currentModuleHandle = GetModuleHandle (0);
  198425. return currentModuleHandle;
  198426. }
  198427. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  198428. {
  198429. currentModuleHandle = newHandle;
  198430. }
  198431. void PlatformUtilities::fpuReset()
  198432. {
  198433. #if JUCE_MSVC
  198434. _clearfp();
  198435. #endif
  198436. }
  198437. END_JUCE_NAMESPACE
  198438. /********* End of inlined file: juce_win32_PlatformUtils.cpp *********/
  198439. /********* Start of inlined file: juce_win32_SystemStats.cpp *********/
  198440. // Auto-link the other win32 libs that are needed by library calls..
  198441. #if defined (JUCE_DLL_BUILD) && JUCE_MSVC
  198442. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  198443. // Auto-links to various win32 libs that are needed by library calls..
  198444. #pragma comment(lib, "kernel32.lib")
  198445. #pragma comment(lib, "user32.lib")
  198446. #pragma comment(lib, "shell32.lib")
  198447. #pragma comment(lib, "gdi32.lib")
  198448. #pragma comment(lib, "vfw32.lib")
  198449. #pragma comment(lib, "comdlg32.lib")
  198450. #pragma comment(lib, "winmm.lib")
  198451. #pragma comment(lib, "wininet.lib")
  198452. #pragma comment(lib, "ole32.lib")
  198453. #pragma comment(lib, "advapi32.lib")
  198454. #pragma comment(lib, "ws2_32.lib")
  198455. #pragma comment(lib, "comsupp.lib")
  198456. #if JUCE_OPENGL
  198457. #pragma comment(lib, "OpenGL32.Lib")
  198458. #pragma comment(lib, "GlU32.Lib")
  198459. #endif
  198460. #if JUCE_QUICKTIME
  198461. #pragma comment (lib, "QTMLClient.lib")
  198462. #endif
  198463. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  198464. #endif
  198465. BEGIN_JUCE_NAMESPACE
  198466. extern void juce_updateMultiMonitorInfo() throw();
  198467. extern void juce_initialiseThreadEvents() throw();
  198468. void Logger::outputDebugString (const String& text) throw()
  198469. {
  198470. OutputDebugString (text + T("\n"));
  198471. }
  198472. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  198473. {
  198474. String text;
  198475. va_list args;
  198476. va_start (args, format);
  198477. text.vprintf(format, args);
  198478. outputDebugString (text);
  198479. }
  198480. static int64 hiResTicksPerSecond;
  198481. static double hiResTicksScaleFactor;
  198482. #if JUCE_USE_INTRINSICS
  198483. // CPU info functions using intrinsics...
  198484. #pragma intrinsic (__cpuid)
  198485. #pragma intrinsic (__rdtsc)
  198486. /*static unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0) throw()
  198487. {
  198488. int info [4];
  198489. __cpuid (info, 1);
  198490. if (familyModel != 0)
  198491. *familyModel = info [0];
  198492. if (extFeatures != 0)
  198493. *extFeatures = info[1];
  198494. return info[3];
  198495. }*/
  198496. const String SystemStats::getCpuVendor() throw()
  198497. {
  198498. int info [4];
  198499. __cpuid (info, 0);
  198500. char v [12];
  198501. memcpy (v, info + 1, 4);
  198502. memcpy (v + 4, info + 3, 4);
  198503. memcpy (v + 8, info + 2, 4);
  198504. return String (v, 12);
  198505. }
  198506. #else
  198507. // CPU info functions using old fashioned inline asm...
  198508. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0)
  198509. {
  198510. unsigned int cpu = 0;
  198511. unsigned int ext = 0;
  198512. unsigned int family = 0;
  198513. #if JUCE_GCC
  198514. unsigned int dummy = 0;
  198515. #endif
  198516. #ifndef __MINGW32__
  198517. __try
  198518. #endif
  198519. {
  198520. #if JUCE_GCC
  198521. __asm__ ("cpuid" : "=a" (family), "=b" (ext), "=c" (dummy),"=d" (cpu) : "a" (1));
  198522. #else
  198523. __asm
  198524. {
  198525. mov eax, 1
  198526. cpuid
  198527. mov cpu, edx
  198528. mov family, eax
  198529. mov ext, ebx
  198530. }
  198531. #endif
  198532. }
  198533. #ifndef __MINGW32__
  198534. __except (EXCEPTION_EXECUTE_HANDLER)
  198535. {
  198536. return 0;
  198537. }
  198538. #endif
  198539. if (familyModel != 0)
  198540. *familyModel = family;
  198541. if (extFeatures != 0)
  198542. *extFeatures = ext;
  198543. return cpu;
  198544. }*/
  198545. static void juce_getCpuVendor (char* const v)
  198546. {
  198547. int vendor[4];
  198548. zeromem (vendor, 16);
  198549. #ifdef JUCE_64BIT
  198550. #else
  198551. #ifndef __MINGW32__
  198552. __try
  198553. #endif
  198554. {
  198555. #if JUCE_GCC
  198556. unsigned int dummy = 0;
  198557. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  198558. #else
  198559. __asm
  198560. {
  198561. mov eax, 0
  198562. cpuid
  198563. mov [vendor], ebx
  198564. mov [vendor + 4], edx
  198565. mov [vendor + 8], ecx
  198566. }
  198567. #endif
  198568. }
  198569. #ifndef __MINGW32__
  198570. __except (EXCEPTION_EXECUTE_HANDLER)
  198571. {
  198572. *v = 0;
  198573. }
  198574. #endif
  198575. #endif
  198576. memcpy (v, vendor, 16);
  198577. }
  198578. const String SystemStats::getCpuVendor() throw()
  198579. {
  198580. char v [16];
  198581. juce_getCpuVendor (v);
  198582. return String (v, 16);
  198583. }
  198584. #endif
  198585. struct CPUFlags
  198586. {
  198587. bool hasMMX : 1;
  198588. bool hasSSE : 1;
  198589. bool hasSSE2 : 1;
  198590. bool has3DNow : 1;
  198591. };
  198592. static CPUFlags cpuFlags;
  198593. bool SystemStats::hasMMX() throw()
  198594. {
  198595. return cpuFlags.hasMMX;
  198596. }
  198597. bool SystemStats::hasSSE() throw()
  198598. {
  198599. return cpuFlags.hasSSE;
  198600. }
  198601. bool SystemStats::hasSSE2() throw()
  198602. {
  198603. return cpuFlags.hasSSE2;
  198604. }
  198605. bool SystemStats::has3DNow() throw()
  198606. {
  198607. return cpuFlags.has3DNow;
  198608. }
  198609. void SystemStats::initialiseStats() throw()
  198610. {
  198611. juce_initialiseThreadEvents();
  198612. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  198613. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  198614. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  198615. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  198616. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  198617. #else
  198618. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  198619. #endif
  198620. LARGE_INTEGER f;
  198621. QueryPerformanceFrequency (&f);
  198622. hiResTicksPerSecond = f.QuadPart;
  198623. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  198624. String s (SystemStats::getJUCEVersion());
  198625. #ifdef JUCE_DEBUG
  198626. const MMRESULT res = timeBeginPeriod (1);
  198627. jassert (res == TIMERR_NOERROR);
  198628. #else
  198629. timeBeginPeriod (1);
  198630. #endif
  198631. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  198632. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  198633. #endif
  198634. }
  198635. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  198636. {
  198637. OSVERSIONINFO info;
  198638. info.dwOSVersionInfoSize = sizeof (info);
  198639. GetVersionEx (&info);
  198640. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  198641. {
  198642. switch (info.dwMajorVersion)
  198643. {
  198644. case 5:
  198645. return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  198646. case 6:
  198647. return WinVista;
  198648. default:
  198649. jassertfalse // !! not a supported OS!
  198650. break;
  198651. }
  198652. }
  198653. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  198654. {
  198655. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  198656. return Win98;
  198657. }
  198658. return UnknownOS;
  198659. }
  198660. const String SystemStats::getOperatingSystemName() throw()
  198661. {
  198662. const char* name = "Unknown OS";
  198663. switch (getOperatingSystemType())
  198664. {
  198665. case WinVista:
  198666. name = "Windows Vista";
  198667. break;
  198668. case WinXP:
  198669. name = "Windows XP";
  198670. break;
  198671. case Win2000:
  198672. name = "Windows 2000";
  198673. break;
  198674. case Win98:
  198675. name = "Windows 98";
  198676. break;
  198677. default:
  198678. jassertfalse // !! new type of OS?
  198679. break;
  198680. }
  198681. return name;
  198682. }
  198683. bool SystemStats::isOperatingSystem64Bit() throw()
  198684. {
  198685. #ifdef _WIN64
  198686. return true;
  198687. #else
  198688. typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  198689. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  198690. BOOL isWow64 = FALSE;
  198691. return (fnIsWow64Process != 0)
  198692. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  198693. && (isWow64 != FALSE);
  198694. #endif
  198695. }
  198696. int SystemStats::getMemorySizeInMegabytes() throw()
  198697. {
  198698. MEMORYSTATUS mem;
  198699. GlobalMemoryStatus (&mem);
  198700. return (int) (mem.dwTotalPhys / (1024 * 1024)) + 1;
  198701. }
  198702. int SystemStats::getNumCpus() throw()
  198703. {
  198704. SYSTEM_INFO systemInfo;
  198705. GetSystemInfo (&systemInfo);
  198706. return systemInfo.dwNumberOfProcessors;
  198707. }
  198708. uint32 juce_millisecondsSinceStartup() throw()
  198709. {
  198710. return (uint32) GetTickCount();
  198711. }
  198712. int64 Time::getHighResolutionTicks() throw()
  198713. {
  198714. LARGE_INTEGER ticks;
  198715. QueryPerformanceCounter (&ticks);
  198716. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  198717. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  198718. // fix for a very obscure PCI hardware bug that can make the counter
  198719. // sometimes jump forwards by a few seconds..
  198720. static int64 hiResTicksOffset = 0;
  198721. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  198722. if (offsetDrift > (hiResTicksPerSecond >> 1))
  198723. hiResTicksOffset = newOffset;
  198724. return ticks.QuadPart + hiResTicksOffset;
  198725. }
  198726. double Time::getMillisecondCounterHiRes() throw()
  198727. {
  198728. return getHighResolutionTicks() * hiResTicksScaleFactor;
  198729. }
  198730. int64 Time::getHighResolutionTicksPerSecond() throw()
  198731. {
  198732. return hiResTicksPerSecond;
  198733. }
  198734. int64 SystemStats::getClockCycleCounter() throw()
  198735. {
  198736. #if JUCE_USE_INTRINSICS
  198737. // MS intrinsics version...
  198738. return __rdtsc();
  198739. #elif JUCE_GCC
  198740. // GNU inline asm version...
  198741. unsigned int hi = 0, lo = 0;
  198742. __asm__ __volatile__ (
  198743. "xor %%eax, %%eax \n\
  198744. xor %%edx, %%edx \n\
  198745. rdtsc \n\
  198746. movl %%eax, %[lo] \n\
  198747. movl %%edx, %[hi]"
  198748. :
  198749. : [hi] "m" (hi),
  198750. [lo] "m" (lo)
  198751. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  198752. return (int64) ((((uint64) hi) << 32) | lo);
  198753. #else
  198754. // MSVC inline asm version...
  198755. unsigned int hi = 0, lo = 0;
  198756. __asm
  198757. {
  198758. xor eax, eax
  198759. xor edx, edx
  198760. rdtsc
  198761. mov lo, eax
  198762. mov hi, edx
  198763. }
  198764. return (int64) ((((uint64) hi) << 32) | lo);
  198765. #endif
  198766. }
  198767. int SystemStats::getCpuSpeedInMegaherz() throw()
  198768. {
  198769. const int64 cycles = SystemStats::getClockCycleCounter();
  198770. const uint32 millis = Time::getMillisecondCounter();
  198771. int lastResult = 0;
  198772. for (;;)
  198773. {
  198774. int n = 1000000;
  198775. while (--n > 0) {}
  198776. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  198777. const int64 cyclesNow = SystemStats::getClockCycleCounter();
  198778. if (millisElapsed > 80)
  198779. {
  198780. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  198781. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  198782. return newResult;
  198783. lastResult = newResult;
  198784. }
  198785. }
  198786. }
  198787. bool Time::setSystemTimeToThisTime() const throw()
  198788. {
  198789. SYSTEMTIME st;
  198790. st.wDayOfWeek = 0;
  198791. st.wYear = (WORD) getYear();
  198792. st.wMonth = (WORD) (getMonth() + 1);
  198793. st.wDay = (WORD) getDayOfMonth();
  198794. st.wHour = (WORD) getHours();
  198795. st.wMinute = (WORD) getMinutes();
  198796. st.wSecond = (WORD) getSeconds();
  198797. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  198798. // do this twice because of daylight saving conversion problems - the
  198799. // first one sets it up, the second one kicks it in.
  198800. return SetLocalTime (&st) != 0
  198801. && SetLocalTime (&st) != 0;
  198802. }
  198803. int SystemStats::getPageSize() throw()
  198804. {
  198805. SYSTEM_INFO systemInfo;
  198806. GetSystemInfo (&systemInfo);
  198807. return systemInfo.dwPageSize;
  198808. }
  198809. END_JUCE_NAMESPACE
  198810. /********* End of inlined file: juce_win32_SystemStats.cpp *********/
  198811. /********* Start of inlined file: juce_win32_Threads.cpp *********/
  198812. #ifdef _MSC_VER
  198813. #pragma warning (disable: 4514)
  198814. #pragma warning (push)
  198815. #include <crtdbg.h>
  198816. #endif
  198817. #include <process.h>
  198818. BEGIN_JUCE_NAMESPACE
  198819. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198820. extern HWND juce_messageWindowHandle;
  198821. #endif
  198822. #ifdef _MSC_VER
  198823. #pragma warning (pop)
  198824. #endif
  198825. CriticalSection::CriticalSection() throw()
  198826. {
  198827. // (just to check the MS haven't changed this structure and broken things...)
  198828. #if _MSC_VER >= 1400
  198829. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  198830. #else
  198831. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  198832. #endif
  198833. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  198834. }
  198835. CriticalSection::~CriticalSection() throw()
  198836. {
  198837. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  198838. }
  198839. void CriticalSection::enter() const throw()
  198840. {
  198841. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  198842. }
  198843. bool CriticalSection::tryEnter() const throw()
  198844. {
  198845. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  198846. }
  198847. void CriticalSection::exit() const throw()
  198848. {
  198849. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  198850. }
  198851. WaitableEvent::WaitableEvent() throw()
  198852. : internal (CreateEvent (0, FALSE, FALSE, 0))
  198853. {
  198854. }
  198855. WaitableEvent::~WaitableEvent() throw()
  198856. {
  198857. CloseHandle (internal);
  198858. }
  198859. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  198860. {
  198861. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  198862. }
  198863. void WaitableEvent::signal() const throw()
  198864. {
  198865. SetEvent (internal);
  198866. }
  198867. void WaitableEvent::reset() const throw()
  198868. {
  198869. ResetEvent (internal);
  198870. }
  198871. void JUCE_API juce_threadEntryPoint (void*);
  198872. static unsigned int __stdcall threadEntryProc (void* userData) throw()
  198873. {
  198874. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198875. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  198876. GetCurrentThreadId(), TRUE);
  198877. #endif
  198878. juce_threadEntryPoint (userData);
  198879. _endthreadex(0);
  198880. return 0;
  198881. }
  198882. void juce_CloseThreadHandle (void* handle) throw()
  198883. {
  198884. CloseHandle ((HANDLE) handle);
  198885. }
  198886. void* juce_createThread (void* userData) throw()
  198887. {
  198888. unsigned int threadId;
  198889. return (void*) _beginthreadex (0, 0,
  198890. &threadEntryProc,
  198891. userData,
  198892. 0, &threadId);
  198893. }
  198894. void juce_killThread (void* handle) throw()
  198895. {
  198896. if (handle != 0)
  198897. {
  198898. #ifdef JUCE_DEBUG
  198899. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  198900. #endif
  198901. TerminateThread (handle, 0);
  198902. }
  198903. }
  198904. void juce_setCurrentThreadName (const String& name) throw()
  198905. {
  198906. #if defined (JUCE_DEBUG) && JUCE_MSVC
  198907. struct
  198908. {
  198909. DWORD dwType;
  198910. LPCSTR szName;
  198911. DWORD dwThreadID;
  198912. DWORD dwFlags;
  198913. } info;
  198914. info.dwType = 0x1000;
  198915. info.szName = name;
  198916. info.dwThreadID = GetCurrentThreadId();
  198917. info.dwFlags = 0;
  198918. #define MS_VC_EXCEPTION 0x406d1388
  198919. __try
  198920. {
  198921. RaiseException (MS_VC_EXCEPTION, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  198922. }
  198923. __except (EXCEPTION_CONTINUE_EXECUTION)
  198924. {}
  198925. #else
  198926. (void) name;
  198927. #endif
  198928. }
  198929. int Thread::getCurrentThreadId() throw()
  198930. {
  198931. return (int) GetCurrentThreadId();
  198932. }
  198933. // priority 1 to 10 where 5=normal, 1=low
  198934. void juce_setThreadPriority (void* threadHandle, int priority) throw()
  198935. {
  198936. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  198937. if (priority < 1)
  198938. pri = THREAD_PRIORITY_IDLE;
  198939. else if (priority < 2)
  198940. pri = THREAD_PRIORITY_LOWEST;
  198941. else if (priority < 5)
  198942. pri = THREAD_PRIORITY_BELOW_NORMAL;
  198943. else if (priority < 7)
  198944. pri = THREAD_PRIORITY_NORMAL;
  198945. else if (priority < 9)
  198946. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  198947. else if (priority < 10)
  198948. pri = THREAD_PRIORITY_HIGHEST;
  198949. if (threadHandle == 0)
  198950. threadHandle = GetCurrentThread();
  198951. SetThreadPriority (threadHandle, pri);
  198952. }
  198953. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  198954. {
  198955. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  198956. }
  198957. static HANDLE sleepEvent = 0;
  198958. void juce_initialiseThreadEvents() throw()
  198959. {
  198960. if (sleepEvent == 0)
  198961. #ifdef JUCE_DEBUG
  198962. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  198963. #else
  198964. sleepEvent = CreateEvent (0, 0, 0, 0);
  198965. #endif
  198966. }
  198967. void Thread::yield() throw()
  198968. {
  198969. Sleep (0);
  198970. }
  198971. void JUCE_CALLTYPE Thread::sleep (const int millisecs) throw()
  198972. {
  198973. if (millisecs >= 10)
  198974. {
  198975. Sleep (millisecs);
  198976. }
  198977. else
  198978. {
  198979. jassert (sleepEvent != 0);
  198980. // unlike Sleep() this is guaranteed to return to the current thread after
  198981. // the time expires, so we'll use this for short waits, which are more likely
  198982. // to need to be accurate
  198983. WaitForSingleObject (sleepEvent, millisecs);
  198984. }
  198985. }
  198986. static int lastProcessPriority = -1;
  198987. // called by WindowDriver because Windows does wierd things to process priority
  198988. // when you swap apps, and this forces an update when the app is brought to the front.
  198989. void juce_repeatLastProcessPriority() throw()
  198990. {
  198991. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  198992. {
  198993. DWORD p;
  198994. switch (lastProcessPriority)
  198995. {
  198996. case Process::LowPriority:
  198997. p = IDLE_PRIORITY_CLASS;
  198998. break;
  198999. case Process::NormalPriority:
  199000. p = NORMAL_PRIORITY_CLASS;
  199001. break;
  199002. case Process::HighPriority:
  199003. p = HIGH_PRIORITY_CLASS;
  199004. break;
  199005. case Process::RealtimePriority:
  199006. p = REALTIME_PRIORITY_CLASS;
  199007. break;
  199008. default:
  199009. jassertfalse // bad priority value
  199010. return;
  199011. }
  199012. SetPriorityClass (GetCurrentProcess(), p);
  199013. }
  199014. }
  199015. void Process::setPriority (ProcessPriority prior)
  199016. {
  199017. if (lastProcessPriority != (int) prior)
  199018. {
  199019. lastProcessPriority = (int) prior;
  199020. juce_repeatLastProcessPriority();
  199021. }
  199022. }
  199023. bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  199024. {
  199025. return IsDebuggerPresent() != FALSE;
  199026. }
  199027. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  199028. {
  199029. return juce_isRunningUnderDebugger();
  199030. }
  199031. void Process::raisePrivilege()
  199032. {
  199033. jassertfalse // xxx not implemented
  199034. }
  199035. void Process::lowerPrivilege()
  199036. {
  199037. jassertfalse // xxx not implemented
  199038. }
  199039. void Process::terminate()
  199040. {
  199041. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  199042. _CrtDumpMemoryLeaks();
  199043. #endif
  199044. // bullet in the head in case there's a problem shutting down..
  199045. ExitProcess (0);
  199046. }
  199047. void* Process::loadDynamicLibrary (const String& name)
  199048. {
  199049. void* result = 0;
  199050. JUCE_TRY
  199051. {
  199052. result = (void*) LoadLibrary (name);
  199053. }
  199054. JUCE_CATCH_ALL
  199055. return result;
  199056. }
  199057. void Process::freeDynamicLibrary (void* h)
  199058. {
  199059. JUCE_TRY
  199060. {
  199061. if (h != 0)
  199062. FreeLibrary ((HMODULE) h);
  199063. }
  199064. JUCE_CATCH_ALL
  199065. }
  199066. void* Process::getProcedureEntryPoint (void* h, const String& name)
  199067. {
  199068. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name)
  199069. : 0;
  199070. }
  199071. InterProcessLock::InterProcessLock (const String& name_) throw()
  199072. : internal (0),
  199073. name (name_),
  199074. reentrancyLevel (0)
  199075. {
  199076. }
  199077. InterProcessLock::~InterProcessLock() throw()
  199078. {
  199079. exit();
  199080. }
  199081. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  199082. {
  199083. if (reentrancyLevel++ == 0)
  199084. {
  199085. internal = CreateMutex (0, TRUE, name);
  199086. if (internal != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  199087. {
  199088. if (timeOutMillisecs == 0
  199089. || WaitForSingleObject (internal, (timeOutMillisecs < 0) ? INFINITE : timeOutMillisecs)
  199090. == WAIT_TIMEOUT)
  199091. {
  199092. ReleaseMutex (internal);
  199093. CloseHandle (internal);
  199094. internal = 0;
  199095. }
  199096. }
  199097. }
  199098. return (internal != 0);
  199099. }
  199100. void InterProcessLock::exit() throw()
  199101. {
  199102. if (--reentrancyLevel == 0 && internal != 0)
  199103. {
  199104. ReleaseMutex (internal);
  199105. CloseHandle (internal);
  199106. internal = 0;
  199107. }
  199108. }
  199109. END_JUCE_NAMESPACE
  199110. /********* End of inlined file: juce_win32_Threads.cpp *********/
  199111. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  199112. BEGIN_JUCE_NAMESPACE
  199113. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  199114. {
  199115. libHandle = LoadLibrary (name);
  199116. }
  199117. DynamicLibraryLoader::~DynamicLibraryLoader()
  199118. {
  199119. FreeLibrary ((HMODULE) libHandle);
  199120. }
  199121. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  199122. {
  199123. return (void*) GetProcAddress ((HMODULE) libHandle, functionName);
  199124. }
  199125. END_JUCE_NAMESPACE
  199126. /********* End of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  199127. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  199128. /********* Start of inlined file: juce_win32_ASIO.cpp *********/
  199129. #undef WINDOWS
  199130. #if JUCE_ASIO
  199131. /*
  199132. This is very frustrating - we only need to use a handful of definitions from
  199133. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  199134. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  199135. implementation...
  199136. ..unfortunately that would break Steinberg's license agreement for use of
  199137. their SDK, so I'm not allowed to do this.
  199138. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  199139. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  199140. (see www.steinberg.net/Steinberg/Developers.asp).
  199141. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  199142. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  199143. if you prefer). Make sure that your header search path will find the
  199144. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  199145. files are actually needed - so to simplify things, you could just copy
  199146. these into your JUCE directory).
  199147. */
  199148. #include "iasiodrv.h" // if you're compiling and this line causes an error because
  199149. // you don't have the ASIO SDK installed, you can disable ASIO
  199150. // support by commenting-out the "#define JUCE_ASIO" line in
  199151. // juce_Config.h
  199152. BEGIN_JUCE_NAMESPACE
  199153. // #define ASIO_DEBUGGING
  199154. #ifdef ASIO_DEBUGGING
  199155. #define log(a) { Logger::writeToLog (a); DBG (a) }
  199156. #else
  199157. #define log(a) {}
  199158. #endif
  199159. #ifdef ASIO_DEBUGGING
  199160. static void logError (const String& context, long error)
  199161. {
  199162. String err ("unknown error");
  199163. if (error == ASE_NotPresent)
  199164. err = "Not Present";
  199165. else if (error == ASE_HWMalfunction)
  199166. err = "Hardware Malfunction";
  199167. else if (error == ASE_InvalidParameter)
  199168. err = "Invalid Parameter";
  199169. else if (error == ASE_InvalidMode)
  199170. err = "Invalid Mode";
  199171. else if (error == ASE_SPNotAdvancing)
  199172. err = "Sample position not advancing";
  199173. else if (error == ASE_NoClock)
  199174. err = "No Clock";
  199175. else if (error == ASE_NoMemory)
  199176. err = "Out of memory";
  199177. log (T("!!error: ") + context + T(" - ") + err);
  199178. }
  199179. #else
  199180. #define logError(a, b) {}
  199181. #endif
  199182. class ASIOAudioIODevice;
  199183. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  199184. static const int maxASIOChannels = 160;
  199185. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  199186. private Timer
  199187. {
  199188. public:
  199189. Component ourWindow;
  199190. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber)
  199191. : AudioIODevice (name_, T("ASIO")),
  199192. asioObject (0),
  199193. classId (classId_),
  199194. currentBitDepth (16),
  199195. currentSampleRate (0),
  199196. tempBuffer (0),
  199197. isOpen_ (false),
  199198. isStarted (false),
  199199. postOutput (true),
  199200. insideControlPanelModalLoop (false),
  199201. shouldUsePreferredSize (false)
  199202. {
  199203. name = name_;
  199204. ourWindow.addToDesktop (0);
  199205. windowHandle = ourWindow.getWindowHandle();
  199206. jassert (currentASIODev [slotNumber] == 0);
  199207. currentASIODev [slotNumber] = this;
  199208. openDevice();
  199209. }
  199210. ~ASIOAudioIODevice()
  199211. {
  199212. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  199213. if (currentASIODev[i] == this)
  199214. currentASIODev[i] = 0;
  199215. close();
  199216. log ("ASIO - exiting");
  199217. removeCurrentDriver();
  199218. juce_free (tempBuffer);
  199219. }
  199220. void updateSampleRates()
  199221. {
  199222. // find a list of sample rates..
  199223. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  199224. sampleRates.clear();
  199225. if (asioObject != 0)
  199226. {
  199227. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  199228. {
  199229. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  199230. if (err == 0)
  199231. {
  199232. sampleRates.add ((int) possibleSampleRates[index]);
  199233. log (T("rate: ") + String ((int) possibleSampleRates[index]));
  199234. }
  199235. else if (err != ASE_NoClock)
  199236. {
  199237. logError (T("CanSampleRate"), err);
  199238. }
  199239. }
  199240. if (sampleRates.size() == 0)
  199241. {
  199242. double cr = 0;
  199243. const long err = asioObject->getSampleRate (&cr);
  199244. log (T("No sample rates supported - current rate: ") + String ((int) cr));
  199245. if (err == 0)
  199246. sampleRates.add ((int) cr);
  199247. }
  199248. }
  199249. }
  199250. const StringArray getOutputChannelNames()
  199251. {
  199252. return outputChannelNames;
  199253. }
  199254. const StringArray getInputChannelNames()
  199255. {
  199256. return inputChannelNames;
  199257. }
  199258. int getNumSampleRates()
  199259. {
  199260. return sampleRates.size();
  199261. }
  199262. double getSampleRate (int index)
  199263. {
  199264. return sampleRates [index];
  199265. }
  199266. int getNumBufferSizesAvailable()
  199267. {
  199268. return bufferSizes.size();
  199269. }
  199270. int getBufferSizeSamples (int index)
  199271. {
  199272. return bufferSizes [index];
  199273. }
  199274. int getDefaultBufferSize()
  199275. {
  199276. return preferredSize;
  199277. }
  199278. const String open (const BitArray& inputChannels,
  199279. const BitArray& outputChannels,
  199280. double sr,
  199281. int bufferSizeSamples)
  199282. {
  199283. close();
  199284. currentCallback = 0;
  199285. if (bufferSizeSamples <= 0)
  199286. shouldUsePreferredSize = true;
  199287. if (asioObject == 0 || ! isASIOOpen)
  199288. {
  199289. log ("Warning: device not open");
  199290. const String err (openDevice());
  199291. if (asioObject == 0 || ! isASIOOpen)
  199292. return err;
  199293. }
  199294. isStarted = false;
  199295. bufferIndex = -1;
  199296. long err = 0;
  199297. long newPreferredSize = 0;
  199298. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  199299. minSize = 0;
  199300. maxSize = 0;
  199301. newPreferredSize = 0;
  199302. granularity = 0;
  199303. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  199304. {
  199305. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  199306. shouldUsePreferredSize = true;
  199307. preferredSize = newPreferredSize;
  199308. }
  199309. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  199310. // dynamic changes to the buffer size...
  199311. shouldUsePreferredSize = shouldUsePreferredSize
  199312. || getName().containsIgnoreCase (T("Digidesign"));
  199313. if (shouldUsePreferredSize)
  199314. {
  199315. log ("Using preferred size for buffer..");
  199316. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  199317. {
  199318. bufferSizeSamples = preferredSize;
  199319. }
  199320. else
  199321. {
  199322. bufferSizeSamples = 1024;
  199323. logError ("GetBufferSize1", err);
  199324. }
  199325. shouldUsePreferredSize = false;
  199326. }
  199327. int sampleRate = roundDoubleToInt (sr);
  199328. currentSampleRate = sampleRate;
  199329. currentBlockSizeSamples = bufferSizeSamples;
  199330. currentChansOut.clear();
  199331. currentChansIn.clear();
  199332. zeromem (inBuffers, sizeof (inBuffers));
  199333. zeromem (outBuffers, sizeof (outBuffers));
  199334. updateSampleRates();
  199335. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  199336. sampleRate = sampleRates[0];
  199337. jassert (sampleRate != 0);
  199338. if (sampleRate == 0)
  199339. sampleRate = 44100;
  199340. long numSources = 32;
  199341. ASIOClockSource clocks[32];
  199342. zeromem (clocks, sizeof (clocks));
  199343. asioObject->getClockSources (clocks, &numSources);
  199344. bool isSourceSet = false;
  199345. // careful not to remove this loop because it does more than just logging!
  199346. int i;
  199347. for (i = 0; i < numSources; ++i)
  199348. {
  199349. String s ("clock: ");
  199350. s += clocks[i].name;
  199351. if (clocks[i].isCurrentSource)
  199352. {
  199353. isSourceSet = true;
  199354. s << " (cur)";
  199355. }
  199356. log (s);
  199357. }
  199358. if (numSources > 1 && ! isSourceSet)
  199359. {
  199360. log ("setting clock source");
  199361. asioObject->setClockSource (clocks[0].index);
  199362. Thread::sleep (20);
  199363. }
  199364. else
  199365. {
  199366. if (numSources == 0)
  199367. {
  199368. log ("ASIO - no clock sources!");
  199369. }
  199370. }
  199371. double cr = 0;
  199372. err = asioObject->getSampleRate (&cr);
  199373. if (err == 0)
  199374. {
  199375. currentSampleRate = cr;
  199376. }
  199377. else
  199378. {
  199379. logError ("GetSampleRate", err);
  199380. currentSampleRate = 0;
  199381. }
  199382. error = String::empty;
  199383. needToReset = false;
  199384. isReSync = false;
  199385. err = 0;
  199386. bool buffersCreated = false;
  199387. if (currentSampleRate != sampleRate)
  199388. {
  199389. log (T("ASIO samplerate: ") + String (currentSampleRate) + T(" to ") + String (sampleRate));
  199390. err = asioObject->setSampleRate (sampleRate);
  199391. if (err == ASE_NoClock && numSources > 0)
  199392. {
  199393. log ("trying to set a clock source..");
  199394. Thread::sleep (10);
  199395. err = asioObject->setClockSource (clocks[0].index);
  199396. if (err != 0)
  199397. {
  199398. logError ("SetClock", err);
  199399. }
  199400. Thread::sleep (10);
  199401. err = asioObject->setSampleRate (sampleRate);
  199402. }
  199403. }
  199404. if (err == 0)
  199405. {
  199406. currentSampleRate = sampleRate;
  199407. if (needToReset)
  199408. {
  199409. if (isReSync)
  199410. {
  199411. log ("Resync request");
  199412. }
  199413. log ("! Resetting ASIO after sample rate change");
  199414. removeCurrentDriver();
  199415. loadDriver();
  199416. const String error (initDriver());
  199417. if (error.isNotEmpty())
  199418. {
  199419. log (T("ASIOInit: ") + error);
  199420. }
  199421. needToReset = false;
  199422. isReSync = false;
  199423. }
  199424. numActiveInputChans = 0;
  199425. numActiveOutputChans = 0;
  199426. ASIOBufferInfo* info = bufferInfos;
  199427. int i;
  199428. for (i = 0; i < totalNumInputChans; ++i)
  199429. {
  199430. if (inputChannels[i])
  199431. {
  199432. currentChansIn.setBit (i);
  199433. info->isInput = 1;
  199434. info->channelNum = i;
  199435. info->buffers[0] = info->buffers[1] = 0;
  199436. ++info;
  199437. ++numActiveInputChans;
  199438. }
  199439. }
  199440. for (i = 0; i < totalNumOutputChans; ++i)
  199441. {
  199442. if (outputChannels[i])
  199443. {
  199444. currentChansOut.setBit (i);
  199445. info->isInput = 0;
  199446. info->channelNum = i;
  199447. info->buffers[0] = info->buffers[1] = 0;
  199448. ++info;
  199449. ++numActiveOutputChans;
  199450. }
  199451. }
  199452. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  199453. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  199454. if (currentASIODev[0] == this)
  199455. {
  199456. callbacks.bufferSwitch = &bufferSwitchCallback0;
  199457. callbacks.asioMessage = &asioMessagesCallback0;
  199458. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  199459. }
  199460. else if (currentASIODev[1] == this)
  199461. {
  199462. callbacks.bufferSwitch = &bufferSwitchCallback1;
  199463. callbacks.asioMessage = &asioMessagesCallback1;
  199464. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  199465. }
  199466. else if (currentASIODev[2] == this)
  199467. {
  199468. callbacks.bufferSwitch = &bufferSwitchCallback2;
  199469. callbacks.asioMessage = &asioMessagesCallback2;
  199470. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  199471. }
  199472. else
  199473. {
  199474. jassertfalse
  199475. }
  199476. log ("disposing buffers");
  199477. err = asioObject->disposeBuffers();
  199478. log (T("creating buffers: ") + String (totalBuffers) + T(", ") + String (currentBlockSizeSamples));
  199479. err = asioObject->createBuffers (bufferInfos,
  199480. totalBuffers,
  199481. currentBlockSizeSamples,
  199482. &callbacks);
  199483. if (err != 0)
  199484. {
  199485. currentBlockSizeSamples = preferredSize;
  199486. logError ("create buffers 2", err);
  199487. asioObject->disposeBuffers();
  199488. err = asioObject->createBuffers (bufferInfos,
  199489. totalBuffers,
  199490. currentBlockSizeSamples,
  199491. &callbacks);
  199492. }
  199493. if (err == 0)
  199494. {
  199495. buffersCreated = true;
  199496. juce_free (tempBuffer);
  199497. tempBuffer = (float*) juce_calloc (totalBuffers * currentBlockSizeSamples * sizeof (float) + 128);
  199498. int n = 0;
  199499. Array <int> types;
  199500. currentBitDepth = 16;
  199501. for (i = 0; i < jmin (totalNumInputChans, maxASIOChannels); ++i)
  199502. {
  199503. if (inputChannels[i])
  199504. {
  199505. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  199506. ASIOChannelInfo channelInfo;
  199507. zerostruct (channelInfo);
  199508. channelInfo.channel = i;
  199509. channelInfo.isInput = 1;
  199510. asioObject->getChannelInfo (&channelInfo);
  199511. types.addIfNotAlreadyThere (channelInfo.type);
  199512. typeToFormatParameters (channelInfo.type,
  199513. inputChannelBitDepths[n],
  199514. inputChannelBytesPerSample[n],
  199515. inputChannelIsFloat[n],
  199516. inputChannelLittleEndian[n]);
  199517. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  199518. ++n;
  199519. }
  199520. }
  199521. jassert (numActiveInputChans == n);
  199522. n = 0;
  199523. for (i = 0; i < jmin (totalNumOutputChans, maxASIOChannels); ++i)
  199524. {
  199525. if (outputChannels[i])
  199526. {
  199527. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  199528. ASIOChannelInfo channelInfo;
  199529. zerostruct (channelInfo);
  199530. channelInfo.channel = i;
  199531. channelInfo.isInput = 0;
  199532. asioObject->getChannelInfo (&channelInfo);
  199533. types.addIfNotAlreadyThere (channelInfo.type);
  199534. typeToFormatParameters (channelInfo.type,
  199535. outputChannelBitDepths[n],
  199536. outputChannelBytesPerSample[n],
  199537. outputChannelIsFloat[n],
  199538. outputChannelLittleEndian[n]);
  199539. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  199540. ++n;
  199541. }
  199542. }
  199543. jassert (numActiveOutputChans == n);
  199544. for (i = types.size(); --i >= 0;)
  199545. {
  199546. log (T("channel format: ") + String (types[i]));
  199547. }
  199548. jassert (n <= totalBuffers);
  199549. for (i = 0; i < numActiveOutputChans; ++i)
  199550. {
  199551. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  199552. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  199553. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  199554. {
  199555. log ("!! Null buffers");
  199556. }
  199557. else
  199558. {
  199559. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  199560. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  199561. }
  199562. }
  199563. inputLatency = outputLatency = 0;
  199564. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  199565. {
  199566. log ("ASIO - no latencies");
  199567. }
  199568. else
  199569. {
  199570. log (T("ASIO latencies: ")
  199571. + String ((int) outputLatency)
  199572. + T(", ")
  199573. + String ((int) inputLatency));
  199574. }
  199575. isOpen_ = true;
  199576. log ("starting ASIO");
  199577. calledback = false;
  199578. err = asioObject->start();
  199579. if (err != 0)
  199580. {
  199581. isOpen_ = false;
  199582. log ("ASIO - stop on failure");
  199583. Thread::sleep (10);
  199584. asioObject->stop();
  199585. error = "Can't start device";
  199586. Thread::sleep (10);
  199587. }
  199588. else
  199589. {
  199590. int count = 300;
  199591. while (--count > 0 && ! calledback)
  199592. Thread::sleep (10);
  199593. isStarted = true;
  199594. if (! calledback)
  199595. {
  199596. error = "Device didn't start correctly";
  199597. log ("ASIO didn't callback - stopping..");
  199598. asioObject->stop();
  199599. }
  199600. }
  199601. }
  199602. else
  199603. {
  199604. error = "Can't create i/o buffers";
  199605. }
  199606. }
  199607. else
  199608. {
  199609. error = "Can't set sample rate: ";
  199610. error << sampleRate;
  199611. }
  199612. if (error.isNotEmpty())
  199613. {
  199614. logError (error, err);
  199615. if (asioObject != 0 && buffersCreated)
  199616. asioObject->disposeBuffers();
  199617. Thread::sleep (20);
  199618. isStarted = false;
  199619. isOpen_ = false;
  199620. close();
  199621. }
  199622. needToReset = false;
  199623. isReSync = false;
  199624. return error;
  199625. }
  199626. void close()
  199627. {
  199628. error = String::empty;
  199629. stopTimer();
  199630. stop();
  199631. if (isASIOOpen && isOpen_)
  199632. {
  199633. const ScopedLock sl (callbackLock);
  199634. isOpen_ = false;
  199635. isStarted = false;
  199636. needToReset = false;
  199637. isReSync = false;
  199638. log ("ASIO - stopping");
  199639. if (asioObject != 0)
  199640. {
  199641. Thread::sleep (20);
  199642. asioObject->stop();
  199643. Thread::sleep (10);
  199644. asioObject->disposeBuffers();
  199645. }
  199646. Thread::sleep (10);
  199647. }
  199648. }
  199649. bool isOpen()
  199650. {
  199651. return isOpen_ || insideControlPanelModalLoop;
  199652. }
  199653. int getCurrentBufferSizeSamples()
  199654. {
  199655. return currentBlockSizeSamples;
  199656. }
  199657. double getCurrentSampleRate()
  199658. {
  199659. return currentSampleRate;
  199660. }
  199661. const BitArray getActiveOutputChannels() const
  199662. {
  199663. return currentChansOut;
  199664. }
  199665. const BitArray getActiveInputChannels() const
  199666. {
  199667. return currentChansIn;
  199668. }
  199669. int getCurrentBitDepth()
  199670. {
  199671. return currentBitDepth;
  199672. }
  199673. int getOutputLatencyInSamples()
  199674. {
  199675. return outputLatency + currentBlockSizeSamples / 4;
  199676. }
  199677. int getInputLatencyInSamples()
  199678. {
  199679. return inputLatency + currentBlockSizeSamples / 4;
  199680. }
  199681. void start (AudioIODeviceCallback* callback)
  199682. {
  199683. if (callback != 0)
  199684. {
  199685. callback->audioDeviceAboutToStart (this);
  199686. const ScopedLock sl (callbackLock);
  199687. currentCallback = callback;
  199688. }
  199689. }
  199690. void stop()
  199691. {
  199692. AudioIODeviceCallback* const lastCallback = currentCallback;
  199693. {
  199694. const ScopedLock sl (callbackLock);
  199695. currentCallback = 0;
  199696. }
  199697. if (lastCallback != 0)
  199698. lastCallback->audioDeviceStopped();
  199699. }
  199700. bool isPlaying()
  199701. {
  199702. return isASIOOpen && (currentCallback != 0);
  199703. }
  199704. const String getLastError()
  199705. {
  199706. return error;
  199707. }
  199708. bool hasControlPanel() const
  199709. {
  199710. return true;
  199711. }
  199712. bool showControlPanel()
  199713. {
  199714. log ("ASIO - showing control panel");
  199715. Component modalWindow (String::empty);
  199716. modalWindow.setOpaque (true);
  199717. modalWindow.addToDesktop (0);
  199718. modalWindow.enterModalState();
  199719. bool done = false;
  199720. JUCE_TRY
  199721. {
  199722. close();
  199723. insideControlPanelModalLoop = true;
  199724. const uint32 started = Time::getMillisecondCounter();
  199725. if (asioObject != 0)
  199726. {
  199727. asioObject->controlPanel();
  199728. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  199729. log (T("spent: ") + String (spent));
  199730. if (spent > 300)
  199731. {
  199732. shouldUsePreferredSize = true;
  199733. done = true;
  199734. }
  199735. }
  199736. }
  199737. JUCE_CATCH_ALL
  199738. insideControlPanelModalLoop = false;
  199739. return done;
  199740. }
  199741. void resetRequest() throw()
  199742. {
  199743. needToReset = true;
  199744. }
  199745. void resyncRequest() throw()
  199746. {
  199747. needToReset = true;
  199748. isReSync = true;
  199749. }
  199750. void timerCallback()
  199751. {
  199752. if (! insideControlPanelModalLoop)
  199753. {
  199754. stopTimer();
  199755. // used to cause a reset
  199756. log ("! ASIO restart request!");
  199757. if (isOpen_)
  199758. {
  199759. AudioIODeviceCallback* const oldCallback = currentCallback;
  199760. close();
  199761. open (currentChansIn, currentChansOut,
  199762. currentSampleRate, currentBlockSizeSamples);
  199763. if (oldCallback != 0)
  199764. start (oldCallback);
  199765. }
  199766. }
  199767. else
  199768. {
  199769. startTimer (100);
  199770. }
  199771. }
  199772. juce_UseDebuggingNewOperator
  199773. private:
  199774. IASIO* volatile asioObject;
  199775. ASIOCallbacks callbacks;
  199776. void* windowHandle;
  199777. CLSID classId;
  199778. String error;
  199779. long totalNumInputChans, totalNumOutputChans;
  199780. StringArray inputChannelNames, outputChannelNames;
  199781. Array<int> sampleRates, bufferSizes;
  199782. long inputLatency, outputLatency;
  199783. long minSize, maxSize, preferredSize, granularity;
  199784. int volatile currentBlockSizeSamples;
  199785. int volatile currentBitDepth;
  199786. double volatile currentSampleRate;
  199787. BitArray currentChansOut, currentChansIn;
  199788. AudioIODeviceCallback* volatile currentCallback;
  199789. CriticalSection callbackLock;
  199790. ASIOBufferInfo bufferInfos [maxASIOChannels];
  199791. float* inBuffers [maxASIOChannels];
  199792. float* outBuffers [maxASIOChannels];
  199793. int inputChannelBitDepths [maxASIOChannels];
  199794. int outputChannelBitDepths [maxASIOChannels];
  199795. int inputChannelBytesPerSample [maxASIOChannels];
  199796. int outputChannelBytesPerSample [maxASIOChannels];
  199797. bool inputChannelIsFloat [maxASIOChannels];
  199798. bool outputChannelIsFloat [maxASIOChannels];
  199799. bool inputChannelLittleEndian [maxASIOChannels];
  199800. bool outputChannelLittleEndian [maxASIOChannels];
  199801. WaitableEvent event1;
  199802. float* tempBuffer;
  199803. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  199804. bool isOpen_, isStarted;
  199805. bool volatile isASIOOpen;
  199806. bool volatile calledback;
  199807. bool volatile littleEndian, postOutput, needToReset, isReSync;
  199808. bool volatile insideControlPanelModalLoop;
  199809. bool volatile shouldUsePreferredSize;
  199810. void removeCurrentDriver()
  199811. {
  199812. if (asioObject != 0)
  199813. {
  199814. asioObject->Release();
  199815. asioObject = 0;
  199816. }
  199817. }
  199818. bool loadDriver()
  199819. {
  199820. removeCurrentDriver();
  199821. JUCE_TRY
  199822. {
  199823. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  199824. classId, (void**) &asioObject) == S_OK)
  199825. {
  199826. return true;
  199827. }
  199828. }
  199829. JUCE_CATCH_ALL
  199830. asioObject = 0;
  199831. return false;
  199832. }
  199833. const String initDriver()
  199834. {
  199835. if (asioObject != 0)
  199836. {
  199837. char buffer [256];
  199838. zeromem (buffer, sizeof (buffer));
  199839. if (! asioObject->init (windowHandle))
  199840. {
  199841. asioObject->getErrorMessage (buffer);
  199842. return String (buffer, sizeof (buffer) - 1);
  199843. }
  199844. // just in case any daft drivers expect this to be called..
  199845. asioObject->getDriverName (buffer);
  199846. return String::empty;
  199847. }
  199848. return "No Driver";
  199849. }
  199850. const String openDevice()
  199851. {
  199852. // use this in case the driver starts opening dialog boxes..
  199853. Component modalWindow (String::empty);
  199854. modalWindow.setOpaque (true);
  199855. modalWindow.addToDesktop (0);
  199856. modalWindow.enterModalState();
  199857. // open the device and get its info..
  199858. log (T("opening ASIO device: ") + getName());
  199859. needToReset = false;
  199860. isReSync = false;
  199861. outputChannelNames.clear();
  199862. inputChannelNames.clear();
  199863. bufferSizes.clear();
  199864. sampleRates.clear();
  199865. isASIOOpen = false;
  199866. isOpen_ = false;
  199867. totalNumInputChans = 0;
  199868. totalNumOutputChans = 0;
  199869. numActiveInputChans = 0;
  199870. numActiveOutputChans = 0;
  199871. currentCallback = 0;
  199872. error = String::empty;
  199873. if (getName().isEmpty())
  199874. return error;
  199875. long err = 0;
  199876. if (loadDriver())
  199877. {
  199878. if ((error = initDriver()).isEmpty())
  199879. {
  199880. numActiveInputChans = 0;
  199881. numActiveOutputChans = 0;
  199882. totalNumInputChans = 0;
  199883. totalNumOutputChans = 0;
  199884. if (asioObject != 0
  199885. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  199886. {
  199887. log (String ((int) totalNumInputChans) + T(" in, ") + String ((int) totalNumOutputChans) + T(" out"));
  199888. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  199889. {
  199890. // find a list of buffer sizes..
  199891. log (String ((int) minSize) + T(" ") + String ((int) maxSize) + T(" ") + String ((int)preferredSize) + T(" ") + String ((int)granularity));
  199892. if (granularity >= 0)
  199893. {
  199894. granularity = jmax (1, (int) granularity);
  199895. for (int i = jmax (minSize, (int) granularity); i < jmin (6400, maxSize); i += granularity)
  199896. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  199897. }
  199898. else if (granularity < 0)
  199899. {
  199900. for (int i = 0; i < 18; ++i)
  199901. {
  199902. const int s = (1 << i);
  199903. if (s >= minSize && s <= maxSize)
  199904. bufferSizes.add (s);
  199905. }
  199906. }
  199907. if (! bufferSizes.contains (preferredSize))
  199908. bufferSizes.insert (0, preferredSize);
  199909. double currentRate = 0;
  199910. asioObject->getSampleRate (&currentRate);
  199911. if (currentRate <= 0.0 || currentRate > 192001.0)
  199912. {
  199913. log ("setting sample rate");
  199914. err = asioObject->setSampleRate (44100.0);
  199915. if (err != 0)
  199916. {
  199917. logError ("setting sample rate", err);
  199918. }
  199919. asioObject->getSampleRate (&currentRate);
  199920. }
  199921. currentSampleRate = currentRate;
  199922. postOutput = (asioObject->outputReady() == 0);
  199923. if (postOutput)
  199924. {
  199925. log ("ASIO outputReady = ok");
  199926. }
  199927. updateSampleRates();
  199928. // ..because cubase does it at this point
  199929. inputLatency = outputLatency = 0;
  199930. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  199931. {
  199932. log ("ASIO - no latencies");
  199933. }
  199934. log (String ("latencies: ")
  199935. + String ((int) inputLatency)
  199936. + T(", ") + String ((int) outputLatency));
  199937. // create some dummy buffers now.. because cubase does..
  199938. numActiveInputChans = 0;
  199939. numActiveOutputChans = 0;
  199940. ASIOBufferInfo* info = bufferInfos;
  199941. int i, numChans = 0;
  199942. for (i = 0; i < jmin (2, totalNumInputChans); ++i)
  199943. {
  199944. info->isInput = 1;
  199945. info->channelNum = i;
  199946. info->buffers[0] = info->buffers[1] = 0;
  199947. ++info;
  199948. ++numChans;
  199949. }
  199950. const int outputBufferIndex = numChans;
  199951. for (i = 0; i < jmin (2, totalNumOutputChans); ++i)
  199952. {
  199953. info->isInput = 0;
  199954. info->channelNum = i;
  199955. info->buffers[0] = info->buffers[1] = 0;
  199956. ++info;
  199957. ++numChans;
  199958. }
  199959. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  199960. if (currentASIODev[0] == this)
  199961. {
  199962. callbacks.bufferSwitch = &bufferSwitchCallback0;
  199963. callbacks.asioMessage = &asioMessagesCallback0;
  199964. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  199965. }
  199966. else if (currentASIODev[1] == this)
  199967. {
  199968. callbacks.bufferSwitch = &bufferSwitchCallback1;
  199969. callbacks.asioMessage = &asioMessagesCallback1;
  199970. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  199971. }
  199972. else if (currentASIODev[2] == this)
  199973. {
  199974. callbacks.bufferSwitch = &bufferSwitchCallback2;
  199975. callbacks.asioMessage = &asioMessagesCallback2;
  199976. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  199977. }
  199978. else
  199979. {
  199980. jassertfalse
  199981. }
  199982. log (T("creating buffers (dummy): ") + String (numChans)
  199983. + T(", ") + String ((int) preferredSize));
  199984. if (preferredSize > 0)
  199985. {
  199986. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  199987. if (err != 0)
  199988. {
  199989. logError ("dummy buffers", err);
  199990. }
  199991. }
  199992. long newInps = 0, newOuts = 0;
  199993. asioObject->getChannels (&newInps, &newOuts);
  199994. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  199995. {
  199996. totalNumInputChans = newInps;
  199997. totalNumOutputChans = newOuts;
  199998. log (String ((int) totalNumInputChans) + T(" in; ")
  199999. + String ((int) totalNumOutputChans) + T(" out"));
  200000. }
  200001. updateSampleRates();
  200002. ASIOChannelInfo channelInfo;
  200003. channelInfo.type = 0;
  200004. for (i = 0; i < totalNumInputChans; ++i)
  200005. {
  200006. zerostruct (channelInfo);
  200007. channelInfo.channel = i;
  200008. channelInfo.isInput = 1;
  200009. asioObject->getChannelInfo (&channelInfo);
  200010. inputChannelNames.add (String (channelInfo.name));
  200011. }
  200012. for (i = 0; i < totalNumOutputChans; ++i)
  200013. {
  200014. zerostruct (channelInfo);
  200015. channelInfo.channel = i;
  200016. channelInfo.isInput = 0;
  200017. asioObject->getChannelInfo (&channelInfo);
  200018. outputChannelNames.add (String (channelInfo.name));
  200019. typeToFormatParameters (channelInfo.type,
  200020. outputChannelBitDepths[i],
  200021. outputChannelBytesPerSample[i],
  200022. outputChannelIsFloat[i],
  200023. outputChannelLittleEndian[i]);
  200024. if (i < 2)
  200025. {
  200026. // clear the channels that are used with the dummy stuff
  200027. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  200028. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  200029. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  200030. }
  200031. }
  200032. outputChannelNames.trim();
  200033. inputChannelNames.trim();
  200034. outputChannelNames.appendNumbersToDuplicates (false, true);
  200035. inputChannelNames.appendNumbersToDuplicates (false, true);
  200036. // start and stop because cubase does it..
  200037. asioObject->getLatencies (&inputLatency, &outputLatency);
  200038. if ((err = asioObject->start()) != 0)
  200039. {
  200040. // ignore an error here, as it might start later after setting other stuff up
  200041. logError ("ASIO start", err);
  200042. }
  200043. Thread::sleep (100);
  200044. asioObject->stop();
  200045. }
  200046. else
  200047. {
  200048. error = "Can't detect buffer sizes";
  200049. }
  200050. }
  200051. else
  200052. {
  200053. error = "Can't detect asio channels";
  200054. }
  200055. }
  200056. }
  200057. else
  200058. {
  200059. error = "No such device";
  200060. }
  200061. if (error.isNotEmpty())
  200062. {
  200063. logError (error, err);
  200064. if (asioObject != 0)
  200065. asioObject->disposeBuffers();
  200066. removeCurrentDriver();
  200067. isASIOOpen = false;
  200068. }
  200069. else
  200070. {
  200071. isASIOOpen = true;
  200072. log ("ASIO device open");
  200073. }
  200074. isOpen_ = false;
  200075. needToReset = false;
  200076. isReSync = false;
  200077. return error;
  200078. }
  200079. void callback (const long index) throw()
  200080. {
  200081. if (isStarted)
  200082. {
  200083. bufferIndex = index;
  200084. processBuffer();
  200085. }
  200086. else
  200087. {
  200088. if (postOutput && (asioObject != 0))
  200089. asioObject->outputReady();
  200090. }
  200091. calledback = true;
  200092. }
  200093. void processBuffer() throw()
  200094. {
  200095. const ASIOBufferInfo* const infos = bufferInfos;
  200096. const int bi = bufferIndex;
  200097. const ScopedLock sl (callbackLock);
  200098. if (needToReset)
  200099. {
  200100. needToReset = false;
  200101. if (isReSync)
  200102. {
  200103. log ("! ASIO resync");
  200104. isReSync = false;
  200105. }
  200106. else
  200107. {
  200108. startTimer (20);
  200109. }
  200110. }
  200111. if (bi >= 0)
  200112. {
  200113. const int samps = currentBlockSizeSamples;
  200114. if (currentCallback != 0)
  200115. {
  200116. int i;
  200117. for (i = 0; i < numActiveInputChans; ++i)
  200118. {
  200119. float* const dst = inBuffers[i];
  200120. jassert (dst != 0);
  200121. const char* const src = (const char*) (infos[i].buffers[bi]);
  200122. if (inputChannelIsFloat[i])
  200123. {
  200124. memcpy (dst, src, samps * sizeof (float));
  200125. }
  200126. else
  200127. {
  200128. jassert (dst == tempBuffer + (samps * i));
  200129. switch (inputChannelBitDepths[i])
  200130. {
  200131. case 16:
  200132. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  200133. samps, inputChannelLittleEndian[i]);
  200134. break;
  200135. case 24:
  200136. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  200137. samps, inputChannelLittleEndian[i]);
  200138. break;
  200139. case 32:
  200140. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  200141. samps, inputChannelLittleEndian[i]);
  200142. break;
  200143. case 64:
  200144. jassertfalse
  200145. break;
  200146. }
  200147. }
  200148. }
  200149. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  200150. numActiveInputChans,
  200151. outBuffers,
  200152. numActiveOutputChans,
  200153. samps);
  200154. for (i = 0; i < numActiveOutputChans; ++i)
  200155. {
  200156. float* const src = outBuffers[i];
  200157. jassert (src != 0);
  200158. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  200159. if (outputChannelIsFloat[i])
  200160. {
  200161. memcpy (dst, src, samps * sizeof (float));
  200162. }
  200163. else
  200164. {
  200165. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  200166. switch (outputChannelBitDepths[i])
  200167. {
  200168. case 16:
  200169. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  200170. samps, outputChannelLittleEndian[i]);
  200171. break;
  200172. case 24:
  200173. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  200174. samps, outputChannelLittleEndian[i]);
  200175. break;
  200176. case 32:
  200177. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  200178. samps, outputChannelLittleEndian[i]);
  200179. break;
  200180. case 64:
  200181. jassertfalse
  200182. break;
  200183. }
  200184. }
  200185. }
  200186. }
  200187. else
  200188. {
  200189. for (int i = 0; i < numActiveOutputChans; ++i)
  200190. {
  200191. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  200192. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  200193. }
  200194. }
  200195. }
  200196. if (postOutput)
  200197. asioObject->outputReady();
  200198. }
  200199. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long) throw()
  200200. {
  200201. if (currentASIODev[0] != 0)
  200202. currentASIODev[0]->callback (index);
  200203. return 0;
  200204. }
  200205. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long) throw()
  200206. {
  200207. if (currentASIODev[1] != 0)
  200208. currentASIODev[1]->callback (index);
  200209. return 0;
  200210. }
  200211. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long) throw()
  200212. {
  200213. if (currentASIODev[2] != 0)
  200214. currentASIODev[2]->callback (index);
  200215. return 0;
  200216. }
  200217. static void bufferSwitchCallback0 (long index, long) throw()
  200218. {
  200219. if (currentASIODev[0] != 0)
  200220. currentASIODev[0]->callback (index);
  200221. }
  200222. static void bufferSwitchCallback1 (long index, long) throw()
  200223. {
  200224. if (currentASIODev[1] != 0)
  200225. currentASIODev[1]->callback (index);
  200226. }
  200227. static void bufferSwitchCallback2 (long index, long) throw()
  200228. {
  200229. if (currentASIODev[2] != 0)
  200230. currentASIODev[2]->callback (index);
  200231. }
  200232. static long asioMessagesCallback0 (long selector, long value, void*, double*) throw()
  200233. {
  200234. return asioMessagesCallback (selector, value, 0);
  200235. }
  200236. static long asioMessagesCallback1 (long selector, long value, void*, double*) throw()
  200237. {
  200238. return asioMessagesCallback (selector, value, 1);
  200239. }
  200240. static long asioMessagesCallback2 (long selector, long value, void*, double*) throw()
  200241. {
  200242. return asioMessagesCallback (selector, value, 2);
  200243. }
  200244. static long asioMessagesCallback (long selector, long value, const int deviceIndex) throw()
  200245. {
  200246. switch (selector)
  200247. {
  200248. case kAsioSelectorSupported:
  200249. if (value == kAsioResetRequest
  200250. || value == kAsioEngineVersion
  200251. || value == kAsioResyncRequest
  200252. || value == kAsioLatenciesChanged
  200253. || value == kAsioSupportsInputMonitor)
  200254. return 1;
  200255. break;
  200256. case kAsioBufferSizeChange:
  200257. break;
  200258. case kAsioResetRequest:
  200259. if (currentASIODev[deviceIndex] != 0)
  200260. currentASIODev[deviceIndex]->resetRequest();
  200261. return 1;
  200262. case kAsioResyncRequest:
  200263. if (currentASIODev[deviceIndex] != 0)
  200264. currentASIODev[deviceIndex]->resyncRequest();
  200265. return 1;
  200266. case kAsioLatenciesChanged:
  200267. return 1;
  200268. case kAsioEngineVersion:
  200269. return 2;
  200270. case kAsioSupportsTimeInfo:
  200271. case kAsioSupportsTimeCode:
  200272. return 0;
  200273. }
  200274. return 0;
  200275. }
  200276. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  200277. {
  200278. }
  200279. static void convertInt16ToFloat (const char* src,
  200280. float* dest,
  200281. const int srcStrideBytes,
  200282. int numSamples,
  200283. const bool littleEndian) throw()
  200284. {
  200285. const double g = 1.0 / 32768.0;
  200286. if (littleEndian)
  200287. {
  200288. while (--numSamples >= 0)
  200289. {
  200290. *dest++ = (float) (g * (short) littleEndianShort (src));
  200291. src += srcStrideBytes;
  200292. }
  200293. }
  200294. else
  200295. {
  200296. while (--numSamples >= 0)
  200297. {
  200298. *dest++ = (float) (g * (short) bigEndianShort (src));
  200299. src += srcStrideBytes;
  200300. }
  200301. }
  200302. }
  200303. static void convertFloatToInt16 (const float* src,
  200304. char* dest,
  200305. const int dstStrideBytes,
  200306. int numSamples,
  200307. const bool littleEndian) throw()
  200308. {
  200309. const double maxVal = (double) 0x7fff;
  200310. if (littleEndian)
  200311. {
  200312. while (--numSamples >= 0)
  200313. {
  200314. *(uint16*) dest = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  200315. dest += dstStrideBytes;
  200316. }
  200317. }
  200318. else
  200319. {
  200320. while (--numSamples >= 0)
  200321. {
  200322. *(uint16*) dest = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  200323. dest += dstStrideBytes;
  200324. }
  200325. }
  200326. }
  200327. static void convertInt24ToFloat (const char* src,
  200328. float* dest,
  200329. const int srcStrideBytes,
  200330. int numSamples,
  200331. const bool littleEndian) throw()
  200332. {
  200333. const double g = 1.0 / 0x7fffff;
  200334. if (littleEndian)
  200335. {
  200336. while (--numSamples >= 0)
  200337. {
  200338. *dest++ = (float) (g * littleEndian24Bit (src));
  200339. src += srcStrideBytes;
  200340. }
  200341. }
  200342. else
  200343. {
  200344. while (--numSamples >= 0)
  200345. {
  200346. *dest++ = (float) (g * bigEndian24Bit (src));
  200347. src += srcStrideBytes;
  200348. }
  200349. }
  200350. }
  200351. static void convertFloatToInt24 (const float* src,
  200352. char* dest,
  200353. const int dstStrideBytes,
  200354. int numSamples,
  200355. const bool littleEndian) throw()
  200356. {
  200357. const double maxVal = (double) 0x7fffff;
  200358. if (littleEndian)
  200359. {
  200360. while (--numSamples >= 0)
  200361. {
  200362. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  200363. dest += dstStrideBytes;
  200364. }
  200365. }
  200366. else
  200367. {
  200368. while (--numSamples >= 0)
  200369. {
  200370. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  200371. dest += dstStrideBytes;
  200372. }
  200373. }
  200374. }
  200375. static void convertInt32ToFloat (const char* src,
  200376. float* dest,
  200377. const int srcStrideBytes,
  200378. int numSamples,
  200379. const bool littleEndian) throw()
  200380. {
  200381. const double g = 1.0 / 0x7fffffff;
  200382. if (littleEndian)
  200383. {
  200384. while (--numSamples >= 0)
  200385. {
  200386. *dest++ = (float) (g * (int) littleEndianInt (src));
  200387. src += srcStrideBytes;
  200388. }
  200389. }
  200390. else
  200391. {
  200392. while (--numSamples >= 0)
  200393. {
  200394. *dest++ = (float) (g * (int) bigEndianInt (src));
  200395. src += srcStrideBytes;
  200396. }
  200397. }
  200398. }
  200399. static void convertFloatToInt32 (const float* src,
  200400. char* dest,
  200401. const int dstStrideBytes,
  200402. int numSamples,
  200403. const bool littleEndian) throw()
  200404. {
  200405. const double maxVal = (double) 0x7fffffff;
  200406. if (littleEndian)
  200407. {
  200408. while (--numSamples >= 0)
  200409. {
  200410. *(uint32*) dest = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  200411. dest += dstStrideBytes;
  200412. }
  200413. }
  200414. else
  200415. {
  200416. while (--numSamples >= 0)
  200417. {
  200418. *(uint32*) dest = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  200419. dest += dstStrideBytes;
  200420. }
  200421. }
  200422. }
  200423. static void typeToFormatParameters (const long type,
  200424. int& bitDepth,
  200425. int& byteStride,
  200426. bool& formatIsFloat,
  200427. bool& littleEndian) throw()
  200428. {
  200429. bitDepth = 0;
  200430. littleEndian = false;
  200431. formatIsFloat = false;
  200432. switch (type)
  200433. {
  200434. case ASIOSTInt16MSB:
  200435. case ASIOSTInt16LSB:
  200436. case ASIOSTInt32MSB16:
  200437. case ASIOSTInt32LSB16:
  200438. bitDepth = 16; break;
  200439. case ASIOSTFloat32MSB:
  200440. case ASIOSTFloat32LSB:
  200441. formatIsFloat = true;
  200442. bitDepth = 32; break;
  200443. case ASIOSTInt32MSB:
  200444. case ASIOSTInt32LSB:
  200445. bitDepth = 32; break;
  200446. case ASIOSTInt24MSB:
  200447. case ASIOSTInt24LSB:
  200448. case ASIOSTInt32MSB24:
  200449. case ASIOSTInt32LSB24:
  200450. case ASIOSTInt32MSB18:
  200451. case ASIOSTInt32MSB20:
  200452. case ASIOSTInt32LSB18:
  200453. case ASIOSTInt32LSB20:
  200454. bitDepth = 24; break;
  200455. case ASIOSTFloat64MSB:
  200456. case ASIOSTFloat64LSB:
  200457. default:
  200458. bitDepth = 64;
  200459. break;
  200460. }
  200461. switch (type)
  200462. {
  200463. case ASIOSTInt16MSB:
  200464. case ASIOSTInt32MSB16:
  200465. case ASIOSTFloat32MSB:
  200466. case ASIOSTFloat64MSB:
  200467. case ASIOSTInt32MSB:
  200468. case ASIOSTInt32MSB18:
  200469. case ASIOSTInt32MSB20:
  200470. case ASIOSTInt32MSB24:
  200471. case ASIOSTInt24MSB:
  200472. littleEndian = false; break;
  200473. case ASIOSTInt16LSB:
  200474. case ASIOSTInt32LSB16:
  200475. case ASIOSTFloat32LSB:
  200476. case ASIOSTFloat64LSB:
  200477. case ASIOSTInt32LSB:
  200478. case ASIOSTInt32LSB18:
  200479. case ASIOSTInt32LSB20:
  200480. case ASIOSTInt32LSB24:
  200481. case ASIOSTInt24LSB:
  200482. littleEndian = true; break;
  200483. default:
  200484. break;
  200485. }
  200486. switch (type)
  200487. {
  200488. case ASIOSTInt16LSB:
  200489. case ASIOSTInt16MSB:
  200490. byteStride = 2; break;
  200491. case ASIOSTInt24LSB:
  200492. case ASIOSTInt24MSB:
  200493. byteStride = 3; break;
  200494. case ASIOSTInt32MSB16:
  200495. case ASIOSTInt32LSB16:
  200496. case ASIOSTInt32MSB:
  200497. case ASIOSTInt32MSB18:
  200498. case ASIOSTInt32MSB20:
  200499. case ASIOSTInt32MSB24:
  200500. case ASIOSTInt32LSB:
  200501. case ASIOSTInt32LSB18:
  200502. case ASIOSTInt32LSB20:
  200503. case ASIOSTInt32LSB24:
  200504. case ASIOSTFloat32LSB:
  200505. case ASIOSTFloat32MSB:
  200506. byteStride = 4; break;
  200507. case ASIOSTFloat64MSB:
  200508. case ASIOSTFloat64LSB:
  200509. byteStride = 8; break;
  200510. default:
  200511. break;
  200512. }
  200513. }
  200514. };
  200515. class ASIOAudioIODeviceType : public AudioIODeviceType
  200516. {
  200517. public:
  200518. ASIOAudioIODeviceType()
  200519. : AudioIODeviceType (T("ASIO")),
  200520. classIds (2),
  200521. hasScanned (false)
  200522. {
  200523. CoInitialize (0);
  200524. }
  200525. ~ASIOAudioIODeviceType()
  200526. {
  200527. }
  200528. void scanForDevices()
  200529. {
  200530. hasScanned = true;
  200531. deviceNames.clear();
  200532. classIds.clear();
  200533. HKEY hk = 0;
  200534. int index = 0;
  200535. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  200536. {
  200537. for (;;)
  200538. {
  200539. char name [256];
  200540. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  200541. {
  200542. addDriverInfo (name, hk);
  200543. }
  200544. else
  200545. {
  200546. break;
  200547. }
  200548. }
  200549. RegCloseKey (hk);
  200550. }
  200551. }
  200552. const StringArray getDeviceNames (const bool /*wantInputNames*/) const
  200553. {
  200554. jassert (hasScanned); // need to call scanForDevices() before doing this
  200555. return deviceNames;
  200556. }
  200557. int getDefaultDeviceIndex (const bool) const
  200558. {
  200559. jassert (hasScanned); // need to call scanForDevices() before doing this
  200560. for (int i = deviceNames.size(); --i >= 0;)
  200561. if (deviceNames[i].containsIgnoreCase (T("asio4all")))
  200562. return i; // asio4all is a safe choice for a default..
  200563. #if JUCE_DEBUG
  200564. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase (T("digidesign")))
  200565. return 1; // (the digi m-box driver crashes the app when you run
  200566. // it in the debugger, which can be a bit annoying)
  200567. #endif
  200568. return 0;
  200569. }
  200570. static int findFreeSlot()
  200571. {
  200572. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  200573. if (currentASIODev[i] == 0)
  200574. return i;
  200575. jassertfalse; // unfortunately you can only have a finite number
  200576. // of ASIO devices open at the same time..
  200577. return -1;
  200578. }
  200579. int getIndexOfDevice (AudioIODevice* d, const bool /*asInput*/) const
  200580. {
  200581. jassert (hasScanned); // need to call scanForDevices() before doing this
  200582. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  200583. }
  200584. bool hasSeparateInputsAndOutputs() const { return false; }
  200585. AudioIODevice* createDevice (const String& outputDeviceName,
  200586. const String& inputDeviceName)
  200587. {
  200588. jassert (inputDeviceName == outputDeviceName);
  200589. (void) inputDeviceName;
  200590. jassert (hasScanned); // need to call scanForDevices() before doing this
  200591. const int index = deviceNames.indexOf (outputDeviceName);
  200592. if (index >= 0)
  200593. {
  200594. const int freeSlot = findFreeSlot();
  200595. if (freeSlot >= 0)
  200596. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot);
  200597. }
  200598. return 0;
  200599. }
  200600. juce_UseDebuggingNewOperator
  200601. private:
  200602. StringArray deviceNames;
  200603. OwnedArray <CLSID> classIds;
  200604. bool hasScanned;
  200605. static bool checkClassIsOk (const String& classId)
  200606. {
  200607. HKEY hk = 0;
  200608. bool ok = false;
  200609. if (RegOpenKeyA (HKEY_CLASSES_ROOT, "clsid", &hk) == ERROR_SUCCESS)
  200610. {
  200611. int index = 0;
  200612. for (;;)
  200613. {
  200614. char buf [512];
  200615. if (RegEnumKeyA (hk, index++, buf, 512) == ERROR_SUCCESS)
  200616. {
  200617. if (classId.equalsIgnoreCase (buf))
  200618. {
  200619. HKEY subKey, pathKey;
  200620. if (RegOpenKeyExA (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  200621. {
  200622. if (RegOpenKeyExA (subKey, "InprocServer32", 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  200623. {
  200624. char pathName [600];
  200625. DWORD dtype = REG_SZ;
  200626. DWORD dsize = sizeof (pathName);
  200627. if (RegQueryValueExA (pathKey, 0, 0, &dtype,
  200628. (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  200629. {
  200630. OFSTRUCT of;
  200631. zerostruct (of);
  200632. of.cBytes = sizeof (of);
  200633. ok = (OpenFile (String (pathName), &of, OF_EXIST) != 0);
  200634. }
  200635. RegCloseKey (pathKey);
  200636. }
  200637. RegCloseKey (subKey);
  200638. }
  200639. break;
  200640. }
  200641. }
  200642. else
  200643. {
  200644. break;
  200645. }
  200646. }
  200647. RegCloseKey (hk);
  200648. }
  200649. return ok;
  200650. }
  200651. void addDriverInfo (const String& keyName, HKEY hk)
  200652. {
  200653. HKEY subKey;
  200654. if (RegOpenKeyExA (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  200655. {
  200656. char buf [256];
  200657. DWORD dtype = REG_SZ;
  200658. DWORD dsize = sizeof (buf);
  200659. zeromem (buf, dsize);
  200660. if (RegQueryValueExA (subKey, "clsid", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  200661. {
  200662. if (dsize > 0 && checkClassIsOk (buf))
  200663. {
  200664. wchar_t classIdStr [130];
  200665. MultiByteToWideChar (CP_ACP, 0, buf, -1, classIdStr, 128);
  200666. String deviceName;
  200667. CLSID classId;
  200668. if (CLSIDFromString ((LPOLESTR) classIdStr, &classId) == S_OK)
  200669. {
  200670. dtype = REG_SZ;
  200671. dsize = sizeof (buf);
  200672. if (RegQueryValueExA (subKey, "description", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  200673. deviceName = buf;
  200674. else
  200675. deviceName = keyName;
  200676. log (T("found ") + deviceName);
  200677. deviceNames.add (deviceName);
  200678. classIds.add (new CLSID (classId));
  200679. }
  200680. }
  200681. RegCloseKey (subKey);
  200682. }
  200683. }
  200684. }
  200685. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  200686. const ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  200687. };
  200688. AudioIODeviceType* juce_createASIOAudioIODeviceType()
  200689. {
  200690. return new ASIOAudioIODeviceType();
  200691. }
  200692. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  200693. void* guid)
  200694. {
  200695. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  200696. if (freeSlot < 0)
  200697. return 0;
  200698. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot);
  200699. }
  200700. END_JUCE_NAMESPACE
  200701. #undef log
  200702. #endif
  200703. /********* End of inlined file: juce_win32_ASIO.cpp *********/
  200704. /********* Start of inlined file: juce_win32_AudioCDReader.cpp *********/
  200705. #ifdef _MSC_VER
  200706. #pragma warning (disable: 4514)
  200707. #pragma warning (push)
  200708. #endif
  200709. #include <stddef.h>
  200710. #if JUCE_USE_CDBURNER
  200711. // you'll need the Platform SDK for these headers - if you don't have it and don't
  200712. // need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  200713. // flag in juce_Config.h to avoid these includes.
  200714. #include <imapi.h>
  200715. #include <imapierror.h>
  200716. #endif
  200717. BEGIN_JUCE_NAMESPACE
  200718. #ifdef _MSC_VER
  200719. #pragma warning (pop)
  200720. #endif
  200721. //***************************************************************************
  200722. // %%% TARGET STATUS VALUES %%%
  200723. //***************************************************************************
  200724. #define STATUS_GOOD 0x00 // Status Good
  200725. #define STATUS_CHKCOND 0x02 // Check Condition
  200726. #define STATUS_CONDMET 0x04 // Condition Met
  200727. #define STATUS_BUSY 0x08 // Busy
  200728. #define STATUS_INTERM 0x10 // Intermediate
  200729. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  200730. #define STATUS_RESCONF 0x18 // Reservation conflict
  200731. #define STATUS_COMTERM 0x22 // Command Terminated
  200732. #define STATUS_QFULL 0x28 // Queue full
  200733. //***************************************************************************
  200734. // %%% SCSI MISCELLANEOUS EQUATES %%%
  200735. //***************************************************************************
  200736. #define MAXLUN 7 // Maximum Logical Unit Id
  200737. #define MAXTARG 7 // Maximum Target Id
  200738. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  200739. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  200740. //***************************************************************************
  200741. // %%% Commands for all Device Types %%%
  200742. //***************************************************************************
  200743. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  200744. #define SCSI_COMPARE 0x39 // Compare (O)
  200745. #define SCSI_COPY 0x18 // Copy (O)
  200746. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  200747. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  200748. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  200749. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  200750. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  200751. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  200752. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  200753. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  200754. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  200755. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  200756. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  200757. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  200758. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  200759. //***************************************************************************
  200760. // %%% Commands Unique to Direct Access Devices %%%
  200761. //***************************************************************************
  200762. #define SCSI_COMPARE 0x39 // Compare (O)
  200763. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  200764. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  200765. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  200766. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  200767. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  200768. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  200769. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  200770. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  200771. #define SCSI_READ_LONG 0x3E // Read Long (O)
  200772. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  200773. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  200774. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  200775. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  200776. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  200777. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  200778. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  200779. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  200780. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  200781. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  200782. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  200783. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  200784. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  200785. #define SCSI_VERIFY 0x2F // Verify (O)
  200786. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  200787. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  200788. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  200789. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  200790. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  200791. //***************************************************************************
  200792. // %%% Commands Unique to Sequential Access Devices %%%
  200793. //***************************************************************************
  200794. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  200795. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  200796. #define SCSI_LOCATE 0x2B // Locate (O)
  200797. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  200798. #define SCSI_READ_POS 0x34 // Read Position (O)
  200799. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  200800. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  200801. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  200802. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  200803. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  200804. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  200805. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  200806. //***************************************************************************
  200807. // %%% Commands Unique to Printer Devices %%%
  200808. //***************************************************************************
  200809. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  200810. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  200811. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  200812. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  200813. //***************************************************************************
  200814. // %%% Commands Unique to Processor Devices %%%
  200815. //***************************************************************************
  200816. #define SCSI_RECEIVE 0x08 // Receive (O)
  200817. #define SCSI_SEND 0x0A // Send (O)
  200818. //***************************************************************************
  200819. // %%% Commands Unique to Write-Once Devices %%%
  200820. //***************************************************************************
  200821. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  200822. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  200823. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  200824. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  200825. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  200826. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  200827. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  200828. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  200829. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  200830. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  200831. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  200832. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  200833. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  200834. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  200835. //***************************************************************************
  200836. // %%% Commands Unique to CD-ROM Devices %%%
  200837. //***************************************************************************
  200838. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  200839. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  200840. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  200841. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  200842. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  200843. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  200844. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  200845. #define SCSI_READHEADER 0x44 // Read Header (O)
  200846. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  200847. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  200848. //***************************************************************************
  200849. // %%% Commands Unique to Scanner Devices %%%
  200850. //***************************************************************************
  200851. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  200852. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  200853. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  200854. #define SCSI_SCAN 0x1B // Scan (O)
  200855. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  200856. //***************************************************************************
  200857. // %%% Commands Unique to Optical Memory Devices %%%
  200858. //***************************************************************************
  200859. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  200860. //***************************************************************************
  200861. // %%% Commands Unique to Medium Changer Devices %%%
  200862. //***************************************************************************
  200863. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  200864. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  200865. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  200866. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  200867. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  200868. //***************************************************************************
  200869. // %%% Commands Unique to Communication Devices %%%
  200870. //***************************************************************************
  200871. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  200872. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  200873. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  200874. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  200875. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  200876. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  200877. //***************************************************************************
  200878. // %%% Request Sense Data Format %%%
  200879. //***************************************************************************
  200880. typedef struct {
  200881. BYTE ErrorCode; // Error Code (70H or 71H)
  200882. BYTE SegmentNum; // Number of current segment descriptor
  200883. BYTE SenseKey; // Sense Key(See bit definitions too)
  200884. BYTE InfoByte0; // Information MSB
  200885. BYTE InfoByte1; // Information MID
  200886. BYTE InfoByte2; // Information MID
  200887. BYTE InfoByte3; // Information LSB
  200888. BYTE AddSenLen; // Additional Sense Length
  200889. BYTE ComSpecInf0; // Command Specific Information MSB
  200890. BYTE ComSpecInf1; // Command Specific Information MID
  200891. BYTE ComSpecInf2; // Command Specific Information MID
  200892. BYTE ComSpecInf3; // Command Specific Information LSB
  200893. BYTE AddSenseCode; // Additional Sense Code
  200894. BYTE AddSenQual; // Additional Sense Code Qualifier
  200895. BYTE FieldRepUCode; // Field Replaceable Unit Code
  200896. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  200897. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  200898. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  200899. BYTE AddSenseBytes; // Additional Sense Bytes
  200900. } SENSE_DATA_FMT;
  200901. //***************************************************************************
  200902. // %%% REQUEST SENSE ERROR CODE %%%
  200903. //***************************************************************************
  200904. #define SERROR_CURRENT 0x70 // Current Errors
  200905. #define SERROR_DEFERED 0x71 // Deferred Errors
  200906. //***************************************************************************
  200907. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  200908. //***************************************************************************
  200909. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  200910. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  200911. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  200912. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  200913. //***************************************************************************
  200914. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  200915. //***************************************************************************
  200916. #define KEY_NOSENSE 0x00 // No Sense
  200917. #define KEY_RECERROR 0x01 // Recovered Error
  200918. #define KEY_NOTREADY 0x02 // Not Ready
  200919. #define KEY_MEDIUMERR 0x03 // Medium Error
  200920. #define KEY_HARDERROR 0x04 // Hardware Error
  200921. #define KEY_ILLGLREQ 0x05 // Illegal Request
  200922. #define KEY_UNITATT 0x06 // Unit Attention
  200923. #define KEY_DATAPROT 0x07 // Data Protect
  200924. #define KEY_BLANKCHK 0x08 // Blank Check
  200925. #define KEY_VENDSPEC 0x09 // Vendor Specific
  200926. #define KEY_COPYABORT 0x0A // Copy Abort
  200927. #define KEY_EQUAL 0x0C // Equal (Search)
  200928. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  200929. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  200930. #define KEY_RESERVED 0x0F // Reserved
  200931. //***************************************************************************
  200932. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  200933. //***************************************************************************
  200934. #define DTYPE_DASD 0x00 // Disk Device
  200935. #define DTYPE_SEQD 0x01 // Tape Device
  200936. #define DTYPE_PRNT 0x02 // Printer
  200937. #define DTYPE_PROC 0x03 // Processor
  200938. #define DTYPE_WORM 0x04 // Write-once read-multiple
  200939. #define DTYPE_CROM 0x05 // CD-ROM device
  200940. #define DTYPE_SCAN 0x06 // Scanner device
  200941. #define DTYPE_OPTI 0x07 // Optical memory device
  200942. #define DTYPE_JUKE 0x08 // Medium Changer device
  200943. #define DTYPE_COMM 0x09 // Communications device
  200944. #define DTYPE_RESL 0x0A // Reserved (low)
  200945. #define DTYPE_RESH 0x1E // Reserved (high)
  200946. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  200947. //***************************************************************************
  200948. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  200949. //***************************************************************************
  200950. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  200951. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  200952. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  200953. #define ANSI_RESLO 0x3 // Reserved (low)
  200954. #define ANSI_RESHI 0x7 // Reserved (high)
  200955. typedef struct
  200956. {
  200957. USHORT Length;
  200958. UCHAR ScsiStatus;
  200959. UCHAR PathId;
  200960. UCHAR TargetId;
  200961. UCHAR Lun;
  200962. UCHAR CdbLength;
  200963. UCHAR SenseInfoLength;
  200964. UCHAR DataIn;
  200965. ULONG DataTransferLength;
  200966. ULONG TimeOutValue;
  200967. ULONG DataBufferOffset;
  200968. ULONG SenseInfoOffset;
  200969. UCHAR Cdb[16];
  200970. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  200971. typedef struct
  200972. {
  200973. USHORT Length;
  200974. UCHAR ScsiStatus;
  200975. UCHAR PathId;
  200976. UCHAR TargetId;
  200977. UCHAR Lun;
  200978. UCHAR CdbLength;
  200979. UCHAR SenseInfoLength;
  200980. UCHAR DataIn;
  200981. ULONG DataTransferLength;
  200982. ULONG TimeOutValue;
  200983. PVOID DataBuffer;
  200984. ULONG SenseInfoOffset;
  200985. UCHAR Cdb[16];
  200986. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  200987. typedef struct
  200988. {
  200989. SCSI_PASS_THROUGH_DIRECT spt;
  200990. ULONG Filler;
  200991. UCHAR ucSenseBuf[32];
  200992. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  200993. typedef struct
  200994. {
  200995. ULONG Length;
  200996. UCHAR PortNumber;
  200997. UCHAR PathId;
  200998. UCHAR TargetId;
  200999. UCHAR Lun;
  201000. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  201001. #define METHOD_BUFFERED 0
  201002. #define METHOD_IN_DIRECT 1
  201003. #define METHOD_OUT_DIRECT 2
  201004. #define METHOD_NEITHER 3
  201005. #define FILE_ANY_ACCESS 0
  201006. #ifndef FILE_READ_ACCESS
  201007. #define FILE_READ_ACCESS (0x0001)
  201008. #endif
  201009. #ifndef FILE_WRITE_ACCESS
  201010. #define FILE_WRITE_ACCESS (0x0002)
  201011. #endif
  201012. #define IOCTL_SCSI_BASE 0x00000004
  201013. #define SCSI_IOCTL_DATA_OUT 0
  201014. #define SCSI_IOCTL_DATA_IN 1
  201015. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  201016. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  201017. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  201018. )
  201019. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  201020. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  201021. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  201022. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  201023. #define SENSE_LEN 14
  201024. #define SRB_DIR_SCSI 0x00
  201025. #define SRB_POSTING 0x01
  201026. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  201027. #define SRB_DIR_IN 0x08
  201028. #define SRB_DIR_OUT 0x10
  201029. #define SRB_EVENT_NOTIFY 0x40
  201030. #define RESIDUAL_COUNT_SUPPORTED 0x02
  201031. #define MAX_SRB_TIMEOUT 1080001u
  201032. #define DEFAULT_SRB_TIMEOUT 1080001u
  201033. #define SC_HA_INQUIRY 0x00
  201034. #define SC_GET_DEV_TYPE 0x01
  201035. #define SC_EXEC_SCSI_CMD 0x02
  201036. #define SC_ABORT_SRB 0x03
  201037. #define SC_RESET_DEV 0x04
  201038. #define SC_SET_HA_PARMS 0x05
  201039. #define SC_GET_DISK_INFO 0x06
  201040. #define SC_RESCAN_SCSI_BUS 0x07
  201041. #define SC_GETSET_TIMEOUTS 0x08
  201042. #define SS_PENDING 0x00
  201043. #define SS_COMP 0x01
  201044. #define SS_ABORTED 0x02
  201045. #define SS_ABORT_FAIL 0x03
  201046. #define SS_ERR 0x04
  201047. #define SS_INVALID_CMD 0x80
  201048. #define SS_INVALID_HA 0x81
  201049. #define SS_NO_DEVICE 0x82
  201050. #define SS_INVALID_SRB 0xE0
  201051. #define SS_OLD_MANAGER 0xE1
  201052. #define SS_BUFFER_ALIGN 0xE1
  201053. #define SS_ILLEGAL_MODE 0xE2
  201054. #define SS_NO_ASPI 0xE3
  201055. #define SS_FAILED_INIT 0xE4
  201056. #define SS_ASPI_IS_BUSY 0xE5
  201057. #define SS_BUFFER_TO_BIG 0xE6
  201058. #define SS_BUFFER_TOO_BIG 0xE6
  201059. #define SS_MISMATCHED_COMPONENTS 0xE7
  201060. #define SS_NO_ADAPTERS 0xE8
  201061. #define SS_INSUFFICIENT_RESOURCES 0xE9
  201062. #define SS_ASPI_IS_SHUTDOWN 0xEA
  201063. #define SS_BAD_INSTALL 0xEB
  201064. #define HASTAT_OK 0x00
  201065. #define HASTAT_SEL_TO 0x11
  201066. #define HASTAT_DO_DU 0x12
  201067. #define HASTAT_BUS_FREE 0x13
  201068. #define HASTAT_PHASE_ERR 0x14
  201069. #define HASTAT_TIMEOUT 0x09
  201070. #define HASTAT_COMMAND_TIMEOUT 0x0B
  201071. #define HASTAT_MESSAGE_REJECT 0x0D
  201072. #define HASTAT_BUS_RESET 0x0E
  201073. #define HASTAT_PARITY_ERROR 0x0F
  201074. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  201075. #define PACKED
  201076. #pragma pack(1)
  201077. typedef struct
  201078. {
  201079. BYTE SRB_Cmd;
  201080. BYTE SRB_Status;
  201081. BYTE SRB_HaID;
  201082. BYTE SRB_Flags;
  201083. DWORD SRB_Hdr_Rsvd;
  201084. BYTE HA_Count;
  201085. BYTE HA_SCSI_ID;
  201086. BYTE HA_ManagerId[16];
  201087. BYTE HA_Identifier[16];
  201088. BYTE HA_Unique[16];
  201089. WORD HA_Rsvd1;
  201090. BYTE pad[20];
  201091. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  201092. typedef struct
  201093. {
  201094. BYTE SRB_Cmd;
  201095. BYTE SRB_Status;
  201096. BYTE SRB_HaID;
  201097. BYTE SRB_Flags;
  201098. DWORD SRB_Hdr_Rsvd;
  201099. BYTE SRB_Target;
  201100. BYTE SRB_Lun;
  201101. BYTE SRB_DeviceType;
  201102. BYTE SRB_Rsvd1;
  201103. BYTE pad[68];
  201104. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  201105. typedef struct
  201106. {
  201107. BYTE SRB_Cmd;
  201108. BYTE SRB_Status;
  201109. BYTE SRB_HaID;
  201110. BYTE SRB_Flags;
  201111. DWORD SRB_Hdr_Rsvd;
  201112. BYTE SRB_Target;
  201113. BYTE SRB_Lun;
  201114. WORD SRB_Rsvd1;
  201115. DWORD SRB_BufLen;
  201116. BYTE FAR *SRB_BufPointer;
  201117. BYTE SRB_SenseLen;
  201118. BYTE SRB_CDBLen;
  201119. BYTE SRB_HaStat;
  201120. BYTE SRB_TargStat;
  201121. VOID FAR *SRB_PostProc;
  201122. BYTE SRB_Rsvd2[20];
  201123. BYTE CDBByte[16];
  201124. BYTE SenseArea[SENSE_LEN+2];
  201125. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  201126. typedef struct
  201127. {
  201128. BYTE SRB_Cmd;
  201129. BYTE SRB_Status;
  201130. BYTE SRB_HaId;
  201131. BYTE SRB_Flags;
  201132. DWORD SRB_Hdr_Rsvd;
  201133. } PACKED SRB, *PSRB, FAR *LPSRB;
  201134. #pragma pack()
  201135. struct CDDeviceInfo
  201136. {
  201137. char vendor[9];
  201138. char productId[17];
  201139. char rev[5];
  201140. char vendorSpec[21];
  201141. BYTE ha;
  201142. BYTE tgt;
  201143. BYTE lun;
  201144. char scsiDriveLetter; // will be 0 if not using scsi
  201145. };
  201146. class CDReadBuffer
  201147. {
  201148. public:
  201149. int startFrame;
  201150. int numFrames;
  201151. int dataStartOffset;
  201152. int dataLength;
  201153. BYTE* buffer;
  201154. int bufferSize;
  201155. int index;
  201156. bool wantsIndex;
  201157. CDReadBuffer (const int numberOfFrames)
  201158. : startFrame (0),
  201159. numFrames (0),
  201160. dataStartOffset (0),
  201161. dataLength (0),
  201162. index (0),
  201163. wantsIndex (false)
  201164. {
  201165. bufferSize = 2352 * numberOfFrames;
  201166. buffer = (BYTE*) malloc (bufferSize);
  201167. }
  201168. ~CDReadBuffer()
  201169. {
  201170. free (buffer);
  201171. }
  201172. bool isZero() const
  201173. {
  201174. BYTE* p = buffer + dataStartOffset;
  201175. for (int i = dataLength; --i >= 0;)
  201176. if (*p++ != 0)
  201177. return false;
  201178. return true;
  201179. }
  201180. };
  201181. class CDDeviceHandle;
  201182. class CDController
  201183. {
  201184. public:
  201185. CDController();
  201186. virtual ~CDController();
  201187. virtual bool read (CDReadBuffer* t) = 0;
  201188. virtual void shutDown();
  201189. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  201190. int getLastIndex();
  201191. public:
  201192. bool initialised;
  201193. CDDeviceHandle* deviceInfo;
  201194. int framesToCheck, framesOverlap;
  201195. void prepare (SRB_ExecSCSICmd& s);
  201196. void perform (SRB_ExecSCSICmd& s);
  201197. void setPaused (bool paused);
  201198. };
  201199. #pragma pack(1)
  201200. struct TOCTRACK
  201201. {
  201202. BYTE rsvd;
  201203. BYTE ADR;
  201204. BYTE trackNumber;
  201205. BYTE rsvd2;
  201206. BYTE addr[4];
  201207. };
  201208. struct TOC
  201209. {
  201210. WORD tocLen;
  201211. BYTE firstTrack;
  201212. BYTE lastTrack;
  201213. TOCTRACK tracks[100];
  201214. };
  201215. #pragma pack()
  201216. enum
  201217. {
  201218. READTYPE_ANY = 0,
  201219. READTYPE_ATAPI1 = 1,
  201220. READTYPE_ATAPI2 = 2,
  201221. READTYPE_READ6 = 3,
  201222. READTYPE_READ10 = 4,
  201223. READTYPE_READ_D8 = 5,
  201224. READTYPE_READ_D4 = 6,
  201225. READTYPE_READ_D4_1 = 7,
  201226. READTYPE_READ10_2 = 8
  201227. };
  201228. class CDDeviceHandle
  201229. {
  201230. public:
  201231. CDDeviceHandle (const CDDeviceInfo* const device)
  201232. : scsiHandle (0),
  201233. readType (READTYPE_ANY),
  201234. controller (0)
  201235. {
  201236. memcpy (&info, device, sizeof (info));
  201237. }
  201238. ~CDDeviceHandle()
  201239. {
  201240. if (controller != 0)
  201241. {
  201242. controller->shutDown();
  201243. delete controller;
  201244. }
  201245. if (scsiHandle != 0)
  201246. CloseHandle (scsiHandle);
  201247. }
  201248. bool readTOC (TOC* lpToc, bool useMSF);
  201249. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  201250. void openDrawer (bool shouldBeOpen);
  201251. CDDeviceInfo info;
  201252. HANDLE scsiHandle;
  201253. BYTE readType;
  201254. private:
  201255. CDController* controller;
  201256. bool testController (const int readType,
  201257. CDController* const newController,
  201258. CDReadBuffer* const bufferToUse);
  201259. };
  201260. DWORD (*fGetASPI32SupportInfo)(void);
  201261. DWORD (*fSendASPI32Command)(LPSRB);
  201262. static HINSTANCE winAspiLib = 0;
  201263. static bool usingScsi = false;
  201264. static bool initialised = false;
  201265. static bool InitialiseCDRipper()
  201266. {
  201267. if (! initialised)
  201268. {
  201269. initialised = true;
  201270. OSVERSIONINFO info;
  201271. info.dwOSVersionInfoSize = sizeof (info);
  201272. GetVersionEx (&info);
  201273. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  201274. if (! usingScsi)
  201275. {
  201276. fGetASPI32SupportInfo = 0;
  201277. fSendASPI32Command = 0;
  201278. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  201279. if (winAspiLib != 0)
  201280. {
  201281. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  201282. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  201283. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  201284. return false;
  201285. }
  201286. else
  201287. {
  201288. usingScsi = true;
  201289. }
  201290. }
  201291. }
  201292. return true;
  201293. }
  201294. static void DeinitialiseCDRipper()
  201295. {
  201296. if (winAspiLib != 0)
  201297. {
  201298. fGetASPI32SupportInfo = 0;
  201299. fSendASPI32Command = 0;
  201300. FreeLibrary (winAspiLib);
  201301. winAspiLib = 0;
  201302. }
  201303. initialised = false;
  201304. }
  201305. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  201306. {
  201307. TCHAR devicePath[8];
  201308. devicePath[0] = '\\';
  201309. devicePath[1] = '\\';
  201310. devicePath[2] = '.';
  201311. devicePath[3] = '\\';
  201312. devicePath[4] = driveLetter;
  201313. devicePath[5] = ':';
  201314. devicePath[6] = 0;
  201315. OSVERSIONINFO info;
  201316. info.dwOSVersionInfoSize = sizeof (info);
  201317. GetVersionEx (&info);
  201318. DWORD flags = GENERIC_READ;
  201319. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  201320. flags = GENERIC_READ | GENERIC_WRITE;
  201321. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  201322. if (h == INVALID_HANDLE_VALUE)
  201323. {
  201324. flags ^= GENERIC_WRITE;
  201325. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  201326. }
  201327. return h;
  201328. }
  201329. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  201330. const char driveLetter,
  201331. HANDLE& deviceHandle,
  201332. const bool retryOnFailure = true)
  201333. {
  201334. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  201335. zerostruct (s);
  201336. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  201337. s.spt.CdbLength = srb->SRB_CDBLen;
  201338. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  201339. ? SCSI_IOCTL_DATA_IN
  201340. : ((srb->SRB_Flags & SRB_DIR_OUT)
  201341. ? SCSI_IOCTL_DATA_OUT
  201342. : SCSI_IOCTL_DATA_UNSPECIFIED));
  201343. s.spt.DataTransferLength = srb->SRB_BufLen;
  201344. s.spt.TimeOutValue = 5;
  201345. s.spt.DataBuffer = srb->SRB_BufPointer;
  201346. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  201347. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  201348. srb->SRB_Status = SS_ERR;
  201349. srb->SRB_TargStat = 0x0004;
  201350. DWORD bytesReturned = 0;
  201351. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  201352. &s, sizeof (s),
  201353. &s, sizeof (s),
  201354. &bytesReturned, 0) != 0)
  201355. {
  201356. srb->SRB_Status = SS_COMP;
  201357. }
  201358. else if (retryOnFailure)
  201359. {
  201360. const DWORD error = GetLastError();
  201361. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  201362. {
  201363. if (error != ERROR_INVALID_HANDLE)
  201364. CloseHandle (deviceHandle);
  201365. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  201366. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  201367. }
  201368. }
  201369. return srb->SRB_Status;
  201370. }
  201371. // Controller types..
  201372. class ControllerType1 : public CDController
  201373. {
  201374. public:
  201375. ControllerType1() {}
  201376. ~ControllerType1() {}
  201377. bool read (CDReadBuffer* rb)
  201378. {
  201379. if (rb->numFrames * 2352 > rb->bufferSize)
  201380. return false;
  201381. SRB_ExecSCSICmd s;
  201382. prepare (s);
  201383. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201384. s.SRB_BufLen = rb->bufferSize;
  201385. s.SRB_BufPointer = rb->buffer;
  201386. s.SRB_CDBLen = 12;
  201387. s.CDBByte[0] = 0xBE;
  201388. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  201389. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  201390. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  201391. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  201392. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  201393. perform (s);
  201394. if (s.SRB_Status != SS_COMP)
  201395. return false;
  201396. rb->dataLength = rb->numFrames * 2352;
  201397. rb->dataStartOffset = 0;
  201398. return true;
  201399. }
  201400. };
  201401. class ControllerType2 : public CDController
  201402. {
  201403. public:
  201404. ControllerType2() {}
  201405. ~ControllerType2() {}
  201406. void shutDown()
  201407. {
  201408. if (initialised)
  201409. {
  201410. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  201411. SRB_ExecSCSICmd s;
  201412. prepare (s);
  201413. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  201414. s.SRB_BufLen = 0x0C;
  201415. s.SRB_BufPointer = bufPointer;
  201416. s.SRB_CDBLen = 6;
  201417. s.CDBByte[0] = 0x15;
  201418. s.CDBByte[4] = 0x0C;
  201419. perform (s);
  201420. }
  201421. }
  201422. bool init()
  201423. {
  201424. SRB_ExecSCSICmd s;
  201425. s.SRB_Status = SS_ERR;
  201426. if (deviceInfo->readType == READTYPE_READ10_2)
  201427. {
  201428. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  201429. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  201430. for (int i = 0; i < 2; ++i)
  201431. {
  201432. prepare (s);
  201433. s.SRB_Flags = SRB_EVENT_NOTIFY;
  201434. s.SRB_BufLen = 0x14;
  201435. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  201436. s.SRB_CDBLen = 6;
  201437. s.CDBByte[0] = 0x15;
  201438. s.CDBByte[1] = 0x10;
  201439. s.CDBByte[4] = 0x14;
  201440. perform (s);
  201441. if (s.SRB_Status != SS_COMP)
  201442. return false;
  201443. }
  201444. }
  201445. else
  201446. {
  201447. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  201448. prepare (s);
  201449. s.SRB_Flags = SRB_EVENT_NOTIFY;
  201450. s.SRB_BufLen = 0x0C;
  201451. s.SRB_BufPointer = bufPointer;
  201452. s.SRB_CDBLen = 6;
  201453. s.CDBByte[0] = 0x15;
  201454. s.CDBByte[4] = 0x0C;
  201455. perform (s);
  201456. }
  201457. return s.SRB_Status == SS_COMP;
  201458. }
  201459. bool read (CDReadBuffer* rb)
  201460. {
  201461. if (rb->numFrames * 2352 > rb->bufferSize)
  201462. return false;
  201463. if (!initialised)
  201464. {
  201465. initialised = init();
  201466. if (!initialised)
  201467. return false;
  201468. }
  201469. SRB_ExecSCSICmd s;
  201470. prepare (s);
  201471. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201472. s.SRB_BufLen = rb->bufferSize;
  201473. s.SRB_BufPointer = rb->buffer;
  201474. s.SRB_CDBLen = 10;
  201475. s.CDBByte[0] = 0x28;
  201476. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  201477. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  201478. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  201479. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  201480. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  201481. perform (s);
  201482. if (s.SRB_Status != SS_COMP)
  201483. return false;
  201484. rb->dataLength = rb->numFrames * 2352;
  201485. rb->dataStartOffset = 0;
  201486. return true;
  201487. }
  201488. };
  201489. class ControllerType3 : public CDController
  201490. {
  201491. public:
  201492. ControllerType3() {}
  201493. ~ControllerType3() {}
  201494. bool read (CDReadBuffer* rb)
  201495. {
  201496. if (rb->numFrames * 2352 > rb->bufferSize)
  201497. return false;
  201498. if (!initialised)
  201499. {
  201500. setPaused (false);
  201501. initialised = true;
  201502. }
  201503. SRB_ExecSCSICmd s;
  201504. prepare (s);
  201505. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201506. s.SRB_BufLen = rb->numFrames * 2352;
  201507. s.SRB_BufPointer = rb->buffer;
  201508. s.SRB_CDBLen = 12;
  201509. s.CDBByte[0] = 0xD8;
  201510. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  201511. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  201512. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  201513. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  201514. perform (s);
  201515. if (s.SRB_Status != SS_COMP)
  201516. return false;
  201517. rb->dataLength = rb->numFrames * 2352;
  201518. rb->dataStartOffset = 0;
  201519. return true;
  201520. }
  201521. };
  201522. class ControllerType4 : public CDController
  201523. {
  201524. public:
  201525. ControllerType4() {}
  201526. ~ControllerType4() {}
  201527. bool selectD4Mode()
  201528. {
  201529. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  201530. SRB_ExecSCSICmd s;
  201531. prepare (s);
  201532. s.SRB_Flags = SRB_EVENT_NOTIFY;
  201533. s.SRB_CDBLen = 6;
  201534. s.SRB_BufLen = 12;
  201535. s.SRB_BufPointer = bufPointer;
  201536. s.CDBByte[0] = 0x15;
  201537. s.CDBByte[1] = 0x10;
  201538. s.CDBByte[4] = 0x08;
  201539. perform (s);
  201540. return s.SRB_Status == SS_COMP;
  201541. }
  201542. bool read (CDReadBuffer* rb)
  201543. {
  201544. if (rb->numFrames * 2352 > rb->bufferSize)
  201545. return false;
  201546. if (!initialised)
  201547. {
  201548. setPaused (true);
  201549. if (deviceInfo->readType == READTYPE_READ_D4_1)
  201550. selectD4Mode();
  201551. initialised = true;
  201552. }
  201553. SRB_ExecSCSICmd s;
  201554. prepare (s);
  201555. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201556. s.SRB_BufLen = rb->bufferSize;
  201557. s.SRB_BufPointer = rb->buffer;
  201558. s.SRB_CDBLen = 10;
  201559. s.CDBByte[0] = 0xD4;
  201560. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  201561. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  201562. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  201563. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  201564. perform (s);
  201565. if (s.SRB_Status != SS_COMP)
  201566. return false;
  201567. rb->dataLength = rb->numFrames * 2352;
  201568. rb->dataStartOffset = 0;
  201569. return true;
  201570. }
  201571. };
  201572. CDController::CDController() : initialised (false)
  201573. {
  201574. }
  201575. CDController::~CDController()
  201576. {
  201577. }
  201578. void CDController::prepare (SRB_ExecSCSICmd& s)
  201579. {
  201580. zerostruct (s);
  201581. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  201582. s.SRB_HaID = deviceInfo->info.ha;
  201583. s.SRB_Target = deviceInfo->info.tgt;
  201584. s.SRB_Lun = deviceInfo->info.lun;
  201585. s.SRB_SenseLen = SENSE_LEN;
  201586. }
  201587. void CDController::perform (SRB_ExecSCSICmd& s)
  201588. {
  201589. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  201590. s.SRB_PostProc = (void*)event;
  201591. ResetEvent (event);
  201592. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  201593. deviceInfo->info.scsiDriveLetter,
  201594. deviceInfo->scsiHandle)
  201595. : fSendASPI32Command ((LPSRB)&s);
  201596. if (status == SS_PENDING)
  201597. WaitForSingleObject (event, 4000);
  201598. CloseHandle (event);
  201599. }
  201600. void CDController::setPaused (bool paused)
  201601. {
  201602. SRB_ExecSCSICmd s;
  201603. prepare (s);
  201604. s.SRB_Flags = SRB_EVENT_NOTIFY;
  201605. s.SRB_CDBLen = 10;
  201606. s.CDBByte[0] = 0x4B;
  201607. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  201608. perform (s);
  201609. }
  201610. void CDController::shutDown()
  201611. {
  201612. }
  201613. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  201614. {
  201615. if (overlapBuffer != 0)
  201616. {
  201617. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  201618. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  201619. if (doJitter
  201620. && overlapBuffer->startFrame > 0
  201621. && overlapBuffer->numFrames > 0
  201622. && overlapBuffer->dataLength > 0)
  201623. {
  201624. const int numFrames = rb->numFrames;
  201625. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  201626. {
  201627. rb->startFrame -= framesOverlap;
  201628. if (framesToCheck < framesOverlap
  201629. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  201630. rb->numFrames += framesOverlap;
  201631. }
  201632. else
  201633. {
  201634. overlapBuffer->dataLength = 0;
  201635. overlapBuffer->startFrame = 0;
  201636. overlapBuffer->numFrames = 0;
  201637. }
  201638. }
  201639. if (! read (rb))
  201640. return false;
  201641. if (doJitter)
  201642. {
  201643. const int checkLen = framesToCheck * 2352;
  201644. const int maxToCheck = rb->dataLength - checkLen;
  201645. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  201646. return true;
  201647. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  201648. bool found = false;
  201649. for (int i = 0; i < maxToCheck; ++i)
  201650. {
  201651. if (!memcmp (p, rb->buffer + i, checkLen))
  201652. {
  201653. i += checkLen;
  201654. rb->dataStartOffset = i;
  201655. rb->dataLength -= i;
  201656. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  201657. found = true;
  201658. break;
  201659. }
  201660. }
  201661. rb->numFrames = rb->dataLength / 2352;
  201662. rb->dataLength = 2352 * rb->numFrames;
  201663. if (!found)
  201664. return false;
  201665. }
  201666. if (canDoJitter)
  201667. {
  201668. memcpy (overlapBuffer->buffer,
  201669. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  201670. 2352 * framesToCheck);
  201671. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  201672. overlapBuffer->numFrames = framesToCheck;
  201673. overlapBuffer->dataLength = 2352 * framesToCheck;
  201674. overlapBuffer->dataStartOffset = 0;
  201675. }
  201676. else
  201677. {
  201678. overlapBuffer->startFrame = 0;
  201679. overlapBuffer->numFrames = 0;
  201680. overlapBuffer->dataLength = 0;
  201681. }
  201682. return true;
  201683. }
  201684. else
  201685. {
  201686. return read (rb);
  201687. }
  201688. }
  201689. int CDController::getLastIndex()
  201690. {
  201691. char qdata[100];
  201692. SRB_ExecSCSICmd s;
  201693. prepare (s);
  201694. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201695. s.SRB_BufLen = sizeof (qdata);
  201696. s.SRB_BufPointer = (BYTE*)qdata;
  201697. s.SRB_CDBLen = 12;
  201698. s.CDBByte[0] = 0x42;
  201699. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  201700. s.CDBByte[2] = 64;
  201701. s.CDBByte[3] = 1; // get current position
  201702. s.CDBByte[7] = 0;
  201703. s.CDBByte[8] = (BYTE)sizeof (qdata);
  201704. perform (s);
  201705. if (s.SRB_Status == SS_COMP)
  201706. return qdata[7];
  201707. return 0;
  201708. }
  201709. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  201710. {
  201711. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  201712. SRB_ExecSCSICmd s;
  201713. zerostruct (s);
  201714. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  201715. s.SRB_HaID = info.ha;
  201716. s.SRB_Target = info.tgt;
  201717. s.SRB_Lun = info.lun;
  201718. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201719. s.SRB_BufLen = 0x324;
  201720. s.SRB_BufPointer = (BYTE*)lpToc;
  201721. s.SRB_SenseLen = 0x0E;
  201722. s.SRB_CDBLen = 0x0A;
  201723. s.SRB_PostProc = (void*)event;
  201724. s.CDBByte[0] = 0x43;
  201725. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  201726. s.CDBByte[7] = 0x03;
  201727. s.CDBByte[8] = 0x24;
  201728. ResetEvent (event);
  201729. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  201730. : fSendASPI32Command ((LPSRB)&s);
  201731. if (status == SS_PENDING)
  201732. WaitForSingleObject (event, 4000);
  201733. CloseHandle (event);
  201734. return (s.SRB_Status == SS_COMP);
  201735. }
  201736. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  201737. CDReadBuffer* const overlapBuffer)
  201738. {
  201739. if (controller == 0)
  201740. {
  201741. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  201742. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  201743. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  201744. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  201745. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  201746. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  201747. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  201748. }
  201749. buffer->index = 0;
  201750. if ((controller != 0)
  201751. && controller->readAudio (buffer, overlapBuffer))
  201752. {
  201753. if (buffer->wantsIndex)
  201754. buffer->index = controller->getLastIndex();
  201755. return true;
  201756. }
  201757. return false;
  201758. }
  201759. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  201760. {
  201761. if (shouldBeOpen)
  201762. {
  201763. if (controller != 0)
  201764. {
  201765. controller->shutDown();
  201766. delete controller;
  201767. controller = 0;
  201768. }
  201769. if (scsiHandle != 0)
  201770. {
  201771. CloseHandle (scsiHandle);
  201772. scsiHandle = 0;
  201773. }
  201774. }
  201775. SRB_ExecSCSICmd s;
  201776. zerostruct (s);
  201777. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  201778. s.SRB_HaID = info.ha;
  201779. s.SRB_Target = info.tgt;
  201780. s.SRB_Lun = info.lun;
  201781. s.SRB_SenseLen = SENSE_LEN;
  201782. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201783. s.SRB_BufLen = 0;
  201784. s.SRB_BufPointer = 0;
  201785. s.SRB_CDBLen = 12;
  201786. s.CDBByte[0] = 0x1b;
  201787. s.CDBByte[1] = (BYTE)(info.lun << 5);
  201788. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  201789. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  201790. s.SRB_PostProc = (void*)event;
  201791. ResetEvent (event);
  201792. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  201793. : fSendASPI32Command ((LPSRB)&s);
  201794. if (status == SS_PENDING)
  201795. WaitForSingleObject (event, 4000);
  201796. CloseHandle (event);
  201797. }
  201798. bool CDDeviceHandle::testController (const int type,
  201799. CDController* const newController,
  201800. CDReadBuffer* const rb)
  201801. {
  201802. controller = newController;
  201803. readType = (BYTE)type;
  201804. controller->deviceInfo = this;
  201805. controller->framesToCheck = 1;
  201806. controller->framesOverlap = 3;
  201807. bool passed = false;
  201808. memset (rb->buffer, 0xcd, rb->bufferSize);
  201809. if (controller->read (rb))
  201810. {
  201811. passed = true;
  201812. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  201813. int wrong = 0;
  201814. for (int i = rb->dataLength / 4; --i >= 0;)
  201815. {
  201816. if (*p++ == (int) 0xcdcdcdcd)
  201817. {
  201818. if (++wrong == 4)
  201819. {
  201820. passed = false;
  201821. break;
  201822. }
  201823. }
  201824. else
  201825. {
  201826. wrong = 0;
  201827. }
  201828. }
  201829. }
  201830. if (! passed)
  201831. {
  201832. controller->shutDown();
  201833. delete controller;
  201834. controller = 0;
  201835. }
  201836. return passed;
  201837. }
  201838. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  201839. {
  201840. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  201841. const int bufSize = 128;
  201842. BYTE buffer[bufSize];
  201843. zeromem (buffer, bufSize);
  201844. SRB_ExecSCSICmd s;
  201845. zerostruct (s);
  201846. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  201847. s.SRB_HaID = ha;
  201848. s.SRB_Target = tgt;
  201849. s.SRB_Lun = lun;
  201850. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201851. s.SRB_BufLen = bufSize;
  201852. s.SRB_BufPointer = buffer;
  201853. s.SRB_SenseLen = SENSE_LEN;
  201854. s.SRB_CDBLen = 6;
  201855. s.SRB_PostProc = (void*)event;
  201856. s.CDBByte[0] = SCSI_INQUIRY;
  201857. s.CDBByte[4] = 100;
  201858. ResetEvent (event);
  201859. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  201860. WaitForSingleObject (event, 4000);
  201861. CloseHandle (event);
  201862. if (s.SRB_Status == SS_COMP)
  201863. {
  201864. memcpy (dev->vendor, &buffer[8], 8);
  201865. memcpy (dev->productId, &buffer[16], 16);
  201866. memcpy (dev->rev, &buffer[32], 4);
  201867. memcpy (dev->vendorSpec, &buffer[36], 20);
  201868. }
  201869. }
  201870. static int FindCDDevices (CDDeviceInfo* const list,
  201871. int maxItems)
  201872. {
  201873. int count = 0;
  201874. if (usingScsi)
  201875. {
  201876. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  201877. {
  201878. TCHAR drivePath[8];
  201879. drivePath[0] = driveLetter;
  201880. drivePath[1] = ':';
  201881. drivePath[2] = '\\';
  201882. drivePath[3] = 0;
  201883. if (GetDriveType (drivePath) == DRIVE_CDROM)
  201884. {
  201885. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  201886. if (h != INVALID_HANDLE_VALUE)
  201887. {
  201888. BYTE buffer[100], passThroughStruct[1024];
  201889. zeromem (buffer, sizeof (buffer));
  201890. zeromem (passThroughStruct, sizeof (passThroughStruct));
  201891. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  201892. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  201893. p->spt.CdbLength = 6;
  201894. p->spt.SenseInfoLength = 24;
  201895. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  201896. p->spt.DataTransferLength = 100;
  201897. p->spt.TimeOutValue = 2;
  201898. p->spt.DataBuffer = buffer;
  201899. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  201900. p->spt.Cdb[0] = 0x12;
  201901. p->spt.Cdb[4] = 100;
  201902. DWORD bytesReturned = 0;
  201903. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  201904. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  201905. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  201906. &bytesReturned, 0) != 0)
  201907. {
  201908. zeromem (&list[count], sizeof (CDDeviceInfo));
  201909. list[count].scsiDriveLetter = driveLetter;
  201910. memcpy (list[count].vendor, &buffer[8], 8);
  201911. memcpy (list[count].productId, &buffer[16], 16);
  201912. memcpy (list[count].rev, &buffer[32], 4);
  201913. memcpy (list[count].vendorSpec, &buffer[36], 20);
  201914. zeromem (passThroughStruct, sizeof (passThroughStruct));
  201915. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  201916. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  201917. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  201918. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  201919. &bytesReturned, 0) != 0)
  201920. {
  201921. list[count].ha = scsiAddr->PortNumber;
  201922. list[count].tgt = scsiAddr->TargetId;
  201923. list[count].lun = scsiAddr->Lun;
  201924. ++count;
  201925. }
  201926. }
  201927. CloseHandle (h);
  201928. }
  201929. }
  201930. }
  201931. }
  201932. else
  201933. {
  201934. const DWORD d = fGetASPI32SupportInfo();
  201935. BYTE status = HIBYTE (LOWORD (d));
  201936. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  201937. return 0;
  201938. const int numAdapters = LOBYTE (LOWORD (d));
  201939. for (BYTE ha = 0; ha < numAdapters; ++ha)
  201940. {
  201941. SRB_HAInquiry s;
  201942. zerostruct (s);
  201943. s.SRB_Cmd = SC_HA_INQUIRY;
  201944. s.SRB_HaID = ha;
  201945. fSendASPI32Command ((LPSRB)&s);
  201946. if (s.SRB_Status == SS_COMP)
  201947. {
  201948. maxItems = (int)s.HA_Unique[3];
  201949. if (maxItems == 0)
  201950. maxItems = 8;
  201951. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  201952. {
  201953. for (BYTE lun = 0; lun < 8; ++lun)
  201954. {
  201955. SRB_GDEVBlock sb;
  201956. zerostruct (sb);
  201957. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  201958. sb.SRB_HaID = ha;
  201959. sb.SRB_Target = tgt;
  201960. sb.SRB_Lun = lun;
  201961. fSendASPI32Command ((LPSRB) &sb);
  201962. if (sb.SRB_Status == SS_COMP
  201963. && sb.SRB_DeviceType == DTYPE_CROM)
  201964. {
  201965. zeromem (&list[count], sizeof (CDDeviceInfo));
  201966. list[count].ha = ha;
  201967. list[count].tgt = tgt;
  201968. list[count].lun = lun;
  201969. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  201970. ++count;
  201971. }
  201972. }
  201973. }
  201974. }
  201975. }
  201976. }
  201977. return count;
  201978. }
  201979. static int ripperUsers = 0;
  201980. static bool initialisedOk = false;
  201981. class DeinitialiseTimer : private Timer,
  201982. private DeletedAtShutdown
  201983. {
  201984. DeinitialiseTimer (const DeinitialiseTimer&);
  201985. const DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  201986. public:
  201987. DeinitialiseTimer()
  201988. {
  201989. startTimer (4000);
  201990. }
  201991. ~DeinitialiseTimer()
  201992. {
  201993. if (--ripperUsers == 0)
  201994. DeinitialiseCDRipper();
  201995. }
  201996. void timerCallback()
  201997. {
  201998. delete this;
  201999. }
  202000. juce_UseDebuggingNewOperator
  202001. };
  202002. static void incUserCount()
  202003. {
  202004. if (ripperUsers++ == 0)
  202005. initialisedOk = InitialiseCDRipper();
  202006. }
  202007. static void decUserCount()
  202008. {
  202009. new DeinitialiseTimer();
  202010. }
  202011. struct CDDeviceWrapper
  202012. {
  202013. CDDeviceHandle* cdH;
  202014. CDReadBuffer* overlapBuffer;
  202015. bool jitter;
  202016. };
  202017. static int getAddressOf (const TOCTRACK* const t)
  202018. {
  202019. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  202020. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  202021. }
  202022. static int getMSFAddressOf (const TOCTRACK* const t)
  202023. {
  202024. return 60 * t->addr[1] + t->addr[2];
  202025. }
  202026. static const int samplesPerFrame = 44100 / 75;
  202027. static const int bytesPerFrame = samplesPerFrame * 4;
  202028. const StringArray AudioCDReader::getAvailableCDNames()
  202029. {
  202030. StringArray results;
  202031. incUserCount();
  202032. if (initialisedOk)
  202033. {
  202034. CDDeviceInfo list[8];
  202035. const int num = FindCDDevices (list, 8);
  202036. decUserCount();
  202037. for (int i = 0; i < num; ++i)
  202038. {
  202039. String s;
  202040. if (list[i].scsiDriveLetter > 0)
  202041. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << T(": ");
  202042. s << String (list[i].vendor).trim()
  202043. << T(" ") << String (list[i].productId).trim()
  202044. << T(" ") << String (list[i].rev).trim();
  202045. results.add (s);
  202046. }
  202047. }
  202048. return results;
  202049. }
  202050. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  202051. {
  202052. SRB_GDEVBlock s;
  202053. zerostruct (s);
  202054. s.SRB_Cmd = SC_GET_DEV_TYPE;
  202055. s.SRB_HaID = device->ha;
  202056. s.SRB_Target = device->tgt;
  202057. s.SRB_Lun = device->lun;
  202058. if (usingScsi)
  202059. {
  202060. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  202061. if (h != INVALID_HANDLE_VALUE)
  202062. {
  202063. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  202064. cdh->scsiHandle = h;
  202065. return cdh;
  202066. }
  202067. }
  202068. else
  202069. {
  202070. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  202071. && s.SRB_DeviceType == DTYPE_CROM)
  202072. {
  202073. return new CDDeviceHandle (device);
  202074. }
  202075. }
  202076. return 0;
  202077. }
  202078. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  202079. {
  202080. incUserCount();
  202081. if (initialisedOk)
  202082. {
  202083. CDDeviceInfo list[8];
  202084. const int num = FindCDDevices (list, 8);
  202085. if (((unsigned int) deviceIndex) < (unsigned int) num)
  202086. {
  202087. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  202088. if (handle != 0)
  202089. {
  202090. CDDeviceWrapper* const d = new CDDeviceWrapper();
  202091. d->cdH = handle;
  202092. d->overlapBuffer = new CDReadBuffer(3);
  202093. return new AudioCDReader (d);
  202094. }
  202095. }
  202096. }
  202097. decUserCount();
  202098. return 0;
  202099. }
  202100. AudioCDReader::AudioCDReader (void* handle_)
  202101. : AudioFormatReader (0, T("CD Audio")),
  202102. handle (handle_),
  202103. indexingEnabled (false),
  202104. lastIndex (0),
  202105. firstFrameInBuffer (0),
  202106. samplesInBuffer (0)
  202107. {
  202108. jassert (handle_ != 0);
  202109. refreshTrackLengths();
  202110. sampleRate = 44100.0;
  202111. bitsPerSample = 16;
  202112. lengthInSamples = getPositionOfTrackStart (numTracks);
  202113. numChannels = 2;
  202114. usesFloatingPointData = false;
  202115. buffer.setSize (4 * bytesPerFrame, true);
  202116. }
  202117. AudioCDReader::~AudioCDReader()
  202118. {
  202119. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  202120. delete device->cdH;
  202121. delete device->overlapBuffer;
  202122. delete device;
  202123. decUserCount();
  202124. }
  202125. bool AudioCDReader::read (int** destSamples,
  202126. int64 startSampleInFile,
  202127. int numSamples)
  202128. {
  202129. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  202130. bool ok = true;
  202131. int offset = 0;
  202132. if (startSampleInFile < 0)
  202133. {
  202134. int* l = destSamples[0];
  202135. int* r = destSamples[1];
  202136. numSamples += (int) startSampleInFile;
  202137. offset -= (int) startSampleInFile;
  202138. while (++startSampleInFile <= 0)
  202139. {
  202140. *l++ = 0;
  202141. if (r != 0)
  202142. *r++ = 0;
  202143. }
  202144. }
  202145. while (numSamples > 0)
  202146. {
  202147. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  202148. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  202149. if (startSampleInFile >= bufferStartSample
  202150. && startSampleInFile < bufferEndSample)
  202151. {
  202152. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  202153. int* const l = destSamples[0] + offset;
  202154. int* const r = destSamples[1] + offset;
  202155. const short* src = (const short*) buffer.getData();
  202156. src += 2 * (startSampleInFile - bufferStartSample);
  202157. for (int i = 0; i < toDo; ++i)
  202158. {
  202159. l[i] = src [i << 1] << 16;
  202160. if (r != 0)
  202161. r[i] = src [(i << 1) + 1] << 16;
  202162. }
  202163. offset += toDo;
  202164. startSampleInFile += toDo;
  202165. numSamples -= toDo;
  202166. }
  202167. else
  202168. {
  202169. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  202170. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  202171. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  202172. {
  202173. device->overlapBuffer->dataLength = 0;
  202174. device->overlapBuffer->startFrame = 0;
  202175. device->overlapBuffer->numFrames = 0;
  202176. device->jitter = false;
  202177. }
  202178. firstFrameInBuffer = frameNeeded;
  202179. lastIndex = 0;
  202180. CDReadBuffer readBuffer (framesInBuffer + 4);
  202181. readBuffer.wantsIndex = indexingEnabled;
  202182. int i;
  202183. for (i = 5; --i >= 0;)
  202184. {
  202185. readBuffer.startFrame = frameNeeded;
  202186. readBuffer.numFrames = framesInBuffer;
  202187. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  202188. break;
  202189. else
  202190. device->overlapBuffer->dataLength = 0;
  202191. }
  202192. if (i >= 0)
  202193. {
  202194. memcpy ((char*) buffer.getData(),
  202195. readBuffer.buffer + readBuffer.dataStartOffset,
  202196. readBuffer.dataLength);
  202197. samplesInBuffer = readBuffer.dataLength >> 2;
  202198. lastIndex = readBuffer.index;
  202199. }
  202200. else
  202201. {
  202202. int* l = destSamples[0] + offset;
  202203. int* r = destSamples[1] + offset;
  202204. while (--numSamples >= 0)
  202205. {
  202206. *l++ = 0;
  202207. if (r != 0)
  202208. *r++ = 0;
  202209. }
  202210. // sometimes the read fails for just the very last couple of blocks, so
  202211. // we'll ignore and errors in the last half-second of the disk..
  202212. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  202213. break;
  202214. }
  202215. }
  202216. }
  202217. return ok;
  202218. }
  202219. bool AudioCDReader::isCDStillPresent() const
  202220. {
  202221. TOC toc;
  202222. zerostruct (toc);
  202223. return ((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false);
  202224. }
  202225. int AudioCDReader::getNumTracks() const
  202226. {
  202227. return numTracks;
  202228. }
  202229. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  202230. {
  202231. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  202232. : 0;
  202233. }
  202234. void AudioCDReader::refreshTrackLengths()
  202235. {
  202236. zeromem (trackStarts, sizeof (trackStarts));
  202237. zeromem (audioTracks, sizeof (audioTracks));
  202238. TOC toc;
  202239. zerostruct (toc);
  202240. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  202241. {
  202242. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  202243. for (int i = 0; i <= numTracks; ++i)
  202244. {
  202245. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  202246. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  202247. }
  202248. }
  202249. else
  202250. {
  202251. numTracks = 0;
  202252. }
  202253. }
  202254. bool AudioCDReader::isTrackAudio (int trackNum) const
  202255. {
  202256. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  202257. : false;
  202258. }
  202259. void AudioCDReader::enableIndexScanning (bool b)
  202260. {
  202261. indexingEnabled = b;
  202262. }
  202263. int AudioCDReader::getLastIndex() const
  202264. {
  202265. return lastIndex;
  202266. }
  202267. const int framesPerIndexRead = 4;
  202268. int AudioCDReader::getIndexAt (int samplePos)
  202269. {
  202270. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  202271. const int frameNeeded = samplePos / samplesPerFrame;
  202272. device->overlapBuffer->dataLength = 0;
  202273. device->overlapBuffer->startFrame = 0;
  202274. device->overlapBuffer->numFrames = 0;
  202275. device->jitter = false;
  202276. firstFrameInBuffer = 0;
  202277. lastIndex = 0;
  202278. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  202279. readBuffer.wantsIndex = true;
  202280. int i;
  202281. for (i = 5; --i >= 0;)
  202282. {
  202283. readBuffer.startFrame = frameNeeded;
  202284. readBuffer.numFrames = framesPerIndexRead;
  202285. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  202286. break;
  202287. }
  202288. if (i >= 0)
  202289. return readBuffer.index;
  202290. return -1;
  202291. }
  202292. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  202293. {
  202294. Array <int> indexes;
  202295. const int trackStart = getPositionOfTrackStart (trackNumber);
  202296. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  202297. bool needToScan = true;
  202298. if (trackEnd - trackStart > 20 * 44100)
  202299. {
  202300. // check the end of the track for indexes before scanning the whole thing
  202301. needToScan = false;
  202302. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  202303. bool seenAnIndex = false;
  202304. while (pos <= trackEnd - samplesPerFrame)
  202305. {
  202306. const int index = getIndexAt (pos);
  202307. if (index == 0)
  202308. {
  202309. // lead-out, so skip back a bit if we've not found any indexes yet..
  202310. if (seenAnIndex)
  202311. break;
  202312. pos -= 44100 * 5;
  202313. if (pos < trackStart)
  202314. break;
  202315. }
  202316. else
  202317. {
  202318. if (index > 0)
  202319. seenAnIndex = true;
  202320. if (index > 1)
  202321. {
  202322. needToScan = true;
  202323. break;
  202324. }
  202325. pos += samplesPerFrame * framesPerIndexRead;
  202326. }
  202327. }
  202328. }
  202329. if (needToScan)
  202330. {
  202331. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  202332. int pos = trackStart;
  202333. int last = -1;
  202334. while (pos < trackEnd - samplesPerFrame * 10)
  202335. {
  202336. const int frameNeeded = pos / samplesPerFrame;
  202337. device->overlapBuffer->dataLength = 0;
  202338. device->overlapBuffer->startFrame = 0;
  202339. device->overlapBuffer->numFrames = 0;
  202340. device->jitter = false;
  202341. firstFrameInBuffer = 0;
  202342. CDReadBuffer readBuffer (4);
  202343. readBuffer.wantsIndex = true;
  202344. int i;
  202345. for (i = 5; --i >= 0;)
  202346. {
  202347. readBuffer.startFrame = frameNeeded;
  202348. readBuffer.numFrames = framesPerIndexRead;
  202349. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  202350. break;
  202351. }
  202352. if (i < 0)
  202353. break;
  202354. if (readBuffer.index > last && readBuffer.index > 1)
  202355. {
  202356. last = readBuffer.index;
  202357. indexes.add (pos);
  202358. }
  202359. pos += samplesPerFrame * framesPerIndexRead;
  202360. }
  202361. indexes.removeValue (trackStart);
  202362. }
  202363. return indexes;
  202364. }
  202365. int AudioCDReader::getCDDBId()
  202366. {
  202367. refreshTrackLengths();
  202368. if (numTracks > 0)
  202369. {
  202370. TOC toc;
  202371. zerostruct (toc);
  202372. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  202373. {
  202374. int n = 0;
  202375. for (int i = numTracks; --i >= 0;)
  202376. {
  202377. int j = getMSFAddressOf (&toc.tracks[i]);
  202378. while (j > 0)
  202379. {
  202380. n += (j % 10);
  202381. j /= 10;
  202382. }
  202383. }
  202384. if (n != 0)
  202385. {
  202386. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  202387. - getMSFAddressOf (&toc.tracks[0]);
  202388. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  202389. }
  202390. }
  202391. }
  202392. return 0;
  202393. }
  202394. void AudioCDReader::ejectDisk()
  202395. {
  202396. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  202397. }
  202398. #if JUCE_USE_CDBURNER
  202399. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  202400. {
  202401. CoInitialize (0);
  202402. IDiscMaster* dm;
  202403. IDiscRecorder* result = 0;
  202404. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  202405. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  202406. IID_IDiscMaster,
  202407. (void**) &dm)))
  202408. {
  202409. if (SUCCEEDED (dm->Open()))
  202410. {
  202411. IEnumDiscRecorders* drEnum = 0;
  202412. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  202413. {
  202414. IDiscRecorder* dr = 0;
  202415. DWORD dummy;
  202416. int index = 0;
  202417. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  202418. {
  202419. if (indexToOpen == index)
  202420. {
  202421. result = dr;
  202422. break;
  202423. }
  202424. else if (list != 0)
  202425. {
  202426. BSTR path;
  202427. if (SUCCEEDED (dr->GetPath (&path)))
  202428. list->add ((const WCHAR*) path);
  202429. }
  202430. ++index;
  202431. dr->Release();
  202432. }
  202433. drEnum->Release();
  202434. }
  202435. /*if (redbookFormat != 0)
  202436. {
  202437. IEnumDiscMasterFormats* mfEnum;
  202438. if (SUCCEEDED (dm->EnumDiscMasterFormats (&mfEnum)))
  202439. {
  202440. IID formatIID;
  202441. DWORD dummy;
  202442. while (mfEnum->Next (1, &formatIID, &dummy) == S_OK)
  202443. {
  202444. }
  202445. mfEnum->Release();
  202446. }
  202447. redbookFormat
  202448. }*/
  202449. if (master == 0)
  202450. dm->Close();
  202451. }
  202452. if (master != 0)
  202453. *master = dm;
  202454. else
  202455. dm->Release();
  202456. }
  202457. return result;
  202458. }
  202459. const StringArray AudioCDBurner::findAvailableDevices()
  202460. {
  202461. StringArray devs;
  202462. enumCDBurners (&devs, -1, 0);
  202463. return devs;
  202464. }
  202465. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  202466. {
  202467. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  202468. if (b->internal == 0)
  202469. deleteAndZero (b);
  202470. return b;
  202471. }
  202472. class CDBurnerInfo : public IDiscMasterProgressEvents
  202473. {
  202474. public:
  202475. CDBurnerInfo()
  202476. : refCount (1),
  202477. progress (0),
  202478. shouldCancel (false),
  202479. listener (0)
  202480. {
  202481. }
  202482. ~CDBurnerInfo()
  202483. {
  202484. }
  202485. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  202486. {
  202487. if (result == 0)
  202488. return E_POINTER;
  202489. if (id == IID_IUnknown || id == IID_IDiscMasterProgressEvents)
  202490. {
  202491. AddRef();
  202492. *result = this;
  202493. return S_OK;
  202494. }
  202495. *result = 0;
  202496. return E_NOINTERFACE;
  202497. }
  202498. ULONG __stdcall AddRef() { return ++refCount; }
  202499. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  202500. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  202501. {
  202502. if (listener != 0 && ! shouldCancel)
  202503. shouldCancel = listener->audioCDBurnProgress (progress);
  202504. *pbCancel = shouldCancel;
  202505. return S_OK;
  202506. }
  202507. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  202508. {
  202509. progress = nCompleted / (float) nTotal;
  202510. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  202511. return E_NOTIMPL;
  202512. }
  202513. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  202514. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  202515. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  202516. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  202517. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  202518. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  202519. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  202520. IDiscMaster* discMaster;
  202521. IDiscRecorder* discRecorder;
  202522. IRedbookDiscMaster* redbook;
  202523. AudioCDBurner::BurnProgressListener* listener;
  202524. float progress;
  202525. bool shouldCancel;
  202526. private:
  202527. int refCount;
  202528. };
  202529. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  202530. : internal (0)
  202531. {
  202532. IDiscMaster* discMaster;
  202533. IDiscRecorder* dr = enumCDBurners (0, deviceIndex, &discMaster);
  202534. if (dr != 0)
  202535. {
  202536. IRedbookDiscMaster* redbook;
  202537. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  202538. hr = discMaster->SetActiveDiscRecorder (dr);
  202539. CDBurnerInfo* const info = new CDBurnerInfo();
  202540. internal = info;
  202541. info->discMaster = discMaster;
  202542. info->discRecorder = dr;
  202543. info->redbook = redbook;
  202544. }
  202545. }
  202546. AudioCDBurner::~AudioCDBurner()
  202547. {
  202548. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  202549. if (info != 0)
  202550. {
  202551. info->discRecorder->Close();
  202552. info->redbook->Release();
  202553. info->discRecorder->Release();
  202554. info->discMaster->Release();
  202555. info->Release();
  202556. }
  202557. }
  202558. bool AudioCDBurner::isDiskPresent() const
  202559. {
  202560. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  202561. HRESULT hr = info->discRecorder->OpenExclusive();
  202562. long type, flags;
  202563. hr = info->discRecorder->QueryMediaType (&type, &flags);
  202564. info->discRecorder->Close();
  202565. return hr == S_OK && type != 0 && (flags & MEDIA_WRITABLE) != 0;
  202566. }
  202567. int AudioCDBurner::getNumAvailableAudioBlocks() const
  202568. {
  202569. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  202570. long blocksFree = 0;
  202571. info->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  202572. return blocksFree;
  202573. }
  202574. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener,
  202575. const bool ejectDiscAfterwards,
  202576. const bool performFakeBurnForTesting)
  202577. {
  202578. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  202579. info->listener = listener;
  202580. info->progress = 0;
  202581. info->shouldCancel = false;
  202582. UINT_PTR cookie;
  202583. HRESULT hr = info->discMaster->ProgressAdvise (info, &cookie);
  202584. hr = info->discMaster->RecordDisc (performFakeBurnForTesting,
  202585. ejectDiscAfterwards);
  202586. String error;
  202587. if (hr != S_OK)
  202588. {
  202589. const char* e = "Couldn't open or write to the CD device";
  202590. if (hr == IMAPI_E_USERABORT)
  202591. e = "User cancelled the write operation";
  202592. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  202593. e = "No Disk present";
  202594. error = e;
  202595. }
  202596. info->discMaster->ProgressUnadvise (cookie);
  202597. info->listener = 0;
  202598. return error;
  202599. }
  202600. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamples)
  202601. {
  202602. if (source == 0)
  202603. return false;
  202604. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  202605. long bytesPerBlock;
  202606. HRESULT hr = info->redbook->GetAudioBlockSize (&bytesPerBlock);
  202607. const int samplesPerBlock = bytesPerBlock / 4;
  202608. bool ok = true;
  202609. hr = info->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  202610. byte* const buffer = (byte*) juce_malloc (bytesPerBlock);
  202611. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  202612. int samplesDone = 0;
  202613. source->prepareToPlay (samplesPerBlock, 44100.0);
  202614. while (ok)
  202615. {
  202616. {
  202617. AudioSourceChannelInfo info;
  202618. info.buffer = &sourceBuffer;
  202619. info.numSamples = samplesPerBlock;
  202620. info.startSample = 0;
  202621. sourceBuffer.clear();
  202622. source->getNextAudioBlock (info);
  202623. }
  202624. zeromem (buffer, bytesPerBlock);
  202625. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  202626. buffer, samplesPerBlock, 4);
  202627. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  202628. buffer + 2, samplesPerBlock, 4);
  202629. hr = info->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  202630. if (hr != S_OK)
  202631. ok = false;
  202632. samplesDone += samplesPerBlock;
  202633. if (samplesDone >= numSamples)
  202634. break;
  202635. }
  202636. juce_free (buffer);
  202637. hr = info->redbook->CloseAudioTrack();
  202638. delete source;
  202639. return ok && hr == S_OK;
  202640. }
  202641. #endif
  202642. END_JUCE_NAMESPACE
  202643. /********* End of inlined file: juce_win32_AudioCDReader.cpp *********/
  202644. /********* Start of inlined file: juce_win32_DirectSound.cpp *********/
  202645. extern "C"
  202646. {
  202647. // Declare just the minimum number of interfaces for the DSound objects that we need..
  202648. typedef struct typeDSBUFFERDESC
  202649. {
  202650. DWORD dwSize;
  202651. DWORD dwFlags;
  202652. DWORD dwBufferBytes;
  202653. DWORD dwReserved;
  202654. LPWAVEFORMATEX lpwfxFormat;
  202655. GUID guid3DAlgorithm;
  202656. } DSBUFFERDESC;
  202657. struct IDirectSoundBuffer;
  202658. #undef INTERFACE
  202659. #define INTERFACE IDirectSound
  202660. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  202661. {
  202662. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  202663. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  202664. STDMETHOD_(ULONG,Release) (THIS) PURE;
  202665. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  202666. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  202667. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  202668. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  202669. STDMETHOD(Compact) (THIS) PURE;
  202670. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  202671. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  202672. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  202673. };
  202674. #undef INTERFACE
  202675. #define INTERFACE IDirectSoundBuffer
  202676. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  202677. {
  202678. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  202679. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  202680. STDMETHOD_(ULONG,Release) (THIS) PURE;
  202681. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  202682. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  202683. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  202684. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  202685. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  202686. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  202687. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  202688. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  202689. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  202690. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  202691. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  202692. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  202693. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  202694. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  202695. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  202696. STDMETHOD(Stop) (THIS) PURE;
  202697. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  202698. STDMETHOD(Restore) (THIS) PURE;
  202699. };
  202700. typedef struct typeDSCBUFFERDESC
  202701. {
  202702. DWORD dwSize;
  202703. DWORD dwFlags;
  202704. DWORD dwBufferBytes;
  202705. DWORD dwReserved;
  202706. LPWAVEFORMATEX lpwfxFormat;
  202707. } DSCBUFFERDESC;
  202708. struct IDirectSoundCaptureBuffer;
  202709. #undef INTERFACE
  202710. #define INTERFACE IDirectSoundCapture
  202711. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  202712. {
  202713. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  202714. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  202715. STDMETHOD_(ULONG,Release) (THIS) PURE;
  202716. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  202717. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  202718. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  202719. };
  202720. #undef INTERFACE
  202721. #define INTERFACE IDirectSoundCaptureBuffer
  202722. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  202723. {
  202724. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  202725. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  202726. STDMETHOD_(ULONG,Release) (THIS) PURE;
  202727. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  202728. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  202729. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  202730. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  202731. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  202732. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  202733. STDMETHOD(Start) (THIS_ DWORD) PURE;
  202734. STDMETHOD(Stop) (THIS) PURE;
  202735. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  202736. };
  202737. };
  202738. BEGIN_JUCE_NAMESPACE
  202739. static const String getDSErrorMessage (HRESULT hr)
  202740. {
  202741. const char* result = 0;
  202742. switch (hr)
  202743. {
  202744. case MAKE_HRESULT(1, 0x878, 10):
  202745. result = "Device already allocated";
  202746. break;
  202747. case MAKE_HRESULT(1, 0x878, 30):
  202748. result = "Control unavailable";
  202749. break;
  202750. case E_INVALIDARG:
  202751. result = "Invalid parameter";
  202752. break;
  202753. case MAKE_HRESULT(1, 0x878, 50):
  202754. result = "Invalid call";
  202755. break;
  202756. case E_FAIL:
  202757. result = "Generic error";
  202758. break;
  202759. case MAKE_HRESULT(1, 0x878, 70):
  202760. result = "Priority level error";
  202761. break;
  202762. case E_OUTOFMEMORY:
  202763. result = "Out of memory";
  202764. break;
  202765. case MAKE_HRESULT(1, 0x878, 100):
  202766. result = "Bad format";
  202767. break;
  202768. case E_NOTIMPL:
  202769. result = "Unsupported function";
  202770. break;
  202771. case MAKE_HRESULT(1, 0x878, 120):
  202772. result = "No driver";
  202773. break;
  202774. case MAKE_HRESULT(1, 0x878, 130):
  202775. result = "Already initialised";
  202776. break;
  202777. case CLASS_E_NOAGGREGATION:
  202778. result = "No aggregation";
  202779. break;
  202780. case MAKE_HRESULT(1, 0x878, 150):
  202781. result = "Buffer lost";
  202782. break;
  202783. case MAKE_HRESULT(1, 0x878, 160):
  202784. result = "Another app has priority";
  202785. break;
  202786. case MAKE_HRESULT(1, 0x878, 170):
  202787. result = "Uninitialised";
  202788. break;
  202789. case E_NOINTERFACE:
  202790. result = "No interface";
  202791. break;
  202792. case S_OK:
  202793. result = "No error";
  202794. break;
  202795. default:
  202796. return "Unknown error: " + String ((int) hr);
  202797. }
  202798. return result;
  202799. }
  202800. #define DS_DEBUGGING 1
  202801. #ifdef DS_DEBUGGING
  202802. #define CATCH JUCE_CATCH_EXCEPTION
  202803. #undef log
  202804. #define log(a) Logger::writeToLog(a);
  202805. #undef logError
  202806. #define logError(a) logDSError(a, __LINE__);
  202807. static void logDSError (HRESULT hr, int lineNum)
  202808. {
  202809. if (hr != S_OK)
  202810. {
  202811. String error ("DS error at line ");
  202812. error << lineNum << T(" - ") << getDSErrorMessage (hr);
  202813. log (error);
  202814. }
  202815. }
  202816. #else
  202817. #define CATCH JUCE_CATCH_ALL
  202818. #define log(a)
  202819. #define logError(a)
  202820. #endif
  202821. #define DSOUND_FUNCTION(functionName, params) \
  202822. typedef HRESULT (WINAPI *type##functionName) params; \
  202823. static type##functionName ds##functionName = 0;
  202824. #define DSOUND_FUNCTION_LOAD(functionName) \
  202825. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  202826. jassert (ds##functionName != 0);
  202827. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  202828. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  202829. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  202830. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  202831. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  202832. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  202833. static void initialiseDSoundFunctions()
  202834. {
  202835. if (dsDirectSoundCreate == 0)
  202836. {
  202837. HMODULE h = LoadLibraryA ("dsound.dll");
  202838. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  202839. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  202840. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  202841. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  202842. }
  202843. }
  202844. class DSoundInternalOutChannel
  202845. {
  202846. String name;
  202847. LPGUID guid;
  202848. int sampleRate, bufferSizeSamples;
  202849. float* leftBuffer;
  202850. float* rightBuffer;
  202851. IDirectSound* pDirectSound;
  202852. IDirectSoundBuffer* pOutputBuffer;
  202853. DWORD writeOffset;
  202854. int totalBytesPerBuffer;
  202855. int bytesPerBuffer;
  202856. unsigned int lastPlayCursor;
  202857. public:
  202858. int bitDepth;
  202859. bool doneFlag;
  202860. DSoundInternalOutChannel (const String& name_,
  202861. LPGUID guid_,
  202862. int rate,
  202863. int bufferSize,
  202864. float* left,
  202865. float* right)
  202866. : name (name_),
  202867. guid (guid_),
  202868. sampleRate (rate),
  202869. bufferSizeSamples (bufferSize),
  202870. leftBuffer (left),
  202871. rightBuffer (right),
  202872. pDirectSound (0),
  202873. pOutputBuffer (0),
  202874. bitDepth (16)
  202875. {
  202876. }
  202877. ~DSoundInternalOutChannel()
  202878. {
  202879. close();
  202880. }
  202881. void close()
  202882. {
  202883. HRESULT hr;
  202884. if (pOutputBuffer != 0)
  202885. {
  202886. JUCE_TRY
  202887. {
  202888. log (T("closing dsound out: ") + name);
  202889. hr = pOutputBuffer->Stop();
  202890. logError (hr);
  202891. }
  202892. CATCH
  202893. JUCE_TRY
  202894. {
  202895. hr = pOutputBuffer->Release();
  202896. logError (hr);
  202897. }
  202898. CATCH
  202899. pOutputBuffer = 0;
  202900. }
  202901. if (pDirectSound != 0)
  202902. {
  202903. JUCE_TRY
  202904. {
  202905. hr = pDirectSound->Release();
  202906. logError (hr);
  202907. }
  202908. CATCH
  202909. pDirectSound = 0;
  202910. }
  202911. }
  202912. const String open()
  202913. {
  202914. log (T("opening dsound out device: ") + name
  202915. + T(" rate=") + String (sampleRate)
  202916. + T(" bits=") + String (bitDepth)
  202917. + T(" buf=") + String (bufferSizeSamples));
  202918. pDirectSound = 0;
  202919. pOutputBuffer = 0;
  202920. writeOffset = 0;
  202921. String error;
  202922. HRESULT hr = E_NOINTERFACE;
  202923. if (dsDirectSoundCreate != 0)
  202924. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  202925. if (hr == S_OK)
  202926. {
  202927. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  202928. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  202929. const int numChannels = 2;
  202930. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  202931. logError (hr);
  202932. if (hr == S_OK)
  202933. {
  202934. IDirectSoundBuffer* pPrimaryBuffer;
  202935. DSBUFFERDESC primaryDesc;
  202936. zerostruct (primaryDesc);
  202937. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  202938. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  202939. primaryDesc.dwBufferBytes = 0;
  202940. primaryDesc.lpwfxFormat = 0;
  202941. log ("opening dsound out step 2");
  202942. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  202943. logError (hr);
  202944. if (hr == S_OK)
  202945. {
  202946. WAVEFORMATEX wfFormat;
  202947. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  202948. wfFormat.nChannels = (unsigned short) numChannels;
  202949. wfFormat.nSamplesPerSec = sampleRate;
  202950. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  202951. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  202952. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  202953. wfFormat.cbSize = 0;
  202954. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  202955. logError (hr);
  202956. if (hr == S_OK)
  202957. {
  202958. DSBUFFERDESC secondaryDesc;
  202959. zerostruct (secondaryDesc);
  202960. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  202961. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  202962. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  202963. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  202964. secondaryDesc.lpwfxFormat = &wfFormat;
  202965. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  202966. logError (hr);
  202967. if (hr == S_OK)
  202968. {
  202969. log ("opening dsound out step 3");
  202970. DWORD dwDataLen;
  202971. unsigned char* pDSBuffData;
  202972. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  202973. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  202974. logError (hr);
  202975. if (hr == S_OK)
  202976. {
  202977. zeromem (pDSBuffData, dwDataLen);
  202978. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  202979. if (hr == S_OK)
  202980. {
  202981. hr = pOutputBuffer->SetCurrentPosition (0);
  202982. if (hr == S_OK)
  202983. {
  202984. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  202985. if (hr == S_OK)
  202986. return String::empty;
  202987. }
  202988. }
  202989. }
  202990. }
  202991. }
  202992. }
  202993. }
  202994. }
  202995. error = getDSErrorMessage (hr);
  202996. close();
  202997. return error;
  202998. }
  202999. void synchronisePosition()
  203000. {
  203001. if (pOutputBuffer != 0)
  203002. {
  203003. DWORD playCursor;
  203004. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  203005. }
  203006. }
  203007. bool service()
  203008. {
  203009. if (pOutputBuffer == 0)
  203010. return true;
  203011. DWORD playCursor, writeCursor;
  203012. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  203013. if (hr != S_OK)
  203014. {
  203015. logError (hr);
  203016. jassertfalse
  203017. return true;
  203018. }
  203019. int playWriteGap = writeCursor - playCursor;
  203020. if (playWriteGap < 0)
  203021. playWriteGap += totalBytesPerBuffer;
  203022. int bytesEmpty = playCursor - writeOffset;
  203023. if (bytesEmpty < 0)
  203024. bytesEmpty += totalBytesPerBuffer;
  203025. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  203026. {
  203027. writeOffset = writeCursor;
  203028. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  203029. }
  203030. if (bytesEmpty >= bytesPerBuffer)
  203031. {
  203032. LPBYTE lpbuf1 = 0;
  203033. LPBYTE lpbuf2 = 0;
  203034. DWORD dwSize1 = 0;
  203035. DWORD dwSize2 = 0;
  203036. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  203037. bytesPerBuffer,
  203038. (void**) &lpbuf1, &dwSize1,
  203039. (void**) &lpbuf2, &dwSize2, 0);
  203040. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  203041. {
  203042. pOutputBuffer->Restore();
  203043. hr = pOutputBuffer->Lock (writeOffset,
  203044. bytesPerBuffer,
  203045. (void**) &lpbuf1, &dwSize1,
  203046. (void**) &lpbuf2, &dwSize2, 0);
  203047. }
  203048. if (hr == S_OK)
  203049. {
  203050. if (bitDepth == 16)
  203051. {
  203052. const float gainL = 32767.0f;
  203053. const float gainR = 32767.0f;
  203054. int* dest = (int*)lpbuf1;
  203055. const float* left = leftBuffer;
  203056. const float* right = rightBuffer;
  203057. int samples1 = dwSize1 >> 2;
  203058. int samples2 = dwSize2 >> 2;
  203059. if (left == 0)
  203060. {
  203061. while (--samples1 >= 0)
  203062. {
  203063. int r = roundFloatToInt (gainR * *right++);
  203064. if (r < -32768)
  203065. r = -32768;
  203066. else if (r > 32767)
  203067. r = 32767;
  203068. *dest++ = (r << 16);
  203069. }
  203070. dest = (int*)lpbuf2;
  203071. while (--samples2 >= 0)
  203072. {
  203073. int r = roundFloatToInt (gainR * *right++);
  203074. if (r < -32768)
  203075. r = -32768;
  203076. else if (r > 32767)
  203077. r = 32767;
  203078. *dest++ = (r << 16);
  203079. }
  203080. }
  203081. else if (right == 0)
  203082. {
  203083. while (--samples1 >= 0)
  203084. {
  203085. int l = roundFloatToInt (gainL * *left++);
  203086. if (l < -32768)
  203087. l = -32768;
  203088. else if (l > 32767)
  203089. l = 32767;
  203090. l &= 0xffff;
  203091. *dest++ = l;
  203092. }
  203093. dest = (int*)lpbuf2;
  203094. while (--samples2 >= 0)
  203095. {
  203096. int l = roundFloatToInt (gainL * *left++);
  203097. if (l < -32768)
  203098. l = -32768;
  203099. else if (l > 32767)
  203100. l = 32767;
  203101. l &= 0xffff;
  203102. *dest++ = l;
  203103. }
  203104. }
  203105. else
  203106. {
  203107. while (--samples1 >= 0)
  203108. {
  203109. int l = roundFloatToInt (gainL * *left++);
  203110. if (l < -32768)
  203111. l = -32768;
  203112. else if (l > 32767)
  203113. l = 32767;
  203114. l &= 0xffff;
  203115. int r = roundFloatToInt (gainR * *right++);
  203116. if (r < -32768)
  203117. r = -32768;
  203118. else if (r > 32767)
  203119. r = 32767;
  203120. *dest++ = (r << 16) | l;
  203121. }
  203122. dest = (int*)lpbuf2;
  203123. while (--samples2 >= 0)
  203124. {
  203125. int l = roundFloatToInt (gainL * *left++);
  203126. if (l < -32768)
  203127. l = -32768;
  203128. else if (l > 32767)
  203129. l = 32767;
  203130. l &= 0xffff;
  203131. int r = roundFloatToInt (gainR * *right++);
  203132. if (r < -32768)
  203133. r = -32768;
  203134. else if (r > 32767)
  203135. r = 32767;
  203136. *dest++ = (r << 16) | l;
  203137. }
  203138. }
  203139. }
  203140. else
  203141. {
  203142. jassertfalse
  203143. }
  203144. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  203145. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  203146. }
  203147. else
  203148. {
  203149. jassertfalse
  203150. logError (hr);
  203151. }
  203152. bytesEmpty -= bytesPerBuffer;
  203153. return true;
  203154. }
  203155. else
  203156. {
  203157. return false;
  203158. }
  203159. }
  203160. };
  203161. struct DSoundInternalInChannel
  203162. {
  203163. String name;
  203164. LPGUID guid;
  203165. int sampleRate, bufferSizeSamples;
  203166. float* leftBuffer;
  203167. float* rightBuffer;
  203168. IDirectSound* pDirectSound;
  203169. IDirectSoundCapture* pDirectSoundCapture;
  203170. IDirectSoundCaptureBuffer* pInputBuffer;
  203171. public:
  203172. unsigned int readOffset;
  203173. int bytesPerBuffer, totalBytesPerBuffer;
  203174. int bitDepth;
  203175. bool doneFlag;
  203176. DSoundInternalInChannel (const String& name_,
  203177. LPGUID guid_,
  203178. int rate,
  203179. int bufferSize,
  203180. float* left,
  203181. float* right)
  203182. : name (name_),
  203183. guid (guid_),
  203184. sampleRate (rate),
  203185. bufferSizeSamples (bufferSize),
  203186. leftBuffer (left),
  203187. rightBuffer (right),
  203188. pDirectSound (0),
  203189. pDirectSoundCapture (0),
  203190. pInputBuffer (0),
  203191. bitDepth (16)
  203192. {
  203193. }
  203194. ~DSoundInternalInChannel()
  203195. {
  203196. close();
  203197. }
  203198. void close()
  203199. {
  203200. HRESULT hr;
  203201. if (pInputBuffer != 0)
  203202. {
  203203. JUCE_TRY
  203204. {
  203205. log (T("closing dsound in: ") + name);
  203206. hr = pInputBuffer->Stop();
  203207. logError (hr);
  203208. }
  203209. CATCH
  203210. JUCE_TRY
  203211. {
  203212. hr = pInputBuffer->Release();
  203213. logError (hr);
  203214. }
  203215. CATCH
  203216. pInputBuffer = 0;
  203217. }
  203218. if (pDirectSoundCapture != 0)
  203219. {
  203220. JUCE_TRY
  203221. {
  203222. hr = pDirectSoundCapture->Release();
  203223. logError (hr);
  203224. }
  203225. CATCH
  203226. pDirectSoundCapture = 0;
  203227. }
  203228. if (pDirectSound != 0)
  203229. {
  203230. JUCE_TRY
  203231. {
  203232. hr = pDirectSound->Release();
  203233. logError (hr);
  203234. }
  203235. CATCH
  203236. pDirectSound = 0;
  203237. }
  203238. }
  203239. const String open()
  203240. {
  203241. log (T("opening dsound in device: ") + name
  203242. + T(" rate=") + String (sampleRate) + T(" bits=") + String (bitDepth) + T(" buf=") + String (bufferSizeSamples));
  203243. pDirectSound = 0;
  203244. pDirectSoundCapture = 0;
  203245. pInputBuffer = 0;
  203246. readOffset = 0;
  203247. totalBytesPerBuffer = 0;
  203248. String error;
  203249. HRESULT hr = E_NOINTERFACE;
  203250. if (dsDirectSoundCaptureCreate != 0)
  203251. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  203252. logError (hr);
  203253. if (hr == S_OK)
  203254. {
  203255. const int numChannels = 2;
  203256. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  203257. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  203258. WAVEFORMATEX wfFormat;
  203259. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  203260. wfFormat.nChannels = (unsigned short)numChannels;
  203261. wfFormat.nSamplesPerSec = sampleRate;
  203262. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  203263. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  203264. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  203265. wfFormat.cbSize = 0;
  203266. DSCBUFFERDESC captureDesc;
  203267. zerostruct (captureDesc);
  203268. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  203269. captureDesc.dwFlags = 0;
  203270. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  203271. captureDesc.lpwfxFormat = &wfFormat;
  203272. log (T("opening dsound in step 2"));
  203273. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  203274. logError (hr);
  203275. if (hr == S_OK)
  203276. {
  203277. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  203278. logError (hr);
  203279. if (hr == S_OK)
  203280. return String::empty;
  203281. }
  203282. }
  203283. error = getDSErrorMessage (hr);
  203284. close();
  203285. return error;
  203286. }
  203287. void synchronisePosition()
  203288. {
  203289. if (pInputBuffer != 0)
  203290. {
  203291. DWORD capturePos;
  203292. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  203293. }
  203294. }
  203295. bool service()
  203296. {
  203297. if (pInputBuffer == 0)
  203298. return true;
  203299. DWORD capturePos, readPos;
  203300. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  203301. logError (hr);
  203302. if (hr != S_OK)
  203303. return true;
  203304. int bytesFilled = readPos - readOffset;
  203305. if (bytesFilled < 0)
  203306. bytesFilled += totalBytesPerBuffer;
  203307. if (bytesFilled >= bytesPerBuffer)
  203308. {
  203309. LPBYTE lpbuf1 = 0;
  203310. LPBYTE lpbuf2 = 0;
  203311. DWORD dwsize1 = 0;
  203312. DWORD dwsize2 = 0;
  203313. HRESULT hr = pInputBuffer->Lock (readOffset,
  203314. bytesPerBuffer,
  203315. (void**) &lpbuf1, &dwsize1,
  203316. (void**) &lpbuf2, &dwsize2, 0);
  203317. if (hr == S_OK)
  203318. {
  203319. if (bitDepth == 16)
  203320. {
  203321. const float g = 1.0f / 32768.0f;
  203322. float* destL = leftBuffer;
  203323. float* destR = rightBuffer;
  203324. int samples1 = dwsize1 >> 2;
  203325. int samples2 = dwsize2 >> 2;
  203326. const short* src = (const short*)lpbuf1;
  203327. if (destL == 0)
  203328. {
  203329. while (--samples1 >= 0)
  203330. {
  203331. ++src;
  203332. *destR++ = *src++ * g;
  203333. }
  203334. src = (const short*)lpbuf2;
  203335. while (--samples2 >= 0)
  203336. {
  203337. ++src;
  203338. *destR++ = *src++ * g;
  203339. }
  203340. }
  203341. else if (destR == 0)
  203342. {
  203343. while (--samples1 >= 0)
  203344. {
  203345. *destL++ = *src++ * g;
  203346. ++src;
  203347. }
  203348. src = (const short*)lpbuf2;
  203349. while (--samples2 >= 0)
  203350. {
  203351. *destL++ = *src++ * g;
  203352. ++src;
  203353. }
  203354. }
  203355. else
  203356. {
  203357. while (--samples1 >= 0)
  203358. {
  203359. *destL++ = *src++ * g;
  203360. *destR++ = *src++ * g;
  203361. }
  203362. src = (const short*)lpbuf2;
  203363. while (--samples2 >= 0)
  203364. {
  203365. *destL++ = *src++ * g;
  203366. *destR++ = *src++ * g;
  203367. }
  203368. }
  203369. }
  203370. else
  203371. {
  203372. jassertfalse
  203373. }
  203374. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  203375. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  203376. }
  203377. else
  203378. {
  203379. logError (hr);
  203380. jassertfalse
  203381. }
  203382. bytesFilled -= bytesPerBuffer;
  203383. return true;
  203384. }
  203385. else
  203386. {
  203387. return false;
  203388. }
  203389. }
  203390. };
  203391. class DSoundAudioIODevice : public AudioIODevice,
  203392. public Thread
  203393. {
  203394. public:
  203395. DSoundAudioIODevice (const String& deviceName,
  203396. const int outputDeviceIndex_,
  203397. const int inputDeviceIndex_)
  203398. : AudioIODevice (deviceName, "DirectSound"),
  203399. Thread ("Juce DSound"),
  203400. isOpen_ (false),
  203401. isStarted (false),
  203402. outputDeviceIndex (outputDeviceIndex_),
  203403. inputDeviceIndex (inputDeviceIndex_),
  203404. inChans (4),
  203405. outChans (4),
  203406. numInputBuffers (0),
  203407. numOutputBuffers (0),
  203408. totalSamplesOut (0),
  203409. sampleRate (0.0),
  203410. inputBuffers (0),
  203411. outputBuffers (0),
  203412. callback (0),
  203413. bufferSizeSamples (0)
  203414. {
  203415. if (outputDeviceIndex_ >= 0)
  203416. {
  203417. outChannels.add (TRANS("Left"));
  203418. outChannels.add (TRANS("Right"));
  203419. }
  203420. if (inputDeviceIndex_ >= 0)
  203421. {
  203422. inChannels.add (TRANS("Left"));
  203423. inChannels.add (TRANS("Right"));
  203424. }
  203425. }
  203426. ~DSoundAudioIODevice()
  203427. {
  203428. close();
  203429. }
  203430. const StringArray getOutputChannelNames()
  203431. {
  203432. return outChannels;
  203433. }
  203434. const StringArray getInputChannelNames()
  203435. {
  203436. return inChannels;
  203437. }
  203438. int getNumSampleRates()
  203439. {
  203440. return 4;
  203441. }
  203442. double getSampleRate (int index)
  203443. {
  203444. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  203445. return samps [jlimit (0, 3, index)];
  203446. }
  203447. int getNumBufferSizesAvailable()
  203448. {
  203449. return 50;
  203450. }
  203451. int getBufferSizeSamples (int index)
  203452. {
  203453. int n = 64;
  203454. for (int i = 0; i < index; ++i)
  203455. n += (n < 512) ? 32
  203456. : ((n < 1024) ? 64
  203457. : ((n < 2048) ? 128 : 256));
  203458. return n;
  203459. }
  203460. int getDefaultBufferSize()
  203461. {
  203462. return 2560;
  203463. }
  203464. const String open (const BitArray& inputChannels,
  203465. const BitArray& outputChannels,
  203466. double sampleRate,
  203467. int bufferSizeSamples)
  203468. {
  203469. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  203470. isOpen_ = lastError.isEmpty();
  203471. return lastError;
  203472. }
  203473. void close()
  203474. {
  203475. stop();
  203476. if (isOpen_)
  203477. {
  203478. closeDevice();
  203479. isOpen_ = false;
  203480. }
  203481. }
  203482. bool isOpen()
  203483. {
  203484. return isOpen_ && isThreadRunning();
  203485. }
  203486. int getCurrentBufferSizeSamples()
  203487. {
  203488. return bufferSizeSamples;
  203489. }
  203490. double getCurrentSampleRate()
  203491. {
  203492. return sampleRate;
  203493. }
  203494. int getCurrentBitDepth()
  203495. {
  203496. int i, bits = 256;
  203497. for (i = inChans.size(); --i >= 0;)
  203498. bits = jmin (bits, inChans[i]->bitDepth);
  203499. for (i = outChans.size(); --i >= 0;)
  203500. bits = jmin (bits, outChans[i]->bitDepth);
  203501. if (bits > 32)
  203502. bits = 16;
  203503. return bits;
  203504. }
  203505. const BitArray getActiveOutputChannels() const
  203506. {
  203507. return enabledOutputs;
  203508. }
  203509. const BitArray getActiveInputChannels() const
  203510. {
  203511. return enabledInputs;
  203512. }
  203513. int getOutputLatencyInSamples()
  203514. {
  203515. return (int) (getCurrentBufferSizeSamples() * 1.5);
  203516. }
  203517. int getInputLatencyInSamples()
  203518. {
  203519. return getOutputLatencyInSamples();
  203520. }
  203521. void start (AudioIODeviceCallback* call)
  203522. {
  203523. if (isOpen_ && call != 0 && ! isStarted)
  203524. {
  203525. if (! isThreadRunning())
  203526. {
  203527. // something gone wrong and the thread's stopped..
  203528. isOpen_ = false;
  203529. return;
  203530. }
  203531. call->audioDeviceAboutToStart (this);
  203532. const ScopedLock sl (startStopLock);
  203533. callback = call;
  203534. isStarted = true;
  203535. }
  203536. }
  203537. void stop()
  203538. {
  203539. if (isStarted)
  203540. {
  203541. AudioIODeviceCallback* const callbackLocal = callback;
  203542. {
  203543. const ScopedLock sl (startStopLock);
  203544. isStarted = false;
  203545. }
  203546. if (callbackLocal != 0)
  203547. callbackLocal->audioDeviceStopped();
  203548. }
  203549. }
  203550. bool isPlaying()
  203551. {
  203552. return isStarted && isOpen_ && isThreadRunning();
  203553. }
  203554. const String getLastError()
  203555. {
  203556. return lastError;
  203557. }
  203558. juce_UseDebuggingNewOperator
  203559. StringArray inChannels, outChannels;
  203560. int outputDeviceIndex, inputDeviceIndex;
  203561. private:
  203562. bool isOpen_;
  203563. bool isStarted;
  203564. String lastError;
  203565. OwnedArray <DSoundInternalInChannel> inChans;
  203566. OwnedArray <DSoundInternalOutChannel> outChans;
  203567. WaitableEvent startEvent;
  203568. int numInputBuffers, numOutputBuffers, bufferSizeSamples;
  203569. int volatile totalSamplesOut;
  203570. int64 volatile lastBlockTime;
  203571. double sampleRate;
  203572. BitArray enabledInputs, enabledOutputs;
  203573. float** inputBuffers;
  203574. float** outputBuffers;
  203575. AudioIODeviceCallback* callback;
  203576. CriticalSection startStopLock;
  203577. DSoundAudioIODevice (const DSoundAudioIODevice&);
  203578. const DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  203579. const String openDevice (const BitArray& inputChannels,
  203580. const BitArray& outputChannels,
  203581. double sampleRate_,
  203582. int bufferSizeSamples_);
  203583. void closeDevice()
  203584. {
  203585. isStarted = false;
  203586. stopThread (5000);
  203587. inChans.clear();
  203588. outChans.clear();
  203589. int i;
  203590. for (i = 0; i < numInputBuffers; ++i)
  203591. juce_free (inputBuffers[i]);
  203592. delete[] inputBuffers;
  203593. inputBuffers = 0;
  203594. numInputBuffers = 0;
  203595. for (i = 0; i < numOutputBuffers; ++i)
  203596. juce_free (outputBuffers[i]);
  203597. delete[] outputBuffers;
  203598. outputBuffers = 0;
  203599. numOutputBuffers = 0;
  203600. }
  203601. void resync()
  203602. {
  203603. int i;
  203604. for (i = outChans.size(); --i >= 0;)
  203605. outChans.getUnchecked(i)->close();
  203606. for (i = inChans.size(); --i >= 0;)
  203607. inChans.getUnchecked(i)->close();
  203608. if (threadShouldExit())
  203609. return;
  203610. // boost our priority while opening the devices to try to get better sync between them
  203611. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  203612. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  203613. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  203614. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  203615. for (i = outChans.size(); --i >= 0;)
  203616. outChans.getUnchecked(i)->open();
  203617. for (i = inChans.size(); --i >= 0;)
  203618. inChans.getUnchecked(i)->open();
  203619. if (! threadShouldExit())
  203620. {
  203621. sleep (5);
  203622. for (i = 0; i < outChans.size(); ++i)
  203623. outChans.getUnchecked(i)->synchronisePosition();
  203624. for (i = 0; i < inChans.size(); ++i)
  203625. inChans.getUnchecked(i)->synchronisePosition();
  203626. }
  203627. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  203628. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  203629. }
  203630. public:
  203631. void run()
  203632. {
  203633. while (! threadShouldExit())
  203634. {
  203635. if (wait (100))
  203636. break;
  203637. }
  203638. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  203639. const int maxTimeMS = jmax (5, 3 * latencyMs);
  203640. while (! threadShouldExit())
  203641. {
  203642. int numToDo = 0;
  203643. uint32 startTime = Time::getMillisecondCounter();
  203644. int i;
  203645. for (i = inChans.size(); --i >= 0;)
  203646. {
  203647. inChans.getUnchecked(i)->doneFlag = false;
  203648. ++numToDo;
  203649. }
  203650. for (i = outChans.size(); --i >= 0;)
  203651. {
  203652. outChans.getUnchecked(i)->doneFlag = false;
  203653. ++numToDo;
  203654. }
  203655. if (numToDo > 0)
  203656. {
  203657. const int maxCount = 3;
  203658. int count = maxCount;
  203659. for (;;)
  203660. {
  203661. for (i = inChans.size(); --i >= 0;)
  203662. {
  203663. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  203664. if ((! in->doneFlag) && in->service())
  203665. {
  203666. in->doneFlag = true;
  203667. --numToDo;
  203668. }
  203669. }
  203670. for (i = outChans.size(); --i >= 0;)
  203671. {
  203672. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  203673. if ((! out->doneFlag) && out->service())
  203674. {
  203675. out->doneFlag = true;
  203676. --numToDo;
  203677. }
  203678. }
  203679. if (numToDo <= 0)
  203680. break;
  203681. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  203682. {
  203683. resync();
  203684. break;
  203685. }
  203686. if (--count <= 0)
  203687. {
  203688. Sleep (1);
  203689. count = maxCount;
  203690. }
  203691. if (threadShouldExit())
  203692. return;
  203693. }
  203694. }
  203695. else
  203696. {
  203697. sleep (1);
  203698. }
  203699. const ScopedLock sl (startStopLock);
  203700. if (isStarted)
  203701. {
  203702. JUCE_TRY
  203703. {
  203704. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  203705. numInputBuffers,
  203706. outputBuffers,
  203707. numOutputBuffers,
  203708. bufferSizeSamples);
  203709. }
  203710. JUCE_CATCH_EXCEPTION
  203711. totalSamplesOut += bufferSizeSamples;
  203712. }
  203713. else
  203714. {
  203715. for (i = 0; i < numOutputBuffers; ++i)
  203716. if (outputBuffers[i] != 0)
  203717. zeromem (outputBuffers[i], bufferSizeSamples * sizeof (float));
  203718. totalSamplesOut = 0;
  203719. sleep (1);
  203720. }
  203721. }
  203722. }
  203723. };
  203724. class DSoundAudioIODeviceType : public AudioIODeviceType
  203725. {
  203726. public:
  203727. DSoundAudioIODeviceType()
  203728. : AudioIODeviceType (T("DirectSound")),
  203729. hasScanned (false)
  203730. {
  203731. initialiseDSoundFunctions();
  203732. }
  203733. ~DSoundAudioIODeviceType()
  203734. {
  203735. }
  203736. void scanForDevices()
  203737. {
  203738. hasScanned = true;
  203739. outputDeviceNames.clear();
  203740. outputGuids.clear();
  203741. inputDeviceNames.clear();
  203742. inputGuids.clear();
  203743. if (dsDirectSoundEnumerateW != 0)
  203744. {
  203745. dsDirectSoundEnumerateW (outputEnumProcW, this);
  203746. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  203747. }
  203748. }
  203749. const StringArray getDeviceNames (const bool wantInputNames) const
  203750. {
  203751. jassert (hasScanned); // need to call scanForDevices() before doing this
  203752. return wantInputNames ? inputDeviceNames
  203753. : outputDeviceNames;
  203754. }
  203755. int getDefaultDeviceIndex (const bool /*forInput*/) const
  203756. {
  203757. jassert (hasScanned); // need to call scanForDevices() before doing this
  203758. return 0;
  203759. }
  203760. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  203761. {
  203762. jassert (hasScanned); // need to call scanForDevices() before doing this
  203763. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  203764. if (d == 0)
  203765. return -1;
  203766. return asInput ? d->inputDeviceIndex
  203767. : d->outputDeviceIndex;
  203768. }
  203769. bool hasSeparateInputsAndOutputs() const { return true; }
  203770. AudioIODevice* createDevice (const String& outputDeviceName,
  203771. const String& inputDeviceName)
  203772. {
  203773. jassert (hasScanned); // need to call scanForDevices() before doing this
  203774. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  203775. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  203776. if (outputIndex >= 0 || inputIndex >= 0)
  203777. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  203778. : inputDeviceName,
  203779. outputIndex, inputIndex);
  203780. return 0;
  203781. }
  203782. juce_UseDebuggingNewOperator
  203783. StringArray outputDeviceNames;
  203784. OwnedArray <GUID> outputGuids;
  203785. StringArray inputDeviceNames;
  203786. OwnedArray <GUID> inputGuids;
  203787. private:
  203788. bool hasScanned;
  203789. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  203790. {
  203791. desc = desc.trim();
  203792. if (desc.isNotEmpty())
  203793. {
  203794. const String origDesc (desc);
  203795. int n = 2;
  203796. while (outputDeviceNames.contains (desc))
  203797. desc = origDesc + T(" (") + String (n++) + T(")");
  203798. outputDeviceNames.add (desc);
  203799. if (lpGUID != 0)
  203800. outputGuids.add (new GUID (*lpGUID));
  203801. else
  203802. outputGuids.add (0);
  203803. }
  203804. return TRUE;
  203805. }
  203806. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  203807. {
  203808. return ((DSoundAudioIODeviceType*) object)
  203809. ->outputEnumProc (lpGUID, String (description));
  203810. }
  203811. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  203812. {
  203813. return ((DSoundAudioIODeviceType*) object)
  203814. ->outputEnumProc (lpGUID, String (description));
  203815. }
  203816. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  203817. {
  203818. desc = desc.trim();
  203819. if (desc.isNotEmpty())
  203820. {
  203821. const String origDesc (desc);
  203822. int n = 2;
  203823. while (inputDeviceNames.contains (desc))
  203824. desc = origDesc + T(" (") + String (n++) + T(")");
  203825. inputDeviceNames.add (desc);
  203826. if (lpGUID != 0)
  203827. inputGuids.add (new GUID (*lpGUID));
  203828. else
  203829. inputGuids.add (0);
  203830. }
  203831. return TRUE;
  203832. }
  203833. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  203834. {
  203835. return ((DSoundAudioIODeviceType*) object)
  203836. ->inputEnumProc (lpGUID, String (description));
  203837. }
  203838. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  203839. {
  203840. return ((DSoundAudioIODeviceType*) object)
  203841. ->inputEnumProc (lpGUID, String (description));
  203842. }
  203843. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  203844. const DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  203845. };
  203846. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  203847. {
  203848. return new DSoundAudioIODeviceType();
  203849. }
  203850. const String DSoundAudioIODevice::openDevice (const BitArray& inputChannels,
  203851. const BitArray& outputChannels,
  203852. double sampleRate_,
  203853. int bufferSizeSamples_)
  203854. {
  203855. closeDevice();
  203856. totalSamplesOut = 0;
  203857. sampleRate = sampleRate_;
  203858. if (bufferSizeSamples_ <= 0)
  203859. bufferSizeSamples_ = 960; // use as a default size if none is set.
  203860. bufferSizeSamples = bufferSizeSamples_ & ~7;
  203861. DSoundAudioIODeviceType dlh;
  203862. dlh.scanForDevices();
  203863. enabledInputs = inputChannels;
  203864. enabledInputs.setRange (inChannels.size(),
  203865. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  203866. false);
  203867. numInputBuffers = enabledInputs.countNumberOfSetBits();
  203868. inputBuffers = new float* [numInputBuffers + 2];
  203869. zeromem (inputBuffers, sizeof (float*) * numInputBuffers + 2);
  203870. int i, numIns = 0;
  203871. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  203872. {
  203873. float* left = 0;
  203874. float* right = 0;
  203875. if (enabledInputs[i])
  203876. left = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  203877. if (enabledInputs[i + 1])
  203878. right = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  203879. if (left != 0 || right != 0)
  203880. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  203881. dlh.inputGuids [inputDeviceIndex],
  203882. (int) sampleRate, bufferSizeSamples,
  203883. left, right));
  203884. }
  203885. enabledOutputs = outputChannels;
  203886. enabledOutputs.setRange (outChannels.size(),
  203887. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  203888. false);
  203889. numOutputBuffers = enabledOutputs.countNumberOfSetBits();
  203890. outputBuffers = new float* [numOutputBuffers + 2];
  203891. zeromem (outputBuffers, sizeof (float*) * numOutputBuffers + 2);
  203892. int numOuts = 0;
  203893. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  203894. {
  203895. float* left = 0;
  203896. float* right = 0;
  203897. if (enabledOutputs[i])
  203898. left = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  203899. if (enabledOutputs[i + 1])
  203900. right = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  203901. if (left != 0 || right != 0)
  203902. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  203903. dlh.outputGuids [outputDeviceIndex],
  203904. (int) sampleRate, bufferSizeSamples,
  203905. left, right));
  203906. }
  203907. String error;
  203908. // boost our priority while opening the devices to try to get better sync between them
  203909. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  203910. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  203911. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  203912. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  203913. for (i = 0; i < outChans.size(); ++i)
  203914. {
  203915. error = outChans[i]->open();
  203916. if (error.isNotEmpty())
  203917. {
  203918. error = T("Error opening ") + dlh.outputDeviceNames[i]
  203919. + T(": \"") + error + T("\"");
  203920. break;
  203921. }
  203922. }
  203923. if (error.isEmpty())
  203924. {
  203925. for (i = 0; i < inChans.size(); ++i)
  203926. {
  203927. error = inChans[i]->open();
  203928. if (error.isNotEmpty())
  203929. {
  203930. error = T("Error opening ") + dlh.inputDeviceNames[i]
  203931. + T(": \"") + error + T("\"");
  203932. break;
  203933. }
  203934. }
  203935. }
  203936. if (error.isEmpty())
  203937. {
  203938. totalSamplesOut = 0;
  203939. for (i = 0; i < outChans.size(); ++i)
  203940. outChans.getUnchecked(i)->synchronisePosition();
  203941. for (i = 0; i < inChans.size(); ++i)
  203942. inChans.getUnchecked(i)->synchronisePosition();
  203943. startThread (9);
  203944. sleep (10);
  203945. notify();
  203946. }
  203947. else
  203948. {
  203949. log (error);
  203950. }
  203951. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  203952. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  203953. return error;
  203954. }
  203955. #undef log
  203956. END_JUCE_NAMESPACE
  203957. /********* End of inlined file: juce_win32_DirectSound.cpp *********/
  203958. /********* Start of inlined file: juce_win32_FileChooser.cpp *********/
  203959. #ifdef _MSC_VER
  203960. #pragma warning (disable: 4514)
  203961. #pragma warning (push)
  203962. #endif
  203963. #include <shlobj.h>
  203964. BEGIN_JUCE_NAMESPACE
  203965. #ifdef _MSC_VER
  203966. #pragma warning (pop)
  203967. #endif
  203968. static const void* defaultDirPath = 0;
  203969. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  203970. static Component* currentExtraFileWin = 0;
  203971. static bool areThereAnyAlwaysOnTopWindows()
  203972. {
  203973. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  203974. {
  203975. Component* c = Desktop::getInstance().getComponent (i);
  203976. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  203977. return true;
  203978. }
  203979. return false;
  203980. }
  203981. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  203982. {
  203983. if (msg == BFFM_INITIALIZED)
  203984. {
  203985. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  203986. }
  203987. else if (msg == BFFM_VALIDATEFAILEDW)
  203988. {
  203989. returnedString = (LPCWSTR) lParam;
  203990. }
  203991. else if (msg == BFFM_VALIDATEFAILEDA)
  203992. {
  203993. returnedString = (const char*) lParam;
  203994. }
  203995. return 0;
  203996. }
  203997. void juce_setWindowStyleBit (HWND h, int styleType, int feature, bool bitIsSet);
  203998. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  203999. {
  204000. if (currentExtraFileWin != 0)
  204001. {
  204002. if (uiMsg == WM_INITDIALOG)
  204003. {
  204004. HWND dialogH = GetParent (hdlg);
  204005. jassert (dialogH != 0);
  204006. if (dialogH == 0)
  204007. dialogH = hdlg;
  204008. RECT r, cr;
  204009. GetWindowRect (dialogH, &r);
  204010. GetClientRect (dialogH, &cr);
  204011. SetWindowPos (dialogH, 0,
  204012. r.left, r.top,
  204013. currentExtraFileWin->getWidth() + jmax (150, r.right - r.left),
  204014. jmax (150, r.bottom - r.top),
  204015. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  204016. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  204017. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  204018. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  204019. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  204020. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  204021. }
  204022. else if (uiMsg == WM_NOTIFY)
  204023. {
  204024. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  204025. if (ofn->hdr.code == CDN_SELCHANGE)
  204026. {
  204027. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  204028. if (comp != 0)
  204029. {
  204030. TCHAR path [MAX_PATH * 2];
  204031. path[0] = 0;
  204032. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  204033. const String fn ((const WCHAR*) path);
  204034. comp->selectedFileChanged (File (fn));
  204035. }
  204036. }
  204037. }
  204038. }
  204039. return 0;
  204040. }
  204041. class FPComponentHolder : public Component
  204042. {
  204043. public:
  204044. FPComponentHolder()
  204045. {
  204046. setVisible (true);
  204047. setOpaque (true);
  204048. }
  204049. ~FPComponentHolder()
  204050. {
  204051. }
  204052. void paint (Graphics& g)
  204053. {
  204054. g.fillAll (Colours::lightgrey);
  204055. }
  204056. private:
  204057. FPComponentHolder (const FPComponentHolder&);
  204058. const FPComponentHolder& operator= (const FPComponentHolder&);
  204059. };
  204060. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  204061. const String& title,
  204062. const File& currentFileOrDirectory,
  204063. const String& filter,
  204064. bool selectsDirectory,
  204065. bool isSaveDialogue,
  204066. bool warnAboutOverwritingExistingFiles,
  204067. bool selectMultipleFiles,
  204068. FilePreviewComponent* extraInfoComponent)
  204069. {
  204070. const int numCharsAvailable = 32768;
  204071. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  204072. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  204073. int fnameIdx = 0;
  204074. JUCE_TRY
  204075. {
  204076. // use a modal window as the parent for this dialog box
  204077. // to block input from other app windows
  204078. const Rectangle mainMon (Desktop::getInstance().getMainMonitorArea());
  204079. Component w (String::empty);
  204080. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  204081. mainMon.getY() + mainMon.getHeight() / 4,
  204082. 0, 0);
  204083. w.setOpaque (true);
  204084. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  204085. w.addToDesktop (0);
  204086. if (extraInfoComponent == 0)
  204087. w.enterModalState();
  204088. String initialDir;
  204089. if (currentFileOrDirectory.isDirectory())
  204090. {
  204091. initialDir = currentFileOrDirectory.getFullPathName();
  204092. }
  204093. else
  204094. {
  204095. currentFileOrDirectory.getFileName().copyToBuffer (fname, numCharsAvailable);
  204096. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  204097. }
  204098. if (currentExtraFileWin->isValidComponent())
  204099. {
  204100. jassertfalse
  204101. return;
  204102. }
  204103. if (selectsDirectory)
  204104. {
  204105. LPITEMIDLIST list = 0;
  204106. filenameSpace.fillWith (0);
  204107. {
  204108. BROWSEINFO bi;
  204109. zerostruct (bi);
  204110. bi.hwndOwner = (HWND) w.getWindowHandle();
  204111. bi.pszDisplayName = fname;
  204112. bi.lpszTitle = title;
  204113. bi.lpfn = browseCallbackProc;
  204114. #ifdef BIF_USENEWUI
  204115. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  204116. #else
  204117. bi.ulFlags = 0x50;
  204118. #endif
  204119. defaultDirPath = (const WCHAR*) initialDir;
  204120. list = SHBrowseForFolder (&bi);
  204121. if (! SHGetPathFromIDListW (list, fname))
  204122. {
  204123. fname[0] = 0;
  204124. returnedString = String::empty;
  204125. }
  204126. }
  204127. LPMALLOC al;
  204128. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  204129. al->Free (list);
  204130. defaultDirPath = 0;
  204131. if (returnedString.isNotEmpty())
  204132. {
  204133. const String stringFName (fname);
  204134. results.add (new File (File (stringFName).getSiblingFile (returnedString)));
  204135. returnedString = String::empty;
  204136. return;
  204137. }
  204138. }
  204139. else
  204140. {
  204141. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  204142. if (warnAboutOverwritingExistingFiles)
  204143. flags |= OFN_OVERWRITEPROMPT;
  204144. if (selectMultipleFiles)
  204145. flags |= OFN_ALLOWMULTISELECT;
  204146. if (extraInfoComponent != 0)
  204147. {
  204148. flags |= OFN_ENABLEHOOK;
  204149. currentExtraFileWin = new FPComponentHolder();
  204150. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  204151. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  204152. extraInfoComponent->getHeight());
  204153. currentExtraFileWin->addToDesktop (0);
  204154. currentExtraFileWin->enterModalState();
  204155. }
  204156. {
  204157. WCHAR filters [1024];
  204158. zeromem (filters, sizeof (filters));
  204159. filter.copyToBuffer (filters, 1024);
  204160. filter.copyToBuffer (filters + filter.length() + 1,
  204161. 1022 - filter.length());
  204162. OPENFILENAMEW of;
  204163. zerostruct (of);
  204164. #ifdef OPENFILENAME_SIZE_VERSION_400W
  204165. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  204166. #else
  204167. of.lStructSize = sizeof (of);
  204168. #endif
  204169. of.hwndOwner = (HWND) w.getWindowHandle();
  204170. of.lpstrFilter = filters;
  204171. of.nFilterIndex = 1;
  204172. of.lpstrFile = fname;
  204173. of.nMaxFile = numCharsAvailable;
  204174. of.lpstrInitialDir = initialDir;
  204175. of.lpstrTitle = title;
  204176. of.Flags = flags;
  204177. if (extraInfoComponent != 0)
  204178. of.lpfnHook = &openCallback;
  204179. if (isSaveDialogue)
  204180. {
  204181. if (! GetSaveFileName (&of))
  204182. fname[0] = 0;
  204183. else
  204184. fnameIdx = of.nFileOffset;
  204185. }
  204186. else
  204187. {
  204188. if (! GetOpenFileName (&of))
  204189. fname[0] = 0;
  204190. else
  204191. fnameIdx = of.nFileOffset;
  204192. }
  204193. }
  204194. }
  204195. }
  204196. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  204197. catch (...)
  204198. {
  204199. fname[0] = 0;
  204200. }
  204201. #endif
  204202. deleteAndZero (currentExtraFileWin);
  204203. const WCHAR* const files = fname;
  204204. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  204205. {
  204206. const WCHAR* filename = files + fnameIdx;
  204207. while (*filename != 0)
  204208. {
  204209. const String filepath (String (files) + T("\\") + String (filename));
  204210. results.add (new File (filepath));
  204211. filename += CharacterFunctions::length (filename) + 1;
  204212. }
  204213. }
  204214. else if (files[0] != 0)
  204215. {
  204216. results.add (new File (files));
  204217. }
  204218. }
  204219. END_JUCE_NAMESPACE
  204220. /********* End of inlined file: juce_win32_FileChooser.cpp *********/
  204221. /********* Start of inlined file: juce_win32_Fonts.cpp *********/
  204222. BEGIN_JUCE_NAMESPACE
  204223. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  204224. NEWTEXTMETRICEXW*,
  204225. int type,
  204226. LPARAM lParam)
  204227. {
  204228. if (lpelfe != 0 && type == TRUETYPE_FONTTYPE)
  204229. {
  204230. const String fontName (lpelfe->elfLogFont.lfFaceName);
  204231. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters (T("@")));
  204232. }
  204233. return 1;
  204234. }
  204235. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  204236. NEWTEXTMETRICEXW*,
  204237. int type,
  204238. LPARAM lParam)
  204239. {
  204240. if (lpelfe != 0
  204241. && ((type & (DEVICE_FONTTYPE | RASTER_FONTTYPE)) == 0))
  204242. {
  204243. LOGFONTW lf;
  204244. zerostruct (lf);
  204245. lf.lfWeight = FW_DONTCARE;
  204246. lf.lfOutPrecision = OUT_TT_ONLY_PRECIS;
  204247. lf.lfQuality = DEFAULT_QUALITY;
  204248. lf.lfCharSet = DEFAULT_CHARSET;
  204249. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204250. lf.lfPitchAndFamily = FF_DONTCARE;
  204251. const String fontName (lpelfe->elfLogFont.lfFaceName);
  204252. fontName.copyToBuffer (lf.lfFaceName, LF_FACESIZE - 1);
  204253. HDC dc = CreateCompatibleDC (0);
  204254. EnumFontFamiliesEx (dc, &lf,
  204255. (FONTENUMPROCW) &wfontEnum2,
  204256. lParam, 0);
  204257. DeleteDC (dc);
  204258. }
  204259. return 1;
  204260. }
  204261. const StringArray Font::findAllTypefaceNames() throw()
  204262. {
  204263. StringArray results;
  204264. HDC dc = CreateCompatibleDC (0);
  204265. {
  204266. LOGFONTW lf;
  204267. zerostruct (lf);
  204268. lf.lfWeight = FW_DONTCARE;
  204269. lf.lfOutPrecision = OUT_TT_ONLY_PRECIS;
  204270. lf.lfQuality = DEFAULT_QUALITY;
  204271. lf.lfCharSet = DEFAULT_CHARSET;
  204272. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204273. lf.lfPitchAndFamily = FF_DONTCARE;
  204274. lf.lfFaceName[0] = 0;
  204275. EnumFontFamiliesEx (dc, &lf,
  204276. (FONTENUMPROCW) &wfontEnum1,
  204277. (LPARAM) &results, 0);
  204278. }
  204279. DeleteDC (dc);
  204280. results.sort (true);
  204281. return results;
  204282. }
  204283. extern bool juce_IsRunningInWine() throw();
  204284. void Font::getDefaultFontNames (String& defaultSans,
  204285. String& defaultSerif,
  204286. String& defaultFixed) throw()
  204287. {
  204288. if (juce_IsRunningInWine())
  204289. {
  204290. // If we're running in Wine, then use fonts that might be available on Linux..
  204291. defaultSans = "Bitstream Vera Sans";
  204292. defaultSerif = "Bitstream Vera Serif";
  204293. defaultFixed = "Bitstream Vera Sans Mono";
  204294. }
  204295. else
  204296. {
  204297. defaultSans = "Verdana";
  204298. defaultSerif = "Times";
  204299. defaultFixed = "Lucida Console";
  204300. }
  204301. }
  204302. class FontDCHolder : private DeletedAtShutdown
  204303. {
  204304. HDC dc;
  204305. String fontName;
  204306. KERNINGPAIR* kps;
  204307. int numKPs;
  204308. bool bold, italic;
  204309. int size;
  204310. FontDCHolder (const FontDCHolder&);
  204311. const FontDCHolder& operator= (const FontDCHolder&);
  204312. public:
  204313. HFONT fontH;
  204314. FontDCHolder() throw()
  204315. : dc (0),
  204316. kps (0),
  204317. numKPs (0),
  204318. bold (false),
  204319. italic (false),
  204320. size (0)
  204321. {
  204322. }
  204323. ~FontDCHolder() throw()
  204324. {
  204325. if (dc != 0)
  204326. {
  204327. DeleteDC (dc);
  204328. DeleteObject (fontH);
  204329. juce_free (kps);
  204330. }
  204331. clearSingletonInstance();
  204332. }
  204333. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  204334. HDC loadFont (const String& fontName_,
  204335. const bool bold_,
  204336. const bool italic_,
  204337. const int size_) throw()
  204338. {
  204339. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  204340. {
  204341. fontName = fontName_;
  204342. bold = bold_;
  204343. italic = italic_;
  204344. size = size_;
  204345. if (dc != 0)
  204346. {
  204347. DeleteDC (dc);
  204348. DeleteObject (fontH);
  204349. juce_free (kps);
  204350. kps = 0;
  204351. }
  204352. fontH = 0;
  204353. dc = CreateCompatibleDC (0);
  204354. SetMapperFlags (dc, 0);
  204355. SetMapMode (dc, MM_TEXT);
  204356. LOGFONTW lfw;
  204357. zerostruct (lfw);
  204358. lfw.lfCharSet = DEFAULT_CHARSET;
  204359. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204360. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  204361. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  204362. lfw.lfQuality = PROOF_QUALITY;
  204363. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  204364. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  204365. fontName.copyToBuffer (lfw.lfFaceName, LF_FACESIZE - 1);
  204366. lfw.lfHeight = size > 0 ? size : -256;
  204367. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  204368. if (standardSizedFont != 0)
  204369. {
  204370. if (SelectObject (dc, standardSizedFont) != 0)
  204371. {
  204372. fontH = standardSizedFont;
  204373. if (size == 0)
  204374. {
  204375. OUTLINETEXTMETRIC otm;
  204376. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  204377. {
  204378. lfw.lfHeight = -(int) otm.otmEMSquare;
  204379. fontH = CreateFontIndirect (&lfw);
  204380. SelectObject (dc, fontH);
  204381. DeleteObject (standardSizedFont);
  204382. }
  204383. }
  204384. }
  204385. else
  204386. {
  204387. jassertfalse
  204388. }
  204389. }
  204390. else
  204391. {
  204392. jassertfalse
  204393. }
  204394. }
  204395. return dc;
  204396. }
  204397. KERNINGPAIR* getKerningPairs (int& numKPs_) throw()
  204398. {
  204399. if (kps == 0)
  204400. {
  204401. numKPs = GetKerningPairs (dc, 0, 0);
  204402. kps = (KERNINGPAIR*) juce_calloc (sizeof (KERNINGPAIR) * numKPs);
  204403. GetKerningPairs (dc, numKPs, kps);
  204404. }
  204405. numKPs_ = numKPs;
  204406. return kps;
  204407. }
  204408. };
  204409. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  204410. static bool addGlyphToTypeface (HDC dc,
  204411. juce_wchar character,
  204412. Typeface& dest,
  204413. bool addKerning)
  204414. {
  204415. Path destShape;
  204416. GLYPHMETRICS gm;
  204417. float height;
  204418. BOOL ok = false;
  204419. {
  204420. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  204421. WORD index = 0;
  204422. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  204423. && index == 0xffff)
  204424. {
  204425. return false;
  204426. }
  204427. }
  204428. TEXTMETRIC tm;
  204429. ok = GetTextMetrics (dc, &tm);
  204430. height = (float) tm.tmHeight;
  204431. if (! ok)
  204432. {
  204433. dest.addGlyph (character, destShape, 0);
  204434. return true;
  204435. }
  204436. const float scaleX = 1.0f / height;
  204437. const float scaleY = -1.0f / height;
  204438. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  204439. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  204440. &gm, 0, 0, &identityMatrix);
  204441. if (bufSize > 0)
  204442. {
  204443. char* const data = (char*) juce_malloc (bufSize);
  204444. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  204445. bufSize, data, &identityMatrix);
  204446. const TTPOLYGONHEADER* pheader = (TTPOLYGONHEADER*) data;
  204447. while ((char*) pheader < data + bufSize)
  204448. {
  204449. #define remapX(v) (scaleX * (v).x.value)
  204450. #define remapY(v) (scaleY * (v).y.value)
  204451. float x = remapX (pheader->pfxStart);
  204452. float y = remapY (pheader->pfxStart);
  204453. destShape.startNewSubPath (x, y);
  204454. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  204455. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  204456. while ((const char*) curve < curveEnd)
  204457. {
  204458. if (curve->wType == TT_PRIM_LINE)
  204459. {
  204460. for (int i = 0; i < curve->cpfx; ++i)
  204461. {
  204462. x = remapX (curve->apfx [i]);
  204463. y = remapY (curve->apfx [i]);
  204464. destShape.lineTo (x, y);
  204465. }
  204466. }
  204467. else if (curve->wType == TT_PRIM_QSPLINE)
  204468. {
  204469. for (int i = 0; i < curve->cpfx - 1; ++i)
  204470. {
  204471. const float x2 = remapX (curve->apfx [i]);
  204472. const float y2 = remapY (curve->apfx [i]);
  204473. float x3, y3;
  204474. if (i < curve->cpfx - 2)
  204475. {
  204476. x3 = 0.5f * (x2 + remapX (curve->apfx [i + 1]));
  204477. y3 = 0.5f * (y2 + remapY (curve->apfx [i + 1]));
  204478. }
  204479. else
  204480. {
  204481. x3 = remapX (curve->apfx [i + 1]);
  204482. y3 = remapY (curve->apfx [i + 1]);
  204483. }
  204484. destShape.quadraticTo (x2, y2, x3, y3);
  204485. x = x3;
  204486. y = y3;
  204487. }
  204488. }
  204489. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  204490. }
  204491. pheader = (const TTPOLYGONHEADER*) curve;
  204492. destShape.closeSubPath();
  204493. }
  204494. juce_free (data);
  204495. }
  204496. dest.addGlyph (character, destShape, gm.gmCellIncX / height);
  204497. if (addKerning)
  204498. {
  204499. int numKPs;
  204500. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  204501. for (int i = 0; i < numKPs; ++i)
  204502. {
  204503. if (kps[i].wFirst == character)
  204504. {
  204505. dest.addKerningPair (kps[i].wFirst,
  204506. kps[i].wSecond,
  204507. kps[i].iKernAmount / height);
  204508. }
  204509. }
  204510. }
  204511. return true;
  204512. }
  204513. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  204514. {
  204515. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), 0);
  204516. return addGlyphToTypeface (dc, character, *this, true);
  204517. }
  204518. /*Image* Typeface::renderGlyphToImage (juce_wchar character, float& topLeftX, float& topLeftY)
  204519. {
  204520. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), hintingSize);
  204521. int bufSize;
  204522. GLYPHMETRICS gm;
  204523. const UINT format = GGO_GRAY2_BITMAP;
  204524. const int shift = 6;
  204525. if (wGetGlyphOutlineW != 0)
  204526. bufSize = wGetGlyphOutlineW (dc, character, format, &gm, 0, 0, &identityMatrix);
  204527. else
  204528. bufSize = GetGlyphOutline (dc, character, format, &gm, 0, 0, &identityMatrix);
  204529. Image* im = new Image (Image::SingleChannel, jmax (1, gm.gmBlackBoxX), jmax (1, gm.gmBlackBoxY), true);
  204530. if (bufSize > 0)
  204531. {
  204532. topLeftX = (float) gm.gmptGlyphOrigin.x;
  204533. topLeftY = (float) -gm.gmptGlyphOrigin.y;
  204534. uint8* const data = (uint8*) juce_calloc (bufSize);
  204535. if (wGetGlyphOutlineW != 0)
  204536. wGetGlyphOutlineW (dc, character, format, &gm, bufSize, data, &identityMatrix);
  204537. else
  204538. GetGlyphOutline (dc, character, format, &gm, bufSize, data, &identityMatrix);
  204539. const int stride = ((gm.gmBlackBoxX + 3) & ~3);
  204540. for (int y = gm.gmBlackBoxY; --y >= 0;)
  204541. {
  204542. for (int x = gm.gmBlackBoxX; --x >= 0;)
  204543. {
  204544. const int level = data [x + y * stride] << shift;
  204545. if (level > 0)
  204546. im->setPixelAt (x, y, Colour ((uint8) 0xff, (uint8) 0xff, (uint8) 0xff, (uint8) jmin (0xff, level)));
  204547. }
  204548. }
  204549. juce_free (data);
  204550. }
  204551. return im;
  204552. }*/
  204553. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  204554. bool bold,
  204555. bool italic,
  204556. bool addAllGlyphsToFont) throw()
  204557. {
  204558. clear();
  204559. HDC dc = FontDCHolder::getInstance()->loadFont (fontName, bold, italic, 0);
  204560. float height;
  204561. int firstChar, lastChar;
  204562. {
  204563. TEXTMETRIC tm;
  204564. GetTextMetrics (dc, &tm);
  204565. height = (float) tm.tmHeight;
  204566. firstChar = tm.tmFirstChar;
  204567. lastChar = tm.tmLastChar;
  204568. setAscent (tm.tmAscent / height);
  204569. setDefaultCharacter (tm.tmDefaultChar);
  204570. }
  204571. setName (fontName);
  204572. setBold (bold);
  204573. setItalic (italic);
  204574. if (addAllGlyphsToFont)
  204575. {
  204576. for (int character = firstChar; character <= lastChar; ++character)
  204577. addGlyphToTypeface (dc, (juce_wchar) character, *this, false);
  204578. int numKPs;
  204579. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  204580. for (int i = 0; i < numKPs; ++i)
  204581. {
  204582. addKerningPair (kps[i].wFirst,
  204583. kps[i].wSecond,
  204584. kps[i].iKernAmount / height);
  204585. }
  204586. }
  204587. }
  204588. END_JUCE_NAMESPACE
  204589. /********* End of inlined file: juce_win32_Fonts.cpp *********/
  204590. /********* Start of inlined file: juce_win32_Messaging.cpp *********/
  204591. BEGIN_JUCE_NAMESPACE
  204592. static const unsigned int specialId = WM_APP + 0x4400;
  204593. static const unsigned int broadcastId = WM_APP + 0x4403;
  204594. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  204595. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  204596. HWND juce_messageWindowHandle = 0;
  204597. extern long improbableWindowNumber; // defined in windowing.cpp
  204598. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  204599. const UINT message,
  204600. const WPARAM wParam,
  204601. const LPARAM lParam) throw()
  204602. {
  204603. JUCE_TRY
  204604. {
  204605. if (h == juce_messageWindowHandle)
  204606. {
  204607. if (message == specialCallbackId)
  204608. {
  204609. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  204610. return (LRESULT) (*func) ((void*) lParam);
  204611. }
  204612. else if (message == specialId)
  204613. {
  204614. // these are trapped early in the dispatch call, but must also be checked
  204615. // here in case there are windows modal dialog boxes doing their own
  204616. // dispatch loop and not calling our version
  204617. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  204618. return 0;
  204619. }
  204620. else if (message == broadcastId)
  204621. {
  204622. String* const messageString = (String*) lParam;
  204623. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  204624. delete messageString;
  204625. return 0;
  204626. }
  204627. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  204628. {
  204629. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  204630. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  204631. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  204632. return 0;
  204633. }
  204634. }
  204635. }
  204636. JUCE_CATCH_EXCEPTION
  204637. return DefWindowProc (h, message, wParam, lParam);
  204638. }
  204639. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  204640. {
  204641. MSG m;
  204642. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  204643. return false;
  204644. if (GetMessage (&m, (HWND) 0, 0, 0) > 0)
  204645. {
  204646. if (m.message == specialId
  204647. && m.hwnd == juce_messageWindowHandle)
  204648. {
  204649. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  204650. }
  204651. else
  204652. {
  204653. if (GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber
  204654. && (m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN))
  204655. {
  204656. // if it's someone else's window being clicked on, and the focus is
  204657. // currently on a juce window, pass the kb focus over..
  204658. HWND currentFocus = GetFocus();
  204659. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  204660. SetFocus (m.hwnd);
  204661. }
  204662. TranslateMessage (&m);
  204663. DispatchMessage (&m);
  204664. }
  204665. }
  204666. return true;
  204667. }
  204668. bool juce_postMessageToSystemQueue (void* message)
  204669. {
  204670. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  204671. }
  204672. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  204673. void* userData)
  204674. {
  204675. if (MessageManager::getInstance()->isThisTheMessageThread())
  204676. {
  204677. return (*callback) (userData);
  204678. }
  204679. else
  204680. {
  204681. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  204682. // deadlock because the message manager is blocked from running, and can't
  204683. // call your function..
  204684. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  204685. return (void*) SendMessage (juce_messageWindowHandle,
  204686. specialCallbackId,
  204687. (WPARAM) callback,
  204688. (LPARAM) userData);
  204689. }
  204690. }
  204691. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  204692. {
  204693. if (hwnd != juce_messageWindowHandle)
  204694. (reinterpret_cast <VoidArray*> (lParam))->add ((void*) hwnd);
  204695. return TRUE;
  204696. }
  204697. void MessageManager::broadcastMessage (const String& value) throw()
  204698. {
  204699. VoidArray windows;
  204700. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  204701. const String localCopy (value);
  204702. COPYDATASTRUCT data;
  204703. data.dwData = broadcastId;
  204704. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  204705. data.lpData = (void*) (const juce_wchar*) localCopy;
  204706. for (int i = windows.size(); --i >= 0;)
  204707. {
  204708. HWND hwnd = (HWND) windows.getUnchecked(i);
  204709. TCHAR windowName [64]; // no need to read longer strings than this
  204710. GetWindowText (hwnd, windowName, 64);
  204711. windowName [63] = 0;
  204712. if (String (windowName) == String (messageWindowName))
  204713. {
  204714. DWORD_PTR result;
  204715. SendMessageTimeout (hwnd, WM_COPYDATA,
  204716. (WPARAM) juce_messageWindowHandle,
  204717. (LPARAM) &data,
  204718. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  204719. 8000,
  204720. &result);
  204721. }
  204722. }
  204723. }
  204724. static const String getMessageWindowClassName()
  204725. {
  204726. // this name has to be different for each app/dll instance because otherwise
  204727. // poor old Win32 can get a bit confused (even despite it not being a process-global
  204728. // window class).
  204729. static int number = 0;
  204730. if (number == 0)
  204731. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  204732. return T("JUCEcs_") + String (number);
  204733. }
  204734. void MessageManager::doPlatformSpecificInitialisation()
  204735. {
  204736. OleInitialize (0);
  204737. const String className (getMessageWindowClassName());
  204738. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204739. WNDCLASSEX wc;
  204740. zerostruct (wc);
  204741. wc.cbSize = sizeof (wc);
  204742. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  204743. wc.cbWndExtra = 4;
  204744. wc.hInstance = hmod;
  204745. wc.lpszClassName = className;
  204746. RegisterClassEx (&wc);
  204747. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  204748. messageWindowName,
  204749. 0, 0, 0, 0, 0, 0, 0,
  204750. hmod, 0);
  204751. }
  204752. void MessageManager::doPlatformSpecificShutdown()
  204753. {
  204754. DestroyWindow (juce_messageWindowHandle);
  204755. UnregisterClass (getMessageWindowClassName(), 0);
  204756. OleUninitialize();
  204757. }
  204758. END_JUCE_NAMESPACE
  204759. /********* End of inlined file: juce_win32_Messaging.cpp *********/
  204760. /********* Start of inlined file: juce_win32_Midi.cpp *********/
  204761. BEGIN_JUCE_NAMESPACE
  204762. #if JUCE_MSVC
  204763. #pragma warning (disable: 4312)
  204764. #endif
  204765. using ::free;
  204766. static const int midiBufferSize = 1024 * 10;
  204767. static const int numInHeaders = 32;
  204768. static const int inBufferSize = 256;
  204769. static Array <void*, CriticalSection> activeMidiThreads;
  204770. class MidiInThread : public Thread
  204771. {
  204772. public:
  204773. MidiInThread (MidiInput* const input_,
  204774. MidiInputCallback* const callback_)
  204775. : Thread ("Juce Midi"),
  204776. hIn (0),
  204777. input (input_),
  204778. callback (callback_),
  204779. isStarted (false),
  204780. startTime (0),
  204781. pendingLength(0)
  204782. {
  204783. for (int i = numInHeaders; --i >= 0;)
  204784. {
  204785. zeromem (&hdr[i], sizeof (MIDIHDR));
  204786. hdr[i].lpData = inData[i];
  204787. hdr[i].dwBufferLength = inBufferSize;
  204788. }
  204789. };
  204790. ~MidiInThread()
  204791. {
  204792. stop();
  204793. if (hIn != 0)
  204794. {
  204795. int count = 5;
  204796. while (--count >= 0)
  204797. {
  204798. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  204799. break;
  204800. Sleep (20);
  204801. }
  204802. }
  204803. }
  204804. void handle (const uint32 message, const uint32 timeStamp) throw()
  204805. {
  204806. const int byte = message & 0xff;
  204807. if (byte < 0x80)
  204808. return;
  204809. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  204810. const double time = timeStampToTime (timeStamp);
  204811. lock.enter();
  204812. if (pendingLength < midiBufferSize - 12)
  204813. {
  204814. char* const p = pending + pendingLength;
  204815. *(double*) p = time;
  204816. *(uint32*) (p + 8) = numBytes;
  204817. *(uint32*) (p + 12) = message;
  204818. pendingLength += 12 + numBytes;
  204819. }
  204820. else
  204821. {
  204822. jassertfalse // midi buffer overflow! You might need to increase the size..
  204823. }
  204824. lock.exit();
  204825. notify();
  204826. }
  204827. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp) throw()
  204828. {
  204829. const int num = hdr->dwBytesRecorded;
  204830. if (num > 0)
  204831. {
  204832. const double time = timeStampToTime (timeStamp);
  204833. lock.enter();
  204834. if (pendingLength < midiBufferSize - (8 + num))
  204835. {
  204836. char* const p = pending + pendingLength;
  204837. *(double*) p = time;
  204838. *(uint32*) (p + 8) = num;
  204839. memcpy (p + 12, hdr->lpData, num);
  204840. pendingLength += 12 + num;
  204841. }
  204842. else
  204843. {
  204844. jassertfalse // midi buffer overflow! You might need to increase the size..
  204845. }
  204846. lock.exit();
  204847. notify();
  204848. }
  204849. }
  204850. void writeBlock (const int i) throw()
  204851. {
  204852. hdr[i].dwBytesRecorded = 0;
  204853. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  204854. jassert (res == MMSYSERR_NOERROR);
  204855. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  204856. jassert (res == MMSYSERR_NOERROR);
  204857. }
  204858. void run()
  204859. {
  204860. MemoryBlock pendingCopy (64);
  204861. while (! threadShouldExit())
  204862. {
  204863. for (int i = 0; i < numInHeaders; ++i)
  204864. {
  204865. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  204866. {
  204867. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  204868. (void) res;
  204869. jassert (res == MMSYSERR_NOERROR);
  204870. writeBlock (i);
  204871. }
  204872. }
  204873. lock.enter();
  204874. int len = pendingLength;
  204875. if (len > 0)
  204876. {
  204877. pendingCopy.ensureSize (len);
  204878. pendingCopy.copyFrom (pending, 0, len);
  204879. pendingLength = 0;
  204880. }
  204881. lock.exit();
  204882. //xxx needs to figure out if blocks are broken up or not
  204883. if (len == 0)
  204884. {
  204885. wait (500);
  204886. }
  204887. else
  204888. {
  204889. const char* p = (const char*) pendingCopy.getData();
  204890. while (len > 0)
  204891. {
  204892. const double time = *(const double*) p;
  204893. const int messageLen = *(const int*) (p + 8);
  204894. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  204895. callback->handleIncomingMidiMessage (input, message);
  204896. p += 12 + messageLen;
  204897. len -= 12 + messageLen;
  204898. }
  204899. }
  204900. }
  204901. }
  204902. void start() throw()
  204903. {
  204904. jassert (hIn != 0);
  204905. if (hIn != 0 && ! isStarted)
  204906. {
  204907. stop();
  204908. activeMidiThreads.addIfNotAlreadyThere (this);
  204909. int i;
  204910. for (i = 0; i < numInHeaders; ++i)
  204911. writeBlock (i);
  204912. startTime = Time::getMillisecondCounter();
  204913. MMRESULT res = midiInStart (hIn);
  204914. jassert (res == MMSYSERR_NOERROR);
  204915. if (res == MMSYSERR_NOERROR)
  204916. {
  204917. isStarted = true;
  204918. pendingLength = 0;
  204919. startThread (6);
  204920. }
  204921. }
  204922. }
  204923. void stop() throw()
  204924. {
  204925. if (isStarted)
  204926. {
  204927. stopThread (5000);
  204928. midiInReset (hIn);
  204929. midiInStop (hIn);
  204930. activeMidiThreads.removeValue (this);
  204931. lock.enter();
  204932. lock.exit();
  204933. for (int i = numInHeaders; --i >= 0;)
  204934. {
  204935. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  204936. {
  204937. int c = 10;
  204938. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  204939. Sleep (20);
  204940. jassert (c >= 0);
  204941. }
  204942. }
  204943. isStarted = false;
  204944. pendingLength = 0;
  204945. }
  204946. }
  204947. juce_UseDebuggingNewOperator
  204948. HMIDIIN hIn;
  204949. private:
  204950. MidiInput* input;
  204951. MidiInputCallback* callback;
  204952. bool isStarted;
  204953. uint32 startTime;
  204954. CriticalSection lock;
  204955. MIDIHDR hdr [numInHeaders];
  204956. char inData [numInHeaders] [inBufferSize];
  204957. int pendingLength;
  204958. char pending [midiBufferSize];
  204959. double timeStampToTime (uint32 timeStamp) throw()
  204960. {
  204961. timeStamp += startTime;
  204962. const uint32 now = Time::getMillisecondCounter();
  204963. if (timeStamp > now)
  204964. {
  204965. if (timeStamp > now + 2)
  204966. --startTime;
  204967. timeStamp = now;
  204968. }
  204969. return 0.001 * timeStamp;
  204970. }
  204971. MidiInThread (const MidiInThread&);
  204972. const MidiInThread& operator= (const MidiInThread&);
  204973. };
  204974. static void CALLBACK midiInCallback (HMIDIIN,
  204975. UINT uMsg,
  204976. DWORD_PTR dwInstance,
  204977. DWORD_PTR midiMessage,
  204978. DWORD_PTR timeStamp)
  204979. {
  204980. MidiInThread* const thread = (MidiInThread*) dwInstance;
  204981. if (thread != 0 && activeMidiThreads.contains (thread))
  204982. {
  204983. if (uMsg == MIM_DATA)
  204984. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  204985. else if (uMsg == MIM_LONGDATA)
  204986. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  204987. }
  204988. }
  204989. const StringArray MidiInput::getDevices()
  204990. {
  204991. StringArray s;
  204992. const int num = midiInGetNumDevs();
  204993. for (int i = 0; i < num; ++i)
  204994. {
  204995. MIDIINCAPS mc;
  204996. zerostruct (mc);
  204997. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  204998. s.add (String (mc.szPname, sizeof (mc.szPname)));
  204999. }
  205000. return s;
  205001. }
  205002. int MidiInput::getDefaultDeviceIndex()
  205003. {
  205004. return 0;
  205005. }
  205006. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  205007. {
  205008. if (callback == 0)
  205009. return 0;
  205010. UINT deviceId = MIDI_MAPPER;
  205011. int n = 0;
  205012. String name;
  205013. const int num = midiInGetNumDevs();
  205014. for (int i = 0; i < num; ++i)
  205015. {
  205016. MIDIINCAPS mc;
  205017. zerostruct (mc);
  205018. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  205019. {
  205020. if (index == n)
  205021. {
  205022. deviceId = i;
  205023. name = String (mc.szPname, sizeof (mc.szPname));
  205024. break;
  205025. }
  205026. ++n;
  205027. }
  205028. }
  205029. MidiInput* const in = new MidiInput (name);
  205030. MidiInThread* const thread = new MidiInThread (in, callback);
  205031. HMIDIIN h;
  205032. HRESULT err = midiInOpen (&h, deviceId,
  205033. (DWORD_PTR) &midiInCallback,
  205034. (DWORD_PTR) thread,
  205035. CALLBACK_FUNCTION);
  205036. if (err == MMSYSERR_NOERROR)
  205037. {
  205038. thread->hIn = h;
  205039. in->internal = (void*) thread;
  205040. return in;
  205041. }
  205042. else
  205043. {
  205044. delete in;
  205045. delete thread;
  205046. return 0;
  205047. }
  205048. }
  205049. MidiInput::MidiInput (const String& name_)
  205050. : name (name_),
  205051. internal (0)
  205052. {
  205053. }
  205054. MidiInput::~MidiInput()
  205055. {
  205056. if (internal != 0)
  205057. {
  205058. MidiInThread* const thread = (MidiInThread*) internal;
  205059. delete thread;
  205060. }
  205061. }
  205062. void MidiInput::start()
  205063. {
  205064. ((MidiInThread*) internal)->start();
  205065. }
  205066. void MidiInput::stop()
  205067. {
  205068. ((MidiInThread*) internal)->stop();
  205069. }
  205070. struct MidiOutHandle
  205071. {
  205072. int refCount;
  205073. UINT deviceId;
  205074. HMIDIOUT handle;
  205075. juce_UseDebuggingNewOperator
  205076. };
  205077. static VoidArray handles (4);
  205078. const StringArray MidiOutput::getDevices()
  205079. {
  205080. StringArray s;
  205081. const int num = midiOutGetNumDevs();
  205082. for (int i = 0; i < num; ++i)
  205083. {
  205084. MIDIOUTCAPS mc;
  205085. zerostruct (mc);
  205086. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  205087. s.add (String (mc.szPname, sizeof (mc.szPname)));
  205088. }
  205089. return s;
  205090. }
  205091. int MidiOutput::getDefaultDeviceIndex()
  205092. {
  205093. const int num = midiOutGetNumDevs();
  205094. int n = 0;
  205095. for (int i = 0; i < num; ++i)
  205096. {
  205097. MIDIOUTCAPS mc;
  205098. zerostruct (mc);
  205099. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  205100. {
  205101. if ((mc.wTechnology & MOD_MAPPER) != 0)
  205102. return n;
  205103. ++n;
  205104. }
  205105. }
  205106. return 0;
  205107. }
  205108. MidiOutput* MidiOutput::openDevice (int index)
  205109. {
  205110. UINT deviceId = MIDI_MAPPER;
  205111. const int num = midiOutGetNumDevs();
  205112. int i, n = 0;
  205113. for (i = 0; i < num; ++i)
  205114. {
  205115. MIDIOUTCAPS mc;
  205116. zerostruct (mc);
  205117. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  205118. {
  205119. // use the microsoft sw synth as a default - best not to allow deviceId
  205120. // to be MIDI_MAPPER, or else device sharing breaks
  205121. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase (T("microsoft")))
  205122. deviceId = i;
  205123. if (index == n)
  205124. {
  205125. deviceId = i;
  205126. break;
  205127. }
  205128. ++n;
  205129. }
  205130. }
  205131. for (i = handles.size(); --i >= 0;)
  205132. {
  205133. MidiOutHandle* const han = (MidiOutHandle*) handles.getUnchecked(i);
  205134. if (han != 0 && han->deviceId == deviceId)
  205135. {
  205136. han->refCount++;
  205137. MidiOutput* const out = new MidiOutput();
  205138. out->internal = (void*) han;
  205139. return out;
  205140. }
  205141. }
  205142. for (i = 4; --i >= 0;)
  205143. {
  205144. HMIDIOUT h = 0;
  205145. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  205146. if (res == MMSYSERR_NOERROR)
  205147. {
  205148. MidiOutHandle* const han = new MidiOutHandle();
  205149. han->deviceId = deviceId;
  205150. han->refCount = 1;
  205151. han->handle = h;
  205152. handles.add (han);
  205153. MidiOutput* const out = new MidiOutput();
  205154. out->internal = (void*) han;
  205155. return out;
  205156. }
  205157. else if (res == MMSYSERR_ALLOCATED)
  205158. {
  205159. Sleep (100);
  205160. }
  205161. else
  205162. {
  205163. break;
  205164. }
  205165. }
  205166. return 0;
  205167. }
  205168. MidiOutput::~MidiOutput()
  205169. {
  205170. MidiOutHandle* const h = (MidiOutHandle*) internal;
  205171. if (handles.contains ((void*) h) && --(h->refCount) == 0)
  205172. {
  205173. midiOutClose (h->handle);
  205174. handles.removeValue ((void*) h);
  205175. delete h;
  205176. }
  205177. }
  205178. void MidiOutput::reset()
  205179. {
  205180. const MidiOutHandle* const h = (MidiOutHandle*) internal;
  205181. midiOutReset (h->handle);
  205182. }
  205183. bool MidiOutput::getVolume (float& leftVol,
  205184. float& rightVol)
  205185. {
  205186. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  205187. DWORD n;
  205188. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  205189. {
  205190. const unsigned short* const nn = (const unsigned short*) &n;
  205191. rightVol = nn[0] / (float) 0xffff;
  205192. leftVol = nn[1] / (float) 0xffff;
  205193. return true;
  205194. }
  205195. else
  205196. {
  205197. rightVol = leftVol = 1.0f;
  205198. return false;
  205199. }
  205200. }
  205201. void MidiOutput::setVolume (float leftVol,
  205202. float rightVol)
  205203. {
  205204. const MidiOutHandle* const handle = (MidiOutHandle*) internal;
  205205. DWORD n;
  205206. unsigned short* const nn = (unsigned short*) &n;
  205207. nn[0] = (unsigned short) jlimit (0, 0xffff, (int)(rightVol * 0xffff));
  205208. nn[1] = (unsigned short) jlimit (0, 0xffff, (int)(leftVol * 0xffff));
  205209. midiOutSetVolume (handle->handle, n);
  205210. }
  205211. void MidiOutput::sendMessageNow (const MidiMessage& message)
  205212. {
  205213. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  205214. if (message.getRawDataSize() > 3
  205215. || message.isSysEx())
  205216. {
  205217. MIDIHDR h;
  205218. zerostruct (h);
  205219. h.lpData = (char*) message.getRawData();
  205220. h.dwBufferLength = message.getRawDataSize();
  205221. h.dwBytesRecorded = message.getRawDataSize();
  205222. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  205223. {
  205224. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  205225. if (res == MMSYSERR_NOERROR)
  205226. {
  205227. while ((h.dwFlags & MHDR_DONE) == 0)
  205228. Sleep (1);
  205229. int count = 500; // 1 sec timeout
  205230. while (--count >= 0)
  205231. {
  205232. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  205233. if (res == MIDIERR_STILLPLAYING)
  205234. Sleep (2);
  205235. else
  205236. break;
  205237. }
  205238. }
  205239. }
  205240. }
  205241. else
  205242. {
  205243. midiOutShortMsg (handle->handle,
  205244. *(unsigned int*) message.getRawData());
  205245. }
  205246. }
  205247. END_JUCE_NAMESPACE
  205248. /********* End of inlined file: juce_win32_Midi.cpp *********/
  205249. /********* Start of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  205250. #ifdef _MSC_VER
  205251. #pragma warning (disable: 4514)
  205252. #pragma warning (push)
  205253. #endif
  205254. #include <comutil.h>
  205255. #include <Exdisp.h>
  205256. #include <exdispid.h>
  205257. #ifdef _MSC_VER
  205258. #pragma warning (pop)
  205259. #pragma warning (disable: 4312 4244)
  205260. #endif
  205261. BEGIN_JUCE_NAMESPACE
  205262. class WebBrowserComponentInternal : public ActiveXControlComponent
  205263. {
  205264. public:
  205265. WebBrowserComponentInternal()
  205266. : browser (0),
  205267. connectionPoint (0),
  205268. adviseCookie (0)
  205269. {
  205270. }
  205271. ~WebBrowserComponentInternal()
  205272. {
  205273. if (connectionPoint != 0)
  205274. connectionPoint->Unadvise (adviseCookie);
  205275. if (browser != 0)
  205276. browser->Release();
  205277. }
  205278. void createBrowser()
  205279. {
  205280. createControl (&CLSID_WebBrowser);
  205281. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  205282. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  205283. if (connectionPointContainer != 0)
  205284. {
  205285. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  205286. &connectionPoint);
  205287. if (connectionPoint != 0)
  205288. {
  205289. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  205290. jassert (owner != 0);
  205291. EventHandler* handler = new EventHandler (owner);
  205292. connectionPoint->Advise (handler, &adviseCookie);
  205293. }
  205294. }
  205295. }
  205296. void goToURL (const String& url,
  205297. const StringArray* headers,
  205298. const MemoryBlock* postData)
  205299. {
  205300. if (browser != 0)
  205301. {
  205302. LPSAFEARRAY sa = 0;
  205303. _variant_t flags, frame, postDataVar, headersVar;
  205304. if (headers != 0)
  205305. headersVar = (const tchar*) headers->joinIntoString ("\r\n");
  205306. if (postData != 0 && postData->getSize() > 0)
  205307. {
  205308. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  205309. if (sa != 0)
  205310. {
  205311. void* data = 0;
  205312. SafeArrayAccessData (sa, &data);
  205313. jassert (data != 0);
  205314. if (data != 0)
  205315. {
  205316. postData->copyTo (data, 0, postData->getSize());
  205317. SafeArrayUnaccessData (sa);
  205318. VARIANT postDataVar2;
  205319. VariantInit (&postDataVar2);
  205320. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  205321. V_ARRAY (&postDataVar2) = sa;
  205322. postDataVar = postDataVar2;
  205323. }
  205324. }
  205325. }
  205326. browser->Navigate ((BSTR) (const OLECHAR*) url,
  205327. &flags, &frame,
  205328. &postDataVar, &headersVar);
  205329. if (sa != 0)
  205330. SafeArrayDestroy (sa);
  205331. }
  205332. }
  205333. IWebBrowser2* browser;
  205334. juce_UseDebuggingNewOperator
  205335. private:
  205336. IConnectionPoint* connectionPoint;
  205337. DWORD adviseCookie;
  205338. class EventHandler : public IDispatch
  205339. {
  205340. public:
  205341. EventHandler (WebBrowserComponent* owner_)
  205342. : owner (owner_),
  205343. refCount (0)
  205344. {
  205345. }
  205346. ~EventHandler()
  205347. {
  205348. }
  205349. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  205350. {
  205351. if (id == IID_IUnknown || id == IID_IDispatch || id == DIID_DWebBrowserEvents2)
  205352. {
  205353. AddRef();
  205354. *result = this;
  205355. return S_OK;
  205356. }
  205357. *result = 0;
  205358. return E_NOINTERFACE;
  205359. }
  205360. ULONG __stdcall AddRef() { return ++refCount; }
  205361. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  205362. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  205363. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  205364. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  205365. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  205366. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  205367. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  205368. UINT __RPC_FAR* /*puArgErr*/)
  205369. {
  205370. switch (dispIdMember)
  205371. {
  205372. case DISPID_BEFORENAVIGATE2:
  205373. {
  205374. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  205375. String url;
  205376. if ((vurl->vt & VT_BYREF) != 0)
  205377. url = *vurl->pbstrVal;
  205378. else
  205379. url = vurl->bstrVal;
  205380. *pDispParams->rgvarg->pboolVal
  205381. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  205382. : VARIANT_TRUE;
  205383. return S_OK;
  205384. }
  205385. default:
  205386. break;
  205387. }
  205388. return E_NOTIMPL;
  205389. }
  205390. juce_UseDebuggingNewOperator
  205391. private:
  205392. WebBrowserComponent* const owner;
  205393. int refCount;
  205394. EventHandler (const EventHandler&);
  205395. const EventHandler& operator= (const EventHandler&);
  205396. };
  205397. };
  205398. WebBrowserComponent::WebBrowserComponent()
  205399. : browser (0),
  205400. blankPageShown (false)
  205401. {
  205402. setOpaque (true);
  205403. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  205404. }
  205405. WebBrowserComponent::~WebBrowserComponent()
  205406. {
  205407. delete browser;
  205408. }
  205409. void WebBrowserComponent::goToURL (const String& url,
  205410. const StringArray* headers,
  205411. const MemoryBlock* postData)
  205412. {
  205413. lastURL = url;
  205414. lastHeaders.clear();
  205415. if (headers != 0)
  205416. lastHeaders = *headers;
  205417. lastPostData.setSize (0);
  205418. if (postData != 0)
  205419. lastPostData = *postData;
  205420. blankPageShown = false;
  205421. browser->goToURL (url, headers, postData);
  205422. }
  205423. void WebBrowserComponent::stop()
  205424. {
  205425. if (browser->browser != 0)
  205426. browser->browser->Stop();
  205427. }
  205428. void WebBrowserComponent::goBack()
  205429. {
  205430. lastURL = String::empty;
  205431. blankPageShown = false;
  205432. if (browser->browser != 0)
  205433. browser->browser->GoBack();
  205434. }
  205435. void WebBrowserComponent::goForward()
  205436. {
  205437. lastURL = String::empty;
  205438. if (browser->browser != 0)
  205439. browser->browser->GoForward();
  205440. }
  205441. void WebBrowserComponent::paint (Graphics& g)
  205442. {
  205443. if (browser->browser == 0)
  205444. g.fillAll (Colours::white);
  205445. }
  205446. void WebBrowserComponent::checkWindowAssociation()
  205447. {
  205448. if (isShowing())
  205449. {
  205450. if (browser->browser == 0 && getPeer() != 0)
  205451. {
  205452. browser->createBrowser();
  205453. reloadLastURL();
  205454. }
  205455. else
  205456. {
  205457. if (blankPageShown)
  205458. goBack();
  205459. }
  205460. }
  205461. else
  205462. {
  205463. if (browser != 0 && ! blankPageShown)
  205464. {
  205465. // when the component becomes invisible, some stuff like flash
  205466. // carries on playing audio, so we need to force it onto a blank
  205467. // page to avoid this..
  205468. blankPageShown = true;
  205469. browser->goToURL ("about:blank", 0, 0);
  205470. }
  205471. }
  205472. }
  205473. void WebBrowserComponent::reloadLastURL()
  205474. {
  205475. if (lastURL.isNotEmpty())
  205476. {
  205477. goToURL (lastURL, &lastHeaders, &lastPostData);
  205478. lastURL = String::empty;
  205479. }
  205480. }
  205481. void WebBrowserComponent::parentHierarchyChanged()
  205482. {
  205483. checkWindowAssociation();
  205484. }
  205485. void WebBrowserComponent::moved()
  205486. {
  205487. }
  205488. void WebBrowserComponent::resized()
  205489. {
  205490. browser->setSize (getWidth(), getHeight());
  205491. }
  205492. void WebBrowserComponent::visibilityChanged()
  205493. {
  205494. checkWindowAssociation();
  205495. }
  205496. bool WebBrowserComponent::pageAboutToLoad (const String&)
  205497. {
  205498. return true;
  205499. }
  205500. END_JUCE_NAMESPACE
  205501. /********* End of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  205502. /********* Start of inlined file: juce_win32_Windowing.cpp *********/
  205503. #ifdef _MSC_VER
  205504. #pragma warning (disable: 4514)
  205505. #pragma warning (push)
  205506. #endif
  205507. #include <float.h>
  205508. #include <windowsx.h>
  205509. #include <shlobj.h>
  205510. #if JUCE_OPENGL
  205511. #include <gl/gl.h>
  205512. #endif
  205513. #ifdef _MSC_VER
  205514. #pragma warning (pop)
  205515. #pragma warning (disable: 4312 4244)
  205516. #endif
  205517. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  205518. // these are in the windows SDK, but need to be repeated here for GCC..
  205519. #ifndef GET_APPCOMMAND_LPARAM
  205520. #define FAPPCOMMAND_MASK 0xF000
  205521. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  205522. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  205523. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  205524. #define APPCOMMAND_MEDIA_STOP 13
  205525. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  205526. #define WM_APPCOMMAND 0x0319
  205527. #endif
  205528. BEGIN_JUCE_NAMESPACE
  205529. extern void juce_repeatLastProcessPriority() throw(); // in juce_win32_Threads.cpp
  205530. extern void juce_CheckCurrentlyFocusedTopLevelWindow() throw(); // in juce_TopLevelWindow.cpp
  205531. extern bool juce_IsRunningInWine() throw();
  205532. #ifndef ULW_ALPHA
  205533. #define ULW_ALPHA 0x00000002
  205534. #endif
  205535. #ifndef AC_SRC_ALPHA
  205536. #define AC_SRC_ALPHA 0x01
  205537. #endif
  205538. #define DEBUG_REPAINT_TIMES 0
  205539. static HPALETTE palette = 0;
  205540. static bool createPaletteIfNeeded = true;
  205541. static bool shouldDeactivateTitleBar = true;
  205542. static bool screenSaverAllowed = true;
  205543. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  205544. #define WM_TRAYNOTIFY WM_USER + 100
  205545. using ::abs;
  205546. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  205547. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  205548. bool Desktop::canUseSemiTransparentWindows() throw()
  205549. {
  205550. if (updateLayeredWindow == 0)
  205551. {
  205552. if (! juce_IsRunningInWine())
  205553. {
  205554. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  205555. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  205556. }
  205557. }
  205558. return updateLayeredWindow != 0;
  205559. }
  205560. #undef DefWindowProc
  205561. #define DefWindowProc DefWindowProcW
  205562. const int extendedKeyModifier = 0x10000;
  205563. const int KeyPress::spaceKey = VK_SPACE;
  205564. const int KeyPress::returnKey = VK_RETURN;
  205565. const int KeyPress::escapeKey = VK_ESCAPE;
  205566. const int KeyPress::backspaceKey = VK_BACK;
  205567. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  205568. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  205569. const int KeyPress::tabKey = VK_TAB;
  205570. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  205571. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  205572. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  205573. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  205574. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  205575. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  205576. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  205577. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  205578. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  205579. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  205580. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  205581. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  205582. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  205583. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  205584. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  205585. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  205586. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  205587. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  205588. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  205589. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  205590. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  205591. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  205592. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  205593. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  205594. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  205595. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  205596. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  205597. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  205598. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  205599. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  205600. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  205601. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  205602. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  205603. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  205604. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  205605. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  205606. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  205607. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  205608. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  205609. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  205610. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  205611. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  205612. const int KeyPress::playKey = 0x30000;
  205613. const int KeyPress::stopKey = 0x30001;
  205614. const int KeyPress::fastForwardKey = 0x30002;
  205615. const int KeyPress::rewindKey = 0x30003;
  205616. class WindowsBitmapImage : public Image
  205617. {
  205618. public:
  205619. HBITMAP hBitmap;
  205620. BITMAPV4HEADER bitmapInfo;
  205621. HDC hdc;
  205622. unsigned char* bitmapData;
  205623. WindowsBitmapImage (const PixelFormat format_,
  205624. const int w, const int h, const bool clearImage)
  205625. : Image (format_, w, h)
  205626. {
  205627. jassert (format_ == RGB || format_ == ARGB);
  205628. pixelStride = (format_ == RGB) ? 3 : 4;
  205629. zerostruct (bitmapInfo);
  205630. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  205631. bitmapInfo.bV4Width = w;
  205632. bitmapInfo.bV4Height = h;
  205633. bitmapInfo.bV4Planes = 1;
  205634. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  205635. if (format_ == ARGB)
  205636. {
  205637. bitmapInfo.bV4AlphaMask = 0xff000000;
  205638. bitmapInfo.bV4RedMask = 0xff0000;
  205639. bitmapInfo.bV4GreenMask = 0xff00;
  205640. bitmapInfo.bV4BlueMask = 0xff;
  205641. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  205642. }
  205643. else
  205644. {
  205645. bitmapInfo.bV4V4Compression = BI_RGB;
  205646. }
  205647. lineStride = -((w * pixelStride + 3) & ~3);
  205648. HDC dc = GetDC (0);
  205649. hdc = CreateCompatibleDC (dc);
  205650. ReleaseDC (0, dc);
  205651. SetMapMode (hdc, MM_TEXT);
  205652. hBitmap = CreateDIBSection (hdc,
  205653. (BITMAPINFO*) &(bitmapInfo),
  205654. DIB_RGB_COLORS,
  205655. (void**) &bitmapData,
  205656. 0, 0);
  205657. SelectObject (hdc, hBitmap);
  205658. if (format_ == ARGB && clearImage)
  205659. zeromem (bitmapData, abs (h * lineStride));
  205660. imageData = bitmapData - (lineStride * (h - 1));
  205661. }
  205662. ~WindowsBitmapImage()
  205663. {
  205664. DeleteDC (hdc);
  205665. DeleteObject (hBitmap);
  205666. imageData = 0; // to stop the base class freeing this
  205667. }
  205668. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  205669. const int x, const int y,
  205670. const RectangleList& maskedRegion) throw()
  205671. {
  205672. static HDRAWDIB hdd = 0;
  205673. static bool needToCreateDrawDib = true;
  205674. if (needToCreateDrawDib)
  205675. {
  205676. needToCreateDrawDib = false;
  205677. HDC dc = GetDC (0);
  205678. const int n = GetDeviceCaps (dc, BITSPIXEL);
  205679. ReleaseDC (0, dc);
  205680. // only open if we're not palettised
  205681. if (n > 8)
  205682. hdd = DrawDibOpen();
  205683. }
  205684. if (createPaletteIfNeeded)
  205685. {
  205686. HDC dc = GetDC (0);
  205687. const int n = GetDeviceCaps (dc, BITSPIXEL);
  205688. ReleaseDC (0, dc);
  205689. if (n <= 8)
  205690. palette = CreateHalftonePalette (dc);
  205691. createPaletteIfNeeded = false;
  205692. }
  205693. if (palette != 0)
  205694. {
  205695. SelectPalette (dc, palette, FALSE);
  205696. RealizePalette (dc);
  205697. SetStretchBltMode (dc, HALFTONE);
  205698. }
  205699. SetMapMode (dc, MM_TEXT);
  205700. if (transparent)
  205701. {
  205702. POINT p, pos;
  205703. SIZE size;
  205704. RECT windowBounds;
  205705. GetWindowRect (hwnd, &windowBounds);
  205706. p.x = -x;
  205707. p.y = -y;
  205708. pos.x = windowBounds.left;
  205709. pos.y = windowBounds.top;
  205710. size.cx = windowBounds.right - windowBounds.left;
  205711. size.cy = windowBounds.bottom - windowBounds.top;
  205712. BLENDFUNCTION bf;
  205713. bf.AlphaFormat = AC_SRC_ALPHA;
  205714. bf.BlendFlags = 0;
  205715. bf.BlendOp = AC_SRC_OVER;
  205716. bf.SourceConstantAlpha = 0xff;
  205717. if (! maskedRegion.isEmpty())
  205718. {
  205719. for (RectangleList::Iterator i (maskedRegion); i.next();)
  205720. {
  205721. const Rectangle& r = *i.getRectangle();
  205722. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  205723. }
  205724. }
  205725. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  205726. }
  205727. else
  205728. {
  205729. int savedDC = 0;
  205730. if (! maskedRegion.isEmpty())
  205731. {
  205732. savedDC = SaveDC (dc);
  205733. for (RectangleList::Iterator i (maskedRegion); i.next();)
  205734. {
  205735. const Rectangle& r = *i.getRectangle();
  205736. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  205737. }
  205738. }
  205739. const int w = getWidth();
  205740. const int h = getHeight();
  205741. if (hdd == 0)
  205742. {
  205743. StretchDIBits (dc,
  205744. x, y, w, h,
  205745. 0, 0, w, h,
  205746. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  205747. DIB_RGB_COLORS, SRCCOPY);
  205748. }
  205749. else
  205750. {
  205751. DrawDibDraw (hdd, dc, x, y, -1, -1,
  205752. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  205753. 0, 0, w, h, 0);
  205754. }
  205755. if (! maskedRegion.isEmpty())
  205756. RestoreDC (dc, savedDC);
  205757. }
  205758. }
  205759. juce_UseDebuggingNewOperator
  205760. private:
  205761. WindowsBitmapImage (const WindowsBitmapImage&);
  205762. const WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  205763. };
  205764. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  205765. static int currentModifiers = 0;
  205766. static int modifiersAtLastCallback = 0;
  205767. static void updateKeyModifiers() throw()
  205768. {
  205769. currentModifiers &= ~(ModifierKeys::shiftModifier
  205770. | ModifierKeys::ctrlModifier
  205771. | ModifierKeys::altModifier);
  205772. if ((GetKeyState (VK_SHIFT) & 0x8000) != 0)
  205773. currentModifiers |= ModifierKeys::shiftModifier;
  205774. if ((GetKeyState (VK_CONTROL) & 0x8000) != 0)
  205775. currentModifiers |= ModifierKeys::ctrlModifier;
  205776. if ((GetKeyState (VK_MENU) & 0x8000) != 0)
  205777. currentModifiers |= ModifierKeys::altModifier;
  205778. if ((GetKeyState (VK_RMENU) & 0x8000) != 0)
  205779. currentModifiers &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  205780. }
  205781. void ModifierKeys::updateCurrentModifiers() throw()
  205782. {
  205783. currentModifierFlags = currentModifiers;
  205784. }
  205785. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  205786. {
  205787. SHORT k = (SHORT) keyCode;
  205788. if ((keyCode & extendedKeyModifier) == 0
  205789. && (k >= (SHORT) T('a') && k <= (SHORT) T('z')))
  205790. k += (SHORT) T('A') - (SHORT) T('a');
  205791. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  205792. (SHORT) '+', VK_OEM_PLUS,
  205793. (SHORT) '-', VK_OEM_MINUS,
  205794. (SHORT) '.', VK_OEM_PERIOD,
  205795. (SHORT) ';', VK_OEM_1,
  205796. (SHORT) ':', VK_OEM_1,
  205797. (SHORT) '/', VK_OEM_2,
  205798. (SHORT) '?', VK_OEM_2,
  205799. (SHORT) '[', VK_OEM_4,
  205800. (SHORT) ']', VK_OEM_6 };
  205801. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  205802. if (k == translatedValues [i])
  205803. k = translatedValues [i + 1];
  205804. return (GetKeyState (k) & 0x8000) != 0;
  205805. }
  205806. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  205807. {
  205808. updateKeyModifiers();
  205809. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  205810. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0)
  205811. currentModifiers |= ModifierKeys::leftButtonModifier;
  205812. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0)
  205813. currentModifiers |= ModifierKeys::rightButtonModifier;
  205814. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0)
  205815. currentModifiers |= ModifierKeys::middleButtonModifier;
  205816. return ModifierKeys (currentModifiers);
  205817. }
  205818. static int64 getMouseEventTime() throw()
  205819. {
  205820. static int64 eventTimeOffset = 0;
  205821. static DWORD lastMessageTime = 0;
  205822. const DWORD thisMessageTime = GetMessageTime();
  205823. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  205824. {
  205825. lastMessageTime = thisMessageTime;
  205826. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  205827. }
  205828. return eventTimeOffset + thisMessageTime;
  205829. }
  205830. class Win32ComponentPeer : public ComponentPeer
  205831. {
  205832. public:
  205833. Win32ComponentPeer (Component* const component,
  205834. const int windowStyleFlags)
  205835. : ComponentPeer (component, windowStyleFlags),
  205836. dontRepaint (false),
  205837. fullScreen (false),
  205838. isDragging (false),
  205839. isMouseOver (false),
  205840. hasCreatedCaret (false),
  205841. currentWindowIcon (0),
  205842. taskBarIcon (0),
  205843. dropTarget (0)
  205844. {
  205845. MessageManager::getInstance()
  205846. ->callFunctionOnMessageThread (&createWindowCallback, (void*) this);
  205847. setTitle (component->getName());
  205848. if ((windowStyleFlags & windowHasDropShadow) != 0
  205849. && Desktop::canUseSemiTransparentWindows())
  205850. {
  205851. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  205852. if (shadower != 0)
  205853. shadower->setOwner (component);
  205854. }
  205855. else
  205856. {
  205857. shadower = 0;
  205858. }
  205859. }
  205860. ~Win32ComponentPeer()
  205861. {
  205862. setTaskBarIcon (0);
  205863. deleteAndZero (shadower);
  205864. // do this before the next bit to avoid messages arriving for this window
  205865. // before it's destroyed
  205866. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  205867. MessageManager::getInstance()
  205868. ->callFunctionOnMessageThread (&destroyWindowCallback, (void*) hwnd);
  205869. if (currentWindowIcon != 0)
  205870. DestroyIcon (currentWindowIcon);
  205871. if (dropTarget != 0)
  205872. {
  205873. dropTarget->Release();
  205874. dropTarget = 0;
  205875. }
  205876. }
  205877. void* getNativeHandle() const
  205878. {
  205879. return (void*) hwnd;
  205880. }
  205881. void setVisible (bool shouldBeVisible)
  205882. {
  205883. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  205884. if (shouldBeVisible)
  205885. InvalidateRect (hwnd, 0, 0);
  205886. else
  205887. lastPaintTime = 0;
  205888. }
  205889. void setTitle (const String& title)
  205890. {
  205891. SetWindowText (hwnd, title);
  205892. }
  205893. void setPosition (int x, int y)
  205894. {
  205895. offsetWithinParent (x, y);
  205896. SetWindowPos (hwnd, 0,
  205897. x - windowBorder.getLeft(),
  205898. y - windowBorder.getTop(),
  205899. 0, 0,
  205900. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205901. }
  205902. void repaintNowIfTransparent()
  205903. {
  205904. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  205905. handlePaintMessage();
  205906. }
  205907. void updateBorderSize()
  205908. {
  205909. WINDOWINFO info;
  205910. info.cbSize = sizeof (info);
  205911. if (GetWindowInfo (hwnd, &info))
  205912. {
  205913. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  205914. info.rcClient.left - info.rcWindow.left,
  205915. info.rcWindow.bottom - info.rcClient.bottom,
  205916. info.rcWindow.right - info.rcClient.right);
  205917. }
  205918. }
  205919. void setSize (int w, int h)
  205920. {
  205921. SetWindowPos (hwnd, 0, 0, 0,
  205922. w + windowBorder.getLeftAndRight(),
  205923. h + windowBorder.getTopAndBottom(),
  205924. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205925. updateBorderSize();
  205926. repaintNowIfTransparent();
  205927. }
  205928. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  205929. {
  205930. fullScreen = isNowFullScreen;
  205931. offsetWithinParent (x, y);
  205932. SetWindowPos (hwnd, 0,
  205933. x - windowBorder.getLeft(),
  205934. y - windowBorder.getTop(),
  205935. w + windowBorder.getLeftAndRight(),
  205936. h + windowBorder.getTopAndBottom(),
  205937. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205938. updateBorderSize();
  205939. repaintNowIfTransparent();
  205940. }
  205941. void getBounds (int& x, int& y, int& w, int& h) const
  205942. {
  205943. RECT r;
  205944. GetWindowRect (hwnd, &r);
  205945. x = r.left;
  205946. y = r.top;
  205947. w = r.right - x;
  205948. h = r.bottom - y;
  205949. HWND parentH = GetParent (hwnd);
  205950. if (parentH != 0)
  205951. {
  205952. GetWindowRect (parentH, &r);
  205953. x -= r.left;
  205954. y -= r.top;
  205955. }
  205956. x += windowBorder.getLeft();
  205957. y += windowBorder.getTop();
  205958. w -= windowBorder.getLeftAndRight();
  205959. h -= windowBorder.getTopAndBottom();
  205960. }
  205961. int getScreenX() const
  205962. {
  205963. RECT r;
  205964. GetWindowRect (hwnd, &r);
  205965. return r.left + windowBorder.getLeft();
  205966. }
  205967. int getScreenY() const
  205968. {
  205969. RECT r;
  205970. GetWindowRect (hwnd, &r);
  205971. return r.top + windowBorder.getTop();
  205972. }
  205973. void relativePositionToGlobal (int& x, int& y)
  205974. {
  205975. RECT r;
  205976. GetWindowRect (hwnd, &r);
  205977. x += r.left + windowBorder.getLeft();
  205978. y += r.top + windowBorder.getTop();
  205979. }
  205980. void globalPositionToRelative (int& x, int& y)
  205981. {
  205982. RECT r;
  205983. GetWindowRect (hwnd, &r);
  205984. x -= r.left + windowBorder.getLeft();
  205985. y -= r.top + windowBorder.getTop();
  205986. }
  205987. void setMinimised (bool shouldBeMinimised)
  205988. {
  205989. if (shouldBeMinimised != isMinimised())
  205990. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  205991. }
  205992. bool isMinimised() const
  205993. {
  205994. WINDOWPLACEMENT wp;
  205995. wp.length = sizeof (WINDOWPLACEMENT);
  205996. GetWindowPlacement (hwnd, &wp);
  205997. return wp.showCmd == SW_SHOWMINIMIZED;
  205998. }
  205999. void setFullScreen (bool shouldBeFullScreen)
  206000. {
  206001. setMinimised (false);
  206002. if (fullScreen != shouldBeFullScreen)
  206003. {
  206004. fullScreen = shouldBeFullScreen;
  206005. const ComponentDeletionWatcher deletionChecker (component);
  206006. if (! fullScreen)
  206007. {
  206008. const Rectangle boundsCopy (lastNonFullscreenBounds);
  206009. if (hasTitleBar())
  206010. ShowWindow (hwnd, SW_SHOWNORMAL);
  206011. if (! boundsCopy.isEmpty())
  206012. {
  206013. setBounds (boundsCopy.getX(),
  206014. boundsCopy.getY(),
  206015. boundsCopy.getWidth(),
  206016. boundsCopy.getHeight(),
  206017. false);
  206018. }
  206019. }
  206020. else
  206021. {
  206022. if (hasTitleBar())
  206023. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  206024. else
  206025. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  206026. }
  206027. if (! deletionChecker.hasBeenDeleted())
  206028. handleMovedOrResized();
  206029. }
  206030. }
  206031. bool isFullScreen() const
  206032. {
  206033. if (! hasTitleBar())
  206034. return fullScreen;
  206035. WINDOWPLACEMENT wp;
  206036. wp.length = sizeof (wp);
  206037. GetWindowPlacement (hwnd, &wp);
  206038. return wp.showCmd == SW_SHOWMAXIMIZED;
  206039. }
  206040. bool contains (int x, int y, bool trueIfInAChildWindow) const
  206041. {
  206042. RECT r;
  206043. GetWindowRect (hwnd, &r);
  206044. POINT p;
  206045. p.x = x + r.left + windowBorder.getLeft();
  206046. p.y = y + r.top + windowBorder.getTop();
  206047. HWND w = WindowFromPoint (p);
  206048. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  206049. }
  206050. const BorderSize getFrameSize() const
  206051. {
  206052. return windowBorder;
  206053. }
  206054. bool setAlwaysOnTop (bool alwaysOnTop)
  206055. {
  206056. const bool oldDeactivate = shouldDeactivateTitleBar;
  206057. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206058. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  206059. 0, 0, 0, 0,
  206060. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206061. shouldDeactivateTitleBar = oldDeactivate;
  206062. if (shadower != 0)
  206063. shadower->componentBroughtToFront (*component);
  206064. return true;
  206065. }
  206066. void toFront (bool makeActive)
  206067. {
  206068. setMinimised (false);
  206069. const bool oldDeactivate = shouldDeactivateTitleBar;
  206070. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206071. MessageManager::getInstance()
  206072. ->callFunctionOnMessageThread (makeActive ? &toFrontCallback1
  206073. : &toFrontCallback2,
  206074. (void*) hwnd);
  206075. shouldDeactivateTitleBar = oldDeactivate;
  206076. if (! makeActive)
  206077. {
  206078. // in this case a broughttofront call won't have occured, so do it now..
  206079. handleBroughtToFront();
  206080. }
  206081. }
  206082. void toBehind (ComponentPeer* other)
  206083. {
  206084. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  206085. jassert (otherPeer != 0); // wrong type of window?
  206086. if (otherPeer != 0)
  206087. {
  206088. setMinimised (false);
  206089. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  206090. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206091. }
  206092. }
  206093. bool isFocused() const
  206094. {
  206095. return MessageManager::getInstance()
  206096. ->callFunctionOnMessageThread (&getFocusCallback, 0) == (void*) hwnd;
  206097. }
  206098. void grabFocus()
  206099. {
  206100. const bool oldDeactivate = shouldDeactivateTitleBar;
  206101. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206102. MessageManager::getInstance()
  206103. ->callFunctionOnMessageThread (&setFocusCallback, (void*) hwnd);
  206104. shouldDeactivateTitleBar = oldDeactivate;
  206105. }
  206106. void textInputRequired (int /*x*/, int /*y*/)
  206107. {
  206108. if (! hasCreatedCaret)
  206109. {
  206110. hasCreatedCaret = true;
  206111. CreateCaret (hwnd, 0, 0, 0);
  206112. }
  206113. ShowCaret (hwnd);
  206114. SetCaretPos (-1, -1);
  206115. }
  206116. void repaint (int x, int y, int w, int h)
  206117. {
  206118. const RECT r = { x, y, x + w, y + h };
  206119. InvalidateRect (hwnd, &r, FALSE);
  206120. }
  206121. void performAnyPendingRepaintsNow()
  206122. {
  206123. MSG m;
  206124. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  206125. DispatchMessage (&m);
  206126. }
  206127. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  206128. {
  206129. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  206130. return (Win32ComponentPeer*) GetWindowLongPtr (h, 8);
  206131. return 0;
  206132. }
  206133. void setTaskBarIcon (const Image* const image)
  206134. {
  206135. if (image != 0)
  206136. {
  206137. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  206138. if (taskBarIcon == 0)
  206139. {
  206140. taskBarIcon = new NOTIFYICONDATA();
  206141. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  206142. taskBarIcon->hWnd = (HWND) hwnd;
  206143. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  206144. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  206145. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  206146. taskBarIcon->hIcon = hicon;
  206147. taskBarIcon->szTip[0] = 0;
  206148. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  206149. }
  206150. else
  206151. {
  206152. HICON oldIcon = taskBarIcon->hIcon;
  206153. taskBarIcon->hIcon = hicon;
  206154. taskBarIcon->uFlags = NIF_ICON;
  206155. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206156. DestroyIcon (oldIcon);
  206157. }
  206158. DestroyIcon (hicon);
  206159. }
  206160. else if (taskBarIcon != 0)
  206161. {
  206162. taskBarIcon->uFlags = 0;
  206163. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  206164. DestroyIcon (taskBarIcon->hIcon);
  206165. deleteAndZero (taskBarIcon);
  206166. }
  206167. }
  206168. void setTaskBarIconToolTip (const String& toolTip) const
  206169. {
  206170. if (taskBarIcon != 0)
  206171. {
  206172. taskBarIcon->uFlags = NIF_TIP;
  206173. toolTip.copyToBuffer (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  206174. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206175. }
  206176. }
  206177. juce_UseDebuggingNewOperator
  206178. bool dontRepaint;
  206179. private:
  206180. HWND hwnd;
  206181. DropShadower* shadower;
  206182. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  206183. BorderSize windowBorder;
  206184. HICON currentWindowIcon;
  206185. NOTIFYICONDATA* taskBarIcon;
  206186. IDropTarget* dropTarget;
  206187. class TemporaryImage : public Timer
  206188. {
  206189. public:
  206190. TemporaryImage()
  206191. : image (0)
  206192. {
  206193. }
  206194. ~TemporaryImage()
  206195. {
  206196. delete image;
  206197. }
  206198. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  206199. {
  206200. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  206201. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  206202. {
  206203. delete image;
  206204. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  206205. }
  206206. startTimer (3000);
  206207. return image;
  206208. }
  206209. void timerCallback()
  206210. {
  206211. stopTimer();
  206212. deleteAndZero (image);
  206213. }
  206214. private:
  206215. WindowsBitmapImage* image;
  206216. TemporaryImage (const TemporaryImage&);
  206217. const TemporaryImage& operator= (const TemporaryImage&);
  206218. };
  206219. TemporaryImage offscreenImageGenerator;
  206220. class WindowClassHolder : public DeletedAtShutdown
  206221. {
  206222. public:
  206223. WindowClassHolder()
  206224. : windowClassName ("JUCE_")
  206225. {
  206226. // this name has to be different for each app/dll instance because otherwise
  206227. // poor old Win32 can get a bit confused (even despite it not being a process-global
  206228. // window class).
  206229. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  206230. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  206231. TCHAR moduleFile [1024];
  206232. moduleFile[0] = 0;
  206233. GetModuleFileName (moduleHandle, moduleFile, 1024);
  206234. WORD iconNum = 0;
  206235. WNDCLASSEX wcex;
  206236. wcex.cbSize = sizeof (wcex);
  206237. wcex.style = CS_OWNDC;
  206238. wcex.lpfnWndProc = (WNDPROC) windowProc;
  206239. wcex.lpszClassName = windowClassName;
  206240. wcex.cbClsExtra = 0;
  206241. wcex.cbWndExtra = 32;
  206242. wcex.hInstance = moduleHandle;
  206243. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  206244. iconNum = 1;
  206245. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  206246. wcex.hCursor = 0;
  206247. wcex.hbrBackground = 0;
  206248. wcex.lpszMenuName = 0;
  206249. RegisterClassEx (&wcex);
  206250. }
  206251. ~WindowClassHolder()
  206252. {
  206253. if (ComponentPeer::getNumPeers() == 0)
  206254. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  206255. clearSingletonInstance();
  206256. }
  206257. String windowClassName;
  206258. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  206259. };
  206260. static void* createWindowCallback (void* userData)
  206261. {
  206262. ((Win32ComponentPeer*) userData)->createWindow();
  206263. return 0;
  206264. }
  206265. void createWindow()
  206266. {
  206267. DWORD exstyle = WS_EX_ACCEPTFILES;
  206268. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  206269. if (hasTitleBar())
  206270. {
  206271. type |= WS_OVERLAPPED;
  206272. exstyle |= WS_EX_APPWINDOW;
  206273. if ((styleFlags & windowHasCloseButton) != 0)
  206274. {
  206275. type |= WS_SYSMENU;
  206276. }
  206277. else
  206278. {
  206279. // annoyingly, windows won't let you have a min/max button without a close button
  206280. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  206281. }
  206282. if ((styleFlags & windowIsResizable) != 0)
  206283. type |= WS_THICKFRAME;
  206284. }
  206285. else
  206286. {
  206287. type |= WS_POPUP | WS_SYSMENU;
  206288. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  206289. exstyle |= WS_EX_TOOLWINDOW;
  206290. else
  206291. exstyle |= WS_EX_APPWINDOW;
  206292. }
  206293. if ((styleFlags & windowHasMinimiseButton) != 0)
  206294. type |= WS_MINIMIZEBOX;
  206295. if ((styleFlags & windowHasMaximiseButton) != 0)
  206296. type |= WS_MAXIMIZEBOX;
  206297. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  206298. exstyle |= WS_EX_TRANSPARENT;
  206299. if ((styleFlags & windowIsSemiTransparent) != 0
  206300. && Desktop::canUseSemiTransparentWindows())
  206301. exstyle |= WS_EX_LAYERED;
  206302. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  206303. if (hwnd != 0)
  206304. {
  206305. SetWindowLongPtr (hwnd, 0, 0);
  206306. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  206307. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  206308. if (dropTarget == 0)
  206309. dropTarget = new JuceDropTarget (this);
  206310. RegisterDragDrop (hwnd, dropTarget);
  206311. updateBorderSize();
  206312. // Calling this function here is (for some reason) necessary to make Windows
  206313. // correctly enable the menu items that we specify in the wm_initmenu message.
  206314. GetSystemMenu (hwnd, false);
  206315. }
  206316. else
  206317. {
  206318. jassertfalse
  206319. }
  206320. }
  206321. static void* destroyWindowCallback (void* handle)
  206322. {
  206323. RevokeDragDrop ((HWND) handle);
  206324. DestroyWindow ((HWND) handle);
  206325. return 0;
  206326. }
  206327. static void* toFrontCallback1 (void* h)
  206328. {
  206329. SetForegroundWindow ((HWND) h);
  206330. return 0;
  206331. }
  206332. static void* toFrontCallback2 (void* h)
  206333. {
  206334. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206335. return 0;
  206336. }
  206337. static void* setFocusCallback (void* h)
  206338. {
  206339. SetFocus ((HWND) h);
  206340. return 0;
  206341. }
  206342. static void* getFocusCallback (void*)
  206343. {
  206344. return (void*) GetFocus();
  206345. }
  206346. void offsetWithinParent (int& x, int& y) const
  206347. {
  206348. if (isTransparent())
  206349. {
  206350. HWND parentHwnd = GetParent (hwnd);
  206351. if (parentHwnd != 0)
  206352. {
  206353. RECT parentRect;
  206354. GetWindowRect (parentHwnd, &parentRect);
  206355. x += parentRect.left;
  206356. y += parentRect.top;
  206357. }
  206358. }
  206359. }
  206360. bool isTransparent() const
  206361. {
  206362. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  206363. }
  206364. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  206365. void setIcon (const Image& newIcon)
  206366. {
  206367. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  206368. if (hicon != 0)
  206369. {
  206370. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  206371. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  206372. if (currentWindowIcon != 0)
  206373. DestroyIcon (currentWindowIcon);
  206374. currentWindowIcon = hicon;
  206375. }
  206376. }
  206377. void handlePaintMessage()
  206378. {
  206379. #if DEBUG_REPAINT_TIMES
  206380. const double paintStart = Time::getMillisecondCounterHiRes();
  206381. #endif
  206382. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  206383. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  206384. PAINTSTRUCT paintStruct;
  206385. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  206386. // message and become re-entrant, but that's OK
  206387. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  206388. // corrupt the image it's using to paint into, so do a check here.
  206389. static bool reentrant = false;
  206390. if (reentrant)
  206391. {
  206392. DeleteObject (rgn);
  206393. EndPaint (hwnd, &paintStruct);
  206394. return;
  206395. }
  206396. reentrant = true;
  206397. // this is the rectangle to update..
  206398. int x = paintStruct.rcPaint.left;
  206399. int y = paintStruct.rcPaint.top;
  206400. int w = paintStruct.rcPaint.right - x;
  206401. int h = paintStruct.rcPaint.bottom - y;
  206402. const bool transparent = isTransparent();
  206403. if (transparent)
  206404. {
  206405. // it's not possible to have a transparent window with a title bar at the moment!
  206406. jassert (! hasTitleBar());
  206407. RECT r;
  206408. GetWindowRect (hwnd, &r);
  206409. x = y = 0;
  206410. w = r.right - r.left;
  206411. h = r.bottom - r.top;
  206412. }
  206413. if (w > 0 && h > 0)
  206414. {
  206415. clearMaskedRegion();
  206416. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  206417. LowLevelGraphicsSoftwareRenderer context (*offscreenImage);
  206418. RectangleList* const contextClip = context.getRawClipRegion();
  206419. contextClip->clear();
  206420. context.setOrigin (-x, -y);
  206421. bool needToPaintAll = true;
  206422. if (regionType == COMPLEXREGION && ! transparent)
  206423. {
  206424. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  206425. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  206426. DeleteObject (clipRgn);
  206427. char rgnData [8192];
  206428. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  206429. if (res > 0 && res <= sizeof (rgnData))
  206430. {
  206431. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  206432. if (hdr->iType == RDH_RECTANGLES
  206433. && hdr->rcBound.right - hdr->rcBound.left >= w
  206434. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  206435. {
  206436. needToPaintAll = false;
  206437. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  206438. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  206439. while (--num >= 0)
  206440. {
  206441. // (need to move this one pixel to the left because of a win32 bug)
  206442. const int cx = jmax (x, rects->left - 1);
  206443. const int cy = rects->top;
  206444. const int cw = rects->right - cx;
  206445. const int ch = rects->bottom - rects->top;
  206446. if (cx + cw - x <= w && cy + ch - y <= h)
  206447. {
  206448. contextClip->addWithoutMerging (Rectangle (cx - x, cy - y, cw, ch));
  206449. }
  206450. else
  206451. {
  206452. needToPaintAll = true;
  206453. break;
  206454. }
  206455. ++rects;
  206456. }
  206457. }
  206458. }
  206459. }
  206460. if (needToPaintAll)
  206461. {
  206462. contextClip->clear();
  206463. contextClip->addWithoutMerging (Rectangle (0, 0, w, h));
  206464. }
  206465. if (transparent)
  206466. {
  206467. RectangleList::Iterator i (*contextClip);
  206468. while (i.next())
  206469. {
  206470. const Rectangle& r = *i.getRectangle();
  206471. offscreenImage->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  206472. }
  206473. }
  206474. // if the component's not opaque, this won't draw properly unless the platform can support this
  206475. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  206476. updateCurrentModifiers();
  206477. handlePaint (context);
  206478. if (! dontRepaint)
  206479. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  206480. }
  206481. DeleteObject (rgn);
  206482. EndPaint (hwnd, &paintStruct);
  206483. reentrant = false;
  206484. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  206485. _fpreset(); // because some graphics cards can unmask FP exceptions
  206486. #endif
  206487. lastPaintTime = Time::getMillisecondCounter();
  206488. #if DEBUG_REPAINT_TIMES
  206489. const double elapsed = Time::getMillisecondCounterHiRes() - paintStart;
  206490. Logger::outputDebugString (T("repaint time: ") + String (elapsed, 2));
  206491. #endif
  206492. }
  206493. void doMouseMove (const int x, const int y)
  206494. {
  206495. static uint32 lastMouseTime = 0;
  206496. // this can be set to throttle the mouse-messages to less than a
  206497. // certain number per second, as things can get unresponsive
  206498. // if each drag or move callback has to do a lot of work.
  206499. const int maxMouseMovesPerSecond = 60;
  206500. const int64 mouseEventTime = getMouseEventTime();
  206501. if (! isMouseOver)
  206502. {
  206503. isMouseOver = true;
  206504. TRACKMOUSEEVENT tme;
  206505. tme.cbSize = sizeof (tme);
  206506. tme.dwFlags = TME_LEAVE;
  206507. tme.hwndTrack = hwnd;
  206508. tme.dwHoverTime = 0;
  206509. if (! TrackMouseEvent (&tme))
  206510. {
  206511. jassertfalse;
  206512. }
  206513. updateKeyModifiers();
  206514. handleMouseEnter (x, y, mouseEventTime);
  206515. }
  206516. else if (! isDragging)
  206517. {
  206518. if (((unsigned int) x) < (unsigned int) component->getWidth()
  206519. && ((unsigned int) y) < (unsigned int) component->getHeight())
  206520. {
  206521. RECT r;
  206522. GetWindowRect (hwnd, &r);
  206523. POINT p;
  206524. p.x = x + r.left + windowBorder.getLeft();
  206525. p.y = y + r.top + windowBorder.getTop();
  206526. if (WindowFromPoint (p) == hwnd)
  206527. {
  206528. const uint32 now = Time::getMillisecondCounter();
  206529. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  206530. {
  206531. lastMouseTime = now;
  206532. handleMouseMove (x, y, mouseEventTime);
  206533. }
  206534. }
  206535. }
  206536. }
  206537. else
  206538. {
  206539. const uint32 now = Time::getMillisecondCounter();
  206540. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  206541. {
  206542. lastMouseTime = now;
  206543. handleMouseDrag (x, y, mouseEventTime);
  206544. }
  206545. }
  206546. }
  206547. void doMouseDown (const int x, const int y, const WPARAM wParam)
  206548. {
  206549. if (GetCapture() != hwnd)
  206550. SetCapture (hwnd);
  206551. doMouseMove (x, y);
  206552. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  206553. if ((wParam & MK_LBUTTON) != 0)
  206554. currentModifiers |= ModifierKeys::leftButtonModifier;
  206555. if ((wParam & MK_RBUTTON) != 0)
  206556. currentModifiers |= ModifierKeys::rightButtonModifier;
  206557. if ((wParam & MK_MBUTTON) != 0)
  206558. currentModifiers |= ModifierKeys::middleButtonModifier;
  206559. updateKeyModifiers();
  206560. isDragging = true;
  206561. handleMouseDown (x, y, getMouseEventTime());
  206562. }
  206563. void doMouseUp (const int x, const int y, const WPARAM wParam)
  206564. {
  206565. int numButtons = 0;
  206566. if ((wParam & MK_LBUTTON) != 0)
  206567. ++numButtons;
  206568. if ((wParam & MK_RBUTTON) != 0)
  206569. ++numButtons;
  206570. if ((wParam & MK_MBUTTON) != 0)
  206571. ++numButtons;
  206572. const int oldModifiers = currentModifiers;
  206573. // update the currentmodifiers only after the callback, so the callback
  206574. // knows which button was released.
  206575. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  206576. if ((wParam & MK_LBUTTON) != 0)
  206577. currentModifiers |= ModifierKeys::leftButtonModifier;
  206578. if ((wParam & MK_RBUTTON) != 0)
  206579. currentModifiers |= ModifierKeys::rightButtonModifier;
  206580. if ((wParam & MK_MBUTTON) != 0)
  206581. currentModifiers |= ModifierKeys::middleButtonModifier;
  206582. updateKeyModifiers();
  206583. isDragging = false;
  206584. // release the mouse capture if the user's not still got a button down
  206585. if (numButtons == 0 && hwnd == GetCapture())
  206586. ReleaseCapture();
  206587. handleMouseUp (oldModifiers, x, y, getMouseEventTime());
  206588. }
  206589. void doCaptureChanged()
  206590. {
  206591. if (isDragging)
  206592. {
  206593. RECT wr;
  206594. GetWindowRect (hwnd, &wr);
  206595. const DWORD mp = GetMessagePos();
  206596. doMouseUp (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  206597. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  206598. getMouseEventTime());
  206599. }
  206600. }
  206601. void doMouseExit()
  206602. {
  206603. if (isMouseOver)
  206604. {
  206605. isMouseOver = false;
  206606. RECT wr;
  206607. GetWindowRect (hwnd, &wr);
  206608. const DWORD mp = GetMessagePos();
  206609. handleMouseExit (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  206610. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  206611. getMouseEventTime());
  206612. }
  206613. }
  206614. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  206615. {
  206616. updateKeyModifiers();
  206617. const int amount = jlimit (-1000, 1000, (int) (0.75f * (short) HIWORD (wParam)));
  206618. handleMouseWheel (isVertical ? 0 : amount,
  206619. isVertical ? amount : 0,
  206620. getMouseEventTime());
  206621. }
  206622. void sendModifierKeyChangeIfNeeded()
  206623. {
  206624. if (modifiersAtLastCallback != currentModifiers)
  206625. {
  206626. modifiersAtLastCallback = currentModifiers;
  206627. handleModifierKeysChange();
  206628. }
  206629. }
  206630. bool doKeyUp (const WPARAM key)
  206631. {
  206632. updateKeyModifiers();
  206633. switch (key)
  206634. {
  206635. case VK_SHIFT:
  206636. case VK_CONTROL:
  206637. case VK_MENU:
  206638. case VK_CAPITAL:
  206639. case VK_LWIN:
  206640. case VK_RWIN:
  206641. case VK_APPS:
  206642. case VK_NUMLOCK:
  206643. case VK_SCROLL:
  206644. case VK_LSHIFT:
  206645. case VK_RSHIFT:
  206646. case VK_LCONTROL:
  206647. case VK_LMENU:
  206648. case VK_RCONTROL:
  206649. case VK_RMENU:
  206650. sendModifierKeyChangeIfNeeded();
  206651. }
  206652. return handleKeyUpOrDown();
  206653. }
  206654. bool doKeyDown (const WPARAM key)
  206655. {
  206656. updateKeyModifiers();
  206657. bool used = false;
  206658. switch (key)
  206659. {
  206660. case VK_SHIFT:
  206661. case VK_LSHIFT:
  206662. case VK_RSHIFT:
  206663. case VK_CONTROL:
  206664. case VK_LCONTROL:
  206665. case VK_RCONTROL:
  206666. case VK_MENU:
  206667. case VK_LMENU:
  206668. case VK_RMENU:
  206669. case VK_LWIN:
  206670. case VK_RWIN:
  206671. case VK_CAPITAL:
  206672. case VK_NUMLOCK:
  206673. case VK_SCROLL:
  206674. case VK_APPS:
  206675. sendModifierKeyChangeIfNeeded();
  206676. break;
  206677. case VK_LEFT:
  206678. case VK_RIGHT:
  206679. case VK_UP:
  206680. case VK_DOWN:
  206681. case VK_PRIOR:
  206682. case VK_NEXT:
  206683. case VK_HOME:
  206684. case VK_END:
  206685. case VK_DELETE:
  206686. case VK_INSERT:
  206687. case VK_F1:
  206688. case VK_F2:
  206689. case VK_F3:
  206690. case VK_F4:
  206691. case VK_F5:
  206692. case VK_F6:
  206693. case VK_F7:
  206694. case VK_F8:
  206695. case VK_F9:
  206696. case VK_F10:
  206697. case VK_F11:
  206698. case VK_F12:
  206699. case VK_F13:
  206700. case VK_F14:
  206701. case VK_F15:
  206702. case VK_F16:
  206703. used = handleKeyUpOrDown();
  206704. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  206705. break;
  206706. case VK_ADD:
  206707. case VK_SUBTRACT:
  206708. case VK_MULTIPLY:
  206709. case VK_DIVIDE:
  206710. case VK_SEPARATOR:
  206711. case VK_DECIMAL:
  206712. used = handleKeyUpOrDown();
  206713. break;
  206714. default:
  206715. used = handleKeyUpOrDown();
  206716. {
  206717. MSG msg;
  206718. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  206719. {
  206720. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  206721. // manually generate the key-press event that matches this key-down.
  206722. const UINT keyChar = MapVirtualKey (key, 2);
  206723. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  206724. }
  206725. }
  206726. break;
  206727. }
  206728. return used;
  206729. }
  206730. bool doKeyChar (int key, const LPARAM flags)
  206731. {
  206732. updateKeyModifiers();
  206733. juce_wchar textChar = (juce_wchar) key;
  206734. const int virtualScanCode = (flags >> 16) & 0xff;
  206735. if (key >= '0' && key <= '9')
  206736. {
  206737. switch (virtualScanCode) // check for a numeric keypad scan-code
  206738. {
  206739. case 0x52:
  206740. case 0x4f:
  206741. case 0x50:
  206742. case 0x51:
  206743. case 0x4b:
  206744. case 0x4c:
  206745. case 0x4d:
  206746. case 0x47:
  206747. case 0x48:
  206748. case 0x49:
  206749. key = (key - '0') + KeyPress::numberPad0;
  206750. break;
  206751. default:
  206752. break;
  206753. }
  206754. }
  206755. else
  206756. {
  206757. // convert the scan code to an unmodified character code..
  206758. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  206759. UINT keyChar = MapVirtualKey (virtualKey, 2);
  206760. keyChar = LOWORD (keyChar);
  206761. if (keyChar != 0)
  206762. key = (int) keyChar;
  206763. // avoid sending junk text characters for some control-key combinations
  206764. if (textChar < ' ' && (currentModifiers & (ModifierKeys::ctrlModifier | ModifierKeys::altModifier)) != 0)
  206765. textChar = 0;
  206766. }
  206767. return handleKeyPress (key, textChar);
  206768. }
  206769. bool doAppCommand (const LPARAM lParam)
  206770. {
  206771. int key = 0;
  206772. switch (GET_APPCOMMAND_LPARAM (lParam))
  206773. {
  206774. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  206775. key = KeyPress::playKey;
  206776. break;
  206777. case APPCOMMAND_MEDIA_STOP:
  206778. key = KeyPress::stopKey;
  206779. break;
  206780. case APPCOMMAND_MEDIA_NEXTTRACK:
  206781. key = KeyPress::fastForwardKey;
  206782. break;
  206783. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  206784. key = KeyPress::rewindKey;
  206785. break;
  206786. }
  206787. if (key != 0)
  206788. {
  206789. updateKeyModifiers();
  206790. if (hwnd == GetActiveWindow())
  206791. {
  206792. handleKeyPress (key, 0);
  206793. return true;
  206794. }
  206795. }
  206796. return false;
  206797. }
  206798. class JuceDropTarget : public IDropTarget
  206799. {
  206800. public:
  206801. JuceDropTarget (Win32ComponentPeer* const owner_)
  206802. : owner (owner_),
  206803. refCount (1)
  206804. {
  206805. }
  206806. virtual ~JuceDropTarget()
  206807. {
  206808. jassert (refCount == 0);
  206809. }
  206810. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  206811. {
  206812. if (id == IID_IUnknown || id == IID_IDropTarget)
  206813. {
  206814. AddRef();
  206815. *result = this;
  206816. return S_OK;
  206817. }
  206818. *result = 0;
  206819. return E_NOINTERFACE;
  206820. }
  206821. ULONG __stdcall AddRef() { return ++refCount; }
  206822. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  206823. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206824. {
  206825. updateFileList (pDataObject);
  206826. int x = mousePos.x, y = mousePos.y;
  206827. owner->globalPositionToRelative (x, y);
  206828. owner->handleFileDragMove (files, x, y);
  206829. *pdwEffect = DROPEFFECT_COPY;
  206830. return S_OK;
  206831. }
  206832. HRESULT __stdcall DragLeave()
  206833. {
  206834. owner->handleFileDragExit (files);
  206835. return S_OK;
  206836. }
  206837. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206838. {
  206839. int x = mousePos.x, y = mousePos.y;
  206840. owner->globalPositionToRelative (x, y);
  206841. owner->handleFileDragMove (files, x, y);
  206842. *pdwEffect = DROPEFFECT_COPY;
  206843. return S_OK;
  206844. }
  206845. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206846. {
  206847. updateFileList (pDataObject);
  206848. int x = mousePos.x, y = mousePos.y;
  206849. owner->globalPositionToRelative (x, y);
  206850. owner->handleFileDragDrop (files, x, y);
  206851. *pdwEffect = DROPEFFECT_COPY;
  206852. return S_OK;
  206853. }
  206854. private:
  206855. Win32ComponentPeer* const owner;
  206856. int refCount;
  206857. StringArray files;
  206858. void updateFileList (IDataObject* const pDataObject)
  206859. {
  206860. files.clear();
  206861. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206862. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206863. if (pDataObject->GetData (&format, &medium) == S_OK)
  206864. {
  206865. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  206866. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  206867. unsigned int i = 0;
  206868. if (pDropFiles->fWide)
  206869. {
  206870. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  206871. for (;;)
  206872. {
  206873. unsigned int len = 0;
  206874. while (i + len < totalLen && fname [i + len] != 0)
  206875. ++len;
  206876. if (len == 0)
  206877. break;
  206878. files.add (String (fname + i, len));
  206879. i += len + 1;
  206880. }
  206881. }
  206882. else
  206883. {
  206884. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  206885. for (;;)
  206886. {
  206887. unsigned int len = 0;
  206888. while (i + len < totalLen && fname [i + len] != 0)
  206889. ++len;
  206890. if (len == 0)
  206891. break;
  206892. files.add (String (fname + i, len));
  206893. i += len + 1;
  206894. }
  206895. }
  206896. GlobalUnlock (medium.hGlobal);
  206897. }
  206898. }
  206899. JuceDropTarget (const JuceDropTarget&);
  206900. const JuceDropTarget& operator= (const JuceDropTarget&);
  206901. };
  206902. void doSettingChange()
  206903. {
  206904. Desktop::getInstance().refreshMonitorSizes();
  206905. if (fullScreen && ! isMinimised())
  206906. {
  206907. const Rectangle r (component->getParentMonitorArea());
  206908. SetWindowPos (hwnd, 0,
  206909. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  206910. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  206911. }
  206912. }
  206913. public:
  206914. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  206915. {
  206916. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  206917. if (peer != 0)
  206918. return peer->peerWindowProc (h, message, wParam, lParam);
  206919. return DefWindowProc (h, message, wParam, lParam);
  206920. }
  206921. private:
  206922. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  206923. {
  206924. {
  206925. const MessageManagerLock messLock;
  206926. if (isValidPeer (this))
  206927. {
  206928. switch (message)
  206929. {
  206930. case WM_NCHITTEST:
  206931. if (hasTitleBar())
  206932. break;
  206933. return HTCLIENT;
  206934. case WM_PAINT:
  206935. handlePaintMessage();
  206936. return 0;
  206937. case WM_NCPAINT:
  206938. if (wParam != 1)
  206939. handlePaintMessage();
  206940. if (hasTitleBar())
  206941. break;
  206942. return 0;
  206943. case WM_ERASEBKGND:
  206944. case WM_NCCALCSIZE:
  206945. if (hasTitleBar())
  206946. break;
  206947. return 1;
  206948. case WM_MOUSEMOVE:
  206949. doMouseMove (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  206950. return 0;
  206951. case WM_MOUSELEAVE:
  206952. doMouseExit();
  206953. return 0;
  206954. case WM_LBUTTONDOWN:
  206955. case WM_MBUTTONDOWN:
  206956. case WM_RBUTTONDOWN:
  206957. doMouseDown (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  206958. return 0;
  206959. case WM_LBUTTONUP:
  206960. case WM_MBUTTONUP:
  206961. case WM_RBUTTONUP:
  206962. doMouseUp (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  206963. return 0;
  206964. case WM_CAPTURECHANGED:
  206965. doCaptureChanged();
  206966. return 0;
  206967. case WM_NCMOUSEMOVE:
  206968. if (hasTitleBar())
  206969. break;
  206970. return 0;
  206971. case 0x020A: /* WM_MOUSEWHEEL */
  206972. doMouseWheel (wParam, true);
  206973. return 0;
  206974. case 0x020E: /* WM_MOUSEHWHEEL */
  206975. doMouseWheel (wParam, false);
  206976. return 0;
  206977. case WM_WINDOWPOSCHANGING:
  206978. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  206979. {
  206980. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  206981. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  206982. {
  206983. if (constrainer != 0)
  206984. {
  206985. const Rectangle current (component->getX() - windowBorder.getLeft(),
  206986. component->getY() - windowBorder.getTop(),
  206987. component->getWidth() + windowBorder.getLeftAndRight(),
  206988. component->getHeight() + windowBorder.getTopAndBottom());
  206989. constrainer->checkBounds (wp->x, wp->y, wp->cx, wp->cy,
  206990. current,
  206991. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  206992. wp->y != current.getY() && wp->y + wp->cy == current.getBottom(),
  206993. wp->x != current.getX() && wp->x + wp->cx == current.getRight(),
  206994. wp->y == current.getY() && wp->y + wp->cy != current.getBottom(),
  206995. wp->x == current.getX() && wp->x + wp->cx != current.getRight());
  206996. }
  206997. }
  206998. }
  206999. return 0;
  207000. case WM_WINDOWPOSCHANGED:
  207001. handleMovedOrResized();
  207002. if (dontRepaint)
  207003. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  207004. else
  207005. return 0;
  207006. case WM_KEYDOWN:
  207007. case WM_SYSKEYDOWN:
  207008. if (doKeyDown (wParam))
  207009. return 0;
  207010. break;
  207011. case WM_KEYUP:
  207012. case WM_SYSKEYUP:
  207013. if (doKeyUp (wParam))
  207014. return 0;
  207015. break;
  207016. case WM_CHAR:
  207017. if (doKeyChar ((int) wParam, lParam))
  207018. return 0;
  207019. break;
  207020. case WM_APPCOMMAND:
  207021. if (doAppCommand (lParam))
  207022. return TRUE;
  207023. break;
  207024. case WM_SETFOCUS:
  207025. updateKeyModifiers();
  207026. handleFocusGain();
  207027. break;
  207028. case WM_KILLFOCUS:
  207029. if (hasCreatedCaret)
  207030. {
  207031. hasCreatedCaret = false;
  207032. DestroyCaret();
  207033. }
  207034. handleFocusLoss();
  207035. break;
  207036. case WM_ACTIVATEAPP:
  207037. // Windows does weird things to process priority when you swap apps,
  207038. // so this forces an update when the app is brought to the front
  207039. if (wParam != FALSE)
  207040. juce_repeatLastProcessPriority();
  207041. juce_CheckCurrentlyFocusedTopLevelWindow();
  207042. modifiersAtLastCallback = -1;
  207043. return 0;
  207044. case WM_ACTIVATE:
  207045. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  207046. {
  207047. modifiersAtLastCallback = -1;
  207048. updateKeyModifiers();
  207049. if (isMinimised())
  207050. {
  207051. component->repaint();
  207052. handleMovedOrResized();
  207053. if (! isValidMessageListener())
  207054. return 0;
  207055. }
  207056. if (LOWORD (wParam) == WA_CLICKACTIVE
  207057. && component->isCurrentlyBlockedByAnotherModalComponent())
  207058. {
  207059. int mx, my;
  207060. component->getMouseXYRelative (mx, my);
  207061. Component* const underMouse = component->getComponentAt (mx, my);
  207062. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  207063. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  207064. return 0;
  207065. }
  207066. handleBroughtToFront();
  207067. return 0;
  207068. }
  207069. break;
  207070. case WM_NCACTIVATE:
  207071. // while a temporary window is being shown, prevent Windows from deactivating the
  207072. // title bars of our main windows.
  207073. if (wParam == 0 && ! shouldDeactivateTitleBar)
  207074. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  207075. break;
  207076. case WM_MOUSEACTIVATE:
  207077. if (! component->getMouseClickGrabsKeyboardFocus())
  207078. return MA_NOACTIVATE;
  207079. break;
  207080. case WM_SHOWWINDOW:
  207081. if (wParam != 0)
  207082. handleBroughtToFront();
  207083. break;
  207084. case WM_CLOSE:
  207085. handleUserClosingWindow();
  207086. return 0;
  207087. case WM_QUIT:
  207088. JUCEApplication::quit();
  207089. return 0;
  207090. case WM_TRAYNOTIFY:
  207091. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207092. {
  207093. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  207094. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207095. {
  207096. Component* const current = Component::getCurrentlyModalComponent();
  207097. if (current != 0)
  207098. current->inputAttemptWhenModal();
  207099. }
  207100. }
  207101. else
  207102. {
  207103. const int oldModifiers = currentModifiers;
  207104. MouseEvent e (0, 0, ModifierKeys::getCurrentModifiersRealtime(), component,
  207105. getMouseEventTime(), 0, 0, getMouseEventTime(), 1, false);
  207106. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  207107. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::leftButtonModifier);
  207108. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  207109. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::rightButtonModifier);
  207110. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  207111. {
  207112. SetFocus (hwnd);
  207113. SetForegroundWindow (hwnd);
  207114. component->mouseDown (e);
  207115. }
  207116. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207117. {
  207118. e.mods = ModifierKeys (oldModifiers);
  207119. component->mouseUp (e);
  207120. }
  207121. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207122. {
  207123. e.mods = ModifierKeys (oldModifiers);
  207124. component->mouseDoubleClick (e);
  207125. }
  207126. else if (lParam == WM_MOUSEMOVE)
  207127. {
  207128. component->mouseMove (e);
  207129. }
  207130. }
  207131. break;
  207132. case WM_SYNCPAINT:
  207133. return 0;
  207134. case WM_PALETTECHANGED:
  207135. InvalidateRect (h, 0, 0);
  207136. break;
  207137. case WM_DISPLAYCHANGE:
  207138. InvalidateRect (h, 0, 0);
  207139. createPaletteIfNeeded = true;
  207140. // intentional fall-through...
  207141. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  207142. doSettingChange();
  207143. break;
  207144. case WM_INITMENU:
  207145. if (! hasTitleBar())
  207146. {
  207147. if (isFullScreen())
  207148. {
  207149. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  207150. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  207151. }
  207152. else if (! isMinimised())
  207153. {
  207154. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  207155. }
  207156. }
  207157. break;
  207158. case WM_SYSCOMMAND:
  207159. switch (wParam & 0xfff0)
  207160. {
  207161. case SC_CLOSE:
  207162. if (hasTitleBar())
  207163. {
  207164. PostMessage (h, WM_CLOSE, 0, 0);
  207165. return 0;
  207166. }
  207167. break;
  207168. case SC_KEYMENU:
  207169. if (hasTitleBar() && h == GetCapture())
  207170. ReleaseCapture();
  207171. break;
  207172. case SC_MAXIMIZE:
  207173. setFullScreen (true);
  207174. return 0;
  207175. case SC_MINIMIZE:
  207176. if (! hasTitleBar())
  207177. {
  207178. setMinimised (true);
  207179. return 0;
  207180. }
  207181. break;
  207182. case SC_RESTORE:
  207183. if (hasTitleBar())
  207184. {
  207185. if (isFullScreen())
  207186. {
  207187. setFullScreen (false);
  207188. return 0;
  207189. }
  207190. }
  207191. else
  207192. {
  207193. if (isMinimised())
  207194. setMinimised (false);
  207195. else if (isFullScreen())
  207196. setFullScreen (false);
  207197. return 0;
  207198. }
  207199. break;
  207200. case SC_MONITORPOWER:
  207201. case SC_SCREENSAVE:
  207202. if (! screenSaverAllowed)
  207203. return 0;
  207204. break;
  207205. }
  207206. break;
  207207. case WM_NCLBUTTONDOWN:
  207208. case WM_NCRBUTTONDOWN:
  207209. case WM_NCMBUTTONDOWN:
  207210. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207211. {
  207212. Component* const current = Component::getCurrentlyModalComponent();
  207213. if (current != 0)
  207214. current->inputAttemptWhenModal();
  207215. }
  207216. break;
  207217. //case WM_IME_STARTCOMPOSITION;
  207218. // return 0;
  207219. case WM_GETDLGCODE:
  207220. return DLGC_WANTALLKEYS;
  207221. default:
  207222. break;
  207223. }
  207224. }
  207225. }
  207226. // (the message manager lock exits before calling this, to avoid deadlocks if
  207227. // this calls into non-juce windows)
  207228. return DefWindowProc (h, message, wParam, lParam);
  207229. }
  207230. Win32ComponentPeer (const Win32ComponentPeer&);
  207231. const Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  207232. };
  207233. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  207234. {
  207235. return new Win32ComponentPeer (this, styleFlags);
  207236. }
  207237. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  207238. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  207239. {
  207240. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  207241. if (wp != 0)
  207242. wp->setTaskBarIcon (&newImage);
  207243. }
  207244. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  207245. {
  207246. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  207247. if (wp != 0)
  207248. wp->setTaskBarIconToolTip (tooltip);
  207249. }
  207250. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  207251. {
  207252. DWORD val = GetWindowLong (h, styleType);
  207253. if (bitIsSet)
  207254. val |= feature;
  207255. else
  207256. val &= ~feature;
  207257. SetWindowLongPtr (h, styleType, val);
  207258. SetWindowPos (h, 0, 0, 0, 0, 0,
  207259. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  207260. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  207261. }
  207262. bool Process::isForegroundProcess() throw()
  207263. {
  207264. HWND fg = GetForegroundWindow();
  207265. if (fg == 0)
  207266. return true;
  207267. DWORD processId = 0;
  207268. GetWindowThreadProcessId (fg, &processId);
  207269. return processId == GetCurrentProcessId();
  207270. }
  207271. void Desktop::getMousePosition (int& x, int& y) throw()
  207272. {
  207273. POINT mousePos;
  207274. GetCursorPos (&mousePos);
  207275. x = mousePos.x;
  207276. y = mousePos.y;
  207277. }
  207278. void Desktop::setMousePosition (int x, int y) throw()
  207279. {
  207280. SetCursorPos (x, y);
  207281. }
  207282. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  207283. {
  207284. screenSaverAllowed = isEnabled;
  207285. }
  207286. bool Desktop::isScreenSaverEnabled() throw()
  207287. {
  207288. return screenSaverAllowed;
  207289. }
  207290. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  207291. {
  207292. Array <Rectangle>* const monitorCoords = (Array <Rectangle>*) userInfo;
  207293. monitorCoords->add (Rectangle (r->left, r->top, r->right - r->left, r->bottom - r->top));
  207294. return TRUE;
  207295. }
  207296. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  207297. {
  207298. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  207299. // make sure the first in the list is the main monitor
  207300. for (int i = 1; i < monitorCoords.size(); ++i)
  207301. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  207302. monitorCoords.swap (i, 0);
  207303. if (monitorCoords.size() == 0)
  207304. {
  207305. RECT r;
  207306. GetWindowRect (GetDesktopWindow(), &r);
  207307. monitorCoords.add (Rectangle (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207308. }
  207309. if (clipToWorkArea)
  207310. {
  207311. // clip the main monitor to the active non-taskbar area
  207312. RECT r;
  207313. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  207314. Rectangle& screen = monitorCoords.getReference (0);
  207315. screen.setPosition (jmax (screen.getX(), r.left),
  207316. jmax (screen.getY(), r.top));
  207317. screen.setSize (jmin (screen.getRight(), r.right) - screen.getX(),
  207318. jmin (screen.getBottom(), r.bottom) - screen.getY());
  207319. }
  207320. }
  207321. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  207322. {
  207323. Image* im = 0;
  207324. if (bitmap != 0)
  207325. {
  207326. BITMAP bm;
  207327. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  207328. && bm.bmWidth > 0 && bm.bmHeight > 0)
  207329. {
  207330. HDC tempDC = GetDC (0);
  207331. HDC dc = CreateCompatibleDC (tempDC);
  207332. ReleaseDC (0, tempDC);
  207333. SelectObject (dc, bitmap);
  207334. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  207335. for (int y = bm.bmHeight; --y >= 0;)
  207336. {
  207337. for (int x = bm.bmWidth; --x >= 0;)
  207338. {
  207339. COLORREF col = GetPixel (dc, x, y);
  207340. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  207341. (uint8) GetGValue (col),
  207342. (uint8) GetBValue (col)));
  207343. }
  207344. }
  207345. DeleteDC (dc);
  207346. }
  207347. }
  207348. return im;
  207349. }
  207350. static Image* createImageFromHICON (HICON icon) throw()
  207351. {
  207352. ICONINFO info;
  207353. if (GetIconInfo (icon, &info))
  207354. {
  207355. Image* const mask = createImageFromHBITMAP (info.hbmMask);
  207356. if (mask == 0)
  207357. return 0;
  207358. Image* const image = createImageFromHBITMAP (info.hbmColor);
  207359. if (image == 0)
  207360. return mask;
  207361. for (int y = image->getHeight(); --y >= 0;)
  207362. {
  207363. for (int x = image->getWidth(); --x >= 0;)
  207364. {
  207365. const float brightness = mask->getPixelAt (x, y).getBrightness();
  207366. if (brightness > 0.0f)
  207367. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  207368. }
  207369. }
  207370. delete mask;
  207371. return image;
  207372. }
  207373. return 0;
  207374. }
  207375. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  207376. {
  207377. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  207378. ICONINFO info;
  207379. info.fIcon = isIcon;
  207380. info.xHotspot = hotspotX;
  207381. info.yHotspot = hotspotY;
  207382. info.hbmMask = mask;
  207383. HICON hi = 0;
  207384. if (SystemStats::getOperatingSystemType() >= SystemStats::WinXP)
  207385. {
  207386. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  207387. Graphics g (bitmap);
  207388. g.drawImageAt (&image, 0, 0);
  207389. info.hbmColor = bitmap.hBitmap;
  207390. hi = CreateIconIndirect (&info);
  207391. }
  207392. else
  207393. {
  207394. HBITMAP colour = CreateCompatibleBitmap (GetDC (0), image.getWidth(), image.getHeight());
  207395. HDC colDC = CreateCompatibleDC (GetDC (0));
  207396. HDC alphaDC = CreateCompatibleDC (GetDC (0));
  207397. SelectObject (colDC, colour);
  207398. SelectObject (alphaDC, mask);
  207399. for (int y = image.getHeight(); --y >= 0;)
  207400. {
  207401. for (int x = image.getWidth(); --x >= 0;)
  207402. {
  207403. const Colour c (image.getPixelAt (x, y));
  207404. SetPixel (colDC, x, y, COLORREF (c.getRed() | (c.getGreen() << 8) | (c.getBlue() << 16)));
  207405. SetPixel (alphaDC, x, y, COLORREF (0xffffff - (c.getAlpha() | (c.getAlpha() << 8) | (c.getAlpha() << 16))));
  207406. }
  207407. }
  207408. DeleteDC (colDC);
  207409. DeleteDC (alphaDC);
  207410. info.hbmColor = colour;
  207411. hi = CreateIconIndirect (&info);
  207412. DeleteObject (colour);
  207413. }
  207414. DeleteObject (mask);
  207415. return hi;
  207416. }
  207417. Image* juce_createIconForFile (const File& file)
  207418. {
  207419. Image* image = 0;
  207420. TCHAR filename [1024];
  207421. file.getFullPathName().copyToBuffer (filename, 1023);
  207422. WORD iconNum = 0;
  207423. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  207424. filename, &iconNum);
  207425. if (icon != 0)
  207426. {
  207427. image = createImageFromHICON (icon);
  207428. DestroyIcon (icon);
  207429. }
  207430. return image;
  207431. }
  207432. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  207433. {
  207434. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  207435. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  207436. const Image* im = &image;
  207437. Image* newIm = 0;
  207438. if (image.getWidth() > maxW || image.getHeight() > maxH)
  207439. {
  207440. im = newIm = image.createCopy (maxW, maxH);
  207441. hotspotX = (hotspotX * maxW) / image.getWidth();
  207442. hotspotY = (hotspotY * maxH) / image.getHeight();
  207443. }
  207444. void* cursorH = 0;
  207445. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  207446. if (os == SystemStats::WinXP)
  207447. {
  207448. cursorH = (void*) createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  207449. }
  207450. else
  207451. {
  207452. const int stride = (maxW + 7) >> 3;
  207453. uint8* const andPlane = (uint8*) juce_calloc (stride * maxH);
  207454. uint8* const xorPlane = (uint8*) juce_calloc (stride * maxH);
  207455. int index = 0;
  207456. for (int y = 0; y < maxH; ++y)
  207457. {
  207458. for (int x = 0; x < maxW; ++x)
  207459. {
  207460. const unsigned char bit = (unsigned char) (1 << (7 - (x & 7)));
  207461. const Colour pixelColour (im->getPixelAt (x, y));
  207462. if (pixelColour.getAlpha() < 127)
  207463. andPlane [index + (x >> 3)] |= bit;
  207464. else if (pixelColour.getBrightness() >= 0.5f)
  207465. xorPlane [index + (x >> 3)] |= bit;
  207466. }
  207467. index += stride;
  207468. }
  207469. cursorH = CreateCursor (0, hotspotX, hotspotY, maxW, maxH, andPlane, xorPlane);
  207470. juce_free (andPlane);
  207471. juce_free (xorPlane);
  207472. }
  207473. delete newIm;
  207474. return cursorH;
  207475. }
  207476. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  207477. {
  207478. if (cursorHandle != 0 && ! isStandard)
  207479. DestroyCursor ((HCURSOR) cursorHandle);
  207480. }
  207481. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  207482. {
  207483. LPCTSTR cursorName = IDC_ARROW;
  207484. switch (type)
  207485. {
  207486. case MouseCursor::NormalCursor:
  207487. cursorName = IDC_ARROW;
  207488. break;
  207489. case MouseCursor::NoCursor:
  207490. return 0;
  207491. case MouseCursor::DraggingHandCursor:
  207492. {
  207493. static void* dragHandCursor = 0;
  207494. if (dragHandCursor == 0)
  207495. {
  207496. static const unsigned char dragHandData[] =
  207497. { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  207498. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39, 132,117,151,116,132,146,248,60,209,138,
  207499. 98,22,203,114,34,236,37,52,77,217,247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  207500. Image* const image = ImageFileFormat::loadFrom ((const char*) dragHandData, sizeof (dragHandData));
  207501. dragHandCursor = juce_createMouseCursorFromImage (*image, 8, 7);
  207502. delete image;
  207503. }
  207504. return dragHandCursor;
  207505. }
  207506. case MouseCursor::WaitCursor:
  207507. cursorName = IDC_WAIT;
  207508. break;
  207509. case MouseCursor::IBeamCursor:
  207510. cursorName = IDC_IBEAM;
  207511. break;
  207512. case MouseCursor::PointingHandCursor:
  207513. cursorName = MAKEINTRESOURCE(32649);
  207514. break;
  207515. case MouseCursor::LeftRightResizeCursor:
  207516. case MouseCursor::LeftEdgeResizeCursor:
  207517. case MouseCursor::RightEdgeResizeCursor:
  207518. cursorName = IDC_SIZEWE;
  207519. break;
  207520. case MouseCursor::UpDownResizeCursor:
  207521. case MouseCursor::TopEdgeResizeCursor:
  207522. case MouseCursor::BottomEdgeResizeCursor:
  207523. cursorName = IDC_SIZENS;
  207524. break;
  207525. case MouseCursor::TopLeftCornerResizeCursor:
  207526. case MouseCursor::BottomRightCornerResizeCursor:
  207527. cursorName = IDC_SIZENWSE;
  207528. break;
  207529. case MouseCursor::TopRightCornerResizeCursor:
  207530. case MouseCursor::BottomLeftCornerResizeCursor:
  207531. cursorName = IDC_SIZENESW;
  207532. break;
  207533. case MouseCursor::UpDownLeftRightResizeCursor:
  207534. cursorName = IDC_SIZEALL;
  207535. break;
  207536. case MouseCursor::CrosshairCursor:
  207537. cursorName = IDC_CROSS;
  207538. break;
  207539. case MouseCursor::CopyingCursor:
  207540. // can't seem to find one of these in the win32 list..
  207541. break;
  207542. }
  207543. HCURSOR cursorH = LoadCursor (0, cursorName);
  207544. if (cursorH == 0)
  207545. cursorH = LoadCursor (0, IDC_ARROW);
  207546. return (void*) cursorH;
  207547. }
  207548. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  207549. {
  207550. SetCursor ((HCURSOR) getHandle());
  207551. }
  207552. void MouseCursor::showInAllWindows() const throw()
  207553. {
  207554. showInWindow (0);
  207555. }
  207556. class JuceDropSource : public IDropSource
  207557. {
  207558. int refCount;
  207559. public:
  207560. JuceDropSource()
  207561. : refCount (1)
  207562. {
  207563. }
  207564. virtual ~JuceDropSource()
  207565. {
  207566. jassert (refCount == 0);
  207567. }
  207568. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207569. {
  207570. if (id == IID_IUnknown || id == IID_IDropSource)
  207571. {
  207572. AddRef();
  207573. *result = this;
  207574. return S_OK;
  207575. }
  207576. *result = 0;
  207577. return E_NOINTERFACE;
  207578. }
  207579. ULONG __stdcall AddRef() { return ++refCount; }
  207580. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  207581. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  207582. {
  207583. if (escapePressed)
  207584. return DRAGDROP_S_CANCEL;
  207585. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  207586. return DRAGDROP_S_DROP;
  207587. return S_OK;
  207588. }
  207589. HRESULT __stdcall GiveFeedback (DWORD)
  207590. {
  207591. return DRAGDROP_S_USEDEFAULTCURSORS;
  207592. }
  207593. };
  207594. class JuceEnumFormatEtc : public IEnumFORMATETC
  207595. {
  207596. public:
  207597. JuceEnumFormatEtc (const FORMATETC* const format_)
  207598. : refCount (1),
  207599. format (format_),
  207600. index (0)
  207601. {
  207602. }
  207603. virtual ~JuceEnumFormatEtc()
  207604. {
  207605. jassert (refCount == 0);
  207606. }
  207607. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207608. {
  207609. if (id == IID_IUnknown || id == IID_IEnumFORMATETC)
  207610. {
  207611. AddRef();
  207612. *result = this;
  207613. return S_OK;
  207614. }
  207615. *result = 0;
  207616. return E_NOINTERFACE;
  207617. }
  207618. ULONG __stdcall AddRef() { return ++refCount; }
  207619. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  207620. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  207621. {
  207622. if (result == 0)
  207623. return E_POINTER;
  207624. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  207625. newOne->index = index;
  207626. *result = newOne;
  207627. return S_OK;
  207628. }
  207629. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  207630. {
  207631. if (pceltFetched != 0)
  207632. *pceltFetched = 0;
  207633. else if (celt != 1)
  207634. return S_FALSE;
  207635. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  207636. {
  207637. copyFormatEtc (lpFormatEtc [0], *format);
  207638. ++index;
  207639. if (pceltFetched != 0)
  207640. *pceltFetched = 1;
  207641. return S_OK;
  207642. }
  207643. return S_FALSE;
  207644. }
  207645. HRESULT __stdcall Skip (ULONG celt)
  207646. {
  207647. if (index + (int) celt >= 1)
  207648. return S_FALSE;
  207649. index += celt;
  207650. return S_OK;
  207651. }
  207652. HRESULT __stdcall Reset()
  207653. {
  207654. index = 0;
  207655. return S_OK;
  207656. }
  207657. private:
  207658. int refCount;
  207659. const FORMATETC* const format;
  207660. int index;
  207661. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  207662. {
  207663. dest = source;
  207664. if (source.ptd != 0)
  207665. {
  207666. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  207667. *(dest.ptd) = *(source.ptd);
  207668. }
  207669. }
  207670. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  207671. const JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  207672. };
  207673. class JuceDataObject : public IDataObject
  207674. {
  207675. JuceDropSource* const dropSource;
  207676. const FORMATETC* const format;
  207677. const STGMEDIUM* const medium;
  207678. int refCount;
  207679. JuceDataObject (const JuceDataObject&);
  207680. const JuceDataObject& operator= (const JuceDataObject&);
  207681. public:
  207682. JuceDataObject (JuceDropSource* const dropSource_,
  207683. const FORMATETC* const format_,
  207684. const STGMEDIUM* const medium_)
  207685. : dropSource (dropSource_),
  207686. format (format_),
  207687. medium (medium_),
  207688. refCount (1)
  207689. {
  207690. }
  207691. virtual ~JuceDataObject()
  207692. {
  207693. jassert (refCount == 0);
  207694. }
  207695. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207696. {
  207697. if (id == IID_IUnknown || id == IID_IDataObject)
  207698. {
  207699. AddRef();
  207700. *result = this;
  207701. return S_OK;
  207702. }
  207703. *result = 0;
  207704. return E_NOINTERFACE;
  207705. }
  207706. ULONG __stdcall AddRef() { return ++refCount; }
  207707. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  207708. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  207709. {
  207710. if (pFormatEtc->tymed == format->tymed
  207711. && pFormatEtc->cfFormat == format->cfFormat
  207712. && pFormatEtc->dwAspect == format->dwAspect)
  207713. {
  207714. pMedium->tymed = format->tymed;
  207715. pMedium->pUnkForRelease = 0;
  207716. if (format->tymed == TYMED_HGLOBAL)
  207717. {
  207718. const SIZE_T len = GlobalSize (medium->hGlobal);
  207719. void* const src = GlobalLock (medium->hGlobal);
  207720. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  207721. memcpy (dst, src, len);
  207722. GlobalUnlock (medium->hGlobal);
  207723. pMedium->hGlobal = dst;
  207724. return S_OK;
  207725. }
  207726. }
  207727. return DV_E_FORMATETC;
  207728. }
  207729. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  207730. {
  207731. if (f == 0)
  207732. return E_INVALIDARG;
  207733. if (f->tymed == format->tymed
  207734. && f->cfFormat == format->cfFormat
  207735. && f->dwAspect == format->dwAspect)
  207736. return S_OK;
  207737. return DV_E_FORMATETC;
  207738. }
  207739. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  207740. {
  207741. pFormatEtcOut->ptd = 0;
  207742. return E_NOTIMPL;
  207743. }
  207744. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  207745. {
  207746. if (result == 0)
  207747. return E_POINTER;
  207748. if (direction == DATADIR_GET)
  207749. {
  207750. *result = new JuceEnumFormatEtc (format);
  207751. return S_OK;
  207752. }
  207753. *result = 0;
  207754. return E_NOTIMPL;
  207755. }
  207756. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  207757. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  207758. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  207759. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  207760. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  207761. };
  207762. static HDROP createHDrop (const StringArray& fileNames) throw()
  207763. {
  207764. int totalChars = 0;
  207765. for (int i = fileNames.size(); --i >= 0;)
  207766. totalChars += fileNames[i].length() + 1;
  207767. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  207768. sizeof (DROPFILES)
  207769. + sizeof (WCHAR) * (totalChars + 2));
  207770. if (hDrop != 0)
  207771. {
  207772. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  207773. pDropFiles->pFiles = sizeof (DROPFILES);
  207774. pDropFiles->fWide = true;
  207775. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  207776. for (int i = 0; i < fileNames.size(); ++i)
  207777. {
  207778. fileNames[i].copyToBuffer (fname, 2048);
  207779. fname += fileNames[i].length() + 1;
  207780. }
  207781. *fname = 0;
  207782. GlobalUnlock (hDrop);
  207783. }
  207784. return hDrop;
  207785. }
  207786. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  207787. {
  207788. JuceDropSource* const source = new JuceDropSource();
  207789. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  207790. DWORD effect;
  207791. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  207792. data->Release();
  207793. source->Release();
  207794. return res == DRAGDROP_S_DROP;
  207795. }
  207796. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  207797. {
  207798. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207799. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207800. medium.hGlobal = createHDrop (files);
  207801. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  207802. : DROPEFFECT_COPY);
  207803. }
  207804. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  207805. {
  207806. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207807. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207808. const int numChars = text.length();
  207809. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  207810. char* d = (char*) GlobalLock (medium.hGlobal);
  207811. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  207812. format.cfFormat = CF_UNICODETEXT;
  207813. GlobalUnlock (medium.hGlobal);
  207814. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  207815. }
  207816. #if JUCE_OPENGL
  207817. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  207818. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  207819. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  207820. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  207821. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  207822. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  207823. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  207824. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  207825. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  207826. #define WGL_ACCELERATION_ARB 0x2003
  207827. #define WGL_SWAP_METHOD_ARB 0x2007
  207828. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  207829. #define WGL_PIXEL_TYPE_ARB 0x2013
  207830. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  207831. #define WGL_COLOR_BITS_ARB 0x2014
  207832. #define WGL_RED_BITS_ARB 0x2015
  207833. #define WGL_GREEN_BITS_ARB 0x2017
  207834. #define WGL_BLUE_BITS_ARB 0x2019
  207835. #define WGL_ALPHA_BITS_ARB 0x201B
  207836. #define WGL_DEPTH_BITS_ARB 0x2022
  207837. #define WGL_STENCIL_BITS_ARB 0x2023
  207838. #define WGL_FULL_ACCELERATION_ARB 0x2027
  207839. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  207840. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  207841. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  207842. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  207843. #define WGL_STEREO_ARB 0x2012
  207844. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  207845. #define WGL_SAMPLES_ARB 0x2042
  207846. #define WGL_TYPE_RGBA_ARB 0x202B
  207847. static void getWglExtensions (HDC dc, StringArray& result) throw()
  207848. {
  207849. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  207850. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  207851. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  207852. else
  207853. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  207854. }
  207855. class WindowedGLContext : public OpenGLContext
  207856. {
  207857. public:
  207858. WindowedGLContext (Component* const component_,
  207859. HGLRC contextToShareWith,
  207860. const OpenGLPixelFormat& pixelFormat)
  207861. : renderContext (0),
  207862. nativeWindow (0),
  207863. dc (0),
  207864. component (component_)
  207865. {
  207866. jassert (component != 0);
  207867. createNativeWindow();
  207868. // Use a default pixel format that should be supported everywhere
  207869. PIXELFORMATDESCRIPTOR pfd;
  207870. zerostruct (pfd);
  207871. pfd.nSize = sizeof (pfd);
  207872. pfd.nVersion = 1;
  207873. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  207874. pfd.iPixelType = PFD_TYPE_RGBA;
  207875. pfd.cColorBits = 24;
  207876. pfd.cDepthBits = 16;
  207877. const int format = ChoosePixelFormat (dc, &pfd);
  207878. if (format != 0)
  207879. SetPixelFormat (dc, format, &pfd);
  207880. renderContext = wglCreateContext (dc);
  207881. makeActive();
  207882. setPixelFormat (pixelFormat);
  207883. if (contextToShareWith != 0 && renderContext != 0)
  207884. wglShareLists (contextToShareWith, renderContext);
  207885. }
  207886. ~WindowedGLContext()
  207887. {
  207888. makeInactive();
  207889. wglDeleteContext (renderContext);
  207890. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  207891. delete nativeWindow;
  207892. }
  207893. bool makeActive() const throw()
  207894. {
  207895. jassert (renderContext != 0);
  207896. return wglMakeCurrent (dc, renderContext) != 0;
  207897. }
  207898. bool makeInactive() const throw()
  207899. {
  207900. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  207901. }
  207902. bool isActive() const throw()
  207903. {
  207904. return wglGetCurrentContext() == renderContext;
  207905. }
  207906. const OpenGLPixelFormat getPixelFormat() const
  207907. {
  207908. OpenGLPixelFormat pf;
  207909. makeActive();
  207910. StringArray availableExtensions;
  207911. getWglExtensions (dc, availableExtensions);
  207912. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  207913. return pf;
  207914. }
  207915. void* getRawContext() const throw()
  207916. {
  207917. return renderContext;
  207918. }
  207919. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  207920. {
  207921. makeActive();
  207922. PIXELFORMATDESCRIPTOR pfd;
  207923. zerostruct (pfd);
  207924. pfd.nSize = sizeof (pfd);
  207925. pfd.nVersion = 1;
  207926. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  207927. pfd.iPixelType = PFD_TYPE_RGBA;
  207928. pfd.iLayerType = PFD_MAIN_PLANE;
  207929. pfd.cColorBits = pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits;
  207930. pfd.cRedBits = pixelFormat.redBits;
  207931. pfd.cGreenBits = pixelFormat.greenBits;
  207932. pfd.cBlueBits = pixelFormat.blueBits;
  207933. pfd.cAlphaBits = pixelFormat.alphaBits;
  207934. pfd.cDepthBits = pixelFormat.depthBufferBits;
  207935. pfd.cStencilBits = pixelFormat.stencilBufferBits;
  207936. pfd.cAccumBits = pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  207937. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits;
  207938. pfd.cAccumRedBits = pixelFormat.accumulationBufferRedBits;
  207939. pfd.cAccumGreenBits = pixelFormat.accumulationBufferGreenBits;
  207940. pfd.cAccumBlueBits = pixelFormat.accumulationBufferBlueBits;
  207941. pfd.cAccumAlphaBits = pixelFormat.accumulationBufferAlphaBits;
  207942. int format = 0;
  207943. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  207944. StringArray availableExtensions;
  207945. getWglExtensions (dc, availableExtensions);
  207946. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  207947. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  207948. {
  207949. int attributes[64];
  207950. int n = 0;
  207951. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  207952. attributes[n++] = GL_TRUE;
  207953. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  207954. attributes[n++] = GL_TRUE;
  207955. attributes[n++] = WGL_ACCELERATION_ARB;
  207956. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  207957. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  207958. attributes[n++] = GL_TRUE;
  207959. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  207960. attributes[n++] = WGL_TYPE_RGBA_ARB;
  207961. attributes[n++] = WGL_COLOR_BITS_ARB;
  207962. attributes[n++] = pfd.cColorBits;
  207963. attributes[n++] = WGL_RED_BITS_ARB;
  207964. attributes[n++] = pixelFormat.redBits;
  207965. attributes[n++] = WGL_GREEN_BITS_ARB;
  207966. attributes[n++] = pixelFormat.greenBits;
  207967. attributes[n++] = WGL_BLUE_BITS_ARB;
  207968. attributes[n++] = pixelFormat.blueBits;
  207969. attributes[n++] = WGL_ALPHA_BITS_ARB;
  207970. attributes[n++] = pixelFormat.alphaBits;
  207971. attributes[n++] = WGL_DEPTH_BITS_ARB;
  207972. attributes[n++] = pixelFormat.depthBufferBits;
  207973. if (pixelFormat.stencilBufferBits > 0)
  207974. {
  207975. attributes[n++] = WGL_STENCIL_BITS_ARB;
  207976. attributes[n++] = pixelFormat.stencilBufferBits;
  207977. }
  207978. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  207979. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  207980. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  207981. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  207982. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  207983. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  207984. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  207985. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  207986. if (availableExtensions.contains ("WGL_ARB_multisample")
  207987. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  207988. {
  207989. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  207990. attributes[n++] = 1;
  207991. attributes[n++] = WGL_SAMPLES_ARB;
  207992. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  207993. }
  207994. attributes[n++] = 0;
  207995. UINT formatsCount;
  207996. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  207997. (void) ok;
  207998. jassert (ok);
  207999. }
  208000. else
  208001. {
  208002. format = ChoosePixelFormat (dc, &pfd);
  208003. }
  208004. if (format != 0)
  208005. {
  208006. makeInactive();
  208007. // win32 can't change the pixel format of a window, so need to delete the
  208008. // old one and create a new one..
  208009. jassert (nativeWindow != 0);
  208010. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208011. delete nativeWindow;
  208012. createNativeWindow();
  208013. if (SetPixelFormat (dc, format, &pfd))
  208014. {
  208015. wglDeleteContext (renderContext);
  208016. renderContext = wglCreateContext (dc);
  208017. jassert (renderContext != 0);
  208018. return renderContext != 0;
  208019. }
  208020. }
  208021. return false;
  208022. }
  208023. void updateWindowPosition (int x, int y, int w, int h, int)
  208024. {
  208025. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  208026. x, y, w, h,
  208027. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  208028. }
  208029. void repaint()
  208030. {
  208031. int x, y, w, h;
  208032. nativeWindow->getBounds (x, y, w, h);
  208033. nativeWindow->repaint (0, 0, w, h);
  208034. }
  208035. void swapBuffers()
  208036. {
  208037. SwapBuffers (dc);
  208038. }
  208039. bool setSwapInterval (const int numFramesPerSwap)
  208040. {
  208041. makeActive();
  208042. StringArray availableExtensions;
  208043. getWglExtensions (dc, availableExtensions);
  208044. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  208045. return availableExtensions.contains ("WGL_EXT_swap_control")
  208046. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  208047. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  208048. }
  208049. int getSwapInterval() const
  208050. {
  208051. makeActive();
  208052. StringArray availableExtensions;
  208053. getWglExtensions (dc, availableExtensions);
  208054. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  208055. if (availableExtensions.contains ("WGL_EXT_swap_control")
  208056. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  208057. return wglGetSwapIntervalEXT();
  208058. return 0;
  208059. }
  208060. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  208061. {
  208062. jassert (isActive());
  208063. StringArray availableExtensions;
  208064. getWglExtensions (dc, availableExtensions);
  208065. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208066. int numTypes = 0;
  208067. if (availableExtensions.contains("WGL_ARB_pixel_format")
  208068. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208069. {
  208070. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  208071. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  208072. jassertfalse
  208073. }
  208074. else
  208075. {
  208076. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  208077. }
  208078. OpenGLPixelFormat pf;
  208079. for (int i = 0; i < numTypes; ++i)
  208080. {
  208081. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  208082. {
  208083. bool alreadyListed = false;
  208084. for (int j = results.size(); --j >= 0;)
  208085. if (pf == *results.getUnchecked(j))
  208086. alreadyListed = true;
  208087. if (! alreadyListed)
  208088. results.add (new OpenGLPixelFormat (pf));
  208089. }
  208090. }
  208091. }
  208092. juce_UseDebuggingNewOperator
  208093. HGLRC renderContext;
  208094. private:
  208095. Win32ComponentPeer* nativeWindow;
  208096. Component* const component;
  208097. HDC dc;
  208098. void createNativeWindow()
  208099. {
  208100. nativeWindow = new Win32ComponentPeer (component, 0);
  208101. nativeWindow->dontRepaint = true;
  208102. nativeWindow->setVisible (true);
  208103. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  208104. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  208105. if (peer != 0)
  208106. {
  208107. SetParent (hwnd, (HWND) peer->getNativeHandle());
  208108. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  208109. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  208110. }
  208111. dc = GetDC (hwnd);
  208112. }
  208113. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  208114. OpenGLPixelFormat& result,
  208115. const StringArray& availableExtensions) const throw()
  208116. {
  208117. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208118. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208119. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208120. {
  208121. int attributes[32];
  208122. int numAttributes = 0;
  208123. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  208124. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  208125. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  208126. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  208127. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  208128. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  208129. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  208130. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  208131. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  208132. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  208133. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  208134. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  208135. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  208136. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  208137. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208138. if (availableExtensions.contains ("WGL_ARB_multisample"))
  208139. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  208140. int values[32];
  208141. zeromem (values, sizeof (values));
  208142. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  208143. {
  208144. int n = 0;
  208145. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  208146. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  208147. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  208148. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  208149. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  208150. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  208151. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  208152. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  208153. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  208154. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  208155. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  208156. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  208157. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  208158. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  208159. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  208160. result.fullSceneAntiAliasingNumSamples = values[n++]; // WGL_SAMPLES_ARB
  208161. return isValidFormat;
  208162. }
  208163. else
  208164. {
  208165. jassertfalse
  208166. }
  208167. }
  208168. else
  208169. {
  208170. PIXELFORMATDESCRIPTOR pfd;
  208171. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  208172. {
  208173. result.redBits = pfd.cRedBits;
  208174. result.greenBits = pfd.cGreenBits;
  208175. result.blueBits = pfd.cBlueBits;
  208176. result.alphaBits = pfd.cAlphaBits;
  208177. result.depthBufferBits = pfd.cDepthBits;
  208178. result.stencilBufferBits = pfd.cStencilBits;
  208179. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  208180. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  208181. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  208182. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  208183. result.fullSceneAntiAliasingNumSamples = 0;
  208184. return true;
  208185. }
  208186. else
  208187. {
  208188. jassertfalse
  208189. }
  208190. }
  208191. return false;
  208192. }
  208193. WindowedGLContext (const WindowedGLContext&);
  208194. const WindowedGLContext& operator= (const WindowedGLContext&);
  208195. };
  208196. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  208197. const OpenGLPixelFormat& pixelFormat,
  208198. const OpenGLContext* const contextToShareWith)
  208199. {
  208200. WindowedGLContext* c = new WindowedGLContext (component,
  208201. contextToShareWith != 0 ? (HGLRC) contextToShareWith->getRawContext() : 0,
  208202. pixelFormat);
  208203. if (c->renderContext == 0)
  208204. deleteAndZero (c);
  208205. return c;
  208206. }
  208207. void juce_glViewport (const int w, const int h)
  208208. {
  208209. glViewport (0, 0, w, h);
  208210. }
  208211. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  208212. OwnedArray <OpenGLPixelFormat>& results)
  208213. {
  208214. Component tempComp;
  208215. {
  208216. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  208217. wc.makeActive();
  208218. wc.findAlternativeOpenGLPixelFormats (results);
  208219. }
  208220. }
  208221. #endif
  208222. class JuceIStorage : public IStorage
  208223. {
  208224. int refCount;
  208225. public:
  208226. JuceIStorage() : refCount (1) {}
  208227. virtual ~JuceIStorage()
  208228. {
  208229. jassert (refCount == 0);
  208230. }
  208231. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  208232. {
  208233. if (id == IID_IUnknown || id == IID_IStorage)
  208234. {
  208235. AddRef();
  208236. *result = this;
  208237. return S_OK;
  208238. }
  208239. *result = 0;
  208240. return E_NOINTERFACE;
  208241. }
  208242. ULONG __stdcall AddRef() { return ++refCount; }
  208243. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  208244. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208245. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208246. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  208247. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  208248. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  208249. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  208250. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  208251. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  208252. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  208253. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  208254. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  208255. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  208256. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  208257. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  208258. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  208259. juce_UseDebuggingNewOperator
  208260. };
  208261. class JuceOleInPlaceFrame : public IOleInPlaceFrame
  208262. {
  208263. int refCount;
  208264. HWND window;
  208265. public:
  208266. JuceOleInPlaceFrame (HWND window_)
  208267. : refCount (1),
  208268. window (window_)
  208269. {
  208270. }
  208271. virtual ~JuceOleInPlaceFrame()
  208272. {
  208273. jassert (refCount == 0);
  208274. }
  208275. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  208276. {
  208277. if (id == IID_IUnknown || id == IID_IOleInPlaceFrame)
  208278. {
  208279. AddRef();
  208280. *result = this;
  208281. return S_OK;
  208282. }
  208283. *result = 0;
  208284. return E_NOINTERFACE;
  208285. }
  208286. ULONG __stdcall AddRef() { return ++refCount; }
  208287. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  208288. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208289. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208290. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  208291. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208292. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208293. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  208294. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  208295. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  208296. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  208297. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  208298. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  208299. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  208300. juce_UseDebuggingNewOperator
  208301. };
  208302. class JuceIOleInPlaceSite : public IOleInPlaceSite
  208303. {
  208304. int refCount;
  208305. HWND window;
  208306. JuceOleInPlaceFrame* frame;
  208307. public:
  208308. JuceIOleInPlaceSite (HWND window_)
  208309. : refCount (1),
  208310. window (window_)
  208311. {
  208312. frame = new JuceOleInPlaceFrame (window);
  208313. }
  208314. virtual ~JuceIOleInPlaceSite()
  208315. {
  208316. jassert (refCount == 0);
  208317. frame->Release();
  208318. }
  208319. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  208320. {
  208321. if (id == IID_IUnknown || id == IID_IOleInPlaceSite)
  208322. {
  208323. AddRef();
  208324. *result = this;
  208325. return S_OK;
  208326. }
  208327. *result = 0;
  208328. return E_NOINTERFACE;
  208329. }
  208330. ULONG __stdcall AddRef() { return ++refCount; }
  208331. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  208332. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208333. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208334. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  208335. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  208336. HRESULT __stdcall OnUIActivate() { return S_OK; }
  208337. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  208338. {
  208339. frame->AddRef();
  208340. *lplpFrame = frame;
  208341. *lplpDoc = 0;
  208342. lpFrameInfo->fMDIApp = FALSE;
  208343. lpFrameInfo->hwndFrame = window;
  208344. lpFrameInfo->haccel = 0;
  208345. lpFrameInfo->cAccelEntries = 0;
  208346. return S_OK;
  208347. }
  208348. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  208349. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  208350. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  208351. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  208352. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  208353. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  208354. juce_UseDebuggingNewOperator
  208355. };
  208356. class JuceIOleClientSite : public IOleClientSite
  208357. {
  208358. int refCount;
  208359. JuceIOleInPlaceSite* inplaceSite;
  208360. public:
  208361. JuceIOleClientSite (HWND window)
  208362. : refCount (1)
  208363. {
  208364. inplaceSite = new JuceIOleInPlaceSite (window);
  208365. }
  208366. virtual ~JuceIOleClientSite()
  208367. {
  208368. jassert (refCount == 0);
  208369. inplaceSite->Release();
  208370. }
  208371. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  208372. {
  208373. if (id == IID_IUnknown || id == IID_IOleClientSite)
  208374. {
  208375. AddRef();
  208376. *result = this;
  208377. return S_OK;
  208378. }
  208379. else if (id == IID_IOleInPlaceSite)
  208380. {
  208381. inplaceSite->AddRef();
  208382. *result = inplaceSite;
  208383. return S_OK;
  208384. }
  208385. *result = 0;
  208386. return E_NOINTERFACE;
  208387. }
  208388. ULONG __stdcall AddRef() { return ++refCount; }
  208389. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  208390. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  208391. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  208392. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  208393. HRESULT __stdcall ShowObject() { return S_OK; }
  208394. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  208395. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  208396. juce_UseDebuggingNewOperator
  208397. };
  208398. class ActiveXControlData : public ComponentMovementWatcher
  208399. {
  208400. ActiveXControlComponent* const owner;
  208401. bool wasShowing;
  208402. public:
  208403. HWND controlHWND;
  208404. IStorage* storage;
  208405. IOleClientSite* clientSite;
  208406. IOleObject* control;
  208407. ActiveXControlData (HWND hwnd,
  208408. ActiveXControlComponent* const owner_)
  208409. : ComponentMovementWatcher (owner_),
  208410. owner (owner_),
  208411. wasShowing (owner_ != 0 && owner_->isShowing()),
  208412. controlHWND (0),
  208413. storage (new JuceIStorage()),
  208414. clientSite (new JuceIOleClientSite (hwnd)),
  208415. control (0)
  208416. {
  208417. }
  208418. ~ActiveXControlData()
  208419. {
  208420. if (control != 0)
  208421. {
  208422. control->Close (OLECLOSE_NOSAVE);
  208423. control->Release();
  208424. }
  208425. clientSite->Release();
  208426. storage->Release();
  208427. }
  208428. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  208429. {
  208430. Component* const topComp = owner->getTopLevelComponent();
  208431. if (topComp->getPeer() != 0)
  208432. {
  208433. int x = 0, y = 0;
  208434. owner->relativePositionToOtherComponent (topComp, x, y);
  208435. owner->setControlBounds (Rectangle (x, y, owner->getWidth(), owner->getHeight()));
  208436. }
  208437. }
  208438. void componentPeerChanged()
  208439. {
  208440. const bool isShowingNow = owner->isShowing();
  208441. if (wasShowing != isShowingNow)
  208442. {
  208443. wasShowing = isShowingNow;
  208444. owner->setControlVisible (isShowingNow);
  208445. }
  208446. }
  208447. void componentVisibilityChanged (Component&)
  208448. {
  208449. componentPeerChanged();
  208450. }
  208451. static bool doesWindowMatch (const ActiveXControlComponent* const ax, HWND hwnd)
  208452. {
  208453. return ((ActiveXControlData*) ax->control)->controlHWND == hwnd;
  208454. }
  208455. };
  208456. static VoidArray activeXComps;
  208457. static HWND getHWND (const ActiveXControlComponent* const component)
  208458. {
  208459. HWND hwnd = 0;
  208460. const IID iid = IID_IOleWindow;
  208461. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  208462. if (window != 0)
  208463. {
  208464. window->GetWindow (&hwnd);
  208465. window->Release();
  208466. }
  208467. return hwnd;
  208468. }
  208469. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  208470. {
  208471. RECT activeXRect, peerRect;
  208472. GetWindowRect (hwnd, &activeXRect);
  208473. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  208474. const int mx = GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left;
  208475. const int my = GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top;
  208476. const int64 mouseEventTime = getMouseEventTime();
  208477. const int oldModifiers = currentModifiers;
  208478. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  208479. switch (message)
  208480. {
  208481. case WM_MOUSEMOVE:
  208482. if (ModifierKeys (currentModifiers).isAnyMouseButtonDown())
  208483. peer->handleMouseDrag (mx, my, mouseEventTime);
  208484. else
  208485. peer->handleMouseMove (mx, my, mouseEventTime);
  208486. break;
  208487. case WM_LBUTTONDOWN:
  208488. case WM_MBUTTONDOWN:
  208489. case WM_RBUTTONDOWN:
  208490. peer->handleMouseDown (mx, my, mouseEventTime);
  208491. break;
  208492. case WM_LBUTTONUP:
  208493. case WM_MBUTTONUP:
  208494. case WM_RBUTTONUP:
  208495. peer->handleMouseUp (oldModifiers, mx, my, mouseEventTime);
  208496. break;
  208497. default:
  208498. break;
  208499. }
  208500. }
  208501. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  208502. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  208503. {
  208504. for (int i = activeXComps.size(); --i >= 0;)
  208505. {
  208506. const ActiveXControlComponent* const ax = (const ActiveXControlComponent*) activeXComps.getUnchecked(i);
  208507. if (ActiveXControlData::doesWindowMatch (ax, hwnd))
  208508. {
  208509. switch (message)
  208510. {
  208511. case WM_MOUSEMOVE:
  208512. case WM_LBUTTONDOWN:
  208513. case WM_MBUTTONDOWN:
  208514. case WM_RBUTTONDOWN:
  208515. case WM_LBUTTONUP:
  208516. case WM_MBUTTONUP:
  208517. case WM_RBUTTONUP:
  208518. case WM_LBUTTONDBLCLK:
  208519. case WM_MBUTTONDBLCLK:
  208520. case WM_RBUTTONDBLCLK:
  208521. if (ax->isShowing())
  208522. {
  208523. ComponentPeer* const peer = ax->getPeer();
  208524. if (peer != 0)
  208525. {
  208526. offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  208527. if (! ax->areMouseEventsAllowed())
  208528. return 0;
  208529. }
  208530. }
  208531. break;
  208532. default:
  208533. break;
  208534. }
  208535. return CallWindowProc ((WNDPROC) (ax->originalWndProc), hwnd, message, wParam, lParam);
  208536. }
  208537. }
  208538. return DefWindowProc (hwnd, message, wParam, lParam);
  208539. }
  208540. ActiveXControlComponent::ActiveXControlComponent()
  208541. : originalWndProc (0),
  208542. control (0),
  208543. mouseEventsAllowed (true)
  208544. {
  208545. activeXComps.add (this);
  208546. }
  208547. ActiveXControlComponent::~ActiveXControlComponent()
  208548. {
  208549. deleteControl();
  208550. activeXComps.removeValue (this);
  208551. }
  208552. void ActiveXControlComponent::paint (Graphics& g)
  208553. {
  208554. if (control == 0)
  208555. g.fillAll (Colours::lightgrey);
  208556. }
  208557. bool ActiveXControlComponent::createControl (const void* controlIID)
  208558. {
  208559. deleteControl();
  208560. ComponentPeer* const peer = getPeer();
  208561. // the component must have already been added to a real window when you call this!
  208562. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  208563. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  208564. {
  208565. int x = 0, y = 0;
  208566. relativePositionToOtherComponent (getTopLevelComponent(), x, y);
  208567. HWND hwnd = (HWND) peer->getNativeHandle();
  208568. ActiveXControlData* const info = new ActiveXControlData (hwnd, this);
  208569. HRESULT hr;
  208570. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  208571. info->clientSite, info->storage,
  208572. (void**) &(info->control))) == S_OK)
  208573. {
  208574. info->control->SetHostNames (L"Juce", 0);
  208575. if (OleSetContainedObject (info->control, TRUE) == S_OK)
  208576. {
  208577. RECT rect;
  208578. rect.left = x;
  208579. rect.top = y;
  208580. rect.right = x + getWidth();
  208581. rect.bottom = y + getHeight();
  208582. if (info->control->DoVerb (OLEIVERB_SHOW, 0, info->clientSite, 0, hwnd, &rect) == S_OK)
  208583. {
  208584. control = info;
  208585. setControlBounds (Rectangle (x, y, getWidth(), getHeight()));
  208586. info->controlHWND = getHWND (this);
  208587. if (info->controlHWND != 0)
  208588. {
  208589. originalWndProc = (void*) GetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC);
  208590. SetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC, (LONG_PTR) activeXHookWndProc);
  208591. }
  208592. return true;
  208593. }
  208594. }
  208595. }
  208596. delete info;
  208597. }
  208598. return false;
  208599. }
  208600. void ActiveXControlComponent::deleteControl()
  208601. {
  208602. ActiveXControlData* const info = (ActiveXControlData*) control;
  208603. if (info != 0)
  208604. {
  208605. delete info;
  208606. control = 0;
  208607. originalWndProc = 0;
  208608. }
  208609. }
  208610. void* ActiveXControlComponent::queryInterface (const void* iid) const
  208611. {
  208612. ActiveXControlData* const info = (ActiveXControlData*) control;
  208613. void* result = 0;
  208614. if (info != 0 && info->control != 0
  208615. && info->control->QueryInterface (*(const IID*) iid, &result) == S_OK)
  208616. return result;
  208617. return 0;
  208618. }
  208619. void ActiveXControlComponent::setControlBounds (const Rectangle& newBounds) const
  208620. {
  208621. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  208622. if (hwnd != 0)
  208623. MoveWindow (hwnd, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  208624. }
  208625. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  208626. {
  208627. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  208628. if (hwnd != 0)
  208629. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  208630. }
  208631. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  208632. {
  208633. mouseEventsAllowed = eventsCanReachControl;
  208634. }
  208635. END_JUCE_NAMESPACE
  208636. /********* End of inlined file: juce_win32_Windowing.cpp *********/
  208637. #endif
  208638. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  208639. // Auto-links to various win32 libs that are needed by library calls..
  208640. #pragma comment(lib, "kernel32.lib")
  208641. #pragma comment(lib, "user32.lib")
  208642. #pragma comment(lib, "shell32.lib")
  208643. #pragma comment(lib, "gdi32.lib")
  208644. #pragma comment(lib, "vfw32.lib")
  208645. #pragma comment(lib, "comdlg32.lib")
  208646. #pragma comment(lib, "winmm.lib")
  208647. #pragma comment(lib, "wininet.lib")
  208648. #pragma comment(lib, "ole32.lib")
  208649. #pragma comment(lib, "advapi32.lib")
  208650. #pragma comment(lib, "ws2_32.lib")
  208651. #pragma comment(lib, "comsupp.lib")
  208652. #if JUCE_OPENGL
  208653. #pragma comment(lib, "OpenGL32.Lib")
  208654. #pragma comment(lib, "GlU32.Lib")
  208655. #endif
  208656. #if JUCE_QUICKTIME
  208657. #pragma comment (lib, "QTMLClient.lib")
  208658. #endif
  208659. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  208660. #endif
  208661. //==============================================================================
  208662. #if JUCE_LINUX
  208663. /********* Start of inlined file: juce_linux_Files.cpp *********/
  208664. /********* Start of inlined file: linuxincludes.h *********/
  208665. #ifndef __LINUXINCLUDES_JUCEHEADER__
  208666. #define __LINUXINCLUDES_JUCEHEADER__
  208667. // Linux Header Files:
  208668. #include <unistd.h>
  208669. #include <stdlib.h>
  208670. #include <sched.h>
  208671. #include <pthread.h>
  208672. #include <sys/time.h>
  208673. #include <errno.h>
  208674. /* Remove this macro if you're having problems compiling the cpu affinity
  208675. calls (the API for these has changed about quite a bit in various Linux
  208676. versions, and a lot of distros seem to ship with obsolete versions)
  208677. */
  208678. #ifndef SUPPORT_AFFINITIES
  208679. #define SUPPORT_AFFINITIES 1
  208680. #endif
  208681. #endif // __LINUXINCLUDES_JUCEHEADER__
  208682. /********* End of inlined file: linuxincludes.h *********/
  208683. #include <sys/stat.h>
  208684. #include <sys/dir.h>
  208685. #include <sys/ptrace.h>
  208686. #include <sys/vfs.h> // for statfs
  208687. #include <sys/wait.h>
  208688. #include <unistd.h>
  208689. #include <fnmatch.h>
  208690. #include <utime.h>
  208691. #include <pwd.h>
  208692. #include <fcntl.h>
  208693. #define U_ISOFS_SUPER_MAGIC (short) 0x9660 // linux/iso_fs.h
  208694. #define U_MSDOS_SUPER_MAGIC (short) 0x4d44 // linux/msdos_fs.h
  208695. #define U_NFS_SUPER_MAGIC (short) 0x6969 // linux/nfs_fs.h
  208696. #define U_SMB_SUPER_MAGIC (short) 0x517B // linux/smb_fs.h
  208697. BEGIN_JUCE_NAMESPACE
  208698. /*
  208699. Note that a lot of methods that you'd expect to find in this file actually
  208700. live in juce_posix_SharedCode.cpp!
  208701. */
  208702. /********* Start of inlined file: juce_posix_SharedCode.cpp *********/
  208703. /*
  208704. This file contains posix routines that are common to both the Linux and Mac builds.
  208705. It gets included directly in the cpp files for these platforms.
  208706. */
  208707. CriticalSection::CriticalSection() throw()
  208708. {
  208709. pthread_mutexattr_t atts;
  208710. pthread_mutexattr_init (&atts);
  208711. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  208712. pthread_mutex_init (&internal, &atts);
  208713. }
  208714. CriticalSection::~CriticalSection() throw()
  208715. {
  208716. pthread_mutex_destroy (&internal);
  208717. }
  208718. void CriticalSection::enter() const throw()
  208719. {
  208720. pthread_mutex_lock (&internal);
  208721. }
  208722. bool CriticalSection::tryEnter() const throw()
  208723. {
  208724. return pthread_mutex_trylock (&internal) == 0;
  208725. }
  208726. void CriticalSection::exit() const throw()
  208727. {
  208728. pthread_mutex_unlock (&internal);
  208729. }
  208730. struct EventStruct
  208731. {
  208732. pthread_cond_t condition;
  208733. pthread_mutex_t mutex;
  208734. bool triggered;
  208735. };
  208736. WaitableEvent::WaitableEvent() throw()
  208737. {
  208738. EventStruct* const es = new EventStruct();
  208739. es->triggered = false;
  208740. pthread_cond_init (&es->condition, 0);
  208741. pthread_mutex_init (&es->mutex, 0);
  208742. internal = es;
  208743. }
  208744. WaitableEvent::~WaitableEvent() throw()
  208745. {
  208746. EventStruct* const es = (EventStruct*) internal;
  208747. pthread_cond_destroy (&es->condition);
  208748. pthread_mutex_destroy (&es->mutex);
  208749. delete es;
  208750. }
  208751. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  208752. {
  208753. EventStruct* const es = (EventStruct*) internal;
  208754. bool ok = true;
  208755. pthread_mutex_lock (&es->mutex);
  208756. if (! es->triggered)
  208757. {
  208758. if (timeOutMillisecs < 0)
  208759. {
  208760. pthread_cond_wait (&es->condition, &es->mutex);
  208761. }
  208762. else
  208763. {
  208764. struct timespec time;
  208765. #if JUCE_MAC
  208766. time.tv_sec = timeOutMillisecs / 1000;
  208767. time.tv_nsec = (timeOutMillisecs % 1000) * 1000000;
  208768. pthread_cond_timedwait_relative_np (&es->condition, &es->mutex, &time);
  208769. #else
  208770. struct timeval t;
  208771. int timeout = 0;
  208772. gettimeofday (&t, 0);
  208773. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  208774. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  208775. while (time.tv_nsec >= 1000000000)
  208776. {
  208777. time.tv_nsec -= 1000000000;
  208778. time.tv_sec++;
  208779. }
  208780. while (! timeout)
  208781. {
  208782. timeout = pthread_cond_timedwait (&es->condition, &es->mutex, &time);
  208783. if (! timeout)
  208784. // Success
  208785. break;
  208786. if (timeout == EINTR)
  208787. // Go round again
  208788. timeout = 0;
  208789. }
  208790. #endif
  208791. }
  208792. ok = es->triggered;
  208793. }
  208794. es->triggered = false;
  208795. pthread_mutex_unlock (&es->mutex);
  208796. return ok;
  208797. }
  208798. void WaitableEvent::signal() const throw()
  208799. {
  208800. EventStruct* const es = (EventStruct*) internal;
  208801. pthread_mutex_lock (&es->mutex);
  208802. es->triggered = true;
  208803. pthread_cond_broadcast (&es->condition);
  208804. pthread_mutex_unlock (&es->mutex);
  208805. }
  208806. void WaitableEvent::reset() const throw()
  208807. {
  208808. EventStruct* const es = (EventStruct*) internal;
  208809. pthread_mutex_lock (&es->mutex);
  208810. es->triggered = false;
  208811. pthread_mutex_unlock (&es->mutex);
  208812. }
  208813. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  208814. {
  208815. struct timespec time;
  208816. time.tv_sec = millisecs / 1000;
  208817. time.tv_nsec = (millisecs % 1000) * 1000000;
  208818. nanosleep (&time, 0);
  208819. }
  208820. const tchar File::separator = T('/');
  208821. const tchar* File::separatorString = T("/");
  208822. bool juce_copyFile (const String& s, const String& d) throw();
  208823. static bool juce_stat (const String& fileName, struct stat& info) throw()
  208824. {
  208825. return fileName.isNotEmpty()
  208826. && (stat (fileName.toUTF8(), &info) == 0);
  208827. }
  208828. bool juce_isDirectory (const String& fileName) throw()
  208829. {
  208830. struct stat info;
  208831. return fileName.isEmpty()
  208832. || (juce_stat (fileName, info)
  208833. && ((info.st_mode & S_IFDIR) != 0));
  208834. }
  208835. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  208836. {
  208837. if (fileName.isEmpty())
  208838. return false;
  208839. const char* const fileNameUTF8 = fileName.toUTF8();
  208840. bool exists = access (fileNameUTF8, F_OK) == 0;
  208841. if (exists && dontCountDirectories)
  208842. {
  208843. struct stat info;
  208844. const int res = stat (fileNameUTF8, &info);
  208845. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  208846. exists = false;
  208847. }
  208848. return exists;
  208849. }
  208850. int64 juce_getFileSize (const String& fileName) throw()
  208851. {
  208852. struct stat info;
  208853. return juce_stat (fileName, info) ? info.st_size : 0;
  208854. }
  208855. bool juce_canWriteToFile (const String& fileName) throw()
  208856. {
  208857. return access (fileName.toUTF8(), W_OK) == 0;
  208858. }
  208859. bool juce_deleteFile (const String& fileName) throw()
  208860. {
  208861. const char* const fileNameUTF8 = fileName.toUTF8();
  208862. if (juce_isDirectory (fileName))
  208863. return rmdir (fileNameUTF8) == 0;
  208864. else
  208865. return remove (fileNameUTF8) == 0;
  208866. }
  208867. bool juce_moveFile (const String& source, const String& dest) throw()
  208868. {
  208869. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  208870. return true;
  208871. if (juce_canWriteToFile (source)
  208872. && juce_copyFile (source, dest))
  208873. {
  208874. if (juce_deleteFile (source))
  208875. return true;
  208876. juce_deleteFile (dest);
  208877. }
  208878. return false;
  208879. }
  208880. void juce_createDirectory (const String& fileName) throw()
  208881. {
  208882. mkdir (fileName.toUTF8(), 0777);
  208883. }
  208884. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  208885. {
  208886. const char* const fileNameUTF8 = fileName.toUTF8();
  208887. int flags = O_RDONLY;
  208888. if (forWriting)
  208889. {
  208890. if (juce_fileExists (fileName, false))
  208891. {
  208892. const int f = open (fileNameUTF8, O_RDWR, 00644);
  208893. if (f != -1)
  208894. lseek (f, 0, SEEK_END);
  208895. return (void*) f;
  208896. }
  208897. else
  208898. {
  208899. flags = O_RDWR + O_CREAT;
  208900. }
  208901. }
  208902. return (void*) open (fileNameUTF8, flags, 00644);
  208903. }
  208904. void juce_fileClose (void* handle) throw()
  208905. {
  208906. if (handle != 0)
  208907. close ((int) (pointer_sized_int) handle);
  208908. }
  208909. int juce_fileRead (void* handle, void* buffer, int size) throw()
  208910. {
  208911. if (handle != 0)
  208912. return read ((int) (pointer_sized_int) handle, buffer, size);
  208913. return 0;
  208914. }
  208915. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  208916. {
  208917. if (handle != 0)
  208918. return write ((int) (pointer_sized_int) handle, buffer, size);
  208919. return 0;
  208920. }
  208921. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  208922. {
  208923. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  208924. return pos;
  208925. return -1;
  208926. }
  208927. int64 juce_fileGetPosition (void* handle) throw()
  208928. {
  208929. if (handle != 0)
  208930. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  208931. else
  208932. return -1;
  208933. }
  208934. void juce_fileFlush (void* handle) throw()
  208935. {
  208936. if (handle != 0)
  208937. fsync ((int) (pointer_sized_int) handle);
  208938. }
  208939. // if this file doesn't exist, find a parent of it that does..
  208940. static bool doStatFS (const File* file, struct statfs& result) throw()
  208941. {
  208942. File f (*file);
  208943. for (int i = 5; --i >= 0;)
  208944. {
  208945. if (f.exists())
  208946. break;
  208947. f = f.getParentDirectory();
  208948. }
  208949. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  208950. }
  208951. int64 File::getBytesFreeOnVolume() const throw()
  208952. {
  208953. int64 free_space = 0;
  208954. struct statfs buf;
  208955. if (doStatFS (this, buf))
  208956. // Note: this returns space available to non-super user
  208957. free_space = (int64) buf.f_bsize * (int64) buf.f_bavail;
  208958. return free_space;
  208959. }
  208960. const String juce_getVolumeLabel (const String& filenameOnVolume,
  208961. int& volumeSerialNumber) throw()
  208962. {
  208963. // There is no equivalent on Linux
  208964. volumeSerialNumber = 0;
  208965. return String::empty;
  208966. }
  208967. #if JUCE_64BIT
  208968. #define filedesc ((long long) internal)
  208969. #else
  208970. #define filedesc ((int) internal)
  208971. #endif
  208972. InterProcessLock::InterProcessLock (const String& name_) throw()
  208973. : internal (0),
  208974. name (name_),
  208975. reentrancyLevel (0)
  208976. {
  208977. #if JUCE_MAC
  208978. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  208979. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  208980. #else
  208981. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  208982. #endif
  208983. temp.create();
  208984. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  208985. }
  208986. InterProcessLock::~InterProcessLock() throw()
  208987. {
  208988. while (reentrancyLevel > 0)
  208989. this->exit();
  208990. close (filedesc);
  208991. }
  208992. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  208993. {
  208994. if (internal == 0)
  208995. return false;
  208996. if (reentrancyLevel != 0)
  208997. return true;
  208998. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  208999. struct flock fl;
  209000. zerostruct (fl);
  209001. fl.l_whence = SEEK_SET;
  209002. fl.l_type = F_WRLCK;
  209003. for (;;)
  209004. {
  209005. const int result = fcntl (filedesc, F_SETLK, &fl);
  209006. if (result >= 0)
  209007. {
  209008. ++reentrancyLevel;
  209009. return true;
  209010. }
  209011. if (errno != EINTR)
  209012. {
  209013. if (timeOutMillisecs == 0
  209014. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  209015. break;
  209016. Thread::sleep (10);
  209017. }
  209018. }
  209019. return false;
  209020. }
  209021. void InterProcessLock::exit() throw()
  209022. {
  209023. if (reentrancyLevel > 0 && internal != 0)
  209024. {
  209025. --reentrancyLevel;
  209026. struct flock fl;
  209027. zerostruct (fl);
  209028. fl.l_whence = SEEK_SET;
  209029. fl.l_type = F_UNLCK;
  209030. for (;;)
  209031. {
  209032. const int result = fcntl (filedesc, F_SETLKW, &fl);
  209033. if (result >= 0 || errno != EINTR)
  209034. break;
  209035. }
  209036. }
  209037. }
  209038. /********* End of inlined file: juce_posix_SharedCode.cpp *********/
  209039. static File executableFile;
  209040. void juce_getFileTimes (const String& fileName,
  209041. int64& modificationTime,
  209042. int64& accessTime,
  209043. int64& creationTime) throw()
  209044. {
  209045. modificationTime = 0;
  209046. accessTime = 0;
  209047. creationTime = 0;
  209048. struct stat info;
  209049. const int res = stat (fileName.toUTF8(), &info);
  209050. if (res == 0)
  209051. {
  209052. modificationTime = (int64) info.st_mtime * 1000;
  209053. accessTime = (int64) info.st_atime * 1000;
  209054. creationTime = (int64) info.st_ctime * 1000;
  209055. }
  209056. }
  209057. bool juce_setFileTimes (const String& fileName,
  209058. int64 modificationTime,
  209059. int64 accessTime,
  209060. int64 creationTime) throw()
  209061. {
  209062. struct utimbuf times;
  209063. times.actime = (time_t) (accessTime / 1000);
  209064. times.modtime = (time_t) (modificationTime / 1000);
  209065. return utime (fileName.toUTF8(), &times) == 0;
  209066. }
  209067. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  209068. {
  209069. struct stat info;
  209070. const int res = stat (fileName.toUTF8(), &info);
  209071. if (res != 0)
  209072. return false;
  209073. info.st_mode &= 0777; // Just permissions
  209074. if( isReadOnly )
  209075. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  209076. else
  209077. // Give everybody write permission?
  209078. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  209079. return chmod (fileName.toUTF8(), info.st_mode) == 0;
  209080. }
  209081. bool juce_copyFile (const String& s, const String& d) throw()
  209082. {
  209083. const File source (s), dest (d);
  209084. FileInputStream* in = source.createInputStream();
  209085. bool ok = false;
  209086. if (in != 0)
  209087. {
  209088. if (dest.deleteFile())
  209089. {
  209090. FileOutputStream* const out = dest.createOutputStream();
  209091. if (out != 0)
  209092. {
  209093. const int bytesCopied = out->writeFromInputStream (*in, -1);
  209094. delete out;
  209095. ok = (bytesCopied == source.getSize());
  209096. if (! ok)
  209097. dest.deleteFile();
  209098. }
  209099. }
  209100. delete in;
  209101. }
  209102. return ok;
  209103. }
  209104. const StringArray juce_getFileSystemRoots() throw()
  209105. {
  209106. StringArray s;
  209107. s.add (T("/"));
  209108. return s;
  209109. }
  209110. bool File::isOnCDRomDrive() const throw()
  209111. {
  209112. struct statfs buf;
  209113. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  209114. return (buf.f_type == U_ISOFS_SUPER_MAGIC);
  209115. // Assume not if this fails for some reason
  209116. return false;
  209117. }
  209118. bool File::isOnHardDisk() const throw()
  209119. {
  209120. struct statfs buf;
  209121. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  209122. {
  209123. switch (buf.f_type)
  209124. {
  209125. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  209126. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  209127. case U_NFS_SUPER_MAGIC: // Network NFS
  209128. case U_SMB_SUPER_MAGIC: // Network Samba
  209129. return false;
  209130. default:
  209131. // Assume anything else is a hard-disk (but note it could
  209132. // be a RAM disk. There isn't a good way of determining
  209133. // this for sure)
  209134. return true;
  209135. }
  209136. }
  209137. // Assume so if this fails for some reason
  209138. return true;
  209139. }
  209140. bool File::isHidden() const throw()
  209141. {
  209142. return getFileName().startsWithChar (T('.'));
  209143. }
  209144. const File File::getSpecialLocation (const SpecialLocationType type)
  209145. {
  209146. switch (type)
  209147. {
  209148. case userHomeDirectory:
  209149. {
  209150. const char* homeDir = getenv ("HOME");
  209151. if (homeDir == 0)
  209152. {
  209153. struct passwd* const pw = getpwuid (getuid());
  209154. if (pw != 0)
  209155. homeDir = pw->pw_dir;
  209156. }
  209157. return File (String::fromUTF8 ((const uint8*) homeDir));
  209158. }
  209159. case userDocumentsDirectory:
  209160. case userMusicDirectory:
  209161. case userMoviesDirectory:
  209162. case userApplicationDataDirectory:
  209163. return File ("~");
  209164. case userDesktopDirectory:
  209165. return File ("~/Desktop");
  209166. case commonApplicationDataDirectory:
  209167. return File ("/var");
  209168. case globalApplicationsDirectory:
  209169. return File ("/usr");
  209170. case tempDirectory:
  209171. {
  209172. File tmp ("/var/tmp");
  209173. if (! tmp.isDirectory())
  209174. {
  209175. tmp = T("/tmp");
  209176. if (! tmp.isDirectory())
  209177. tmp = File::getCurrentWorkingDirectory();
  209178. }
  209179. return tmp;
  209180. }
  209181. case currentExecutableFile:
  209182. case currentApplicationFile:
  209183. // if this fails, it's probably because juce_setCurrentExecutableFileName()
  209184. // was never called to set the filename - this should be done by the juce
  209185. // main() function, so maybe you've hacked it to use your own custom main()?
  209186. jassert (executableFile.exists());
  209187. return executableFile;
  209188. default:
  209189. jassertfalse // unknown type?
  209190. break;
  209191. }
  209192. return File::nonexistent;
  209193. }
  209194. void juce_setCurrentExecutableFileName (const String& filename) throw()
  209195. {
  209196. executableFile = File::getCurrentWorkingDirectory().getChildFile (filename);
  209197. }
  209198. const File File::getCurrentWorkingDirectory() throw()
  209199. {
  209200. char buf [2048];
  209201. getcwd (buf, sizeof(buf));
  209202. return File (String::fromUTF8 ((const uint8*) buf));
  209203. }
  209204. bool File::setAsCurrentWorkingDirectory() const throw()
  209205. {
  209206. return chdir (getFullPathName().toUTF8()) == 0;
  209207. }
  209208. struct FindFileStruct
  209209. {
  209210. String parentDir, wildCard;
  209211. DIR* dir;
  209212. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  209213. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  209214. {
  209215. const char* const wildcardUTF8 = wildCard.toUTF8();
  209216. for (;;)
  209217. {
  209218. struct dirent* const de = readdir (dir);
  209219. if (de == 0)
  209220. break;
  209221. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  209222. {
  209223. result = String::fromUTF8 ((const uint8*) de->d_name);
  209224. const String path (parentDir + result);
  209225. if (isDir != 0 || fileSize != 0)
  209226. {
  209227. struct stat info;
  209228. const bool statOk = (stat (path.toUTF8(), &info) == 0);
  209229. if (isDir != 0)
  209230. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  209231. if (isHidden != 0)
  209232. *isHidden = (de->d_name[0] == '.');
  209233. if (fileSize != 0)
  209234. *fileSize = statOk ? info.st_size : 0;
  209235. }
  209236. if (modTime != 0 || creationTime != 0)
  209237. {
  209238. int64 m, a, c;
  209239. juce_getFileTimes (path, m, a, c);
  209240. if (modTime != 0)
  209241. *modTime = m;
  209242. if (creationTime != 0)
  209243. *creationTime = c;
  209244. }
  209245. if (isReadOnly != 0)
  209246. *isReadOnly = ! juce_canWriteToFile (path);
  209247. return true;
  209248. }
  209249. }
  209250. return false;
  209251. }
  209252. };
  209253. // returns 0 on failure
  209254. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  209255. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  209256. Time* creationTime, bool* isReadOnly) throw()
  209257. {
  209258. DIR* d = opendir (directory.toUTF8());
  209259. if (d != 0)
  209260. {
  209261. FindFileStruct* ff = new FindFileStruct();
  209262. ff->parentDir = directory;
  209263. if (!ff->parentDir.endsWithChar (File::separator))
  209264. ff->parentDir += File::separator;
  209265. ff->wildCard = wildCard;
  209266. if (wildCard == T("*.*"))
  209267. ff->wildCard = T("*");
  209268. ff->dir = d;
  209269. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  209270. {
  209271. return ff;
  209272. }
  209273. else
  209274. {
  209275. firstResultFile = String::empty;
  209276. isDir = false;
  209277. isHidden = false;
  209278. closedir (d);
  209279. delete ff;
  209280. }
  209281. }
  209282. return 0;
  209283. }
  209284. bool juce_findFileNext (void* handle, String& resultFile,
  209285. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  209286. {
  209287. FindFileStruct* const ff = (FindFileStruct*) handle;
  209288. if (ff != 0)
  209289. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  209290. return false;
  209291. }
  209292. void juce_findFileClose (void* handle) throw()
  209293. {
  209294. FindFileStruct* const ff = (FindFileStruct*) handle;
  209295. if (ff != 0)
  209296. {
  209297. closedir (ff->dir);
  209298. delete ff;
  209299. }
  209300. }
  209301. bool juce_launchFile (const String& fileName,
  209302. const String& parameters) throw()
  209303. {
  209304. String cmdString (fileName);
  209305. cmdString << " " << parameters;
  209306. if (URL::isProbablyAWebsiteURL (cmdString) || URL::isProbablyAnEmailAddress (cmdString))
  209307. {
  209308. // create a command that tries to launch a bunch of likely browsers
  209309. const char* const browserNames[] = { "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  209310. StringArray cmdLines;
  209311. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  209312. cmdLines.add (String (browserNames[i]) + T(" ") + cmdString.trim().quoted());
  209313. cmdString = cmdLines.joinIntoString (T(" || "));
  209314. }
  209315. char* const argv[4] = { "/bin/sh", "-c", (char*) cmdString.toUTF8(), 0 };
  209316. const int cpid = fork();
  209317. if (cpid == 0)
  209318. {
  209319. setsid();
  209320. // Child process
  209321. execve (argv[0], argv, environ);
  209322. exit (0);
  209323. }
  209324. return cpid >= 0;
  209325. }
  209326. END_JUCE_NAMESPACE
  209327. /********* End of inlined file: juce_linux_Files.cpp *********/
  209328. /********* Start of inlined file: juce_linux_NamedPipe.cpp *********/
  209329. /********* Start of inlined file: juce_mac_NamedPipe.cpp *********/
  209330. #include <sys/stat.h>
  209331. #include <sys/dir.h>
  209332. #include <fcntl.h>
  209333. // As well as being for the mac, this file is included by the linux build.
  209334. #if ! JUCE_MAC
  209335. #include <sys/wait.h>
  209336. #include <errno.h>
  209337. #include <unistd.h>
  209338. #endif
  209339. BEGIN_JUCE_NAMESPACE
  209340. struct NamedPipeInternal
  209341. {
  209342. String pipeInName, pipeOutName;
  209343. int pipeIn, pipeOut;
  209344. bool volatile createdPipe, blocked, stopReadOperation;
  209345. static void signalHandler (int) {}
  209346. };
  209347. void NamedPipe::cancelPendingReads()
  209348. {
  209349. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  209350. {
  209351. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  209352. intern->stopReadOperation = true;
  209353. char buffer [1] = { 0 };
  209354. ::write (intern->pipeIn, buffer, 1);
  209355. int timeout = 2000;
  209356. while (intern->blocked && --timeout >= 0)
  209357. Thread::sleep (2);
  209358. intern->stopReadOperation = false;
  209359. }
  209360. }
  209361. void NamedPipe::close()
  209362. {
  209363. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  209364. if (intern != 0)
  209365. {
  209366. internal = 0;
  209367. if (intern->pipeIn != -1)
  209368. ::close (intern->pipeIn);
  209369. if (intern->pipeOut != -1)
  209370. ::close (intern->pipeOut);
  209371. if (intern->createdPipe)
  209372. {
  209373. unlink (intern->pipeInName);
  209374. unlink (intern->pipeOutName);
  209375. }
  209376. delete intern;
  209377. }
  209378. }
  209379. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  209380. {
  209381. close();
  209382. NamedPipeInternal* const intern = new NamedPipeInternal();
  209383. internal = intern;
  209384. intern->createdPipe = createPipe;
  209385. intern->blocked = false;
  209386. intern->stopReadOperation = false;
  209387. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  209388. siginterrupt (SIGPIPE, 1);
  209389. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  209390. intern->pipeInName = pipePath + T("_in");
  209391. intern->pipeOutName = pipePath + T("_out");
  209392. intern->pipeIn = -1;
  209393. intern->pipeOut = -1;
  209394. if (createPipe)
  209395. {
  209396. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  209397. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  209398. {
  209399. delete intern;
  209400. internal = 0;
  209401. return false;
  209402. }
  209403. }
  209404. return true;
  209405. }
  209406. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  209407. {
  209408. int bytesRead = -1;
  209409. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  209410. if (intern != 0)
  209411. {
  209412. intern->blocked = true;
  209413. if (intern->pipeIn == -1)
  209414. {
  209415. if (intern->createdPipe)
  209416. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  209417. else
  209418. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  209419. if (intern->pipeIn == -1)
  209420. {
  209421. intern->blocked = false;
  209422. return -1;
  209423. }
  209424. }
  209425. bytesRead = 0;
  209426. char* p = (char*) destBuffer;
  209427. while (bytesRead < maxBytesToRead)
  209428. {
  209429. const int bytesThisTime = maxBytesToRead - bytesRead;
  209430. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  209431. if (numRead <= 0 || intern->stopReadOperation)
  209432. {
  209433. bytesRead = -1;
  209434. break;
  209435. }
  209436. bytesRead += numRead;
  209437. p += bytesRead;
  209438. }
  209439. intern->blocked = false;
  209440. }
  209441. return bytesRead;
  209442. }
  209443. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  209444. {
  209445. int bytesWritten = -1;
  209446. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  209447. if (intern != 0)
  209448. {
  209449. if (intern->pipeOut == -1)
  209450. {
  209451. if (intern->createdPipe)
  209452. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  209453. else
  209454. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  209455. if (intern->pipeOut == -1)
  209456. {
  209457. return -1;
  209458. }
  209459. }
  209460. const char* p = (const char*) sourceBuffer;
  209461. bytesWritten = 0;
  209462. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  209463. while (bytesWritten < numBytesToWrite
  209464. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  209465. {
  209466. const int bytesThisTime = numBytesToWrite - bytesWritten;
  209467. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  209468. if (numWritten <= 0)
  209469. {
  209470. bytesWritten = -1;
  209471. break;
  209472. }
  209473. bytesWritten += numWritten;
  209474. p += bytesWritten;
  209475. }
  209476. }
  209477. return bytesWritten;
  209478. }
  209479. END_JUCE_NAMESPACE
  209480. /********* End of inlined file: juce_mac_NamedPipe.cpp *********/
  209481. /********* End of inlined file: juce_linux_NamedPipe.cpp *********/
  209482. /********* Start of inlined file: juce_linux_Network.cpp *********/
  209483. #include <netdb.h>
  209484. #include <arpa/inet.h>
  209485. #include <netinet/in.h>
  209486. #include <sys/types.h>
  209487. #include <sys/ioctl.h>
  209488. #include <sys/socket.h>
  209489. #include <sys/wait.h>
  209490. #include <linux/if.h>
  209491. BEGIN_JUCE_NAMESPACE
  209492. // we'll borrow the mac's socket-based http streaming code..
  209493. /********* Start of inlined file: juce_mac_HTTPStream.h *********/
  209494. // (This file gets included by the mac + linux networking code)
  209495. /** A HTTP input stream that uses sockets.
  209496. */
  209497. class JUCE_HTTPSocketStream
  209498. {
  209499. public:
  209500. JUCE_HTTPSocketStream()
  209501. : readPosition (0),
  209502. socketHandle (-1),
  209503. levelsOfRedirection (0),
  209504. timeoutSeconds (15)
  209505. {
  209506. }
  209507. ~JUCE_HTTPSocketStream()
  209508. {
  209509. closeSocket();
  209510. }
  209511. bool open (const String& url,
  209512. const String& headers,
  209513. const MemoryBlock& postData,
  209514. const bool isPost,
  209515. URL::OpenStreamProgressCallback* callback,
  209516. void* callbackContext,
  209517. int timeOutMs)
  209518. {
  209519. closeSocket();
  209520. uint32 timeOutTime = Time::getMillisecondCounter();
  209521. if (timeOutMs == 0)
  209522. timeOutTime += 60000;
  209523. else if (timeOutMs < 0)
  209524. timeOutTime = 0xffffffff;
  209525. else
  209526. timeOutTime += timeOutMs;
  209527. String hostName, hostPath;
  209528. int hostPort;
  209529. if (! decomposeURL (url, hostName, hostPath, hostPort))
  209530. return false;
  209531. const struct hostent* host = 0;
  209532. int port = 0;
  209533. String proxyName, proxyPath;
  209534. int proxyPort = 0;
  209535. String proxyURL (getenv ("http_proxy"));
  209536. if (proxyURL.startsWithIgnoreCase (T("http://")))
  209537. {
  209538. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  209539. return false;
  209540. host = gethostbyname ((const char*) proxyName.toUTF8());
  209541. port = proxyPort;
  209542. }
  209543. else
  209544. {
  209545. host = gethostbyname ((const char*) hostName.toUTF8());
  209546. port = hostPort;
  209547. }
  209548. if (host == 0)
  209549. return false;
  209550. struct sockaddr_in address;
  209551. zerostruct (address);
  209552. memcpy ((void*) &address.sin_addr, (const void*) host->h_addr, host->h_length);
  209553. address.sin_family = host->h_addrtype;
  209554. address.sin_port = htons (port);
  209555. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  209556. if (socketHandle == -1)
  209557. return false;
  209558. int receiveBufferSize = 16384;
  209559. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  209560. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  209561. #if JUCE_MAC
  209562. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  209563. #endif
  209564. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  209565. {
  209566. closeSocket();
  209567. return false;
  209568. }
  209569. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  209570. proxyName, proxyPort,
  209571. hostPath, url,
  209572. headers, postData,
  209573. isPost));
  209574. int totalHeaderSent = 0;
  209575. while (totalHeaderSent < requestHeader.getSize())
  209576. {
  209577. if (Time::getMillisecondCounter() > timeOutTime)
  209578. {
  209579. closeSocket();
  209580. return false;
  209581. }
  209582. const int numToSend = jmin (1024, requestHeader.getSize() - totalHeaderSent);
  209583. if (send (socketHandle,
  209584. ((const char*) requestHeader.getData()) + totalHeaderSent,
  209585. numToSend, 0)
  209586. != numToSend)
  209587. {
  209588. closeSocket();
  209589. return false;
  209590. }
  209591. totalHeaderSent += numToSend;
  209592. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  209593. {
  209594. closeSocket();
  209595. return false;
  209596. }
  209597. }
  209598. const String responseHeader (readResponse (timeOutTime));
  209599. if (responseHeader.isNotEmpty())
  209600. {
  209601. //DBG (responseHeader);
  209602. StringArray lines;
  209603. lines.addLines (responseHeader);
  209604. // NB - using charToString() here instead of just T(" "), because that was
  209605. // causing a mysterious gcc internal compiler error...
  209606. const int statusCode = responseHeader.fromFirstOccurrenceOf (String::charToString (T(' ')), false, false)
  209607. .substring (0, 3)
  209608. .getIntValue();
  209609. //int contentLength = findHeaderItem (lines, T("Content-Length:")).getIntValue();
  209610. //bool isChunked = findHeaderItem (lines, T("Transfer-Encoding:")).equalsIgnoreCase ("chunked");
  209611. String location (findHeaderItem (lines, T("Location:")));
  209612. if (statusCode >= 300 && statusCode < 400
  209613. && location.isNotEmpty())
  209614. {
  209615. if (! location.startsWithIgnoreCase (T("http://")))
  209616. location = T("http://") + location;
  209617. if (levelsOfRedirection++ < 3)
  209618. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  209619. }
  209620. else
  209621. {
  209622. levelsOfRedirection = 0;
  209623. return true;
  209624. }
  209625. }
  209626. closeSocket();
  209627. return false;
  209628. }
  209629. int read (void* buffer, int bytesToRead)
  209630. {
  209631. fd_set readbits;
  209632. FD_ZERO (&readbits);
  209633. FD_SET (socketHandle, &readbits);
  209634. struct timeval tv;
  209635. tv.tv_sec = timeoutSeconds;
  209636. tv.tv_usec = 0;
  209637. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  209638. return 0; // (timeout)
  209639. const int bytesRead = jmax (0, recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  209640. readPosition += bytesRead;
  209641. return bytesRead;
  209642. }
  209643. int readPosition;
  209644. juce_UseDebuggingNewOperator
  209645. private:
  209646. int socketHandle, levelsOfRedirection;
  209647. const int timeoutSeconds;
  209648. void closeSocket()
  209649. {
  209650. if (socketHandle >= 0)
  209651. close (socketHandle);
  209652. socketHandle = -1;
  209653. }
  209654. const MemoryBlock createRequestHeader (const String& hostName,
  209655. const int hostPort,
  209656. const String& proxyName,
  209657. const int proxyPort,
  209658. const String& hostPath,
  209659. const String& originalURL,
  209660. const String& headers,
  209661. const MemoryBlock& postData,
  209662. const bool isPost)
  209663. {
  209664. String header (isPost ? "POST " : "GET ");
  209665. if (proxyName.isEmpty())
  209666. {
  209667. header << hostPath << " HTTP/1.0\r\nHost: "
  209668. << hostName << ':' << hostPort;
  209669. }
  209670. else
  209671. {
  209672. header << originalURL << " HTTP/1.0\r\nHost: "
  209673. << proxyName << ':' << proxyPort;
  209674. }
  209675. header << "\r\nUser-Agent: JUCE/"
  209676. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  209677. << "\r\nConnection: Close\r\nContent-Length: "
  209678. << postData.getSize() << "\r\n"
  209679. << headers << "\r\n";
  209680. MemoryBlock mb;
  209681. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  209682. mb.append (postData.getData(), postData.getSize());
  209683. return mb;
  209684. }
  209685. const String readResponse (const uint32 timeOutTime)
  209686. {
  209687. int bytesRead = 0, numConsecutiveLFs = 0;
  209688. MemoryBlock buffer (1024, true);
  209689. while (numConsecutiveLFs < 2 && bytesRead < 32768
  209690. && Time::getMillisecondCounter() <= timeOutTime)
  209691. {
  209692. fd_set readbits;
  209693. FD_ZERO (&readbits);
  209694. FD_SET (socketHandle, &readbits);
  209695. struct timeval tv;
  209696. tv.tv_sec = timeoutSeconds;
  209697. tv.tv_usec = 0;
  209698. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  209699. return String::empty; // (timeout)
  209700. buffer.ensureSize (bytesRead + 8, true);
  209701. char* const dest = (char*) buffer.getData() + bytesRead;
  209702. if (recv (socketHandle, dest, 1, 0) == -1)
  209703. return String::empty;
  209704. const char lastByte = *dest;
  209705. ++bytesRead;
  209706. if (lastByte == '\n')
  209707. ++numConsecutiveLFs;
  209708. else if (lastByte != '\r')
  209709. numConsecutiveLFs = 0;
  209710. }
  209711. const String header (String::fromUTF8 ((const uint8*) buffer.getData()));
  209712. if (header.startsWithIgnoreCase (T("HTTP/")))
  209713. return header.trimEnd();
  209714. return String::empty;
  209715. }
  209716. static bool decomposeURL (const String& url,
  209717. String& host, String& path, int& port)
  209718. {
  209719. if (! url.startsWithIgnoreCase (T("http://")))
  209720. return false;
  209721. const int nextSlash = url.indexOfChar (7, '/');
  209722. int nextColon = url.indexOfChar (7, ':');
  209723. if (nextColon > nextSlash && nextSlash > 0)
  209724. nextColon = -1;
  209725. if (nextColon >= 0)
  209726. {
  209727. host = url.substring (7, nextColon);
  209728. if (nextSlash >= 0)
  209729. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  209730. else
  209731. port = url.substring (nextColon + 1).getIntValue();
  209732. }
  209733. else
  209734. {
  209735. port = 80;
  209736. if (nextSlash >= 0)
  209737. host = url.substring (7, nextSlash);
  209738. else
  209739. host = url.substring (7);
  209740. }
  209741. if (nextSlash >= 0)
  209742. path = url.substring (nextSlash);
  209743. else
  209744. path = T("/");
  209745. return true;
  209746. }
  209747. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  209748. {
  209749. for (int i = 0; i < lines.size(); ++i)
  209750. if (lines[i].startsWithIgnoreCase (itemName))
  209751. return lines[i].substring (itemName.length()).trim();
  209752. return String::empty;
  209753. }
  209754. };
  209755. bool juce_isOnLine()
  209756. {
  209757. return true;
  209758. }
  209759. void* juce_openInternetFile (const String& url,
  209760. const String& headers,
  209761. const MemoryBlock& postData,
  209762. const bool isPost,
  209763. URL::OpenStreamProgressCallback* callback,
  209764. void* callbackContext,
  209765. int timeOutMs)
  209766. {
  209767. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  209768. if (s->open (url, headers, postData, isPost,
  209769. callback, callbackContext, timeOutMs))
  209770. return s;
  209771. delete s;
  209772. return 0;
  209773. }
  209774. void juce_closeInternetFile (void* handle)
  209775. {
  209776. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  209777. if (s != 0)
  209778. delete s;
  209779. }
  209780. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  209781. {
  209782. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  209783. if (s != 0)
  209784. return s->read (buffer, bytesToRead);
  209785. return 0;
  209786. }
  209787. int juce_seekInInternetFile (void* handle, int newPosition)
  209788. {
  209789. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  209790. if (s != 0)
  209791. return s->readPosition;
  209792. return 0;
  209793. }
  209794. /********* End of inlined file: juce_mac_HTTPStream.h *********/
  209795. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  209796. {
  209797. int numResults = 0;
  209798. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  209799. if (s != -1)
  209800. {
  209801. char buf [1024];
  209802. struct ifconf ifc;
  209803. ifc.ifc_len = sizeof (buf);
  209804. ifc.ifc_buf = buf;
  209805. ioctl (s, SIOCGIFCONF, &ifc);
  209806. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  209807. {
  209808. struct ifreq ifr;
  209809. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  209810. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  209811. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  209812. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  209813. && numResults < maxNum)
  209814. {
  209815. int64 a = 0;
  209816. for (int j = 6; --j >= 0;)
  209817. a = (a << 8) | ifr.ifr_hwaddr.sa_data[j];
  209818. *addresses++ = a;
  209819. ++numResults;
  209820. }
  209821. }
  209822. close (s);
  209823. }
  209824. return numResults;
  209825. }
  209826. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  209827. const String& emailSubject,
  209828. const String& bodyText,
  209829. const StringArray& filesToAttach)
  209830. {
  209831. jassertfalse // xxx todo
  209832. return false;
  209833. }
  209834. END_JUCE_NAMESPACE
  209835. /********* End of inlined file: juce_linux_Network.cpp *********/
  209836. /********* Start of inlined file: juce_linux_SystemStats.cpp *********/
  209837. #include <sys/sysinfo.h>
  209838. #include <dlfcn.h>
  209839. #ifndef CPU_ISSET
  209840. #undef SUPPORT_AFFINITIES
  209841. #endif
  209842. BEGIN_JUCE_NAMESPACE
  209843. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel, int* extFeatures) throw()
  209844. {
  209845. unsigned int cpu = 0;
  209846. unsigned int ext = 0;
  209847. unsigned int family = 0;
  209848. unsigned int dummy = 0;
  209849. #if JUCE_64BIT
  209850. __asm__ ("cpuid"
  209851. : "=a" (family), "=b" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  209852. #else
  209853. __asm__ ("push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx"
  209854. : "=a" (family), "=D" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  209855. #endif
  209856. if (familyModel != 0)
  209857. *familyModel = family;
  209858. if (extFeatures != 0)
  209859. *extFeatures = ext;
  209860. return cpu;
  209861. }*/
  209862. void Logger::outputDebugString (const String& text) throw()
  209863. {
  209864. fprintf (stdout, text.toUTF8());
  209865. fprintf (stdout, "\n");
  209866. }
  209867. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  209868. {
  209869. String text;
  209870. va_list args;
  209871. va_start (args, format);
  209872. text.vprintf(format, args);
  209873. outputDebugString(text);
  209874. }
  209875. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  209876. {
  209877. return Linux;
  209878. }
  209879. const String SystemStats::getOperatingSystemName() throw()
  209880. {
  209881. return T("Linux");
  209882. }
  209883. bool SystemStats::isOperatingSystem64Bit() throw()
  209884. {
  209885. #if JUCE_64BIT
  209886. return true;
  209887. #else
  209888. //xxx not sure how to find this out?..
  209889. return false;
  209890. #endif
  209891. }
  209892. static const String getCpuInfo (const char* key, bool lastOne = false) throw()
  209893. {
  209894. String info;
  209895. char buf [256];
  209896. FILE* f = fopen ("/proc/cpuinfo", "r");
  209897. while (f != 0 && fgets (buf, sizeof(buf), f))
  209898. {
  209899. if (strncmp (buf, key, strlen (key)) == 0)
  209900. {
  209901. char* p = buf;
  209902. while (*p && *p != '\n')
  209903. ++p;
  209904. if (*p != 0)
  209905. *p = 0;
  209906. p = buf;
  209907. while (*p != 0 && *p != ':')
  209908. ++p;
  209909. if (*p != 0 && *(p + 1) != 0)
  209910. info = p + 2;
  209911. if (! lastOne)
  209912. break;
  209913. }
  209914. }
  209915. fclose (f);
  209916. return info;
  209917. }
  209918. bool SystemStats::hasMMX() throw()
  209919. {
  209920. return getCpuInfo ("flags").contains (T("mmx"));
  209921. }
  209922. bool SystemStats::hasSSE() throw()
  209923. {
  209924. return getCpuInfo ("flags").contains (T("sse"));
  209925. }
  209926. bool SystemStats::hasSSE2() throw()
  209927. {
  209928. return getCpuInfo ("flags").contains (T("sse2"));
  209929. }
  209930. bool SystemStats::has3DNow() throw()
  209931. {
  209932. return getCpuInfo ("flags").contains (T("3dnow"));
  209933. }
  209934. const String SystemStats::getCpuVendor() throw()
  209935. {
  209936. return getCpuInfo ("vendor_id");
  209937. }
  209938. int SystemStats::getCpuSpeedInMegaherz() throw()
  209939. {
  209940. const String speed (getCpuInfo ("cpu MHz"));
  209941. return (int) (speed.getFloatValue() + 0.5f);
  209942. }
  209943. int SystemStats::getMemorySizeInMegabytes() throw()
  209944. {
  209945. struct sysinfo sysi;
  209946. if (sysinfo (&sysi) == 0)
  209947. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  209948. return 0;
  209949. }
  209950. uint32 juce_millisecondsSinceStartup() throw()
  209951. {
  209952. static unsigned int calibrate = 0;
  209953. static bool calibrated = false;
  209954. timeval t;
  209955. unsigned int ret = 0;
  209956. if (! gettimeofday (&t, 0))
  209957. {
  209958. if (! calibrated)
  209959. {
  209960. struct sysinfo sysi;
  209961. if (sysinfo (&sysi) == 0)
  209962. // Safe to assume system was not brought up earlier than 1970!
  209963. calibrate = t.tv_sec - sysi.uptime;
  209964. calibrated = true;
  209965. }
  209966. ret = 1000 * (t.tv_sec - calibrate) + (t.tv_usec / 1000);
  209967. }
  209968. return ret;
  209969. }
  209970. double Time::getMillisecondCounterHiRes() throw()
  209971. {
  209972. return getHighResolutionTicks() * 0.001;
  209973. }
  209974. int64 Time::getHighResolutionTicks() throw()
  209975. {
  209976. timeval t;
  209977. if (gettimeofday (&t, 0))
  209978. return 0;
  209979. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  209980. }
  209981. int64 Time::getHighResolutionTicksPerSecond() throw()
  209982. {
  209983. // Microseconds
  209984. return 1000000;
  209985. }
  209986. bool Time::setSystemTimeToThisTime() const throw()
  209987. {
  209988. timeval t;
  209989. t.tv_sec = millisSinceEpoch % 1000000;
  209990. t.tv_usec = millisSinceEpoch - t.tv_sec;
  209991. return settimeofday (&t, NULL) ? false : true;
  209992. }
  209993. int SystemStats::getPageSize() throw()
  209994. {
  209995. static int systemPageSize = 0;
  209996. if (systemPageSize == 0)
  209997. systemPageSize = sysconf (_SC_PAGESIZE);
  209998. return systemPageSize;
  209999. }
  210000. int SystemStats::getNumCpus() throw()
  210001. {
  210002. const int lastCpu = getCpuInfo ("processor", true).getIntValue();
  210003. return lastCpu + 1;
  210004. }
  210005. void SystemStats::initialiseStats() throw()
  210006. {
  210007. // Process starts off as root when running suid
  210008. Process::lowerPrivilege();
  210009. String s (SystemStats::getJUCEVersion());
  210010. }
  210011. void PlatformUtilities::fpuReset()
  210012. {
  210013. }
  210014. END_JUCE_NAMESPACE
  210015. /********* End of inlined file: juce_linux_SystemStats.cpp *********/
  210016. /********* Start of inlined file: juce_linux_Threads.cpp *********/
  210017. #include <dlfcn.h>
  210018. #include <sys/file.h>
  210019. #include <sys/types.h>
  210020. #include <sys/ptrace.h>
  210021. BEGIN_JUCE_NAMESPACE
  210022. /*
  210023. Note that a lot of methods that you'd expect to find in this file actually
  210024. live in juce_posix_SharedCode.cpp!
  210025. */
  210026. #ifndef CPU_ISSET
  210027. #undef SUPPORT_AFFINITIES
  210028. #endif
  210029. void JUCE_API juce_threadEntryPoint (void*);
  210030. void* threadEntryProc (void* value) throw()
  210031. {
  210032. // New threads start off as root when running suid
  210033. Process::lowerPrivilege();
  210034. juce_threadEntryPoint (value);
  210035. return 0;
  210036. }
  210037. void* juce_createThread (void* userData) throw()
  210038. {
  210039. pthread_t handle = 0;
  210040. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  210041. {
  210042. pthread_detach (handle);
  210043. return (void*)handle;
  210044. }
  210045. return 0;
  210046. }
  210047. void juce_killThread (void* handle) throw()
  210048. {
  210049. if (handle != 0)
  210050. pthread_cancel ((pthread_t)handle);
  210051. }
  210052. void juce_setCurrentThreadName (const String& /*name*/) throw()
  210053. {
  210054. }
  210055. int Thread::getCurrentThreadId() throw()
  210056. {
  210057. return (int) pthread_self();
  210058. }
  210059. /*
  210060. * This is all a bit non-ideal... the trouble is that on Linux you
  210061. * need to call setpriority to affect the dynamic priority for
  210062. * non-realtime processes, but this requires the pid, which is not
  210063. * accessible from the pthread_t. We could get it by calling getpid
  210064. * once each thread has started, but then we would need a list of
  210065. * running threads etc etc.
  210066. * Also there is no such thing as IDLE priority on Linux.
  210067. * For the moment, map idle, low and normal process priorities to
  210068. * SCHED_OTHER, with the thread priority ignored for these classes.
  210069. * Map high priority processes to the lower half of the SCHED_RR
  210070. * range, and realtime to the upper half
  210071. */
  210072. // priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  210073. // priority of the current thread
  210074. void juce_setThreadPriority (void* handle, int priority) throw()
  210075. {
  210076. struct sched_param param;
  210077. int policy, maxp, minp, pri;
  210078. if (handle == 0)
  210079. handle = (void*) pthread_self();
  210080. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  210081. && policy != SCHED_OTHER)
  210082. {
  210083. minp = sched_get_priority_min(policy);
  210084. maxp = sched_get_priority_max(policy);
  210085. pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  210086. if (param.__sched_priority >= (minp + (maxp - minp) / 2))
  210087. // Realtime process priority
  210088. param.__sched_priority = minp + ((maxp - minp) / 2) + pri;
  210089. else
  210090. // High process priority
  210091. param.__sched_priority = minp + pri;
  210092. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  210093. pthread_setschedparam ((pthread_t) handle, policy, &param);
  210094. }
  210095. }
  210096. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  210097. {
  210098. #if SUPPORT_AFFINITIES
  210099. cpu_set_t affinity;
  210100. CPU_ZERO (&affinity);
  210101. for (int i = 0; i < 32; ++i)
  210102. if ((affinityMask & (1 << i)) != 0)
  210103. CPU_SET (i, &affinity);
  210104. /*
  210105. N.B. If this line causes a compile error, then you've probably not got the latest
  210106. version of glibc installed.
  210107. If you don't want to update your copy of glibc and don't care about cpu affinities,
  210108. then you can just disable all this stuff by removing the SUPPORT_AFFINITIES macro
  210109. from the linuxincludes.h file.
  210110. */
  210111. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  210112. sched_yield();
  210113. #else
  210114. /* affinities aren't supported because either the appropriate header files weren't found,
  210115. or the SUPPORT_AFFINITIES macro was turned off in linuxheaders.h
  210116. */
  210117. jassertfalse
  210118. #endif
  210119. }
  210120. void Thread::yield() throw()
  210121. {
  210122. sched_yield();
  210123. }
  210124. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  210125. void Process::setPriority (ProcessPriority prior)
  210126. {
  210127. struct sched_param param;
  210128. int policy, maxp, minp;
  210129. const int p = (int) prior;
  210130. if (p <= 1)
  210131. policy = SCHED_OTHER;
  210132. else
  210133. policy = SCHED_RR;
  210134. minp = sched_get_priority_min (policy);
  210135. maxp = sched_get_priority_max (policy);
  210136. if (p < 2)
  210137. param.__sched_priority = 0;
  210138. else if (p == 2 )
  210139. // Set to middle of lower realtime priority range
  210140. param.__sched_priority = minp + (maxp - minp) / 4;
  210141. else
  210142. // Set to middle of higher realtime priority range
  210143. param.__sched_priority = minp + (3 * (maxp - minp) / 4);
  210144. pthread_setschedparam (pthread_self(), policy, &param);
  210145. }
  210146. void Process::terminate()
  210147. {
  210148. exit (0);
  210149. }
  210150. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  210151. {
  210152. static char testResult = 0;
  210153. if (testResult == 0)
  210154. {
  210155. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  210156. if (testResult >= 0)
  210157. {
  210158. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  210159. testResult = 1;
  210160. }
  210161. }
  210162. return testResult < 0;
  210163. }
  210164. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  210165. {
  210166. return juce_isRunningUnderDebugger();
  210167. }
  210168. void Process::raisePrivilege()
  210169. {
  210170. // If running suid root, change effective user
  210171. // to root
  210172. if (geteuid() != 0 && getuid() == 0)
  210173. {
  210174. setreuid (geteuid(), getuid());
  210175. setregid (getegid(), getgid());
  210176. }
  210177. }
  210178. void Process::lowerPrivilege()
  210179. {
  210180. // If runing suid root, change effective user
  210181. // back to real user
  210182. if (geteuid() == 0 && getuid() != 0)
  210183. {
  210184. setreuid (geteuid(), getuid());
  210185. setregid (getegid(), getgid());
  210186. }
  210187. }
  210188. #if JUCE_BUILD_GUI_CLASSES
  210189. void* Process::loadDynamicLibrary (const String& name)
  210190. {
  210191. return dlopen ((const char*) name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  210192. }
  210193. void Process::freeDynamicLibrary (void* handle)
  210194. {
  210195. dlclose(handle);
  210196. }
  210197. void* Process::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  210198. {
  210199. return dlsym (libraryHandle, (const char*) procedureName);
  210200. }
  210201. #endif
  210202. END_JUCE_NAMESPACE
  210203. /********* End of inlined file: juce_linux_Threads.cpp *********/
  210204. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  210205. /********* Start of inlined file: juce_linux_Audio.cpp *********/
  210206. #if JUCE_BUILD_GUI_CLASSES
  210207. #if JUCE_ALSA
  210208. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  210209. not got your paths set up correctly to find its header files.
  210210. The package you need to install to get ASLA support is "libasound2-dev".
  210211. If you don't have the ALSA library and don't want to build Juce with audio support,
  210212. just disable the JUCE_ALSA flag in juce_Config.h
  210213. */
  210214. #include <alsa/asoundlib.h>
  210215. BEGIN_JUCE_NAMESPACE
  210216. static const int maxNumChans = 64;
  210217. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  210218. {
  210219. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  210220. snd_pcm_hw_params_t* hwParams;
  210221. snd_pcm_hw_params_alloca (&hwParams);
  210222. for (int i = 0; ratesToTry[i] != 0; ++i)
  210223. {
  210224. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  210225. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  210226. {
  210227. rates.addIfNotAlreadyThere (ratesToTry[i]);
  210228. }
  210229. }
  210230. }
  210231. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  210232. {
  210233. snd_pcm_hw_params_t *params;
  210234. snd_pcm_hw_params_alloca (&params);
  210235. if (snd_pcm_hw_params_any (handle, params) >= 0)
  210236. {
  210237. snd_pcm_hw_params_get_channels_min (params, minChans);
  210238. snd_pcm_hw_params_get_channels_max (params, maxChans);
  210239. }
  210240. }
  210241. static void getDeviceProperties (const String& id,
  210242. unsigned int& minChansOut,
  210243. unsigned int& maxChansOut,
  210244. unsigned int& minChansIn,
  210245. unsigned int& maxChansIn,
  210246. Array <int>& rates)
  210247. {
  210248. if (id.isEmpty())
  210249. return;
  210250. snd_ctl_t* handle;
  210251. if (snd_ctl_open (&handle, id.upToLastOccurrenceOf (T(","), false, false), SND_CTL_NONBLOCK) >= 0)
  210252. {
  210253. snd_pcm_info_t* info;
  210254. snd_pcm_info_alloca (&info);
  210255. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  210256. snd_pcm_info_set_device (info, id.fromLastOccurrenceOf (T(","), false, false).getIntValue());
  210257. snd_pcm_info_set_subdevice (info, 0);
  210258. if (snd_ctl_pcm_info (handle, info) >= 0)
  210259. {
  210260. snd_pcm_t* pcmHandle;
  210261. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  210262. {
  210263. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  210264. getDeviceSampleRates (pcmHandle, rates);
  210265. snd_pcm_close (pcmHandle);
  210266. }
  210267. }
  210268. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  210269. if (snd_ctl_pcm_info (handle, info) >= 0)
  210270. {
  210271. snd_pcm_t* pcmHandle;
  210272. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  210273. {
  210274. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  210275. if (rates.size() == 0)
  210276. getDeviceSampleRates (pcmHandle, rates);
  210277. snd_pcm_close (pcmHandle);
  210278. }
  210279. }
  210280. snd_ctl_close (handle);
  210281. }
  210282. }
  210283. class ALSADevice
  210284. {
  210285. public:
  210286. ALSADevice (const String& id,
  210287. const bool forInput)
  210288. : handle (0),
  210289. bitDepth (16),
  210290. numChannelsRunning (0),
  210291. isInput (forInput),
  210292. sampleFormat (AudioDataConverters::int16LE)
  210293. {
  210294. failed (snd_pcm_open (&handle, id,
  210295. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  210296. SND_PCM_ASYNC));
  210297. }
  210298. ~ALSADevice()
  210299. {
  210300. if (handle != 0)
  210301. snd_pcm_close (handle);
  210302. }
  210303. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  210304. {
  210305. if (handle == 0)
  210306. return false;
  210307. snd_pcm_hw_params_t* hwParams;
  210308. snd_pcm_hw_params_alloca (&hwParams);
  210309. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  210310. return false;
  210311. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  210312. isInterleaved = false;
  210313. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  210314. isInterleaved = true;
  210315. else
  210316. {
  210317. jassertfalse
  210318. return false;
  210319. }
  210320. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  210321. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  210322. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  210323. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  210324. SND_PCM_FORMAT_S24_LE, 24, AudioDataConverters::int24LE,
  210325. SND_PCM_FORMAT_S24_BE, 24, AudioDataConverters::int24BE,
  210326. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  210327. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  210328. bitDepth = 0;
  210329. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  210330. {
  210331. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  210332. {
  210333. bitDepth = formatsToTry [i + 1];
  210334. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  210335. break;
  210336. }
  210337. }
  210338. if (bitDepth == 0)
  210339. {
  210340. error = "device doesn't support a compatible PCM format";
  210341. DBG (T("ALSA error: ") + error + T("\n"));
  210342. return false;
  210343. }
  210344. int dir = 0;
  210345. unsigned int periods = 4;
  210346. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  210347. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  210348. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  210349. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  210350. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  210351. || failed (snd_pcm_hw_params (handle, hwParams)))
  210352. {
  210353. return false;
  210354. }
  210355. snd_pcm_sw_params_t* swParams;
  210356. snd_pcm_sw_params_alloca (&swParams);
  210357. if (failed (snd_pcm_sw_params_current (handle, swParams))
  210358. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  210359. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, 0))
  210360. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  210361. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, INT_MAX))
  210362. || failed (snd_pcm_sw_params (handle, swParams)))
  210363. {
  210364. return false;
  210365. }
  210366. /*
  210367. #ifdef JUCE_DEBUG
  210368. // enable this to dump the config of the devices that get opened
  210369. snd_output_t* out;
  210370. snd_output_stdio_attach (&out, stderr, 0);
  210371. snd_pcm_hw_params_dump (hwParams, out);
  210372. snd_pcm_sw_params_dump (swParams, out);
  210373. #endif
  210374. */
  210375. numChannelsRunning = numChannels;
  210376. return true;
  210377. }
  210378. bool write (float** const data, const int numSamples)
  210379. {
  210380. if (isInterleaved)
  210381. {
  210382. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  210383. float* interleaved = (float*) scratch;
  210384. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  210385. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  210386. snd_pcm_sframes_t num = snd_pcm_writei (handle, (void*) interleaved, numSamples);
  210387. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  210388. return false;
  210389. }
  210390. else
  210391. {
  210392. for (int i = 0; i < numChannelsRunning; ++i)
  210393. if (data[i] != 0)
  210394. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  210395. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  210396. if (failed (num))
  210397. {
  210398. if (num == -EPIPE)
  210399. {
  210400. if (failed (snd_pcm_prepare (handle)))
  210401. return false;
  210402. }
  210403. else if (num != -ESTRPIPE)
  210404. return false;
  210405. }
  210406. }
  210407. return true;
  210408. }
  210409. bool read (float** const data, const int numSamples)
  210410. {
  210411. if (isInterleaved)
  210412. {
  210413. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  210414. float* interleaved = (float*) scratch;
  210415. snd_pcm_sframes_t num = snd_pcm_readi (handle, (void*) interleaved, numSamples);
  210416. if (failed (num))
  210417. {
  210418. if (num == -EPIPE)
  210419. {
  210420. if (failed (snd_pcm_prepare (handle)))
  210421. return false;
  210422. }
  210423. else if (num != -ESTRPIPE)
  210424. return false;
  210425. }
  210426. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  210427. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  210428. }
  210429. else
  210430. {
  210431. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  210432. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  210433. return false;
  210434. for (int i = 0; i < numChannelsRunning; ++i)
  210435. if (data[i] != 0)
  210436. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  210437. }
  210438. return true;
  210439. }
  210440. juce_UseDebuggingNewOperator
  210441. snd_pcm_t* handle;
  210442. String error;
  210443. int bitDepth, numChannelsRunning;
  210444. private:
  210445. const bool isInput;
  210446. bool isInterleaved;
  210447. MemoryBlock scratch;
  210448. AudioDataConverters::DataFormat sampleFormat;
  210449. bool failed (const int errorNum)
  210450. {
  210451. if (errorNum >= 0)
  210452. return false;
  210453. error = snd_strerror (errorNum);
  210454. DBG (T("ALSA error: ") + error + T("\n"));
  210455. return true;
  210456. }
  210457. };
  210458. class ALSAThread : public Thread
  210459. {
  210460. public:
  210461. ALSAThread (const String& inputId_,
  210462. const String& outputId_)
  210463. : Thread ("Juce ALSA"),
  210464. sampleRate (0),
  210465. bufferSize (0),
  210466. callback (0),
  210467. inputId (inputId_),
  210468. outputId (outputId_),
  210469. outputDevice (0),
  210470. inputDevice (0),
  210471. numCallbacks (0),
  210472. totalNumInputChannels (0),
  210473. totalNumOutputChannels (0)
  210474. {
  210475. zeromem (outputChannelData, sizeof (outputChannelData));
  210476. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  210477. zeromem (inputChannelData, sizeof (inputChannelData));
  210478. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  210479. initialiseRatesAndChannels();
  210480. }
  210481. ~ALSAThread()
  210482. {
  210483. close();
  210484. }
  210485. void open (const BitArray& inputChannels,
  210486. const BitArray& outputChannels,
  210487. const double sampleRate_,
  210488. const int bufferSize_)
  210489. {
  210490. close();
  210491. error = String::empty;
  210492. sampleRate = sampleRate_;
  210493. bufferSize = bufferSize_;
  210494. currentInputChans.clear();
  210495. currentOutputChans.clear();
  210496. if (inputChannels.getHighestBit() >= 0)
  210497. {
  210498. for (int i = 0; i <= inputChannels.getHighestBit(); ++i)
  210499. {
  210500. inputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  210501. if (inputChannels[i])
  210502. {
  210503. inputChannelDataForCallback [totalNumInputChannels++] = inputChannelData [i];
  210504. currentInputChans.setBit (i);
  210505. }
  210506. }
  210507. }
  210508. if (outputChannels.getHighestBit() >= 0)
  210509. {
  210510. for (int i = 0; i <= outputChannels.getHighestBit(); ++i)
  210511. {
  210512. outputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  210513. if (outputChannels[i])
  210514. {
  210515. outputChannelDataForCallback [totalNumOutputChannels++] = outputChannelData [i];
  210516. currentOutputChans.setBit (i);
  210517. }
  210518. }
  210519. }
  210520. if (totalNumOutputChannels > 0 && outputId.isNotEmpty())
  210521. {
  210522. outputDevice = new ALSADevice (outputId, false);
  210523. if (outputDevice->error.isNotEmpty())
  210524. {
  210525. error = outputDevice->error;
  210526. deleteAndZero (outputDevice);
  210527. return;
  210528. }
  210529. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  210530. currentOutputChans.getHighestBit() + 1,
  210531. bufferSize))
  210532. {
  210533. error = outputDevice->error;
  210534. deleteAndZero (outputDevice);
  210535. return;
  210536. }
  210537. }
  210538. if (totalNumInputChannels > 0 && inputId.isNotEmpty())
  210539. {
  210540. inputDevice = new ALSADevice (inputId, true);
  210541. if (inputDevice->error.isNotEmpty())
  210542. {
  210543. error = inputDevice->error;
  210544. deleteAndZero (inputDevice);
  210545. return;
  210546. }
  210547. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  210548. currentInputChans.getHighestBit() + 1,
  210549. bufferSize))
  210550. {
  210551. error = inputDevice->error;
  210552. deleteAndZero (inputDevice);
  210553. return;
  210554. }
  210555. }
  210556. if (outputDevice == 0 && inputDevice == 0)
  210557. {
  210558. error = "no channels";
  210559. return;
  210560. }
  210561. if (outputDevice != 0 && inputDevice != 0)
  210562. {
  210563. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  210564. }
  210565. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  210566. return;
  210567. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  210568. return;
  210569. startThread (9);
  210570. int count = 1000;
  210571. while (numCallbacks == 0)
  210572. {
  210573. sleep (5);
  210574. if (--count < 0 || ! isThreadRunning())
  210575. {
  210576. error = "device didn't start";
  210577. break;
  210578. }
  210579. }
  210580. }
  210581. void close()
  210582. {
  210583. stopThread (6000);
  210584. deleteAndZero (inputDevice);
  210585. deleteAndZero (outputDevice);
  210586. for (int i = 0; i < maxNumChans; ++i)
  210587. {
  210588. juce_free (inputChannelData [i]);
  210589. juce_free (outputChannelData [i]);
  210590. }
  210591. zeromem (outputChannelData, sizeof (outputChannelData));
  210592. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  210593. zeromem (inputChannelData, sizeof (inputChannelData));
  210594. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  210595. totalNumOutputChannels = 0;
  210596. totalNumInputChannels = 0;
  210597. numCallbacks = 0;
  210598. }
  210599. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  210600. {
  210601. const ScopedLock sl (callbackLock);
  210602. callback = newCallback;
  210603. }
  210604. void run()
  210605. {
  210606. while (! threadShouldExit())
  210607. {
  210608. if (inputDevice != 0)
  210609. {
  210610. if (! inputDevice->read (inputChannelData, bufferSize))
  210611. {
  210612. DBG ("ALSA: read failure");
  210613. break;
  210614. }
  210615. }
  210616. if (threadShouldExit())
  210617. break;
  210618. {
  210619. const ScopedLock sl (callbackLock);
  210620. ++numCallbacks;
  210621. if (callback != 0)
  210622. {
  210623. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback,
  210624. totalNumInputChannels,
  210625. outputChannelDataForCallback,
  210626. totalNumOutputChannels,
  210627. bufferSize);
  210628. }
  210629. else
  210630. {
  210631. for (int i = 0; i < totalNumOutputChannels; ++i)
  210632. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  210633. }
  210634. }
  210635. if (outputDevice != 0)
  210636. {
  210637. failed (snd_pcm_wait (outputDevice->handle, 2000));
  210638. if (threadShouldExit())
  210639. break;
  210640. failed (snd_pcm_avail_update (outputDevice->handle));
  210641. if (! outputDevice->write (outputChannelData, bufferSize))
  210642. {
  210643. DBG ("ALSA: write failure");
  210644. break;
  210645. }
  210646. }
  210647. }
  210648. }
  210649. int getBitDepth() const throw()
  210650. {
  210651. if (outputDevice != 0)
  210652. return outputDevice->bitDepth;
  210653. if (inputDevice != 0)
  210654. return inputDevice->bitDepth;
  210655. return 16;
  210656. }
  210657. juce_UseDebuggingNewOperator
  210658. String error;
  210659. double sampleRate;
  210660. int bufferSize;
  210661. BitArray currentInputChans, currentOutputChans;
  210662. Array <int> sampleRates;
  210663. StringArray channelNamesOut, channelNamesIn;
  210664. AudioIODeviceCallback* callback;
  210665. private:
  210666. const String inputId, outputId;
  210667. ALSADevice* outputDevice;
  210668. ALSADevice* inputDevice;
  210669. int numCallbacks;
  210670. CriticalSection callbackLock;
  210671. float* outputChannelData [maxNumChans];
  210672. float* outputChannelDataForCallback [maxNumChans];
  210673. int totalNumInputChannels;
  210674. float* inputChannelData [maxNumChans];
  210675. float* inputChannelDataForCallback [maxNumChans];
  210676. int totalNumOutputChannels;
  210677. unsigned int minChansOut, maxChansOut;
  210678. unsigned int minChansIn, maxChansIn;
  210679. bool failed (const int errorNum) throw()
  210680. {
  210681. if (errorNum >= 0)
  210682. return false;
  210683. error = snd_strerror (errorNum);
  210684. DBG (T("ALSA error: ") + error + T("\n"));
  210685. return true;
  210686. }
  210687. void initialiseRatesAndChannels() throw()
  210688. {
  210689. sampleRates.clear();
  210690. channelNamesOut.clear();
  210691. channelNamesIn.clear();
  210692. minChansOut = 0;
  210693. maxChansOut = 0;
  210694. minChansIn = 0;
  210695. maxChansIn = 0;
  210696. unsigned int dummy = 0;
  210697. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  210698. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  210699. unsigned int i;
  210700. for (i = 0; i < maxChansOut; ++i)
  210701. channelNamesOut.add (T("channel ") + String ((int) i + 1));
  210702. for (i = 0; i < maxChansIn; ++i)
  210703. channelNamesIn.add (T("channel ") + String ((int) i + 1));
  210704. }
  210705. };
  210706. class ALSAAudioIODevice : public AudioIODevice
  210707. {
  210708. public:
  210709. ALSAAudioIODevice (const String& deviceName,
  210710. const String& inputId_,
  210711. const String& outputId_)
  210712. : AudioIODevice (deviceName, T("ALSA")),
  210713. inputId (inputId_),
  210714. outputId (outputId_),
  210715. isOpen_ (false),
  210716. isStarted (false),
  210717. internal (0)
  210718. {
  210719. internal = new ALSAThread (inputId, outputId);
  210720. }
  210721. ~ALSAAudioIODevice()
  210722. {
  210723. delete internal;
  210724. }
  210725. const StringArray getOutputChannelNames()
  210726. {
  210727. return internal->channelNamesOut;
  210728. }
  210729. const StringArray getInputChannelNames()
  210730. {
  210731. return internal->channelNamesIn;
  210732. }
  210733. int getNumSampleRates()
  210734. {
  210735. return internal->sampleRates.size();
  210736. }
  210737. double getSampleRate (int index)
  210738. {
  210739. return internal->sampleRates [index];
  210740. }
  210741. int getNumBufferSizesAvailable()
  210742. {
  210743. return 50;
  210744. }
  210745. int getBufferSizeSamples (int index)
  210746. {
  210747. int n = 16;
  210748. for (int i = 0; i < index; ++i)
  210749. n += n < 64 ? 16
  210750. : (n < 512 ? 32
  210751. : (n < 1024 ? 64
  210752. : (n < 2048 ? 128 : 256)));
  210753. return n;
  210754. }
  210755. int getDefaultBufferSize()
  210756. {
  210757. return 512;
  210758. }
  210759. const String open (const BitArray& inputChannels,
  210760. const BitArray& outputChannels,
  210761. double sampleRate,
  210762. int bufferSizeSamples)
  210763. {
  210764. close();
  210765. if (bufferSizeSamples <= 0)
  210766. bufferSizeSamples = getDefaultBufferSize();
  210767. if (sampleRate <= 0)
  210768. {
  210769. for (int i = 0; i < getNumSampleRates(); ++i)
  210770. {
  210771. if (getSampleRate (i) >= 44100)
  210772. {
  210773. sampleRate = getSampleRate (i);
  210774. break;
  210775. }
  210776. }
  210777. }
  210778. internal->open (inputChannels, outputChannels,
  210779. sampleRate, bufferSizeSamples);
  210780. isOpen_ = internal->error.isEmpty();
  210781. return internal->error;
  210782. }
  210783. void close()
  210784. {
  210785. stop();
  210786. internal->close();
  210787. isOpen_ = false;
  210788. }
  210789. bool isOpen()
  210790. {
  210791. return isOpen_;
  210792. }
  210793. int getCurrentBufferSizeSamples()
  210794. {
  210795. return internal->bufferSize;
  210796. }
  210797. double getCurrentSampleRate()
  210798. {
  210799. return internal->sampleRate;
  210800. }
  210801. int getCurrentBitDepth()
  210802. {
  210803. return internal->getBitDepth();
  210804. }
  210805. const BitArray getActiveOutputChannels() const
  210806. {
  210807. return internal->currentOutputChans;
  210808. }
  210809. const BitArray getActiveInputChannels() const
  210810. {
  210811. return internal->currentInputChans;
  210812. }
  210813. int getOutputLatencyInSamples()
  210814. {
  210815. return 0;
  210816. }
  210817. int getInputLatencyInSamples()
  210818. {
  210819. return 0;
  210820. }
  210821. void start (AudioIODeviceCallback* callback)
  210822. {
  210823. if (! isOpen_)
  210824. callback = 0;
  210825. internal->setCallback (callback);
  210826. if (callback != 0)
  210827. callback->audioDeviceAboutToStart (this);
  210828. isStarted = (callback != 0);
  210829. }
  210830. void stop()
  210831. {
  210832. AudioIODeviceCallback* const oldCallback = internal->callback;
  210833. start (0);
  210834. if (oldCallback != 0)
  210835. oldCallback->audioDeviceStopped();
  210836. }
  210837. bool isPlaying()
  210838. {
  210839. return isStarted && internal->error.isEmpty();
  210840. }
  210841. const String getLastError()
  210842. {
  210843. return internal->error;
  210844. }
  210845. String inputId, outputId;
  210846. private:
  210847. bool isOpen_, isStarted;
  210848. ALSAThread* internal;
  210849. };
  210850. class ALSAAudioIODeviceType : public AudioIODeviceType
  210851. {
  210852. public:
  210853. ALSAAudioIODeviceType()
  210854. : AudioIODeviceType (T("ALSA")),
  210855. hasScanned (false)
  210856. {
  210857. }
  210858. ~ALSAAudioIODeviceType()
  210859. {
  210860. }
  210861. void scanForDevices()
  210862. {
  210863. if (hasScanned)
  210864. return;
  210865. hasScanned = true;
  210866. inputNames.clear();
  210867. inputIds.clear();
  210868. outputNames.clear();
  210869. outputIds.clear();
  210870. snd_ctl_t* handle;
  210871. snd_ctl_card_info_t* info;
  210872. snd_ctl_card_info_alloca (&info);
  210873. int cardNum = -1;
  210874. while (outputIds.size() + inputIds.size() <= 32)
  210875. {
  210876. snd_card_next (&cardNum);
  210877. if (cardNum < 0)
  210878. break;
  210879. if (snd_ctl_open (&handle, T("hw:") + String (cardNum), SND_CTL_NONBLOCK) >= 0)
  210880. {
  210881. if (snd_ctl_card_info (handle, info) >= 0)
  210882. {
  210883. String cardId (snd_ctl_card_info_get_id (info));
  210884. if (cardId.removeCharacters (T("0123456789")).isEmpty())
  210885. cardId = String (cardNum);
  210886. int device = -1;
  210887. for (;;)
  210888. {
  210889. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  210890. break;
  210891. String id, name;
  210892. id << "hw:" << cardId << ',' << device;
  210893. bool isInput, isOutput;
  210894. if (testDevice (id, isInput, isOutput))
  210895. {
  210896. name << snd_ctl_card_info_get_name (info);
  210897. if (name.isEmpty())
  210898. name = id;
  210899. if (isInput)
  210900. {
  210901. inputNames.add (name);
  210902. inputIds.add (id);
  210903. }
  210904. if (isOutput)
  210905. {
  210906. outputNames.add (name);
  210907. outputIds.add (id);
  210908. }
  210909. }
  210910. }
  210911. }
  210912. snd_ctl_close (handle);
  210913. }
  210914. }
  210915. inputNames.appendNumbersToDuplicates (false, true);
  210916. outputNames.appendNumbersToDuplicates (false, true);
  210917. }
  210918. const StringArray getDeviceNames (const bool wantInputNames) const
  210919. {
  210920. jassert (hasScanned); // need to call scanForDevices() before doing this
  210921. return wantInputNames ? inputNames : outputNames;
  210922. }
  210923. int getDefaultDeviceIndex (const bool forInput) const
  210924. {
  210925. jassert (hasScanned); // need to call scanForDevices() before doing this
  210926. return 0;
  210927. }
  210928. bool hasSeparateInputsAndOutputs() const { return true; }
  210929. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  210930. {
  210931. jassert (hasScanned); // need to call scanForDevices() before doing this
  210932. ALSAAudioIODevice* const d = dynamic_cast <ALSAAudioIODevice*> (device);
  210933. if (d == 0)
  210934. return -1;
  210935. return asInput ? inputIds.indexOf (d->inputId)
  210936. : outputIds.indexOf (d->outputId);
  210937. }
  210938. AudioIODevice* createDevice (const String& outputDeviceName,
  210939. const String& inputDeviceName)
  210940. {
  210941. jassert (hasScanned); // need to call scanForDevices() before doing this
  210942. const int inputIndex = inputNames.indexOf (inputDeviceName);
  210943. const int outputIndex = outputNames.indexOf (outputDeviceName);
  210944. String deviceName (outputDeviceName);
  210945. if (deviceName.isEmpty())
  210946. deviceName = inputDeviceName;
  210947. if (index >= 0)
  210948. return new ALSAAudioIODevice (deviceName,
  210949. inputIds [inputIndex],
  210950. outputIds [outputIndex]);
  210951. return 0;
  210952. }
  210953. juce_UseDebuggingNewOperator
  210954. private:
  210955. StringArray inputNames, outputNames, inputIds, outputIds;
  210956. bool hasScanned;
  210957. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  210958. {
  210959. unsigned int minChansOut = 0, maxChansOut = 0;
  210960. unsigned int minChansIn = 0, maxChansIn = 0;
  210961. Array <int> rates;
  210962. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  210963. DBG (T("ALSA device: ") + id
  210964. + T(" outs=") + String ((int) minChansOut) + T("-") + String ((int) maxChansOut)
  210965. + T(" ins=") + String ((int) minChansIn) + T("-") + String ((int) maxChansIn)
  210966. + T(" rates=") + String (rates.size()));
  210967. isInput = maxChansIn > 0;
  210968. isOutput = maxChansOut > 0;
  210969. return (isInput || isOutput) && rates.size() > 0;
  210970. }
  210971. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  210972. const ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  210973. };
  210974. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  210975. {
  210976. return new ALSAAudioIODeviceType();
  210977. }
  210978. END_JUCE_NAMESPACE
  210979. #else // if ALSA is turned off..
  210980. BEGIN_JUCE_NAMESPACE
  210981. AudioIODeviceType* juce_createDefaultAudioIODeviceType() { return 0; }
  210982. END_JUCE_NAMESPACE
  210983. #endif
  210984. #endif
  210985. /********* End of inlined file: juce_linux_Audio.cpp *********/
  210986. /********* Start of inlined file: juce_linux_AudioCDReader.cpp *********/
  210987. BEGIN_JUCE_NAMESPACE
  210988. AudioCDReader::AudioCDReader()
  210989. : AudioFormatReader (0, T("CD Audio"))
  210990. {
  210991. }
  210992. const StringArray AudioCDReader::getAvailableCDNames()
  210993. {
  210994. StringArray names;
  210995. return names;
  210996. }
  210997. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  210998. {
  210999. return 0;
  211000. }
  211001. AudioCDReader::~AudioCDReader()
  211002. {
  211003. }
  211004. void AudioCDReader::refreshTrackLengths()
  211005. {
  211006. }
  211007. bool AudioCDReader::read (int** destSamples,
  211008. int64 startSampleInFile,
  211009. int numSamples)
  211010. {
  211011. return false;
  211012. }
  211013. bool AudioCDReader::isCDStillPresent() const
  211014. {
  211015. return false;
  211016. }
  211017. int AudioCDReader::getNumTracks() const
  211018. {
  211019. return 0;
  211020. }
  211021. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  211022. {
  211023. return 0;
  211024. }
  211025. bool AudioCDReader::isTrackAudio (int trackNum) const
  211026. {
  211027. return false;
  211028. }
  211029. void AudioCDReader::enableIndexScanning (bool b)
  211030. {
  211031. }
  211032. int AudioCDReader::getLastIndex() const
  211033. {
  211034. return 0;
  211035. }
  211036. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211037. {
  211038. return Array<int>();
  211039. }
  211040. int AudioCDReader::getCDDBId()
  211041. {
  211042. return 0;
  211043. }
  211044. END_JUCE_NAMESPACE
  211045. /********* End of inlined file: juce_linux_AudioCDReader.cpp *********/
  211046. /********* Start of inlined file: juce_linux_FileChooser.cpp *********/
  211047. #if JUCE_BUILD_GUI_CLASSES
  211048. BEGIN_JUCE_NAMESPACE
  211049. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  211050. const String& title,
  211051. const File& file,
  211052. const String& filters,
  211053. bool isDirectory,
  211054. bool isSave,
  211055. bool warnAboutOverwritingExistingFiles,
  211056. bool selectMultipleFiles,
  211057. FilePreviewComponent* previewComponent)
  211058. {
  211059. //xxx ain't got one!
  211060. jassertfalse
  211061. }
  211062. END_JUCE_NAMESPACE
  211063. #endif
  211064. /********* End of inlined file: juce_linux_FileChooser.cpp *********/
  211065. /********* Start of inlined file: juce_linux_Fonts.cpp *********/
  211066. #if JUCE_BUILD_GUI_CLASSES
  211067. /* Got a build error here? You'll need to install the freetype library...
  211068. The name of the package to install is "libfreetype6-dev".
  211069. */
  211070. #include <ft2build.h>
  211071. #include FT_FREETYPE_H
  211072. BEGIN_JUCE_NAMESPACE
  211073. class FreeTypeFontFace
  211074. {
  211075. public:
  211076. enum FontStyle
  211077. {
  211078. Plain = 0,
  211079. Bold = 1,
  211080. Italic = 2
  211081. };
  211082. struct FontNameIndex
  211083. {
  211084. String fileName;
  211085. int faceIndex;
  211086. };
  211087. FreeTypeFontFace (const String& familyName)
  211088. : hasSerif (false),
  211089. monospaced (false)
  211090. {
  211091. family = familyName;
  211092. }
  211093. void setFileName (const String& name,
  211094. const int faceIndex,
  211095. FontStyle style)
  211096. {
  211097. if (names[(int) style].fileName.isEmpty())
  211098. {
  211099. names[(int) style].fileName = name;
  211100. names[(int) style].faceIndex = faceIndex;
  211101. }
  211102. }
  211103. const String& getFamilyName() const throw()
  211104. {
  211105. return family;
  211106. }
  211107. const String& getFileName (int style, int* faceIndex) const throw()
  211108. {
  211109. *faceIndex = names [style].faceIndex;
  211110. return names[style].fileName;
  211111. }
  211112. void setMonospaced (bool mono) { monospaced = mono; }
  211113. bool getMonospaced () const throw() { return monospaced; }
  211114. void setSerif (const bool serif) { hasSerif = serif; }
  211115. bool getSerif () const throw() { return hasSerif; }
  211116. private:
  211117. String family;
  211118. FontNameIndex names[4];
  211119. bool hasSerif, monospaced;
  211120. };
  211121. class FreeTypeInterface : public DeletedAtShutdown
  211122. {
  211123. public:
  211124. FreeTypeInterface() throw()
  211125. : lastFace (0),
  211126. lastBold (false),
  211127. lastItalic (false)
  211128. {
  211129. if (FT_Init_FreeType (&ftLib) != 0)
  211130. {
  211131. ftLib = 0;
  211132. DBG (T("Failed to initialize FreeType"));
  211133. }
  211134. StringArray fontDirs;
  211135. fontDirs.addTokens (String (getenv ("JUCE_FONT_PATH")), T(";,"), 0);
  211136. fontDirs.removeEmptyStrings (true);
  211137. if (fontDirs.size() == 0)
  211138. {
  211139. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  211140. XmlElement* const fontsInfo = fontsConfig.getDocumentElement();
  211141. if (fontsInfo != 0)
  211142. {
  211143. forEachXmlChildElementWithTagName (*fontsInfo, e, T("dir"))
  211144. {
  211145. fontDirs.add (e->getAllSubText().trim());
  211146. }
  211147. delete fontsInfo;
  211148. }
  211149. }
  211150. if (fontDirs.size() == 0)
  211151. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  211152. for (int i = 0; i < fontDirs.size(); ++i)
  211153. enumerateFaces (fontDirs[i]);
  211154. }
  211155. ~FreeTypeInterface() throw()
  211156. {
  211157. if (lastFace != 0)
  211158. FT_Done_Face (lastFace);
  211159. if (ftLib != 0)
  211160. FT_Done_FreeType (ftLib);
  211161. clearSingletonInstance();
  211162. }
  211163. FreeTypeFontFace* findOrCreate (const String& familyName,
  211164. const bool create = false) throw()
  211165. {
  211166. for (int i = 0; i < faces.size(); i++)
  211167. if (faces[i]->getFamilyName() == familyName)
  211168. return faces[i];
  211169. if (! create)
  211170. return NULL;
  211171. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  211172. faces.add (newFace);
  211173. return newFace;
  211174. }
  211175. // Enumerate all font faces available in a given directory
  211176. void enumerateFaces (const String& path) throw()
  211177. {
  211178. File dirPath (path);
  211179. if (path.isEmpty() || ! dirPath.isDirectory())
  211180. return;
  211181. DirectoryIterator di (dirPath, true);
  211182. while (di.next())
  211183. {
  211184. File possible (di.getFile());
  211185. if (possible.hasFileExtension (T("ttf"))
  211186. || possible.hasFileExtension (T("pfb"))
  211187. || possible.hasFileExtension (T("pcf")))
  211188. {
  211189. FT_Face face;
  211190. int faceIndex = 0;
  211191. int numFaces = 0;
  211192. do
  211193. {
  211194. if (FT_New_Face (ftLib,
  211195. possible.getFullPathName(),
  211196. faceIndex,
  211197. &face) == 0)
  211198. {
  211199. if (faceIndex == 0)
  211200. numFaces = face->num_faces;
  211201. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  211202. {
  211203. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  211204. int style = (int) FreeTypeFontFace::Plain;
  211205. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  211206. style |= (int) FreeTypeFontFace::Bold;
  211207. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  211208. style |= (int) FreeTypeFontFace::Italic;
  211209. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  211210. if ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0)
  211211. newFace->setMonospaced (true);
  211212. else
  211213. newFace->setMonospaced (false);
  211214. // Surely there must be a better way to do this?
  211215. if (String (face->family_name).containsIgnoreCase (T("Sans"))
  211216. || String (face->family_name).containsIgnoreCase (T("Verdana"))
  211217. || String (face->family_name).containsIgnoreCase (T("Arial")))
  211218. {
  211219. newFace->setSerif (false);
  211220. }
  211221. else
  211222. {
  211223. newFace->setSerif (true);
  211224. }
  211225. }
  211226. FT_Done_Face (face);
  211227. }
  211228. ++faceIndex;
  211229. }
  211230. while (faceIndex < numFaces);
  211231. }
  211232. }
  211233. }
  211234. // Create a FreeType face object for a given font
  211235. FT_Face createFT_Face (const String& fontName,
  211236. const bool bold,
  211237. const bool italic) throw()
  211238. {
  211239. FT_Face face = NULL;
  211240. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  211241. {
  211242. face = lastFace;
  211243. }
  211244. else
  211245. {
  211246. if (lastFace)
  211247. {
  211248. FT_Done_Face (lastFace);
  211249. lastFace = NULL;
  211250. }
  211251. lastFontName = fontName;
  211252. lastBold = bold;
  211253. lastItalic = italic;
  211254. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  211255. if (ftFace != 0)
  211256. {
  211257. int style = (int) FreeTypeFontFace::Plain;
  211258. if (bold)
  211259. style |= (int) FreeTypeFontFace::Bold;
  211260. if (italic)
  211261. style |= (int) FreeTypeFontFace::Italic;
  211262. int faceIndex;
  211263. String fileName (ftFace->getFileName (style, &faceIndex));
  211264. if (fileName.isEmpty())
  211265. {
  211266. style ^= (int) FreeTypeFontFace::Bold;
  211267. fileName = ftFace->getFileName (style, &faceIndex);
  211268. if (fileName.isEmpty())
  211269. {
  211270. style ^= (int) FreeTypeFontFace::Bold;
  211271. style ^= (int) FreeTypeFontFace::Italic;
  211272. fileName = ftFace->getFileName (style, &faceIndex);
  211273. if (! fileName.length())
  211274. {
  211275. style ^= (int) FreeTypeFontFace::Bold;
  211276. fileName = ftFace->getFileName (style, &faceIndex);
  211277. }
  211278. }
  211279. }
  211280. if (! FT_New_Face (ftLib, (const char*) fileName, faceIndex, &lastFace))
  211281. {
  211282. face = lastFace;
  211283. // If there isn't a unicode charmap then select the first one.
  211284. if (FT_Select_Charmap (face, ft_encoding_unicode))
  211285. FT_Set_Charmap (face, face->charmaps[0]);
  211286. }
  211287. }
  211288. }
  211289. return face;
  211290. }
  211291. bool addGlyph (FT_Face face, Typeface& dest, uint32 character) throw()
  211292. {
  211293. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  211294. const float height = (float) (face->ascender - face->descender);
  211295. const float scaleX = 1.0f / height;
  211296. const float scaleY = -1.0f / height;
  211297. Path destShape;
  211298. #define CONVERTX(val) (scaleX * (val).x)
  211299. #define CONVERTY(val) (scaleY * (val).y)
  211300. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE
  211301. | FT_LOAD_NO_BITMAP
  211302. | FT_LOAD_IGNORE_TRANSFORM) != 0
  211303. || face->glyph->format != ft_glyph_format_outline)
  211304. {
  211305. return false;
  211306. }
  211307. const FT_Outline* const outline = &face->glyph->outline;
  211308. const short* const contours = outline->contours;
  211309. const char* const tags = outline->tags;
  211310. FT_Vector* const points = outline->points;
  211311. for (int c = 0; c < outline->n_contours; c++)
  211312. {
  211313. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  211314. const int endPoint = contours[c];
  211315. for (int p = startPoint; p <= endPoint; p++)
  211316. {
  211317. const float x = CONVERTX (points[p]);
  211318. const float y = CONVERTY (points[p]);
  211319. if (p == startPoint)
  211320. {
  211321. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  211322. {
  211323. float x2 = CONVERTX (points [endPoint]);
  211324. float y2 = CONVERTY (points [endPoint]);
  211325. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  211326. {
  211327. x2 = (x + x2) * 0.5f;
  211328. y2 = (y + y2) * 0.5f;
  211329. }
  211330. destShape.startNewSubPath (x2, y2);
  211331. }
  211332. else
  211333. {
  211334. destShape.startNewSubPath (x, y);
  211335. }
  211336. }
  211337. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  211338. {
  211339. if (p != startPoint)
  211340. destShape.lineTo (x, y);
  211341. }
  211342. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  211343. {
  211344. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  211345. float x2 = CONVERTX (points [nextIndex]);
  211346. float y2 = CONVERTY (points [nextIndex]);
  211347. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  211348. {
  211349. x2 = (x + x2) * 0.5f;
  211350. y2 = (y + y2) * 0.5f;
  211351. }
  211352. else
  211353. {
  211354. ++p;
  211355. }
  211356. destShape.quadraticTo (x, y, x2, y2);
  211357. }
  211358. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  211359. {
  211360. if (p >= endPoint)
  211361. return false;
  211362. const int next1 = p + 1;
  211363. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  211364. const float x2 = CONVERTX (points [next1]);
  211365. const float y2 = CONVERTY (points [next1]);
  211366. const float x3 = CONVERTX (points [next2]);
  211367. const float y3 = CONVERTY (points [next2]);
  211368. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  211369. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  211370. return false;
  211371. destShape.cubicTo (x, y, x2, y2, x3, y3);
  211372. p += 2;
  211373. }
  211374. }
  211375. destShape.closeSubPath();
  211376. }
  211377. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance/height);
  211378. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  211379. addKerning (face, dest, character, glyphIndex);
  211380. return true;
  211381. }
  211382. void addKerning (FT_Face face, Typeface& dest, const uint32 character, const uint32 glyphIndex) throw()
  211383. {
  211384. const float height = (float) (face->ascender - face->descender);
  211385. uint32 rightGlyphIndex;
  211386. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  211387. while (rightGlyphIndex != 0)
  211388. {
  211389. FT_Vector kerning;
  211390. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  211391. {
  211392. if (kerning.x != 0)
  211393. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  211394. }
  211395. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  211396. }
  211397. }
  211398. // Add a glyph to a font
  211399. bool addGlyphToFont (const uint32 character,
  211400. const tchar* fontName, bool bold, bool italic,
  211401. Typeface& dest) throw()
  211402. {
  211403. FT_Face face = createFT_Face (fontName, bold, italic);
  211404. if (face != 0)
  211405. return addGlyph (face, dest, character);
  211406. return false;
  211407. }
  211408. // Create a Typeface object for given name/style
  211409. bool createTypeface (const String& fontName,
  211410. const bool bold, const bool italic,
  211411. Typeface& dest,
  211412. const bool addAllGlyphs) throw()
  211413. {
  211414. dest.clear();
  211415. dest.setName (fontName);
  211416. dest.setBold (bold);
  211417. dest.setItalic (italic);
  211418. FT_Face face = createFT_Face (fontName, bold, italic);
  211419. if (face == 0)
  211420. {
  211421. #ifdef JUCE_DEBUG
  211422. String msg (T("Failed to create typeface: "));
  211423. msg << fontName << " " << (bold ? 'B' : ' ') << (italic ? 'I' : ' ');
  211424. DBG (msg);
  211425. #endif
  211426. return face;
  211427. }
  211428. const float height = (float) (face->ascender - face->descender);
  211429. dest.setAscent (face->ascender / height);
  211430. dest.setDefaultCharacter (L' ');
  211431. if (addAllGlyphs)
  211432. {
  211433. uint32 glyphIndex;
  211434. uint32 charCode = FT_Get_First_Char (face, &glyphIndex);
  211435. while (glyphIndex != 0)
  211436. {
  211437. addGlyph (face, dest, charCode);
  211438. charCode = FT_Get_Next_Char (face, charCode, &glyphIndex);
  211439. }
  211440. }
  211441. return true;
  211442. }
  211443. void getFamilyNames (StringArray& familyNames) const throw()
  211444. {
  211445. for (int i = 0; i < faces.size(); i++)
  211446. familyNames.add (faces[i]->getFamilyName());
  211447. }
  211448. void getMonospacedNames (StringArray& monoSpaced) const throw()
  211449. {
  211450. for (int i = 0; i < faces.size(); i++)
  211451. if (faces[i]->getMonospaced())
  211452. monoSpaced.add (faces[i]->getFamilyName());
  211453. }
  211454. void getSerifNames (StringArray& serif) const throw()
  211455. {
  211456. for (int i = 0; i < faces.size(); i++)
  211457. if (faces[i]->getSerif())
  211458. serif.add (faces[i]->getFamilyName());
  211459. }
  211460. void getSansSerifNames (StringArray& sansSerif) const throw()
  211461. {
  211462. for (int i = 0; i < faces.size(); i++)
  211463. if (! faces[i]->getSerif())
  211464. sansSerif.add (faces[i]->getFamilyName());
  211465. }
  211466. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  211467. private:
  211468. FT_Library ftLib;
  211469. FT_Face lastFace;
  211470. String lastFontName;
  211471. bool lastBold, lastItalic;
  211472. OwnedArray<FreeTypeFontFace> faces;
  211473. };
  211474. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  211475. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  211476. bool bold, bool italic,
  211477. bool addAllGlyphsToFont) throw()
  211478. {
  211479. FreeTypeInterface::getInstance()
  211480. ->createTypeface (fontName, bold, italic, *this, addAllGlyphsToFont);
  211481. }
  211482. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  211483. {
  211484. return FreeTypeInterface::getInstance()
  211485. ->addGlyphToFont (character, getName(), isBold(), isItalic(), *this);
  211486. }
  211487. const StringArray Font::findAllTypefaceNames() throw()
  211488. {
  211489. StringArray s;
  211490. FreeTypeInterface::getInstance()->getFamilyNames (s);
  211491. s.sort (true);
  211492. return s;
  211493. }
  211494. static const String pickBestFont (const StringArray& names,
  211495. const char* const choicesString)
  211496. {
  211497. StringArray choices;
  211498. choices.addTokens (String (choicesString), T(","), 0);
  211499. choices.trim();
  211500. choices.removeEmptyStrings();
  211501. int i, j;
  211502. for (j = 0; j < choices.size(); ++j)
  211503. if (names.contains (choices[j], true))
  211504. return choices[j];
  211505. for (j = 0; j < choices.size(); ++j)
  211506. for (i = 0; i < names.size(); i++)
  211507. if (names[i].startsWithIgnoreCase (choices[j]))
  211508. return names[i];
  211509. for (j = 0; j < choices.size(); ++j)
  211510. for (i = 0; i < names.size(); i++)
  211511. if (names[i].containsIgnoreCase (choices[j]))
  211512. return names[i];
  211513. return names[0];
  211514. }
  211515. static const String linux_getDefaultSansSerifFontName()
  211516. {
  211517. StringArray allFonts;
  211518. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  211519. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  211520. }
  211521. static const String linux_getDefaultSerifFontName()
  211522. {
  211523. StringArray allFonts;
  211524. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  211525. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  211526. }
  211527. static const String linux_getDefaultMonospacedFontName()
  211528. {
  211529. StringArray allFonts;
  211530. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  211531. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  211532. }
  211533. void Font::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  211534. {
  211535. defaultSans = linux_getDefaultSansSerifFontName();
  211536. defaultSerif = linux_getDefaultSerifFontName();
  211537. defaultFixed = linux_getDefaultMonospacedFontName();
  211538. }
  211539. END_JUCE_NAMESPACE
  211540. #endif
  211541. /********* End of inlined file: juce_linux_Fonts.cpp *********/
  211542. /********* Start of inlined file: juce_linux_Messaging.cpp *********/
  211543. #if JUCE_BUILD_GUI_CLASSES
  211544. #include <stdio.h>
  211545. #include <signal.h>
  211546. #include <X11/Xlib.h>
  211547. #include <X11/Xatom.h>
  211548. #include <X11/Xresource.h>
  211549. #include <X11/Xutil.h>
  211550. BEGIN_JUCE_NAMESPACE
  211551. #ifdef JUCE_DEBUG
  211552. #define JUCE_DEBUG_XERRORS 1
  211553. #endif
  211554. Display* display = 0; // This is also referenced from WindowDriver.cpp
  211555. static Window juce_messageWindowHandle = None;
  211556. #define SpecialAtom "JUCESpecialAtom"
  211557. #define BroadcastAtom "JUCEBroadcastAtom"
  211558. #define SpecialCallbackAtom "JUCESpecialCallbackAtom"
  211559. static Atom specialId;
  211560. static Atom broadcastId;
  211561. static Atom specialCallbackId;
  211562. // This is referenced from WindowDriver.cpp
  211563. XContext improbableNumber;
  211564. // Defined in WindowDriver.cpp
  211565. extern void juce_windowMessageReceive (XEvent* event);
  211566. struct MessageThreadFuncCall
  211567. {
  211568. MessageCallbackFunction* func;
  211569. void* parameter;
  211570. void* result;
  211571. CriticalSection lock;
  211572. WaitableEvent event;
  211573. };
  211574. static bool errorCondition = false;
  211575. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  211576. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  211577. // (defined in another file to avoid problems including certain headers in this one)
  211578. extern bool juce_isRunningAsApplication();
  211579. // Usually happens when client-server connection is broken
  211580. static int ioErrorHandler (Display* display)
  211581. {
  211582. DBG (T("ERROR: connection to X server broken.. terminating."));
  211583. errorCondition = true;
  211584. if (juce_isRunningAsApplication())
  211585. Process::terminate();
  211586. return 0;
  211587. }
  211588. // A protocol error has occurred
  211589. static int errorHandler (Display* display, XErrorEvent* event)
  211590. {
  211591. #ifdef JUCE_DEBUG_XERRORS
  211592. char errorStr[64] = { 0 };
  211593. char requestStr[64] = { 0 };
  211594. XGetErrorText (display, event->error_code, errorStr, 64);
  211595. XGetErrorDatabaseText (display,
  211596. "XRequest",
  211597. (const char*) String (event->request_code),
  211598. "Unknown",
  211599. requestStr,
  211600. 64);
  211601. DBG (T("ERROR: X returned ") + String (errorStr) + T(" for operation ") + String (requestStr));
  211602. #endif
  211603. return 0;
  211604. }
  211605. static bool breakIn = false;
  211606. // Breakin from keyboard
  211607. static void sig_handler (int sig)
  211608. {
  211609. if (sig == SIGINT)
  211610. {
  211611. breakIn = true;
  211612. return;
  211613. }
  211614. static bool reentrant = false;
  211615. if (reentrant == false)
  211616. {
  211617. reentrant = true;
  211618. // Illegal instruction
  211619. fflush (stdout);
  211620. Logger::outputDebugString ("ERROR: Program executed illegal instruction.. terminating");
  211621. errorCondition = true;
  211622. if (juce_isRunningAsApplication())
  211623. Process::terminate();
  211624. }
  211625. else
  211626. {
  211627. if (juce_isRunningAsApplication())
  211628. exit(0);
  211629. }
  211630. }
  211631. void MessageManager::doPlatformSpecificInitialisation()
  211632. {
  211633. // Initialise xlib for multiple thread support
  211634. static bool initThreadCalled = false;
  211635. if (! initThreadCalled)
  211636. {
  211637. if (! XInitThreads())
  211638. {
  211639. // This is fatal! Print error and closedown
  211640. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  211641. if (juce_isRunningAsApplication())
  211642. Process::terminate();
  211643. return;
  211644. }
  211645. initThreadCalled = true;
  211646. }
  211647. // This is called if the client/server connection is broken
  211648. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  211649. // This is called if a protocol error occurs
  211650. oldErrorHandler = XSetErrorHandler (errorHandler);
  211651. // Install signal handler for break-in
  211652. struct sigaction saction;
  211653. sigset_t maskSet;
  211654. sigemptyset (&maskSet);
  211655. saction.sa_handler = sig_handler;
  211656. saction.sa_mask = maskSet;
  211657. saction.sa_flags = 0;
  211658. sigaction (SIGINT, &saction, NULL);
  211659. #ifndef _DEBUG
  211660. // Setup signal handlers for various fatal errors
  211661. sigaction (SIGILL, &saction, NULL);
  211662. sigaction (SIGBUS, &saction, NULL);
  211663. sigaction (SIGFPE, &saction, NULL);
  211664. sigaction (SIGSEGV, &saction, NULL);
  211665. sigaction (SIGSYS, &saction, NULL);
  211666. #endif
  211667. String displayName (getenv ("DISPLAY"));
  211668. if (displayName.isEmpty())
  211669. displayName = T(":0.0");
  211670. display = XOpenDisplay (displayName);
  211671. if (display == 0)
  211672. {
  211673. // This is fatal! Print error and closedown
  211674. Logger::outputDebugString ("Failed to open the X display.");
  211675. if (juce_isRunningAsApplication())
  211676. Process::terminate();
  211677. return;
  211678. }
  211679. // Get defaults for various properties
  211680. int screen = DefaultScreen (display);
  211681. Window root = RootWindow (display, screen);
  211682. Visual* visual = DefaultVisual (display, screen);
  211683. // Create atoms for our ClientMessages (these cannot be deleted)
  211684. specialId = XInternAtom (display, SpecialAtom, false);
  211685. broadcastId = XInternAtom (display, BroadcastAtom, false);
  211686. specialCallbackId = XInternAtom (display, SpecialCallbackAtom, false);
  211687. // Create a context to store user data associated with Windows we
  211688. // create in WindowDriver
  211689. improbableNumber = XUniqueContext();
  211690. // We're only interested in client messages for this window
  211691. // which are always sent
  211692. XSetWindowAttributes swa;
  211693. swa.event_mask = NoEventMask;
  211694. // Create our message window (this will never be mapped)
  211695. juce_messageWindowHandle = XCreateWindow (display, root,
  211696. 0, 0, 1, 1, 0, 0, InputOnly,
  211697. visual, CWEventMask, &swa);
  211698. }
  211699. void MessageManager::doPlatformSpecificShutdown()
  211700. {
  211701. if (errorCondition == false)
  211702. {
  211703. XDestroyWindow (display, juce_messageWindowHandle);
  211704. XCloseDisplay (display);
  211705. // reset pointers
  211706. juce_messageWindowHandle = 0;
  211707. display = 0;
  211708. // Restore original error handlers
  211709. XSetIOErrorHandler (oldIOErrorHandler);
  211710. oldIOErrorHandler = 0;
  211711. XSetErrorHandler (oldErrorHandler);
  211712. oldErrorHandler = 0;
  211713. }
  211714. }
  211715. bool juce_postMessageToSystemQueue (void* message)
  211716. {
  211717. if (errorCondition)
  211718. return false;
  211719. XClientMessageEvent clientMsg;
  211720. clientMsg.display = display;
  211721. clientMsg.window = juce_messageWindowHandle;
  211722. clientMsg.type = ClientMessage;
  211723. clientMsg.format = 32;
  211724. clientMsg.message_type = specialId;
  211725. #if JUCE_64BIT
  211726. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) message) >> 32));
  211727. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (long) message);
  211728. #else
  211729. clientMsg.data.l[0] = (long) message;
  211730. #endif
  211731. XSendEvent (display, juce_messageWindowHandle, false,
  211732. NoEventMask, (XEvent*) &clientMsg);
  211733. XFlush (display); // This is necessary to ensure the event is delivered
  211734. return true;
  211735. }
  211736. void MessageManager::broadcastMessage (const String& value) throw()
  211737. {
  211738. }
  211739. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  211740. void* parameter)
  211741. {
  211742. void* retVal = 0;
  211743. if (! errorCondition)
  211744. {
  211745. if (! isThisTheMessageThread())
  211746. {
  211747. static MessageThreadFuncCall messageFuncCallContext;
  211748. const ScopedLock sl (messageFuncCallContext.lock);
  211749. XClientMessageEvent clientMsg;
  211750. clientMsg.display = display;
  211751. clientMsg.window = juce_messageWindowHandle;
  211752. clientMsg.type = ClientMessage;
  211753. clientMsg.format = 32;
  211754. clientMsg.message_type = specialCallbackId;
  211755. #if JUCE_64BIT
  211756. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) &messageFuncCallContext) >> 32));
  211757. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (uint64) &messageFuncCallContext);
  211758. #else
  211759. clientMsg.data.l[0] = (long) &messageFuncCallContext;
  211760. #endif
  211761. messageFuncCallContext.func = func;
  211762. messageFuncCallContext.parameter = parameter;
  211763. if (XSendEvent (display, juce_messageWindowHandle, false, NoEventMask, (XEvent*) &clientMsg) == 0)
  211764. return 0;
  211765. XFlush (display); // This is necessary to ensure the event is delivered
  211766. // Wait for it to complete before continuing
  211767. messageFuncCallContext.event.wait();
  211768. retVal = messageFuncCallContext.result;
  211769. }
  211770. else
  211771. {
  211772. // Just call the function directly
  211773. retVal = func (parameter);
  211774. }
  211775. }
  211776. return retVal;
  211777. }
  211778. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  211779. {
  211780. if (errorCondition)
  211781. return false;
  211782. if (breakIn)
  211783. {
  211784. errorCondition = true;
  211785. if (juce_isRunningAsApplication())
  211786. Process::terminate();
  211787. return false;
  211788. }
  211789. if (returnIfNoPendingMessages && ! XPending (display))
  211790. return false;
  211791. XEvent evt;
  211792. XNextEvent (display, &evt);
  211793. if (evt.type == ClientMessage && evt.xany.window == juce_messageWindowHandle)
  211794. {
  211795. XClientMessageEvent* const clientMsg = (XClientMessageEvent*) &evt;
  211796. if (clientMsg->format != 32)
  211797. {
  211798. jassertfalse
  211799. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received malformed client message.");
  211800. }
  211801. else
  211802. {
  211803. JUCE_TRY
  211804. {
  211805. #if JUCE_64BIT
  211806. void* const messagePtr
  211807. = (void*) ((0xffffffff00000000 & (((uint64) clientMsg->data.l[0]) << 32))
  211808. | (clientMsg->data.l[1] & 0x00000000ffffffff));
  211809. #else
  211810. void* const messagePtr = (void*) (clientMsg->data.l[0]);
  211811. #endif
  211812. if (clientMsg->message_type == specialId)
  211813. {
  211814. MessageManager::getInstance()->deliverMessage (messagePtr);
  211815. }
  211816. else if (clientMsg->message_type == specialCallbackId)
  211817. {
  211818. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) messagePtr;
  211819. MessageCallbackFunction* func = call->func;
  211820. call->result = (*func) (call->parameter);
  211821. call->event.signal();
  211822. }
  211823. else if (clientMsg->message_type == broadcastId)
  211824. {
  211825. #if 0
  211826. TCHAR buffer[8192];
  211827. zeromem (buffer, sizeof (buffer));
  211828. if (GlobalGetAtomName ((ATOM) lParam, buffer, 8192) != 0)
  211829. mq->deliverBroadcastMessage (String (buffer));
  211830. #endif
  211831. }
  211832. else
  211833. {
  211834. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received unknown client message.");
  211835. }
  211836. }
  211837. JUCE_CATCH_ALL
  211838. }
  211839. }
  211840. else if (evt.xany.window != juce_messageWindowHandle)
  211841. {
  211842. juce_windowMessageReceive (&evt);
  211843. }
  211844. return true;
  211845. }
  211846. END_JUCE_NAMESPACE
  211847. #endif
  211848. /********* End of inlined file: juce_linux_Messaging.cpp *********/
  211849. /********* Start of inlined file: juce_linux_Midi.cpp *********/
  211850. #if JUCE_BUILD_GUI_CLASSES
  211851. #if JUCE_ALSA
  211852. #include <alsa/asoundlib.h>
  211853. BEGIN_JUCE_NAMESPACE
  211854. static snd_seq_t* iterateDevices (const bool forInput,
  211855. StringArray& deviceNamesFound,
  211856. const int deviceIndexToOpen)
  211857. {
  211858. snd_seq_t* returnedHandle = 0;
  211859. snd_seq_t* seqHandle;
  211860. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  211861. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  211862. {
  211863. snd_seq_system_info_t* systemInfo;
  211864. snd_seq_client_info_t* clientInfo;
  211865. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  211866. {
  211867. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  211868. && snd_seq_client_info_malloc (&clientInfo) == 0)
  211869. {
  211870. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  211871. while (--numClients >= 0 && returnedHandle == 0)
  211872. {
  211873. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  211874. {
  211875. snd_seq_port_info_t* portInfo;
  211876. if (snd_seq_port_info_malloc (&portInfo) == 0)
  211877. {
  211878. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  211879. const int client = snd_seq_client_info_get_client (clientInfo);
  211880. snd_seq_port_info_set_client (portInfo, client);
  211881. snd_seq_port_info_set_port (portInfo, -1);
  211882. while (--numPorts >= 0)
  211883. {
  211884. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  211885. && (snd_seq_port_info_get_capability (portInfo)
  211886. & (forInput ? SND_SEQ_PORT_CAP_READ
  211887. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  211888. {
  211889. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  211890. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  211891. {
  211892. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  211893. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  211894. if (sourcePort != -1)
  211895. {
  211896. snd_seq_set_client_name (seqHandle,
  211897. forInput ? "Juce Midi Input"
  211898. : "Juce Midi Output");
  211899. const int portId
  211900. = snd_seq_create_simple_port (seqHandle,
  211901. forInput ? "Juce Midi In Port"
  211902. : "Juce Midi Out Port",
  211903. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  211904. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  211905. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  211906. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  211907. returnedHandle = seqHandle;
  211908. break;
  211909. }
  211910. }
  211911. }
  211912. }
  211913. snd_seq_port_info_free (portInfo);
  211914. }
  211915. }
  211916. }
  211917. snd_seq_client_info_free (clientInfo);
  211918. }
  211919. snd_seq_system_info_free (systemInfo);
  211920. }
  211921. if (returnedHandle == 0)
  211922. snd_seq_close (seqHandle);
  211923. }
  211924. deviceNamesFound.appendNumbersToDuplicates (true, true);
  211925. return returnedHandle;
  211926. }
  211927. static snd_seq_t* createDevice (const bool forInput,
  211928. const String& deviceNameToOpen)
  211929. {
  211930. snd_seq_t* seqHandle = 0;
  211931. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  211932. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  211933. {
  211934. snd_seq_set_client_name (seqHandle,
  211935. (const char*) (forInput ? (deviceNameToOpen + T(" Input"))
  211936. : (deviceNameToOpen + T(" Output"))));
  211937. const int portId
  211938. = snd_seq_create_simple_port (seqHandle,
  211939. forInput ? "in"
  211940. : "out",
  211941. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  211942. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  211943. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  211944. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  211945. if (portId < 0)
  211946. {
  211947. snd_seq_close (seqHandle);
  211948. seqHandle = 0;
  211949. }
  211950. }
  211951. return seqHandle;
  211952. }
  211953. class MidiOutputDevice
  211954. {
  211955. public:
  211956. MidiOutputDevice (MidiOutput* const midiOutput_,
  211957. snd_seq_t* const seqHandle_)
  211958. :
  211959. midiOutput (midiOutput_),
  211960. seqHandle (seqHandle_),
  211961. maxEventSize (16 * 1024)
  211962. {
  211963. jassert (seqHandle != 0 && midiOutput != 0);
  211964. snd_midi_event_new (maxEventSize, &midiParser);
  211965. }
  211966. ~MidiOutputDevice()
  211967. {
  211968. snd_midi_event_free (midiParser);
  211969. snd_seq_close (seqHandle);
  211970. }
  211971. void sendMessageNow (const MidiMessage& message)
  211972. {
  211973. if (message.getRawDataSize() > maxEventSize)
  211974. {
  211975. maxEventSize = message.getRawDataSize();
  211976. snd_midi_event_free (midiParser);
  211977. snd_midi_event_new (maxEventSize, &midiParser);
  211978. }
  211979. snd_seq_event_t event;
  211980. snd_seq_ev_clear (&event);
  211981. snd_midi_event_encode (midiParser,
  211982. message.getRawData(),
  211983. message.getRawDataSize(),
  211984. &event);
  211985. snd_midi_event_reset_encode (midiParser);
  211986. snd_seq_ev_set_source (&event, 0);
  211987. snd_seq_ev_set_subs (&event);
  211988. snd_seq_ev_set_direct (&event);
  211989. snd_seq_event_output_direct (seqHandle, &event);
  211990. }
  211991. juce_UseDebuggingNewOperator
  211992. private:
  211993. MidiOutput* const midiOutput;
  211994. snd_seq_t* const seqHandle;
  211995. snd_midi_event_t* midiParser;
  211996. int maxEventSize;
  211997. };
  211998. const StringArray MidiOutput::getDevices()
  211999. {
  212000. StringArray devices;
  212001. iterateDevices (false, devices, -1);
  212002. return devices;
  212003. }
  212004. int MidiOutput::getDefaultDeviceIndex()
  212005. {
  212006. return 0;
  212007. }
  212008. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  212009. {
  212010. MidiOutput* newDevice = 0;
  212011. StringArray devices;
  212012. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  212013. if (handle != 0)
  212014. {
  212015. newDevice = new MidiOutput();
  212016. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  212017. }
  212018. return newDevice;
  212019. }
  212020. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  212021. {
  212022. MidiOutput* newDevice = 0;
  212023. snd_seq_t* const handle = createDevice (false, deviceName);
  212024. if (handle != 0)
  212025. {
  212026. newDevice = new MidiOutput();
  212027. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  212028. }
  212029. return newDevice;
  212030. }
  212031. MidiOutput::~MidiOutput()
  212032. {
  212033. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  212034. delete device;
  212035. }
  212036. void MidiOutput::reset()
  212037. {
  212038. }
  212039. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212040. {
  212041. return false;
  212042. }
  212043. void MidiOutput::setVolume (float leftVol, float rightVol)
  212044. {
  212045. }
  212046. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212047. {
  212048. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  212049. }
  212050. class MidiInputThread : public Thread
  212051. {
  212052. public:
  212053. MidiInputThread (MidiInput* const midiInput_,
  212054. snd_seq_t* const seqHandle_,
  212055. MidiInputCallback* const callback_)
  212056. : Thread (T("Juce MIDI Input")),
  212057. midiInput (midiInput_),
  212058. seqHandle (seqHandle_),
  212059. callback (callback_)
  212060. {
  212061. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  212062. }
  212063. ~MidiInputThread()
  212064. {
  212065. snd_seq_close (seqHandle);
  212066. }
  212067. void run()
  212068. {
  212069. const int maxEventSize = 16 * 1024;
  212070. snd_midi_event_t* midiParser;
  212071. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  212072. {
  212073. uint8* const buffer = (uint8*) juce_malloc (maxEventSize);
  212074. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  212075. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  212076. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  212077. while (! threadShouldExit())
  212078. {
  212079. if (poll (pfd, numPfds, 500) > 0)
  212080. {
  212081. snd_seq_event_t* inputEvent = 0;
  212082. snd_seq_nonblock (seqHandle, 1);
  212083. do
  212084. {
  212085. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  212086. {
  212087. // xxx what about SYSEXes that are too big for the buffer?
  212088. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  212089. snd_midi_event_reset_decode (midiParser);
  212090. if (numBytes > 0)
  212091. {
  212092. const MidiMessage message ((const uint8*) buffer,
  212093. numBytes,
  212094. Time::getMillisecondCounter() * 0.001);
  212095. callback->handleIncomingMidiMessage (midiInput, message);
  212096. }
  212097. snd_seq_free_event (inputEvent);
  212098. }
  212099. }
  212100. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  212101. snd_seq_free_event (inputEvent);
  212102. }
  212103. }
  212104. snd_midi_event_free (midiParser);
  212105. juce_free (buffer);
  212106. }
  212107. };
  212108. juce_UseDebuggingNewOperator
  212109. private:
  212110. MidiInput* const midiInput;
  212111. snd_seq_t* const seqHandle;
  212112. MidiInputCallback* const callback;
  212113. };
  212114. MidiInput::MidiInput (const String& name_)
  212115. : name (name_),
  212116. internal (0)
  212117. {
  212118. }
  212119. MidiInput::~MidiInput()
  212120. {
  212121. stop();
  212122. MidiInputThread* const thread = (MidiInputThread*) internal;
  212123. delete thread;
  212124. }
  212125. void MidiInput::start()
  212126. {
  212127. ((MidiInputThread*) internal)->startThread();
  212128. }
  212129. void MidiInput::stop()
  212130. {
  212131. ((MidiInputThread*) internal)->stopThread (3000);
  212132. }
  212133. int MidiInput::getDefaultDeviceIndex()
  212134. {
  212135. return 0;
  212136. }
  212137. const StringArray MidiInput::getDevices()
  212138. {
  212139. StringArray devices;
  212140. iterateDevices (true, devices, -1);
  212141. return devices;
  212142. }
  212143. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  212144. {
  212145. MidiInput* newDevice = 0;
  212146. StringArray devices;
  212147. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  212148. if (handle != 0)
  212149. {
  212150. newDevice = new MidiInput (devices [deviceIndex]);
  212151. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  212152. }
  212153. return newDevice;
  212154. }
  212155. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  212156. {
  212157. MidiInput* newDevice = 0;
  212158. snd_seq_t* const handle = createDevice (true, deviceName);
  212159. if (handle != 0)
  212160. {
  212161. newDevice = new MidiInput (deviceName);
  212162. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  212163. }
  212164. return newDevice;
  212165. }
  212166. END_JUCE_NAMESPACE
  212167. #else
  212168. // (These are just stub functions if ALSA is unavailable...)
  212169. BEGIN_JUCE_NAMESPACE
  212170. const StringArray MidiOutput::getDevices() { return StringArray(); }
  212171. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  212172. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  212173. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  212174. MidiOutput::~MidiOutput() {}
  212175. void MidiOutput::reset() {}
  212176. bool MidiOutput::getVolume (float&, float&) { return false; }
  212177. void MidiOutput::setVolume (float, float) {}
  212178. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  212179. MidiInput::MidiInput (const String& name_)
  212180. : name (name_),
  212181. internal (0)
  212182. {}
  212183. MidiInput::~MidiInput() {}
  212184. void MidiInput::start() {}
  212185. void MidiInput::stop() {}
  212186. int MidiInput::getDefaultDeviceIndex() { return 0; }
  212187. const StringArray MidiInput::getDevices() { return StringArray(); }
  212188. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  212189. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  212190. END_JUCE_NAMESPACE
  212191. #endif
  212192. #endif
  212193. /********* End of inlined file: juce_linux_Midi.cpp *********/
  212194. /********* Start of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  212195. BEGIN_JUCE_NAMESPACE
  212196. /*
  212197. Sorry.. This class isn't implemented on Linux!
  212198. */
  212199. WebBrowserComponent::WebBrowserComponent()
  212200. : browser (0),
  212201. blankPageShown (false)
  212202. {
  212203. setOpaque (true);
  212204. }
  212205. WebBrowserComponent::~WebBrowserComponent()
  212206. {
  212207. }
  212208. void WebBrowserComponent::goToURL (const String& url,
  212209. const StringArray* headers,
  212210. const MemoryBlock* postData)
  212211. {
  212212. lastURL = url;
  212213. lastHeaders.clear();
  212214. if (headers != 0)
  212215. lastHeaders = *headers;
  212216. lastPostData.setSize (0);
  212217. if (postData != 0)
  212218. lastPostData = *postData;
  212219. blankPageShown = false;
  212220. }
  212221. void WebBrowserComponent::stop()
  212222. {
  212223. }
  212224. void WebBrowserComponent::goBack()
  212225. {
  212226. lastURL = String::empty;
  212227. blankPageShown = false;
  212228. }
  212229. void WebBrowserComponent::goForward()
  212230. {
  212231. lastURL = String::empty;
  212232. }
  212233. void WebBrowserComponent::paint (Graphics& g)
  212234. {
  212235. g.fillAll (Colours::white);
  212236. }
  212237. void WebBrowserComponent::checkWindowAssociation()
  212238. {
  212239. }
  212240. void WebBrowserComponent::reloadLastURL()
  212241. {
  212242. if (lastURL.isNotEmpty())
  212243. {
  212244. goToURL (lastURL, &lastHeaders, &lastPostData);
  212245. lastURL = String::empty;
  212246. }
  212247. }
  212248. void WebBrowserComponent::parentHierarchyChanged()
  212249. {
  212250. checkWindowAssociation();
  212251. }
  212252. void WebBrowserComponent::moved()
  212253. {
  212254. }
  212255. void WebBrowserComponent::resized()
  212256. {
  212257. }
  212258. void WebBrowserComponent::visibilityChanged()
  212259. {
  212260. checkWindowAssociation();
  212261. }
  212262. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  212263. {
  212264. return true;
  212265. }
  212266. END_JUCE_NAMESPACE
  212267. /********* End of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  212268. /********* Start of inlined file: juce_linux_Windowing.cpp *********/
  212269. #if JUCE_BUILD_GUI_CLASSES
  212270. #include <X11/Xlib.h>
  212271. #include <X11/Xutil.h>
  212272. #include <X11/Xatom.h>
  212273. #include <X11/Xmd.h>
  212274. #include <X11/keysym.h>
  212275. #include <X11/cursorfont.h>
  212276. #include <dlfcn.h>
  212277. #if JUCE_USE_XINERAMA
  212278. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package..
  212279. */
  212280. #include <X11/extensions/Xinerama.h>
  212281. #endif
  212282. #if JUCE_USE_XSHM
  212283. #include <X11/extensions/XShm.h>
  212284. #include <sys/shm.h>
  212285. #include <sys/ipc.h>
  212286. #endif
  212287. #if JUCE_OPENGL
  212288. /* Got an include error here?
  212289. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  212290. and "freeglut3-dev".
  212291. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  212292. want to disable it.
  212293. */
  212294. #include <GL/glx.h>
  212295. #endif
  212296. #undef KeyPress
  212297. BEGIN_JUCE_NAMESPACE
  212298. #define TAKE_FOCUS 0
  212299. #define DELETE_WINDOW 1
  212300. #define SYSTEM_TRAY_REQUEST_DOCK 0
  212301. #define SYSTEM_TRAY_BEGIN_MESSAGE 1
  212302. #define SYSTEM_TRAY_CANCEL_MESSAGE 2
  212303. static const int repaintTimerPeriod = 1000 / 100; // 100 fps maximum
  212304. static Atom wm_ChangeState = None;
  212305. static Atom wm_State = None;
  212306. static Atom wm_Protocols = None;
  212307. static Atom wm_ProtocolList [2] = { None, None };
  212308. static Atom wm_ActiveWin = None;
  212309. #define ourDndVersion 3
  212310. static Atom XA_XdndAware = None;
  212311. static Atom XA_XdndEnter = None;
  212312. static Atom XA_XdndLeave = None;
  212313. static Atom XA_XdndPosition = None;
  212314. static Atom XA_XdndStatus = None;
  212315. static Atom XA_XdndDrop = None;
  212316. static Atom XA_XdndFinished = None;
  212317. static Atom XA_XdndSelection = None;
  212318. static Atom XA_XdndProxy = None;
  212319. static Atom XA_XdndTypeList = None;
  212320. static Atom XA_XdndActionList = None;
  212321. static Atom XA_XdndActionDescription = None;
  212322. static Atom XA_XdndActionCopy = None;
  212323. static Atom XA_XdndActionMove = None;
  212324. static Atom XA_XdndActionLink = None;
  212325. static Atom XA_XdndActionAsk = None;
  212326. static Atom XA_XdndActionPrivate = None;
  212327. static Atom XA_JXSelectionWindowProperty = None;
  212328. static Atom XA_MimeTextPlain = None;
  212329. static Atom XA_MimeTextUriList = None;
  212330. static Atom XA_MimeRootDrop = None;
  212331. static XErrorHandler oldHandler = 0;
  212332. static int trappedErrorCode = 0;
  212333. extern "C" int errorTrapHandler (Display* dpy, XErrorEvent* err)
  212334. {
  212335. trappedErrorCode = err->error_code;
  212336. return 0;
  212337. }
  212338. static void trapErrors()
  212339. {
  212340. trappedErrorCode = 0;
  212341. oldHandler = XSetErrorHandler (errorTrapHandler);
  212342. }
  212343. static bool untrapErrors()
  212344. {
  212345. XSetErrorHandler (oldHandler);
  212346. return (trappedErrorCode == 0);
  212347. }
  212348. static bool isActiveApplication = false;
  212349. bool Process::isForegroundProcess() throw()
  212350. {
  212351. return isActiveApplication;
  212352. }
  212353. // (used in the messaging code, declared here for build reasons)
  212354. bool juce_isRunningAsApplication()
  212355. {
  212356. return JUCEApplication::getInstance() != 0;
  212357. }
  212358. // These are defined in juce_linux_Messaging.cpp
  212359. extern Display* display;
  212360. extern XContext improbableNumber;
  212361. static const int eventMask = NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  212362. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  212363. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  212364. static int pointerMap[5];
  212365. static int lastMousePosX = 0, lastMousePosY = 0;
  212366. enum MouseButtons
  212367. {
  212368. NoButton = 0,
  212369. LeftButton = 1,
  212370. MiddleButton = 2,
  212371. RightButton = 3,
  212372. WheelUp = 4,
  212373. WheelDown = 5
  212374. };
  212375. static void getMousePos (int& x, int& y, int& mouseMods) throw()
  212376. {
  212377. Window root, child;
  212378. int winx, winy;
  212379. unsigned int mask;
  212380. mouseMods = 0;
  212381. if (XQueryPointer (display,
  212382. RootWindow (display, DefaultScreen (display)),
  212383. &root, &child,
  212384. &x, &y, &winx, &winy, &mask) == False)
  212385. {
  212386. // Pointer not on the default screen
  212387. x = y = -1;
  212388. }
  212389. else
  212390. {
  212391. if ((mask & Button1Mask) != 0)
  212392. mouseMods |= ModifierKeys::leftButtonModifier;
  212393. if ((mask & Button2Mask) != 0)
  212394. mouseMods |= ModifierKeys::middleButtonModifier;
  212395. if ((mask & Button3Mask) != 0)
  212396. mouseMods |= ModifierKeys::rightButtonModifier;
  212397. }
  212398. }
  212399. static int AltMask = 0;
  212400. static int NumLockMask = 0;
  212401. static bool numLock = 0;
  212402. static bool capsLock = 0;
  212403. static char keyStates [32];
  212404. static void updateKeyStates (const int keycode, const bool press) throw()
  212405. {
  212406. const int keybyte = keycode >> 3;
  212407. const int keybit = (1 << (keycode & 7));
  212408. if (press)
  212409. keyStates [keybyte] |= keybit;
  212410. else
  212411. keyStates [keybyte] &= ~keybit;
  212412. }
  212413. static bool keyDown (const int keycode) throw()
  212414. {
  212415. const int keybyte = keycode >> 3;
  212416. const int keybit = (1 << (keycode & 7));
  212417. return (keyStates [keybyte] & keybit) != 0;
  212418. }
  212419. static const int extendedKeyModifier = 0x10000000;
  212420. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  212421. {
  212422. int keysym;
  212423. if (keyCode & extendedKeyModifier)
  212424. {
  212425. keysym = 0xff00 | (keyCode & 0xff);
  212426. }
  212427. else
  212428. {
  212429. keysym = keyCode;
  212430. if (keysym == (XK_Tab & 0xff)
  212431. || keysym == (XK_Return & 0xff)
  212432. || keysym == (XK_Escape & 0xff)
  212433. || keysym == (XK_BackSpace & 0xff))
  212434. {
  212435. keysym |= 0xff00;
  212436. }
  212437. }
  212438. return keyDown (XKeysymToKeycode (display, keysym));
  212439. }
  212440. // Alt and Num lock are not defined by standard X
  212441. // modifier constants: check what they're mapped to
  212442. static void getModifierMapping() throw()
  212443. {
  212444. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  212445. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  212446. AltMask = 0;
  212447. NumLockMask = 0;
  212448. XModifierKeymap* mapping = XGetModifierMapping (display);
  212449. if (mapping)
  212450. {
  212451. for (int i = 0; i < 8; i++)
  212452. {
  212453. if (mapping->modifiermap [i << 1] == altLeftCode)
  212454. AltMask = 1 << i;
  212455. else if (mapping->modifiermap [i << 1] == numLockCode)
  212456. NumLockMask = 1 << i;
  212457. }
  212458. XFreeModifiermap (mapping);
  212459. }
  212460. }
  212461. static int currentModifiers = 0;
  212462. void ModifierKeys::updateCurrentModifiers() throw()
  212463. {
  212464. currentModifierFlags = currentModifiers;
  212465. }
  212466. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  212467. {
  212468. int x, y, mouseMods;
  212469. getMousePos (x, y, mouseMods);
  212470. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  212471. currentModifiers |= mouseMods;
  212472. return ModifierKeys (currentModifiers);
  212473. }
  212474. static void updateKeyModifiers (const int status) throw()
  212475. {
  212476. currentModifiers &= ~(ModifierKeys::shiftModifier
  212477. | ModifierKeys::ctrlModifier
  212478. | ModifierKeys::altModifier);
  212479. if (status & ShiftMask)
  212480. currentModifiers |= ModifierKeys::shiftModifier;
  212481. if (status & ControlMask)
  212482. currentModifiers |= ModifierKeys::ctrlModifier;
  212483. if (status & AltMask)
  212484. currentModifiers |= ModifierKeys::altModifier;
  212485. numLock = ((status & NumLockMask) != 0);
  212486. capsLock = ((status & LockMask) != 0);
  212487. }
  212488. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  212489. {
  212490. int modifier = 0;
  212491. bool isModifier = true;
  212492. switch (sym)
  212493. {
  212494. case XK_Shift_L:
  212495. case XK_Shift_R:
  212496. modifier = ModifierKeys::shiftModifier;
  212497. break;
  212498. case XK_Control_L:
  212499. case XK_Control_R:
  212500. modifier = ModifierKeys::ctrlModifier;
  212501. break;
  212502. case XK_Alt_L:
  212503. case XK_Alt_R:
  212504. modifier = ModifierKeys::altModifier;
  212505. break;
  212506. case XK_Num_Lock:
  212507. if (press)
  212508. numLock = ! numLock;
  212509. break;
  212510. case XK_Caps_Lock:
  212511. if (press)
  212512. capsLock = ! capsLock;
  212513. break;
  212514. case XK_Scroll_Lock:
  212515. break;
  212516. default:
  212517. isModifier = false;
  212518. break;
  212519. }
  212520. if (modifier != 0)
  212521. {
  212522. if (press)
  212523. currentModifiers |= modifier;
  212524. else
  212525. currentModifiers &= ~modifier;
  212526. }
  212527. return isModifier;
  212528. }
  212529. #if JUCE_USE_XSHM
  212530. static bool isShmAvailable() throw()
  212531. {
  212532. static bool isChecked = false;
  212533. static bool isAvailable = false;
  212534. if (! isChecked)
  212535. {
  212536. isChecked = true;
  212537. int major, minor;
  212538. Bool pixmaps;
  212539. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  212540. {
  212541. trapErrors();
  212542. XShmSegmentInfo segmentInfo;
  212543. zerostruct (segmentInfo);
  212544. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  212545. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  212546. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  212547. xImage->bytes_per_line * xImage->height,
  212548. IPC_CREAT | 0777)) >= 0)
  212549. {
  212550. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  212551. if (segmentInfo.shmaddr != (void*) -1)
  212552. {
  212553. segmentInfo.readOnly = False;
  212554. xImage->data = segmentInfo.shmaddr;
  212555. XSync (display, False);
  212556. if (XShmAttach (display, &segmentInfo) != 0)
  212557. {
  212558. XSync (display, False);
  212559. XShmDetach (display, &segmentInfo);
  212560. isAvailable = true;
  212561. }
  212562. }
  212563. XFlush (display);
  212564. XDestroyImage (xImage);
  212565. shmdt (segmentInfo.shmaddr);
  212566. }
  212567. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  212568. isAvailable &= untrapErrors();
  212569. }
  212570. }
  212571. return isAvailable;
  212572. }
  212573. #endif
  212574. class XBitmapImage : public Image
  212575. {
  212576. public:
  212577. XBitmapImage (const PixelFormat format_, const int w, const int h,
  212578. const bool clearImage, const bool is16Bit_)
  212579. : Image (format_, w, h),
  212580. is16Bit (is16Bit_)
  212581. {
  212582. jassert (format_ == RGB || format_ == ARGB);
  212583. pixelStride = (format_ == RGB) ? 3 : 4;
  212584. lineStride = ((w * pixelStride + 3) & ~3);
  212585. Visual* const visual = DefaultVisual (display, DefaultScreen (display));
  212586. #if JUCE_USE_XSHM
  212587. usingXShm = false;
  212588. if ((! is16Bit) && isShmAvailable())
  212589. {
  212590. zerostruct (segmentInfo);
  212591. xImage = XShmCreateImage (display, visual, 24, ZPixmap, 0, &segmentInfo, w, h);
  212592. if (xImage != 0)
  212593. {
  212594. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  212595. xImage->bytes_per_line * xImage->height,
  212596. IPC_CREAT | 0777)) >= 0)
  212597. {
  212598. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  212599. if (segmentInfo.shmaddr != (void*) -1)
  212600. {
  212601. segmentInfo.readOnly = False;
  212602. xImage->data = segmentInfo.shmaddr;
  212603. imageData = (uint8*) segmentInfo.shmaddr;
  212604. XSync (display, False);
  212605. if (XShmAttach (display, &segmentInfo) != 0)
  212606. {
  212607. XSync (display, False);
  212608. usingXShm = true;
  212609. }
  212610. else
  212611. {
  212612. jassertfalse
  212613. }
  212614. }
  212615. else
  212616. {
  212617. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  212618. }
  212619. }
  212620. }
  212621. }
  212622. if (! usingXShm)
  212623. #endif
  212624. {
  212625. imageData = (uint8*) juce_malloc (lineStride * h);
  212626. if (format_ == ARGB && clearImage)
  212627. zeromem (imageData, h * lineStride);
  212628. xImage = (XImage*) juce_calloc (sizeof (XImage));
  212629. xImage->width = w;
  212630. xImage->height = h;
  212631. xImage->xoffset = 0;
  212632. xImage->format = ZPixmap;
  212633. xImage->data = (char*) imageData;
  212634. xImage->byte_order = ImageByteOrder (display);
  212635. xImage->bitmap_unit = BitmapUnit (display);
  212636. xImage->bitmap_bit_order = BitmapBitOrder (display);
  212637. xImage->bitmap_pad = 32;
  212638. xImage->depth = pixelStride * 8;
  212639. xImage->bytes_per_line = lineStride;
  212640. xImage->bits_per_pixel = pixelStride * 8;
  212641. xImage->red_mask = 0x00FF0000;
  212642. xImage->green_mask = 0x0000FF00;
  212643. xImage->blue_mask = 0x000000FF;
  212644. if (is16Bit)
  212645. {
  212646. const int pixelStride = 2;
  212647. const int lineStride = ((w * pixelStride + 3) & ~3);
  212648. xImage->data = (char*) juce_malloc (lineStride * h);
  212649. xImage->bitmap_pad = 16;
  212650. xImage->depth = pixelStride * 8;
  212651. xImage->bytes_per_line = lineStride;
  212652. xImage->bits_per_pixel = pixelStride * 8;
  212653. xImage->red_mask = visual->red_mask;
  212654. xImage->green_mask = visual->green_mask;
  212655. xImage->blue_mask = visual->blue_mask;
  212656. }
  212657. if (! XInitImage (xImage))
  212658. {
  212659. jassertfalse
  212660. }
  212661. }
  212662. }
  212663. ~XBitmapImage()
  212664. {
  212665. #if JUCE_USE_XSHM
  212666. if (usingXShm)
  212667. {
  212668. XShmDetach (display, &segmentInfo);
  212669. XFlush (display);
  212670. XDestroyImage (xImage);
  212671. shmdt (segmentInfo.shmaddr);
  212672. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  212673. }
  212674. else
  212675. #endif
  212676. {
  212677. juce_free (xImage->data);
  212678. xImage->data = 0;
  212679. XDestroyImage (xImage);
  212680. }
  212681. if (! is16Bit)
  212682. imageData = 0; // to stop the base class freeing this (for the 16-bit version we want it to free it)
  212683. }
  212684. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  212685. {
  212686. static GC gc = 0;
  212687. if (gc == 0)
  212688. gc = DefaultGC (display, DefaultScreen (display));
  212689. if (is16Bit)
  212690. {
  212691. const uint32 rMask = xImage->red_mask;
  212692. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  212693. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  212694. const uint32 gMask = xImage->green_mask;
  212695. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  212696. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  212697. const uint32 bMask = xImage->blue_mask;
  212698. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  212699. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  212700. int ls, ps;
  212701. const uint8* const pixels = lockPixelDataReadOnly (0, 0, getWidth(), getHeight(), ls, ps);
  212702. jassert (! isARGB())
  212703. for (int y = sy; y < sy + dh; ++y)
  212704. {
  212705. const uint8* p = pixels + y * ls + sx * ps;
  212706. for (int x = sx; x < sx + dw; ++x)
  212707. {
  212708. const PixelRGB* const pixel = (const PixelRGB*) p;
  212709. p += ps;
  212710. XPutPixel (xImage, x, y,
  212711. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  212712. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  212713. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  212714. }
  212715. }
  212716. releasePixelDataReadOnly (pixels);
  212717. }
  212718. // blit results to screen.
  212719. #if JUCE_USE_XSHM
  212720. if (usingXShm)
  212721. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, False);
  212722. else
  212723. #endif
  212724. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  212725. }
  212726. juce_UseDebuggingNewOperator
  212727. private:
  212728. XImage* xImage;
  212729. const bool is16Bit;
  212730. #if JUCE_USE_XSHM
  212731. XShmSegmentInfo segmentInfo;
  212732. bool usingXShm;
  212733. #endif
  212734. static int getShiftNeeded (const uint32 mask) throw()
  212735. {
  212736. for (int i = 32; --i >= 0;)
  212737. if (((mask >> i) & 1) != 0)
  212738. return i - 7;
  212739. jassertfalse
  212740. return 0;
  212741. }
  212742. };
  212743. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  212744. class LinuxComponentPeer : public ComponentPeer
  212745. {
  212746. public:
  212747. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  212748. : ComponentPeer (component, windowStyleFlags),
  212749. windowH (0),
  212750. parentWindow (0),
  212751. wx (0),
  212752. wy (0),
  212753. ww (0),
  212754. wh (0),
  212755. taskbarImage (0),
  212756. fullScreen (false),
  212757. entered (false),
  212758. mapped (false)
  212759. {
  212760. // it's dangerous to create a window on a thread other than the message thread..
  212761. checkMessageManagerIsLocked
  212762. repainter = new LinuxRepaintManager (this);
  212763. createWindow();
  212764. setTitle (component->getName());
  212765. }
  212766. ~LinuxComponentPeer()
  212767. {
  212768. // it's dangerous to delete a window on a thread other than the message thread..
  212769. checkMessageManagerIsLocked
  212770. deleteTaskBarIcon();
  212771. destroyWindow();
  212772. windowH = 0;
  212773. delete repainter;
  212774. }
  212775. void* getNativeHandle() const
  212776. {
  212777. return (void*) windowH;
  212778. }
  212779. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  212780. {
  212781. XPointer peer = 0;
  212782. if (! XFindContext (display, (XID) windowHandle, improbableNumber, &peer))
  212783. {
  212784. if (peer != 0 && ! ((LinuxComponentPeer*) peer)->isValidMessageListener())
  212785. peer = 0;
  212786. }
  212787. return (LinuxComponentPeer*) peer;
  212788. }
  212789. void setVisible (bool shouldBeVisible)
  212790. {
  212791. if (shouldBeVisible)
  212792. XMapWindow (display, windowH);
  212793. else
  212794. XUnmapWindow (display, windowH);
  212795. }
  212796. void setTitle (const String& title)
  212797. {
  212798. setWindowTitle (windowH, title);
  212799. }
  212800. void setPosition (int x, int y)
  212801. {
  212802. setBounds (x, y, ww, wh, false);
  212803. }
  212804. void setSize (int w, int h)
  212805. {
  212806. setBounds (wx, wy, w, h, false);
  212807. }
  212808. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  212809. {
  212810. fullScreen = isNowFullScreen;
  212811. if (windowH != 0)
  212812. {
  212813. const ComponentDeletionWatcher deletionChecker (component);
  212814. wx = x;
  212815. wy = y;
  212816. ww = jmax (1, w);
  212817. wh = jmax (1, h);
  212818. if (! mapped)
  212819. {
  212820. // Make sure the Window manager does what we want
  212821. XSizeHints* hints = XAllocSizeHints();
  212822. hints->flags = USSize | USPosition;
  212823. hints->width = ww + windowBorder.getLeftAndRight();
  212824. hints->height = wh + windowBorder.getTopAndBottom();
  212825. hints->x = wx - windowBorder.getLeft();
  212826. hints->y = wy - windowBorder.getTop();
  212827. XSetWMNormalHints (display, windowH, hints);
  212828. XFree (hints);
  212829. }
  212830. XMoveResizeWindow (display, windowH,
  212831. wx - windowBorder.getLeft(),
  212832. wy - windowBorder.getTop(),
  212833. ww + windowBorder.getLeftAndRight(),
  212834. wh + windowBorder.getTopAndBottom());
  212835. if (! deletionChecker.hasBeenDeleted())
  212836. {
  212837. updateBorderSize();
  212838. handleMovedOrResized();
  212839. }
  212840. }
  212841. }
  212842. void getBounds (int& x, int& y, int& w, int& h) const
  212843. {
  212844. x = wx;
  212845. y = wy;
  212846. w = ww;
  212847. h = wh;
  212848. }
  212849. int getScreenX() const
  212850. {
  212851. return wx;
  212852. }
  212853. int getScreenY() const
  212854. {
  212855. return wy;
  212856. }
  212857. void relativePositionToGlobal (int& x, int& y)
  212858. {
  212859. x += wx;
  212860. y += wy;
  212861. }
  212862. void globalPositionToRelative (int& x, int& y)
  212863. {
  212864. x -= wx;
  212865. y -= wy;
  212866. }
  212867. void setMinimised (bool shouldBeMinimised)
  212868. {
  212869. if (shouldBeMinimised)
  212870. {
  212871. Window root = RootWindow (display, DefaultScreen (display));
  212872. XClientMessageEvent clientMsg;
  212873. clientMsg.display = display;
  212874. clientMsg.window = windowH;
  212875. clientMsg.type = ClientMessage;
  212876. clientMsg.format = 32;
  212877. clientMsg.message_type = wm_ChangeState;
  212878. clientMsg.data.l[0] = IconicState;
  212879. XSendEvent (display, root, false,
  212880. SubstructureRedirectMask | SubstructureNotifyMask,
  212881. (XEvent*) &clientMsg);
  212882. }
  212883. else
  212884. {
  212885. setVisible (true);
  212886. }
  212887. }
  212888. bool isMinimised() const
  212889. {
  212890. bool minimised = false;
  212891. unsigned char* stateProp;
  212892. unsigned long nitems, bytesLeft;
  212893. Atom actualType;
  212894. int actualFormat;
  212895. if (XGetWindowProperty (display, windowH, wm_State, 0, 64, False,
  212896. wm_State, &actualType, &actualFormat, &nitems, &bytesLeft,
  212897. &stateProp) == Success
  212898. && actualType == wm_State
  212899. && actualFormat == 32
  212900. && nitems > 0)
  212901. {
  212902. if (((unsigned long*) stateProp)[0] == IconicState)
  212903. minimised = true;
  212904. XFree (stateProp);
  212905. }
  212906. return minimised;
  212907. }
  212908. void setFullScreen (const bool shouldBeFullScreen)
  212909. {
  212910. Rectangle r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  212911. setMinimised (false);
  212912. if (fullScreen != shouldBeFullScreen)
  212913. {
  212914. if (shouldBeFullScreen)
  212915. r = Desktop::getInstance().getMainMonitorArea();
  212916. if (! r.isEmpty())
  212917. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  212918. getComponent()->repaint();
  212919. }
  212920. }
  212921. bool isFullScreen() const
  212922. {
  212923. return fullScreen;
  212924. }
  212925. bool isChildWindowOf (Window possibleParent) const
  212926. {
  212927. Window* windowList = 0;
  212928. uint32 windowListSize = 0;
  212929. Window parent, root;
  212930. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  212931. {
  212932. if (windowList != 0)
  212933. XFree (windowList);
  212934. return parent == possibleParent;
  212935. }
  212936. return false;
  212937. }
  212938. bool isFrontWindow() const
  212939. {
  212940. Window* windowList = 0;
  212941. uint32 windowListSize = 0;
  212942. bool result = false;
  212943. Window parent, root = RootWindow (display, DefaultScreen (display));
  212944. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  212945. {
  212946. for (int i = windowListSize; --i >= 0;)
  212947. {
  212948. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  212949. if (peer != 0)
  212950. {
  212951. result = (peer == this);
  212952. break;
  212953. }
  212954. }
  212955. }
  212956. if (windowList != 0)
  212957. XFree (windowList);
  212958. return result;
  212959. }
  212960. bool contains (int x, int y, bool trueIfInAChildWindow) const
  212961. {
  212962. jassert (x >= 0 && y >= 0 && x < ww && y < wh); // should only be called for points that are actually inside the bounds
  212963. if (((unsigned int) x) >= (unsigned int) ww
  212964. || ((unsigned int) y) >= (unsigned int) wh)
  212965. return false;
  212966. bool inFront = false;
  212967. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  212968. {
  212969. Component* const c = Desktop::getInstance().getComponent (i);
  212970. if (inFront)
  212971. {
  212972. if (c->contains (x + wx - c->getScreenX(),
  212973. y + wy - c->getScreenY()))
  212974. {
  212975. return false;
  212976. }
  212977. }
  212978. else if (c == getComponent())
  212979. {
  212980. inFront = true;
  212981. }
  212982. }
  212983. if (trueIfInAChildWindow)
  212984. return true;
  212985. ::Window root, child;
  212986. unsigned int bw, depth;
  212987. int wx, wy, w, h;
  212988. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  212989. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  212990. &bw, &depth))
  212991. {
  212992. return false;
  212993. }
  212994. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  212995. return false;
  212996. return child == None;
  212997. }
  212998. const BorderSize getFrameSize() const
  212999. {
  213000. return BorderSize();
  213001. }
  213002. bool setAlwaysOnTop (bool alwaysOnTop)
  213003. {
  213004. if (windowH != 0)
  213005. {
  213006. const bool wasVisible = component->isVisible();
  213007. if (wasVisible)
  213008. setVisible (false); // doesn't always seem to work if the window is visible when this is done..
  213009. XSetWindowAttributes swa;
  213010. swa.override_redirect = alwaysOnTop ? True : False;
  213011. XChangeWindowAttributes (display, windowH, CWOverrideRedirect, &swa);
  213012. if (wasVisible)
  213013. setVisible (true);
  213014. }
  213015. return true;
  213016. }
  213017. void toFront (bool makeActive)
  213018. {
  213019. if (makeActive)
  213020. {
  213021. setVisible (true);
  213022. grabFocus();
  213023. }
  213024. XEvent ev;
  213025. ev.xclient.type = ClientMessage;
  213026. ev.xclient.serial = 0;
  213027. ev.xclient.send_event = True;
  213028. ev.xclient.message_type = wm_ActiveWin;
  213029. ev.xclient.window = windowH;
  213030. ev.xclient.format = 32;
  213031. ev.xclient.data.l[0] = 2;
  213032. ev.xclient.data.l[1] = CurrentTime;
  213033. ev.xclient.data.l[2] = 0;
  213034. ev.xclient.data.l[3] = 0;
  213035. ev.xclient.data.l[4] = 0;
  213036. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  213037. False,
  213038. SubstructureRedirectMask | SubstructureNotifyMask,
  213039. &ev);
  213040. XSync (display, False);
  213041. handleBroughtToFront();
  213042. }
  213043. void toBehind (ComponentPeer* other)
  213044. {
  213045. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  213046. jassert (otherPeer != 0); // wrong type of window?
  213047. if (otherPeer != 0)
  213048. {
  213049. setMinimised (false);
  213050. Window newStack[] = { otherPeer->windowH, windowH };
  213051. XRestackWindows (display, newStack, 2);
  213052. }
  213053. }
  213054. bool isFocused() const
  213055. {
  213056. int revert;
  213057. Window focusedWindow = 0;
  213058. XGetInputFocus (display, &focusedWindow, &revert);
  213059. return focusedWindow == windowH;
  213060. }
  213061. void grabFocus()
  213062. {
  213063. XWindowAttributes atts;
  213064. if (windowH != 0
  213065. && XGetWindowAttributes (display, windowH, &atts)
  213066. && atts.map_state == IsViewable
  213067. && ! isFocused())
  213068. {
  213069. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  213070. isActiveApplication = true;
  213071. }
  213072. }
  213073. void textInputRequired (int /*x*/, int /*y*/)
  213074. {
  213075. }
  213076. void repaint (int x, int y, int w, int h)
  213077. {
  213078. if (Rectangle::intersectRectangles (x, y, w, h,
  213079. 0, 0,
  213080. getComponent()->getWidth(),
  213081. getComponent()->getHeight()))
  213082. {
  213083. repainter->repaint (x, y, w, h);
  213084. }
  213085. }
  213086. void performAnyPendingRepaintsNow()
  213087. {
  213088. repainter->performAnyPendingRepaintsNow();
  213089. }
  213090. void setIcon (const Image& newIcon)
  213091. {
  213092. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  213093. uint32* const data = (uint32*) juce_malloc (dataSize);
  213094. int index = 0;
  213095. data[index++] = newIcon.getWidth();
  213096. data[index++] = newIcon.getHeight();
  213097. for (int y = 0; y < newIcon.getHeight(); ++y)
  213098. for (int x = 0; x < newIcon.getWidth(); ++x)
  213099. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  213100. XChangeProperty (display, windowH,
  213101. XInternAtom (display, "_NET_WM_ICON", False),
  213102. XA_CARDINAL, 32, PropModeReplace,
  213103. (unsigned char*) data, dataSize);
  213104. XSync (display, False);
  213105. juce_free (data);
  213106. }
  213107. void handleWindowMessage (XEvent* event)
  213108. {
  213109. switch (event->xany.type)
  213110. {
  213111. case 2: // 'KeyPress'
  213112. {
  213113. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  213114. updateKeyStates (keyEvent->keycode, true);
  213115. char utf8 [64];
  213116. zeromem (utf8, sizeof (utf8));
  213117. KeySym sym;
  213118. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  213119. const juce_wchar unicodeChar = *(const juce_wchar*) String::fromUTF8 ((const uint8*) utf8, sizeof (utf8) - 1);
  213120. int keyCode = (int) unicodeChar;
  213121. if (keyCode < 0x20)
  213122. keyCode = XKeycodeToKeysym (display, keyEvent->keycode,
  213123. (currentModifiers & ModifierKeys::shiftModifier) != 0 ? 1 : 0);
  213124. const int oldMods = currentModifiers;
  213125. bool keyPressed = false;
  213126. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  213127. if ((sym & 0xff00) == 0xff00)
  213128. {
  213129. // Translate keypad
  213130. if (sym == XK_KP_Divide)
  213131. keyCode = XK_slash;
  213132. else if (sym == XK_KP_Multiply)
  213133. keyCode = XK_asterisk;
  213134. else if (sym == XK_KP_Subtract)
  213135. keyCode = XK_hyphen;
  213136. else if (sym == XK_KP_Add)
  213137. keyCode = XK_plus;
  213138. else if (sym == XK_KP_Enter)
  213139. keyCode = XK_Return;
  213140. else if (sym == XK_KP_Decimal)
  213141. keyCode = numLock ? XK_period : XK_Delete;
  213142. else if (sym == XK_KP_0)
  213143. keyCode = numLock ? XK_0 : XK_Insert;
  213144. else if (sym == XK_KP_1)
  213145. keyCode = numLock ? XK_1 : XK_End;
  213146. else if (sym == XK_KP_2)
  213147. keyCode = numLock ? XK_2 : XK_Down;
  213148. else if (sym == XK_KP_3)
  213149. keyCode = numLock ? XK_3 : XK_Page_Down;
  213150. else if (sym == XK_KP_4)
  213151. keyCode = numLock ? XK_4 : XK_Left;
  213152. else if (sym == XK_KP_5)
  213153. keyCode = XK_5;
  213154. else if (sym == XK_KP_6)
  213155. keyCode = numLock ? XK_6 : XK_Right;
  213156. else if (sym == XK_KP_7)
  213157. keyCode = numLock ? XK_7 : XK_Home;
  213158. else if (sym == XK_KP_8)
  213159. keyCode = numLock ? XK_8 : XK_Up;
  213160. else if (sym == XK_KP_9)
  213161. keyCode = numLock ? XK_9 : XK_Page_Up;
  213162. switch (sym)
  213163. {
  213164. case XK_Left:
  213165. case XK_Right:
  213166. case XK_Up:
  213167. case XK_Down:
  213168. case XK_Page_Up:
  213169. case XK_Page_Down:
  213170. case XK_End:
  213171. case XK_Home:
  213172. case XK_Delete:
  213173. case XK_Insert:
  213174. keyPressed = true;
  213175. keyCode = (sym & 0xff) | extendedKeyModifier;
  213176. break;
  213177. case XK_Tab:
  213178. case XK_Return:
  213179. case XK_Escape:
  213180. case XK_BackSpace:
  213181. keyPressed = true;
  213182. keyCode &= 0xff;
  213183. break;
  213184. default:
  213185. {
  213186. if (sym >= XK_F1 && sym <= XK_F16)
  213187. {
  213188. keyPressed = true;
  213189. keyCode = (sym & 0xff) | extendedKeyModifier;
  213190. }
  213191. break;
  213192. }
  213193. }
  213194. }
  213195. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  213196. keyPressed = true;
  213197. if (oldMods != currentModifiers)
  213198. handleModifierKeysChange();
  213199. if (keyDownChange)
  213200. handleKeyUpOrDown();
  213201. if (keyPressed)
  213202. handleKeyPress (keyCode, unicodeChar);
  213203. break;
  213204. }
  213205. case KeyRelease:
  213206. {
  213207. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  213208. updateKeyStates (keyEvent->keycode, false);
  213209. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  213210. const int oldMods = currentModifiers;
  213211. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  213212. if (oldMods != currentModifiers)
  213213. handleModifierKeysChange();
  213214. if (keyDownChange)
  213215. handleKeyUpOrDown();
  213216. break;
  213217. }
  213218. case ButtonPress:
  213219. {
  213220. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  213221. bool buttonMsg = false;
  213222. bool wheelUpMsg = false;
  213223. bool wheelDownMsg = false;
  213224. const int map = pointerMap [buttonPressEvent->button - Button1];
  213225. if (map == LeftButton)
  213226. {
  213227. currentModifiers |= ModifierKeys::leftButtonModifier;
  213228. buttonMsg = true;
  213229. }
  213230. else if (map == RightButton)
  213231. {
  213232. currentModifiers |= ModifierKeys::rightButtonModifier;
  213233. buttonMsg = true;
  213234. }
  213235. else if (map == MiddleButton)
  213236. {
  213237. currentModifiers |= ModifierKeys::middleButtonModifier;
  213238. buttonMsg = true;
  213239. }
  213240. else if (map == WheelUp)
  213241. {
  213242. wheelUpMsg = true;
  213243. }
  213244. else if (map == WheelDown)
  213245. {
  213246. wheelDownMsg = true;
  213247. }
  213248. updateKeyModifiers (buttonPressEvent->state);
  213249. if (buttonMsg)
  213250. {
  213251. toFront (true);
  213252. handleMouseDown (buttonPressEvent->x, buttonPressEvent->y,
  213253. getEventTime (buttonPressEvent->time));
  213254. }
  213255. else if (wheelUpMsg || wheelDownMsg)
  213256. {
  213257. handleMouseWheel (0, wheelDownMsg ? -84 : 84,
  213258. getEventTime (buttonPressEvent->time));
  213259. }
  213260. lastMousePosX = lastMousePosY = 0x100000;
  213261. break;
  213262. }
  213263. case ButtonRelease:
  213264. {
  213265. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  213266. const int oldModifiers = currentModifiers;
  213267. const int map = pointerMap [buttonRelEvent->button - Button1];
  213268. if (map == LeftButton)
  213269. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  213270. else if (map == RightButton)
  213271. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  213272. else if (map == MiddleButton)
  213273. currentModifiers &= ~ModifierKeys::middleButtonModifier;
  213274. updateKeyModifiers (buttonRelEvent->state);
  213275. handleMouseUp (oldModifiers,
  213276. buttonRelEvent->x, buttonRelEvent->y,
  213277. getEventTime (buttonRelEvent->time));
  213278. lastMousePosX = lastMousePosY = 0x100000;
  213279. break;
  213280. }
  213281. case MotionNotify:
  213282. {
  213283. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  213284. updateKeyModifiers (movedEvent->state);
  213285. int x, y, mouseMods;
  213286. getMousePos (x, y, mouseMods);
  213287. if (lastMousePosX != x || lastMousePosY != y)
  213288. {
  213289. lastMousePosX = x;
  213290. lastMousePosY = y;
  213291. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  213292. {
  213293. Window wRoot = 0, wParent = 0;
  213294. Window* wChild = 0;
  213295. unsigned int numChildren;
  213296. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  213297. if (wParent != 0
  213298. && wParent != windowH
  213299. && wParent != wRoot)
  213300. {
  213301. parentWindow = wParent;
  213302. updateBounds();
  213303. x -= getScreenX();
  213304. y -= getScreenY();
  213305. }
  213306. else
  213307. {
  213308. parentWindow = 0;
  213309. x -= getScreenX();
  213310. y -= getScreenY();
  213311. }
  213312. }
  213313. else
  213314. {
  213315. x -= getScreenX();
  213316. y -= getScreenY();
  213317. }
  213318. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0)
  213319. handleMouseMove (x, y, getEventTime (movedEvent->time));
  213320. else
  213321. handleMouseDrag (x, y, getEventTime (movedEvent->time));
  213322. }
  213323. break;
  213324. }
  213325. case EnterNotify:
  213326. {
  213327. lastMousePosX = lastMousePosY = 0x100000;
  213328. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  213329. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  213330. && ! entered)
  213331. {
  213332. updateKeyModifiers (enterEvent->state);
  213333. handleMouseEnter (enterEvent->x, enterEvent->y, getEventTime (enterEvent->time));
  213334. entered = true;
  213335. }
  213336. break;
  213337. }
  213338. case LeaveNotify:
  213339. {
  213340. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  213341. // Suppress the normal leave if we've got a pointer grab, or if
  213342. // it's a bogus one caused by clicking a mouse button when running
  213343. // in a Window manager
  213344. if (((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  213345. && leaveEvent->mode == NotifyNormal)
  213346. || leaveEvent->mode == NotifyUngrab)
  213347. {
  213348. updateKeyModifiers (leaveEvent->state);
  213349. handleMouseExit (leaveEvent->x, leaveEvent->y, getEventTime (leaveEvent->time));
  213350. entered = false;
  213351. }
  213352. break;
  213353. }
  213354. case FocusIn:
  213355. {
  213356. isActiveApplication = true;
  213357. if (isFocused())
  213358. handleFocusGain();
  213359. break;
  213360. }
  213361. case FocusOut:
  213362. {
  213363. isActiveApplication = false;
  213364. if (! isFocused())
  213365. handleFocusLoss();
  213366. break;
  213367. }
  213368. case Expose:
  213369. {
  213370. // Batch together all pending expose events
  213371. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  213372. XEvent nextEvent;
  213373. if (exposeEvent->window != windowH)
  213374. {
  213375. Window child;
  213376. XTranslateCoordinates (display, exposeEvent->window, windowH,
  213377. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  213378. &child);
  213379. }
  213380. repaint (exposeEvent->x, exposeEvent->y,
  213381. exposeEvent->width, exposeEvent->height);
  213382. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  213383. {
  213384. XPeekEvent (display, (XEvent*) &nextEvent);
  213385. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  213386. break;
  213387. XNextEvent (display, (XEvent*) &nextEvent);
  213388. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  213389. repaint (nextExposeEvent->x, nextExposeEvent->y,
  213390. nextExposeEvent->width, nextExposeEvent->height);
  213391. }
  213392. break;
  213393. }
  213394. case CirculateNotify:
  213395. case CreateNotify:
  213396. case DestroyNotify:
  213397. // Think we can ignore these
  213398. break;
  213399. case ConfigureNotify:
  213400. {
  213401. updateBounds();
  213402. updateBorderSize();
  213403. handleMovedOrResized();
  213404. // if the native title bar is dragged, need to tell any active menus, etc.
  213405. if ((styleFlags & windowHasTitleBar) != 0
  213406. && component->isCurrentlyBlockedByAnotherModalComponent())
  213407. {
  213408. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  213409. if (currentModalComp != 0)
  213410. currentModalComp->inputAttemptWhenModal();
  213411. }
  213412. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  213413. if (confEvent->window == windowH
  213414. && confEvent->above != 0
  213415. && isFrontWindow())
  213416. {
  213417. handleBroughtToFront();
  213418. }
  213419. break;
  213420. }
  213421. case ReparentNotify:
  213422. case GravityNotify:
  213423. {
  213424. parentWindow = 0;
  213425. Window wRoot = 0;
  213426. Window* wChild = 0;
  213427. unsigned int numChildren;
  213428. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  213429. if (parentWindow == windowH || parentWindow == wRoot)
  213430. parentWindow = 0;
  213431. updateBounds();
  213432. updateBorderSize();
  213433. handleMovedOrResized();
  213434. break;
  213435. }
  213436. case MapNotify:
  213437. mapped = true;
  213438. handleBroughtToFront();
  213439. break;
  213440. case UnmapNotify:
  213441. mapped = false;
  213442. break;
  213443. case MappingNotify:
  213444. {
  213445. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  213446. if (mappingEvent->request != MappingPointer)
  213447. {
  213448. // Deal with modifier/keyboard mapping
  213449. XRefreshKeyboardMapping (mappingEvent);
  213450. getModifierMapping();
  213451. }
  213452. break;
  213453. }
  213454. case ClientMessage:
  213455. {
  213456. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  213457. if (clientMsg->message_type == wm_Protocols && clientMsg->format == 32)
  213458. {
  213459. const Atom atom = (Atom) clientMsg->data.l[0];
  213460. if (atom == wm_ProtocolList [TAKE_FOCUS])
  213461. {
  213462. XWindowAttributes atts;
  213463. if (clientMsg->window != 0
  213464. && XGetWindowAttributes (display, clientMsg->window, &atts))
  213465. {
  213466. if (atts.map_state == IsViewable)
  213467. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  213468. }
  213469. }
  213470. else if (atom == wm_ProtocolList [DELETE_WINDOW])
  213471. {
  213472. handleUserClosingWindow();
  213473. }
  213474. }
  213475. else if (clientMsg->message_type == XA_XdndEnter)
  213476. {
  213477. handleDragAndDropEnter (clientMsg);
  213478. }
  213479. else if (clientMsg->message_type == XA_XdndLeave)
  213480. {
  213481. resetDragAndDrop();
  213482. }
  213483. else if (clientMsg->message_type == XA_XdndPosition)
  213484. {
  213485. handleDragAndDropPosition (clientMsg);
  213486. }
  213487. else if (clientMsg->message_type == XA_XdndDrop)
  213488. {
  213489. handleDragAndDropDrop (clientMsg);
  213490. }
  213491. else if (clientMsg->message_type == XA_XdndStatus)
  213492. {
  213493. handleDragAndDropStatus (clientMsg);
  213494. }
  213495. else if (clientMsg->message_type == XA_XdndFinished)
  213496. {
  213497. resetDragAndDrop();
  213498. }
  213499. break;
  213500. }
  213501. case SelectionNotify:
  213502. handleDragAndDropSelection (event);
  213503. break;
  213504. case SelectionClear:
  213505. case SelectionRequest:
  213506. break;
  213507. default:
  213508. break;
  213509. }
  213510. }
  213511. void showMouseCursor (Cursor cursor) throw()
  213512. {
  213513. XDefineCursor (display, windowH, cursor);
  213514. }
  213515. void setTaskBarIcon (const Image& image)
  213516. {
  213517. deleteTaskBarIcon();
  213518. taskbarImage = image.createCopy();
  213519. Screen* const screen = XDefaultScreenOfDisplay (display);
  213520. const int screenNumber = XScreenNumberOfScreen (screen);
  213521. char screenAtom[32];
  213522. snprintf (screenAtom, sizeof (screenAtom), "_NET_SYSTEM_TRAY_S%d", screenNumber);
  213523. Atom selectionAtom = XInternAtom (display, screenAtom, false);
  213524. XGrabServer (display);
  213525. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  213526. if (managerWin != None)
  213527. XSelectInput (display, managerWin, StructureNotifyMask);
  213528. XUngrabServer (display);
  213529. XFlush (display);
  213530. if (managerWin != None)
  213531. {
  213532. XEvent ev;
  213533. zerostruct (ev);
  213534. ev.xclient.type = ClientMessage;
  213535. ev.xclient.window = managerWin;
  213536. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  213537. ev.xclient.format = 32;
  213538. ev.xclient.data.l[0] = CurrentTime;
  213539. ev.xclient.data.l[1] = SYSTEM_TRAY_REQUEST_DOCK;
  213540. ev.xclient.data.l[2] = windowH;
  213541. ev.xclient.data.l[3] = 0;
  213542. ev.xclient.data.l[4] = 0;
  213543. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  213544. XSync (display, False);
  213545. }
  213546. // For older KDE's ...
  213547. long atomData = 1;
  213548. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  213549. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  213550. // For more recent KDE's...
  213551. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  213552. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  213553. }
  213554. void deleteTaskBarIcon()
  213555. {
  213556. deleteAndZero (taskbarImage);
  213557. }
  213558. const Image* getTaskbarIcon() const throw() { return taskbarImage; }
  213559. juce_UseDebuggingNewOperator
  213560. bool dontRepaint;
  213561. private:
  213562. class LinuxRepaintManager : public Timer
  213563. {
  213564. public:
  213565. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  213566. : peer (peer_),
  213567. image (0),
  213568. lastTimeImageUsed (0)
  213569. {
  213570. #if JUCE_USE_XSHM
  213571. useARGBImagesForRendering = isShmAvailable();
  213572. if (useARGBImagesForRendering)
  213573. {
  213574. XShmSegmentInfo segmentinfo;
  213575. XImage* const testImage
  213576. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  213577. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  213578. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  213579. XDestroyImage (testImage);
  213580. }
  213581. #endif
  213582. }
  213583. ~LinuxRepaintManager()
  213584. {
  213585. delete image;
  213586. }
  213587. void timerCallback()
  213588. {
  213589. if (! regionsNeedingRepaint.isEmpty())
  213590. {
  213591. stopTimer();
  213592. performAnyPendingRepaintsNow();
  213593. }
  213594. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  213595. {
  213596. stopTimer();
  213597. deleteAndZero (image);
  213598. }
  213599. }
  213600. void repaint (int x, int y, int w, int h)
  213601. {
  213602. if (! isTimerRunning())
  213603. startTimer (repaintTimerPeriod);
  213604. regionsNeedingRepaint.add (x, y, w, h);
  213605. }
  213606. void performAnyPendingRepaintsNow()
  213607. {
  213608. peer->clearMaskedRegion();
  213609. const Rectangle totalArea (regionsNeedingRepaint.getBounds());
  213610. if (! totalArea.isEmpty())
  213611. {
  213612. if (image == 0 || image->getWidth() < totalArea.getWidth()
  213613. || image->getHeight() < totalArea.getHeight())
  213614. {
  213615. delete image;
  213616. #if JUCE_USE_XSHM
  213617. image = new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  213618. : Image::RGB,
  213619. #else
  213620. image = new XBitmapImage (Image::RGB,
  213621. #endif
  213622. (totalArea.getWidth() + 31) & ~31,
  213623. (totalArea.getHeight() + 31) & ~31,
  213624. false,
  213625. peer->depthIs16Bit);
  213626. }
  213627. startTimer (repaintTimerPeriod);
  213628. LowLevelGraphicsSoftwareRenderer context (*image);
  213629. context.setOrigin (-totalArea.getX(), -totalArea.getY());
  213630. if (context.reduceClipRegion (regionsNeedingRepaint))
  213631. peer->handlePaint (context);
  213632. if (! peer->maskedRegion.isEmpty())
  213633. regionsNeedingRepaint.subtract (peer->maskedRegion);
  213634. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  213635. {
  213636. const Rectangle& r = *i.getRectangle();
  213637. image->blitToWindow (peer->windowH,
  213638. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  213639. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  213640. }
  213641. }
  213642. regionsNeedingRepaint.clear();
  213643. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  213644. startTimer (repaintTimerPeriod);
  213645. }
  213646. private:
  213647. LinuxComponentPeer* const peer;
  213648. XBitmapImage* image;
  213649. uint32 lastTimeImageUsed;
  213650. RectangleList regionsNeedingRepaint;
  213651. #if JUCE_USE_XSHM
  213652. bool useARGBImagesForRendering;
  213653. #endif
  213654. LinuxRepaintManager (const LinuxRepaintManager&);
  213655. const LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  213656. };
  213657. LinuxRepaintManager* repainter;
  213658. friend class LinuxRepaintManager;
  213659. Window windowH, parentWindow;
  213660. int wx, wy, ww, wh;
  213661. Image* taskbarImage;
  213662. bool fullScreen, entered, mapped, depthIs16Bit;
  213663. BorderSize windowBorder;
  213664. void removeWindowDecorations (Window wndH)
  213665. {
  213666. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  213667. if (hints != None)
  213668. {
  213669. typedef struct
  213670. {
  213671. unsigned long flags;
  213672. unsigned long functions;
  213673. unsigned long decorations;
  213674. long input_mode;
  213675. unsigned long status;
  213676. } MotifWmHints;
  213677. MotifWmHints motifHints;
  213678. zerostruct (motifHints);
  213679. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  213680. motifHints.decorations = 0;
  213681. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  213682. (unsigned char*) &motifHints, 4);
  213683. }
  213684. hints = XInternAtom (display, "_WIN_HINTS", True);
  213685. if (hints != None)
  213686. {
  213687. long gnomeHints = 0;
  213688. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  213689. (unsigned char*) &gnomeHints, 1);
  213690. }
  213691. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  213692. if (hints != None)
  213693. {
  213694. long kwmHints = 2; /*KDE_tinyDecoration*/
  213695. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  213696. (unsigned char*) &kwmHints, 1);
  213697. }
  213698. hints = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  213699. if (hints != None)
  213700. {
  213701. long netHints [2];
  213702. netHints[0] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  213703. if ((styleFlags & windowIsTemporary) != 0)
  213704. netHints[1] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_MENU", True);
  213705. else
  213706. netHints[1] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  213707. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  213708. (unsigned char*) &netHints, 2);
  213709. }
  213710. }
  213711. void addWindowButtons (Window wndH)
  213712. {
  213713. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  213714. if (hints != None)
  213715. {
  213716. typedef struct
  213717. {
  213718. unsigned long flags;
  213719. unsigned long functions;
  213720. unsigned long decorations;
  213721. long input_mode;
  213722. unsigned long status;
  213723. } MotifWmHints;
  213724. MotifWmHints motifHints;
  213725. zerostruct (motifHints);
  213726. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  213727. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  213728. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  213729. if ((styleFlags & windowHasCloseButton) != 0)
  213730. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  213731. if ((styleFlags & windowHasMinimiseButton) != 0)
  213732. {
  213733. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  213734. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  213735. }
  213736. if ((styleFlags & windowHasMaximiseButton) != 0)
  213737. {
  213738. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  213739. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  213740. }
  213741. if ((styleFlags & windowIsResizable) != 0)
  213742. {
  213743. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  213744. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  213745. }
  213746. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  213747. }
  213748. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  213749. if (hints != None)
  213750. {
  213751. long netHints [6];
  213752. int num = 0;
  213753. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", (styleFlags & windowIsResizable) ? True : False);
  213754. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", (styleFlags & windowHasMaximiseButton) ? True : False);
  213755. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", (styleFlags & windowHasMinimiseButton) ? True : False);
  213756. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", (styleFlags & windowHasCloseButton) ? True : False);
  213757. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  213758. (unsigned char*) &netHints, num);
  213759. }
  213760. }
  213761. void createWindow()
  213762. {
  213763. static bool atomsInitialised = false;
  213764. if (! atomsInitialised)
  213765. {
  213766. atomsInitialised = true;
  213767. wm_Protocols = XInternAtom (display, "WM_PROTOCOLS", 1);
  213768. wm_ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", 1);
  213769. wm_ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", 1);
  213770. wm_ChangeState = XInternAtom (display, "WM_CHANGE_STATE", 1);
  213771. wm_State = XInternAtom (display, "WM_STATE", 1);
  213772. wm_ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  213773. XA_XdndAware = XInternAtom (display, "XdndAware", 0);
  213774. XA_XdndEnter = XInternAtom (display, "XdndEnter", 0);
  213775. XA_XdndLeave = XInternAtom (display, "XdndLeave", 0);
  213776. XA_XdndPosition = XInternAtom (display, "XdndPosition", 0);
  213777. XA_XdndStatus = XInternAtom (display, "XdndStatus", 0);
  213778. XA_XdndDrop = XInternAtom (display, "XdndDrop", 0);
  213779. XA_XdndFinished = XInternAtom (display, "XdndFinished", 0);
  213780. XA_XdndSelection = XInternAtom (display, "XdndSelection", 0);
  213781. XA_XdndProxy = XInternAtom (display, "XdndProxy", 0);
  213782. XA_XdndTypeList = XInternAtom (display, "XdndTypeList", 0);
  213783. XA_XdndActionList = XInternAtom (display, "XdndActionList", 0);
  213784. XA_XdndActionCopy = XInternAtom (display, "XdndActionCopy", 0);
  213785. XA_XdndActionMove = XInternAtom (display, "XdndActionMove", 0);
  213786. XA_XdndActionLink = XInternAtom (display, "XdndActionLink", 0);
  213787. XA_XdndActionAsk = XInternAtom (display, "XdndActionAsk", 0);
  213788. XA_XdndActionPrivate = XInternAtom (display, "XdndActionPrivate", 0);
  213789. XA_XdndActionDescription = XInternAtom (display, "XdndActionDescription", 0);
  213790. XA_JXSelectionWindowProperty = XInternAtom (display, "JXSelectionWindowProperty", 0);
  213791. XA_MimeTextPlain = XInternAtom (display, "text/plain", 0);
  213792. XA_MimeTextUriList = XInternAtom (display, "text/uri-list", 0);
  213793. XA_MimeRootDrop = XInternAtom (display, "application/x-rootwindow-drop", 0);
  213794. }
  213795. resetDragAndDrop();
  213796. XA_OtherMime = XA_MimeTextPlain; // xxx why??
  213797. allowedMimeTypeAtoms [0] = XA_MimeTextPlain;
  213798. allowedMimeTypeAtoms [1] = XA_OtherMime;
  213799. allowedMimeTypeAtoms [2] = XA_MimeTextUriList;
  213800. allowedActions [0] = XA_XdndActionMove;
  213801. allowedActions [1] = XA_XdndActionCopy;
  213802. allowedActions [2] = XA_XdndActionLink;
  213803. allowedActions [3] = XA_XdndActionAsk;
  213804. allowedActions [4] = XA_XdndActionPrivate;
  213805. // Get defaults for various properties
  213806. const int screen = DefaultScreen (display);
  213807. Window root = RootWindow (display, screen);
  213808. // Attempt to create a 24-bit window on the default screen. If this is not
  213809. // possible then exit
  213810. XVisualInfo desiredVisual;
  213811. desiredVisual.screen = screen;
  213812. desiredVisual.depth = 24;
  213813. depthIs16Bit = false;
  213814. int numVisuals;
  213815. XVisualInfo* visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  213816. &desiredVisual, &numVisuals);
  213817. if (numVisuals < 1 || visuals == 0)
  213818. {
  213819. XFree (visuals);
  213820. desiredVisual.depth = 16;
  213821. visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  213822. &desiredVisual, &numVisuals);
  213823. if (numVisuals < 1 || visuals == 0)
  213824. {
  213825. Logger::outputDebugString ("ERROR: System doesn't support 24 or 16 bit RGB display.\n");
  213826. Process::terminate();
  213827. }
  213828. depthIs16Bit = true;
  213829. }
  213830. XFree (visuals);
  213831. // Set up the window attributes
  213832. XSetWindowAttributes swa;
  213833. swa.border_pixel = 0;
  213834. swa.background_pixmap = None;
  213835. swa.colormap = DefaultColormap (display, screen);
  213836. swa.override_redirect = getComponent()->isAlwaysOnTop() ? True : False;
  213837. swa.event_mask = eventMask;
  213838. Window wndH = XCreateWindow (display, root,
  213839. 0, 0, 1, 1,
  213840. 0, 0, InputOutput, (Visual*) CopyFromParent,
  213841. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  213842. &swa);
  213843. XGrabButton (display, AnyButton, AnyModifier, wndH, False,
  213844. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  213845. GrabModeAsync, GrabModeAsync, None, None);
  213846. // Set the window context to identify the window handle object
  213847. if (XSaveContext (display, (XID) wndH, improbableNumber, (XPointer) this))
  213848. {
  213849. // Failed
  213850. jassertfalse
  213851. Logger::outputDebugString ("Failed to create context information for window.\n");
  213852. XDestroyWindow (display, wndH);
  213853. wndH = 0;
  213854. }
  213855. // Set window manager hints
  213856. XWMHints* wmHints = XAllocWMHints();
  213857. wmHints->flags = InputHint | StateHint;
  213858. wmHints->input = True; // Locally active input model
  213859. wmHints->initial_state = NormalState;
  213860. XSetWMHints (display, wndH, wmHints);
  213861. XFree (wmHints);
  213862. if ((styleFlags & windowIsSemiTransparent) != 0)
  213863. {
  213864. //xxx
  213865. }
  213866. if ((styleFlags & windowAppearsOnTaskbar) != 0)
  213867. {
  213868. //xxx
  213869. }
  213870. //XSetTransientForHint (display, wndH, RootWindow (display, DefaultScreen (display)));
  213871. if ((styleFlags & windowHasTitleBar) == 0)
  213872. removeWindowDecorations (wndH);
  213873. else
  213874. addWindowButtons (wndH);
  213875. // Set window manager protocols
  213876. XChangeProperty (display, wndH, wm_Protocols, XA_ATOM, 32, PropModeReplace,
  213877. (unsigned char*) wm_ProtocolList, 2);
  213878. // Set drag and drop flags
  213879. XChangeProperty (display, wndH, XA_XdndTypeList, XA_ATOM, 32, PropModeReplace,
  213880. (const unsigned char*) allowedMimeTypeAtoms, numElementsInArray (allowedMimeTypeAtoms));
  213881. XChangeProperty (display, wndH, XA_XdndActionList, XA_ATOM, 32, PropModeReplace,
  213882. (const unsigned char*) allowedActions, numElementsInArray (allowedActions));
  213883. XChangeProperty (display, wndH, XA_XdndActionDescription, XA_STRING, 8, PropModeReplace,
  213884. (const unsigned char*) "", 0);
  213885. unsigned long dndVersion = ourDndVersion;
  213886. XChangeProperty (display, wndH, XA_XdndAware, XA_ATOM, 32, PropModeReplace,
  213887. (const unsigned char*) &dndVersion, 1);
  213888. // Set window name
  213889. setWindowTitle (wndH, getComponent()->getName());
  213890. // Initialise the pointer and keyboard mapping
  213891. // This is not the same as the logical pointer mapping the X server uses:
  213892. // we don't mess with this.
  213893. static bool mappingInitialised = false;
  213894. if (! mappingInitialised)
  213895. {
  213896. mappingInitialised = true;
  213897. const int numButtons = XGetPointerMapping (display, 0, 0);
  213898. if (numButtons == 2)
  213899. {
  213900. pointerMap[0] = LeftButton;
  213901. pointerMap[1] = RightButton;
  213902. pointerMap[2] = pointerMap[3] = pointerMap[4] = NoButton;
  213903. }
  213904. else if (numButtons >= 3)
  213905. {
  213906. pointerMap[0] = LeftButton;
  213907. pointerMap[1] = MiddleButton;
  213908. pointerMap[2] = RightButton;
  213909. if (numButtons >= 5)
  213910. {
  213911. pointerMap[3] = WheelUp;
  213912. pointerMap[4] = WheelDown;
  213913. }
  213914. }
  213915. getModifierMapping();
  213916. }
  213917. windowH = wndH;
  213918. }
  213919. void destroyWindow()
  213920. {
  213921. XPointer handlePointer;
  213922. if (! XFindContext (display, (XID) windowH, improbableNumber, &handlePointer))
  213923. XDeleteContext (display, (XID) windowH, improbableNumber);
  213924. XDestroyWindow (display, windowH);
  213925. // Wait for it to complete and then remove any events for this
  213926. // window from the event queue.
  213927. XSync (display, false);
  213928. XEvent event;
  213929. while (XCheckWindowEvent (display, windowH, eventMask, &event) == True)
  213930. {}
  213931. }
  213932. static int64 getEventTime (::Time t) throw()
  213933. {
  213934. static int64 eventTimeOffset = 0x12345678;
  213935. const int64 thisMessageTime = t;
  213936. if (eventTimeOffset == 0x12345678)
  213937. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  213938. return eventTimeOffset + thisMessageTime;
  213939. }
  213940. static void setWindowTitle (Window xwin, const char* const title) throw()
  213941. {
  213942. XTextProperty nameProperty;
  213943. char* strings[] = { (char*) title };
  213944. if (XStringListToTextProperty (strings, 1, &nameProperty))
  213945. {
  213946. XSetWMName (display, xwin, &nameProperty);
  213947. XSetWMIconName (display, xwin, &nameProperty);
  213948. XFree (nameProperty.value);
  213949. }
  213950. }
  213951. void updateBorderSize()
  213952. {
  213953. if ((styleFlags & windowHasTitleBar) == 0)
  213954. {
  213955. windowBorder = BorderSize (0);
  213956. }
  213957. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  213958. {
  213959. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  213960. if (hints != None)
  213961. {
  213962. unsigned char* data = 0;
  213963. unsigned long nitems, bytesLeft;
  213964. Atom actualType;
  213965. int actualFormat;
  213966. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  213967. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  213968. &data) == Success)
  213969. {
  213970. const unsigned long* const sizes = (const unsigned long*) data;
  213971. if (actualFormat == 32)
  213972. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  213973. (int) sizes[3], (int) sizes[1]);
  213974. XFree (data);
  213975. }
  213976. }
  213977. }
  213978. }
  213979. void updateBounds()
  213980. {
  213981. jassert (windowH != 0);
  213982. if (windowH != 0)
  213983. {
  213984. Window root, child;
  213985. unsigned int bw, depth;
  213986. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  213987. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  213988. &bw, &depth))
  213989. {
  213990. wx = wy = ww = wh = 0;
  213991. }
  213992. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  213993. {
  213994. wx = wy = 0;
  213995. }
  213996. }
  213997. }
  213998. void resetDragAndDrop()
  213999. {
  214000. dragAndDropFiles.clear();
  214001. lastDropX = lastDropY = -1;
  214002. dragAndDropCurrentMimeType = 0;
  214003. dragAndDropSourceWindow = 0;
  214004. srcMimeTypeAtomList.clear();
  214005. }
  214006. void sendDragAndDropMessage (XClientMessageEvent& msg)
  214007. {
  214008. msg.type = ClientMessage;
  214009. msg.display = display;
  214010. msg.window = dragAndDropSourceWindow;
  214011. msg.format = 32;
  214012. msg.data.l[0] = windowH;
  214013. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  214014. }
  214015. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  214016. {
  214017. XClientMessageEvent msg;
  214018. zerostruct (msg);
  214019. msg.message_type = XA_XdndStatus;
  214020. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  214021. msg.data.l[4] = dropAction;
  214022. sendDragAndDropMessage (msg);
  214023. }
  214024. void sendDragAndDropLeave()
  214025. {
  214026. XClientMessageEvent msg;
  214027. zerostruct (msg);
  214028. msg.message_type = XA_XdndLeave;
  214029. sendDragAndDropMessage (msg);
  214030. }
  214031. void sendDragAndDropFinish()
  214032. {
  214033. XClientMessageEvent msg;
  214034. zerostruct (msg);
  214035. msg.message_type = XA_XdndFinished;
  214036. sendDragAndDropMessage (msg);
  214037. }
  214038. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  214039. {
  214040. if ((clientMsg->data.l[1] & 1) == 0)
  214041. {
  214042. sendDragAndDropLeave();
  214043. if (dragAndDropFiles.size() > 0)
  214044. handleFileDragExit (dragAndDropFiles);
  214045. dragAndDropFiles.clear();
  214046. }
  214047. }
  214048. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  214049. {
  214050. if (dragAndDropSourceWindow == 0)
  214051. return;
  214052. dragAndDropSourceWindow = clientMsg->data.l[0];
  214053. const int dropX = ((int) clientMsg->data.l[2] >> 16) - getScreenX();
  214054. const int dropY = ((int) clientMsg->data.l[2] & 0xffff) - getScreenY();
  214055. if (lastDropX != dropX || lastDropY != dropY)
  214056. {
  214057. lastDropX = dropX;
  214058. lastDropY = dropY;
  214059. dragAndDropTimestamp = clientMsg->data.l[3];
  214060. Atom targetAction = XA_XdndActionCopy;
  214061. for (int i = numElementsInArray (allowedActions); --i >= 0;)
  214062. {
  214063. if ((Atom) clientMsg->data.l[4] == allowedActions[i])
  214064. {
  214065. targetAction = allowedActions[i];
  214066. break;
  214067. }
  214068. }
  214069. sendDragAndDropStatus (true, targetAction);
  214070. if (dragAndDropFiles.size() == 0)
  214071. updateDraggedFileList (clientMsg);
  214072. if (dragAndDropFiles.size() > 0)
  214073. handleFileDragMove (dragAndDropFiles, dropX, dropY);
  214074. }
  214075. }
  214076. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  214077. {
  214078. if (dragAndDropFiles.size() == 0)
  214079. updateDraggedFileList (clientMsg);
  214080. const StringArray files (dragAndDropFiles);
  214081. const int lastX = lastDropX, lastY = lastDropY;
  214082. sendDragAndDropFinish();
  214083. resetDragAndDrop();
  214084. if (files.size() > 0)
  214085. handleFileDragDrop (files, lastX, lastY);
  214086. }
  214087. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  214088. {
  214089. dragAndDropFiles.clear();
  214090. srcMimeTypeAtomList.clear();
  214091. dragAndDropCurrentMimeType = 0;
  214092. const int dndCurrentVersion = (int) (clientMsg->data.l[1] & 0xff000000) >> 24;
  214093. if (dndCurrentVersion < 3 || dndCurrentVersion > ourDndVersion)
  214094. {
  214095. dragAndDropSourceWindow = 0;
  214096. return;
  214097. }
  214098. dragAndDropSourceWindow = clientMsg->data.l[0];
  214099. if ((clientMsg->data.l[1] & 1) != 0)
  214100. {
  214101. Atom actual;
  214102. int format;
  214103. unsigned long count = 0, remaining = 0;
  214104. unsigned char* data = 0;
  214105. XGetWindowProperty (display, dragAndDropSourceWindow, XA_XdndTypeList,
  214106. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  214107. &count, &remaining, &data);
  214108. if (data != 0)
  214109. {
  214110. if (actual == XA_ATOM && format == 32 && count != 0)
  214111. {
  214112. const unsigned long* const types = (const unsigned long*) data;
  214113. for (unsigned int i = 0; i < count; ++i)
  214114. if (types[i] != None)
  214115. srcMimeTypeAtomList.add (types[i]);
  214116. }
  214117. XFree (data);
  214118. }
  214119. }
  214120. if (srcMimeTypeAtomList.size() == 0)
  214121. {
  214122. for (int i = 2; i < 5; ++i)
  214123. if (clientMsg->data.l[i] != None)
  214124. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  214125. if (srcMimeTypeAtomList.size() == 0)
  214126. {
  214127. dragAndDropSourceWindow = 0;
  214128. return;
  214129. }
  214130. }
  214131. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  214132. for (int j = 0; j < numElementsInArray (allowedMimeTypeAtoms); ++j)
  214133. if (srcMimeTypeAtomList[i] == allowedMimeTypeAtoms[j])
  214134. dragAndDropCurrentMimeType = allowedMimeTypeAtoms[j];
  214135. handleDragAndDropPosition (clientMsg);
  214136. }
  214137. void handleDragAndDropSelection (const XEvent* const evt)
  214138. {
  214139. dragAndDropFiles.clear();
  214140. if (evt->xselection.property != 0)
  214141. {
  214142. StringArray lines;
  214143. {
  214144. MemoryBlock dropData;
  214145. for (;;)
  214146. {
  214147. Atom actual;
  214148. uint8* data = 0;
  214149. unsigned long count = 0, remaining = 0;
  214150. int format = 0;
  214151. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  214152. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  214153. &format, &count, &remaining, &data) == Success)
  214154. {
  214155. dropData.append (data, count * format / 8);
  214156. XFree (data);
  214157. if (remaining == 0)
  214158. break;
  214159. }
  214160. else
  214161. {
  214162. XFree (data);
  214163. break;
  214164. }
  214165. }
  214166. lines.addLines (dropData.toString());
  214167. }
  214168. for (int i = 0; i < lines.size(); ++i)
  214169. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf (T("file://"), false, true)));
  214170. dragAndDropFiles.trim();
  214171. dragAndDropFiles.removeEmptyStrings();
  214172. }
  214173. }
  214174. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  214175. {
  214176. dragAndDropFiles.clear();
  214177. if (dragAndDropSourceWindow != None
  214178. && dragAndDropCurrentMimeType != 0)
  214179. {
  214180. dragAndDropTimestamp = clientMsg->data.l[2];
  214181. XConvertSelection (display,
  214182. XA_XdndSelection,
  214183. dragAndDropCurrentMimeType,
  214184. XA_JXSelectionWindowProperty,
  214185. windowH,
  214186. dragAndDropTimestamp);
  214187. }
  214188. }
  214189. StringArray dragAndDropFiles;
  214190. int dragAndDropTimestamp, lastDropX, lastDropY;
  214191. Atom XA_OtherMime, dragAndDropCurrentMimeType;
  214192. Window dragAndDropSourceWindow;
  214193. unsigned long allowedActions [5];
  214194. unsigned long allowedMimeTypeAtoms [3];
  214195. Array <Atom> srcMimeTypeAtomList;
  214196. };
  214197. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  214198. {
  214199. return new LinuxComponentPeer (this, styleFlags);
  214200. }
  214201. // (this callback is hooked up in the messaging code)
  214202. void juce_windowMessageReceive (XEvent* event)
  214203. {
  214204. if (event->xany.window != None)
  214205. {
  214206. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  214207. const MessageManagerLock messLock;
  214208. if (ComponentPeer::isValidPeer (peer))
  214209. peer->handleWindowMessage (event);
  214210. }
  214211. else
  214212. {
  214213. switch (event->xany.type)
  214214. {
  214215. case KeymapNotify:
  214216. {
  214217. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  214218. memcpy (keyStates, keymapEvent->key_vector, 32);
  214219. break;
  214220. }
  214221. default:
  214222. break;
  214223. }
  214224. }
  214225. }
  214226. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool /*clipToWorkArea*/) throw()
  214227. {
  214228. #if JUCE_USE_XINERAMA
  214229. int major_opcode, first_event, first_error;
  214230. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error)
  214231. && XineramaIsActive (display))
  214232. {
  214233. int numMonitors = 0;
  214234. XineramaScreenInfo* const screens = XineramaQueryScreens (display, &numMonitors);
  214235. if (screens != 0)
  214236. {
  214237. for (int i = numMonitors; --i >= 0;)
  214238. {
  214239. int index = screens[i].screen_number;
  214240. if (index >= 0)
  214241. {
  214242. while (monitorCoords.size() < index)
  214243. monitorCoords.add (Rectangle (0, 0, 0, 0));
  214244. monitorCoords.set (index, Rectangle (screens[i].x_org,
  214245. screens[i].y_org,
  214246. screens[i].width,
  214247. screens[i].height));
  214248. }
  214249. }
  214250. XFree (screens);
  214251. }
  214252. }
  214253. if (monitorCoords.size() == 0)
  214254. #endif
  214255. {
  214256. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  214257. if (hints != None)
  214258. {
  214259. const int numMonitors = ScreenCount (display);
  214260. for (int i = 0; i < numMonitors; ++i)
  214261. {
  214262. Window root = RootWindow (display, i);
  214263. unsigned long nitems, bytesLeft;
  214264. Atom actualType;
  214265. int actualFormat;
  214266. unsigned char* data = 0;
  214267. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  214268. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  214269. &data) == Success)
  214270. {
  214271. const long* const position = (const long*) data;
  214272. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  214273. monitorCoords.add (Rectangle (position[0], position[1],
  214274. position[2], position[3]));
  214275. XFree (data);
  214276. }
  214277. }
  214278. }
  214279. if (monitorCoords.size() == 0)
  214280. {
  214281. monitorCoords.add (Rectangle (0, 0,
  214282. DisplayWidth (display, DefaultScreen (display)),
  214283. DisplayHeight (display, DefaultScreen (display))));
  214284. }
  214285. }
  214286. }
  214287. bool Desktop::canUseSemiTransparentWindows() throw()
  214288. {
  214289. return false;
  214290. }
  214291. void Desktop::getMousePosition (int& x, int& y) throw()
  214292. {
  214293. int mouseMods;
  214294. getMousePos (x, y, mouseMods);
  214295. }
  214296. void Desktop::setMousePosition (int x, int y) throw()
  214297. {
  214298. Window root = RootWindow (display, DefaultScreen (display));
  214299. XWarpPointer (display, None, root, 0, 0, 0, 0, x, y);
  214300. }
  214301. static bool screenSaverAllowed = true;
  214302. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  214303. {
  214304. if (screenSaverAllowed != isEnabled)
  214305. {
  214306. screenSaverAllowed = isEnabled;
  214307. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  214308. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  214309. if (xScreenSaverSuspend == 0)
  214310. {
  214311. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  214312. if (h != 0)
  214313. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  214314. }
  214315. if (xScreenSaverSuspend != 0)
  214316. xScreenSaverSuspend (display, ! isEnabled);
  214317. }
  214318. }
  214319. bool Desktop::isScreenSaverEnabled() throw()
  214320. {
  214321. return screenSaverAllowed;
  214322. }
  214323. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  214324. {
  214325. Window root = RootWindow (display, DefaultScreen (display));
  214326. const unsigned int imageW = image.getWidth();
  214327. const unsigned int imageH = image.getHeight();
  214328. unsigned int cursorW, cursorH;
  214329. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  214330. return 0;
  214331. Image im (Image::ARGB, cursorW, cursorH, true);
  214332. Graphics g (im);
  214333. if (imageW > cursorW || imageH > cursorH)
  214334. {
  214335. hotspotX = (hotspotX * cursorW) / imageW;
  214336. hotspotY = (hotspotY * cursorH) / imageH;
  214337. g.drawImageWithin (&image, 0, 0, imageW, imageH,
  214338. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  214339. false);
  214340. }
  214341. else
  214342. {
  214343. g.drawImageAt (&image, 0, 0);
  214344. }
  214345. const int stride = (cursorW + 7) >> 3;
  214346. uint8* const maskPlane = (uint8*) juce_calloc (stride * cursorH);
  214347. uint8* const sourcePlane = (uint8*) juce_calloc (stride * cursorH);
  214348. bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  214349. for (int y = cursorH; --y >= 0;)
  214350. {
  214351. for (int x = cursorW; --x >= 0;)
  214352. {
  214353. const uint8 mask = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  214354. const int offset = y * stride + (x >> 3);
  214355. const Colour c (im.getPixelAt (x, y));
  214356. if (c.getAlpha() >= 128)
  214357. maskPlane[offset] |= mask;
  214358. if (c.getBrightness() >= 0.5f)
  214359. sourcePlane[offset] |= mask;
  214360. }
  214361. }
  214362. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, (char*) sourcePlane, cursorW, cursorH, 0xffff, 0, 1);
  214363. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, (char*) maskPlane, cursorW, cursorH, 0xffff, 0, 1);
  214364. juce_free (maskPlane);
  214365. juce_free (sourcePlane);
  214366. XColor white, black;
  214367. black.red = black.green = black.blue = 0;
  214368. white.red = white.green = white.blue = 0xffff;
  214369. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  214370. XFreePixmap (display, sourcePixmap);
  214371. XFreePixmap (display, maskPixmap);
  214372. return result;
  214373. }
  214374. void juce_deleteMouseCursor (void* const cursorHandle, const bool) throw()
  214375. {
  214376. if (cursorHandle != None)
  214377. XFreeCursor (display, (Cursor) cursorHandle);
  214378. }
  214379. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  214380. {
  214381. unsigned int shape;
  214382. switch (type)
  214383. {
  214384. case MouseCursor::NoCursor:
  214385. {
  214386. const Image im (Image::ARGB, 16, 16, true);
  214387. return juce_createMouseCursorFromImage (im, 0, 0);
  214388. }
  214389. case MouseCursor::NormalCursor:
  214390. return (void*) None; // Use parent cursor
  214391. case MouseCursor::DraggingHandCursor:
  214392. {
  214393. static unsigned char dragHandData[] = {71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  214394. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  214395. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  214396. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  214397. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  214398. const int dragHandDataSize = 99;
  214399. Image* const im = ImageFileFormat::loadFrom ((const char*) dragHandData, dragHandDataSize);
  214400. void* const dragHandCursor = juce_createMouseCursorFromImage (*im, 8, 7);
  214401. delete im;
  214402. return dragHandCursor;
  214403. }
  214404. case MouseCursor::CopyingCursor:
  214405. {
  214406. static unsigned char copyCursorData[] = {71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  214407. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0,
  214408. 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  214409. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174,
  214410. 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  214411. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  214412. const int copyCursorSize = 119;
  214413. Image* const im = ImageFileFormat::loadFrom ((const char*) copyCursorData, copyCursorSize);
  214414. void* const copyCursor = juce_createMouseCursorFromImage (*im, 1, 3);
  214415. delete im;
  214416. return copyCursor;
  214417. }
  214418. case MouseCursor::WaitCursor:
  214419. shape = XC_watch;
  214420. break;
  214421. case MouseCursor::IBeamCursor:
  214422. shape = XC_xterm;
  214423. break;
  214424. case MouseCursor::PointingHandCursor:
  214425. shape = XC_hand2;
  214426. break;
  214427. case MouseCursor::LeftRightResizeCursor:
  214428. shape = XC_sb_h_double_arrow;
  214429. break;
  214430. case MouseCursor::UpDownResizeCursor:
  214431. shape = XC_sb_v_double_arrow;
  214432. break;
  214433. case MouseCursor::UpDownLeftRightResizeCursor:
  214434. shape = XC_fleur;
  214435. break;
  214436. case MouseCursor::TopEdgeResizeCursor:
  214437. shape = XC_top_side;
  214438. break;
  214439. case MouseCursor::BottomEdgeResizeCursor:
  214440. shape = XC_bottom_side;
  214441. break;
  214442. case MouseCursor::LeftEdgeResizeCursor:
  214443. shape = XC_left_side;
  214444. break;
  214445. case MouseCursor::RightEdgeResizeCursor:
  214446. shape = XC_right_side;
  214447. break;
  214448. case MouseCursor::TopLeftCornerResizeCursor:
  214449. shape = XC_top_left_corner;
  214450. break;
  214451. case MouseCursor::TopRightCornerResizeCursor:
  214452. shape = XC_top_right_corner;
  214453. break;
  214454. case MouseCursor::BottomLeftCornerResizeCursor:
  214455. shape = XC_bottom_left_corner;
  214456. break;
  214457. case MouseCursor::BottomRightCornerResizeCursor:
  214458. shape = XC_bottom_right_corner;
  214459. break;
  214460. case MouseCursor::CrosshairCursor:
  214461. shape = XC_crosshair;
  214462. break;
  214463. default:
  214464. return (void*) None; // Use parent cursor
  214465. }
  214466. return (void*) XCreateFontCursor (display, shape);
  214467. }
  214468. void MouseCursor::showInWindow (ComponentPeer* peer) const throw()
  214469. {
  214470. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  214471. if (lp != 0)
  214472. lp->showMouseCursor ((Cursor) getHandle());
  214473. }
  214474. void MouseCursor::showInAllWindows() const throw()
  214475. {
  214476. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  214477. showInWindow (ComponentPeer::getPeer (i));
  214478. }
  214479. Image* juce_createIconForFile (const File& file)
  214480. {
  214481. return 0;
  214482. }
  214483. #if JUCE_OPENGL
  214484. class WindowedGLContext : public OpenGLContext
  214485. {
  214486. public:
  214487. WindowedGLContext (Component* const component,
  214488. const OpenGLPixelFormat& pixelFormat_,
  214489. GLXContext sharedContext)
  214490. : renderContext (0),
  214491. embeddedWindow (0),
  214492. pixelFormat (pixelFormat_)
  214493. {
  214494. jassert (component != 0);
  214495. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  214496. if (peer == 0)
  214497. return;
  214498. XSync (display, False);
  214499. GLint attribs [64];
  214500. int n = 0;
  214501. attribs[n++] = GLX_RGBA;
  214502. attribs[n++] = GLX_DOUBLEBUFFER;
  214503. attribs[n++] = GLX_RED_SIZE;
  214504. attribs[n++] = pixelFormat.redBits;
  214505. attribs[n++] = GLX_GREEN_SIZE;
  214506. attribs[n++] = pixelFormat.greenBits;
  214507. attribs[n++] = GLX_BLUE_SIZE;
  214508. attribs[n++] = pixelFormat.blueBits;
  214509. attribs[n++] = GLX_ALPHA_SIZE;
  214510. attribs[n++] = pixelFormat.alphaBits;
  214511. attribs[n++] = GLX_DEPTH_SIZE;
  214512. attribs[n++] = pixelFormat.depthBufferBits;
  214513. attribs[n++] = GLX_STENCIL_SIZE;
  214514. attribs[n++] = pixelFormat.stencilBufferBits;
  214515. attribs[n++] = GLX_ACCUM_RED_SIZE;
  214516. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  214517. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  214518. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  214519. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  214520. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  214521. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  214522. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  214523. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  214524. attribs[n++] = None;
  214525. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  214526. if (bestVisual == 0)
  214527. return;
  214528. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  214529. Window windowH = (Window) peer->getNativeHandle();
  214530. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  214531. XSetWindowAttributes swa;
  214532. swa.colormap = colourMap;
  214533. swa.border_pixel = 0;
  214534. swa.event_mask = ExposureMask | StructureNotifyMask;
  214535. embeddedWindow = XCreateWindow (display, windowH,
  214536. 0, 0, 1, 1, 0,
  214537. bestVisual->depth,
  214538. InputOutput,
  214539. bestVisual->visual,
  214540. CWBorderPixel | CWColormap | CWEventMask,
  214541. &swa);
  214542. XSaveContext (display, (XID) embeddedWindow, improbableNumber, (XPointer) peer);
  214543. XMapWindow (display, embeddedWindow);
  214544. XFreeColormap (display, colourMap);
  214545. XFree (bestVisual);
  214546. XSync (display, False);
  214547. }
  214548. ~WindowedGLContext()
  214549. {
  214550. makeInactive();
  214551. glXDestroyContext (display, renderContext);
  214552. XUnmapWindow (display, embeddedWindow);
  214553. XDestroyWindow (display, embeddedWindow);
  214554. }
  214555. bool makeActive() const throw()
  214556. {
  214557. jassert (renderContext != 0);
  214558. return glXMakeCurrent (display, embeddedWindow, renderContext)
  214559. && XSync (display, False);
  214560. }
  214561. bool makeInactive() const throw()
  214562. {
  214563. return (! isActive()) || glXMakeCurrent (display, None, 0);
  214564. }
  214565. bool isActive() const throw()
  214566. {
  214567. return glXGetCurrentContext() == renderContext;
  214568. }
  214569. const OpenGLPixelFormat getPixelFormat() const
  214570. {
  214571. return pixelFormat;
  214572. }
  214573. void* getRawContext() const throw()
  214574. {
  214575. return renderContext;
  214576. }
  214577. void updateWindowPosition (int x, int y, int w, int h, int)
  214578. {
  214579. XMoveResizeWindow (display, embeddedWindow,
  214580. x, y, jmax (1, w), jmax (1, h));
  214581. }
  214582. void swapBuffers()
  214583. {
  214584. glXSwapBuffers (display, embeddedWindow);
  214585. }
  214586. bool setSwapInterval (const int numFramesPerSwap)
  214587. {
  214588. // xxx needs doing..
  214589. return false;
  214590. }
  214591. int getSwapInterval() const
  214592. {
  214593. // xxx needs doing..
  214594. return 0;
  214595. }
  214596. void repaint()
  214597. {
  214598. }
  214599. juce_UseDebuggingNewOperator
  214600. GLXContext renderContext;
  214601. private:
  214602. Window embeddedWindow;
  214603. OpenGLPixelFormat pixelFormat;
  214604. WindowedGLContext (const WindowedGLContext&);
  214605. const WindowedGLContext& operator= (const WindowedGLContext&);
  214606. };
  214607. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  214608. const OpenGLPixelFormat& pixelFormat,
  214609. const OpenGLContext* const contextToShareWith)
  214610. {
  214611. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  214612. contextToShareWith != 0 ? (GLXContext) contextToShareWith->getRawContext() : 0);
  214613. if (c->renderContext == 0)
  214614. deleteAndZero (c);
  214615. return c;
  214616. }
  214617. void juce_glViewport (const int w, const int h)
  214618. {
  214619. glViewport (0, 0, w, h);
  214620. }
  214621. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  214622. OwnedArray <OpenGLPixelFormat>& results)
  214623. {
  214624. results.add (new OpenGLPixelFormat()); // xxx
  214625. }
  214626. #endif
  214627. static void initClipboard (Window root, Atom* cutBuffers) throw()
  214628. {
  214629. static bool init = false;
  214630. if (! init)
  214631. {
  214632. init = true;
  214633. // Make sure all cut buffers exist before use
  214634. for (int i = 0; i < 8; i++)
  214635. {
  214636. XChangeProperty (display, root, cutBuffers[i],
  214637. XA_STRING, 8, PropModeAppend, NULL, 0);
  214638. }
  214639. }
  214640. }
  214641. // Clipboard implemented currently using cut buffers
  214642. // rather than the more powerful selection method
  214643. void SystemClipboard::copyTextToClipboard (const String& clipText) throw()
  214644. {
  214645. Window root = RootWindow (display, DefaultScreen (display));
  214646. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  214647. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  214648. initClipboard (root, cutBuffers);
  214649. XRotateWindowProperties (display, root, cutBuffers, 8, 1);
  214650. XChangeProperty (display, root, cutBuffers[0],
  214651. XA_STRING, 8, PropModeReplace, (const unsigned char*) (const char*) clipText,
  214652. clipText.length());
  214653. }
  214654. const String SystemClipboard::getTextFromClipboard() throw()
  214655. {
  214656. const int bufSize = 64; // in words
  214657. String returnData;
  214658. int byteOffset = 0;
  214659. Window root = RootWindow (display, DefaultScreen (display));
  214660. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  214661. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  214662. initClipboard (root, cutBuffers);
  214663. for (;;)
  214664. {
  214665. unsigned long bytesLeft = 0, nitems = 0;
  214666. unsigned char* clipData = 0;
  214667. int actualFormat = 0;
  214668. Atom actualType;
  214669. if (XGetWindowProperty (display, root, cutBuffers[0], byteOffset >> 2, bufSize,
  214670. False, XA_STRING, &actualType, &actualFormat, &nitems, &bytesLeft,
  214671. &clipData) == Success)
  214672. {
  214673. if (actualType == XA_STRING && actualFormat == 8)
  214674. {
  214675. byteOffset += nitems;
  214676. returnData += String ((const char*) clipData, nitems);
  214677. }
  214678. else
  214679. {
  214680. bytesLeft = 0;
  214681. }
  214682. if (clipData != 0)
  214683. XFree (clipData);
  214684. }
  214685. if (bytesLeft == 0)
  214686. break;
  214687. }
  214688. return returnData;
  214689. }
  214690. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  214691. {
  214692. jassertfalse // not implemented!
  214693. return false;
  214694. }
  214695. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  214696. {
  214697. jassertfalse // not implemented!
  214698. return false;
  214699. }
  214700. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  214701. {
  214702. if (! isOnDesktop ())
  214703. addToDesktop (0);
  214704. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  214705. if (wp != 0)
  214706. {
  214707. wp->setTaskBarIcon (newImage);
  214708. setVisible (true);
  214709. toFront (false);
  214710. repaint();
  214711. }
  214712. }
  214713. void SystemTrayIconComponent::paint (Graphics& g)
  214714. {
  214715. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  214716. if (wp != 0)
  214717. {
  214718. const Image* const image = wp->getTaskbarIcon();
  214719. if (image != 0)
  214720. g.drawImageAt (image, 0, 0, false);
  214721. }
  214722. }
  214723. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  214724. {
  214725. // xxx not yet implemented!
  214726. }
  214727. void PlatformUtilities::beep()
  214728. {
  214729. fprintf (stdout, "\a");
  214730. fflush (stdout);
  214731. }
  214732. bool AlertWindow::showNativeDialogBox (const String& title,
  214733. const String& bodyText,
  214734. bool isOkCancel)
  214735. {
  214736. // xxx this is supposed to pop up an alert!
  214737. Logger::outputDebugString (title + ": " + bodyText);
  214738. // use a non-native one for the time being..
  214739. if (isOkCancel)
  214740. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  214741. else
  214742. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  214743. return true;
  214744. }
  214745. const int KeyPress::spaceKey = XK_space & 0xff;
  214746. const int KeyPress::returnKey = XK_Return & 0xff;
  214747. const int KeyPress::escapeKey = XK_Escape & 0xff;
  214748. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  214749. const int KeyPress::leftKey = (XK_Left & 0xff) | extendedKeyModifier;
  214750. const int KeyPress::rightKey = (XK_Right & 0xff) | extendedKeyModifier;
  214751. const int KeyPress::upKey = (XK_Up & 0xff) | extendedKeyModifier;
  214752. const int KeyPress::downKey = (XK_Down & 0xff) | extendedKeyModifier;
  214753. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | extendedKeyModifier;
  214754. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | extendedKeyModifier;
  214755. const int KeyPress::endKey = (XK_End & 0xff) | extendedKeyModifier;
  214756. const int KeyPress::homeKey = (XK_Home & 0xff) | extendedKeyModifier;
  214757. const int KeyPress::insertKey = (XK_Insert & 0xff) | extendedKeyModifier;
  214758. const int KeyPress::deleteKey = (XK_Delete & 0xff) | extendedKeyModifier;
  214759. const int KeyPress::tabKey = XK_Tab & 0xff;
  214760. const int KeyPress::F1Key = (XK_F1 & 0xff) | extendedKeyModifier;
  214761. const int KeyPress::F2Key = (XK_F2 & 0xff) | extendedKeyModifier;
  214762. const int KeyPress::F3Key = (XK_F3 & 0xff) | extendedKeyModifier;
  214763. const int KeyPress::F4Key = (XK_F4 & 0xff) | extendedKeyModifier;
  214764. const int KeyPress::F5Key = (XK_F5 & 0xff) | extendedKeyModifier;
  214765. const int KeyPress::F6Key = (XK_F6 & 0xff) | extendedKeyModifier;
  214766. const int KeyPress::F7Key = (XK_F7 & 0xff) | extendedKeyModifier;
  214767. const int KeyPress::F8Key = (XK_F8 & 0xff) | extendedKeyModifier;
  214768. const int KeyPress::F9Key = (XK_F9 & 0xff) | extendedKeyModifier;
  214769. const int KeyPress::F10Key = (XK_F10 & 0xff) | extendedKeyModifier;
  214770. const int KeyPress::F11Key = (XK_F11 & 0xff) | extendedKeyModifier;
  214771. const int KeyPress::F12Key = (XK_F12 & 0xff) | extendedKeyModifier;
  214772. const int KeyPress::F13Key = (XK_F13 & 0xff) | extendedKeyModifier;
  214773. const int KeyPress::F14Key = (XK_F14 & 0xff) | extendedKeyModifier;
  214774. const int KeyPress::F15Key = (XK_F15 & 0xff) | extendedKeyModifier;
  214775. const int KeyPress::F16Key = (XK_F16 & 0xff) | extendedKeyModifier;
  214776. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | extendedKeyModifier;
  214777. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | extendedKeyModifier;
  214778. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | extendedKeyModifier;
  214779. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | extendedKeyModifier;
  214780. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | extendedKeyModifier;
  214781. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | extendedKeyModifier;
  214782. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | extendedKeyModifier;
  214783. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| extendedKeyModifier;
  214784. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| extendedKeyModifier;
  214785. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| extendedKeyModifier;
  214786. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| extendedKeyModifier;
  214787. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| extendedKeyModifier;
  214788. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| extendedKeyModifier;
  214789. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| extendedKeyModifier;
  214790. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| extendedKeyModifier;
  214791. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| extendedKeyModifier;
  214792. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| extendedKeyModifier;
  214793. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| extendedKeyModifier;
  214794. const int KeyPress::playKey = (0xffeeff00) | extendedKeyModifier;
  214795. const int KeyPress::stopKey = (0xffeeff01) | extendedKeyModifier;
  214796. const int KeyPress::fastForwardKey = (0xffeeff02) | extendedKeyModifier;
  214797. const int KeyPress::rewindKey = (0xffeeff03) | extendedKeyModifier;
  214798. END_JUCE_NAMESPACE
  214799. #endif
  214800. /********* End of inlined file: juce_linux_Windowing.cpp *********/
  214801. #endif
  214802. #endif
  214803. //==============================================================================
  214804. #if JUCE_MAC
  214805. /********* Start of inlined file: juce_mac_Files.cpp *********/
  214806. #include <ApplicationServices/ApplicationServices.h>
  214807. #include <sys/stat.h>
  214808. #include <sys/dir.h>
  214809. #include <sys/param.h>
  214810. #include <sys/mount.h>
  214811. #include <unistd.h>
  214812. #include <fnmatch.h>
  214813. #include <utime.h>
  214814. #include <pwd.h>
  214815. #include <fcntl.h>
  214816. BEGIN_JUCE_NAMESPACE
  214817. /*
  214818. Note that a lot of methods that you'd expect to find in this file actually
  214819. live in juce_posix_SharedCode.cpp!
  214820. */
  214821. /********* Start of inlined file: juce_posix_SharedCode.cpp *********/
  214822. /*
  214823. This file contains posix routines that are common to both the Linux and Mac builds.
  214824. It gets included directly in the cpp files for these platforms.
  214825. */
  214826. CriticalSection::CriticalSection() throw()
  214827. {
  214828. pthread_mutexattr_t atts;
  214829. pthread_mutexattr_init (&atts);
  214830. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  214831. pthread_mutex_init (&internal, &atts);
  214832. }
  214833. CriticalSection::~CriticalSection() throw()
  214834. {
  214835. pthread_mutex_destroy (&internal);
  214836. }
  214837. void CriticalSection::enter() const throw()
  214838. {
  214839. pthread_mutex_lock (&internal);
  214840. }
  214841. bool CriticalSection::tryEnter() const throw()
  214842. {
  214843. return pthread_mutex_trylock (&internal) == 0;
  214844. }
  214845. void CriticalSection::exit() const throw()
  214846. {
  214847. pthread_mutex_unlock (&internal);
  214848. }
  214849. struct EventStruct
  214850. {
  214851. pthread_cond_t condition;
  214852. pthread_mutex_t mutex;
  214853. bool triggered;
  214854. };
  214855. WaitableEvent::WaitableEvent() throw()
  214856. {
  214857. EventStruct* const es = new EventStruct();
  214858. es->triggered = false;
  214859. pthread_cond_init (&es->condition, 0);
  214860. pthread_mutex_init (&es->mutex, 0);
  214861. internal = es;
  214862. }
  214863. WaitableEvent::~WaitableEvent() throw()
  214864. {
  214865. EventStruct* const es = (EventStruct*) internal;
  214866. pthread_cond_destroy (&es->condition);
  214867. pthread_mutex_destroy (&es->mutex);
  214868. delete es;
  214869. }
  214870. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  214871. {
  214872. EventStruct* const es = (EventStruct*) internal;
  214873. bool ok = true;
  214874. pthread_mutex_lock (&es->mutex);
  214875. if (! es->triggered)
  214876. {
  214877. if (timeOutMillisecs < 0)
  214878. {
  214879. pthread_cond_wait (&es->condition, &es->mutex);
  214880. }
  214881. else
  214882. {
  214883. struct timespec time;
  214884. #if JUCE_MAC
  214885. time.tv_sec = timeOutMillisecs / 1000;
  214886. time.tv_nsec = (timeOutMillisecs % 1000) * 1000000;
  214887. pthread_cond_timedwait_relative_np (&es->condition, &es->mutex, &time);
  214888. #else
  214889. struct timeval t;
  214890. int timeout = 0;
  214891. gettimeofday (&t, 0);
  214892. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  214893. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  214894. while (time.tv_nsec >= 1000000000)
  214895. {
  214896. time.tv_nsec -= 1000000000;
  214897. time.tv_sec++;
  214898. }
  214899. while (! timeout)
  214900. {
  214901. timeout = pthread_cond_timedwait (&es->condition, &es->mutex, &time);
  214902. if (! timeout)
  214903. // Success
  214904. break;
  214905. if (timeout == EINTR)
  214906. // Go round again
  214907. timeout = 0;
  214908. }
  214909. #endif
  214910. }
  214911. ok = es->triggered;
  214912. }
  214913. es->triggered = false;
  214914. pthread_mutex_unlock (&es->mutex);
  214915. return ok;
  214916. }
  214917. void WaitableEvent::signal() const throw()
  214918. {
  214919. EventStruct* const es = (EventStruct*) internal;
  214920. pthread_mutex_lock (&es->mutex);
  214921. es->triggered = true;
  214922. pthread_cond_broadcast (&es->condition);
  214923. pthread_mutex_unlock (&es->mutex);
  214924. }
  214925. void WaitableEvent::reset() const throw()
  214926. {
  214927. EventStruct* const es = (EventStruct*) internal;
  214928. pthread_mutex_lock (&es->mutex);
  214929. es->triggered = false;
  214930. pthread_mutex_unlock (&es->mutex);
  214931. }
  214932. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  214933. {
  214934. struct timespec time;
  214935. time.tv_sec = millisecs / 1000;
  214936. time.tv_nsec = (millisecs % 1000) * 1000000;
  214937. nanosleep (&time, 0);
  214938. }
  214939. const tchar File::separator = T('/');
  214940. const tchar* File::separatorString = T("/");
  214941. bool juce_copyFile (const String& s, const String& d) throw();
  214942. static bool juce_stat (const String& fileName, struct stat& info) throw()
  214943. {
  214944. return fileName.isNotEmpty()
  214945. && (stat (fileName.toUTF8(), &info) == 0);
  214946. }
  214947. bool juce_isDirectory (const String& fileName) throw()
  214948. {
  214949. struct stat info;
  214950. return fileName.isEmpty()
  214951. || (juce_stat (fileName, info)
  214952. && ((info.st_mode & S_IFDIR) != 0));
  214953. }
  214954. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  214955. {
  214956. if (fileName.isEmpty())
  214957. return false;
  214958. const char* const fileNameUTF8 = fileName.toUTF8();
  214959. bool exists = access (fileNameUTF8, F_OK) == 0;
  214960. if (exists && dontCountDirectories)
  214961. {
  214962. struct stat info;
  214963. const int res = stat (fileNameUTF8, &info);
  214964. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  214965. exists = false;
  214966. }
  214967. return exists;
  214968. }
  214969. int64 juce_getFileSize (const String& fileName) throw()
  214970. {
  214971. struct stat info;
  214972. return juce_stat (fileName, info) ? info.st_size : 0;
  214973. }
  214974. bool juce_canWriteToFile (const String& fileName) throw()
  214975. {
  214976. return access (fileName.toUTF8(), W_OK) == 0;
  214977. }
  214978. bool juce_deleteFile (const String& fileName) throw()
  214979. {
  214980. const char* const fileNameUTF8 = fileName.toUTF8();
  214981. if (juce_isDirectory (fileName))
  214982. return rmdir (fileNameUTF8) == 0;
  214983. else
  214984. return remove (fileNameUTF8) == 0;
  214985. }
  214986. bool juce_moveFile (const String& source, const String& dest) throw()
  214987. {
  214988. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  214989. return true;
  214990. if (juce_canWriteToFile (source)
  214991. && juce_copyFile (source, dest))
  214992. {
  214993. if (juce_deleteFile (source))
  214994. return true;
  214995. juce_deleteFile (dest);
  214996. }
  214997. return false;
  214998. }
  214999. void juce_createDirectory (const String& fileName) throw()
  215000. {
  215001. mkdir (fileName.toUTF8(), 0777);
  215002. }
  215003. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  215004. {
  215005. const char* const fileNameUTF8 = fileName.toUTF8();
  215006. int flags = O_RDONLY;
  215007. if (forWriting)
  215008. {
  215009. if (juce_fileExists (fileName, false))
  215010. {
  215011. const int f = open (fileNameUTF8, O_RDWR, 00644);
  215012. if (f != -1)
  215013. lseek (f, 0, SEEK_END);
  215014. return (void*) f;
  215015. }
  215016. else
  215017. {
  215018. flags = O_RDWR + O_CREAT;
  215019. }
  215020. }
  215021. return (void*) open (fileNameUTF8, flags, 00644);
  215022. }
  215023. void juce_fileClose (void* handle) throw()
  215024. {
  215025. if (handle != 0)
  215026. close ((int) (pointer_sized_int) handle);
  215027. }
  215028. int juce_fileRead (void* handle, void* buffer, int size) throw()
  215029. {
  215030. if (handle != 0)
  215031. return read ((int) (pointer_sized_int) handle, buffer, size);
  215032. return 0;
  215033. }
  215034. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  215035. {
  215036. if (handle != 0)
  215037. return write ((int) (pointer_sized_int) handle, buffer, size);
  215038. return 0;
  215039. }
  215040. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  215041. {
  215042. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  215043. return pos;
  215044. return -1;
  215045. }
  215046. int64 juce_fileGetPosition (void* handle) throw()
  215047. {
  215048. if (handle != 0)
  215049. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  215050. else
  215051. return -1;
  215052. }
  215053. void juce_fileFlush (void* handle) throw()
  215054. {
  215055. if (handle != 0)
  215056. fsync ((int) (pointer_sized_int) handle);
  215057. }
  215058. // if this file doesn't exist, find a parent of it that does..
  215059. static bool doStatFS (const File* file, struct statfs& result) throw()
  215060. {
  215061. File f (*file);
  215062. for (int i = 5; --i >= 0;)
  215063. {
  215064. if (f.exists())
  215065. break;
  215066. f = f.getParentDirectory();
  215067. }
  215068. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  215069. }
  215070. int64 File::getBytesFreeOnVolume() const throw()
  215071. {
  215072. int64 free_space = 0;
  215073. struct statfs buf;
  215074. if (doStatFS (this, buf))
  215075. // Note: this returns space available to non-super user
  215076. free_space = (int64) buf.f_bsize * (int64) buf.f_bavail;
  215077. return free_space;
  215078. }
  215079. const String juce_getVolumeLabel (const String& filenameOnVolume,
  215080. int& volumeSerialNumber) throw()
  215081. {
  215082. // There is no equivalent on Linux
  215083. volumeSerialNumber = 0;
  215084. return String::empty;
  215085. }
  215086. #if JUCE_64BIT
  215087. #define filedesc ((long long) internal)
  215088. #else
  215089. #define filedesc ((int) internal)
  215090. #endif
  215091. InterProcessLock::InterProcessLock (const String& name_) throw()
  215092. : internal (0),
  215093. name (name_),
  215094. reentrancyLevel (0)
  215095. {
  215096. #if JUCE_MAC
  215097. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  215098. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  215099. #else
  215100. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  215101. #endif
  215102. temp.create();
  215103. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  215104. }
  215105. InterProcessLock::~InterProcessLock() throw()
  215106. {
  215107. while (reentrancyLevel > 0)
  215108. this->exit();
  215109. close (filedesc);
  215110. }
  215111. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  215112. {
  215113. if (internal == 0)
  215114. return false;
  215115. if (reentrancyLevel != 0)
  215116. return true;
  215117. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  215118. struct flock fl;
  215119. zerostruct (fl);
  215120. fl.l_whence = SEEK_SET;
  215121. fl.l_type = F_WRLCK;
  215122. for (;;)
  215123. {
  215124. const int result = fcntl (filedesc, F_SETLK, &fl);
  215125. if (result >= 0)
  215126. {
  215127. ++reentrancyLevel;
  215128. return true;
  215129. }
  215130. if (errno != EINTR)
  215131. {
  215132. if (timeOutMillisecs == 0
  215133. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  215134. break;
  215135. Thread::sleep (10);
  215136. }
  215137. }
  215138. return false;
  215139. }
  215140. void InterProcessLock::exit() throw()
  215141. {
  215142. if (reentrancyLevel > 0 && internal != 0)
  215143. {
  215144. --reentrancyLevel;
  215145. struct flock fl;
  215146. zerostruct (fl);
  215147. fl.l_whence = SEEK_SET;
  215148. fl.l_type = F_UNLCK;
  215149. for (;;)
  215150. {
  215151. const int result = fcntl (filedesc, F_SETLKW, &fl);
  215152. if (result >= 0 || errno != EINTR)
  215153. break;
  215154. }
  215155. }
  215156. }
  215157. /********* End of inlined file: juce_posix_SharedCode.cpp *********/
  215158. static File executableFile;
  215159. void PlatformUtilities::copyToStr255 (Str255& d, const String& s)
  215160. {
  215161. unsigned char* t = (unsigned char*) d;
  215162. t[0] = jmin (254, s.length());
  215163. s.copyToBuffer ((char*) t + 1, 254);
  215164. }
  215165. void PlatformUtilities::copyToStr63 (Str63& d, const String& s)
  215166. {
  215167. unsigned char* t = (unsigned char*) d;
  215168. t[0] = jmin (62, s.length());
  215169. s.copyToBuffer ((char*) t + 1, 62);
  215170. }
  215171. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  215172. {
  215173. String result;
  215174. if (cfString != 0)
  215175. {
  215176. #if JUCE_STRINGS_ARE_UNICODE
  215177. CFRange range = { 0, CFStringGetLength (cfString) };
  215178. UniChar* const u = (UniChar*) juce_malloc (sizeof (UniChar) * (range.length + 1));
  215179. CFStringGetCharacters (cfString, range, u);
  215180. u[range.length] = 0;
  215181. result = convertUTF16ToString (u);
  215182. juce_free (u);
  215183. #else
  215184. const int len = CFStringGetLength (cfString);
  215185. char* buffer = (char*) juce_malloc (len + 1);
  215186. CFStringGetCString (cfString, buffer, len + 1, CFStringGetSystemEncoding());
  215187. result = buffer;
  215188. juce_free (buffer);
  215189. #endif
  215190. }
  215191. return result;
  215192. }
  215193. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  215194. {
  215195. #if JUCE_STRINGS_ARE_UNICODE
  215196. const int len = s.length();
  215197. const juce_wchar* t = (const juce_wchar*) s;
  215198. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  215199. for (int i = 0; i <= len; ++i)
  215200. temp[i] = t[i];
  215201. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  215202. juce_free (temp);
  215203. return result;
  215204. #else
  215205. return CFStringCreateWithCString (kCFAllocatorDefault,
  215206. (const char*) s,
  215207. CFStringGetSystemEncoding());
  215208. #endif
  215209. }
  215210. const String PlatformUtilities::convertUTF16ToString (const UniChar* utf16)
  215211. {
  215212. String s;
  215213. while (*utf16 != 0)
  215214. s += (juce_wchar) *utf16++;
  215215. return s;
  215216. }
  215217. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  215218. {
  215219. UnicodeMapping map;
  215220. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  215221. kUnicodeNoSubset,
  215222. kTextEncodingDefaultFormat);
  215223. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  215224. kUnicodeCanonicalCompVariant,
  215225. kTextEncodingDefaultFormat);
  215226. map.mappingVersion = kUnicodeUseLatestMapping;
  215227. UnicodeToTextInfo conversionInfo = 0;
  215228. String result;
  215229. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  215230. {
  215231. const int len = s.length();
  215232. UniChar* const tempIn = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  215233. UniChar* const tempOut = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  215234. for (int i = 0; i <= len; ++i)
  215235. tempIn[i] = s[i];
  215236. ByteCount bytesRead = 0;
  215237. ByteCount outputBufferSize = 0;
  215238. if (ConvertFromUnicodeToText (conversionInfo,
  215239. len * sizeof (UniChar), tempIn,
  215240. kUnicodeDefaultDirectionMask,
  215241. 0, 0, 0, 0,
  215242. len * sizeof (UniChar), &bytesRead,
  215243. &outputBufferSize, tempOut) == noErr)
  215244. {
  215245. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  215246. tchar* t = const_cast <tchar*> ((const tchar*) result);
  215247. int i;
  215248. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  215249. t[i] = (tchar) tempOut[i];
  215250. t[i] = 0;
  215251. }
  215252. juce_free (tempIn);
  215253. juce_free (tempOut);
  215254. DisposeUnicodeToTextInfo (&conversionInfo);
  215255. }
  215256. return result;
  215257. }
  215258. const unsigned int macTimeToUnixTimeDiff = 0x7c25be90;
  215259. static uint64 utcDateTimeToUnixTime (const UTCDateTime& d) throw()
  215260. {
  215261. if (d.highSeconds == 0 && d.lowSeconds == 0 && d.fraction == 0)
  215262. return 0;
  215263. return (((((uint64) d.highSeconds) << 32) | (uint64) d.lowSeconds) * 1000)
  215264. + ((d.fraction * 1000) >> 16)
  215265. - 2082844800000ll;
  215266. }
  215267. static void unixTimeToUtcDateTime (uint64 t, UTCDateTime& d) throw()
  215268. {
  215269. if (t != 0)
  215270. t += 2082844800000ll;
  215271. d.highSeconds = (t / 1000) >> 32;
  215272. d.lowSeconds = (t / 1000) & (uint64) 0xffffffff;
  215273. d.fraction = ((t % 1000) << 16) / 1000;
  215274. }
  215275. void juce_getFileTimes (const String& fileName,
  215276. int64& modificationTime,
  215277. int64& accessTime,
  215278. int64& creationTime) throw()
  215279. {
  215280. modificationTime = 0;
  215281. accessTime = 0;
  215282. creationTime = 0;
  215283. FSRef fileRef;
  215284. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  215285. {
  215286. FSRefParam info;
  215287. zerostruct (info);
  215288. info.ref = &fileRef;
  215289. info.whichInfo = kFSCatInfoAllDates;
  215290. FSCatalogInfo catInfo;
  215291. info.catInfo = &catInfo;
  215292. if (PBGetCatalogInfoSync (&info) == noErr)
  215293. {
  215294. creationTime = utcDateTimeToUnixTime (catInfo.createDate);
  215295. accessTime = utcDateTimeToUnixTime (catInfo.accessDate);
  215296. modificationTime = utcDateTimeToUnixTime (catInfo.contentModDate);
  215297. }
  215298. }
  215299. }
  215300. bool juce_setFileTimes (const String& fileName,
  215301. int64 modificationTime,
  215302. int64 accessTime,
  215303. int64 creationTime) throw()
  215304. {
  215305. FSRef fileRef;
  215306. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  215307. {
  215308. FSRefParam info;
  215309. zerostruct (info);
  215310. info.ref = &fileRef;
  215311. info.whichInfo = kFSCatInfoAllDates;
  215312. FSCatalogInfo catInfo;
  215313. info.catInfo = &catInfo;
  215314. if (PBGetCatalogInfoSync (&info) == noErr)
  215315. {
  215316. if (creationTime != 0)
  215317. unixTimeToUtcDateTime (creationTime, catInfo.createDate);
  215318. if (modificationTime != 0)
  215319. unixTimeToUtcDateTime (modificationTime, catInfo.contentModDate);
  215320. if (accessTime != 0)
  215321. unixTimeToUtcDateTime (accessTime, catInfo.accessDate);
  215322. return PBSetCatalogInfoSync (&info) == noErr;
  215323. }
  215324. }
  215325. return false;
  215326. }
  215327. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  215328. {
  215329. const char* const fileNameUTF8 = fileName.toUTF8();
  215330. struct stat info;
  215331. const int res = stat (fileNameUTF8, &info);
  215332. bool ok = false;
  215333. if (res == 0)
  215334. {
  215335. info.st_mode &= 0777; // Just permissions
  215336. if (isReadOnly)
  215337. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  215338. else
  215339. // Give everybody write permission?
  215340. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  215341. ok = chmod (fileNameUTF8, info.st_mode) == 0;
  215342. }
  215343. return ok;
  215344. }
  215345. bool juce_copyFile (const String& src, const String& dst) throw()
  215346. {
  215347. const File destFile (dst);
  215348. if (! destFile.create())
  215349. return false;
  215350. FSRef srcRef, dstRef;
  215351. if (! (PlatformUtilities::makeFSRefFromPath (&srcRef, src)
  215352. && PlatformUtilities::makeFSRefFromPath (&dstRef, dst)))
  215353. {
  215354. return false;
  215355. }
  215356. int okForks = 0;
  215357. CatPositionRec iter;
  215358. iter.initialize = 0;
  215359. HFSUniStr255 forkName;
  215360. // can't just copy the data because this is a bloody Mac, so we need to copy each
  215361. // fork separately...
  215362. while (FSIterateForks (&srcRef, &iter, &forkName, 0, 0) == noErr)
  215363. {
  215364. SInt16 srcForkNum = 0, dstForkNum = 0;
  215365. OSErr err = FSOpenFork (&srcRef, forkName.length, forkName.unicode, fsRdPerm, &srcForkNum);
  215366. if (err == noErr)
  215367. {
  215368. err = FSOpenFork (&dstRef, forkName.length, forkName.unicode, fsRdWrPerm, &dstForkNum);
  215369. if (err == noErr)
  215370. {
  215371. MemoryBlock buf (32768);
  215372. SInt64 pos = 0;
  215373. for (;;)
  215374. {
  215375. ByteCount bytesRead = 0;
  215376. err = FSReadFork (srcForkNum, fsFromStart, pos, buf.getSize(), (char*) buf, &bytesRead);
  215377. if (bytesRead > 0)
  215378. {
  215379. err = FSWriteFork (dstForkNum, fsFromStart, pos, bytesRead, (const char*) buf, &bytesRead);
  215380. pos += bytesRead;
  215381. }
  215382. if (err != noErr)
  215383. {
  215384. if (err == eofErr)
  215385. ++okForks;
  215386. break;
  215387. }
  215388. }
  215389. FSFlushFork (dstForkNum);
  215390. FSCloseFork (dstForkNum);
  215391. }
  215392. FSCloseFork (srcForkNum);
  215393. }
  215394. }
  215395. if (okForks > 0) // some files seem to be ok even if not all their forks get copied..
  215396. {
  215397. // copy permissions..
  215398. struct stat info;
  215399. if (juce_stat (src, info))
  215400. chmod (dst.toUTF8(), info.st_mode & 0777);
  215401. return true;
  215402. }
  215403. return false;
  215404. }
  215405. const StringArray juce_getFileSystemRoots() throw()
  215406. {
  215407. StringArray s;
  215408. s.add (T("/"));
  215409. return s;
  215410. }
  215411. static bool isFileOnDriveType (const File* const f, const char** types) throw()
  215412. {
  215413. struct statfs buf;
  215414. if (doStatFS (f, buf))
  215415. {
  215416. const String type (buf.f_fstypename);
  215417. while (*types != 0)
  215418. if (type.equalsIgnoreCase (*types++))
  215419. return true;
  215420. }
  215421. return false;
  215422. }
  215423. bool File::isOnCDRomDrive() const throw()
  215424. {
  215425. static const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  215426. return isFileOnDriveType (this, (const char**) cdTypes);
  215427. }
  215428. bool File::isOnHardDisk() const throw()
  215429. {
  215430. static const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  215431. return ! (isOnCDRomDrive() || isFileOnDriveType (this, (const char**) nonHDTypes));
  215432. }
  215433. static bool juce_isHiddenFile (const String& path) throw()
  215434. {
  215435. FSRef ref;
  215436. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  215437. return false;
  215438. FSCatalogInfo info;
  215439. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  215440. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  215441. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  215442. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  215443. }
  215444. bool File::isHidden() const throw()
  215445. {
  215446. return juce_isHiddenFile (getFullPathName());
  215447. }
  215448. const File File::getSpecialLocation (const SpecialLocationType type)
  215449. {
  215450. const char* resultPath = 0;
  215451. switch (type)
  215452. {
  215453. case userHomeDirectory:
  215454. resultPath = getenv ("HOME");
  215455. if (resultPath == 0)
  215456. {
  215457. struct passwd* const pw = getpwuid (getuid());
  215458. if (pw != 0)
  215459. resultPath = pw->pw_dir;
  215460. }
  215461. break;
  215462. case userDocumentsDirectory:
  215463. resultPath = "~/Documents";
  215464. break;
  215465. case userDesktopDirectory:
  215466. resultPath = "~/Desktop";
  215467. break;
  215468. case userApplicationDataDirectory:
  215469. resultPath = "~/Library";
  215470. break;
  215471. case commonApplicationDataDirectory:
  215472. resultPath = "/Library";
  215473. break;
  215474. case globalApplicationsDirectory:
  215475. resultPath = "/Applications";
  215476. break;
  215477. case userMusicDirectory:
  215478. resultPath = "~/Music";
  215479. break;
  215480. case userMoviesDirectory:
  215481. resultPath = "~/Movies";
  215482. break;
  215483. case tempDirectory:
  215484. {
  215485. File tmp (T("~/Library/Caches/") + executableFile.getFileNameWithoutExtension());
  215486. tmp.createDirectory();
  215487. return tmp.getFullPathName();
  215488. }
  215489. case currentExecutableFile:
  215490. return executableFile;
  215491. case currentApplicationFile:
  215492. {
  215493. const File parent (executableFile.getParentDirectory());
  215494. return parent.getFullPathName().endsWithIgnoreCase (T("Contents/MacOS"))
  215495. ? parent.getParentDirectory().getParentDirectory()
  215496. : executableFile;
  215497. }
  215498. default:
  215499. jassertfalse // unknown type?
  215500. break;
  215501. }
  215502. if (resultPath != 0)
  215503. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  215504. return File::nonexistent;
  215505. }
  215506. void juce_setCurrentExecutableFileName (const String& filename) throw()
  215507. {
  215508. executableFile = File::getCurrentWorkingDirectory()
  215509. .getChildFile (PlatformUtilities::convertToPrecomposedUnicode (filename));
  215510. }
  215511. void juce_setCurrentExecutableFileNameFromBundleId (const String& bundleId) throw()
  215512. {
  215513. CFStringRef bundleIdStringRef = PlatformUtilities::juceStringToCFString (bundleId);
  215514. CFBundleRef bundleRef = CFBundleGetBundleWithIdentifier (bundleIdStringRef);
  215515. CFRelease (bundleIdStringRef);
  215516. if (bundleRef != 0)
  215517. {
  215518. CFURLRef exeURLRef = CFBundleCopyExecutableURL (bundleRef);
  215519. if (exeURLRef != 0)
  215520. {
  215521. CFStringRef pathStringRef = CFURLCopyFileSystemPath (exeURLRef, kCFURLPOSIXPathStyle);
  215522. CFRelease (exeURLRef);
  215523. if (pathStringRef != 0)
  215524. {
  215525. juce_setCurrentExecutableFileName (PlatformUtilities::cfStringToJuceString (pathStringRef));
  215526. CFRelease (pathStringRef);
  215527. }
  215528. }
  215529. }
  215530. }
  215531. const File File::getCurrentWorkingDirectory() throw()
  215532. {
  215533. char buf [2048];
  215534. getcwd (buf, sizeof(buf));
  215535. return File (PlatformUtilities::convertToPrecomposedUnicode (buf));
  215536. }
  215537. bool File::setAsCurrentWorkingDirectory() const throw()
  215538. {
  215539. return chdir (getFullPathName().toUTF8()) == 0;
  215540. }
  215541. struct FindFileStruct
  215542. {
  215543. String parentDir, wildCard;
  215544. DIR* dir;
  215545. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  215546. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  215547. {
  215548. const char* const wildCardUTF8 = wildCard.toUTF8();
  215549. for (;;)
  215550. {
  215551. struct dirent* const de = readdir (dir);
  215552. if (de == 0)
  215553. break;
  215554. if (fnmatch (wildCardUTF8, de->d_name, 0) == 0)
  215555. {
  215556. result = PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 ((const uint8*) de->d_name));
  215557. const String path (parentDir + result);
  215558. if (isDir != 0 || fileSize != 0)
  215559. {
  215560. struct stat info;
  215561. const bool statOk = juce_stat (path, info);
  215562. if (isDir != 0)
  215563. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  215564. if (isHidden != 0)
  215565. *isHidden = (de->d_name[0] == '.')
  215566. || juce_isHiddenFile (path);
  215567. if (fileSize != 0)
  215568. *fileSize = statOk ? info.st_size : 0;
  215569. }
  215570. if (modTime != 0 || creationTime != 0)
  215571. {
  215572. int64 m, a, c;
  215573. juce_getFileTimes (path, m, a, c);
  215574. if (modTime != 0)
  215575. *modTime = m;
  215576. if (creationTime != 0)
  215577. *creationTime = c;
  215578. }
  215579. if (isReadOnly != 0)
  215580. *isReadOnly = ! juce_canWriteToFile (path);
  215581. return true;
  215582. }
  215583. }
  215584. return false;
  215585. }
  215586. };
  215587. // returns 0 on failure
  215588. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  215589. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  215590. Time* creationTime, bool* isReadOnly) throw()
  215591. {
  215592. DIR* const d = opendir (directory.toUTF8());
  215593. if (d != 0)
  215594. {
  215595. FindFileStruct* const ff = new FindFileStruct();
  215596. ff->parentDir = directory;
  215597. if (!ff->parentDir.endsWithChar (File::separator))
  215598. ff->parentDir += File::separator;
  215599. ff->wildCard = wildCard;
  215600. ff->dir = d;
  215601. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  215602. {
  215603. return ff;
  215604. }
  215605. else
  215606. {
  215607. firstResultFile = String::empty;
  215608. isDir = false;
  215609. closedir (d);
  215610. delete ff;
  215611. }
  215612. }
  215613. return 0;
  215614. }
  215615. bool juce_findFileNext (void* handle, String& resultFile,
  215616. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  215617. {
  215618. FindFileStruct* const ff = (FindFileStruct*) handle;
  215619. if (ff != 0)
  215620. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  215621. return false;
  215622. }
  215623. void juce_findFileClose (void* handle) throw()
  215624. {
  215625. FindFileStruct* const ff = (FindFileStruct*)handle;
  215626. if (ff != 0)
  215627. {
  215628. closedir (ff->dir);
  215629. delete ff;
  215630. }
  215631. }
  215632. bool juce_launchExecutable (const String& pathAndArguments) throw()
  215633. {
  215634. char* const argv[4] = { "/bin/sh", "-c", (char*) (const char*) pathAndArguments, 0 };
  215635. const int cpid = fork();
  215636. if (cpid == 0)
  215637. {
  215638. // Child process
  215639. if (execve (argv[0], argv, 0) < 0)
  215640. exit (0);
  215641. }
  215642. else
  215643. {
  215644. if (cpid < 0)
  215645. return false;
  215646. }
  215647. return true;
  215648. }
  215649. bool juce_launchFile (const String& fileName,
  215650. const String& parameters) throw()
  215651. {
  215652. bool ok = false;
  215653. if (fileName.startsWithIgnoreCase (T("http:"))
  215654. || fileName.startsWithIgnoreCase (T("https:"))
  215655. || fileName.startsWithIgnoreCase (T("ftp:"))
  215656. || fileName.startsWithIgnoreCase (T("file:")))
  215657. {
  215658. CFStringRef urlString = PlatformUtilities::juceStringToCFString (fileName);
  215659. if (urlString != 0)
  215660. {
  215661. CFURLRef url = CFURLCreateWithString (kCFAllocatorDefault,
  215662. urlString, 0);
  215663. CFRelease (urlString);
  215664. if (url != 0)
  215665. {
  215666. ok = (LSOpenCFURLRef (url, 0) == noErr);
  215667. CFRelease (url);
  215668. }
  215669. }
  215670. }
  215671. else
  215672. {
  215673. FSRef ref;
  215674. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  215675. {
  215676. if (juce_isDirectory (fileName) && parameters.isNotEmpty())
  215677. {
  215678. // if we're launching a bundled app with a document..
  215679. StringArray docs;
  215680. docs.addTokens (parameters, true);
  215681. FSRef* docRefs = new FSRef [docs.size()];
  215682. for (int i = 0; i < docs.size(); ++i)
  215683. PlatformUtilities::makeFSRefFromPath (docRefs + i, docs[i]);
  215684. LSLaunchFSRefSpec ors;
  215685. ors.appRef = &ref;
  215686. ors.numDocs = docs.size();
  215687. ors.itemRefs = docRefs;
  215688. ors.passThruParams = 0;
  215689. ors.launchFlags = kLSLaunchDefaults;
  215690. ors.asyncRefCon = 0;
  215691. FSRef actual;
  215692. ok = (LSOpenFromRefSpec (&ors, &actual) == noErr);
  215693. delete docRefs;
  215694. }
  215695. else
  215696. {
  215697. if (parameters.isNotEmpty())
  215698. ok = juce_launchExecutable (T("\"") + fileName + T("\" ") + parameters);
  215699. else
  215700. ok = (LSOpenFSRef (&ref, 0) == noErr);
  215701. }
  215702. }
  215703. }
  215704. return ok;
  215705. }
  215706. bool PlatformUtilities::makeFSSpecFromPath (FSSpec* fs, const String& path)
  215707. {
  215708. FSRef ref;
  215709. return makeFSRefFromPath (&ref, path)
  215710. && FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, fs, 0) == noErr;
  215711. }
  215712. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  215713. {
  215714. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  215715. }
  215716. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  215717. {
  215718. uint8 path [2048];
  215719. zeromem (path, sizeof (path));
  215720. String result;
  215721. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  215722. result = String::fromUTF8 (path);
  215723. return PlatformUtilities::convertToPrecomposedUnicode (result);
  215724. }
  215725. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  215726. {
  215727. FSRef fs;
  215728. if (makeFSRefFromPath (&fs, filename))
  215729. {
  215730. LSItemInfoRecord info;
  215731. if (LSCopyItemInfoForRef (&fs, kLSRequestTypeCreator, &info) == noErr)
  215732. return info.filetype;
  215733. }
  215734. return 0;
  215735. }
  215736. bool PlatformUtilities::isBundle (const String& filename)
  215737. {
  215738. FSRef fs;
  215739. if (makeFSRefFromPath (&fs, filename))
  215740. {
  215741. LSItemInfoRecord info;
  215742. if (LSCopyItemInfoForRef (&fs, kLSItemInfoIsPackage, &info) == noErr)
  215743. return (info.flags & kLSItemInfoIsPackage) != 0;
  215744. }
  215745. return false;
  215746. }
  215747. END_JUCE_NAMESPACE
  215748. /********* End of inlined file: juce_mac_Files.cpp *********/
  215749. /********* Start of inlined file: juce_mac_NamedPipe.cpp *********/
  215750. #include <sys/stat.h>
  215751. #include <sys/dir.h>
  215752. #include <fcntl.h>
  215753. // As well as being for the mac, this file is included by the linux build.
  215754. #if ! JUCE_MAC
  215755. #include <sys/wait.h>
  215756. #include <errno.h>
  215757. #include <unistd.h>
  215758. #endif
  215759. BEGIN_JUCE_NAMESPACE
  215760. struct NamedPipeInternal
  215761. {
  215762. String pipeInName, pipeOutName;
  215763. int pipeIn, pipeOut;
  215764. bool volatile createdPipe, blocked, stopReadOperation;
  215765. static void signalHandler (int) {}
  215766. };
  215767. void NamedPipe::cancelPendingReads()
  215768. {
  215769. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  215770. {
  215771. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215772. intern->stopReadOperation = true;
  215773. char buffer [1] = { 0 };
  215774. ::write (intern->pipeIn, buffer, 1);
  215775. int timeout = 2000;
  215776. while (intern->blocked && --timeout >= 0)
  215777. Thread::sleep (2);
  215778. intern->stopReadOperation = false;
  215779. }
  215780. }
  215781. void NamedPipe::close()
  215782. {
  215783. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215784. if (intern != 0)
  215785. {
  215786. internal = 0;
  215787. if (intern->pipeIn != -1)
  215788. ::close (intern->pipeIn);
  215789. if (intern->pipeOut != -1)
  215790. ::close (intern->pipeOut);
  215791. if (intern->createdPipe)
  215792. {
  215793. unlink (intern->pipeInName);
  215794. unlink (intern->pipeOutName);
  215795. }
  215796. delete intern;
  215797. }
  215798. }
  215799. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  215800. {
  215801. close();
  215802. NamedPipeInternal* const intern = new NamedPipeInternal();
  215803. internal = intern;
  215804. intern->createdPipe = createPipe;
  215805. intern->blocked = false;
  215806. intern->stopReadOperation = false;
  215807. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  215808. siginterrupt (SIGPIPE, 1);
  215809. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  215810. intern->pipeInName = pipePath + T("_in");
  215811. intern->pipeOutName = pipePath + T("_out");
  215812. intern->pipeIn = -1;
  215813. intern->pipeOut = -1;
  215814. if (createPipe)
  215815. {
  215816. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  215817. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  215818. {
  215819. delete intern;
  215820. internal = 0;
  215821. return false;
  215822. }
  215823. }
  215824. return true;
  215825. }
  215826. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  215827. {
  215828. int bytesRead = -1;
  215829. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215830. if (intern != 0)
  215831. {
  215832. intern->blocked = true;
  215833. if (intern->pipeIn == -1)
  215834. {
  215835. if (intern->createdPipe)
  215836. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  215837. else
  215838. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  215839. if (intern->pipeIn == -1)
  215840. {
  215841. intern->blocked = false;
  215842. return -1;
  215843. }
  215844. }
  215845. bytesRead = 0;
  215846. char* p = (char*) destBuffer;
  215847. while (bytesRead < maxBytesToRead)
  215848. {
  215849. const int bytesThisTime = maxBytesToRead - bytesRead;
  215850. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  215851. if (numRead <= 0 || intern->stopReadOperation)
  215852. {
  215853. bytesRead = -1;
  215854. break;
  215855. }
  215856. bytesRead += numRead;
  215857. p += bytesRead;
  215858. }
  215859. intern->blocked = false;
  215860. }
  215861. return bytesRead;
  215862. }
  215863. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  215864. {
  215865. int bytesWritten = -1;
  215866. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215867. if (intern != 0)
  215868. {
  215869. if (intern->pipeOut == -1)
  215870. {
  215871. if (intern->createdPipe)
  215872. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  215873. else
  215874. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  215875. if (intern->pipeOut == -1)
  215876. {
  215877. return -1;
  215878. }
  215879. }
  215880. const char* p = (const char*) sourceBuffer;
  215881. bytesWritten = 0;
  215882. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  215883. while (bytesWritten < numBytesToWrite
  215884. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  215885. {
  215886. const int bytesThisTime = numBytesToWrite - bytesWritten;
  215887. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  215888. if (numWritten <= 0)
  215889. {
  215890. bytesWritten = -1;
  215891. break;
  215892. }
  215893. bytesWritten += numWritten;
  215894. p += bytesWritten;
  215895. }
  215896. }
  215897. return bytesWritten;
  215898. }
  215899. END_JUCE_NAMESPACE
  215900. /********* End of inlined file: juce_mac_NamedPipe.cpp *********/
  215901. /********* Start of inlined file: juce_mac_SystemStats.mm *********/
  215902. /********* Start of inlined file: juce_mac_NativeHeaders.h *********/
  215903. #ifndef __JUCE_MAC_NATIVEHEADERS_JUCEHEADER__
  215904. #define __JUCE_MAC_NATIVEHEADERS_JUCEHEADER__
  215905. #include <Cocoa/Cocoa.h>
  215906. BEGIN_JUCE_NAMESPACE
  215907. class AutoPool
  215908. {
  215909. public:
  215910. AutoPool() { pool = [[NSAutoreleasePool alloc] init]; }
  215911. ~AutoPool() { [pool release]; }
  215912. private:
  215913. NSAutoreleasePool* pool;
  215914. };
  215915. END_JUCE_NAMESPACE
  215916. static const JUCE_NAMESPACE::String nsStringToJuce (NSString* s)
  215917. {
  215918. return JUCE_NAMESPACE::String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [s UTF8String]);
  215919. }
  215920. static NSString* juceStringToNS (const JUCE_NAMESPACE::String& s)
  215921. {
  215922. return [NSString stringWithUTF8String: (const char*) s.toUTF8()];
  215923. }
  215924. #endif
  215925. /********* End of inlined file: juce_mac_NativeHeaders.h *********/
  215926. #include <AppKit/AppKit.h>
  215927. #include <CoreAudio/HostTime.h>
  215928. #include <ctime>
  215929. #include <sys/resource.h>
  215930. BEGIN_JUCE_NAMESPACE
  215931. static int64 highResTimerFrequency;
  215932. #if JUCE_INTEL
  215933. static void juce_getCpuVendor (char* const v) throw()
  215934. {
  215935. int vendor[4];
  215936. zerostruct (vendor);
  215937. int dummy = 0;
  215938. asm ("mov %%ebx, %%esi \n\t"
  215939. "cpuid \n\t"
  215940. "xchg %%esi, %%ebx"
  215941. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  215942. memcpy (v, vendor, 16);
  215943. }
  215944. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures) throw()
  215945. {
  215946. unsigned int cpu = 0;
  215947. unsigned int ext = 0;
  215948. unsigned int family = 0;
  215949. unsigned int dummy = 0;
  215950. asm ("mov %%ebx, %%esi \n\t"
  215951. "cpuid \n\t"
  215952. "xchg %%esi, %%ebx"
  215953. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  215954. familyModel = family;
  215955. extFeatures = ext;
  215956. return cpu;
  215957. }
  215958. struct CPUFlags
  215959. {
  215960. bool hasMMX : 1;
  215961. bool hasSSE : 1;
  215962. bool hasSSE2 : 1;
  215963. bool has3DNow : 1;
  215964. };
  215965. static CPUFlags cpuFlags;
  215966. #endif
  215967. void Logger::outputDebugString (const String& text) throw()
  215968. {
  215969. String withLineFeed (text + T("\n"));
  215970. const char* const utf8 = withLineFeed.toUTF8();
  215971. fwrite (utf8, strlen (utf8), 1, stdout);
  215972. }
  215973. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  215974. {
  215975. String text;
  215976. va_list args;
  215977. va_start (args, format);
  215978. text.vprintf(format, args);
  215979. outputDebugString (text);
  215980. }
  215981. int SystemStats::getMemorySizeInMegabytes() throw()
  215982. {
  215983. long bytes;
  215984. if (Gestalt (gestaltPhysicalRAMSize, &bytes) == noErr)
  215985. return (int) (((unsigned long) bytes) / (1024 * 1024));
  215986. return 0;
  215987. }
  215988. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  215989. {
  215990. return MacOSX;
  215991. }
  215992. const String SystemStats::getOperatingSystemName() throw()
  215993. {
  215994. return T("Mac OS X");
  215995. }
  215996. bool SystemStats::isOperatingSystem64Bit() throw()
  215997. {
  215998. #if JUCE_64BIT
  215999. return true;
  216000. #else
  216001. //xxx not sure how to find this out?..
  216002. return false;
  216003. #endif
  216004. }
  216005. void SystemStats::initialiseStats() throw()
  216006. {
  216007. static bool initialised = false;
  216008. if (! initialised)
  216009. {
  216010. initialised = true;
  216011. [NSApplication sharedApplication];
  216012. NSApplicationLoad();
  216013. #if JUCE_INTEL
  216014. {
  216015. unsigned int familyModel, extFeatures;
  216016. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  216017. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  216018. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  216019. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  216020. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  216021. }
  216022. #endif
  216023. highResTimerFrequency = (int64) AudioGetHostClockFrequency();
  216024. String s (SystemStats::getJUCEVersion());
  216025. rlimit lim;
  216026. getrlimit (RLIMIT_NOFILE, &lim);
  216027. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  216028. setrlimit (RLIMIT_NOFILE, &lim);
  216029. }
  216030. }
  216031. bool SystemStats::hasMMX() throw()
  216032. {
  216033. #if JUCE_INTEL
  216034. return cpuFlags.hasMMX;
  216035. #else
  216036. return false;
  216037. #endif
  216038. }
  216039. bool SystemStats::hasSSE() throw()
  216040. {
  216041. #if JUCE_INTEL
  216042. return cpuFlags.hasSSE;
  216043. #else
  216044. return false;
  216045. #endif
  216046. }
  216047. bool SystemStats::hasSSE2() throw()
  216048. {
  216049. #if JUCE_INTEL
  216050. return cpuFlags.hasSSE2;
  216051. #else
  216052. return false;
  216053. #endif
  216054. }
  216055. bool SystemStats::has3DNow() throw()
  216056. {
  216057. #if JUCE_INTEL
  216058. return cpuFlags.has3DNow;
  216059. #else
  216060. return false;
  216061. #endif
  216062. }
  216063. const String SystemStats::getCpuVendor() throw()
  216064. {
  216065. #if JUCE_INTEL
  216066. char v [16];
  216067. juce_getCpuVendor (v);
  216068. return String (v, 16);
  216069. #else
  216070. return String::empty;
  216071. #endif
  216072. }
  216073. int SystemStats::getCpuSpeedInMegaherz() throw()
  216074. {
  216075. return GetCPUSpeed();
  216076. }
  216077. int SystemStats::getNumCpus() throw()
  216078. {
  216079. return MPProcessors();
  216080. }
  216081. static int64 juce_getMicroseconds() throw()
  216082. {
  216083. UnsignedWide t;
  216084. Microseconds (&t);
  216085. return (((int64) t.hi) << 32) | t.lo;
  216086. }
  216087. uint32 juce_millisecondsSinceStartup() throw()
  216088. {
  216089. return (uint32) (juce_getMicroseconds() / 1000);
  216090. }
  216091. double Time::getMillisecondCounterHiRes() throw()
  216092. {
  216093. // xxx might be more accurate to use a scaled AudioGetCurrentHostTime?
  216094. return juce_getMicroseconds() * 0.001;
  216095. }
  216096. int64 Time::getHighResolutionTicks() throw()
  216097. {
  216098. return (int64) AudioGetCurrentHostTime();
  216099. }
  216100. int64 Time::getHighResolutionTicksPerSecond() throw()
  216101. {
  216102. return highResTimerFrequency;
  216103. }
  216104. int64 SystemStats::getClockCycleCounter() throw()
  216105. {
  216106. jassertfalse
  216107. return 0;
  216108. }
  216109. bool Time::setSystemTimeToThisTime() const throw()
  216110. {
  216111. jassertfalse
  216112. return false;
  216113. }
  216114. int SystemStats::getPageSize() throw()
  216115. {
  216116. jassertfalse
  216117. return 512; //xxx
  216118. }
  216119. void PlatformUtilities::fpuReset()
  216120. {
  216121. }
  216122. END_JUCE_NAMESPACE
  216123. /********* End of inlined file: juce_mac_SystemStats.mm *********/
  216124. /********* Start of inlined file: juce_mac_Threads.cpp *********/
  216125. #include <pthread.h>
  216126. #include <sched.h>
  216127. #include <sys/file.h>
  216128. #include <sys/types.h>
  216129. #include <sys/sysctl.h>
  216130. BEGIN_JUCE_NAMESPACE
  216131. /*
  216132. Note that a lot of methods that you'd expect to find in this file actually
  216133. live in juce_posix_SharedCode.cpp!
  216134. */
  216135. void JUCE_API juce_threadEntryPoint (void*);
  216136. void* threadEntryProc (void* userData) throw()
  216137. {
  216138. juce_threadEntryPoint (userData);
  216139. return 0;
  216140. }
  216141. void* juce_createThread (void* userData) throw()
  216142. {
  216143. pthread_t handle = 0;
  216144. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  216145. {
  216146. pthread_detach (handle);
  216147. return (void*) handle;
  216148. }
  216149. return 0;
  216150. }
  216151. void juce_killThread (void* handle) throw()
  216152. {
  216153. if (handle != 0)
  216154. pthread_cancel ((pthread_t) handle);
  216155. }
  216156. void juce_setCurrentThreadName (const String& /*name*/) throw()
  216157. {
  216158. }
  216159. int Thread::getCurrentThreadId() throw()
  216160. {
  216161. return (int) pthread_self();
  216162. }
  216163. void juce_setThreadPriority (void* handle, int priority) throw()
  216164. {
  216165. if (handle == 0)
  216166. handle = (void*) pthread_self();
  216167. struct sched_param param;
  216168. int policy;
  216169. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  216170. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  216171. pthread_setschedparam ((pthread_t) handle, policy, &param);
  216172. }
  216173. void Thread::yield() throw()
  216174. {
  216175. sched_yield();
  216176. }
  216177. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  216178. {
  216179. // xxx
  216180. jassertfalse
  216181. }
  216182. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  216183. {
  216184. static char testResult = 0;
  216185. if (testResult == 0)
  216186. {
  216187. struct kinfo_proc info;
  216188. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  216189. size_t sz = sizeof (info);
  216190. sysctl (m, 4, &info, &sz, 0, 0);
  216191. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  216192. }
  216193. return testResult > 0;
  216194. }
  216195. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  216196. {
  216197. return juce_isRunningUnderDebugger();
  216198. }
  216199. void Process::raisePrivilege()
  216200. {
  216201. jassertfalse
  216202. }
  216203. void Process::lowerPrivilege()
  216204. {
  216205. jassertfalse
  216206. }
  216207. void Process::terminate()
  216208. {
  216209. exit (0);
  216210. }
  216211. void Process::setPriority (ProcessPriority p)
  216212. {
  216213. // xxx
  216214. }
  216215. void* Process::loadDynamicLibrary (const String& name)
  216216. {
  216217. // xxx needs to use bundles
  216218. FSSpec fs;
  216219. if (PlatformUtilities::makeFSSpecFromPath (&fs, name))
  216220. {
  216221. CFragConnectionID connID;
  216222. Ptr mainPtr;
  216223. Str255 errorMessage;
  216224. Str63 nm;
  216225. PlatformUtilities::copyToStr63 (nm, name);
  216226. const OSErr err = GetDiskFragment (&fs, 0, kCFragGoesToEOF, nm, kReferenceCFrag, &connID, &mainPtr, errorMessage);
  216227. if (err == noErr)
  216228. return (void*)connID;
  216229. }
  216230. return 0;
  216231. }
  216232. void Process::freeDynamicLibrary (void* handle)
  216233. {
  216234. if (handle != 0)
  216235. CloseConnection ((CFragConnectionID*)&handle);
  216236. }
  216237. void* Process::getProcedureEntryPoint (void* h, const String& procedureName)
  216238. {
  216239. if (h != 0)
  216240. {
  216241. CFragSymbolClass cl;
  216242. Ptr ptr;
  216243. Str255 name;
  216244. PlatformUtilities::copyToStr255 (name, procedureName);
  216245. if (FindSymbol ((CFragConnectionID) h, name, &ptr, &cl) == noErr)
  216246. {
  216247. return ptr;
  216248. }
  216249. }
  216250. return 0;
  216251. }
  216252. END_JUCE_NAMESPACE
  216253. /********* End of inlined file: juce_mac_Threads.cpp *********/
  216254. /********* Start of inlined file: juce_mac_Network.mm *********/
  216255. #include <IOKit/IOKitLib.h>
  216256. #include <IOKit/network/IOEthernetInterface.h>
  216257. #include <IOKit/network/IONetworkInterface.h>
  216258. #include <IOKit/network/IOEthernetController.h>
  216259. #include <netdb.h>
  216260. #include <arpa/inet.h>
  216261. #include <netinet/in.h>
  216262. #include <sys/types.h>
  216263. #include <sys/socket.h>
  216264. #include <sys/wait.h>
  216265. BEGIN_JUCE_NAMESPACE
  216266. /********* Start of inlined file: juce_mac_HTTPStream.h *********/
  216267. // (This file gets included by the mac + linux networking code)
  216268. /** A HTTP input stream that uses sockets.
  216269. */
  216270. class JUCE_HTTPSocketStream
  216271. {
  216272. public:
  216273. JUCE_HTTPSocketStream()
  216274. : readPosition (0),
  216275. socketHandle (-1),
  216276. levelsOfRedirection (0),
  216277. timeoutSeconds (15)
  216278. {
  216279. }
  216280. ~JUCE_HTTPSocketStream()
  216281. {
  216282. closeSocket();
  216283. }
  216284. bool open (const String& url,
  216285. const String& headers,
  216286. const MemoryBlock& postData,
  216287. const bool isPost,
  216288. URL::OpenStreamProgressCallback* callback,
  216289. void* callbackContext,
  216290. int timeOutMs)
  216291. {
  216292. closeSocket();
  216293. uint32 timeOutTime = Time::getMillisecondCounter();
  216294. if (timeOutMs == 0)
  216295. timeOutTime += 60000;
  216296. else if (timeOutMs < 0)
  216297. timeOutTime = 0xffffffff;
  216298. else
  216299. timeOutTime += timeOutMs;
  216300. String hostName, hostPath;
  216301. int hostPort;
  216302. if (! decomposeURL (url, hostName, hostPath, hostPort))
  216303. return false;
  216304. const struct hostent* host = 0;
  216305. int port = 0;
  216306. String proxyName, proxyPath;
  216307. int proxyPort = 0;
  216308. String proxyURL (getenv ("http_proxy"));
  216309. if (proxyURL.startsWithIgnoreCase (T("http://")))
  216310. {
  216311. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  216312. return false;
  216313. host = gethostbyname ((const char*) proxyName.toUTF8());
  216314. port = proxyPort;
  216315. }
  216316. else
  216317. {
  216318. host = gethostbyname ((const char*) hostName.toUTF8());
  216319. port = hostPort;
  216320. }
  216321. if (host == 0)
  216322. return false;
  216323. struct sockaddr_in address;
  216324. zerostruct (address);
  216325. memcpy ((void*) &address.sin_addr, (const void*) host->h_addr, host->h_length);
  216326. address.sin_family = host->h_addrtype;
  216327. address.sin_port = htons (port);
  216328. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  216329. if (socketHandle == -1)
  216330. return false;
  216331. int receiveBufferSize = 16384;
  216332. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  216333. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  216334. #if JUCE_MAC
  216335. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  216336. #endif
  216337. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  216338. {
  216339. closeSocket();
  216340. return false;
  216341. }
  216342. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  216343. proxyName, proxyPort,
  216344. hostPath, url,
  216345. headers, postData,
  216346. isPost));
  216347. int totalHeaderSent = 0;
  216348. while (totalHeaderSent < requestHeader.getSize())
  216349. {
  216350. if (Time::getMillisecondCounter() > timeOutTime)
  216351. {
  216352. closeSocket();
  216353. return false;
  216354. }
  216355. const int numToSend = jmin (1024, requestHeader.getSize() - totalHeaderSent);
  216356. if (send (socketHandle,
  216357. ((const char*) requestHeader.getData()) + totalHeaderSent,
  216358. numToSend, 0)
  216359. != numToSend)
  216360. {
  216361. closeSocket();
  216362. return false;
  216363. }
  216364. totalHeaderSent += numToSend;
  216365. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  216366. {
  216367. closeSocket();
  216368. return false;
  216369. }
  216370. }
  216371. const String responseHeader (readResponse (timeOutTime));
  216372. if (responseHeader.isNotEmpty())
  216373. {
  216374. //DBG (responseHeader);
  216375. StringArray lines;
  216376. lines.addLines (responseHeader);
  216377. // NB - using charToString() here instead of just T(" "), because that was
  216378. // causing a mysterious gcc internal compiler error...
  216379. const int statusCode = responseHeader.fromFirstOccurrenceOf (String::charToString (T(' ')), false, false)
  216380. .substring (0, 3)
  216381. .getIntValue();
  216382. //int contentLength = findHeaderItem (lines, T("Content-Length:")).getIntValue();
  216383. //bool isChunked = findHeaderItem (lines, T("Transfer-Encoding:")).equalsIgnoreCase ("chunked");
  216384. String location (findHeaderItem (lines, T("Location:")));
  216385. if (statusCode >= 300 && statusCode < 400
  216386. && location.isNotEmpty())
  216387. {
  216388. if (! location.startsWithIgnoreCase (T("http://")))
  216389. location = T("http://") + location;
  216390. if (levelsOfRedirection++ < 3)
  216391. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  216392. }
  216393. else
  216394. {
  216395. levelsOfRedirection = 0;
  216396. return true;
  216397. }
  216398. }
  216399. closeSocket();
  216400. return false;
  216401. }
  216402. int read (void* buffer, int bytesToRead)
  216403. {
  216404. fd_set readbits;
  216405. FD_ZERO (&readbits);
  216406. FD_SET (socketHandle, &readbits);
  216407. struct timeval tv;
  216408. tv.tv_sec = timeoutSeconds;
  216409. tv.tv_usec = 0;
  216410. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216411. return 0; // (timeout)
  216412. const int bytesRead = jmax (0, recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  216413. readPosition += bytesRead;
  216414. return bytesRead;
  216415. }
  216416. int readPosition;
  216417. juce_UseDebuggingNewOperator
  216418. private:
  216419. int socketHandle, levelsOfRedirection;
  216420. const int timeoutSeconds;
  216421. void closeSocket()
  216422. {
  216423. if (socketHandle >= 0)
  216424. close (socketHandle);
  216425. socketHandle = -1;
  216426. }
  216427. const MemoryBlock createRequestHeader (const String& hostName,
  216428. const int hostPort,
  216429. const String& proxyName,
  216430. const int proxyPort,
  216431. const String& hostPath,
  216432. const String& originalURL,
  216433. const String& headers,
  216434. const MemoryBlock& postData,
  216435. const bool isPost)
  216436. {
  216437. String header (isPost ? "POST " : "GET ");
  216438. if (proxyName.isEmpty())
  216439. {
  216440. header << hostPath << " HTTP/1.0\r\nHost: "
  216441. << hostName << ':' << hostPort;
  216442. }
  216443. else
  216444. {
  216445. header << originalURL << " HTTP/1.0\r\nHost: "
  216446. << proxyName << ':' << proxyPort;
  216447. }
  216448. header << "\r\nUser-Agent: JUCE/"
  216449. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  216450. << "\r\nConnection: Close\r\nContent-Length: "
  216451. << postData.getSize() << "\r\n"
  216452. << headers << "\r\n";
  216453. MemoryBlock mb;
  216454. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  216455. mb.append (postData.getData(), postData.getSize());
  216456. return mb;
  216457. }
  216458. const String readResponse (const uint32 timeOutTime)
  216459. {
  216460. int bytesRead = 0, numConsecutiveLFs = 0;
  216461. MemoryBlock buffer (1024, true);
  216462. while (numConsecutiveLFs < 2 && bytesRead < 32768
  216463. && Time::getMillisecondCounter() <= timeOutTime)
  216464. {
  216465. fd_set readbits;
  216466. FD_ZERO (&readbits);
  216467. FD_SET (socketHandle, &readbits);
  216468. struct timeval tv;
  216469. tv.tv_sec = timeoutSeconds;
  216470. tv.tv_usec = 0;
  216471. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216472. return String::empty; // (timeout)
  216473. buffer.ensureSize (bytesRead + 8, true);
  216474. char* const dest = (char*) buffer.getData() + bytesRead;
  216475. if (recv (socketHandle, dest, 1, 0) == -1)
  216476. return String::empty;
  216477. const char lastByte = *dest;
  216478. ++bytesRead;
  216479. if (lastByte == '\n')
  216480. ++numConsecutiveLFs;
  216481. else if (lastByte != '\r')
  216482. numConsecutiveLFs = 0;
  216483. }
  216484. const String header (String::fromUTF8 ((const uint8*) buffer.getData()));
  216485. if (header.startsWithIgnoreCase (T("HTTP/")))
  216486. return header.trimEnd();
  216487. return String::empty;
  216488. }
  216489. static bool decomposeURL (const String& url,
  216490. String& host, String& path, int& port)
  216491. {
  216492. if (! url.startsWithIgnoreCase (T("http://")))
  216493. return false;
  216494. const int nextSlash = url.indexOfChar (7, '/');
  216495. int nextColon = url.indexOfChar (7, ':');
  216496. if (nextColon > nextSlash && nextSlash > 0)
  216497. nextColon = -1;
  216498. if (nextColon >= 0)
  216499. {
  216500. host = url.substring (7, nextColon);
  216501. if (nextSlash >= 0)
  216502. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  216503. else
  216504. port = url.substring (nextColon + 1).getIntValue();
  216505. }
  216506. else
  216507. {
  216508. port = 80;
  216509. if (nextSlash >= 0)
  216510. host = url.substring (7, nextSlash);
  216511. else
  216512. host = url.substring (7);
  216513. }
  216514. if (nextSlash >= 0)
  216515. path = url.substring (nextSlash);
  216516. else
  216517. path = T("/");
  216518. return true;
  216519. }
  216520. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  216521. {
  216522. for (int i = 0; i < lines.size(); ++i)
  216523. if (lines[i].startsWithIgnoreCase (itemName))
  216524. return lines[i].substring (itemName.length()).trim();
  216525. return String::empty;
  216526. }
  216527. };
  216528. bool juce_isOnLine()
  216529. {
  216530. return true;
  216531. }
  216532. void* juce_openInternetFile (const String& url,
  216533. const String& headers,
  216534. const MemoryBlock& postData,
  216535. const bool isPost,
  216536. URL::OpenStreamProgressCallback* callback,
  216537. void* callbackContext,
  216538. int timeOutMs)
  216539. {
  216540. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  216541. if (s->open (url, headers, postData, isPost,
  216542. callback, callbackContext, timeOutMs))
  216543. return s;
  216544. delete s;
  216545. return 0;
  216546. }
  216547. void juce_closeInternetFile (void* handle)
  216548. {
  216549. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  216550. if (s != 0)
  216551. delete s;
  216552. }
  216553. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  216554. {
  216555. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  216556. if (s != 0)
  216557. return s->read (buffer, bytesToRead);
  216558. return 0;
  216559. }
  216560. int juce_seekInInternetFile (void* handle, int newPosition)
  216561. {
  216562. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  216563. if (s != 0)
  216564. return s->readPosition;
  216565. return 0;
  216566. }
  216567. /********* End of inlined file: juce_mac_HTTPStream.h *********/
  216568. static bool GetEthernetIterator (io_iterator_t* matchingServices) throw()
  216569. {
  216570. mach_port_t masterPort;
  216571. if (IOMasterPort (MACH_PORT_NULL, &masterPort) == KERN_SUCCESS)
  216572. {
  216573. CFMutableDictionaryRef dict = IOServiceMatching (kIOEthernetInterfaceClass);
  216574. if (dict != 0)
  216575. {
  216576. CFMutableDictionaryRef propDict = CFDictionaryCreateMutable (kCFAllocatorDefault,
  216577. 0,
  216578. &kCFTypeDictionaryKeyCallBacks,
  216579. &kCFTypeDictionaryValueCallBacks);
  216580. if (propDict != 0)
  216581. {
  216582. CFDictionarySetValue (propDict, CFSTR (kIOPrimaryInterface), kCFBooleanTrue);
  216583. CFDictionarySetValue (dict, CFSTR (kIOPropertyMatchKey), propDict);
  216584. CFRelease (propDict);
  216585. }
  216586. }
  216587. return IOServiceGetMatchingServices (masterPort, dict, matchingServices) == KERN_SUCCESS;
  216588. }
  216589. return false;
  216590. }
  216591. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  216592. {
  216593. int numResults = 0;
  216594. io_iterator_t it;
  216595. if (GetEthernetIterator (&it))
  216596. {
  216597. io_object_t i;
  216598. while ((i = IOIteratorNext (it)) != 0)
  216599. {
  216600. io_object_t controller;
  216601. if (IORegistryEntryGetParentEntry (i, kIOServicePlane, &controller) == KERN_SUCCESS)
  216602. {
  216603. CFTypeRef data = IORegistryEntryCreateCFProperty (controller,
  216604. CFSTR (kIOMACAddress),
  216605. kCFAllocatorDefault,
  216606. 0);
  216607. if (data != 0)
  216608. {
  216609. UInt8 addr [kIOEthernetAddressSize];
  216610. zeromem (addr, sizeof (addr));
  216611. CFDataGetBytes ((CFDataRef) data, CFRangeMake (0, sizeof (addr)), addr);
  216612. CFRelease (data);
  216613. int64 a = 0;
  216614. for (int i = 6; --i >= 0;)
  216615. a = (a << 8) | addr[i];
  216616. if (! littleEndian)
  216617. a = (int64) swapByteOrder ((uint64) a);
  216618. if (numResults < maxNum)
  216619. {
  216620. *addresses++ = a;
  216621. ++numResults;
  216622. }
  216623. }
  216624. IOObjectRelease (controller);
  216625. }
  216626. IOObjectRelease (i);
  216627. }
  216628. IOObjectRelease (it);
  216629. }
  216630. return numResults;
  216631. }
  216632. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  216633. const String& emailSubject,
  216634. const String& bodyText,
  216635. const StringArray& filesToAttach)
  216636. {
  216637. const AutoPool pool;
  216638. String script;
  216639. script << "tell application \"Mail\"\r\n"
  216640. "set newMessage to make new outgoing message with properties {subject:\""
  216641. << emailSubject.replace (T("\""), T("\\\""))
  216642. << "\", content:\""
  216643. << bodyText.replace (T("\""), T("\\\""))
  216644. << "\" & return & return}\r\n"
  216645. "tell newMessage\r\n"
  216646. "set visible to true\r\n"
  216647. "set sender to \"sdfsdfsdfewf\"\r\n"
  216648. "make new to recipient at end of to recipients with properties {address:\""
  216649. << targetEmailAddress
  216650. << "\"}\r\n";
  216651. for (int i = 0; i < filesToAttach.size(); ++i)
  216652. {
  216653. script << "tell content\r\n"
  216654. "make new attachment with properties {file name:\""
  216655. << filesToAttach[i].replace (T("\""), T("\\\""))
  216656. << "\"} at after the last paragraph\r\n"
  216657. "end tell\r\n";
  216658. }
  216659. script << "end tell\r\n"
  216660. "end tell\r\n";
  216661. NSAppleScript* s = [[NSAppleScript alloc]
  216662. initWithSource: [NSString stringWithUTF8String: (const char*) script.toUTF8()]];
  216663. NSDictionary* error = 0;
  216664. const bool ok = [s executeAndReturnError: &error] != nil;
  216665. [s release];
  216666. return ok;
  216667. }
  216668. END_JUCE_NAMESPACE
  216669. /********* End of inlined file: juce_mac_Network.mm *********/
  216670. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  216671. /********* Start of inlined file: juce_mac_AudioCDBurner.mm *********/
  216672. #if JUCE_USE_CDBURNER
  216673. #import <DiscRecording/DiscRecording.h>
  216674. BEGIN_JUCE_NAMESPACE
  216675. END_JUCE_NAMESPACE
  216676. @interface OpenDiskDevice : NSObject
  216677. {
  216678. DRDevice* device;
  216679. NSMutableArray* tracks;
  216680. }
  216681. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device;
  216682. - (void) dealloc;
  216683. - (bool) isDiskPresent;
  216684. - (int) getNumAvailableAudioBlocks;
  216685. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  216686. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  216687. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting;
  216688. @end
  216689. @interface AudioTrackProducer : NSObject
  216690. {
  216691. JUCE_NAMESPACE::AudioSource* source;
  216692. int readPosition, lengthInFrames;
  216693. }
  216694. - (AudioTrackProducer*) init: (int) lengthInFrames;
  216695. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  216696. - (void) dealloc;
  216697. - (void) setupTrackProperties: (DRTrack*) track;
  216698. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  216699. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  216700. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  216701. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  216702. toMedia:(NSDictionary*)mediaInfo;
  216703. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  216704. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  216705. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  216706. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  216707. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  216708. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  216709. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  216710. ioFlags:(uint32_t*)flags;
  216711. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  216712. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  216713. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  216714. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  216715. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  216716. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  216717. ioFlags:(uint32_t*)flags;
  216718. @end
  216719. @implementation OpenDiskDevice
  216720. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device_
  216721. {
  216722. [super init];
  216723. device = device_;
  216724. tracks = [[NSMutableArray alloc] init];
  216725. return self;
  216726. }
  216727. - (void) dealloc
  216728. {
  216729. [tracks release];
  216730. [super dealloc];
  216731. }
  216732. - (bool) isDiskPresent
  216733. {
  216734. return [device isValid]
  216735. && [[[device status] objectForKey: DRDeviceMediaStateKey]
  216736. isEqualTo: DRDeviceMediaStateMediaPresent];
  216737. }
  216738. - (int) getNumAvailableAudioBlocks
  216739. {
  216740. return [[[[device status] objectForKey: DRDeviceMediaInfoKey]
  216741. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  216742. }
  216743. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  216744. {
  216745. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  216746. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  216747. [p setupTrackProperties: t];
  216748. [tracks addObject: t];
  216749. [t release];
  216750. [p release];
  216751. }
  216752. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  216753. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting
  216754. {
  216755. DRBurn* burn = [DRBurn burnForDevice: device];
  216756. if (! [device acquireExclusiveAccess])
  216757. {
  216758. *error = "Couldn't open or write to the CD device";
  216759. return;
  216760. }
  216761. [device acquireMediaReservation];
  216762. NSMutableDictionary* d = [[burn properties] mutableCopy];
  216763. [d autorelease];
  216764. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  216765. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  216766. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount)
  216767. forKey: DRBurnCompletionActionKey];
  216768. [burn setProperties: d];
  216769. [burn writeLayout: tracks];
  216770. for (;;)
  216771. {
  216772. JUCE_NAMESPACE::Thread::sleep (300);
  216773. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  216774. NSLog ([[burn status] description]);
  216775. if (listener != 0 && listener->audioCDBurnProgress (progress))
  216776. {
  216777. [burn abort];
  216778. *error = "User cancelled the write operation";
  216779. break;
  216780. }
  216781. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  216782. {
  216783. *error = "Write operation failed";
  216784. break;
  216785. }
  216786. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  216787. {
  216788. break;
  216789. }
  216790. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  216791. objectForKey: DRErrorStatusErrorStringKey];
  216792. if ([err length] > 0)
  216793. {
  216794. *error = JUCE_NAMESPACE::String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [err UTF8String]);
  216795. break;
  216796. }
  216797. }
  216798. [device releaseMediaReservation];
  216799. [device releaseExclusiveAccess];
  216800. }
  216801. @end
  216802. @implementation AudioTrackProducer
  216803. - (AudioTrackProducer*) init: (int) lengthInFrames_
  216804. {
  216805. lengthInFrames = lengthInFrames_;
  216806. readPosition = 0;
  216807. return self;
  216808. }
  216809. - (void) setupTrackProperties: (DRTrack*) track
  216810. {
  216811. NSMutableDictionary* p = [[track properties] mutableCopy];
  216812. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  216813. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  216814. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  216815. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  216816. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  216817. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  216818. [track setProperties: p];
  216819. [p release];
  216820. }
  216821. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  216822. {
  216823. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  216824. if (s != nil)
  216825. s->source = source_;
  216826. return s;
  216827. }
  216828. - (void) dealloc
  216829. {
  216830. if (source != 0)
  216831. {
  216832. source->releaseResources();
  216833. delete source;
  216834. }
  216835. [super dealloc];
  216836. }
  216837. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  216838. {
  216839. }
  216840. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track
  216841. {
  216842. return true;
  216843. }
  216844. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track
  216845. {
  216846. return lengthInFrames;
  216847. }
  216848. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  216849. toMedia:(NSDictionary*)mediaInfo
  216850. {
  216851. if (source != 0)
  216852. source->prepareToPlay (44100 / 75, 44100);
  216853. readPosition = 0;
  216854. return true;
  216855. }
  216856. - (BOOL) prepareTrackForVerification:(DRTrack*)track
  216857. {
  216858. if (source != 0)
  216859. source->prepareToPlay (44100 / 75, 44100);
  216860. return true;
  216861. }
  216862. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  216863. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  216864. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags
  216865. {
  216866. if (source != 0)
  216867. {
  216868. const int numSamples = JUCE_NAMESPACE::jmin (bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  216869. if (numSamples > 0)
  216870. {
  216871. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  216872. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  216873. info.buffer = &tempBuffer;
  216874. info.startSample = 0;
  216875. info.numSamples = numSamples;
  216876. source->getNextAudioBlock (info);
  216877. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  216878. buffer, numSamples, 4);
  216879. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  216880. buffer + 2, numSamples, 4);
  216881. readPosition += numSamples;
  216882. }
  216883. return numSamples * 4;
  216884. }
  216885. return 0;
  216886. }
  216887. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  216888. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  216889. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  216890. ioFlags:(uint32_t*)flags
  216891. {
  216892. zeromem (buffer, bufferLength);
  216893. return bufferLength;
  216894. }
  216895. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  216896. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  216897. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags
  216898. {
  216899. return true;
  216900. }
  216901. @end
  216902. BEGIN_JUCE_NAMESPACE
  216903. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  216904. : internal (0)
  216905. {
  216906. const AutoPool pool;
  216907. OpenDiskDevice* dev = [[OpenDiskDevice alloc] initWithDevice: [[DRDevice devices] objectAtIndex: deviceIndex]];
  216908. internal = (void*) dev;
  216909. }
  216910. AudioCDBurner::~AudioCDBurner()
  216911. {
  216912. const AutoPool pool;
  216913. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216914. if (dev != 0)
  216915. [dev release];
  216916. }
  216917. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  216918. {
  216919. const AutoPool pool;
  216920. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  216921. if (b->internal == 0)
  216922. deleteAndZero (b);
  216923. return b;
  216924. }
  216925. static NSArray* findDiskBurnerDevices()
  216926. {
  216927. NSMutableArray* results = [NSMutableArray array];
  216928. NSArray* devs = [DRDevice devices];
  216929. if (devs != 0)
  216930. {
  216931. int num = [devs count];
  216932. int i;
  216933. for (i = 0; i < num; ++i)
  216934. {
  216935. NSDictionary* dic = [[devs objectAtIndex: i] info];
  216936. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  216937. if (name != nil)
  216938. [results addObject: name];
  216939. }
  216940. }
  216941. return results;
  216942. }
  216943. const StringArray AudioCDBurner::findAvailableDevices()
  216944. {
  216945. const AutoPool pool;
  216946. NSArray* names = findDiskBurnerDevices();
  216947. StringArray s;
  216948. for (int i = 0; i < [names count]; ++i)
  216949. s.add (String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [[names objectAtIndex: i] UTF8String]));
  216950. return s;
  216951. }
  216952. bool AudioCDBurner::isDiskPresent() const
  216953. {
  216954. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216955. return dev != 0 && [dev isDiskPresent];
  216956. }
  216957. int AudioCDBurner::getNumAvailableAudioBlocks() const
  216958. {
  216959. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216960. return [dev getNumAvailableAudioBlocks];
  216961. }
  216962. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  216963. {
  216964. const AutoPool pool;
  216965. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216966. if (dev != 0)
  216967. {
  216968. [dev addSourceTrack: source numSamples: numSamps];
  216969. return true;
  216970. }
  216971. return false;
  216972. }
  216973. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  216974. const bool ejectDiscAfterwards,
  216975. const bool peformFakeBurnForTesting)
  216976. {
  216977. const AutoPool pool;
  216978. JUCE_NAMESPACE::String error ("Couldn't open or write to the CD device");
  216979. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216980. if (dev != 0)
  216981. {
  216982. error = JUCE_NAMESPACE::String::empty;
  216983. [dev burn: listener
  216984. errorString: &error
  216985. ejectAfterwards: ejectDiscAfterwards
  216986. isFake: peformFakeBurnForTesting];
  216987. }
  216988. return error;
  216989. }
  216990. END_JUCE_NAMESPACE
  216991. #endif
  216992. /********* End of inlined file: juce_mac_AudioCDBurner.mm *********/
  216993. /********* Start of inlined file: juce_mac_CoreAudio.cpp *********/
  216994. #include <CoreAudio/AudioHardware.h>
  216995. BEGIN_JUCE_NAMESPACE
  216996. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  216997. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  216998. #endif
  216999. #undef log
  217000. #if JUCE_COREAUDIO_LOGGING_ENABLED
  217001. #define log(a) Logger::writeToLog (a)
  217002. #else
  217003. #define log(a)
  217004. #endif
  217005. #undef OK
  217006. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  217007. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  217008. {
  217009. if (err == noErr)
  217010. return true;
  217011. Logger::writeToLog (T("CoreAudio error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  217012. jassertfalse
  217013. return false;
  217014. }
  217015. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  217016. #else
  217017. #define OK(a) (a == noErr)
  217018. #endif
  217019. static const int maxNumChans = 96;
  217020. class CoreAudioInternal : public Timer
  217021. {
  217022. public:
  217023. CoreAudioInternal (AudioDeviceID id)
  217024. : deviceID (id),
  217025. started (false),
  217026. audioBuffer (0),
  217027. numInputChans (0),
  217028. numOutputChans (0),
  217029. callbacksAllowed (true),
  217030. numInputChannelInfos (0),
  217031. numOutputChannelInfos (0),
  217032. inputLatency (0),
  217033. outputLatency (0),
  217034. callback (0),
  217035. inputDevice (0),
  217036. isSlaveDevice (false)
  217037. {
  217038. sampleRate = 0;
  217039. bufferSize = 512;
  217040. if (deviceID == 0)
  217041. {
  217042. error = TRANS("can't open device");
  217043. }
  217044. else
  217045. {
  217046. updateDetailsFromDevice();
  217047. AudioDeviceAddPropertyListener (deviceID,
  217048. kAudioPropertyWildcardChannel,
  217049. kAudioPropertyWildcardSection,
  217050. kAudioPropertyWildcardPropertyID,
  217051. deviceListenerProc, this);
  217052. }
  217053. }
  217054. ~CoreAudioInternal()
  217055. {
  217056. AudioDeviceRemovePropertyListener (deviceID,
  217057. kAudioPropertyWildcardChannel,
  217058. kAudioPropertyWildcardSection,
  217059. kAudioPropertyWildcardPropertyID,
  217060. deviceListenerProc);
  217061. stop (false);
  217062. juce_free (audioBuffer);
  217063. delete inputDevice;
  217064. }
  217065. void setTempBufferSize (const int numChannels, const int numSamples)
  217066. {
  217067. juce_free (audioBuffer);
  217068. audioBuffer = (float*) juce_calloc (32 + numChannels * numSamples * sizeof (float));
  217069. zeromem (tempInputBuffers, sizeof (tempInputBuffers));
  217070. zeromem (tempOutputBuffers, sizeof (tempOutputBuffers));
  217071. int count = 0;
  217072. int i;
  217073. for (i = 0; i < numInputChans; ++i)
  217074. tempInputBuffers[i] = audioBuffer + count++ * numSamples;
  217075. for (i = 0; i < numOutputChans; ++i)
  217076. tempOutputBuffers[i] = audioBuffer + count++ * numSamples;
  217077. }
  217078. // returns the number of actual available channels
  217079. void fillInChannelInfo (bool input)
  217080. {
  217081. int chanNum = 0, activeChans = 0;
  217082. UInt32 size;
  217083. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, 0)))
  217084. {
  217085. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  217086. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, bufList)))
  217087. {
  217088. const int numStreams = bufList->mNumberBuffers;
  217089. for (int i = 0; i < numStreams; ++i)
  217090. {
  217091. const AudioBuffer& b = bufList->mBuffers[i];
  217092. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  217093. {
  217094. if (input)
  217095. {
  217096. if (activeInputChans[chanNum])
  217097. {
  217098. inputChannelInfo [activeChans].sourceChannelNum = chanNum;
  217099. inputChannelInfo [activeChans].streamNum = i;
  217100. inputChannelInfo [activeChans].dataOffsetSamples = j;
  217101. inputChannelInfo [activeChans].dataStrideSamples = b.mNumberChannels;
  217102. ++activeChans;
  217103. numInputChannelInfos = activeChans;
  217104. }
  217105. inChanNames.add (T("input ") + String (chanNum + 1));
  217106. }
  217107. else
  217108. {
  217109. if (activeOutputChans[chanNum])
  217110. {
  217111. outputChannelInfo [activeChans].sourceChannelNum = chanNum;
  217112. outputChannelInfo [activeChans].streamNum = i;
  217113. outputChannelInfo [activeChans].dataOffsetSamples = j;
  217114. outputChannelInfo [activeChans].dataStrideSamples = b.mNumberChannels;
  217115. ++activeChans;
  217116. numOutputChannelInfos = activeChans;
  217117. }
  217118. outChanNames.add (T("output ") + String (chanNum + 1));
  217119. }
  217120. ++chanNum;
  217121. }
  217122. }
  217123. }
  217124. juce_free (bufList);
  217125. }
  217126. }
  217127. void updateDetailsFromDevice()
  217128. {
  217129. stopTimer();
  217130. if (deviceID == 0)
  217131. return;
  217132. const ScopedLock sl (callbackLock);
  217133. Float64 sr;
  217134. UInt32 size = sizeof (Float64);
  217135. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyNominalSampleRate, &size, &sr)))
  217136. sampleRate = sr;
  217137. UInt32 framesPerBuf;
  217138. size = sizeof (framesPerBuf);
  217139. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSize, &size, &framesPerBuf)))
  217140. {
  217141. bufferSize = framesPerBuf;
  217142. if (bufferSize > 0)
  217143. setTempBufferSize (numInputChans + numOutputChans, bufferSize);
  217144. }
  217145. bufferSizes.clear();
  217146. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, 0)))
  217147. {
  217148. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  217149. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, ranges)))
  217150. {
  217151. bufferSizes.add ((int) ranges[0].mMinimum);
  217152. for (int i = 32; i < 8192; i += 32)
  217153. {
  217154. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  217155. {
  217156. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  217157. {
  217158. bufferSizes.addIfNotAlreadyThere (i);
  217159. break;
  217160. }
  217161. }
  217162. }
  217163. if (bufferSize > 0)
  217164. bufferSizes.addIfNotAlreadyThere (bufferSize);
  217165. }
  217166. juce_free (ranges);
  217167. }
  217168. if (bufferSizes.size() == 0 && bufferSize > 0)
  217169. bufferSizes.add (bufferSize);
  217170. sampleRates.clear();
  217171. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  217172. String rates;
  217173. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, 0)))
  217174. {
  217175. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  217176. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, ranges)))
  217177. {
  217178. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  217179. {
  217180. bool ok = false;
  217181. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  217182. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  217183. ok = true;
  217184. if (ok)
  217185. {
  217186. sampleRates.add (possibleRates[i]);
  217187. rates << possibleRates[i] << T(" ");
  217188. }
  217189. }
  217190. }
  217191. juce_free (ranges);
  217192. }
  217193. if (sampleRates.size() == 0 && sampleRate > 0)
  217194. {
  217195. sampleRates.add (sampleRate);
  217196. rates << sampleRate;
  217197. }
  217198. log (T("sr: ") + rates);
  217199. inputLatency = 0;
  217200. outputLatency = 0;
  217201. UInt32 lat;
  217202. size = sizeof (UInt32);
  217203. if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  217204. inputLatency = (int) lat;
  217205. if (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  217206. outputLatency = (int) lat;
  217207. log (T("lat: ") + String (inputLatency) + T(" ") + String (outputLatency));
  217208. inChanNames.clear();
  217209. outChanNames.clear();
  217210. zeromem (inputChannelInfo, sizeof (inputChannelInfo));
  217211. zeromem (outputChannelInfo, sizeof (outputChannelInfo));
  217212. fillInChannelInfo (true);
  217213. fillInChannelInfo (false);
  217214. }
  217215. const StringArray getSources (bool input)
  217216. {
  217217. StringArray s;
  217218. int num = 0;
  217219. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  217220. if (types != 0)
  217221. {
  217222. for (int i = 0; i < num; ++i)
  217223. {
  217224. AudioValueTranslation avt;
  217225. char buffer[256];
  217226. avt.mInputData = (void*) &(types[i]);
  217227. avt.mInputDataSize = sizeof (UInt32);
  217228. avt.mOutputData = buffer;
  217229. avt.mOutputDataSize = 256;
  217230. UInt32 transSize = sizeof (avt);
  217231. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSourceNameForID, &transSize, &avt)))
  217232. {
  217233. DBG (buffer);
  217234. s.add (buffer);
  217235. }
  217236. }
  217237. juce_free (types);
  217238. }
  217239. return s;
  217240. }
  217241. int getCurrentSourceIndex (bool input) const
  217242. {
  217243. OSType currentSourceID = 0;
  217244. UInt32 size = 0;
  217245. int result = -1;
  217246. if (deviceID != 0
  217247. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, 0)))
  217248. {
  217249. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, &currentSourceID)))
  217250. {
  217251. int num = 0;
  217252. OSType* const types = getAllDataSourcesForDevice (deviceID, input, num);
  217253. if (types != 0)
  217254. {
  217255. for (int i = 0; i < num; ++i)
  217256. {
  217257. if (types[num] == currentSourceID)
  217258. {
  217259. result = i;
  217260. break;
  217261. }
  217262. }
  217263. juce_free (types);
  217264. }
  217265. }
  217266. }
  217267. return result;
  217268. }
  217269. void setCurrentSourceIndex (int index, bool input)
  217270. {
  217271. if (deviceID != 0)
  217272. {
  217273. int num = 0;
  217274. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  217275. if (types != 0)
  217276. {
  217277. if (((unsigned int) index) < num)
  217278. {
  217279. OSType typeId = types[index];
  217280. AudioDeviceSetProperty (deviceID, 0, 0, input, kAudioDevicePropertyDataSource, sizeof (typeId), &typeId);
  217281. }
  217282. juce_free (types);
  217283. }
  217284. }
  217285. }
  217286. const String reopen (const BitArray& inputChannels,
  217287. const BitArray& outputChannels,
  217288. double newSampleRate,
  217289. int bufferSizeSamples)
  217290. {
  217291. error = String::empty;
  217292. log ("CoreAudio reopen");
  217293. callbacksAllowed = false;
  217294. stopTimer();
  217295. stop (false);
  217296. activeInputChans = inputChannels;
  217297. activeOutputChans = outputChannels;
  217298. activeInputChans.setRange (inChanNames.size(),
  217299. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  217300. false);
  217301. activeOutputChans.setRange (outChanNames.size(),
  217302. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  217303. false);
  217304. numInputChans = activeInputChans.countNumberOfSetBits();
  217305. numOutputChans = activeOutputChans.countNumberOfSetBits();
  217306. // set sample rate
  217307. Float64 sr = newSampleRate;
  217308. UInt32 size = sizeof (sr);
  217309. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyNominalSampleRate, size, &sr));
  217310. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyNominalSampleRate, size, &sr));
  217311. // change buffer size
  217312. UInt32 framesPerBuf = bufferSizeSamples;
  217313. size = sizeof (framesPerBuf);
  217314. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  217315. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  217316. // wait for the changes to happen (on some devices)
  217317. int i = 30;
  217318. while (--i >= 0)
  217319. {
  217320. updateDetailsFromDevice();
  217321. if (sampleRate == newSampleRate && bufferSizeSamples == bufferSize)
  217322. break;
  217323. Thread::sleep (100);
  217324. }
  217325. if (i < 0)
  217326. error = "Couldn't change sample rate/buffer size";
  217327. if (sampleRates.size() == 0)
  217328. error = "Device has no available sample-rates";
  217329. if (bufferSizes.size() == 0)
  217330. error = "Device has no available buffer-sizes";
  217331. if (inputDevice != 0 && error.isEmpty())
  217332. error = inputDevice->reopen (inputChannels,
  217333. outputChannels,
  217334. newSampleRate,
  217335. bufferSizeSamples);
  217336. callbacksAllowed = true;
  217337. return error;
  217338. }
  217339. bool start (AudioIODeviceCallback* cb)
  217340. {
  217341. if (! started)
  217342. {
  217343. callback = 0;
  217344. if (deviceID != 0)
  217345. {
  217346. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, (void*) this)))
  217347. {
  217348. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  217349. {
  217350. started = true;
  217351. }
  217352. else
  217353. {
  217354. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  217355. }
  217356. }
  217357. }
  217358. }
  217359. if (started)
  217360. {
  217361. const ScopedLock sl (callbackLock);
  217362. callback = cb;
  217363. }
  217364. if (inputDevice != 0)
  217365. return started && inputDevice->start (cb);
  217366. else
  217367. return started;
  217368. }
  217369. void stop (bool leaveInterruptRunning)
  217370. {
  217371. callbackLock.enter();
  217372. callback = 0;
  217373. callbackLock.exit();
  217374. if (started
  217375. && (deviceID != 0)
  217376. && ! leaveInterruptRunning)
  217377. {
  217378. OK (AudioDeviceStop (deviceID, audioIOProc));
  217379. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  217380. started = false;
  217381. callbackLock.enter();
  217382. callbackLock.exit();
  217383. // wait until it's definately stopped calling back..
  217384. for (int i = 40; --i >= 0;)
  217385. {
  217386. Thread::sleep (50);
  217387. UInt32 running = 0;
  217388. UInt32 size = sizeof (running);
  217389. OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyDeviceIsRunning, &size, &running));
  217390. if (running == 0)
  217391. break;
  217392. }
  217393. callbackLock.enter();
  217394. callbackLock.exit();
  217395. }
  217396. if (inputDevice != 0)
  217397. inputDevice->stop (leaveInterruptRunning);
  217398. }
  217399. double getSampleRate() const
  217400. {
  217401. return sampleRate;
  217402. }
  217403. int getBufferSize() const
  217404. {
  217405. return bufferSize;
  217406. }
  217407. void audioCallback (const AudioBufferList* inInputData,
  217408. AudioBufferList* outOutputData)
  217409. {
  217410. int i;
  217411. const ScopedLock sl (callbackLock);
  217412. if (callback != 0)
  217413. {
  217414. if (inputDevice == 0)
  217415. {
  217416. for (i = numInputChans; --i >= 0;)
  217417. {
  217418. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  217419. float* dest = tempInputBuffers [info.sourceChannelNum];
  217420. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  217421. + info.dataOffsetSamples;
  217422. const int stride = info.dataStrideSamples;
  217423. if (stride != 0) // if this is zero, info is invalid
  217424. {
  217425. for (int j = bufferSize; --j >= 0;)
  217426. {
  217427. *dest++ = *src;
  217428. src += stride;
  217429. }
  217430. }
  217431. }
  217432. }
  217433. if (! isSlaveDevice)
  217434. {
  217435. if (inputDevice == 0)
  217436. {
  217437. callback->audioDeviceIOCallback ((const float**) tempInputBuffers,
  217438. numInputChans,
  217439. tempOutputBuffers,
  217440. numOutputChans,
  217441. bufferSize);
  217442. }
  217443. else
  217444. {
  217445. jassert (inputDevice->bufferSize == bufferSize);
  217446. callback->audioDeviceIOCallback ((const float**) inputDevice->tempInputBuffers,
  217447. inputDevice->numInputChans,
  217448. tempOutputBuffers,
  217449. numOutputChans,
  217450. bufferSize);
  217451. }
  217452. for (i = numOutputChans; --i >= 0;)
  217453. {
  217454. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  217455. const float* src = tempOutputBuffers [i];
  217456. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  217457. + info.dataOffsetSamples;
  217458. const int stride = info.dataStrideSamples;
  217459. if (stride != 0) // if this is zero, info is invalid
  217460. {
  217461. for (int j = bufferSize; --j >= 0;)
  217462. {
  217463. *dest = *src++;
  217464. dest += stride;
  217465. }
  217466. }
  217467. }
  217468. }
  217469. }
  217470. else
  217471. {
  217472. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  217473. {
  217474. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  217475. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  217476. + info.dataOffsetSamples;
  217477. const int stride = info.dataStrideSamples;
  217478. if (stride != 0) // if this is zero, info is invalid
  217479. {
  217480. for (int j = bufferSize; --j >= 0;)
  217481. {
  217482. *dest = 0.0f;
  217483. dest += stride;
  217484. }
  217485. }
  217486. }
  217487. }
  217488. }
  217489. // called by callbacks
  217490. void deviceDetailsChanged()
  217491. {
  217492. if (callbacksAllowed)
  217493. startTimer (100);
  217494. }
  217495. void timerCallback()
  217496. {
  217497. stopTimer();
  217498. log ("CoreAudio device changed callback");
  217499. const double oldSampleRate = sampleRate;
  217500. const int oldBufferSize = bufferSize;
  217501. updateDetailsFromDevice();
  217502. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  217503. {
  217504. callbacksAllowed = false;
  217505. stop (false);
  217506. updateDetailsFromDevice();
  217507. callbacksAllowed = true;
  217508. }
  217509. }
  217510. CoreAudioInternal* getRelatedDevice() const
  217511. {
  217512. UInt32 size = 0;
  217513. CoreAudioInternal* result = 0;
  217514. if (deviceID != 0
  217515. && AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, 0) == noErr
  217516. && size > 0)
  217517. {
  217518. AudioDeviceID* devs = (AudioDeviceID*) juce_calloc (size);
  217519. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, devs)))
  217520. {
  217521. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  217522. {
  217523. if (devs[i] != deviceID && devs[i] != 0)
  217524. {
  217525. result = new CoreAudioInternal (devs[i]);
  217526. if (result->error.isEmpty())
  217527. {
  217528. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  217529. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  217530. if (thisIsInput != otherIsInput
  217531. || (inChanNames.size() + outChanNames.size() == 0)
  217532. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  217533. break;
  217534. }
  217535. deleteAndZero (result);
  217536. }
  217537. }
  217538. }
  217539. juce_free (devs);
  217540. }
  217541. return result;
  217542. }
  217543. juce_UseDebuggingNewOperator
  217544. String error;
  217545. int inputLatency, outputLatency;
  217546. BitArray activeInputChans, activeOutputChans;
  217547. StringArray inChanNames, outChanNames;
  217548. Array <double> sampleRates;
  217549. Array <int> bufferSizes;
  217550. AudioIODeviceCallback* callback;
  217551. CoreAudioInternal* inputDevice;
  217552. bool isSlaveDevice;
  217553. private:
  217554. CriticalSection callbackLock;
  217555. AudioDeviceID deviceID;
  217556. bool started;
  217557. double sampleRate;
  217558. int bufferSize;
  217559. float* audioBuffer;
  217560. int numInputChans, numOutputChans;
  217561. bool callbacksAllowed;
  217562. struct CallbackDetailsForChannel
  217563. {
  217564. int sourceChannelNum;
  217565. int streamNum;
  217566. int dataOffsetSamples;
  217567. int dataStrideSamples;
  217568. };
  217569. int numInputChannelInfos, numOutputChannelInfos;
  217570. CallbackDetailsForChannel inputChannelInfo [maxNumChans];
  217571. CallbackDetailsForChannel outputChannelInfo [maxNumChans];
  217572. float* tempInputBuffers [maxNumChans];
  217573. float* tempOutputBuffers [maxNumChans];
  217574. CoreAudioInternal (const CoreAudioInternal&);
  217575. const CoreAudioInternal& operator= (const CoreAudioInternal&);
  217576. static OSStatus audioIOProc (AudioDeviceID inDevice,
  217577. const AudioTimeStamp* inNow,
  217578. const AudioBufferList* inInputData,
  217579. const AudioTimeStamp* inInputTime,
  217580. AudioBufferList* outOutputData,
  217581. const AudioTimeStamp* inOutputTime,
  217582. void* device)
  217583. {
  217584. ((CoreAudioInternal*) device)->audioCallback (inInputData, outOutputData);
  217585. return noErr;
  217586. }
  217587. static OSStatus deviceListenerProc (AudioDeviceID inDevice,
  217588. UInt32 inLine,
  217589. Boolean isInput,
  217590. AudioDevicePropertyID inPropertyID,
  217591. void* inClientData)
  217592. {
  217593. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  217594. switch (inPropertyID)
  217595. {
  217596. case kAudioDevicePropertyBufferSize:
  217597. case kAudioDevicePropertyBufferFrameSize:
  217598. case kAudioDevicePropertyNominalSampleRate:
  217599. case kAudioDevicePropertyStreamFormat:
  217600. case kAudioDevicePropertyDeviceIsAlive:
  217601. intern->deviceDetailsChanged();
  217602. break;
  217603. case kAudioDevicePropertyBufferSizeRange:
  217604. case kAudioDevicePropertyVolumeScalar:
  217605. case kAudioDevicePropertyMute:
  217606. case kAudioDevicePropertyPlayThru:
  217607. case kAudioDevicePropertyDataSource:
  217608. case kAudioDevicePropertyDeviceIsRunning:
  217609. break;
  217610. }
  217611. return noErr;
  217612. }
  217613. static OSType* getAllDataSourcesForDevice (AudioDeviceID deviceID, const bool input, int& num)
  217614. {
  217615. OSType* types = 0;
  217616. UInt32 size = 0;
  217617. num = 0;
  217618. if (deviceID != 0
  217619. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, 0)))
  217620. {
  217621. types = (OSType*) juce_calloc (size);
  217622. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, types)))
  217623. {
  217624. num = size / sizeof (OSType);
  217625. }
  217626. else
  217627. {
  217628. juce_free (types);
  217629. types = 0;
  217630. }
  217631. }
  217632. return types;
  217633. }
  217634. };
  217635. class CoreAudioIODevice : public AudioIODevice
  217636. {
  217637. public:
  217638. CoreAudioIODevice (const String& deviceName,
  217639. AudioDeviceID inputDeviceId,
  217640. const int inputIndex_,
  217641. AudioDeviceID outputDeviceId,
  217642. const int outputIndex_)
  217643. : AudioIODevice (deviceName, "CoreAudio"),
  217644. inputIndex (inputIndex_),
  217645. outputIndex (outputIndex_),
  217646. isOpen_ (false),
  217647. isStarted (false)
  217648. {
  217649. internal = 0;
  217650. CoreAudioInternal* device = 0;
  217651. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  217652. {
  217653. jassert (inputDeviceId != 0);
  217654. device = new CoreAudioInternal (inputDeviceId);
  217655. lastError = device->error;
  217656. if (lastError.isNotEmpty())
  217657. deleteAndZero (device);
  217658. }
  217659. else
  217660. {
  217661. device = new CoreAudioInternal (outputDeviceId);
  217662. lastError = device->error;
  217663. if (lastError.isNotEmpty())
  217664. {
  217665. deleteAndZero (device);
  217666. }
  217667. else if (inputDeviceId != 0)
  217668. {
  217669. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  217670. lastError = device->error;
  217671. if (lastError.isNotEmpty())
  217672. {
  217673. delete secondDevice;
  217674. }
  217675. else
  217676. {
  217677. device->inputDevice = secondDevice;
  217678. secondDevice->isSlaveDevice = true;
  217679. }
  217680. }
  217681. }
  217682. internal = device;
  217683. AudioHardwareAddPropertyListener (kAudioPropertyWildcardPropertyID,
  217684. hardwareListenerProc, internal);
  217685. }
  217686. ~CoreAudioIODevice()
  217687. {
  217688. AudioHardwareRemovePropertyListener (kAudioPropertyWildcardPropertyID,
  217689. hardwareListenerProc);
  217690. delete internal;
  217691. }
  217692. const StringArray getOutputChannelNames()
  217693. {
  217694. return internal->outChanNames;
  217695. }
  217696. const StringArray getInputChannelNames()
  217697. {
  217698. if (internal->inputDevice != 0)
  217699. return internal->inputDevice->inChanNames;
  217700. else
  217701. return internal->inChanNames;
  217702. }
  217703. int getNumSampleRates()
  217704. {
  217705. return internal->sampleRates.size();
  217706. }
  217707. double getSampleRate (int index)
  217708. {
  217709. return internal->sampleRates [index];
  217710. }
  217711. int getNumBufferSizesAvailable()
  217712. {
  217713. return internal->bufferSizes.size();
  217714. }
  217715. int getBufferSizeSamples (int index)
  217716. {
  217717. return internal->bufferSizes [index];
  217718. }
  217719. int getDefaultBufferSize()
  217720. {
  217721. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  217722. if (getBufferSizeSamples(i) >= 512)
  217723. return getBufferSizeSamples(i);
  217724. return 512;
  217725. }
  217726. const String open (const BitArray& inputChannels,
  217727. const BitArray& outputChannels,
  217728. double sampleRate,
  217729. int bufferSizeSamples)
  217730. {
  217731. isOpen_ = true;
  217732. if (bufferSizeSamples <= 0)
  217733. bufferSizeSamples = getDefaultBufferSize();
  217734. internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  217735. lastError = internal->error;
  217736. return lastError;
  217737. }
  217738. void close()
  217739. {
  217740. isOpen_ = false;
  217741. }
  217742. bool isOpen()
  217743. {
  217744. return isOpen_;
  217745. }
  217746. int getCurrentBufferSizeSamples()
  217747. {
  217748. return internal != 0 ? internal->getBufferSize() : 512;
  217749. }
  217750. double getCurrentSampleRate()
  217751. {
  217752. return internal != 0 ? internal->getSampleRate() : 0;
  217753. }
  217754. int getCurrentBitDepth()
  217755. {
  217756. return 32; // no way to find out, so just assume it's high..
  217757. }
  217758. const BitArray getActiveOutputChannels() const
  217759. {
  217760. return internal != 0 ? internal->activeOutputChans : BitArray();
  217761. }
  217762. const BitArray getActiveInputChannels() const
  217763. {
  217764. BitArray chans;
  217765. if (internal != 0)
  217766. {
  217767. chans = internal->activeInputChans;
  217768. if (internal->inputDevice != 0)
  217769. chans.orWith (internal->inputDevice->activeInputChans);
  217770. }
  217771. return chans;
  217772. }
  217773. int getOutputLatencyInSamples()
  217774. {
  217775. if (internal == 0)
  217776. return 0;
  217777. // this seems like a good guess at getting the latency right - comparing
  217778. // this with a round-trip measurement, it gets it to within a few millisecs
  217779. // for the built-in mac soundcard
  217780. return internal->outputLatency + internal->getBufferSize() * 2;
  217781. }
  217782. int getInputLatencyInSamples()
  217783. {
  217784. if (internal == 0)
  217785. return 0;
  217786. return internal->inputLatency + internal->getBufferSize() * 2;
  217787. }
  217788. void start (AudioIODeviceCallback* callback)
  217789. {
  217790. if (internal != 0 && ! isStarted)
  217791. {
  217792. if (callback != 0)
  217793. callback->audioDeviceAboutToStart (this);
  217794. isStarted = true;
  217795. internal->start (callback);
  217796. }
  217797. }
  217798. void stop()
  217799. {
  217800. if (isStarted && internal != 0)
  217801. {
  217802. AudioIODeviceCallback* const lastCallback = internal->callback;
  217803. isStarted = false;
  217804. internal->stop (true);
  217805. if (lastCallback != 0)
  217806. lastCallback->audioDeviceStopped();
  217807. }
  217808. }
  217809. bool isPlaying()
  217810. {
  217811. if (internal->callback == 0)
  217812. isStarted = false;
  217813. return isStarted;
  217814. }
  217815. const String getLastError()
  217816. {
  217817. return lastError;
  217818. }
  217819. int inputIndex, outputIndex;
  217820. juce_UseDebuggingNewOperator
  217821. private:
  217822. CoreAudioInternal* internal;
  217823. bool isOpen_, isStarted;
  217824. String lastError;
  217825. static OSStatus hardwareListenerProc (AudioHardwarePropertyID inPropertyID, void* inClientData)
  217826. {
  217827. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  217828. switch (inPropertyID)
  217829. {
  217830. case kAudioHardwarePropertyDevices:
  217831. intern->deviceDetailsChanged();
  217832. break;
  217833. case kAudioHardwarePropertyDefaultOutputDevice:
  217834. case kAudioHardwarePropertyDefaultInputDevice:
  217835. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  217836. break;
  217837. }
  217838. return noErr;
  217839. }
  217840. CoreAudioIODevice (const CoreAudioIODevice&);
  217841. const CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  217842. };
  217843. class CoreAudioIODeviceType : public AudioIODeviceType
  217844. {
  217845. public:
  217846. CoreAudioIODeviceType()
  217847. : AudioIODeviceType (T("CoreAudio")),
  217848. hasScanned (false)
  217849. {
  217850. }
  217851. ~CoreAudioIODeviceType()
  217852. {
  217853. }
  217854. void scanForDevices()
  217855. {
  217856. hasScanned = true;
  217857. inputDeviceNames.clear();
  217858. outputDeviceNames.clear();
  217859. inputIds.clear();
  217860. outputIds.clear();
  217861. UInt32 size;
  217862. if (OK (AudioHardwareGetPropertyInfo (kAudioHardwarePropertyDevices, &size, 0)))
  217863. {
  217864. AudioDeviceID* const devs = (AudioDeviceID*) juce_calloc (size);
  217865. if (OK (AudioHardwareGetProperty (kAudioHardwarePropertyDevices, &size, devs)))
  217866. {
  217867. static bool alreadyLogged = false;
  217868. const int num = size / sizeof (AudioDeviceID);
  217869. for (int i = 0; i < num; ++i)
  217870. {
  217871. char name[1024];
  217872. size = sizeof (name);
  217873. if (OK (AudioDeviceGetProperty (devs[i], 0, false, kAudioDevicePropertyDeviceName, &size, name)))
  217874. {
  217875. const String nameString (String::fromUTF8 ((const uint8*) name, strlen (name)));
  217876. if (! alreadyLogged)
  217877. log (T("CoreAudio device: ") + nameString);
  217878. const int numIns = getNumChannels (devs[i], true);
  217879. const int numOuts = getNumChannels (devs[i], false);
  217880. if (numIns > 0)
  217881. {
  217882. inputDeviceNames.add (nameString);
  217883. inputIds.add (devs[i]);
  217884. }
  217885. if (numOuts > 0)
  217886. {
  217887. outputDeviceNames.add (nameString);
  217888. outputIds.add (devs[i]);
  217889. }
  217890. }
  217891. }
  217892. alreadyLogged = true;
  217893. }
  217894. juce_free (devs);
  217895. }
  217896. inputDeviceNames.appendNumbersToDuplicates (false, true);
  217897. outputDeviceNames.appendNumbersToDuplicates (false, true);
  217898. }
  217899. const StringArray getDeviceNames (const bool wantInputNames) const
  217900. {
  217901. jassert (hasScanned); // need to call scanForDevices() before doing this
  217902. if (wantInputNames)
  217903. return inputDeviceNames;
  217904. else
  217905. return outputDeviceNames;
  217906. }
  217907. int getDefaultDeviceIndex (const bool forInput) const
  217908. {
  217909. jassert (hasScanned); // need to call scanForDevices() before doing this
  217910. AudioDeviceID deviceID;
  217911. UInt32 size = sizeof (deviceID);
  217912. // if they're asking for any input channels at all, use the default input, so we
  217913. // get the built-in mic rather than the built-in output with no inputs..
  217914. if (AudioHardwareGetProperty (forInput ? kAudioHardwarePropertyDefaultInputDevice
  217915. : kAudioHardwarePropertyDefaultOutputDevice,
  217916. &size, &deviceID) == noErr)
  217917. {
  217918. if (forInput)
  217919. {
  217920. for (int i = inputIds.size(); --i >= 0;)
  217921. if (inputIds[i] == deviceID)
  217922. return i;
  217923. }
  217924. else
  217925. {
  217926. for (int i = outputIds.size(); --i >= 0;)
  217927. if (outputIds[i] == deviceID)
  217928. return i;
  217929. }
  217930. }
  217931. return 0;
  217932. }
  217933. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  217934. {
  217935. jassert (hasScanned); // need to call scanForDevices() before doing this
  217936. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  217937. if (d == 0)
  217938. return -1;
  217939. return asInput ? d->inputIndex
  217940. : d->outputIndex;
  217941. }
  217942. bool hasSeparateInputsAndOutputs() const { return true; }
  217943. AudioIODevice* createDevice (const String& outputDeviceName,
  217944. const String& inputDeviceName)
  217945. {
  217946. jassert (hasScanned); // need to call scanForDevices() before doing this
  217947. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  217948. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  217949. String deviceName (outputDeviceName);
  217950. if (deviceName.isEmpty())
  217951. deviceName = inputDeviceName;
  217952. if (index >= 0)
  217953. return new CoreAudioIODevice (deviceName,
  217954. inputIds [inputIndex],
  217955. inputIndex,
  217956. outputIds [outputIndex],
  217957. outputIndex);
  217958. return 0;
  217959. }
  217960. juce_UseDebuggingNewOperator
  217961. private:
  217962. StringArray inputDeviceNames, outputDeviceNames;
  217963. Array <AudioDeviceID> inputIds, outputIds;
  217964. bool hasScanned;
  217965. static int getNumChannels (AudioDeviceID deviceID, bool input)
  217966. {
  217967. int total = 0;
  217968. UInt32 size;
  217969. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, 0)))
  217970. {
  217971. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  217972. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, bufList)))
  217973. {
  217974. const int numStreams = bufList->mNumberBuffers;
  217975. for (int i = 0; i < numStreams; ++i)
  217976. {
  217977. const AudioBuffer& b = bufList->mBuffers[i];
  217978. total += b.mNumberChannels;
  217979. }
  217980. }
  217981. juce_free (bufList);
  217982. }
  217983. return total;
  217984. }
  217985. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  217986. const CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  217987. };
  217988. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  217989. {
  217990. return new CoreAudioIODeviceType();
  217991. }
  217992. #undef log
  217993. END_JUCE_NAMESPACE
  217994. /********* End of inlined file: juce_mac_CoreAudio.cpp *********/
  217995. /********* Start of inlined file: juce_mac_CoreMidi.cpp *********/
  217996. #include <CoreMIDI/MIDIServices.h>
  217997. BEGIN_JUCE_NAMESPACE
  217998. #undef log
  217999. #define log(a) Logger::writeToLog(a)
  218000. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  218001. {
  218002. if (err == noErr)
  218003. return true;
  218004. log (T("CoreMidi error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  218005. jassertfalse
  218006. return false;
  218007. }
  218008. #undef OK
  218009. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  218010. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  218011. {
  218012. String result;
  218013. CFStringRef str = 0;
  218014. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  218015. if (str != 0)
  218016. {
  218017. result = PlatformUtilities::cfStringToJuceString (str);
  218018. CFRelease (str);
  218019. str = 0;
  218020. }
  218021. MIDIEntityRef entity = 0;
  218022. MIDIEndpointGetEntity (endpoint, &entity);
  218023. if (entity == 0)
  218024. return result; // probably virtual
  218025. if (result.isEmpty())
  218026. {
  218027. // endpoint name has zero length - try the entity
  218028. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  218029. if (str != 0)
  218030. {
  218031. result += PlatformUtilities::cfStringToJuceString (str);
  218032. CFRelease (str);
  218033. str = 0;
  218034. }
  218035. }
  218036. // now consider the device's name
  218037. MIDIDeviceRef device = 0;
  218038. MIDIEntityGetDevice (entity, &device);
  218039. if (device == 0)
  218040. return result;
  218041. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  218042. if (str != 0)
  218043. {
  218044. const String s (PlatformUtilities::cfStringToJuceString (str));
  218045. CFRelease (str);
  218046. // if an external device has only one entity, throw away
  218047. // the endpoint name and just use the device name
  218048. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  218049. {
  218050. result = s;
  218051. }
  218052. else if (! result.startsWithIgnoreCase (s))
  218053. {
  218054. // prepend the device name to the entity name
  218055. result = (s + T(" ") + result).trimEnd();
  218056. }
  218057. }
  218058. return result;
  218059. }
  218060. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  218061. {
  218062. String result;
  218063. // Does the endpoint have connections?
  218064. CFDataRef connections = 0;
  218065. int numConnections = 0;
  218066. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  218067. if (connections != 0)
  218068. {
  218069. numConnections = CFDataGetLength (connections) / sizeof (MIDIUniqueID);
  218070. if (numConnections > 0)
  218071. {
  218072. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  218073. for (int i = 0; i < numConnections; ++i, ++pid)
  218074. {
  218075. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  218076. MIDIObjectRef connObject;
  218077. MIDIObjectType connObjectType;
  218078. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  218079. if (err == noErr)
  218080. {
  218081. String s;
  218082. if (connObjectType == kMIDIObjectType_ExternalSource
  218083. || connObjectType == kMIDIObjectType_ExternalDestination)
  218084. {
  218085. // Connected to an external device's endpoint (10.3 and later).
  218086. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  218087. }
  218088. else
  218089. {
  218090. // Connected to an external device (10.2) (or something else, catch-all)
  218091. CFStringRef str = 0;
  218092. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  218093. if (str != 0)
  218094. {
  218095. s = PlatformUtilities::cfStringToJuceString (str);
  218096. CFRelease (str);
  218097. }
  218098. }
  218099. if (s.isNotEmpty())
  218100. {
  218101. if (result.isNotEmpty())
  218102. result += (", ");
  218103. result += s;
  218104. }
  218105. }
  218106. }
  218107. }
  218108. CFRelease (connections);
  218109. }
  218110. if (result.isNotEmpty())
  218111. return result;
  218112. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  218113. return getEndpointName (endpoint, false);
  218114. }
  218115. const StringArray MidiOutput::getDevices()
  218116. {
  218117. StringArray s;
  218118. const ItemCount num = MIDIGetNumberOfDestinations();
  218119. for (ItemCount i = 0; i < num; ++i)
  218120. {
  218121. MIDIEndpointRef dest = MIDIGetDestination (i);
  218122. if (dest != 0)
  218123. {
  218124. String name (getConnectedEndpointName (dest));
  218125. if (name.isEmpty())
  218126. name = "<error>";
  218127. s.add (name);
  218128. }
  218129. else
  218130. {
  218131. s.add ("<error>");
  218132. }
  218133. }
  218134. return s;
  218135. }
  218136. int MidiOutput::getDefaultDeviceIndex()
  218137. {
  218138. return 0;
  218139. }
  218140. static MIDIClientRef globalMidiClient;
  218141. static bool hasGlobalClientBeenCreated = false;
  218142. static bool makeSureClientExists()
  218143. {
  218144. if (! hasGlobalClientBeenCreated)
  218145. {
  218146. String name (T("JUCE"));
  218147. if (JUCEApplication::getInstance() != 0)
  218148. name = JUCEApplication::getInstance()->getApplicationName();
  218149. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  218150. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  218151. CFRelease (appName);
  218152. }
  218153. return hasGlobalClientBeenCreated;
  218154. }
  218155. struct MidiPortAndEndpoint
  218156. {
  218157. MIDIPortRef port;
  218158. MIDIEndpointRef endPoint;
  218159. };
  218160. MidiOutput* MidiOutput::openDevice (int index)
  218161. {
  218162. MidiOutput* mo = 0;
  218163. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  218164. {
  218165. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  218166. CFStringRef pname;
  218167. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  218168. {
  218169. log (T("CoreMidi - opening out: ") + PlatformUtilities::cfStringToJuceString (pname));
  218170. if (makeSureClientExists())
  218171. {
  218172. MIDIPortRef port;
  218173. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  218174. {
  218175. MidiPortAndEndpoint* mpe = new MidiPortAndEndpoint();
  218176. mpe->port = port;
  218177. mpe->endPoint = endPoint;
  218178. mo = new MidiOutput();
  218179. mo->internal = (void*)mpe;
  218180. }
  218181. }
  218182. CFRelease (pname);
  218183. }
  218184. }
  218185. return mo;
  218186. }
  218187. MidiOutput::~MidiOutput()
  218188. {
  218189. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  218190. MIDIPortDispose (mpe->port);
  218191. delete mpe;
  218192. }
  218193. void MidiOutput::reset()
  218194. {
  218195. }
  218196. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  218197. {
  218198. return false;
  218199. }
  218200. void MidiOutput::setVolume (float leftVol, float rightVol)
  218201. {
  218202. }
  218203. void MidiOutput::sendMessageNow (const MidiMessage& message)
  218204. {
  218205. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  218206. if (message.isSysEx())
  218207. {
  218208. MIDIPacketList* const packets = (MIDIPacketList*) juce_malloc (32 + message.getRawDataSize());
  218209. packets->numPackets = 1;
  218210. packets->packet[0].timeStamp = 0;
  218211. packets->packet[0].length = message.getRawDataSize();
  218212. memcpy (packets->packet[0].data, message.getRawData(), message.getRawDataSize());
  218213. MIDISend (mpe->port, mpe->endPoint, packets);
  218214. juce_free (packets);
  218215. }
  218216. else
  218217. {
  218218. MIDIPacketList packets;
  218219. packets.numPackets = 1;
  218220. packets.packet[0].timeStamp = 0;
  218221. packets.packet[0].length = message.getRawDataSize();
  218222. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  218223. MIDISend (mpe->port, mpe->endPoint, &packets);
  218224. }
  218225. }
  218226. const StringArray MidiInput::getDevices()
  218227. {
  218228. StringArray s;
  218229. const ItemCount num = MIDIGetNumberOfSources();
  218230. for (ItemCount i = 0; i < num; ++i)
  218231. {
  218232. MIDIEndpointRef source = MIDIGetSource (i);
  218233. if (source != 0)
  218234. {
  218235. String name (getConnectedEndpointName (source));
  218236. if (name.isEmpty())
  218237. name = "<error>";
  218238. s.add (name);
  218239. }
  218240. else
  218241. {
  218242. s.add ("<error>");
  218243. }
  218244. }
  218245. return s;
  218246. }
  218247. int MidiInput::getDefaultDeviceIndex()
  218248. {
  218249. return 0;
  218250. }
  218251. struct MidiPortAndCallback
  218252. {
  218253. MidiInput* input;
  218254. MIDIPortRef port;
  218255. MIDIEndpointRef endPoint;
  218256. MidiInputCallback* callback;
  218257. MemoryBlock pendingData;
  218258. int pendingBytes;
  218259. double pendingDataTime;
  218260. bool active;
  218261. };
  218262. static CriticalSection callbackLock;
  218263. static VoidArray activeCallbacks;
  218264. static void processSysex (MidiPortAndCallback* const mpe, const uint8*& d, int& size, const double time)
  218265. {
  218266. if (*d == 0xf0)
  218267. {
  218268. mpe->pendingBytes = 0;
  218269. mpe->pendingDataTime = time;
  218270. }
  218271. mpe->pendingData.ensureSize (mpe->pendingBytes + size, false);
  218272. uint8* totalMessage = (uint8*) mpe->pendingData.getData();
  218273. uint8* dest = totalMessage + mpe->pendingBytes;
  218274. while (size > 0)
  218275. {
  218276. if (mpe->pendingBytes > 0 && *d >= 0x80)
  218277. {
  218278. if (*d >= 0xfa || *d == 0xf8)
  218279. {
  218280. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (*d, time));
  218281. ++d;
  218282. --size;
  218283. }
  218284. else
  218285. {
  218286. if (*d == 0xf7)
  218287. {
  218288. *dest++ = *d++;
  218289. mpe->pendingBytes++;
  218290. --size;
  218291. }
  218292. break;
  218293. }
  218294. }
  218295. else
  218296. {
  218297. *dest++ = *d++;
  218298. mpe->pendingBytes++;
  218299. --size;
  218300. }
  218301. }
  218302. if (totalMessage [mpe->pendingBytes - 1] == 0xf7)
  218303. {
  218304. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (totalMessage,
  218305. mpe->pendingBytes,
  218306. mpe->pendingDataTime));
  218307. mpe->pendingBytes = 0;
  218308. }
  218309. else
  218310. {
  218311. mpe->callback->handlePartialSysexMessage (mpe->input,
  218312. totalMessage,
  218313. mpe->pendingBytes,
  218314. mpe->pendingDataTime);
  218315. }
  218316. }
  218317. static void midiInputProc (const MIDIPacketList* pktlist,
  218318. void* readProcRefCon,
  218319. void* srcConnRefCon)
  218320. {
  218321. double time = Time::getMillisecondCounterHiRes() * 0.001;
  218322. const double originalTime = time;
  218323. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) readProcRefCon;
  218324. const ScopedLock sl (callbackLock);
  218325. if (activeCallbacks.contains (mpe) && mpe->active)
  218326. {
  218327. const MIDIPacket* packet = &pktlist->packet[0];
  218328. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  218329. {
  218330. const uint8* d = (const uint8*) (packet->data);
  218331. int size = packet->length;
  218332. while (size > 0)
  218333. {
  218334. time = originalTime;
  218335. if (mpe->pendingBytes > 0 || d[0] == 0xf0)
  218336. {
  218337. processSysex (mpe, d, size, time);
  218338. }
  218339. else
  218340. {
  218341. int used = 0;
  218342. const MidiMessage m (d, size, used, 0, time);
  218343. if (used <= 0)
  218344. {
  218345. jassertfalse // malformed midi message
  218346. break;
  218347. }
  218348. else
  218349. {
  218350. mpe->callback->handleIncomingMidiMessage (mpe->input, m);
  218351. }
  218352. size -= used;
  218353. d += used;
  218354. }
  218355. }
  218356. packet = MIDIPacketNext (packet);
  218357. }
  218358. }
  218359. }
  218360. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  218361. {
  218362. MidiInput* mi = 0;
  218363. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  218364. {
  218365. MIDIEndpointRef endPoint = MIDIGetSource (index);
  218366. if (endPoint != 0)
  218367. {
  218368. CFStringRef pname;
  218369. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  218370. {
  218371. log (T("CoreMidi - opening inp: ") + PlatformUtilities::cfStringToJuceString (pname));
  218372. if (makeSureClientExists())
  218373. {
  218374. MIDIPortRef port;
  218375. MidiPortAndCallback* const mpe = new MidiPortAndCallback();
  218376. mpe->active = false;
  218377. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpe, &port)))
  218378. {
  218379. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  218380. {
  218381. mpe->port = port;
  218382. mpe->endPoint = endPoint;
  218383. mpe->callback = callback;
  218384. mpe->pendingBytes = 0;
  218385. mpe->pendingData.ensureSize (128);
  218386. mi = new MidiInput (getDevices() [index]);
  218387. mpe->input = mi;
  218388. mi->internal = (void*) mpe;
  218389. const ScopedLock sl (callbackLock);
  218390. activeCallbacks.add (mpe);
  218391. }
  218392. else
  218393. {
  218394. OK (MIDIPortDispose (port));
  218395. delete mpe;
  218396. }
  218397. }
  218398. else
  218399. {
  218400. delete mpe;
  218401. }
  218402. }
  218403. }
  218404. CFRelease (pname);
  218405. }
  218406. }
  218407. return mi;
  218408. }
  218409. MidiInput::MidiInput (const String& name_)
  218410. : name (name_)
  218411. {
  218412. }
  218413. MidiInput::~MidiInput()
  218414. {
  218415. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  218416. mpe->active = false;
  218417. callbackLock.enter();
  218418. activeCallbacks.removeValue (mpe);
  218419. callbackLock.exit();
  218420. OK (MIDIPortDisconnectSource (mpe->port, mpe->endPoint));
  218421. OK (MIDIPortDispose (mpe->port));
  218422. delete mpe;
  218423. }
  218424. void MidiInput::start()
  218425. {
  218426. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  218427. const ScopedLock sl (callbackLock);
  218428. mpe->active = true;
  218429. }
  218430. void MidiInput::stop()
  218431. {
  218432. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  218433. const ScopedLock sl (callbackLock);
  218434. mpe->active = false;
  218435. }
  218436. #undef log
  218437. END_JUCE_NAMESPACE
  218438. /********* End of inlined file: juce_mac_CoreMidi.cpp *********/
  218439. /********* Start of inlined file: juce_mac_FileChooser.mm *********/
  218440. #include <fnmatch.h>
  218441. BEGIN_JUCE_NAMESPACE
  218442. END_JUCE_NAMESPACE
  218443. @interface JuceFileChooserDelegate : NSObject
  218444. {
  218445. JUCE_NAMESPACE::StringArray* filters;
  218446. }
  218447. - (JuceFileChooserDelegate*) initWithFilters: (JUCE_NAMESPACE::StringArray*) filters_;
  218448. - (void) dealloc;
  218449. - (BOOL) panel:(id) sender shouldShowFilename: (NSString*) filename;
  218450. @end
  218451. @implementation JuceFileChooserDelegate
  218452. - (JuceFileChooserDelegate*) initWithFilters: (JUCE_NAMESPACE::StringArray*) filters_
  218453. {
  218454. [super init];
  218455. filters = filters_;
  218456. return self;
  218457. }
  218458. - (void) dealloc
  218459. {
  218460. delete filters;
  218461. [super dealloc];
  218462. }
  218463. - (BOOL) panel:(id) sender shouldShowFilename: (NSString*) filename
  218464. {
  218465. const char* filenameUTF8 = (const char*) [filename UTF8String];
  218466. for (int i = filters->size(); --i >= 0;)
  218467. {
  218468. const JUCE_NAMESPACE::String wildcard ((*filters)[i].toLowerCase());
  218469. if (fnmatch (wildcard.toUTF8(), filenameUTF8, 0) == 0)
  218470. return true;
  218471. }
  218472. return JUCE_NAMESPACE::File (nsStringToJuce (filename)).isDirectory();
  218473. }
  218474. @end
  218475. BEGIN_JUCE_NAMESPACE
  218476. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  218477. const String& title,
  218478. const File& currentFileOrDirectory,
  218479. const String& filter,
  218480. bool selectsDirectory,
  218481. bool isSaveDialogue,
  218482. bool warnAboutOverwritingExistingFiles,
  218483. bool selectMultipleFiles,
  218484. FilePreviewComponent* extraInfoComponent)
  218485. {
  218486. const AutoPool pool;
  218487. StringArray* filters = new StringArray();
  218488. filters->addTokens (filter.replaceCharacters (T(",:"), T(";;")), T(";"), 0);
  218489. filters->trim();
  218490. filters->removeEmptyStrings();
  218491. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  218492. [delegate autorelease];
  218493. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  218494. : [NSOpenPanel openPanel];
  218495. [panel setTitle: juceStringToNS (title)];
  218496. if (! isSaveDialogue)
  218497. {
  218498. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  218499. [openPanel setCanChooseDirectories: selectsDirectory];
  218500. [openPanel setCanChooseFiles: ! selectsDirectory];
  218501. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  218502. }
  218503. [panel setDelegate: delegate];
  218504. if ([panel runModalForDirectory: juceStringToNS (currentFileOrDirectory.getParentDirectory().getFullPathName())
  218505. file: juceStringToNS (currentFileOrDirectory.getFileName())]
  218506. == NSOKButton)
  218507. {
  218508. if (isSaveDialogue)
  218509. {
  218510. results.add (new File (nsStringToJuce ([panel filename])));
  218511. }
  218512. else
  218513. {
  218514. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  218515. NSArray* urls = [openPanel filenames];
  218516. for (int i = 0; i < [urls count]; ++i)
  218517. {
  218518. NSString* f = [urls objectAtIndex: i];
  218519. results.add (new File (nsStringToJuce (f)));
  218520. }
  218521. }
  218522. }
  218523. }
  218524. END_JUCE_NAMESPACE
  218525. /********* End of inlined file: juce_mac_FileChooser.mm *********/
  218526. /********* Start of inlined file: juce_mac_Fonts.mm *********/
  218527. #include <ApplicationServices/ApplicationServices.h>
  218528. BEGIN_JUCE_NAMESPACE
  218529. static OSStatus pascal CubicMoveTo (const Float32Point *pt,
  218530. void* callBackDataPtr)
  218531. {
  218532. Path* const p = (Path*) callBackDataPtr;
  218533. p->startNewSubPath (pt->x, pt->y);
  218534. return noErr;
  218535. }
  218536. static OSStatus pascal CubicLineTo (const Float32Point *pt,
  218537. void* callBackDataPtr)
  218538. {
  218539. Path* const p = (Path*) callBackDataPtr;
  218540. p->lineTo (pt->x, pt->y);
  218541. return noErr;
  218542. }
  218543. static OSStatus pascal CubicCurveTo (const Float32Point *pt1,
  218544. const Float32Point *pt2,
  218545. const Float32Point *pt3,
  218546. void* callBackDataPtr)
  218547. {
  218548. Path* const p = (Path*) callBackDataPtr;
  218549. p->cubicTo (pt1->x, pt1->y,
  218550. pt2->x, pt2->y,
  218551. pt3->x, pt3->y);
  218552. return noErr;
  218553. }
  218554. static OSStatus pascal CubicClosePath (void* callBackDataPtr)
  218555. {
  218556. Path* const p = (Path*) callBackDataPtr;
  218557. p->closeSubPath();
  218558. return noErr;
  218559. }
  218560. class ATSFontHelper
  218561. {
  218562. ATSUFontID fontId;
  218563. ATSUStyle style;
  218564. ATSCubicMoveToUPP moveToProc;
  218565. ATSCubicLineToUPP lineToProc;
  218566. ATSCubicCurveToUPP curveToProc;
  218567. ATSCubicClosePathUPP closePathProc;
  218568. float totalSize, ascent;
  218569. TextToUnicodeInfo encodingInfo;
  218570. public:
  218571. String name;
  218572. bool isBold, isItalic;
  218573. float fontSize;
  218574. int refCount;
  218575. ATSFontHelper (const String& name_,
  218576. const bool bold_,
  218577. const bool italic_,
  218578. const float size_)
  218579. : fontId (0),
  218580. name (name_),
  218581. isBold (bold_),
  218582. isItalic (italic_),
  218583. fontSize (size_),
  218584. refCount (1)
  218585. {
  218586. const char* const nameUtf8 = name_.toUTF8();
  218587. ATSUFindFontFromName (const_cast <char*> (nameUtf8),
  218588. strlen (nameUtf8),
  218589. kFontFullName,
  218590. kFontNoPlatformCode,
  218591. kFontNoScriptCode,
  218592. kFontNoLanguageCode,
  218593. &fontId);
  218594. ATSUCreateStyle (&style);
  218595. ATSUAttributeTag attTypes[] = { kATSUFontTag,
  218596. kATSUQDBoldfaceTag,
  218597. kATSUQDItalicTag,
  218598. kATSUSizeTag };
  218599. ByteCount attSizes[] = { sizeof (ATSUFontID),
  218600. sizeof (Boolean),
  218601. sizeof (Boolean),
  218602. sizeof (Fixed) };
  218603. Boolean bold = bold_, italic = italic_;
  218604. Fixed size = X2Fix (size_);
  218605. ATSUAttributeValuePtr attValues[] = { &fontId,
  218606. &bold,
  218607. &italic,
  218608. &size };
  218609. ATSUSetAttributes (style, 4, attTypes, attSizes, attValues);
  218610. moveToProc = NewATSCubicMoveToUPP (CubicMoveTo);
  218611. lineToProc = NewATSCubicLineToUPP (CubicLineTo);
  218612. curveToProc = NewATSCubicCurveToUPP (CubicCurveTo);
  218613. closePathProc = NewATSCubicClosePathUPP (CubicClosePath);
  218614. ascent = 0.0f;
  218615. float kern, descent = 0.0f;
  218616. getPathAndKerning (T('N'), T('O'), 0, kern, &ascent, &descent);
  218617. totalSize = ascent + descent;
  218618. }
  218619. ~ATSFontHelper()
  218620. {
  218621. ATSUDisposeStyle (style);
  218622. DisposeATSCubicMoveToUPP (moveToProc);
  218623. DisposeATSCubicLineToUPP (lineToProc);
  218624. DisposeATSCubicCurveToUPP (curveToProc);
  218625. DisposeATSCubicClosePathUPP (closePathProc);
  218626. }
  218627. bool getPathAndKerning (const juce_wchar char1,
  218628. const juce_wchar char2,
  218629. Path* path,
  218630. float& kerning,
  218631. float* ascent,
  218632. float* descent)
  218633. {
  218634. bool ok = false;
  218635. UniChar buffer[4];
  218636. buffer[0] = T(' ');
  218637. buffer[1] = char1;
  218638. buffer[2] = char2;
  218639. buffer[3] = 0;
  218640. UniCharCount count = kATSUToTextEnd;
  218641. ATSUTextLayout layout;
  218642. OSStatus err = ATSUCreateTextLayoutWithTextPtr (buffer,
  218643. 0,
  218644. 2,
  218645. 2,
  218646. 1,
  218647. &count,
  218648. &style,
  218649. &layout);
  218650. if (err == noErr)
  218651. {
  218652. ATSUSetTransientFontMatching (layout, true);
  218653. ATSLayoutRecord* layoutRecords;
  218654. ItemCount numRecords;
  218655. Fixed* deltaYs;
  218656. ItemCount numDeltaYs;
  218657. ATSUDirectGetLayoutDataArrayPtrFromTextLayout (layout,
  218658. 0,
  218659. kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
  218660. (void**) &layoutRecords,
  218661. &numRecords);
  218662. ATSUDirectGetLayoutDataArrayPtrFromTextLayout (layout,
  218663. 0,
  218664. kATSUDirectDataBaselineDeltaFixedArray,
  218665. (void**) &deltaYs,
  218666. &numDeltaYs);
  218667. if (numRecords > 2)
  218668. {
  218669. kerning = (float) (Fix2X (layoutRecords[2].realPos)
  218670. - Fix2X (layoutRecords[1].realPos));
  218671. if (ascent != 0)
  218672. {
  218673. ATSUTextMeasurement asc;
  218674. ByteCount actualSize;
  218675. ATSUGetLineControl (layout,
  218676. 0,
  218677. kATSULineAscentTag,
  218678. sizeof (ATSUTextMeasurement),
  218679. &asc,
  218680. &actualSize);
  218681. *ascent = (float) Fix2X (asc);
  218682. }
  218683. if (descent != 0)
  218684. {
  218685. ATSUTextMeasurement desc;
  218686. ByteCount actualSize;
  218687. ATSUGetLineControl (layout,
  218688. 0,
  218689. kATSULineDescentTag,
  218690. sizeof (ATSUTextMeasurement),
  218691. &desc,
  218692. &actualSize);
  218693. *descent = (float) Fix2X (desc);
  218694. }
  218695. if (path != 0)
  218696. {
  218697. OSStatus callbackResult;
  218698. ok = (ATSUGlyphGetCubicPaths (style,
  218699. layoutRecords[1].glyphID,
  218700. moveToProc,
  218701. lineToProc,
  218702. curveToProc,
  218703. closePathProc,
  218704. (void*) path,
  218705. &callbackResult) == noErr);
  218706. if (numDeltaYs > 0 && ok)
  218707. {
  218708. const float dy = (float) Fix2X (deltaYs[1]);
  218709. path->applyTransform (AffineTransform::translation (0.0f, dy));
  218710. }
  218711. }
  218712. else
  218713. {
  218714. ok = true;
  218715. }
  218716. }
  218717. if (deltaYs != 0)
  218718. ATSUDirectReleaseLayoutDataArrayPtr (0, kATSUDirectDataBaselineDeltaFixedArray,
  218719. (void**) &deltaYs);
  218720. if (layoutRecords != 0)
  218721. ATSUDirectReleaseLayoutDataArrayPtr (0, kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
  218722. (void**) &layoutRecords);
  218723. ATSUDisposeTextLayout (layout);
  218724. }
  218725. return kerning;
  218726. }
  218727. float getAscent()
  218728. {
  218729. return ascent;
  218730. }
  218731. float getTotalHeight()
  218732. {
  218733. return totalSize;
  218734. }
  218735. juce_wchar getDefaultChar()
  218736. {
  218737. return 0;
  218738. }
  218739. };
  218740. class ATSFontHelperCache : public Timer,
  218741. public DeletedAtShutdown
  218742. {
  218743. VoidArray cache;
  218744. public:
  218745. ATSFontHelperCache()
  218746. {
  218747. }
  218748. ~ATSFontHelperCache()
  218749. {
  218750. for (int i = cache.size(); --i >= 0;)
  218751. {
  218752. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  218753. delete f;
  218754. }
  218755. clearSingletonInstance();
  218756. }
  218757. ATSFontHelper* getFont (const String& name,
  218758. const bool bold,
  218759. const bool italic,
  218760. const float size = 1024)
  218761. {
  218762. for (int i = cache.size(); --i >= 0;)
  218763. {
  218764. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  218765. if (f->name == name
  218766. && f->isBold == bold
  218767. && f->isItalic == italic
  218768. && f->fontSize == size)
  218769. {
  218770. f->refCount++;
  218771. return f;
  218772. }
  218773. }
  218774. ATSFontHelper* const f = new ATSFontHelper (name, bold, italic, size);
  218775. cache.add (f);
  218776. return f;
  218777. }
  218778. void releaseFont (ATSFontHelper* f)
  218779. {
  218780. for (int i = cache.size(); --i >= 0;)
  218781. {
  218782. ATSFontHelper* const f2 = (ATSFontHelper*) cache.getUnchecked(i);
  218783. if (f == f2)
  218784. {
  218785. f->refCount--;
  218786. if (f->refCount == 0)
  218787. startTimer (5000);
  218788. break;
  218789. }
  218790. }
  218791. }
  218792. void timerCallback()
  218793. {
  218794. stopTimer();
  218795. for (int i = cache.size(); --i >= 0;)
  218796. {
  218797. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  218798. if (f->refCount == 0)
  218799. {
  218800. cache.remove (i);
  218801. delete f;
  218802. }
  218803. }
  218804. if (cache.size() == 0)
  218805. delete this;
  218806. }
  218807. juce_DeclareSingleton_SingleThreaded_Minimal (ATSFontHelperCache)
  218808. };
  218809. juce_ImplementSingleton_SingleThreaded (ATSFontHelperCache)
  218810. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  218811. bool bold,
  218812. bool italic,
  218813. bool addAllGlyphsToFont) throw()
  218814. {
  218815. // This method is only safe to be called from the normal UI thread..
  218816. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  218817. ATSFontHelper* const helper = ATSFontHelperCache::getInstance()
  218818. ->getFont (fontName, bold, italic);
  218819. clear();
  218820. setAscent (helper->getAscent() / helper->getTotalHeight());
  218821. setName (fontName);
  218822. setDefaultCharacter (helper->getDefaultChar());
  218823. setBold (bold);
  218824. setItalic (italic);
  218825. if (addAllGlyphsToFont)
  218826. {
  218827. //xxx
  218828. jassertfalse
  218829. }
  218830. ATSFontHelperCache::getInstance()->releaseFont (helper);
  218831. }
  218832. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  218833. {
  218834. // This method is only safe to be called from the normal UI thread..
  218835. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  218836. ATSFontHelper* const helper = ATSFontHelperCache::getInstance()
  218837. ->getFont (getName(), isBold(), isItalic());
  218838. Path path;
  218839. float width;
  218840. bool foundOne = false;
  218841. if (helper->getPathAndKerning (character, T('I'), &path, width, 0, 0))
  218842. {
  218843. path.applyTransform (AffineTransform::scale (1.0f / helper->getTotalHeight(),
  218844. 1.0f / helper->getTotalHeight()));
  218845. addGlyph (character, path, width / helper->getTotalHeight());
  218846. for (int i = 0; i < glyphs.size(); ++i)
  218847. {
  218848. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  218849. float kerning;
  218850. if (helper->getPathAndKerning (character, g->getCharacter(), 0, kerning, 0, 0))
  218851. {
  218852. kerning = (kerning - width) / helper->getTotalHeight();
  218853. if (kerning != 0)
  218854. addKerningPair (character, g->getCharacter(), kerning);
  218855. }
  218856. if (helper->getPathAndKerning (g->getCharacter(), character, 0, kerning, 0, 0))
  218857. {
  218858. kerning = kerning / helper->getTotalHeight() - g->width;
  218859. if (kerning != 0)
  218860. addKerningPair (g->getCharacter(), character, kerning);
  218861. }
  218862. }
  218863. foundOne = true;
  218864. }
  218865. ATSFontHelperCache::getInstance()->releaseFont (helper);
  218866. return foundOne;
  218867. }
  218868. const StringArray Font::findAllTypefaceNames() throw()
  218869. {
  218870. StringArray names;
  218871. ATSFontIterator iter;
  218872. if (ATSFontIteratorCreate (kATSFontContextGlobal,
  218873. 0,
  218874. 0,
  218875. kATSOptionFlagsRestrictedScope,
  218876. &iter) == noErr)
  218877. {
  218878. ATSFontRef font;
  218879. while (ATSFontIteratorNext (iter, &font) == noErr)
  218880. {
  218881. CFStringRef name;
  218882. if (ATSFontGetName (font,
  218883. kATSOptionFlagsDefault,
  218884. &name) == noErr)
  218885. {
  218886. const String nm (PlatformUtilities::cfStringToJuceString (name));
  218887. if (nm.isNotEmpty())
  218888. names.add (nm);
  218889. CFRelease (name);
  218890. }
  218891. }
  218892. ATSFontIteratorRelease (&iter);
  218893. }
  218894. // Use some totuous logic to eliminate bold/italic versions of fonts that we've already got
  218895. // a plain version of. This is only necessary because of Carbon's total lack of support
  218896. // for dealing with font families...
  218897. for (int j = names.size(); --j >= 0;)
  218898. {
  218899. const char* const endings[] = { " bold", " italic", " bold italic", " bolditalic",
  218900. " oblque", " bold oblique", " boldoblique" };
  218901. for (int i = 0; i < numElementsInArray (endings); ++i)
  218902. {
  218903. const String ending (endings[i]);
  218904. if (names[j].endsWithIgnoreCase (ending))
  218905. {
  218906. const String root (names[j].dropLastCharacters (ending.length()).trimEnd());
  218907. if (names.contains (root)
  218908. || names.contains (root + T(" plain"), true))
  218909. {
  218910. names.remove (j);
  218911. break;
  218912. }
  218913. }
  218914. }
  218915. }
  218916. names.sort (true);
  218917. return names;
  218918. }
  218919. void Font::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  218920. {
  218921. defaultSans = "Lucida Grande";
  218922. defaultSerif = "Times New Roman";
  218923. defaultFixed = "Monaco";
  218924. }
  218925. END_JUCE_NAMESPACE
  218926. /********* End of inlined file: juce_mac_Fonts.mm *********/
  218927. /********* Start of inlined file: juce_mac_Messaging.mm *********/
  218928. #include <Carbon/Carbon.h>
  218929. BEGIN_JUCE_NAMESPACE
  218930. #undef Point
  218931. extern void juce_HandleProcessFocusChange();
  218932. extern void juce_maximiseAllMinimisedWindows();
  218933. extern void juce_InvokeMainMenuCommand (const HICommand& command);
  218934. extern void juce_MainMenuAboutToBeUsed();
  218935. struct CallbackMessagePayload
  218936. {
  218937. MessageCallbackFunction* function;
  218938. void* parameter;
  218939. void* volatile result;
  218940. bool volatile hasBeenExecuted;
  218941. };
  218942. END_JUCE_NAMESPACE
  218943. #if JUCE_COCOA
  218944. NSString* juceMessageName = 0;
  218945. @interface JuceAppDelegate : NSObject
  218946. id oldDelegate;
  218947. - (JuceAppDelegate*) init;
  218948. - (void) dealloc;
  218949. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  218950. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  218951. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  218952. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  218953. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  218954. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  218955. - (void) customEvent: (NSNotification*) aNotification;
  218956. - (void) performCallback: (id) info;
  218957. @end
  218958. @implementation JuceAppDelegate
  218959. - (JuceAppDelegate*) init
  218960. {
  218961. [super init];
  218962. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  218963. if (JUCE_NAMESPACE::JUCEApplication::getInstance() != 0)
  218964. {
  218965. oldDelegate = [NSApp delegate];
  218966. [NSApp setDelegate: self];
  218967. }
  218968. else
  218969. {
  218970. oldDelegate = 0;
  218971. [center addObserver: self selector: @selector (applicationDidResignActive:)
  218972. name: NSApplicationDidResignActiveNotification object: NSApp];
  218973. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  218974. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  218975. [center addObserver: self selector: @selector (applicationWillUnhide:)
  218976. name: NSApplicationWillUnhideNotification object: NSApp];
  218977. }
  218978. [center addObserver: self selector: @selector (customEvent:)
  218979. name: juceMessageName object: nil];
  218980. return self;
  218981. }
  218982. - (void) dealloc
  218983. {
  218984. if (oldDelegate != 0)
  218985. [NSApp setDelegate: oldDelegate];
  218986. [[NSNotificationCenter defaultCenter] removeObserver: self];
  218987. [super dealloc];
  218988. }
  218989. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  218990. {
  218991. if (JUCE_NAMESPACE::JUCEApplication::getInstance() != 0)
  218992. JUCE_NAMESPACE::JUCEApplication::getInstance()->systemRequestedQuit();
  218993. return NSTerminateLater;
  218994. }
  218995. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  218996. {
  218997. if (JUCE_NAMESPACE::JUCEApplication::getInstance() != 0)
  218998. {
  218999. JUCE_NAMESPACE::JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  219000. return YES;
  219001. }
  219002. return NO;
  219003. }
  219004. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  219005. {
  219006. JUCE_NAMESPACE::StringArray files;
  219007. for (int i = 0; i < [filenames count]; ++i)
  219008. files.add (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  219009. if (files.size() > 0 && JUCE_NAMESPACE::JUCEApplication::getInstance() != 0)
  219010. JUCE_NAMESPACE::JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (T(" ")));
  219011. }
  219012. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  219013. {
  219014. JUCE_NAMESPACE::juce_HandleProcessFocusChange();
  219015. }
  219016. - (void) applicationDidResignActive: (NSNotification*) aNotification
  219017. {
  219018. JUCE_NAMESPACE::juce_HandleProcessFocusChange();
  219019. }
  219020. - (void) applicationWillUnhide: (NSNotification*) aNotification
  219021. {
  219022. JUCE_NAMESPACE::juce_maximiseAllMinimisedWindows();
  219023. }
  219024. - (void) customEvent: (NSNotification*) n
  219025. {
  219026. void* message = 0;
  219027. [((NSData*) [n object]) getBytes: &message length: sizeof (message)];
  219028. if (message != 0)
  219029. JUCE_NAMESPACE::MessageManager::getInstance()->deliverMessage (message);
  219030. }
  219031. - (void) performCallback: (id) info
  219032. {
  219033. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) info;
  219034. if (pl != 0)
  219035. {
  219036. pl->result = (*pl->function) (pl->parameter);
  219037. pl->hasBeenExecuted = true;
  219038. }
  219039. }
  219040. @end
  219041. #endif
  219042. BEGIN_JUCE_NAMESPACE
  219043. #if JUCE_COCOA
  219044. static JuceAppDelegate* juceAppDelegate = 0;
  219045. #else
  219046. static int kJUCEClass = FOUR_CHAR_CODE ('JUCE');
  219047. const int kJUCEKind = 1;
  219048. const int kCallbackKind = 2;
  219049. static pascal OSStatus EventHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  219050. {
  219051. void* event = 0;
  219052. GetEventParameter (theEvent, 'mess', typeVoidPtr, 0, sizeof (void*), 0, &event);
  219053. if (event != 0)
  219054. MessageManager::getInstance()->deliverMessage (event);
  219055. return noErr;
  219056. }
  219057. static pascal OSStatus CallbackHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  219058. {
  219059. CallbackMessagePayload* pl = 0;
  219060. GetEventParameter (theEvent, 'mess', typeVoidPtr, 0, sizeof(pl), 0, &pl);
  219061. if (pl != 0)
  219062. {
  219063. pl->result = (*pl->function) (pl->parameter);
  219064. pl->hasBeenExecuted = true;
  219065. }
  219066. return noErr;
  219067. }
  219068. static pascal OSStatus MouseClickHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  219069. {
  219070. ::Point where;
  219071. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof(::Point), 0, &where);
  219072. WindowRef window;
  219073. if (FindWindow (where, &window) == inMenuBar)
  219074. {
  219075. // turn off the wait cursor before going in here..
  219076. const int oldTimeBeforeWaitCursor = MessageManager::getInstance()->getTimeBeforeShowingWaitCursor();
  219077. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (0);
  219078. if (Component::getCurrentlyModalComponent() != 0)
  219079. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  219080. juce_MainMenuAboutToBeUsed();
  219081. MenuSelect (where);
  219082. HiliteMenu (0);
  219083. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (oldTimeBeforeWaitCursor);
  219084. return noErr;
  219085. }
  219086. return eventNotHandledErr;
  219087. }
  219088. static pascal OSErr QuitAppleEventHandler (const AppleEvent *appleEvt, AppleEvent* reply, long refcon)
  219089. {
  219090. if (JUCEApplication::getInstance() != 0)
  219091. JUCEApplication::getInstance()->systemRequestedQuit();
  219092. return noErr;
  219093. }
  219094. static pascal OSErr OpenDocEventHandler (const AppleEvent *appleEvt, AppleEvent* reply, long refcon)
  219095. {
  219096. AEDescList docs;
  219097. StringArray files;
  219098. if (AEGetParamDesc (appleEvt, keyDirectObject, typeAEList, &docs) == noErr)
  219099. {
  219100. long num;
  219101. if (AECountItems (&docs, &num) == noErr)
  219102. {
  219103. for (int i = 1; i <= num; ++i)
  219104. {
  219105. FSRef file;
  219106. AEKeyword keyword;
  219107. DescType type;
  219108. Size size;
  219109. if (AEGetNthPtr (&docs, i, typeFSRef, &keyword, &type,
  219110. &file, sizeof (file), &size) == noErr)
  219111. {
  219112. const String path (PlatformUtilities::makePathFromFSRef (&file));
  219113. if (path.isNotEmpty())
  219114. files.add (path.quoted());
  219115. }
  219116. }
  219117. if (files.size() > 0
  219118. && JUCEApplication::getInstance() != 0)
  219119. {
  219120. JUCE_TRY
  219121. {
  219122. JUCEApplication::getInstance()
  219123. ->anotherInstanceStarted (files.joinIntoString (T(" ")));
  219124. }
  219125. JUCE_CATCH_ALL
  219126. }
  219127. }
  219128. AEDisposeDesc (&docs);
  219129. };
  219130. return noErr;
  219131. }
  219132. static pascal OSStatus AppEventHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  219133. {
  219134. const UInt32 eventClass = GetEventClass (theEvent);
  219135. if (eventClass == kEventClassCommand)
  219136. {
  219137. HICommand command;
  219138. if (GetEventParameter (theEvent, kEventParamHICommand, typeHICommand, 0, sizeof (command), 0, &command) == noErr
  219139. || GetEventParameter (theEvent, kEventParamDirectObject, typeHICommand, 0, sizeof (command), 0, &command) == noErr)
  219140. {
  219141. if (command.commandID == kHICommandQuit)
  219142. {
  219143. if (JUCEApplication::getInstance() != 0)
  219144. JUCEApplication::getInstance()->systemRequestedQuit();
  219145. return noErr;
  219146. }
  219147. else if (command.commandID == kHICommandMaximizeAll
  219148. || command.commandID == kHICommandMaximizeWindow
  219149. || command.commandID == kHICommandBringAllToFront)
  219150. {
  219151. juce_maximiseAllMinimisedWindows();
  219152. return noErr;
  219153. }
  219154. else
  219155. {
  219156. juce_InvokeMainMenuCommand (command);
  219157. }
  219158. }
  219159. }
  219160. else if (eventClass == kEventClassApplication)
  219161. {
  219162. if (GetEventKind (theEvent) == kEventAppFrontSwitched)
  219163. {
  219164. juce_HandleProcessFocusChange();
  219165. }
  219166. else if (GetEventKind (theEvent) == kEventAppShown)
  219167. {
  219168. // this seems to blank the windows, so we need to do a repaint..
  219169. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  219170. {
  219171. Component* const c = Desktop::getInstance().getComponent (i);
  219172. if (c != 0)
  219173. c->repaint();
  219174. }
  219175. }
  219176. }
  219177. return eventNotHandledErr;
  219178. }
  219179. static EventQueueRef mainQueue;
  219180. static EventHandlerRef juceEventHandler = 0;
  219181. static EventHandlerRef callbackEventHandler = 0;
  219182. #endif
  219183. void MessageManager::doPlatformSpecificInitialisation()
  219184. {
  219185. static bool initialised = false;
  219186. if (! initialised)
  219187. {
  219188. initialised = true;
  219189. #if JUCE_COCOA
  219190. // if we're linking a Juce app to one or more dynamic libraries, we'll need different values
  219191. // for this so each module doesn't interfere with the others.
  219192. UnsignedWide t;
  219193. Microseconds (&t);
  219194. kJUCEClass ^= t.lo;
  219195. juceMessageName = juceStringToNS ("juce_" + String::toHexString ((int) t.lo));
  219196. juceAppDelegate = [[JuceAppDelegate alloc] init];
  219197. #else
  219198. mainQueue = GetMainEventQueue();
  219199. #endif
  219200. }
  219201. #if ! JUCE_COCOA
  219202. const EventTypeSpec type1 = { kJUCEClass, kJUCEKind };
  219203. InstallApplicationEventHandler (NewEventHandlerUPP (EventHandlerProc), 1, &type1, 0, &juceEventHandler);
  219204. const EventTypeSpec type2 = { kJUCEClass, kCallbackKind };
  219205. InstallApplicationEventHandler (NewEventHandlerUPP (CallbackHandlerProc), 1, &type2, 0, &callbackEventHandler);
  219206. // only do this stuff if we're running as an application rather than a library..
  219207. if (JUCEApplication::getInstance() != 0)
  219208. {
  219209. const EventTypeSpec type3 = { kEventClassMouse, kEventMouseDown };
  219210. InstallApplicationEventHandler (NewEventHandlerUPP (MouseClickHandlerProc), 1, &type3, 0, 0);
  219211. const EventTypeSpec type4[] = { { kEventClassApplication, kEventAppShown },
  219212. { kEventClassApplication, kEventAppFrontSwitched },
  219213. { kEventClassCommand, kEventProcessCommand } };
  219214. InstallApplicationEventHandler (NewEventHandlerUPP (AppEventHandlerProc), 3, type4, 0, 0);
  219215. AEInstallEventHandler (kCoreEventClass, kAEQuitApplication,
  219216. NewAEEventHandlerUPP (QuitAppleEventHandler), 0, false);
  219217. AEInstallEventHandler (kCoreEventClass, kAEOpenDocuments,
  219218. NewAEEventHandlerUPP (OpenDocEventHandler), 0, false);
  219219. }
  219220. #endif
  219221. }
  219222. void MessageManager::doPlatformSpecificShutdown()
  219223. {
  219224. if (juceEventHandler != 0)
  219225. {
  219226. RemoveEventHandler (juceEventHandler);
  219227. juceEventHandler = 0;
  219228. }
  219229. if (callbackEventHandler != 0)
  219230. {
  219231. RemoveEventHandler (callbackEventHandler);
  219232. callbackEventHandler = 0;
  219233. }
  219234. }
  219235. bool juce_postMessageToSystemQueue (void* message)
  219236. {
  219237. #if JUCE_COCOA
  219238. [[NSNotificationCenter defaultCenter] postNotificationName: juceMessageName
  219239. object: [NSData dataWithBytes: &message
  219240. length: (int) sizeof (message)]];
  219241. return true;
  219242. #else
  219243. jassert (mainQueue == GetMainEventQueue());
  219244. EventRef event;
  219245. if (CreateEvent (0, kJUCEClass, kJUCEKind, 0, kEventAttributeUserEvent, &event) == noErr)
  219246. {
  219247. SetEventParameter (event, 'mess', typeVoidPtr, sizeof (void*), &message);
  219248. const bool ok = PostEventToQueue (mainQueue, event, kEventPriorityStandard) == noErr;
  219249. ReleaseEvent (event);
  219250. return ok;
  219251. }
  219252. return false;
  219253. #endif
  219254. }
  219255. void MessageManager::broadcastMessage (const String& value) throw()
  219256. {
  219257. }
  219258. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  219259. void* data)
  219260. {
  219261. if (isThisTheMessageThread())
  219262. {
  219263. return (*callback) (data);
  219264. }
  219265. else
  219266. {
  219267. CallbackMessagePayload cmp;
  219268. cmp.function = callback;
  219269. cmp.parameter = data;
  219270. cmp.result = 0;
  219271. cmp.hasBeenExecuted = false;
  219272. #if JUCE_COCOA
  219273. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  219274. withObject: (id) &cmp
  219275. waitUntilDone: YES];
  219276. return cmp.result;
  219277. #else
  219278. jassert (mainQueue == GetMainEventQueue());
  219279. EventRef event;
  219280. if (CreateEvent (0, kJUCEClass, kCallbackKind, 0, kEventAttributeUserEvent, &event) == noErr)
  219281. {
  219282. void* v = &cmp;
  219283. SetEventParameter (event, 'mess', typeVoidPtr, sizeof (void*), &v);
  219284. if (PostEventToQueue (mainQueue, event, kEventPriorityStandard) == noErr)
  219285. {
  219286. while (! cmp.hasBeenExecuted)
  219287. Thread::yield();
  219288. return cmp.result;
  219289. }
  219290. }
  219291. return 0;
  219292. #endif
  219293. }
  219294. }
  219295. END_JUCE_NAMESPACE
  219296. /********* End of inlined file: juce_mac_Messaging.mm *********/
  219297. /********* Start of inlined file: juce_mac_WebBrowserComponent.mm *********/
  219298. #include <Cocoa/Cocoa.h>
  219299. #include <WebKit/WebKit.h>
  219300. #include <WebKit/HIWebView.h>
  219301. #include <WebKit/WebPolicyDelegate.h>
  219302. #include <WebKit/CarbonUtils.h>
  219303. BEGIN_JUCE_NAMESPACE
  219304. END_JUCE_NAMESPACE
  219305. @interface DownloadClickDetector : NSObject
  219306. {
  219307. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  219308. }
  219309. - (DownloadClickDetector*) initWithOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  219310. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  219311. request: (NSURLRequest*) request
  219312. frame: (WebFrame*) frame
  219313. decisionListener: (id<WebPolicyDecisionListener>) listener;
  219314. @end
  219315. @implementation DownloadClickDetector
  219316. - (DownloadClickDetector*) initWithOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  219317. {
  219318. [super init];
  219319. ownerComponent = ownerComponent_;
  219320. return self;
  219321. }
  219322. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id < WebPolicyDecisionListener >)listener
  219323. {
  219324. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  219325. if (ownerComponent->pageAboutToLoad (JUCE_NAMESPACE::String::fromUTF8 ((const JUCE_NAMESPACE::uint8*) [[url absoluteString] UTF8String])))
  219326. [listener use];
  219327. else
  219328. [listener ignore];
  219329. }
  219330. @end
  219331. BEGIN_JUCE_NAMESPACE
  219332. class WebBrowserComponentInternal : public Timer
  219333. {
  219334. public:
  219335. WebBrowserComponentInternal (WebBrowserComponent* owner_)
  219336. : owner (owner_),
  219337. view (0),
  219338. webView (0)
  219339. {
  219340. HIWebViewCreate (&view);
  219341. ComponentPeer* const peer = owner_->getPeer();
  219342. jassert (peer != 0);
  219343. if (view != 0 && peer != 0)
  219344. {
  219345. WindowRef parentWindow = (WindowRef) peer->getNativeHandle();
  219346. WindowAttributes attributes;
  219347. GetWindowAttributes (parentWindow, &attributes);
  219348. HIViewRef parentView = 0;
  219349. if ((attributes & kWindowCompositingAttribute) != 0)
  219350. {
  219351. HIViewRef root = HIViewGetRoot (parentWindow);
  219352. HIViewFindByID (root, kHIViewWindowContentID, &parentView);
  219353. if (parentView == 0)
  219354. parentView = root;
  219355. }
  219356. else
  219357. {
  219358. GetRootControl (parentWindow, (ControlRef*) &parentView);
  219359. if (parentView == 0)
  219360. CreateRootControl (parentWindow, (ControlRef*) &parentView);
  219361. }
  219362. HIViewAddSubview (parentView, view);
  219363. updateBounds();
  219364. show();
  219365. webView = HIWebViewGetWebView (view);
  219366. clickListener = [[DownloadClickDetector alloc] initWithOwner: owner_];
  219367. [webView setPolicyDelegate: clickListener];
  219368. }
  219369. startTimer (500);
  219370. }
  219371. ~WebBrowserComponentInternal()
  219372. {
  219373. [webView setPolicyDelegate: nil];
  219374. [clickListener release];
  219375. if (view != 0)
  219376. CFRelease (view);
  219377. }
  219378. // Horrific bodge-workaround for the fact that the webview somehow hangs onto key
  219379. // focus when you pop up a new window, no matter what that window does to
  219380. // try to grab focus for itself. This catches such a situation and forces
  219381. // focus away from the webview, then back to the place it should be..
  219382. void timerCallback()
  219383. {
  219384. WindowRef viewWindow = HIViewGetWindow (view);
  219385. WindowRef focusedWindow = GetUserFocusWindow();
  219386. if (focusedWindow != viewWindow)
  219387. {
  219388. if (HIViewSubtreeContainsFocus (view))
  219389. {
  219390. HIViewAdvanceFocus (HIViewGetRoot (viewWindow), 0);
  219391. HIViewAdvanceFocus (HIViewGetRoot (focusedWindow), 0);
  219392. }
  219393. }
  219394. }
  219395. void show()
  219396. {
  219397. HIViewSetVisible (view, true);
  219398. }
  219399. void hide()
  219400. {
  219401. HIViewSetVisible (view, false);
  219402. }
  219403. void goToURL (const String& url,
  219404. const StringArray* headers,
  219405. const MemoryBlock* postData)
  219406. {
  219407. char** headerNamesAsChars = 0;
  219408. char** headerValuesAsChars = 0;
  219409. int numHeaders = 0;
  219410. if (headers != 0)
  219411. {
  219412. numHeaders = headers->size();
  219413. headerNamesAsChars = (char**) juce_malloc (sizeof (char*) * numHeaders);
  219414. headerValuesAsChars = (char**) juce_malloc (sizeof (char*) * numHeaders);
  219415. int i;
  219416. for (i = 0; i < numHeaders; ++i)
  219417. {
  219418. const String headerName ((*headers)[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  219419. headerNamesAsChars[i] = (char*) juce_calloc (headerName.copyToUTF8 (0));
  219420. headerName.copyToUTF8 ((JUCE_NAMESPACE::uint8*) headerNamesAsChars[i]);
  219421. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  219422. headerValuesAsChars[i] = (char*) juce_calloc (headerValue.copyToUTF8 (0));
  219423. headerValue.copyToUTF8 ((JUCE_NAMESPACE::uint8*) headerValuesAsChars[i]);
  219424. }
  219425. }
  219426. sendWebViewToURL ((const char*) url.toUTF8(),
  219427. (const char**) headerNamesAsChars,
  219428. (const char**) headerValuesAsChars,
  219429. numHeaders,
  219430. postData != 0 ? (const char*) postData->getData() : 0,
  219431. postData != 0 ? postData->getSize() : 0);
  219432. for (int i = 0; i < numHeaders; ++i)
  219433. {
  219434. juce_free (headerNamesAsChars[i]);
  219435. juce_free (headerValuesAsChars[i]);
  219436. }
  219437. juce_free (headerNamesAsChars);
  219438. juce_free (headerValuesAsChars);
  219439. }
  219440. void goBack()
  219441. {
  219442. [webView goBack];
  219443. }
  219444. void goForward()
  219445. {
  219446. [webView goForward];
  219447. }
  219448. void stop()
  219449. {
  219450. [webView stopLoading: nil];
  219451. }
  219452. void updateBounds()
  219453. {
  219454. HIRect r;
  219455. r.origin.x = (float) owner->getScreenX() - owner->getTopLevelComponent()->getScreenX();
  219456. r.origin.y = (float) owner->getScreenY() - owner->getTopLevelComponent()->getScreenY();
  219457. r.size.width = (float) owner->getWidth();
  219458. r.size.height = (float) owner->getHeight();
  219459. HIViewSetFrame (view, &r);
  219460. }
  219461. private:
  219462. WebBrowserComponent* const owner;
  219463. HIViewRef view;
  219464. WebView* webView;
  219465. DownloadClickDetector* clickListener;
  219466. void sendWebViewToURL (const char* utf8URL,
  219467. const char** headerNames,
  219468. const char** headerValues,
  219469. int numHeaders,
  219470. const char* postData,
  219471. int postDataSize)
  219472. {
  219473. NSMutableURLRequest* r = [NSMutableURLRequest
  219474. requestWithURL: [NSURL URLWithString: [NSString stringWithUTF8String: utf8URL]]
  219475. cachePolicy: NSURLRequestUseProtocolCachePolicy
  219476. timeoutInterval: 30.0];
  219477. if (postDataSize > 0)
  219478. {
  219479. [ r setHTTPMethod: @"POST"];
  219480. [ r setHTTPBody: [NSData dataWithBytes: postData length: postDataSize]];
  219481. }
  219482. int i;
  219483. for (i = 0; i < numHeaders; ++i)
  219484. {
  219485. [ r setValue: [NSString stringWithUTF8String: headerValues[i]]
  219486. forHTTPHeaderField: [NSString stringWithUTF8String: headerNames[i]]];
  219487. }
  219488. [[webView mainFrame] stopLoading ];
  219489. [[webView mainFrame] loadRequest: r];
  219490. }
  219491. WebBrowserComponentInternal (const WebBrowserComponentInternal&);
  219492. const WebBrowserComponentInternal& operator= (const WebBrowserComponentInternal&);
  219493. };
  219494. WebBrowserComponent::WebBrowserComponent()
  219495. : browser (0),
  219496. associatedWindow (0),
  219497. blankPageShown (false)
  219498. {
  219499. setOpaque (true);
  219500. }
  219501. WebBrowserComponent::~WebBrowserComponent()
  219502. {
  219503. deleteBrowser();
  219504. }
  219505. void WebBrowserComponent::goToURL (const String& url,
  219506. const StringArray* headers,
  219507. const MemoryBlock* postData)
  219508. {
  219509. lastURL = url;
  219510. lastHeaders.clear();
  219511. if (headers != 0)
  219512. lastHeaders = *headers;
  219513. lastPostData.setSize (0);
  219514. if (postData != 0)
  219515. lastPostData = *postData;
  219516. blankPageShown = false;
  219517. if (browser != 0)
  219518. browser->goToURL (url, headers, postData);
  219519. }
  219520. void WebBrowserComponent::stop()
  219521. {
  219522. if (browser != 0)
  219523. browser->stop();
  219524. }
  219525. void WebBrowserComponent::goBack()
  219526. {
  219527. lastURL = String::empty;
  219528. blankPageShown = false;
  219529. if (browser != 0)
  219530. browser->goBack();
  219531. }
  219532. void WebBrowserComponent::goForward()
  219533. {
  219534. lastURL = String::empty;
  219535. if (browser != 0)
  219536. browser->goForward();
  219537. }
  219538. void WebBrowserComponent::paint (Graphics& g)
  219539. {
  219540. if (browser == 0)
  219541. g.fillAll (Colours::white);
  219542. }
  219543. void WebBrowserComponent::checkWindowAssociation()
  219544. {
  219545. void* const window = getWindowHandle();
  219546. if (window != associatedWindow
  219547. || (browser == 0 && window != 0))
  219548. {
  219549. associatedWindow = window;
  219550. deleteBrowser();
  219551. createBrowser();
  219552. }
  219553. if (browser != 0)
  219554. {
  219555. if (associatedWindow != 0 && isShowing())
  219556. {
  219557. browser->show();
  219558. if (blankPageShown)
  219559. goBack();
  219560. }
  219561. else
  219562. {
  219563. if (! blankPageShown)
  219564. {
  219565. // when the component becomes invisible, some stuff like flash
  219566. // carries on playing audio, so we need to force it onto a blank
  219567. // page to avoid this..
  219568. blankPageShown = true;
  219569. browser->goToURL ("about:blank", 0, 0);
  219570. }
  219571. browser->hide();
  219572. }
  219573. }
  219574. }
  219575. void WebBrowserComponent::createBrowser()
  219576. {
  219577. deleteBrowser();
  219578. if (isShowing())
  219579. {
  219580. WebInitForCarbon();
  219581. browser = new WebBrowserComponentInternal (this);
  219582. reloadLastURL();
  219583. }
  219584. }
  219585. void WebBrowserComponent::deleteBrowser()
  219586. {
  219587. deleteAndZero (browser);
  219588. }
  219589. void WebBrowserComponent::reloadLastURL()
  219590. {
  219591. if (lastURL.isNotEmpty())
  219592. {
  219593. goToURL (lastURL, &lastHeaders, &lastPostData);
  219594. lastURL = String::empty;
  219595. }
  219596. }
  219597. void WebBrowserComponent::updateBrowserPosition()
  219598. {
  219599. if (getPeer() != 0 && browser != 0)
  219600. browser->updateBounds();
  219601. }
  219602. void WebBrowserComponent::parentHierarchyChanged()
  219603. {
  219604. checkWindowAssociation();
  219605. }
  219606. void WebBrowserComponent::moved()
  219607. {
  219608. updateBrowserPosition();
  219609. }
  219610. void WebBrowserComponent::resized()
  219611. {
  219612. updateBrowserPosition();
  219613. }
  219614. void WebBrowserComponent::visibilityChanged()
  219615. {
  219616. checkWindowAssociation();
  219617. }
  219618. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  219619. {
  219620. return true;
  219621. }
  219622. END_JUCE_NAMESPACE
  219623. /********* End of inlined file: juce_mac_WebBrowserComponent.mm *********/
  219624. /********* Start of inlined file: juce_mac_Windowing.mm *********/
  219625. #include <Carbon/Carbon.h>
  219626. #include <IOKit/IOKitLib.h>
  219627. #include <IOKit/IOCFPlugIn.h>
  219628. #include <IOKit/hid/IOHIDLib.h>
  219629. #include <IOKit/hid/IOHIDKeys.h>
  219630. #include <fnmatch.h>
  219631. #if JUCE_OPENGL
  219632. #include <AGL/agl.h>
  219633. #endif
  219634. BEGIN_JUCE_NAMESPACE
  219635. #undef Point
  219636. const WindowRegionCode windowRegionToUse = kWindowContentRgn;
  219637. static HIObjectClassRef viewClassRef = 0;
  219638. static CFStringRef juceHiViewClassNameCFString = 0;
  219639. static ComponentPeer* juce_currentMouseTrackingPeer = 0;
  219640. static VoidArray keysCurrentlyDown;
  219641. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  219642. {
  219643. if (keysCurrentlyDown.contains ((void*) keyCode))
  219644. return true;
  219645. if (keyCode >= 'A' && keyCode <= 'Z'
  219646. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toLowerCase ((tchar) keyCode)))
  219647. return true;
  219648. if (keyCode >= 'a' && keyCode <= 'z'
  219649. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toUpperCase ((tchar) keyCode)))
  219650. return true;
  219651. return false;
  219652. }
  219653. static VoidArray minimisedWindows;
  219654. static void setWindowMinimised (WindowRef ref, const bool isMinimised)
  219655. {
  219656. if (isMinimised != minimisedWindows.contains (ref))
  219657. CollapseWindow (ref, isMinimised);
  219658. }
  219659. void juce_maximiseAllMinimisedWindows()
  219660. {
  219661. const VoidArray minWin (minimisedWindows);
  219662. for (int i = minWin.size(); --i >= 0;)
  219663. setWindowMinimised ((WindowRef) (minWin[i]), false);
  219664. }
  219665. class HIViewComponentPeer;
  219666. static HIViewComponentPeer* currentlyFocusedPeer = 0;
  219667. static int currentModifiers = 0;
  219668. static void updateModifiers (EventRef theEvent)
  219669. {
  219670. currentModifiers &= ~ (ModifierKeys::shiftModifier | ModifierKeys::ctrlModifier
  219671. | ModifierKeys::altModifier | ModifierKeys::commandModifier);
  219672. UInt32 m;
  219673. if (theEvent != 0)
  219674. GetEventParameter (theEvent, kEventParamKeyModifiers, typeUInt32, 0, sizeof(m), 0, &m);
  219675. else
  219676. m = GetCurrentEventKeyModifiers();
  219677. if ((m & (shiftKey | rightShiftKey)) != 0)
  219678. currentModifiers |= ModifierKeys::shiftModifier;
  219679. if ((m & (controlKey | rightControlKey)) != 0)
  219680. currentModifiers |= ModifierKeys::ctrlModifier;
  219681. if ((m & (optionKey | rightOptionKey)) != 0)
  219682. currentModifiers |= ModifierKeys::altModifier;
  219683. if ((m & cmdKey) != 0)
  219684. currentModifiers |= ModifierKeys::commandModifier;
  219685. }
  219686. void ModifierKeys::updateCurrentModifiers() throw()
  219687. {
  219688. currentModifierFlags = currentModifiers;
  219689. }
  219690. static int64 getEventTime (EventRef event)
  219691. {
  219692. const int64 millis = (int64) (1000.0 * (event != 0 ? GetEventTime (event)
  219693. : GetCurrentEventTime()));
  219694. static int64 offset = 0;
  219695. if (offset == 0)
  219696. offset = Time::currentTimeMillis() - millis;
  219697. return offset + millis;
  219698. }
  219699. class MacBitmapImage : public Image
  219700. {
  219701. public:
  219702. CGColorSpaceRef colourspace;
  219703. CGDataProviderRef provider;
  219704. MacBitmapImage (const PixelFormat format_,
  219705. const int w, const int h, const bool clearImage)
  219706. : Image (format_, w, h)
  219707. {
  219708. jassert (format_ == RGB || format_ == ARGB);
  219709. pixelStride = (format_ == RGB) ? 3 : 4;
  219710. lineStride = (w * pixelStride + 3) & ~3;
  219711. const int imageSize = lineStride * h;
  219712. if (clearImage)
  219713. imageData = (uint8*) juce_calloc (imageSize);
  219714. else
  219715. imageData = (uint8*) juce_malloc (imageSize);
  219716. //colourspace = CGColorSpaceCreateWithName (kCGColorSpaceUserRGB);
  219717. CMProfileRef prof;
  219718. CMGetSystemProfile (&prof);
  219719. colourspace = CGColorSpaceCreateWithPlatformColorSpace (prof);
  219720. provider = CGDataProviderCreateWithData (0, imageData, h * lineStride, 0);
  219721. CMCloseProfile (prof);
  219722. }
  219723. MacBitmapImage::~MacBitmapImage()
  219724. {
  219725. CGDataProviderRelease (provider);
  219726. CGColorSpaceRelease (colourspace);
  219727. juce_free (imageData);
  219728. imageData = 0; // to stop the base class freeing this
  219729. }
  219730. void blitToContext (CGContextRef context, const float dx, const float dy)
  219731. {
  219732. CGImageRef tempImage = CGImageCreate (getWidth(), getHeight(),
  219733. 8, pixelStride << 3, lineStride, colourspace,
  219734. #if MACOS_10_3_OR_EARLIER || JUCE_BIG_ENDIAN
  219735. hasAlphaChannel() ? kCGImageAlphaPremultipliedFirst
  219736. : kCGImageAlphaNone,
  219737. #else
  219738. hasAlphaChannel() ? kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst
  219739. : kCGImageAlphaNone,
  219740. #endif
  219741. provider, 0, false,
  219742. kCGRenderingIntentDefault);
  219743. HIRect r;
  219744. r.origin.x = dx;
  219745. r.origin.y = dy;
  219746. r.size.width = (float) getWidth();
  219747. r.size.height = (float) getHeight();
  219748. HIViewDrawCGImage (context, &r, tempImage);
  219749. CGImageRelease (tempImage);
  219750. }
  219751. juce_UseDebuggingNewOperator
  219752. };
  219753. class MouseCheckTimer : private Timer,
  219754. private DeletedAtShutdown
  219755. {
  219756. public:
  219757. MouseCheckTimer()
  219758. : lastX (0),
  219759. lastY (0)
  219760. {
  219761. lastPeerUnderMouse = 0;
  219762. resetMouseMoveChecker();
  219763. #if ! MACOS_10_2_OR_EARLIER
  219764. // Just putting this in here because it's a convenient object that'll get deleted at shutdown
  219765. CGDisplayRegisterReconfigurationCallback (&displayChangeCallback, 0);
  219766. #endif
  219767. }
  219768. ~MouseCheckTimer()
  219769. {
  219770. #if ! MACOS_10_2_OR_EARLIER
  219771. CGDisplayRemoveReconfigurationCallback (&displayChangeCallback, 0);
  219772. #endif
  219773. clearSingletonInstance();
  219774. }
  219775. juce_DeclareSingleton_SingleThreaded_Minimal (MouseCheckTimer)
  219776. bool hasEverHadAMouseMove;
  219777. void moved (HIViewComponentPeer* const peer)
  219778. {
  219779. if (hasEverHadAMouseMove)
  219780. startTimer (200);
  219781. lastPeerUnderMouse = peer;
  219782. }
  219783. void resetMouseMoveChecker()
  219784. {
  219785. hasEverHadAMouseMove = false;
  219786. startTimer (1000 / 16);
  219787. }
  219788. void timerCallback();
  219789. private:
  219790. HIViewComponentPeer* lastPeerUnderMouse;
  219791. int lastX, lastY;
  219792. #if ! MACOS_10_2_OR_EARLIER
  219793. static void displayChangeCallback (CGDirectDisplayID, CGDisplayChangeSummaryFlags flags, void*)
  219794. {
  219795. Desktop::getInstance().refreshMonitorSizes();
  219796. }
  219797. #endif
  219798. };
  219799. juce_ImplementSingleton_SingleThreaded (MouseCheckTimer)
  219800. #if JUCE_QUICKTIME
  219801. extern void OfferMouseClickToQuickTime (WindowRef window, ::Point where, long when, long modifiers,
  219802. Component* topLevelComp);
  219803. #endif
  219804. class HIViewComponentPeer : public ComponentPeer,
  219805. private Timer
  219806. {
  219807. public:
  219808. HIViewComponentPeer (Component* const component,
  219809. const int windowStyleFlags,
  219810. HIViewRef viewToAttachTo)
  219811. : ComponentPeer (component, windowStyleFlags),
  219812. fullScreen (false),
  219813. isCompositingWindow (false),
  219814. windowRef (0),
  219815. viewRef (0)
  219816. {
  219817. repainter = new RepaintManager (this);
  219818. eventHandlerRef = 0;
  219819. if (viewToAttachTo != 0)
  219820. {
  219821. isSharedWindow = true;
  219822. }
  219823. else
  219824. {
  219825. isSharedWindow = false;
  219826. WindowRef newWindow = createNewWindow (windowStyleFlags);
  219827. GetRootControl (newWindow, (ControlRef*) &viewToAttachTo);
  219828. jassert (viewToAttachTo != 0);
  219829. HIViewRef growBox = 0;
  219830. HIViewFindByID (HIViewGetRoot (newWindow), kHIViewWindowGrowBoxID, &growBox);
  219831. if (growBox != 0)
  219832. HIGrowBoxViewSetTransparent (growBox, true);
  219833. }
  219834. createNewHIView();
  219835. HIViewAddSubview (viewToAttachTo, viewRef);
  219836. HIViewSetVisible (viewRef, component->isVisible());
  219837. setTitle (component->getName());
  219838. if (component->isVisible() && ! isSharedWindow)
  219839. {
  219840. ShowWindow (windowRef);
  219841. ActivateWindow (windowRef, component->getWantsKeyboardFocus());
  219842. }
  219843. }
  219844. ~HIViewComponentPeer()
  219845. {
  219846. minimisedWindows.removeValue (windowRef);
  219847. if (IsValidWindowPtr (windowRef))
  219848. {
  219849. if (! isSharedWindow)
  219850. {
  219851. CFRelease (viewRef);
  219852. viewRef = 0;
  219853. DisposeWindow (windowRef);
  219854. }
  219855. else
  219856. {
  219857. if (eventHandlerRef != 0)
  219858. RemoveEventHandler (eventHandlerRef);
  219859. CFRelease (viewRef);
  219860. viewRef = 0;
  219861. }
  219862. windowRef = 0;
  219863. }
  219864. if (currentlyFocusedPeer == this)
  219865. currentlyFocusedPeer = 0;
  219866. delete repainter;
  219867. }
  219868. void* getNativeHandle() const
  219869. {
  219870. return windowRef;
  219871. }
  219872. void setVisible (bool shouldBeVisible)
  219873. {
  219874. HIViewSetVisible (viewRef, shouldBeVisible);
  219875. if ((! isSharedWindow) && IsValidWindowPtr (windowRef))
  219876. {
  219877. if (shouldBeVisible)
  219878. ShowWindow (windowRef);
  219879. else
  219880. HideWindow (windowRef);
  219881. resizeViewToFitWindow();
  219882. // If nothing else is focused, then grab the focus too
  219883. if (shouldBeVisible
  219884. && Component::getCurrentlyFocusedComponent() == 0
  219885. && Process::isForegroundProcess())
  219886. {
  219887. component->toFront (true);
  219888. }
  219889. }
  219890. }
  219891. void setTitle (const String& title)
  219892. {
  219893. if ((! isSharedWindow) && IsValidWindowPtr (windowRef))
  219894. {
  219895. CFStringRef t = PlatformUtilities::juceStringToCFString (title);
  219896. SetWindowTitleWithCFString (windowRef, t);
  219897. CFRelease (t);
  219898. }
  219899. }
  219900. void setPosition (int x, int y)
  219901. {
  219902. if (isSharedWindow)
  219903. {
  219904. HIViewPlaceInSuperviewAt (viewRef, x, y);
  219905. }
  219906. else if (IsValidWindowPtr (windowRef))
  219907. {
  219908. Rect r;
  219909. GetWindowBounds (windowRef, windowRegionToUse, &r);
  219910. r.right += x - r.left;
  219911. r.bottom += y - r.top;
  219912. r.left = x;
  219913. r.top = y;
  219914. SetWindowBounds (windowRef, windowRegionToUse, &r);
  219915. }
  219916. }
  219917. void setSize (int w, int h)
  219918. {
  219919. w = jmax (0, w);
  219920. h = jmax (0, h);
  219921. if (w != getComponent()->getWidth()
  219922. || h != getComponent()->getHeight())
  219923. {
  219924. repainter->repaint (0, 0, w, h);
  219925. }
  219926. if (isSharedWindow)
  219927. {
  219928. HIRect r;
  219929. HIViewGetFrame (viewRef, &r);
  219930. r.size.width = (float) w;
  219931. r.size.height = (float) h;
  219932. HIViewSetFrame (viewRef, &r);
  219933. }
  219934. else if (IsValidWindowPtr (windowRef))
  219935. {
  219936. Rect r;
  219937. GetWindowBounds (windowRef, windowRegionToUse, &r);
  219938. r.right = r.left + w;
  219939. r.bottom = r.top + h;
  219940. SetWindowBounds (windowRef, windowRegionToUse, &r);
  219941. }
  219942. }
  219943. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  219944. {
  219945. fullScreen = isNowFullScreen;
  219946. w = jmax (0, w);
  219947. h = jmax (0, h);
  219948. if (w != getComponent()->getWidth()
  219949. || h != getComponent()->getHeight())
  219950. {
  219951. repainter->repaint (0, 0, w, h);
  219952. }
  219953. if (isSharedWindow)
  219954. {
  219955. HIRect r;
  219956. r.origin.x = (float) x;
  219957. r.origin.y = (float) y;
  219958. r.size.width = (float) w;
  219959. r.size.height = (float) h;
  219960. HIViewSetFrame (viewRef, &r);
  219961. }
  219962. else if (IsValidWindowPtr (windowRef))
  219963. {
  219964. Rect r;
  219965. r.left = x;
  219966. r.top = y;
  219967. r.right = x + w;
  219968. r.bottom = y + h;
  219969. SetWindowBounds (windowRef, windowRegionToUse, &r);
  219970. }
  219971. }
  219972. void getBounds (int& x, int& y, int& w, int& h, const bool global) const
  219973. {
  219974. HIRect hiViewPos;
  219975. HIViewGetFrame (viewRef, &hiViewPos);
  219976. if (global)
  219977. {
  219978. HIViewRef content = 0;
  219979. HIViewFindByID (HIViewGetRoot (windowRef), kHIViewWindowContentID, &content);
  219980. HIPoint p = { 0.0f, 0.0f };
  219981. HIViewConvertPoint (&p, viewRef, content);
  219982. x = (int) p.x;
  219983. y = (int) p.y;
  219984. if (IsValidWindowPtr (windowRef))
  219985. {
  219986. Rect windowPos;
  219987. GetWindowBounds (windowRef, kWindowContentRgn, &windowPos);
  219988. x += windowPos.left;
  219989. y += windowPos.top;
  219990. }
  219991. }
  219992. else
  219993. {
  219994. x = (int) hiViewPos.origin.x;
  219995. y = (int) hiViewPos.origin.y;
  219996. }
  219997. w = (int) hiViewPos.size.width;
  219998. h = (int) hiViewPos.size.height;
  219999. }
  220000. void getBounds (int& x, int& y, int& w, int& h) const
  220001. {
  220002. getBounds (x, y, w, h, ! isSharedWindow);
  220003. }
  220004. int getScreenX() const
  220005. {
  220006. int x, y, w, h;
  220007. getBounds (x, y, w, h, true);
  220008. return x;
  220009. }
  220010. int getScreenY() const
  220011. {
  220012. int x, y, w, h;
  220013. getBounds (x, y, w, h, true);
  220014. return y;
  220015. }
  220016. void relativePositionToGlobal (int& x, int& y)
  220017. {
  220018. int wx, wy, ww, wh;
  220019. getBounds (wx, wy, ww, wh, true);
  220020. x += wx;
  220021. y += wy;
  220022. }
  220023. void globalPositionToRelative (int& x, int& y)
  220024. {
  220025. int wx, wy, ww, wh;
  220026. getBounds (wx, wy, ww, wh, true);
  220027. x -= wx;
  220028. y -= wy;
  220029. }
  220030. void setMinimised (bool shouldBeMinimised)
  220031. {
  220032. if (! isSharedWindow)
  220033. setWindowMinimised (windowRef, shouldBeMinimised);
  220034. }
  220035. bool isMinimised() const
  220036. {
  220037. return minimisedWindows.contains (windowRef);
  220038. }
  220039. void setFullScreen (bool shouldBeFullScreen)
  220040. {
  220041. if (! isSharedWindow)
  220042. {
  220043. Rectangle r (lastNonFullscreenBounds);
  220044. setMinimised (false);
  220045. if (fullScreen != shouldBeFullScreen)
  220046. {
  220047. if (shouldBeFullScreen)
  220048. r = Desktop::getInstance().getMainMonitorArea();
  220049. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  220050. if (r != getComponent()->getBounds() && ! r.isEmpty())
  220051. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  220052. }
  220053. }
  220054. }
  220055. bool isFullScreen() const
  220056. {
  220057. return fullScreen;
  220058. }
  220059. bool contains (int x, int y, bool trueIfInAChildWindow) const
  220060. {
  220061. if (((unsigned int) x) >= (unsigned int) component->getWidth()
  220062. || ((unsigned int) y) >= (unsigned int) component->getHeight()
  220063. || ! IsValidWindowPtr (windowRef))
  220064. return false;
  220065. Rect r;
  220066. GetWindowBounds (windowRef, windowRegionToUse, &r);
  220067. ::Point p;
  220068. p.h = r.left + x;
  220069. p.v = r.top + y;
  220070. WindowRef ref2 = 0;
  220071. FindWindow (p, &ref2);
  220072. if (windowRef != ref2)
  220073. return false;
  220074. if (trueIfInAChildWindow)
  220075. return true;
  220076. HIPoint p2;
  220077. p2.x = (float) x;
  220078. p2.y = (float) y;
  220079. HIViewRef hit;
  220080. HIViewGetSubviewHit (viewRef, &p2, true, &hit);
  220081. return hit == 0 || hit == viewRef;
  220082. }
  220083. const BorderSize getFrameSize() const
  220084. {
  220085. return BorderSize();
  220086. }
  220087. bool setAlwaysOnTop (bool alwaysOnTop)
  220088. {
  220089. // can't do this so return false and let the component create a new window
  220090. return false;
  220091. }
  220092. void toFront (bool makeActiveWindow)
  220093. {
  220094. makeActiveWindow = makeActiveWindow
  220095. && component->isValidComponent()
  220096. && (component->getWantsKeyboardFocus()
  220097. || component->isCurrentlyModal());
  220098. if (windowRef != FrontWindow()
  220099. || (makeActiveWindow && ! IsWindowActive (windowRef))
  220100. || ! Process::isForegroundProcess())
  220101. {
  220102. if (! Process::isForegroundProcess())
  220103. {
  220104. ProcessSerialNumber psn;
  220105. GetCurrentProcess (&psn);
  220106. SetFrontProcessWithOptions (&psn, kSetFrontProcessFrontWindowOnly);
  220107. }
  220108. if (IsValidWindowPtr (windowRef))
  220109. {
  220110. if (makeActiveWindow)
  220111. {
  220112. SelectWindow (windowRef);
  220113. SetUserFocusWindow (windowRef);
  220114. HIViewAdvanceFocus (viewRef, 0);
  220115. }
  220116. else
  220117. {
  220118. BringToFront (windowRef);
  220119. }
  220120. handleBroughtToFront();
  220121. }
  220122. }
  220123. }
  220124. void toBehind (ComponentPeer* other)
  220125. {
  220126. HIViewComponentPeer* const otherWindow = dynamic_cast <HIViewComponentPeer*> (other);
  220127. if (other != 0 && windowRef != 0 && otherWindow->windowRef != 0)
  220128. {
  220129. if (windowRef == otherWindow->windowRef)
  220130. {
  220131. HIViewSetZOrder (viewRef, kHIViewZOrderBelow, otherWindow->viewRef);
  220132. }
  220133. else
  220134. {
  220135. SendBehind (windowRef, otherWindow->windowRef);
  220136. }
  220137. }
  220138. }
  220139. void setIcon (const Image& /*newIcon*/)
  220140. {
  220141. // to do..
  220142. }
  220143. void viewFocusGain()
  220144. {
  220145. const MessageManagerLock messLock;
  220146. if (currentlyFocusedPeer != this)
  220147. {
  220148. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  220149. currentlyFocusedPeer->handleFocusLoss();
  220150. currentlyFocusedPeer = this;
  220151. handleFocusGain();
  220152. }
  220153. }
  220154. void viewFocusLoss()
  220155. {
  220156. if (currentlyFocusedPeer == this)
  220157. {
  220158. currentlyFocusedPeer = 0;
  220159. handleFocusLoss();
  220160. }
  220161. }
  220162. bool isFocused() const
  220163. {
  220164. return windowRef == GetUserFocusWindow()
  220165. && HIViewSubtreeContainsFocus (viewRef);
  220166. }
  220167. void grabFocus()
  220168. {
  220169. if ((! isFocused()) && IsValidWindowPtr (windowRef))
  220170. {
  220171. SetUserFocusWindow (windowRef);
  220172. HIViewAdvanceFocus (viewRef, 0);
  220173. }
  220174. }
  220175. void textInputRequired (int /*x*/, int /*y*/)
  220176. {
  220177. }
  220178. void repaint (int x, int y, int w, int h)
  220179. {
  220180. if (Rectangle::intersectRectangles (x, y, w, h,
  220181. 0, 0,
  220182. getComponent()->getWidth(),
  220183. getComponent()->getHeight()))
  220184. {
  220185. if ((getStyleFlags() & windowRepaintedExplictly) == 0)
  220186. {
  220187. if (isCompositingWindow)
  220188. {
  220189. #if MACOS_10_3_OR_EARLIER
  220190. RgnHandle rgn = NewRgn();
  220191. SetRectRgn (rgn, x, y, x + w, y + h);
  220192. HIViewSetNeedsDisplayInRegion (viewRef, rgn, true);
  220193. DisposeRgn (rgn);
  220194. #else
  220195. HIRect r;
  220196. r.origin.x = x;
  220197. r.origin.y = y;
  220198. r.size.width = w;
  220199. r.size.height = h;
  220200. HIViewSetNeedsDisplayInRect (viewRef, &r, true);
  220201. #endif
  220202. }
  220203. else
  220204. {
  220205. if (! isTimerRunning())
  220206. startTimer (20);
  220207. }
  220208. }
  220209. repainter->repaint (x, y, w, h);
  220210. }
  220211. }
  220212. void timerCallback()
  220213. {
  220214. performAnyPendingRepaintsNow();
  220215. }
  220216. void performAnyPendingRepaintsNow()
  220217. {
  220218. stopTimer();
  220219. if (component->isVisible())
  220220. {
  220221. #if MACOS_10_2_OR_EARLIER
  220222. if (! isCompositingWindow)
  220223. {
  220224. Rect w;
  220225. GetWindowBounds (windowRef, windowRegionToUse, &w);
  220226. const int offsetInWindowX = component->getScreenX() - getScreenX();
  220227. const int offsetInWindowY = component->getScreenY() - getScreenY();
  220228. for (RectangleList::Iterator i (repainter->getRegionsNeedingRepaint()); i.next();)
  220229. {
  220230. const Rectangle& r = *i.getRectangle();
  220231. w.left = offsetInWindowX + r.getX();
  220232. w.top = offsetInWindowY + r.getY();
  220233. w.right = offsetInWindowX + r.getRight();
  220234. w.bottom = offsetInWindowY + r.getBottom();
  220235. InvalWindowRect (windowRef, &w);
  220236. }
  220237. }
  220238. else
  220239. {
  220240. EventRef theEvent;
  220241. EventTypeSpec eventTypes[1];
  220242. eventTypes[0].eventClass = kEventClassControl;
  220243. eventTypes[0].eventKind = kEventControlDraw;
  220244. int n = 3;
  220245. while (--n >= 0
  220246. && ReceiveNextEvent (1, eventTypes, kEventDurationNoWait, true, &theEvent) == noErr)
  220247. {
  220248. if (GetEventClass (theEvent) == kEventClassAppleEvent)
  220249. {
  220250. EventRecord eventRec;
  220251. if (ConvertEventRefToEventRecord (theEvent, &eventRec))
  220252. AEProcessAppleEvent (&eventRec);
  220253. }
  220254. else
  220255. {
  220256. EventTargetRef theTarget = GetEventDispatcherTarget();
  220257. SendEventToEventTarget (theEvent, theTarget);
  220258. }
  220259. ReleaseEvent (theEvent);
  220260. }
  220261. }
  220262. #else
  220263. if (HIViewGetNeedsDisplay (viewRef) || repainter->isRepaintNeeded())
  220264. HIViewRender (viewRef);
  220265. #endif
  220266. }
  220267. }
  220268. juce_UseDebuggingNewOperator
  220269. WindowRef windowRef;
  220270. HIViewRef viewRef;
  220271. private:
  220272. EventHandlerRef eventHandlerRef;
  220273. bool fullScreen, isSharedWindow, isCompositingWindow;
  220274. StringArray dragAndDropFiles;
  220275. class RepaintManager : public Timer
  220276. {
  220277. public:
  220278. RepaintManager (HIViewComponentPeer* const peer_)
  220279. : peer (peer_),
  220280. image (0)
  220281. {
  220282. }
  220283. ~RepaintManager()
  220284. {
  220285. delete image;
  220286. }
  220287. void timerCallback()
  220288. {
  220289. stopTimer();
  220290. deleteAndZero (image);
  220291. }
  220292. void repaint (int x, int y, int w, int h)
  220293. {
  220294. regionsNeedingRepaint.add (x, y, w, h);
  220295. }
  220296. bool isRepaintNeeded() const throw()
  220297. {
  220298. return ! regionsNeedingRepaint.isEmpty();
  220299. }
  220300. void repaintAnyRemainingRegions()
  220301. {
  220302. // if any regions have been invaldated during the paint callback,
  220303. // we need to repaint them explicitly because the mac throws this
  220304. // stuff away
  220305. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  220306. {
  220307. const Rectangle& r = *i.getRectangle();
  220308. peer->repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  220309. }
  220310. }
  220311. void paint (CGContextRef cgContext, int x, int y, int w, int h)
  220312. {
  220313. if (w > 0 && h > 0)
  220314. {
  220315. bool refresh = false;
  220316. int imW = image != 0 ? image->getWidth() : 0;
  220317. int imH = image != 0 ? image->getHeight() : 0;
  220318. if (imW < w || imH < h)
  220319. {
  220320. imW = jmin (peer->getComponent()->getWidth(), (w + 31) & ~31);
  220321. imH = jmin (peer->getComponent()->getHeight(), (h + 31) & ~31);
  220322. delete image;
  220323. image = new MacBitmapImage (peer->getComponent()->isOpaque() ? Image::RGB
  220324. : Image::ARGB,
  220325. imW, imH, false);
  220326. refresh = true;
  220327. }
  220328. else if (imageX > x || imageY > y
  220329. || imageX + imW < x + w
  220330. || imageY + imH < y + h)
  220331. {
  220332. refresh = true;
  220333. }
  220334. if (refresh)
  220335. {
  220336. regionsNeedingRepaint.clear();
  220337. regionsNeedingRepaint.addWithoutMerging (Rectangle (x, y, imW, imH));
  220338. imageX = x;
  220339. imageY = y;
  220340. }
  220341. LowLevelGraphicsSoftwareRenderer context (*image);
  220342. context.setOrigin (-imageX, -imageY);
  220343. if (context.reduceClipRegion (regionsNeedingRepaint))
  220344. {
  220345. regionsNeedingRepaint.clear();
  220346. if (! peer->getComponent()->isOpaque())
  220347. {
  220348. for (RectangleList::Iterator i (*context.getRawClipRegion()); i.next();)
  220349. {
  220350. const Rectangle& r = *i.getRectangle();
  220351. image->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  220352. }
  220353. }
  220354. regionsNeedingRepaint.clear();
  220355. peer->clearMaskedRegion();
  220356. peer->handlePaint (context);
  220357. }
  220358. else
  220359. {
  220360. regionsNeedingRepaint.clear();
  220361. }
  220362. if (! peer->maskedRegion.isEmpty())
  220363. {
  220364. RectangleList total (Rectangle (x, y, w, h));
  220365. total.subtract (peer->maskedRegion);
  220366. CGRect* rects = (CGRect*) juce_malloc (sizeof (CGRect) * total.getNumRectangles());
  220367. int n = 0;
  220368. for (RectangleList::Iterator i (total); i.next();)
  220369. {
  220370. const Rectangle& r = *i.getRectangle();
  220371. rects[n].origin.x = (int) r.getX();
  220372. rects[n].origin.y = (int) r.getY();
  220373. rects[n].size.width = roundFloatToInt (r.getWidth());
  220374. rects[n++].size.height = roundFloatToInt (r.getHeight());
  220375. }
  220376. CGContextClipToRects (cgContext, rects, n);
  220377. juce_free (rects);
  220378. }
  220379. if (peer->isSharedWindow)
  220380. {
  220381. CGRect clip;
  220382. clip.origin.x = x;
  220383. clip.origin.y = y;
  220384. clip.size.width = jmin (w, peer->getComponent()->getWidth() - x);
  220385. clip.size.height = jmin (h, peer->getComponent()->getHeight() - y);
  220386. CGContextClipToRect (cgContext, clip);
  220387. }
  220388. image->blitToContext (cgContext, imageX, imageY);
  220389. }
  220390. startTimer (3000);
  220391. }
  220392. private:
  220393. HIViewComponentPeer* const peer;
  220394. MacBitmapImage* image;
  220395. int imageX, imageY;
  220396. RectangleList regionsNeedingRepaint;
  220397. RepaintManager (const RepaintManager&);
  220398. const RepaintManager& operator= (const RepaintManager&);
  220399. };
  220400. RepaintManager* repainter;
  220401. friend class RepaintManager;
  220402. static OSStatus handleFrameRepaintEvent (EventHandlerCallRef myHandler,
  220403. EventRef theEvent,
  220404. void* userData)
  220405. {
  220406. // don't draw the frame..
  220407. return noErr;
  220408. }
  220409. OSStatus handleKeyEvent (EventRef theEvent, juce_wchar textCharacter)
  220410. {
  220411. updateModifiers (theEvent);
  220412. UniChar unicodeChars [4];
  220413. zeromem (unicodeChars, sizeof (unicodeChars));
  220414. GetEventParameter (theEvent, kEventParamKeyUnicodes, typeUnicodeText, 0, sizeof (unicodeChars), 0, unicodeChars);
  220415. int keyCode = (int) (unsigned int) unicodeChars[0];
  220416. UInt32 rawKey = 0;
  220417. GetEventParameter (theEvent, kEventParamKeyCode, typeUInt32, 0, sizeof (UInt32), 0, &rawKey);
  220418. if ((currentModifiers & ModifierKeys::ctrlModifier) != 0
  220419. && keyCode >= 1 && keyCode <= 26)
  220420. {
  220421. keyCode += ('A' - 1);
  220422. }
  220423. else
  220424. {
  220425. static const int keyTranslations[] =
  220426. {
  220427. 0, 's', 'd', 'f', 'h', 'g', 'z', 'x', 'c', 'v', 0xa7, 'b',
  220428. 'q', 'w', 'e', 'r', 'y', 't', '1', '2', '3', '4', '6', '5',
  220429. '=', '9', '7', '-', '8', '0', ']', 'o', 'u', '[', 'i', 'p',
  220430. KeyPress::returnKey, 'l', 'j', '\'', 'k', ';', '\\', ',', '/',
  220431. 'n', 'm', '.', 0, KeyPress::spaceKey, '`', KeyPress::backspaceKey, 0, 0, 0, 0,
  220432. 0, 0, 0, 0, 0, 0, 0, 0, 0, KeyPress::numberPadDecimalPoint,
  220433. 0, KeyPress::numberPadMultiply, 0, KeyPress::numberPadAdd,
  220434. 0, KeyPress::numberPadDelete, 0, 0, 0, KeyPress::numberPadDivide, KeyPress::returnKey,
  220435. 0, KeyPress::numberPadSubtract, 0, 0, KeyPress::numberPadEquals, KeyPress::numberPad0,
  220436. KeyPress::numberPad1, KeyPress::numberPad2, KeyPress::numberPad3,
  220437. KeyPress::numberPad4, KeyPress::numberPad5, KeyPress::numberPad6,
  220438. KeyPress::numberPad7, 0, KeyPress::numberPad8, KeyPress::numberPad9,
  220439. 0, 0, 0, KeyPress::F5Key, KeyPress::F6Key, KeyPress::F7Key, KeyPress::F3Key,
  220440. KeyPress::F8Key, KeyPress::F9Key, 0, KeyPress::F11Key, 0, KeyPress::F13Key,
  220441. KeyPress::F16Key, KeyPress::F14Key, 0, KeyPress::F10Key, 0, KeyPress::F12Key,
  220442. 0, KeyPress::F15Key, 0, KeyPress::homeKey, KeyPress::pageUpKey, 0, KeyPress::F4Key,
  220443. KeyPress::endKey, KeyPress::F2Key, KeyPress::pageDownKey, KeyPress::F1Key,
  220444. KeyPress::leftKey, KeyPress::rightKey, KeyPress::downKey, KeyPress::upKey, 0
  220445. };
  220446. if (((unsigned int) rawKey) < (unsigned int) numElementsInArray (keyTranslations)
  220447. && keyTranslations [rawKey] != 0)
  220448. {
  220449. keyCode = keyTranslations [rawKey];
  220450. }
  220451. if ((rawKey == 0 && textCharacter != 0)
  220452. || (CharacterFunctions::isLetterOrDigit ((juce_wchar) keyCode)
  220453. && CharacterFunctions::isLetterOrDigit (textCharacter))) // correction for azerty-type layouts..
  220454. {
  220455. keyCode = CharacterFunctions::toLowerCase (textCharacter);
  220456. }
  220457. }
  220458. if ((currentModifiers & (ModifierKeys::commandModifier | ModifierKeys::ctrlModifier)) != 0)
  220459. textCharacter = 0;
  220460. static juce_wchar lastTextCharacter = 0;
  220461. switch (GetEventKind (theEvent))
  220462. {
  220463. case kEventRawKeyDown:
  220464. {
  220465. keysCurrentlyDown.addIfNotAlreadyThere ((void*) keyCode);
  220466. lastTextCharacter = textCharacter;
  220467. const bool used1 = handleKeyUpOrDown();
  220468. const bool used2 = handleKeyPress (keyCode, textCharacter);
  220469. if (used1 || used2)
  220470. return noErr;
  220471. break;
  220472. }
  220473. case kEventRawKeyUp:
  220474. keysCurrentlyDown.removeValue ((void*) keyCode);
  220475. lastTextCharacter = 0;
  220476. if (handleKeyUpOrDown())
  220477. return noErr;
  220478. break;
  220479. case kEventRawKeyRepeat:
  220480. if (handleKeyPress (keyCode, lastTextCharacter))
  220481. return noErr;
  220482. break;
  220483. case kEventRawKeyModifiersChanged:
  220484. handleModifierKeysChange();
  220485. break;
  220486. default:
  220487. jassertfalse
  220488. break;
  220489. }
  220490. return eventNotHandledErr;
  220491. }
  220492. OSStatus handleTextInputEvent (EventRef theEvent)
  220493. {
  220494. UInt32 numBytesRequired = 0;
  220495. GetEventParameter (theEvent, kEventParamTextInputSendText, typeUnicodeText, 0, 0, &numBytesRequired, 0);
  220496. MemoryBlock buffer (numBytesRequired, true);
  220497. UniChar* const uc = (UniChar*) buffer.getData();
  220498. GetEventParameter (theEvent, kEventParamTextInputSendText, typeUnicodeText, 0, numBytesRequired, &numBytesRequired, uc);
  220499. EventRef originalEvent;
  220500. GetEventParameter (theEvent, kEventParamTextInputSendKeyboardEvent, typeEventRef, 0, sizeof (originalEvent), 0, &originalEvent);
  220501. OSStatus res = noErr;
  220502. for (int i = 0; i < numBytesRequired / sizeof (UniChar); ++i)
  220503. res = handleKeyEvent (originalEvent, (juce_wchar) uc[i]);
  220504. return res;
  220505. }
  220506. OSStatus handleMouseEvent (EventHandlerCallRef callRef, EventRef theEvent)
  220507. {
  220508. MouseCheckTimer::getInstance()->moved (this);
  220509. ::Point where;
  220510. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof (::Point), 0, &where);
  220511. int x = where.h;
  220512. int y = where.v;
  220513. globalPositionToRelative (x, y);
  220514. int64 time = getEventTime (theEvent);
  220515. switch (GetEventKind (theEvent))
  220516. {
  220517. case kEventMouseMoved:
  220518. MouseCheckTimer::getInstance()->hasEverHadAMouseMove = true;
  220519. updateModifiers (theEvent);
  220520. handleMouseMove (x, y, time);
  220521. break;
  220522. case kEventMouseDragged:
  220523. updateModifiers (theEvent);
  220524. handleMouseDrag (x, y, time);
  220525. break;
  220526. case kEventMouseDown:
  220527. {
  220528. if (! Process::isForegroundProcess())
  220529. {
  220530. ProcessSerialNumber psn;
  220531. GetCurrentProcess (&psn);
  220532. SetFrontProcessWithOptions (&psn, kSetFrontProcessFrontWindowOnly);
  220533. toFront (true);
  220534. }
  220535. #if JUCE_QUICKTIME
  220536. {
  220537. long mods;
  220538. GetEventParameter (theEvent, kEventParamKeyModifiers, typeUInt32, 0, sizeof (mods), 0, &mods);
  220539. ::Point where;
  220540. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof (::Point), 0, &where);
  220541. OfferMouseClickToQuickTime (windowRef, where, EventTimeToTicks (GetEventTime (theEvent)), mods, component);
  220542. }
  220543. #endif
  220544. if (component->isBroughtToFrontOnMouseClick()
  220545. && ! component->isCurrentlyBlockedByAnotherModalComponent())
  220546. {
  220547. //ActivateWindow (windowRef, true);
  220548. SelectWindow (windowRef);
  220549. }
  220550. EventMouseButton button;
  220551. GetEventParameter (theEvent, kEventParamMouseButton, typeMouseButton, 0, sizeof (EventMouseButton), 0, &button);
  220552. // need to clear all these flags because sometimes the mac can swallow (right) mouse-up events and
  220553. // this makes a button get stuck down. Since there's no other way to tell what buttons are down,
  220554. // this is all I can think of doing about it..
  220555. currentModifiers &= ~(ModifierKeys::leftButtonModifier | ModifierKeys::rightButtonModifier | ModifierKeys::middleButtonModifier);
  220556. if (button == kEventMouseButtonPrimary)
  220557. currentModifiers |= ModifierKeys::leftButtonModifier;
  220558. else if (button == kEventMouseButtonSecondary)
  220559. currentModifiers |= ModifierKeys::rightButtonModifier;
  220560. else if (button == kEventMouseButtonTertiary)
  220561. currentModifiers |= ModifierKeys::middleButtonModifier;
  220562. updateModifiers (theEvent);
  220563. juce_currentMouseTrackingPeer = this; // puts the message dispatcher into mouse-tracking mode..
  220564. handleMouseDown (x, y, time);
  220565. break;
  220566. }
  220567. case kEventMouseUp:
  220568. {
  220569. const int oldModifiers = currentModifiers;
  220570. EventMouseButton button;
  220571. GetEventParameter (theEvent, kEventParamMouseButton, typeMouseButton, 0, sizeof (EventMouseButton), 0, &button);
  220572. if (button == kEventMouseButtonPrimary)
  220573. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  220574. else if (button == kEventMouseButtonSecondary)
  220575. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  220576. updateModifiers (theEvent);
  220577. juce_currentMouseTrackingPeer = 0;
  220578. handleMouseUp (oldModifiers, x, y, time);
  220579. break;
  220580. }
  220581. case kEventMouseWheelMoved:
  220582. {
  220583. EventMouseWheelAxis axis;
  220584. GetEventParameter (theEvent, kEventParamMouseWheelAxis, typeMouseWheelAxis, 0, sizeof (axis), 0, &axis);
  220585. SInt32 delta;
  220586. GetEventParameter (theEvent, kEventParamMouseWheelDelta,
  220587. typeLongInteger, 0, sizeof (delta), 0, &delta);
  220588. updateModifiers (theEvent);
  220589. handleMouseWheel (axis == kEventMouseWheelAxisX ? delta * 10 : 0,
  220590. axis == kEventMouseWheelAxisX ? 0 : delta * 10,
  220591. time);
  220592. break;
  220593. }
  220594. }
  220595. return noErr;
  220596. }
  220597. void doDragDropEnter (EventRef theEvent)
  220598. {
  220599. updateDragAndDropFileList (theEvent);
  220600. if (dragAndDropFiles.size() > 0)
  220601. {
  220602. int x, y;
  220603. component->getMouseXYRelative (x, y);
  220604. handleFileDragMove (dragAndDropFiles, x, y);
  220605. }
  220606. }
  220607. void doDragDropMove (EventRef theEvent)
  220608. {
  220609. if (dragAndDropFiles.size() > 0)
  220610. {
  220611. int x, y;
  220612. component->getMouseXYRelative (x, y);
  220613. handleFileDragMove (dragAndDropFiles, x, y);
  220614. }
  220615. }
  220616. void doDragDropExit (EventRef theEvent)
  220617. {
  220618. if (dragAndDropFiles.size() > 0)
  220619. handleFileDragExit (dragAndDropFiles);
  220620. }
  220621. void doDragDrop (EventRef theEvent)
  220622. {
  220623. updateDragAndDropFileList (theEvent);
  220624. if (dragAndDropFiles.size() > 0)
  220625. {
  220626. int x, y;
  220627. component->getMouseXYRelative (x, y);
  220628. handleFileDragDrop (dragAndDropFiles, x, y);
  220629. }
  220630. }
  220631. void updateDragAndDropFileList (EventRef theEvent)
  220632. {
  220633. dragAndDropFiles.clear();
  220634. DragRef dragRef;
  220635. if (GetEventParameter (theEvent, kEventParamDragRef, typeDragRef, 0, sizeof (dragRef), 0, &dragRef) == noErr)
  220636. {
  220637. UInt16 numItems = 0;
  220638. if (CountDragItems (dragRef, &numItems) == noErr)
  220639. {
  220640. for (int i = 0; i < (int) numItems; ++i)
  220641. {
  220642. DragItemRef ref;
  220643. if (GetDragItemReferenceNumber (dragRef, i + 1, &ref) == noErr)
  220644. {
  220645. const FlavorType flavorType = kDragFlavorTypeHFS;
  220646. Size size = 0;
  220647. if (GetFlavorDataSize (dragRef, ref, flavorType, &size) == noErr)
  220648. {
  220649. void* data = juce_calloc (size);
  220650. if (GetFlavorData (dragRef, ref, flavorType, data, &size, 0) == noErr)
  220651. {
  220652. HFSFlavor* f = (HFSFlavor*) data;
  220653. FSRef fsref;
  220654. if (FSpMakeFSRef (&f->fileSpec, &fsref) == noErr)
  220655. {
  220656. const String path (PlatformUtilities::makePathFromFSRef (&fsref));
  220657. if (path.isNotEmpty())
  220658. dragAndDropFiles.add (path);
  220659. }
  220660. }
  220661. juce_free (data);
  220662. }
  220663. }
  220664. }
  220665. dragAndDropFiles.trim();
  220666. dragAndDropFiles.removeEmptyStrings();
  220667. }
  220668. }
  220669. }
  220670. void resizeViewToFitWindow()
  220671. {
  220672. HIRect r;
  220673. if (isSharedWindow)
  220674. {
  220675. HIViewGetFrame (viewRef, &r);
  220676. r.size.width = (float) component->getWidth();
  220677. r.size.height = (float) component->getHeight();
  220678. }
  220679. else
  220680. {
  220681. r.origin.x = 0;
  220682. r.origin.y = 0;
  220683. Rect w;
  220684. GetWindowBounds (windowRef, windowRegionToUse, &w);
  220685. r.size.width = (float) (w.right - w.left);
  220686. r.size.height = (float) (w.bottom - w.top);
  220687. }
  220688. HIViewSetFrame (viewRef, &r);
  220689. #if MACOS_10_3_OR_EARLIER
  220690. component->repaint();
  220691. #endif
  220692. }
  220693. OSStatus hiViewDraw (EventRef theEvent)
  220694. {
  220695. CGContextRef context = 0;
  220696. GetEventParameter (theEvent, kEventParamCGContextRef, typeCGContextRef, 0, sizeof (CGContextRef), 0, &context);
  220697. CGrafPtr oldPort;
  220698. CGrafPtr port = 0;
  220699. if (context == 0)
  220700. {
  220701. GetEventParameter (theEvent, kEventParamGrafPort, typeGrafPtr, 0, sizeof (CGrafPtr), 0, &port);
  220702. GetPort (&oldPort);
  220703. SetPort (port);
  220704. if (port != 0)
  220705. QDBeginCGContext (port, &context);
  220706. if (! isCompositingWindow)
  220707. {
  220708. Rect bounds;
  220709. GetWindowBounds (windowRef, windowRegionToUse, &bounds);
  220710. CGContextTranslateCTM (context, 0, bounds.bottom - bounds.top);
  220711. CGContextScaleCTM (context, 1.0, -1.0);
  220712. }
  220713. if (isSharedWindow)
  220714. {
  220715. // NB - Had terrible problems trying to correctly get the position
  220716. // of this view relative to the window, and this seems wrong, but
  220717. // works better than any other method I've tried..
  220718. HIRect hiViewPos;
  220719. HIViewGetFrame (viewRef, &hiViewPos);
  220720. CGContextTranslateCTM (context, hiViewPos.origin.x, hiViewPos.origin.y);
  220721. }
  220722. }
  220723. #if MACOS_10_2_OR_EARLIER
  220724. RgnHandle rgn = 0;
  220725. GetEventParameter (theEvent, kEventParamRgnHandle, typeQDRgnHandle, 0, sizeof (RgnHandle), 0, &rgn);
  220726. CGRect clip;
  220727. // (avoid doing this in plugins because of some strange redraw bugs..)
  220728. if (rgn != 0 && JUCEApplication::getInstance() != 0)
  220729. {
  220730. Rect bounds;
  220731. GetRegionBounds (rgn, &bounds);
  220732. clip.origin.x = bounds.left;
  220733. clip.origin.y = bounds.top;
  220734. clip.size.width = bounds.right - bounds.left;
  220735. clip.size.height = bounds.bottom - bounds.top;
  220736. }
  220737. else
  220738. {
  220739. HIViewGetBounds (viewRef, &clip);
  220740. clip.origin.x = 0;
  220741. clip.origin.y = 0;
  220742. }
  220743. #else
  220744. CGRect clip (CGContextGetClipBoundingBox (context));
  220745. #endif
  220746. clip = CGRectIntegral (clip);
  220747. if (clip.origin.x < 0)
  220748. {
  220749. clip.size.width += clip.origin.x;
  220750. clip.origin.x = 0;
  220751. }
  220752. if (clip.origin.y < 0)
  220753. {
  220754. clip.size.height += clip.origin.y;
  220755. clip.origin.y = 0;
  220756. }
  220757. if (! component->isOpaque())
  220758. CGContextClearRect (context, clip);
  220759. repainter->paint (context,
  220760. (int) clip.origin.x, (int) clip.origin.y,
  220761. (int) clip.size.width, (int) clip.size.height);
  220762. if (port != 0)
  220763. {
  220764. CGContextFlush (context);
  220765. QDEndCGContext (port, &context);
  220766. SetPort (oldPort);
  220767. }
  220768. repainter->repaintAnyRemainingRegions();
  220769. return noErr;
  220770. }
  220771. OSStatus handleWindowClassEvent (EventRef theEvent)
  220772. {
  220773. switch (GetEventKind (theEvent))
  220774. {
  220775. case kEventWindowBoundsChanged:
  220776. resizeViewToFitWindow();
  220777. break; // allow other handlers in the event chain to also get a look at the events
  220778. case kEventWindowBoundsChanging:
  220779. if ((styleFlags & (windowIsResizable | windowHasTitleBar)) == (windowIsResizable | windowHasTitleBar))
  220780. {
  220781. UInt32 atts = 0;
  220782. GetEventParameter (theEvent, kEventParamAttributes, typeUInt32,
  220783. 0, sizeof (UInt32), 0, &atts);
  220784. if ((atts & (kWindowBoundsChangeUserDrag | kWindowBoundsChangeUserResize)) != 0)
  220785. {
  220786. if (component->isCurrentlyBlockedByAnotherModalComponent())
  220787. {
  220788. Component* const modal = Component::getCurrentlyModalComponent();
  220789. if (modal != 0)
  220790. {
  220791. static uint32 lastDragTime = 0;
  220792. const uint32 now = Time::currentTimeMillis();
  220793. if (now > lastDragTime + 1000)
  220794. {
  220795. lastDragTime = now;
  220796. modal->inputAttemptWhenModal();
  220797. }
  220798. const Rectangle currentRect (getComponent()->getBounds());
  220799. Rect current;
  220800. current.left = currentRect.getX();
  220801. current.top = currentRect.getY();
  220802. current.right = currentRect.getRight();
  220803. current.bottom = currentRect.getBottom();
  220804. // stop the window getting dragged..
  220805. SetEventParameter (theEvent, kEventParamCurrentBounds, typeQDRectangle,
  220806. sizeof (Rect), &current);
  220807. return noErr;
  220808. }
  220809. }
  220810. if ((atts & kWindowBoundsChangeUserResize) != 0
  220811. && constrainer != 0 && ! isSharedWindow)
  220812. {
  220813. Rect current;
  220814. GetEventParameter (theEvent, kEventParamCurrentBounds, typeQDRectangle,
  220815. 0, sizeof (Rect), 0, &current);
  220816. int x = current.left;
  220817. int y = current.top;
  220818. int w = current.right - current.left;
  220819. int h = current.bottom - current.top;
  220820. const Rectangle currentRect (getComponent()->getBounds());
  220821. constrainer->checkBounds (x, y, w, h, currentRect,
  220822. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  220823. y != currentRect.getY() && y + h == currentRect.getBottom(),
  220824. x != currentRect.getX() && x + w == currentRect.getRight(),
  220825. y == currentRect.getY() && y + h != currentRect.getBottom(),
  220826. x == currentRect.getX() && x + w != currentRect.getRight());
  220827. current.left = x;
  220828. current.top = y;
  220829. current.right = x + w;
  220830. current.bottom = y + h;
  220831. SetEventParameter (theEvent, kEventParamCurrentBounds, typeQDRectangle,
  220832. sizeof (Rect), &current);
  220833. return noErr;
  220834. }
  220835. }
  220836. }
  220837. break;
  220838. case kEventWindowFocusAcquired:
  220839. keysCurrentlyDown.clear();
  220840. if ((! isSharedWindow) || HIViewSubtreeContainsFocus (viewRef))
  220841. viewFocusGain();
  220842. break; // allow other handlers in the event chain to also get a look at the events
  220843. case kEventWindowFocusRelinquish:
  220844. keysCurrentlyDown.clear();
  220845. viewFocusLoss();
  220846. break; // allow other handlers in the event chain to also get a look at the events
  220847. case kEventWindowCollapsed:
  220848. minimisedWindows.addIfNotAlreadyThere (windowRef);
  220849. handleMovedOrResized();
  220850. break; // allow other handlers in the event chain to also get a look at the events
  220851. case kEventWindowExpanded:
  220852. minimisedWindows.removeValue (windowRef);
  220853. handleMovedOrResized();
  220854. break; // allow other handlers in the event chain to also get a look at the events
  220855. case kEventWindowShown:
  220856. break; // allow other handlers in the event chain to also get a look at the events
  220857. case kEventWindowClose:
  220858. if (isSharedWindow)
  220859. break; // break to let the OS delete the window
  220860. handleUserClosingWindow();
  220861. return noErr; // avoids letting the OS to delete the window, we'll do that ourselves.
  220862. default:
  220863. break;
  220864. }
  220865. return eventNotHandledErr;
  220866. }
  220867. OSStatus handleWindowEventForPeer (EventHandlerCallRef callRef, EventRef theEvent)
  220868. {
  220869. switch (GetEventClass (theEvent))
  220870. {
  220871. case kEventClassMouse:
  220872. {
  220873. static HIViewComponentPeer* lastMouseDownPeer = 0;
  220874. const UInt32 eventKind = GetEventKind (theEvent);
  220875. HIViewRef view = 0;
  220876. if (eventKind == kEventMouseDragged)
  220877. {
  220878. view = viewRef;
  220879. }
  220880. else
  220881. {
  220882. HIViewGetViewForMouseEvent (HIViewGetRoot (windowRef), theEvent, &view);
  220883. if (view != viewRef)
  220884. {
  220885. if ((eventKind == kEventMouseUp
  220886. || eventKind == kEventMouseExited)
  220887. && ComponentPeer::isValidPeer (lastMouseDownPeer))
  220888. {
  220889. return lastMouseDownPeer->handleMouseEvent (callRef, theEvent);
  220890. }
  220891. return eventNotHandledErr;
  220892. }
  220893. }
  220894. if (eventKind == kEventMouseDown
  220895. || eventKind == kEventMouseDragged
  220896. || eventKind == kEventMouseEntered)
  220897. {
  220898. lastMouseDownPeer = this;
  220899. }
  220900. return handleMouseEvent (callRef, theEvent);
  220901. }
  220902. break;
  220903. case kEventClassWindow:
  220904. return handleWindowClassEvent (theEvent);
  220905. case kEventClassKeyboard:
  220906. if (isFocused())
  220907. return handleKeyEvent (theEvent, 0);
  220908. break;
  220909. case kEventClassTextInput:
  220910. if (isFocused())
  220911. return handleTextInputEvent (theEvent);
  220912. break;
  220913. default:
  220914. break;
  220915. }
  220916. return eventNotHandledErr;
  220917. }
  220918. static pascal OSStatus handleWindowEvent (EventHandlerCallRef callRef, EventRef theEvent, void* userData)
  220919. {
  220920. MessageManager::delayWaitCursor();
  220921. HIViewComponentPeer* const peer = (HIViewComponentPeer*) userData;
  220922. const MessageManagerLock messLock;
  220923. if (ComponentPeer::isValidPeer (peer))
  220924. return peer->handleWindowEventForPeer (callRef, theEvent);
  220925. return eventNotHandledErr;
  220926. }
  220927. static pascal OSStatus hiViewEventHandler (EventHandlerCallRef myHandler, EventRef theEvent, void* userData)
  220928. {
  220929. MessageManager::delayWaitCursor();
  220930. const UInt32 eventKind = GetEventKind (theEvent);
  220931. const UInt32 eventClass = GetEventClass (theEvent);
  220932. if (eventClass == kEventClassHIObject)
  220933. {
  220934. switch (eventKind)
  220935. {
  220936. case kEventHIObjectConstruct:
  220937. {
  220938. void* data = juce_calloc (sizeof (void*));
  220939. SetEventParameter (theEvent, kEventParamHIObjectInstance,
  220940. typeVoidPtr, sizeof (void*), &data);
  220941. return noErr;
  220942. }
  220943. case kEventHIObjectInitialize:
  220944. GetEventParameter (theEvent, 'peer', typeVoidPtr, 0, sizeof (void*), 0, (void**) userData);
  220945. return noErr;
  220946. case kEventHIObjectDestruct:
  220947. juce_free (userData);
  220948. return noErr;
  220949. default:
  220950. break;
  220951. }
  220952. }
  220953. else if (eventClass == kEventClassControl)
  220954. {
  220955. HIViewComponentPeer* const peer = *(HIViewComponentPeer**) userData;
  220956. const MessageManagerLock messLock;
  220957. if (! ComponentPeer::isValidPeer (peer))
  220958. return eventNotHandledErr;
  220959. switch (eventKind)
  220960. {
  220961. case kEventControlDraw:
  220962. return peer->hiViewDraw (theEvent);
  220963. case kEventControlBoundsChanged:
  220964. {
  220965. HIRect bounds;
  220966. HIViewGetBounds (peer->viewRef, &bounds);
  220967. peer->repaint (0, 0, roundFloatToInt (bounds.size.width), roundFloatToInt (bounds.size.height));
  220968. peer->handleMovedOrResized();
  220969. return noErr;
  220970. }
  220971. case kEventControlHitTest:
  220972. {
  220973. HIPoint where;
  220974. GetEventParameter (theEvent, kEventParamMouseLocation, typeHIPoint, 0, sizeof (HIPoint), 0, &where);
  220975. HIRect bounds;
  220976. HIViewGetBounds (peer->viewRef, &bounds);
  220977. ControlPartCode part = kControlNoPart;
  220978. if (CGRectContainsPoint (bounds, where))
  220979. part = 1;
  220980. SetEventParameter (theEvent, kEventParamControlPart, typeControlPartCode, sizeof (ControlPartCode), &part);
  220981. return noErr;
  220982. }
  220983. break;
  220984. case kEventControlSetFocusPart:
  220985. {
  220986. ControlPartCode desiredFocus;
  220987. if (GetEventParameter (theEvent, kEventParamControlPart, typeControlPartCode, 0, sizeof (ControlPartCode), 0, &desiredFocus) != noErr)
  220988. break;
  220989. if (desiredFocus == kControlNoPart)
  220990. peer->viewFocusLoss();
  220991. else
  220992. peer->viewFocusGain();
  220993. return noErr;
  220994. }
  220995. break;
  220996. case kEventControlDragEnter:
  220997. {
  220998. #if MACOS_10_2_OR_EARLIER
  220999. enum { kEventParamControlWouldAcceptDrop = 'cldg' };
  221000. #endif
  221001. Boolean accept = true;
  221002. SetEventParameter (theEvent, kEventParamControlWouldAcceptDrop, typeBoolean, sizeof (accept), &accept);
  221003. peer->doDragDropEnter (theEvent);
  221004. return noErr;
  221005. }
  221006. case kEventControlDragWithin:
  221007. peer->doDragDropMove (theEvent);
  221008. return noErr;
  221009. case kEventControlDragLeave:
  221010. peer->doDragDropExit (theEvent);
  221011. return noErr;
  221012. case kEventControlDragReceive:
  221013. peer->doDragDrop (theEvent);
  221014. return noErr;
  221015. case kEventControlOwningWindowChanged:
  221016. return peer->ownerWindowChanged (theEvent);
  221017. #if ! MACOS_10_2_OR_EARLIER
  221018. case kEventControlGetFrameMetrics:
  221019. {
  221020. CallNextEventHandler (myHandler, theEvent);
  221021. HIViewFrameMetrics metrics;
  221022. GetEventParameter (theEvent, kEventParamControlFrameMetrics, typeControlFrameMetrics, 0, sizeof (metrics), 0, &metrics);
  221023. metrics.top = metrics.bottom = 0;
  221024. SetEventParameter (theEvent, kEventParamControlFrameMetrics, typeControlFrameMetrics, sizeof (metrics), &metrics);
  221025. return noErr;
  221026. }
  221027. #endif
  221028. case kEventControlInitialize:
  221029. {
  221030. UInt32 features = kControlSupportsDragAndDrop
  221031. | kControlSupportsFocus
  221032. | kControlHandlesTracking
  221033. | kControlSupportsEmbedding
  221034. | (1 << 8) /*kHIViewFeatureGetsFocusOnClick*/;
  221035. SetEventParameter (theEvent, kEventParamControlFeatures, typeUInt32, sizeof (UInt32), &features);
  221036. return noErr;
  221037. }
  221038. default:
  221039. break;
  221040. }
  221041. }
  221042. return eventNotHandledErr;
  221043. }
  221044. WindowRef createNewWindow (const int windowStyleFlags)
  221045. {
  221046. jassert (windowRef == 0);
  221047. static ToolboxObjectClassRef customWindowClass = 0;
  221048. if (customWindowClass == 0)
  221049. {
  221050. // Register our window class
  221051. const EventTypeSpec customTypes[] = { { kEventClassWindow, kEventWindowDrawFrame } };
  221052. UnsignedWide t;
  221053. Microseconds (&t);
  221054. const String randomString ((int) (t.lo & 0x7ffffff));
  221055. const String juceWindowClassName (T("JUCEWindowClass_") + randomString);
  221056. CFStringRef juceWindowClassNameCFString = PlatformUtilities::juceStringToCFString (juceWindowClassName);
  221057. RegisterToolboxObjectClass (juceWindowClassNameCFString,
  221058. 0, 1, customTypes,
  221059. NewEventHandlerUPP (handleFrameRepaintEvent),
  221060. 0, &customWindowClass);
  221061. CFRelease (juceWindowClassNameCFString);
  221062. }
  221063. Rect pos;
  221064. pos.left = getComponent()->getX();
  221065. pos.top = getComponent()->getY();
  221066. pos.right = getComponent()->getRight();
  221067. pos.bottom = getComponent()->getBottom();
  221068. int attributes = kWindowStandardHandlerAttribute | kWindowCompositingAttribute;
  221069. if ((windowStyleFlags & windowHasDropShadow) == 0)
  221070. attributes |= kWindowNoShadowAttribute;
  221071. if ((windowStyleFlags & windowIgnoresMouseClicks) != 0)
  221072. attributes |= kWindowIgnoreClicksAttribute;
  221073. #if ! MACOS_10_3_OR_EARLIER
  221074. if ((windowStyleFlags & windowIsTemporary) != 0)
  221075. attributes |= kWindowDoesNotCycleAttribute;
  221076. #endif
  221077. WindowRef newWindow = 0;
  221078. if ((windowStyleFlags & windowHasTitleBar) == 0)
  221079. {
  221080. attributes |= kWindowCollapseBoxAttribute;
  221081. WindowDefSpec customWindowSpec;
  221082. customWindowSpec.defType = kWindowDefObjectClass;
  221083. customWindowSpec.u.classRef = customWindowClass;
  221084. CreateCustomWindow (&customWindowSpec,
  221085. ((windowStyleFlags & windowIsTemporary) != 0) ? kUtilityWindowClass :
  221086. (getComponent()->isAlwaysOnTop() ? kUtilityWindowClass
  221087. : kDocumentWindowClass),
  221088. attributes,
  221089. &pos,
  221090. &newWindow);
  221091. }
  221092. else
  221093. {
  221094. if ((windowStyleFlags & windowHasCloseButton) != 0)
  221095. attributes |= kWindowCloseBoxAttribute;
  221096. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  221097. attributes |= kWindowCollapseBoxAttribute;
  221098. if ((windowStyleFlags & windowHasMaximiseButton) != 0)
  221099. attributes |= kWindowFullZoomAttribute;
  221100. if ((windowStyleFlags & windowIsResizable) != 0)
  221101. attributes |= kWindowResizableAttribute | kWindowLiveResizeAttribute;
  221102. CreateNewWindow (kDocumentWindowClass, attributes, &pos, &newWindow);
  221103. }
  221104. jassert (newWindow != 0);
  221105. if (newWindow != 0)
  221106. {
  221107. HideWindow (newWindow);
  221108. SetAutomaticControlDragTrackingEnabledForWindow (newWindow, true);
  221109. if (! getComponent()->isOpaque())
  221110. SetWindowAlpha (newWindow, 0.9999999f); // to fool it into giving the window an alpha-channel
  221111. }
  221112. return newWindow;
  221113. }
  221114. OSStatus ownerWindowChanged (EventRef theEvent)
  221115. {
  221116. WindowRef newWindow = 0;
  221117. GetEventParameter (theEvent, kEventParamControlCurrentOwningWindow, typeWindowRef, 0, sizeof (newWindow), 0, &newWindow);
  221118. if (windowRef != newWindow)
  221119. {
  221120. if (eventHandlerRef != 0)
  221121. {
  221122. RemoveEventHandler (eventHandlerRef);
  221123. eventHandlerRef = 0;
  221124. }
  221125. windowRef = newWindow;
  221126. if (windowRef != 0)
  221127. {
  221128. const EventTypeSpec eventTypes[] =
  221129. {
  221130. { kEventClassWindow, kEventWindowBoundsChanged },
  221131. { kEventClassWindow, kEventWindowBoundsChanging },
  221132. { kEventClassWindow, kEventWindowFocusAcquired },
  221133. { kEventClassWindow, kEventWindowFocusRelinquish },
  221134. { kEventClassWindow, kEventWindowCollapsed },
  221135. { kEventClassWindow, kEventWindowExpanded },
  221136. { kEventClassWindow, kEventWindowShown },
  221137. { kEventClassWindow, kEventWindowClose },
  221138. { kEventClassMouse, kEventMouseDown },
  221139. { kEventClassMouse, kEventMouseUp },
  221140. { kEventClassMouse, kEventMouseMoved },
  221141. { kEventClassMouse, kEventMouseDragged },
  221142. { kEventClassMouse, kEventMouseEntered },
  221143. { kEventClassMouse, kEventMouseExited },
  221144. { kEventClassMouse, kEventMouseWheelMoved },
  221145. { kEventClassKeyboard, kEventRawKeyUp },
  221146. { kEventClassKeyboard, kEventRawKeyRepeat },
  221147. { kEventClassKeyboard, kEventRawKeyModifiersChanged },
  221148. { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent }
  221149. };
  221150. static EventHandlerUPP handleWindowEventUPP = 0;
  221151. if (handleWindowEventUPP == 0)
  221152. handleWindowEventUPP = NewEventHandlerUPP (handleWindowEvent);
  221153. InstallWindowEventHandler (windowRef, handleWindowEventUPP,
  221154. GetEventTypeCount (eventTypes), eventTypes,
  221155. (void*) this, (EventHandlerRef*) &eventHandlerRef);
  221156. WindowAttributes attributes;
  221157. GetWindowAttributes (windowRef, &attributes);
  221158. #if MACOS_10_3_OR_EARLIER
  221159. isCompositingWindow = ((attributes & kWindowCompositingAttribute) != 0);
  221160. #else
  221161. isCompositingWindow = HIViewIsCompositingEnabled (viewRef);
  221162. #endif
  221163. SetAutomaticControlDragTrackingEnabledForWindow (newWindow, true);
  221164. MouseCheckTimer::getInstance()->resetMouseMoveChecker();
  221165. }
  221166. }
  221167. resizeViewToFitWindow();
  221168. return noErr;
  221169. }
  221170. void createNewHIView()
  221171. {
  221172. jassert (viewRef == 0);
  221173. if (viewClassRef == 0)
  221174. {
  221175. // Register our HIView class
  221176. EventTypeSpec viewEvents[] =
  221177. {
  221178. { kEventClassHIObject, kEventHIObjectConstruct },
  221179. { kEventClassHIObject, kEventHIObjectInitialize },
  221180. { kEventClassHIObject, kEventHIObjectDestruct },
  221181. { kEventClassControl, kEventControlInitialize },
  221182. { kEventClassControl, kEventControlDraw },
  221183. { kEventClassControl, kEventControlBoundsChanged },
  221184. { kEventClassControl, kEventControlSetFocusPart },
  221185. { kEventClassControl, kEventControlHitTest },
  221186. { kEventClassControl, kEventControlDragEnter },
  221187. { kEventClassControl, kEventControlDragLeave },
  221188. { kEventClassControl, kEventControlDragWithin },
  221189. { kEventClassControl, kEventControlDragReceive },
  221190. { kEventClassControl, kEventControlOwningWindowChanged }
  221191. };
  221192. UnsignedWide t;
  221193. Microseconds (&t);
  221194. const String randomString ((int) (t.lo & 0x7ffffff));
  221195. const String juceHiViewClassName (T("JUCEHIViewClass_") + randomString);
  221196. juceHiViewClassNameCFString = PlatformUtilities::juceStringToCFString (juceHiViewClassName);
  221197. HIObjectRegisterSubclass (juceHiViewClassNameCFString,
  221198. kHIViewClassID, 0,
  221199. NewEventHandlerUPP (hiViewEventHandler),
  221200. GetEventTypeCount (viewEvents),
  221201. viewEvents, 0,
  221202. &viewClassRef);
  221203. }
  221204. EventRef event;
  221205. CreateEvent (0, kEventClassHIObject, kEventHIObjectInitialize, GetCurrentEventTime(), kEventAttributeNone, &event);
  221206. void* thisPointer = this;
  221207. SetEventParameter (event, 'peer', typeVoidPtr, sizeof (void*), &thisPointer);
  221208. HIObjectCreate (juceHiViewClassNameCFString, event, (HIObjectRef*) &viewRef);
  221209. SetControlDragTrackingEnabled (viewRef, true);
  221210. if (isSharedWindow)
  221211. {
  221212. setBounds (component->getX(), component->getY(),
  221213. component->getWidth(), component->getHeight(), false);
  221214. }
  221215. }
  221216. };
  221217. bool juce_isHIViewCreatedByJuce (HIViewRef view)
  221218. {
  221219. return juceHiViewClassNameCFString != 0
  221220. && HIObjectIsOfClass ((HIObjectRef) view, juceHiViewClassNameCFString);
  221221. }
  221222. bool juce_isWindowCreatedByJuce (WindowRef window)
  221223. {
  221224. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221225. if (ComponentPeer::getPeer(i)->getNativeHandle() == window)
  221226. return true;
  221227. return false;
  221228. }
  221229. static void trackNextMouseEvent()
  221230. {
  221231. UInt32 mods;
  221232. MouseTrackingResult result;
  221233. ::Point where;
  221234. if (TrackMouseLocationWithOptions ((GrafPtr) -1, 0, 0.01, //kEventDurationForever,
  221235. &where, &mods, &result) != noErr
  221236. || ! ComponentPeer::isValidPeer (juce_currentMouseTrackingPeer))
  221237. {
  221238. juce_currentMouseTrackingPeer = 0;
  221239. return;
  221240. }
  221241. if (result == kMouseTrackingTimedOut)
  221242. return;
  221243. #if MACOS_10_3_OR_EARLIER
  221244. const int x = where.h - juce_currentMouseTrackingPeer->getScreenX();
  221245. const int y = where.v - juce_currentMouseTrackingPeer->getScreenY();
  221246. #else
  221247. HIPoint p;
  221248. p.x = where.h;
  221249. p.y = where.v;
  221250. HIPointConvert (&p, kHICoordSpaceScreenPixel, 0,
  221251. kHICoordSpaceView, ((HIViewComponentPeer*) juce_currentMouseTrackingPeer)->viewRef);
  221252. const int x = p.x;
  221253. const int y = p.y;
  221254. #endif
  221255. if (result == kMouseTrackingMouseDragged)
  221256. {
  221257. updateModifiers (0);
  221258. juce_currentMouseTrackingPeer->handleMouseDrag (x, y, getEventTime (0));
  221259. if (! ComponentPeer::isValidPeer (juce_currentMouseTrackingPeer))
  221260. {
  221261. juce_currentMouseTrackingPeer = 0;
  221262. return;
  221263. }
  221264. }
  221265. else if (result == kMouseTrackingMouseUp
  221266. || result == kMouseTrackingUserCancelled
  221267. || result == kMouseTrackingMouseMoved)
  221268. {
  221269. ComponentPeer* const oldPeer = juce_currentMouseTrackingPeer;
  221270. juce_currentMouseTrackingPeer = 0;
  221271. if (ComponentPeer::isValidPeer (oldPeer))
  221272. {
  221273. const int oldModifiers = currentModifiers;
  221274. currentModifiers &= ~(ModifierKeys::leftButtonModifier | ModifierKeys::rightButtonModifier | ModifierKeys::middleButtonModifier);
  221275. updateModifiers (0);
  221276. oldPeer->handleMouseUp (oldModifiers, x, y, getEventTime (0));
  221277. }
  221278. }
  221279. }
  221280. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  221281. {
  221282. if (juce_currentMouseTrackingPeer != 0)
  221283. trackNextMouseEvent();
  221284. /* [[NSRunLoop mainRunLoop] acceptInputForMode: NSDefaultRunLoopMode
  221285. beforeDate: returnIfNoPendingMessages
  221286. ? [[NSDate date] addTimeInterval: 0.01]
  221287. : [NSDate distantFuture]];
  221288. */
  221289. EventRef theEvent;
  221290. if (ReceiveNextEvent (0, 0, (returnIfNoPendingMessages) ? kEventDurationNoWait
  221291. : kEventDurationForever,
  221292. true, &theEvent) == noErr)
  221293. {
  221294. if (GetEventClass (theEvent) == kEventClassAppleEvent)
  221295. {
  221296. EventRecord eventRec;
  221297. if (ConvertEventRefToEventRecord (theEvent, &eventRec))
  221298. AEProcessAppleEvent (&eventRec);
  221299. }
  221300. else
  221301. {
  221302. EventTargetRef theTarget = GetEventDispatcherTarget();
  221303. SendEventToEventTarget (theEvent, theTarget);
  221304. }
  221305. ReleaseEvent (theEvent);
  221306. return true;
  221307. }
  221308. return false;
  221309. }
  221310. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  221311. {
  221312. return new HIViewComponentPeer (this, styleFlags, (HIViewRef) windowToAttachTo);
  221313. }
  221314. void MouseCheckTimer::timerCallback()
  221315. {
  221316. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  221317. return;
  221318. if (Process::isForegroundProcess())
  221319. {
  221320. bool stillOver = false;
  221321. int x = 0, y = 0, w = 0, h = 0;
  221322. int mx = 0, my = 0;
  221323. const bool validWindow = ComponentPeer::isValidPeer (lastPeerUnderMouse);
  221324. if (validWindow)
  221325. {
  221326. lastPeerUnderMouse->getBounds (x, y, w, h, true);
  221327. Desktop::getMousePosition (mx, my);
  221328. stillOver = (mx >= x && my >= y && mx < x + w && my < y + h);
  221329. if (stillOver)
  221330. {
  221331. // check if it's over an embedded HIView
  221332. int rx = mx, ry = my;
  221333. lastPeerUnderMouse->globalPositionToRelative (rx, ry);
  221334. HIPoint hipoint;
  221335. hipoint.x = rx;
  221336. hipoint.y = ry;
  221337. HIViewRef root;
  221338. GetRootControl ((WindowRef) lastPeerUnderMouse->getNativeHandle(), &root);
  221339. HIViewRef hitview;
  221340. if (HIViewGetSubviewHit (root, &hipoint, true, &hitview) == noErr && hitview != 0)
  221341. {
  221342. stillOver = HIObjectIsOfClass ((HIObjectRef) hitview, juceHiViewClassNameCFString);
  221343. }
  221344. }
  221345. }
  221346. if (! stillOver)
  221347. {
  221348. // mouse is outside our windows so set a normal cursor (only
  221349. // if we're running as an app, not a plugin)
  221350. if (JUCEApplication::getInstance() != 0)
  221351. SetThemeCursor (kThemeArrowCursor);
  221352. if (validWindow)
  221353. lastPeerUnderMouse->handleMouseExit (mx - x, my - y, Time::currentTimeMillis());
  221354. if (hasEverHadAMouseMove)
  221355. stopTimer();
  221356. }
  221357. if ((! hasEverHadAMouseMove) && validWindow
  221358. && (mx != lastX || my != lastY))
  221359. {
  221360. lastX = mx;
  221361. lastY = my;
  221362. if (stillOver)
  221363. lastPeerUnderMouse->handleMouseMove (mx - x, my - y, Time::currentTimeMillis());
  221364. }
  221365. }
  221366. }
  221367. // called from juce_Messaging.cpp
  221368. void juce_HandleProcessFocusChange()
  221369. {
  221370. keysCurrentlyDown.clear();
  221371. if (HIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  221372. {
  221373. if (Process::isForegroundProcess())
  221374. currentlyFocusedPeer->handleFocusGain();
  221375. else
  221376. currentlyFocusedPeer->handleFocusLoss();
  221377. }
  221378. }
  221379. static bool performDrag (DragRef drag)
  221380. {
  221381. EventRecord event;
  221382. event.what = mouseDown;
  221383. event.message = 0;
  221384. event.when = TickCount();
  221385. int x, y;
  221386. Desktop::getMousePosition (x, y);
  221387. event.where.h = x;
  221388. event.where.v = y;
  221389. event.modifiers = GetCurrentKeyModifiers();
  221390. RgnHandle rgn = NewRgn();
  221391. RgnHandle rgn2 = NewRgn();
  221392. SetRectRgn (rgn,
  221393. event.where.h - 8, event.where.v - 8,
  221394. event.where.h + 8, event.where.v + 8);
  221395. CopyRgn (rgn, rgn2);
  221396. InsetRgn (rgn2, 1, 1);
  221397. DiffRgn (rgn, rgn2, rgn);
  221398. DisposeRgn (rgn2);
  221399. bool result = TrackDrag (drag, &event, rgn) == noErr;
  221400. DisposeRgn (rgn);
  221401. return result;
  221402. }
  221403. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  221404. {
  221405. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221406. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  221407. DragRef drag;
  221408. bool result = false;
  221409. if (NewDrag (&drag) == noErr)
  221410. {
  221411. for (int i = 0; i < files.size(); ++i)
  221412. {
  221413. HFSFlavor hfsData;
  221414. if (PlatformUtilities::makeFSSpecFromPath (&hfsData.fileSpec, files[i]))
  221415. {
  221416. FInfo info;
  221417. if (FSpGetFInfo (&hfsData.fileSpec, &info) == noErr)
  221418. {
  221419. hfsData.fileType = info.fdType;
  221420. hfsData.fileCreator = info.fdCreator;
  221421. hfsData.fdFlags = info.fdFlags;
  221422. AddDragItemFlavor (drag, i + 1, kDragFlavorTypeHFS, &hfsData, sizeof (hfsData), 0);
  221423. result = true;
  221424. }
  221425. }
  221426. }
  221427. SetDragAllowableActions (drag, canMoveFiles ? kDragActionAll
  221428. : kDragActionCopy, false);
  221429. if (result)
  221430. result = performDrag (drag);
  221431. DisposeDrag (drag);
  221432. }
  221433. return result;
  221434. }
  221435. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  221436. {
  221437. jassertfalse // not implemented!
  221438. return false;
  221439. }
  221440. bool Process::isForegroundProcess() throw()
  221441. {
  221442. ProcessSerialNumber psn, front;
  221443. GetCurrentProcess (&psn);
  221444. GetFrontProcess (&front);
  221445. Boolean b;
  221446. return (SameProcess (&psn, &front, &b) == noErr) && b;
  221447. }
  221448. bool Desktop::canUseSemiTransparentWindows() throw()
  221449. {
  221450. return true;
  221451. }
  221452. void Desktop::getMousePosition (int& x, int& y) throw()
  221453. {
  221454. CGrafPtr currentPort;
  221455. GetPort (&currentPort);
  221456. if (! IsValidPort (currentPort))
  221457. {
  221458. WindowRef front = FrontWindow();
  221459. if (front != 0)
  221460. {
  221461. SetPortWindowPort (front);
  221462. }
  221463. else
  221464. {
  221465. x = y = 0;
  221466. return;
  221467. }
  221468. }
  221469. ::Point p;
  221470. GetMouse (&p);
  221471. LocalToGlobal (&p);
  221472. x = p.h;
  221473. y = p.v;
  221474. SetPort (currentPort);
  221475. }
  221476. void Desktop::setMousePosition (int x, int y) throw()
  221477. {
  221478. // this rubbish needs to be done around the warp call, to avoid causing a
  221479. // bizarre glitch..
  221480. CGAssociateMouseAndMouseCursorPosition (false);
  221481. CGSetLocalEventsSuppressionInterval (0);
  221482. CGPoint pos = { x, y };
  221483. CGWarpMouseCursorPosition (pos);
  221484. CGAssociateMouseAndMouseCursorPosition (true);
  221485. }
  221486. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221487. {
  221488. return ModifierKeys (currentModifiers);
  221489. }
  221490. class ScreenSaverDefeater : public Timer,
  221491. public DeletedAtShutdown
  221492. {
  221493. public:
  221494. ScreenSaverDefeater() throw()
  221495. {
  221496. startTimer (10000);
  221497. timerCallback();
  221498. }
  221499. ~ScreenSaverDefeater()
  221500. {
  221501. }
  221502. void timerCallback()
  221503. {
  221504. if (Process::isForegroundProcess())
  221505. UpdateSystemActivity (UsrActivity);
  221506. }
  221507. };
  221508. static ScreenSaverDefeater* screenSaverDefeater = 0;
  221509. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  221510. {
  221511. if (screenSaverDefeater == 0)
  221512. screenSaverDefeater = new ScreenSaverDefeater();
  221513. }
  221514. bool Desktop::isScreenSaverEnabled() throw()
  221515. {
  221516. return screenSaverDefeater == 0;
  221517. }
  221518. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  221519. {
  221520. int mainMonitorIndex = 0;
  221521. CGDirectDisplayID mainDisplayID = CGMainDisplayID();
  221522. CGDisplayCount count = 0;
  221523. CGDirectDisplayID disps [8];
  221524. if (CGGetOnlineDisplayList (numElementsInArray (disps), disps, &count) == noErr)
  221525. {
  221526. for (int i = 0; i < count; ++i)
  221527. {
  221528. if (mainDisplayID == disps[i])
  221529. mainMonitorIndex = monitorCoords.size();
  221530. GDHandle hGDevice;
  221531. if (clipToWorkArea
  221532. && DMGetGDeviceByDisplayID ((DisplayIDType) disps[i], &hGDevice, false) == noErr)
  221533. {
  221534. Rect rect;
  221535. GetAvailableWindowPositioningBounds (hGDevice, &rect);
  221536. monitorCoords.add (Rectangle (rect.left,
  221537. rect.top,
  221538. rect.right - rect.left,
  221539. rect.bottom - rect.top));
  221540. }
  221541. else
  221542. {
  221543. const CGRect r (CGDisplayBounds (disps[i]));
  221544. monitorCoords.add (Rectangle ((int) r.origin.x,
  221545. (int) r.origin.y,
  221546. (int) r.size.width,
  221547. (int) r.size.height));
  221548. }
  221549. }
  221550. }
  221551. // make sure the first in the list is the main monitor
  221552. if (mainMonitorIndex > 0)
  221553. monitorCoords.swap (mainMonitorIndex, 0);
  221554. jassert (monitorCoords.size() > 0);
  221555. if (monitorCoords.size() == 0)
  221556. monitorCoords.add (Rectangle (0, 0, 1024, 768));
  221557. }
  221558. static NSImage* juceImageToNSImage (const Image& image)
  221559. {
  221560. int lineStride, pixelStride;
  221561. const uint8* pixels = image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(),
  221562. lineStride, pixelStride);
  221563. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  221564. initWithBitmapDataPlanes: NULL
  221565. pixelsWide: image.getWidth()
  221566. pixelsHigh: image.getHeight()
  221567. bitsPerSample: 8
  221568. samplesPerPixel: image.hasAlphaChannel() ? 4 : 3
  221569. hasAlpha: image.hasAlphaChannel()
  221570. isPlanar: NO
  221571. colorSpaceName: NSCalibratedRGBColorSpace
  221572. bitmapFormat: (NSBitmapFormat) 0
  221573. bytesPerRow: lineStride
  221574. bitsPerPixel: pixelStride * 8];
  221575. unsigned char* newData = [rep bitmapData];
  221576. memcpy (newData, pixels, lineStride * image.getHeight());
  221577. image.releasePixelDataReadOnly (pixels);
  221578. NSImage* im = [[NSImage alloc] init];
  221579. [im addRepresentation: rep];
  221580. [rep release];
  221581. return im;
  221582. }
  221583. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  221584. {
  221585. NSImage* im = juceImageToNSImage (image);
  221586. [im autorelease];
  221587. NSPoint hs;
  221588. hs.x = (int) hotspotX;
  221589. hs.y = (int) hotspotY;
  221590. NSCursor* c = [[NSCursor alloc] initWithImage: im hotSpot: hs];
  221591. return (void*) c;
  221592. }
  221593. static void* juce_cursorFromData (const unsigned char* data, const int size, float hx, float hy) throw()
  221594. {
  221595. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  221596. jassert (im != 0);
  221597. if (im == 0)
  221598. return 0;
  221599. void* const curs = juce_createMouseCursorFromImage (*im,
  221600. (int) (hx * im->getWidth()),
  221601. (int) (hy * im->getHeight()));
  221602. delete im;
  221603. return curs;
  221604. }
  221605. static void* juce_cursorFromWebKitFile (const char* filename, float hx, float hy)
  221606. {
  221607. File f ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources");
  221608. MemoryBlock mb;
  221609. if (f.getChildFile (filename).loadFileAsData (mb))
  221610. return juce_cursorFromData ((const unsigned char*) mb.getData(), mb.getSize(), hx, hy);
  221611. return 0;
  221612. }
  221613. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  221614. {
  221615. NSCursor* c = 0;
  221616. switch (type)
  221617. {
  221618. case MouseCursor::NormalCursor:
  221619. c = [NSCursor arrowCursor];
  221620. break;
  221621. case MouseCursor::NoCursor:
  221622. {
  221623. Image blank (Image::ARGB, 8, 8, true);
  221624. return juce_createMouseCursorFromImage (blank, 0, 0);
  221625. }
  221626. case MouseCursor::DraggingHandCursor:
  221627. c = [NSCursor openHandCursor];
  221628. break;
  221629. case MouseCursor::CopyingCursor:
  221630. return juce_cursorFromWebKitFile ("copyCursor.png", 0, 0);
  221631. case MouseCursor::WaitCursor:
  221632. c = [NSCursor arrowCursor]; // avoid this on the mac, let the OS provide the beachball
  221633. break;
  221634. //return juce_cursorFromWebKitFile ("waitCursor.png", 0.5f, 0.5f);
  221635. case MouseCursor::IBeamCursor:
  221636. c = [NSCursor IBeamCursor];
  221637. break;
  221638. case MouseCursor::PointingHandCursor:
  221639. c = [NSCursor pointingHandCursor];
  221640. break;
  221641. case MouseCursor::LeftRightResizeCursor:
  221642. c = [NSCursor resizeLeftRightCursor];
  221643. break;
  221644. case MouseCursor::LeftEdgeResizeCursor:
  221645. c = [NSCursor resizeLeftCursor];
  221646. break;
  221647. case MouseCursor::RightEdgeResizeCursor:
  221648. c = [NSCursor resizeRightCursor];
  221649. break;
  221650. case MouseCursor::UpDownResizeCursor:
  221651. case MouseCursor::TopEdgeResizeCursor:
  221652. case MouseCursor::BottomEdgeResizeCursor:
  221653. return juce_cursorFromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  221654. case MouseCursor::TopLeftCornerResizeCursor:
  221655. case MouseCursor::BottomRightCornerResizeCursor:
  221656. return juce_cursorFromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  221657. case MouseCursor::TopRightCornerResizeCursor:
  221658. case MouseCursor::BottomLeftCornerResizeCursor:
  221659. return juce_cursorFromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  221660. case MouseCursor::UpDownLeftRightResizeCursor:
  221661. return juce_cursorFromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  221662. case MouseCursor::CrosshairCursor:
  221663. c = [NSCursor crosshairCursor];
  221664. break;
  221665. }
  221666. [c retain];
  221667. return (void*) c;
  221668. }
  221669. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  221670. {
  221671. NSCursor* c = (NSCursor*) cursorHandle;
  221672. [c release];
  221673. }
  221674. void MouseCursor::showInAllWindows() const throw()
  221675. {
  221676. showInWindow (0);
  221677. }
  221678. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  221679. {
  221680. NSCursor* const c = (NSCursor*) getHandle();
  221681. if (c != 0)
  221682. [c set];
  221683. }
  221684. Image* juce_createIconForFile (const File& file)
  221685. {
  221686. return 0;
  221687. }
  221688. class MainMenuHandler;
  221689. static MainMenuHandler* mainMenu = 0;
  221690. class MainMenuHandler : private MenuBarModelListener,
  221691. private DeletedAtShutdown
  221692. {
  221693. public:
  221694. MainMenuHandler() throw()
  221695. : currentModel (0)
  221696. {
  221697. }
  221698. ~MainMenuHandler() throw()
  221699. {
  221700. setMenu (0);
  221701. jassert (mainMenu == this);
  221702. mainMenu = 0;
  221703. }
  221704. void setMenu (MenuBarModel* const newMenuBarModel) throw()
  221705. {
  221706. if (currentModel != newMenuBarModel)
  221707. {
  221708. if (currentModel != 0)
  221709. currentModel->removeListener (this);
  221710. currentModel = newMenuBarModel;
  221711. if (currentModel != 0)
  221712. currentModel->addListener (this);
  221713. menuBarItemsChanged (0);
  221714. }
  221715. }
  221716. void menuBarItemsChanged (MenuBarModel*)
  221717. {
  221718. ClearMenuBar();
  221719. if (currentModel != 0)
  221720. {
  221721. int menuId = 1000;
  221722. const StringArray menuNames (currentModel->getMenuBarNames());
  221723. for (int i = 0; i < menuNames.size(); ++i)
  221724. {
  221725. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  221726. MenuRef m = createMenu (menu, menuNames [i], menuId, i);
  221727. InsertMenu (m, 0);
  221728. CFRelease (m);
  221729. }
  221730. }
  221731. }
  221732. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  221733. {
  221734. MenuRef menu = 0;
  221735. MenuItemIndex index = 0;
  221736. GetIndMenuItemWithCommandID (0, info.commandID, 1, &menu, &index);
  221737. if (menu != 0)
  221738. {
  221739. FlashMenuBar (GetMenuID (menu));
  221740. FlashMenuBar (GetMenuID (menu));
  221741. }
  221742. }
  221743. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  221744. {
  221745. if (currentModel != 0)
  221746. {
  221747. if (commandManager != 0)
  221748. {
  221749. ApplicationCommandTarget::InvocationInfo info (commandId);
  221750. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  221751. commandManager->invoke (info, true);
  221752. }
  221753. currentModel->menuItemSelected (commandId, topLevelIndex);
  221754. }
  221755. }
  221756. MenuBarModel* currentModel;
  221757. private:
  221758. static MenuRef createMenu (const PopupMenu menu,
  221759. const String& menuName,
  221760. int& id,
  221761. const int topLevelIndex)
  221762. {
  221763. MenuRef m = 0;
  221764. if (CreateNewMenu (id++, kMenuAttrAutoDisable, &m) == noErr)
  221765. {
  221766. CFStringRef name = PlatformUtilities::juceStringToCFString (menuName);
  221767. SetMenuTitleWithCFString (m, name);
  221768. CFRelease (name);
  221769. PopupMenu::MenuItemIterator iter (menu);
  221770. while (iter.next())
  221771. {
  221772. MenuItemIndex index = 0;
  221773. int flags = kMenuAttrAutoDisable | kMenuItemAttrIgnoreMeta | kMenuItemAttrNotPreviousAlternate;
  221774. if (! iter.isEnabled)
  221775. flags |= kMenuItemAttrDisabled;
  221776. CFStringRef text = PlatformUtilities::juceStringToCFString (iter.itemName.upToFirstOccurrenceOf (T("<end>"), false, true));
  221777. if (iter.isSeparator)
  221778. {
  221779. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSeparator, 0, &index);
  221780. }
  221781. else if (iter.isSectionHeader)
  221782. {
  221783. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSectionHeader, 0, &index);
  221784. }
  221785. else if (iter.subMenu != 0)
  221786. {
  221787. AppendMenuItemTextWithCFString (m, text, flags, id++, &index);
  221788. MenuRef sub = createMenu (*iter.subMenu, iter.itemName, id, topLevelIndex);
  221789. SetMenuItemHierarchicalMenu (m, index, sub);
  221790. CFRelease (sub);
  221791. }
  221792. else
  221793. {
  221794. AppendMenuItemTextWithCFString (m, text, flags, iter.itemId, &index);
  221795. if (iter.isTicked)
  221796. CheckMenuItem (m, index, true);
  221797. SetMenuItemProperty (m, index, 'juce', 'apcm', sizeof (void*), &iter.commandManager);
  221798. SetMenuItemProperty (m, index, 'juce', 'topi', sizeof (int), &topLevelIndex);
  221799. if (iter.commandManager != 0)
  221800. {
  221801. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  221802. ->getKeyPressesAssignedToCommand (iter.itemId));
  221803. if (keyPresses.size() > 0)
  221804. {
  221805. const KeyPress& kp = keyPresses.getReference(0);
  221806. int mods = 0;
  221807. if (kp.getModifiers().isShiftDown())
  221808. mods |= kMenuShiftModifier;
  221809. if (kp.getModifiers().isCtrlDown())
  221810. mods |= kMenuControlModifier;
  221811. if (kp.getModifiers().isAltDown())
  221812. mods |= kMenuOptionModifier;
  221813. if (! kp.getModifiers().isCommandDown())
  221814. mods |= kMenuNoCommandModifier;
  221815. tchar keyCode = (tchar) kp.getKeyCode();
  221816. if (kp.getKeyCode() >= KeyPress::numberPad0
  221817. && kp.getKeyCode() <= KeyPress::numberPad9)
  221818. {
  221819. keyCode = (tchar) ((T('0') - KeyPress::numberPad0) + kp.getKeyCode());
  221820. }
  221821. SetMenuItemCommandKey (m, index, true, 255);
  221822. if (CharacterFunctions::isLetterOrDigit (keyCode)
  221823. || CharacterFunctions::indexOfChar (T(",.;/\\'[]=-+_<>?{}\":"), keyCode, false) >= 0)
  221824. {
  221825. SetMenuItemModifiers (m, index, mods);
  221826. SetMenuItemCommandKey (m, index, false, CharacterFunctions::toUpperCase (keyCode));
  221827. }
  221828. else
  221829. {
  221830. const SInt16 glyph = getGlyphForKeyCode (kp.getKeyCode());
  221831. if (glyph != 0)
  221832. {
  221833. SetMenuItemModifiers (m, index, mods);
  221834. SetMenuItemKeyGlyph (m, index, glyph);
  221835. }
  221836. }
  221837. // if we set the key glyph to be a text char, and enable virtual
  221838. // key triggering, it stops the menu automatically triggering the callback
  221839. ChangeMenuItemAttributes (m, index, kMenuItemAttrUseVirtualKey, 0);
  221840. }
  221841. }
  221842. }
  221843. CFRelease (text);
  221844. }
  221845. }
  221846. return m;
  221847. }
  221848. static SInt16 getGlyphForKeyCode (const int keyCode) throw()
  221849. {
  221850. if (keyCode == KeyPress::spaceKey)
  221851. return kMenuSpaceGlyph;
  221852. else if (keyCode == KeyPress::returnKey)
  221853. return kMenuReturnGlyph;
  221854. else if (keyCode == KeyPress::escapeKey)
  221855. return kMenuEscapeGlyph;
  221856. else if (keyCode == KeyPress::backspaceKey)
  221857. return kMenuDeleteLeftGlyph;
  221858. else if (keyCode == KeyPress::leftKey)
  221859. return kMenuLeftArrowGlyph;
  221860. else if (keyCode == KeyPress::rightKey)
  221861. return kMenuRightArrowGlyph;
  221862. else if (keyCode == KeyPress::upKey)
  221863. return kMenuUpArrowGlyph;
  221864. else if (keyCode == KeyPress::downKey)
  221865. return kMenuDownArrowGlyph;
  221866. else if (keyCode == KeyPress::pageUpKey)
  221867. return kMenuPageUpGlyph;
  221868. else if (keyCode == KeyPress::pageDownKey)
  221869. return kMenuPageDownGlyph;
  221870. else if (keyCode == KeyPress::endKey)
  221871. return kMenuSoutheastArrowGlyph;
  221872. else if (keyCode == KeyPress::homeKey)
  221873. return kMenuNorthwestArrowGlyph;
  221874. else if (keyCode == KeyPress::deleteKey)
  221875. return kMenuDeleteRightGlyph;
  221876. else if (keyCode == KeyPress::tabKey)
  221877. return kMenuTabRightGlyph;
  221878. else if (keyCode == KeyPress::F1Key)
  221879. return kMenuF1Glyph;
  221880. else if (keyCode == KeyPress::F2Key)
  221881. return kMenuF2Glyph;
  221882. else if (keyCode == KeyPress::F3Key)
  221883. return kMenuF3Glyph;
  221884. else if (keyCode == KeyPress::F4Key)
  221885. return kMenuF4Glyph;
  221886. else if (keyCode == KeyPress::F5Key)
  221887. return kMenuF5Glyph;
  221888. else if (keyCode == KeyPress::F6Key)
  221889. return kMenuF6Glyph;
  221890. else if (keyCode == KeyPress::F7Key)
  221891. return kMenuF7Glyph;
  221892. else if (keyCode == KeyPress::F8Key)
  221893. return kMenuF8Glyph;
  221894. else if (keyCode == KeyPress::F9Key)
  221895. return kMenuF9Glyph;
  221896. else if (keyCode == KeyPress::F10Key)
  221897. return kMenuF10Glyph;
  221898. else if (keyCode == KeyPress::F11Key)
  221899. return kMenuF11Glyph;
  221900. else if (keyCode == KeyPress::F12Key)
  221901. return kMenuF12Glyph;
  221902. else if (keyCode == KeyPress::F13Key)
  221903. return kMenuF13Glyph;
  221904. else if (keyCode == KeyPress::F14Key)
  221905. return kMenuF14Glyph;
  221906. else if (keyCode == KeyPress::F15Key)
  221907. return kMenuF15Glyph;
  221908. return 0;
  221909. }
  221910. };
  221911. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel) throw()
  221912. {
  221913. if (getMacMainMenu() != newMenuBarModel)
  221914. {
  221915. if (newMenuBarModel == 0)
  221916. {
  221917. delete mainMenu;
  221918. jassert (mainMenu == 0); // should be zeroed in the destructor
  221919. }
  221920. else
  221921. {
  221922. if (mainMenu == 0)
  221923. mainMenu = new MainMenuHandler();
  221924. mainMenu->setMenu (newMenuBarModel);
  221925. }
  221926. }
  221927. }
  221928. MenuBarModel* MenuBarModel::getMacMainMenu() throw()
  221929. {
  221930. return mainMenu != 0 ? mainMenu->currentModel : 0;
  221931. }
  221932. // these functions are called externally from the message handling code
  221933. void juce_MainMenuAboutToBeUsed()
  221934. {
  221935. // force an update of the items just before the menu appears..
  221936. if (mainMenu != 0)
  221937. mainMenu->menuBarItemsChanged (0);
  221938. }
  221939. void juce_InvokeMainMenuCommand (const HICommand& command)
  221940. {
  221941. if (mainMenu != 0)
  221942. {
  221943. ApplicationCommandManager* commandManager = 0;
  221944. int topLevelIndex = 0;
  221945. if (GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  221946. 'juce', 'apcm', sizeof (commandManager), 0, &commandManager) == noErr
  221947. && GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  221948. 'juce', 'topi', sizeof (topLevelIndex), 0, &topLevelIndex) == noErr)
  221949. {
  221950. mainMenu->invoke (command.commandID, commandManager, topLevelIndex);
  221951. }
  221952. }
  221953. }
  221954. void PlatformUtilities::beep()
  221955. {
  221956. SysBeep (30);
  221957. }
  221958. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  221959. {
  221960. ClearCurrentScrap();
  221961. ScrapRef ref;
  221962. GetCurrentScrap (&ref);
  221963. const int len = text.length();
  221964. const int numBytes = sizeof (UniChar) * len;
  221965. UniChar* const temp = (UniChar*) juce_calloc (numBytes);
  221966. for (int i = 0; i < len; ++i)
  221967. temp[i] = (UniChar) text[i];
  221968. PutScrapFlavor (ref,
  221969. kScrapFlavorTypeUnicode,
  221970. kScrapFlavorMaskNone,
  221971. numBytes,
  221972. temp);
  221973. juce_free (temp);
  221974. }
  221975. const String SystemClipboard::getTextFromClipboard() throw()
  221976. {
  221977. String result;
  221978. ScrapRef ref;
  221979. GetCurrentScrap (&ref);
  221980. Size size = 0;
  221981. if (GetScrapFlavorSize (ref, kScrapFlavorTypeUnicode, &size) == noErr
  221982. && size > 0)
  221983. {
  221984. void* const data = juce_calloc (size + 8);
  221985. if (GetScrapFlavorData (ref, kScrapFlavorTypeUnicode, &size, data) == noErr)
  221986. {
  221987. result = PlatformUtilities::convertUTF16ToString ((UniChar*) data);
  221988. }
  221989. juce_free (data);
  221990. }
  221991. return result;
  221992. }
  221993. bool AlertWindow::showNativeDialogBox (const String& title,
  221994. const String& bodyText,
  221995. bool isOkCancel)
  221996. {
  221997. Str255 tit, txt;
  221998. PlatformUtilities::copyToStr255 (tit, title);
  221999. PlatformUtilities::copyToStr255 (txt, bodyText);
  222000. AlertStdAlertParamRec ar;
  222001. ar.movable = true;
  222002. ar.helpButton = false;
  222003. ar.filterProc = 0;
  222004. ar.defaultText = (const unsigned char*)-1;
  222005. ar.cancelText = (const unsigned char*)((isOkCancel) ? -1 : 0);
  222006. ar.otherText = 0;
  222007. ar.defaultButton = kAlertStdAlertOKButton;
  222008. ar.cancelButton = 0;
  222009. ar.position = kWindowDefaultPosition;
  222010. SInt16 result;
  222011. StandardAlert (kAlertNoteAlert, tit, txt, &ar, &result);
  222012. return result == kAlertStdAlertOKButton;
  222013. }
  222014. const int KeyPress::spaceKey = ' ';
  222015. const int KeyPress::returnKey = kReturnCharCode;
  222016. const int KeyPress::escapeKey = kEscapeCharCode;
  222017. const int KeyPress::backspaceKey = kBackspaceCharCode;
  222018. const int KeyPress::leftKey = kLeftArrowCharCode;
  222019. const int KeyPress::rightKey = kRightArrowCharCode;
  222020. const int KeyPress::upKey = kUpArrowCharCode;
  222021. const int KeyPress::downKey = kDownArrowCharCode;
  222022. const int KeyPress::pageUpKey = kPageUpCharCode;
  222023. const int KeyPress::pageDownKey = kPageDownCharCode;
  222024. const int KeyPress::endKey = kEndCharCode;
  222025. const int KeyPress::homeKey = kHomeCharCode;
  222026. const int KeyPress::deleteKey = kDeleteCharCode;
  222027. const int KeyPress::insertKey = -1;
  222028. const int KeyPress::tabKey = kTabCharCode;
  222029. const int KeyPress::F1Key = 0x10110;
  222030. const int KeyPress::F2Key = 0x10111;
  222031. const int KeyPress::F3Key = 0x10112;
  222032. const int KeyPress::F4Key = 0x10113;
  222033. const int KeyPress::F5Key = 0x10114;
  222034. const int KeyPress::F6Key = 0x10115;
  222035. const int KeyPress::F7Key = 0x10116;
  222036. const int KeyPress::F8Key = 0x10117;
  222037. const int KeyPress::F9Key = 0x10118;
  222038. const int KeyPress::F10Key = 0x10119;
  222039. const int KeyPress::F11Key = 0x1011a;
  222040. const int KeyPress::F12Key = 0x1011b;
  222041. const int KeyPress::F13Key = 0x1011c;
  222042. const int KeyPress::F14Key = 0x1011d;
  222043. const int KeyPress::F15Key = 0x1011e;
  222044. const int KeyPress::F16Key = 0x1011f;
  222045. const int KeyPress::numberPad0 = 0x30020;
  222046. const int KeyPress::numberPad1 = 0x30021;
  222047. const int KeyPress::numberPad2 = 0x30022;
  222048. const int KeyPress::numberPad3 = 0x30023;
  222049. const int KeyPress::numberPad4 = 0x30024;
  222050. const int KeyPress::numberPad5 = 0x30025;
  222051. const int KeyPress::numberPad6 = 0x30026;
  222052. const int KeyPress::numberPad7 = 0x30027;
  222053. const int KeyPress::numberPad8 = 0x30028;
  222054. const int KeyPress::numberPad9 = 0x30029;
  222055. const int KeyPress::numberPadAdd = 0x3002a;
  222056. const int KeyPress::numberPadSubtract = 0x3002b;
  222057. const int KeyPress::numberPadMultiply = 0x3002c;
  222058. const int KeyPress::numberPadDivide = 0x3002d;
  222059. const int KeyPress::numberPadSeparator = 0x3002e;
  222060. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  222061. const int KeyPress::numberPadEquals = 0x30030;
  222062. const int KeyPress::numberPadDelete = 0x30031;
  222063. const int KeyPress::playKey = 0x30000;
  222064. const int KeyPress::stopKey = 0x30001;
  222065. const int KeyPress::fastForwardKey = 0x30002;
  222066. const int KeyPress::rewindKey = 0x30003;
  222067. AppleRemoteDevice::AppleRemoteDevice()
  222068. : device (0),
  222069. queue (0),
  222070. remoteId (0)
  222071. {
  222072. }
  222073. AppleRemoteDevice::~AppleRemoteDevice()
  222074. {
  222075. stop();
  222076. }
  222077. static io_object_t getAppleRemoteDevice() throw()
  222078. {
  222079. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  222080. io_iterator_t iter = 0;
  222081. io_object_t iod = 0;
  222082. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  222083. && iter != 0)
  222084. {
  222085. iod = IOIteratorNext (iter);
  222086. }
  222087. IOObjectRelease (iter);
  222088. return iod;
  222089. }
  222090. static bool createAppleRemoteInterface (io_object_t iod, void** device) throw()
  222091. {
  222092. jassert (*device == 0);
  222093. io_name_t classname;
  222094. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  222095. {
  222096. IOCFPlugInInterface** cfPlugInInterface = 0;
  222097. SInt32 score = 0;
  222098. if (IOCreatePlugInInterfaceForService (iod,
  222099. kIOHIDDeviceUserClientTypeID,
  222100. kIOCFPlugInInterfaceID,
  222101. &cfPlugInInterface,
  222102. &score) == kIOReturnSuccess)
  222103. {
  222104. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  222105. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  222106. device);
  222107. (void) hr;
  222108. (*cfPlugInInterface)->Release (cfPlugInInterface);
  222109. }
  222110. }
  222111. return *device != 0;
  222112. }
  222113. bool AppleRemoteDevice::start (const bool inExclusiveMode) throw()
  222114. {
  222115. if (queue != 0)
  222116. return true;
  222117. stop();
  222118. bool result = false;
  222119. io_object_t iod = getAppleRemoteDevice();
  222120. if (iod != 0)
  222121. {
  222122. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  222123. result = true;
  222124. else
  222125. stop();
  222126. IOObjectRelease (iod);
  222127. }
  222128. return result;
  222129. }
  222130. void AppleRemoteDevice::stop() throw()
  222131. {
  222132. if (queue != 0)
  222133. {
  222134. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  222135. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  222136. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  222137. queue = 0;
  222138. }
  222139. if (device != 0)
  222140. {
  222141. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  222142. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  222143. device = 0;
  222144. }
  222145. }
  222146. bool AppleRemoteDevice::isActive() const throw()
  222147. {
  222148. return queue != 0;
  222149. }
  222150. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  222151. {
  222152. if (result == kIOReturnSuccess)
  222153. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  222154. }
  222155. bool AppleRemoteDevice::open (const bool openInExclusiveMode) throw()
  222156. {
  222157. #if ! MACOS_10_2_OR_EARLIER
  222158. Array <int> cookies;
  222159. CFArrayRef elements;
  222160. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  222161. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  222162. return false;
  222163. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  222164. {
  222165. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  222166. // get the cookie
  222167. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  222168. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  222169. continue;
  222170. long number;
  222171. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  222172. continue;
  222173. cookies.add ((int) number);
  222174. }
  222175. CFRelease (elements);
  222176. if ((*(IOHIDDeviceInterface**) device)
  222177. ->open ((IOHIDDeviceInterface**) device,
  222178. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  222179. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  222180. {
  222181. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  222182. if (queue != 0)
  222183. {
  222184. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  222185. for (int i = 0; i < cookies.size(); ++i)
  222186. {
  222187. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  222188. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  222189. }
  222190. CFRunLoopSourceRef eventSource;
  222191. if ((*(IOHIDQueueInterface**) queue)
  222192. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  222193. {
  222194. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  222195. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  222196. {
  222197. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  222198. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  222199. return true;
  222200. }
  222201. }
  222202. }
  222203. }
  222204. #endif
  222205. return false;
  222206. }
  222207. void AppleRemoteDevice::handleCallbackInternal()
  222208. {
  222209. int totalValues = 0;
  222210. AbsoluteTime nullTime = { 0, 0 };
  222211. char cookies [12];
  222212. int numCookies = 0;
  222213. while (numCookies < numElementsInArray (cookies))
  222214. {
  222215. IOHIDEventStruct e;
  222216. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  222217. break;
  222218. if ((int) e.elementCookie == 19)
  222219. {
  222220. remoteId = e.value;
  222221. buttonPressed (switched, false);
  222222. }
  222223. else
  222224. {
  222225. totalValues += e.value;
  222226. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  222227. }
  222228. }
  222229. cookies [numCookies++] = 0;
  222230. static const char buttonPatterns[] =
  222231. {
  222232. 14, 7, 6, 5, 14, 7, 6, 5, 0,
  222233. 14, 8, 6, 5, 14, 8, 6, 5, 0,
  222234. 14, 12, 11, 6, 5, 0,
  222235. 14, 13, 11, 6, 5, 0,
  222236. 14, 9, 6, 5, 14, 9, 6, 5, 0,
  222237. 14, 10, 6, 5, 14, 10, 6, 5, 0,
  222238. 14, 6, 5, 4, 2, 0,
  222239. 14, 6, 5, 3, 2, 0,
  222240. 14, 6, 5, 14, 6, 5, 0,
  222241. 18, 14, 6, 5, 18, 14, 6, 5, 0,
  222242. 19, 0
  222243. };
  222244. int buttonNum = (int) menuButton;
  222245. int i = 0;
  222246. while (i < numElementsInArray (buttonPatterns))
  222247. {
  222248. if (strcmp (cookies, buttonPatterns + i) == 0)
  222249. {
  222250. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  222251. break;
  222252. }
  222253. i += strlen (buttonPatterns + i) + 1;
  222254. ++buttonNum;
  222255. }
  222256. }
  222257. #if JUCE_OPENGL
  222258. class WindowedGLContext : public OpenGLContext
  222259. {
  222260. public:
  222261. WindowedGLContext (Component* const component,
  222262. const OpenGLPixelFormat& pixelFormat_,
  222263. AGLContext sharedContext)
  222264. : renderContext (0),
  222265. pixelFormat (pixelFormat_)
  222266. {
  222267. jassert (component != 0);
  222268. HIViewComponentPeer* const peer = dynamic_cast <HIViewComponentPeer*> (component->getTopLevelComponent()->getPeer());
  222269. if (peer == 0)
  222270. return;
  222271. GLint attribs [64];
  222272. int n = 0;
  222273. attribs[n++] = AGL_RGBA;
  222274. attribs[n++] = AGL_DOUBLEBUFFER;
  222275. attribs[n++] = AGL_ACCELERATED;
  222276. attribs[n++] = AGL_RED_SIZE;
  222277. attribs[n++] = pixelFormat.redBits;
  222278. attribs[n++] = AGL_GREEN_SIZE;
  222279. attribs[n++] = pixelFormat.greenBits;
  222280. attribs[n++] = AGL_BLUE_SIZE;
  222281. attribs[n++] = pixelFormat.blueBits;
  222282. attribs[n++] = AGL_ALPHA_SIZE;
  222283. attribs[n++] = pixelFormat.alphaBits;
  222284. attribs[n++] = AGL_DEPTH_SIZE;
  222285. attribs[n++] = pixelFormat.depthBufferBits;
  222286. attribs[n++] = AGL_STENCIL_SIZE;
  222287. attribs[n++] = pixelFormat.stencilBufferBits;
  222288. attribs[n++] = AGL_ACCUM_RED_SIZE;
  222289. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  222290. attribs[n++] = AGL_ACCUM_GREEN_SIZE;
  222291. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  222292. attribs[n++] = AGL_ACCUM_BLUE_SIZE;
  222293. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  222294. attribs[n++] = AGL_ACCUM_ALPHA_SIZE;
  222295. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  222296. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  222297. attribs[n++] = AGL_SAMPLE_BUFFERS_ARB;
  222298. attribs[n++] = 1;
  222299. attribs[n++] = AGL_SAMPLES_ARB;
  222300. attribs[n++] = 4;
  222301. attribs[n++] = AGL_CLOSEST_POLICY;
  222302. attribs[n++] = AGL_NO_RECOVERY;
  222303. attribs[n++] = AGL_NONE;
  222304. renderContext = aglCreateContext (aglChoosePixelFormat (0, 0, attribs),
  222305. sharedContext);
  222306. aglSetDrawable (renderContext, GetWindowPort (peer->windowRef));
  222307. }
  222308. ~WindowedGLContext()
  222309. {
  222310. makeInactive();
  222311. aglSetDrawable (renderContext, 0);
  222312. aglDestroyContext (renderContext);
  222313. }
  222314. bool makeActive() const throw()
  222315. {
  222316. jassert (renderContext != 0);
  222317. return aglSetCurrentContext (renderContext);
  222318. }
  222319. bool makeInactive() const throw()
  222320. {
  222321. return (! isActive()) || aglSetCurrentContext (0);
  222322. }
  222323. bool isActive() const throw()
  222324. {
  222325. return aglGetCurrentContext() == renderContext;
  222326. }
  222327. const OpenGLPixelFormat getPixelFormat() const
  222328. {
  222329. return pixelFormat;
  222330. }
  222331. void* getRawContext() const throw()
  222332. {
  222333. return renderContext;
  222334. }
  222335. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  222336. {
  222337. GLint bufferRect[4];
  222338. bufferRect[0] = x;
  222339. bufferRect[1] = outerWindowHeight - (y + h);
  222340. bufferRect[2] = w;
  222341. bufferRect[3] = h;
  222342. aglSetInteger (renderContext, AGL_BUFFER_RECT, bufferRect);
  222343. aglEnable (renderContext, AGL_BUFFER_RECT);
  222344. }
  222345. void swapBuffers()
  222346. {
  222347. aglSwapBuffers (renderContext);
  222348. }
  222349. bool setSwapInterval (const int numFramesPerSwap)
  222350. {
  222351. return aglSetInteger (renderContext, AGL_SWAP_INTERVAL, (const GLint*) &numFramesPerSwap);
  222352. }
  222353. int getSwapInterval() const
  222354. {
  222355. GLint numFrames = 0;
  222356. aglGetInteger (renderContext, AGL_SWAP_INTERVAL, &numFrames);
  222357. return numFrames;
  222358. }
  222359. void repaint()
  222360. {
  222361. }
  222362. juce_UseDebuggingNewOperator
  222363. AGLContext renderContext;
  222364. private:
  222365. OpenGLPixelFormat pixelFormat;
  222366. WindowedGLContext (const WindowedGLContext&);
  222367. const WindowedGLContext& operator= (const WindowedGLContext&);
  222368. };
  222369. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  222370. const OpenGLPixelFormat& pixelFormat,
  222371. const OpenGLContext* const contextToShareWith)
  222372. {
  222373. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  222374. contextToShareWith != 0 ? (AGLContext) contextToShareWith->getRawContext() : 0);
  222375. if (c->renderContext == 0)
  222376. deleteAndZero (c);
  222377. return c;
  222378. }
  222379. void juce_glViewport (const int w, const int h)
  222380. {
  222381. glViewport (0, 0, w, h);
  222382. }
  222383. static int getAGLAttribute (AGLPixelFormat p, const GLint attrib)
  222384. {
  222385. GLint result = 0;
  222386. aglDescribePixelFormat (p, attrib, &result);
  222387. return result;
  222388. }
  222389. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  222390. OwnedArray <OpenGLPixelFormat>& results)
  222391. {
  222392. GLint attribs [64];
  222393. int n = 0;
  222394. attribs[n++] = AGL_RGBA;
  222395. attribs[n++] = AGL_DOUBLEBUFFER;
  222396. attribs[n++] = AGL_ACCELERATED;
  222397. attribs[n++] = AGL_NO_RECOVERY;
  222398. attribs[n++] = AGL_NONE;
  222399. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  222400. while (p != 0)
  222401. {
  222402. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  222403. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  222404. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  222405. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  222406. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  222407. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  222408. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  222409. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  222410. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  222411. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  222412. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  222413. results.add (pf);
  222414. p = aglNextPixelFormat (p);
  222415. }
  222416. }
  222417. #endif
  222418. END_JUCE_NAMESPACE
  222419. /********* End of inlined file: juce_mac_Windowing.mm *********/
  222420. #endif
  222421. #endif